From d1cac6462e40e705a19d2f82f94191b0dff130e8 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 16:12:22 +0000 Subject: [PATCH 01/15] wip: six publish-time rules and sealed node-type vocabulary Claude-Session: https://claude.ai/code/session_01JQwxbXGvw43spR79ztEvWt Co-authored-by: Claude --- packages/lint/src/authoring-rules.ts | 64 ++++++++++++- packages/lint/src/index.ts | 12 +++ packages/lint/src/lint-flow-patterns.ts | 86 ++++++++++++++++++ packages/lint/src/rule-explanations.ts | 91 +++++++++++++++++++ packages/lint/src/runtime-gate.ts | 12 +++ .../src/validate-action-object-binding.ts | 61 +++++++++++++ .../lint/src/validate-flow-node-executors.ts | 77 ++++++++++++++++ .../src/validate-inert-object-declarations.ts | 87 ++++++++++++++++++ .../src/protocol-authoring-gate.ts | 36 +++++++- packages/metadata-protocol/src/protocol.ts | 23 +++++ .../src/runtime-authoring-gate.ts | 12 +++ .../services/service-automation/src/engine.ts | 15 +++ .../src/flow-node-type-audit.test.ts | 20 +++- 13 files changed, 593 insertions(+), 3 deletions(-) create mode 100644 packages/lint/src/validate-action-object-binding.ts create mode 100644 packages/lint/src/validate-flow-node-executors.ts create mode 100644 packages/lint/src/validate-inert-object-declarations.ts diff --git a/packages/lint/src/authoring-rules.ts b/packages/lint/src/authoring-rules.ts index b5e747f4118..02d5abb70f7 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,21 @@ 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) and the object's action route answers "not found". + // Gating: nothing about the declaration can 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 +1902,21 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ surfaceReason: RUNTIME_NEEDS_FULL_SNAPSHOT, run: (stack) => validateSeedStateMachine(stack), }, + // A required checkbox (the form refuses an unchecked box, so only "on" can be + // saved) and a state machine with no `initialStates` (a record can be born + // in any state). Gating: each declaration works against its author on every + // record. 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..7bb2c637431 100644 --- a/packages/lint/src/index.ts +++ b/packages/lint/src/index.ts @@ -675,6 +675,16 @@ 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, + FIELD_BOOLEAN_REQUIRED, + STATE_MACHINE_NO_INITIAL_STATES, +} from './validate-inert-object-declarations.js'; +export type { InertObjectDeclarationFinding } from './validate-inert-object-declarations.js'; export { validatePageFieldBindings, @@ -1106,6 +1116,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.ts b/packages/lint/src/lint-flow-patterns.ts index a6f9efc50e0..000bbf8e91c 100644 --- a/packages/lint/src/lint-flow-patterns.ts +++ b/packages/lint/src/lint-flow-patterns.ts @@ -377,6 +377,18 @@ 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 `config.timeoutMs`. `warning`: the executor arms its + * timer only when the key is set. 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 +1834,74 @@ 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 `config.timeoutMs` has no timer of its own: the + * executor arms one only when the key is set (`service-automation` + * `builtin/http-nodes.ts`), so 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. + */ +function scanHttpTimeouts(at: string, nodes: AnyRec[], findings: FlowLintFinding[], sites?: FlowNodeSites): void { + for (const node of nodes) { + if (node.type !== 'http') continue; + const cfg = (node.config ?? {}) as AnyRec; + if (cfg.timeoutMs !== undefined) continue; + const nodeId = typeof node.id === 'string' ? node.id : 'http'; + findings.push({ + severity: 'warning', + where: `${at} · node '${nodeId}' (http)`, + ...(sites?.nodes.get(node) ? { path: `${sites.nodes.get(node)!.path}.config` } : {}), + message: + `http node '${nodeId}' sets no \`config.timeoutMs\`, so the call has no timeout of its own: 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 number of milliseconds, e.g. `timeoutMs: 10000`.', + rule: FLOW_HTTP_TIMEOUT_MISSING, + }); + } +} + function scanApprovalReviseLoops( at: string, nodes: AnyRec[], @@ -2632,6 +2712,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..3cbc0374316 100644 --- a/packages/lint/src/rule-explanations.ts +++ b/packages/lint/src/rule-explanations.ts @@ -6252,6 +6252,91 @@ 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 set. Without it 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 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 FIELD_BOOLEAN_REQUIRED_EXPLANATION: RuleExplanation = { + rule: 'field-boolean-required', + covers: 'why a checkbox is never required', + paragraphs: [ + '`required` says a record must carry a value. A `boolean` or `toggle` field always carries one of its two ' + + 'values, and `false` is a value, so the flag guards nothing. The record form reads it the other way: as ' + + '"must be checked". It then refuses to save the box unchecked, and the app can only create records with ' + + 'the box on — the state the control shows by default is the one value it will not save.', + 'Remove `required`, and give the field `defaultValue: false` so a new record starts unchecked. If the box ' + + 'really must be ticked (an accepted agreement), say so with a validation rule.', + ], +}; + +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.', + '`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.', + ], +}; + +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, the ' + + 'button it declares renders nowhere, and the object\'s action route answers "not found".', + '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 +6572,12 @@ 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, + [FIELD_BOOLEAN_REQUIRED_EXPLANATION.rule]: FIELD_BOOLEAN_REQUIRED_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.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.ts b/packages/lint/src/validate-action-object-binding.ts new file mode 100644 index 00000000000..e6901995572 --- /dev/null +++ b/packages/lint/src/validate-action-object-binding.ts @@ -0,0 +1,61 @@ +// 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 and a call on an + * object's action route answers "not found". 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: the button never renders, and a call on an object\'s action route answers "not found".', + 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.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.ts b/packages/lint/src/validate-inert-object-declarations.ts new file mode 100644 index 00000000000..47436853238 --- /dev/null +++ b/packages/lint/src/validate-inert-object-declarations.ts @@ -0,0 +1,87 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Two object declarations that pass the schema and then work against their + * author at run time — each a refusal at publish, with the fix named. + * + * 1. {@link FIELD_BOOLEAN_REQUIRED} — a `boolean` / `toggle` field marked + * `required`. `required` is a presence contract and a checkbox is never + * absent, so it guards nothing; the record form reads it as "must be + * checked" and refuses to save the box unchecked, so the app can only ever + * create records with the box ON. + * 2. {@link STATE_MACHINE_NO_INITIAL_STATES} — a `state_machine` validation + * with no `initialStates`. `transitions` governs UPDATE only, so without an + * entry guard a record can be CREATED already in any state (born + * `approved`), walking straight past the process the machine declares. + * + * Both read 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 FIELD_BOOLEAN_REQUIRED = 'field-boolean-required'; +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; +} + +const CHECKBOX_TYPES = new Set(['boolean', 'toggle']); + +/** Flag a required checkbox and 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; + + for (const { rec: field, path: fieldPath } of collectionEntries(obj.fields, `${objPath}.fields`)) { + if (typeof field.type !== 'string' || !CHECKBOX_TYPES.has(field.type) || field.required !== true) continue; + const fieldName = typeof field.name === 'string' ? field.name : fieldPath; + const hasDefault = field.defaultValue !== undefined && field.defaultValue !== null; + findings.push({ + severity: 'error', + rule: FIELD_BOOLEAN_REQUIRED, + where: `object "${objectName}" field "${fieldName}"`, + path: `${fieldPath}.required`, + message: + `Field "${fieldName}" is a ${field.type} marked required. "false" is a legal value, not a missing one, ` + + 'so the flag guards nothing — and the record form reads it as "must be checked" and refuses to save ' + + 'the box unchecked.', + hint: + `Remove \`required\` from "${fieldName}"${hasDefault ? '' : ' and give it `defaultValue: false`'}. ` + + 'If the box really must be ticked, write a validation rule that says so.', + }); + } + + 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.initialStates !== undefined) 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\`. 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/protocol-authoring-gate.ts b/packages/metadata-protocol/src/protocol-authoring-gate.ts index 638ced616c4..2324825fef2 100644 --- a/packages/metadata-protocol/src/protocol-authoring-gate.ts +++ b/packages/metadata-protocol/src/protocol-authoring-gate.ts @@ -99,6 +99,7 @@ export interface AuthoringGateHost { unknownGrantObjectSaveRefusal: ObjectStackProtocolImplementation['unknownGrantObjectSaveRefusal']; unknownPicklistBindingSaveRefusal: ObjectStackProtocolImplementation['unknownPicklistBindingSaveRefusal']; seedExternalIdSaveRefusal: ObjectStackProtocolImplementation['seedExternalIdSaveRefusal']; + sealedFlowNodeTypeVocabulary: ObjectStackProtocolImplementation['sealedFlowNodeTypeVocabulary']; } /** The body of `ObjectStackProtocolImplementation#restoredBodyDerivation`; the method's docblock there is its contract. */ @@ -319,7 +320,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 +608,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 +662,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 +878,29 @@ export async function draftPublishJudgement( } return { refusals: told.length > 0 ? [...told, ...issues] : issues, advisories: verdict.advisories }; } + +/** + * The body of `ObjectStackProtocolImplementation#sealedFlowNodeTypeVocabulary`; + * the method's docblock there is its contract. + */ +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.ts b/packages/metadata-protocol/src/protocol.ts index 8b709139b40..84008cc2ab4 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 { @@ -1869,6 +1870,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 assertRuntimeAuthoringRules.call(host, evt); @@ -1939,6 +1941,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 +2239,26 @@ export class ObjectStackProtocolImplementation implements return rlsMembershipResolverKeys.call(host); } + /** + * 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 publish, as {@link rlsMembershipResolverKeys} reads its service, + * and recorded nowhere. `undefined` — the CLI's reading, under which no node + * type is judged — when this 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"). + */ + 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(); + }); +}); From 42672fb765682490e9817968a1b8fe7847017b0e Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 16:20:19 +0000 Subject: [PATCH 02/15] test: pins for the six publish-time rules Claude-Session: https://claude.ai/code/session_01JQwxbXGvw43spR79ztEvWt Co-authored-by: Claude --- packages/lint/src/lint-flow-patterns.test.ts | 79 ++++++++++++++++++- .../validate-action-object-binding.test.ts | 32 ++++++++ .../src/validate-flow-node-executors.test.ts | 61 ++++++++++++++ ...validate-inert-object-declarations.test.ts | 76 ++++++++++++++++++ 4 files changed, 246 insertions(+), 2 deletions(-) create mode 100644 packages/lint/src/validate-action-object-binding.test.ts create mode 100644 packages/lint/src/validate-flow-node-executors.test.ts create mode 100644 packages/lint/src/validate-inert-object-declarations.test.ts diff --git a/packages/lint/src/lint-flow-patterns.test.ts b/packages/lint/src/lint-flow-patterns.test.ts index 031cd2624dc..6f56e5b7449 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,75 @@ 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) => ({ + 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 } }, + ], + 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([]); + }); +}); 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-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-inert-object-declarations.test.ts b/packages/lint/src/validate-inert-object-declarations.test.ts new file mode 100644 index 00000000000..cf0ed81763a --- /dev/null +++ b/packages/lint/src/validate-inert-object-declarations.test.ts @@ -0,0 +1,76 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, expect, it } from 'vitest'; +import { runRuntimeAuthoringRules } from './runtime-gate.js'; +import { + FIELD_BOOLEAN_REQUIRED, + 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('field-boolean-required', () => { + it('refuses a required boolean and a required toggle, at the `required` key', () => { + const findings = validateInertObjectDeclarations({ + objects: [task({ is_done: { type: 'boolean', label: 'Done', required: true }, on: { type: 'toggle', label: 'On', required: true, defaultValue: false } })], + }); + expect(findings.map((f) => [f.rule, f.severity, f.path])).toEqual([ + [FIELD_BOOLEAN_REQUIRED, 'error', 'objects[0].fields.is_done.required'], + [FIELD_BOOLEAN_REQUIRED, 'error', 'objects[0].fields.on.required'], + ]); + // The fix names the default only where the field has none. + expect(findings[0].hint).toContain('defaultValue: false'); + expect(findings[1].hint).not.toContain('defaultValue'); + }); + + it('is silent on an optional boolean and on a required non-boolean', () => { + expect(validateInertObjectDeclarations({ + objects: [task({ is_done: { type: 'boolean', label: 'Done', defaultValue: false }, code: { type: 'text', label: 'Code', required: true } })], + })).toEqual([]); + }); +}); + +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('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 either declaration', () => { + it('raises each as an error on an `object` write', () => { + const item = task({ is_done: { type: 'boolean', label: 'Done', required: true }, status: STATUS }, [machine()]); + const verdict = runRuntimeAuthoringRules({ type: 'object', item }); + const rules = verdict.errors.map((f) => f.rule); + expect(rules).toContain(FIELD_BOOLEAN_REQUIRED); + expect(rules).toContain(STATE_MACHINE_NO_INITIAL_STATES); + }); +}); From c65d17a54f4dc3eb18c6ab5c9eb62246596c3620 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 16:45:04 +0000 Subject: [PATCH 03/15] feat(metadata-protocol): four build probes over what landed widget_empty_result, rollup_never_computed, seed_reference_unresolved and flow_connector_action_unresolved: warnings on the publish receipt, each with the person's sentence in eleven locales. The publish passes the automation engine's connector lookups and its package to the probes. Claude-Session: https://claude.ai/code/session_01JQwxbXGvw43spR79ztEvWt Co-authored-by: Claude --- .../src/runtime-gate.object-writes.test.ts | 4 + .../src/build-probes-landed-data.test.ts | 211 +++++++++++ .../src/build-probes-user-message.test.ts | 111 ++++++ .../metadata-protocol/src/build-probes.ts | 331 +++++++++++++++++- .../src/build-probes.user-text.ts | 213 +++++++++++ .../src/protocol-history-and-publish.ts | 6 + packages/spec/src/api/protocol.zod.ts | 24 +- 7 files changed, 891 insertions(+), 9 deletions(-) create mode 100644 packages/metadata-protocol/src/build-probes-landed-data.test.ts diff --git a/packages/lint/src/runtime-gate.object-writes.test.ts b/packages/lint/src/runtime-gate.object-writes.test.ts index 3ae2b38889e..359ec0ca712 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 required checkbox and 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/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..88a299785d3 --- /dev/null +++ b/packages/metadata-protocol/src/build-probes-landed-data.test.ts @@ -0,0 +1,211 @@ +// 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; + +/** Fixed tables; honours `where.id.$in` and `limit` (`check:objectql-double-limit`). */ +const engineOver = (tables: Record): ProbeEngine => ({ + find: async (object, query) => { + const q = query as { where?: { id?: { $in?: unknown[] } }; limit?: unknown } | undefined; + const ids = q?.where?.id?.$in; + const rows = (tables[object] ?? []).filter((r) => !ids || ids.includes(r.id)); + return typeof q?.limit === 'number' ? rows.slice(0, q.limit) : rows; + }, +}); + +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: [] }, + '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]); + +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', acct_ref: 'a1', owner: 'Jane Smith' }, { id: 'd2', acct_ref: 'a_gone' }], + acct: [{ id: 'a1' }], + sys_user: [{ id: 'u1' }], + }), + 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', acct_ref: 'a1', owner: 'u1' }, { id: 'd2', acct_ref: null }], acct: [{ id: 'a1' }], sys_user: [{ id: 'u1' }] }), + 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', acct_ref: 'a_gone' }]; + throw new Error('no such table'); + }, + }, + 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([]); + }); +}); 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..f87bfc0a931 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: [] }, + '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,36 @@ const engineThrowing: ProbeEngine = { }, }; +/** + * An engine over fixed tables: honours `where.id.$in` and `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 ids = ((query as { where?: { id?: { $in?: unknown[] } } } | undefined)?.where?.id?.$in); + const rows = (tables[object] ?? []).filter((r) => !ids || ids.includes(r.id)); + 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 +406,57 @@ 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 }), + 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', acct_ref: 'Acme Corp' }], crm_acct: [{ id: 'a1' }] }), + 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..642dad84663 100644 --- a/packages/metadata-protocol/src/build-probes.ts +++ b/packages/metadata-protocol/src/build-probes.ts @@ -25,6 +25,8 @@ import type { BuildProbeReport, RuntimeBuildIssue, StandardErrorCode } from '@objectstack/spec/api'; import { resolveI18nLabel, type I18nLabel } from '@objectstack/spec/ui'; +import { referenceTargetOf } from '@objectstack/spec/data'; +import { collectFlowGraphs } from '@objectstack/spec/automation'; import { PackageScopedNameRefusedError, describePackageScopedHolder, 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 @@ -127,6 +133,33 @@ 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 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 +253,44 @@ 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 `where` a probe read scopes to the publishing organization, beside its own clause. */ +function scoped(organizationId: string | null | undefined, where: Rec = {}): Rec | undefined { + const merged = organizationId ? { ...where, organization_id: organizationId } : where; + return Object.keys(merged).length > 0 ? merged : undefined; +} + +/** 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); +} + +/** 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 +604,146 @@ export async function runBuildProbes(opts: RunBuildProbesOptions): Promise + c && (!childField || (c[childField] !== null && c[childField] !== undefined)) ? idsIn(c[fk]) : []))]; + if (parentIds.length === 0) continue; + const parents = asArr(await engine.find(p.name, { + where: { id: { $in: parentIds } }, + limit: parentIds.length, + context: SYSTEM_READ, + })).map(asRec).filter((r): r is Rec => !!r); + if (parents.length === 0 || parents.some((r) => r[fieldName] !== null && r[fieldName] !== undefined)) continue; + 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 ${parents.length} parent row(s) that have "${childObject}" ` + + 'children — the field is configured, but the engine has never computed it. A roll-up recalculates only ' + + 'when a child row is written, so one declared after the children loaded stays blank until a child changes.', + fix: + `Check that "${childObject}" rows carry "${fk}" back to "${p.name}", then write one child row (any change) ` + + 'to trigger the recompute. 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), + }), + }); + } 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 re-check for references, so a + // value naming no row lands unchallenged, and the first one to notice is + // the person whose edit form refuses to save the record + // (`reference_not_found`). One sample read of the object, then one + // `id $in` read per reference column. A blank is not a dangle, and a read + // that fails judges nothing. + 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 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; + let rows: Rec[]; + try { + rows = asArr(await engine.find(objectName, { + limit: PROBE_SAMPLE_ROWS, + ...(scoped(organizationId) ? { where: scoped(organizationId) } : {}), + context: SYSTEM_READ, + })).map(asRec).filter((r): r is Rec => !!r); + } catch { + continue; + } + for (const { name: field, def, target } of refFields) { + const values = [...new Set(rows.flatMap((r) => idsIn(r[field])))].slice(0, PROBE_SAMPLE_ROWS); + if (values.length === 0) continue; + let found: Set; + try { + const existing = asArr(await engine.find(target, { + where: { id: { $in: values } }, + limit: values.length, + context: SYSTEM_READ, + })).map(asRec); + found = new Set(existing.map((r) => String(r?.id ?? r?._id))); + } catch { + continue; + } + const missing = values.filter((v) => !found.has(v)); + if (missing.length === 0) continue; + const shown = missing.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 ${missing.length} value(s) that name no "${target}" row: ` + + `${shown}${missing.length > 5 ? ', …' : ''}. The edit form submits the whole record and the engine re-checks ` + + `every reference in it, so those records cannot be saved (\`${field}: reference_not_found\`), whichever field the user changed.`, + 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(missing.length), + }), + }); + } + } + // ── Dashboard widgets: the real dataset selection must return data ────── const dashboards = published.filter((x) => x.type === 'dashboard'); let widgetsToProbe = 0; @@ -619,6 +830,29 @@ 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..b7384fd64ac 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` | 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,211 @@ 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. */ +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, so it has not been calculated yet. Edit one of those "${p.child}" records to recalculate it.`, + 'zh-Hans': (p) => + `“${p.object}”的汇总字段“${p.field}”在每条有相关“${p.child}”记录的记录上都是空的,说明它还没有计算过。` + + `请编辑其中一条“${p.child}”记录以重新计算。`, + 'zh-Hant': (p) => + `「${p.object}」的匯總欄位「${p.field}」在每筆有相關「${p.child}」記錄的記錄上都是空的,表示它還沒有計算過。` + + `請編輯其中一筆「${p.child}」記錄以重新計算。`, + 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}", así que aún no se ha calculado. Edite uno de esos registros de "${p.child}" para recalcularlo.`, + ar: (p) => + `حقل التجميع "${p.field}" في "${p.object}" فارغ في كل سجل له سجلات "${p.child}" مرتبطة، أي أنه لم يُحسب بعد. ` + + `عدّل أحد سجلات "${p.child}" هذه لإعادة حسابه.`, + 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 : il n’a donc pas encore été calculé. Modifiez l’un de ces ` + + `enregistrements « ${p.child} » pour le recalculer.`, + '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}", então ainda não foi calculado. Edite um desses registros de "${p.child}" para recalculá-lo.`, + ru: (p) => + `Сводное поле «${p.field}» объекта «${p.object}» пустое во всех записях, у которых есть связанные записи ` + + `«${p.child}», то есть оно ещё не рассчитано. Измените одну из этих записей «${p.child}», чтобы пересчитать его.`, + de: (p) => + `Das Rollup-Feld „${p.field}“ in „${p.object}“ ist bei jedem Datensatz mit verknüpften „${p.child}“-Datensätzen ` + + `leer, wurde also noch nicht berechnet. Bearbeiten Sie einen dieser „${p.child}“-Datensätze, um es neu zu berechnen.`, + ja: (p) => + `「${p.object}」の積み上げ集計項目「${p.field}」は、関連する「${p.child}」レコードを持つすべてのレコードで空のため、` + + `まだ計算されていません。それらの「${p.child}」レコードのいずれかを編集して再計算してください。`, + ko: (p) => + `"${p.object}"의 롤업 필드 "${p.field}"가 관련 "${p.child}" 레코드가 있는 모든 레코드에서 비어 있어 아직 계산되지 않았습니다. ` + + `해당 "${p.child}" 레코드 중 하나를 편집하여 다시 계산하세요.`, +}; + +/** `seed_reference_unresolved`: sample records point at records that do not exist, so they cannot be saved. */ +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 those records cannot be saved after an edit. 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}”,然后重新发布。`, + 'zh-Hant': (p) => + `部分「${p.object}」示例記錄(「${p.field}」中有 ${p.count} 個值)指向不存在的「${p.target}」記錄,因此這些記錄編輯後無法儲存。` + + `請在示例資料中修正或清空「${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, por lo que no se pueden guardar tras editarlos. 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}" في البيانات التجريبية أو أفرغه، ثم أعد النشر.`, + fr: (p) => + `Certains enregistrements d’exemple « ${p.object} » (${p.count} valeur(s) dans « ${p.field} ») pointent vers ` + + `des enregistrements « ${p.target} » inexistants : ils ne peuvent donc pas être enregistrés après une ` + + `modification. 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 não podem ser salvos após uma edição. Corrija ou limpe "${p.field}" nos ` + + `dados de exemplo e publique novamente.`, + ru: (p) => + `Некоторые примеры записей «${p.object}» (значений в поле «${p.field}»: ${p.count}) ссылаются на ` + + `несуществующие записи «${p.target}», поэтому после изменения их нельзя сохранить. Исправьте или очистите ` + + `«${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, und lassen sich daher nach einer Änderung nicht speichern. 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}」を修正するか空にしてから、もう一度公開してください。`, + ko: (p) => + `일부 "${p.object}" 샘플 레코드("${p.field}"의 값 ${p.count}개)가 존재하지 않는 "${p.target}" 레코드를 가리키므로 ` + + `편집 후 저장할 수 없습니다. 샘플 데이터에서 "${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 +1064,10 @@ export const BUILD_PROBE_USER_TEXT: Readonly 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`), or what landed reads in a ' + + 'way the person will notice although it may be the truth (`widget_empty_result`, ' + + '`rollup_never_computed`, `seed_reference_unresolved`, ' + + '`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.', + + 'to, the connector a flow step dispatches. 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.', ), From a8d9400b53d80c573c40519861b1f0195c955cb0 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 16:49:36 +0000 Subject: [PATCH 04/15] docs(spec): regenerate the protocol reference for the probe codes Claude-Session: https://claude.ai/code/session_01JQwxbXGvw43spR79ztEvWt Co-authored-by: Claude --- content/docs/references/api/protocol.mdx | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/content/docs/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index feee8113694..e9d175a1996 100644 --- a/content/docs/references/api/protocol.mdx +++ b/content/docs/references/api/protocol.mdx @@ -474,10 +474,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`), or what landed reads in a way the person will notice although it may be the truth (`widget_empty_result`, `rollup_never_computed`, `seed_reference_unresolved`, `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, when that is not the artifact itself: the object a seed loads into or a view reads, the dataset a widget is bound to, the connector a flow step dispatches. 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. | @@ -2970,10 +2970,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`), or what landed reads in a way the person will notice although it may be the truth (`widget_empty_result`, `rollup_never_computed`, `seed_reference_unresolved`, `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, when that is not the artifact itself: the object a seed loads into or a view reads, the dataset a widget is bound to, the connector a flow step dispatches. 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. | @@ -2982,16 +2982,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. | --- From ccfd1c14484e64176b980fb7e4c5c49f6230fc7d Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 16:52:57 +0000 Subject: [PATCH 05/15] chore: changeset for the six publish-time checks and four build probes Claude-Session: https://claude.ai/code/session_01JQwxbXGvw43spR79ztEvWt Co-authored-by: Claude --- .../34776-publish-checks-build-probes.md | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 .changeset/34776-publish-checks-build-probes.md diff --git a/.changeset/34776-publish-checks-build-probes.md b/.changeset/34776-publish-checks-build-probes.md new file mode 100644 index 00000000000..8673a19a9cc --- /dev/null +++ b/.changeset/34776-publish-checks-build-probes.md @@ -0,0 +1,27 @@ +--- +'@objectstack/lint': minor +'@objectstack/metadata-protocol': minor +'@objectstack/service-automation': minor +'@objectstack/spec': minor +--- + +feat(lint): six 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: six publish-time refusals of metadata the schema accepts today) +Metadata-protocol: narrowed +Skills-docs: follow-up owed — skills/** traps for the six rules + +Six 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` routes no decision. +- `flow-http-timeout-missing` (warning): an `http` node with no `timeoutMs` waits on a slow upstream for as long as the connection stays open; the engine arms no default timer. +- `field-boolean-required` (error): a `boolean` / `toggle` field marked `required` guards nothing, and the record form refuses to save the box unchecked. Remove `required` (and give it `defaultValue: false`). +- `state-machine-no-initial-states` (error): a `state_machine` validation without `initialStates` 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 required checkbox, 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 landed sample record whose reference names no row, so the edit form cannot save it) 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` and `packageId`; the publish passes the automation engine's connector lookups and the publishing package. + +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`, `FIELD_BOOLEAN_REQUIRED`, `STATE_MACHINE_NO_INITIAL_STATES`, `ACTION_NO_OBJECT_BINDING`; `@objectstack/metadata-protocol` adds the `ProbeAutomation` type; `@objectstack/service-automation` adds `AutomationEngine.getSealedNodeTypeVocabulary()`. `@objectstack/spec` changes only the descriptions of `RuntimeBuildIssueSchema`. From 48e5d4354b6ba5ba56f185a62b26996b205c2af0 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 17:24:53 +0000 Subject: [PATCH 06/15] fix: keep protocol.ts within its ceiling, seat the probe doubles, update transcript counts The runtime gate's host is the draft verdicts' host (a superset), so the facade does not grow; the probe tests' find doubles honour any `where`, so the limit gate can drive them; the CLI transcripts print 73 author-time rules. Claude-Session: https://claude.ai/code/session_01JQwxbXGvw43spR79ztEvWt Co-authored-by: Claude --- content/docs/deployment/cli.mdx | 2 +- .../docs/deployment/validating-metadata.mdx | 2 +- .../build-with-claude-code.mdx | 2 +- content/docs/ui/react-pages.mdx | 2 +- .../src/build-probes-landed-data.test.ts | 14 ++++++--- .../src/build-probes-user-message.test.ts | 13 +++++--- .../src/protocol-authoring-gate.ts | 15 ++++++++-- packages/metadata-protocol/src/protocol.ts | 30 ++----------------- 8 files changed, 38 insertions(+), 42 deletions(-) diff --git a/content/docs/deployment/cli.mdx b/content/docs/deployment/cli.mdx index cd2b81bc5a7..4114aaab3c0 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/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/packages/metadata-protocol/src/build-probes-landed-data.test.ts b/packages/metadata-protocol/src/build-probes-landed-data.test.ts index 88a299785d3..175bb7d1305 100644 --- a/packages/metadata-protocol/src/build-probes-landed-data.test.ts +++ b/packages/metadata-protocol/src/build-probes-landed-data.test.ts @@ -15,12 +15,18 @@ import { runBuildProbes, type ProbeAutomation, type ProbeEngine, type RunBuildPr type Row = Record; -/** Fixed tables; honours `where.id.$in` and `limit` (`check:objectql-double-limit`). */ +/** One `where` clause on one row: `{ $in: [...] }`, else equality. */ +const matches = (row: Row, where: Record | undefined): boolean => + Object.entries(where ?? {}).every(([key, want]) => { + const $in = want && typeof want === 'object' ? (want as { $in?: unknown[] }).$in : undefined; + return Array.isArray($in) ? $in.includes(row[key]) : row[key] === want; + }); + +/** Fixed tables; honours `where` and then `limit` (`check:objectql-double-limit`). */ const engineOver = (tables: Record): ProbeEngine => ({ find: async (object, query) => { - const q = query as { where?: { id?: { $in?: unknown[] } }; limit?: unknown } | undefined; - const ids = q?.where?.id?.$in; - const rows = (tables[object] ?? []).filter((r) => !ids || ids.includes(r.id)); + const q = query as { where?: Record; limit?: unknown } | undefined; + const rows = (tables[object] ?? []).filter((r) => matches(r, q?.where)); return typeof q?.limit === 'number' ? rows.slice(0, q.limit) : rows; }, }); 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 f87bfc0a931..b40b072dc4e 100644 --- a/packages/metadata-protocol/src/build-probes-user-message.test.ts +++ b/packages/metadata-protocol/src/build-probes-user-message.test.ts @@ -144,14 +144,19 @@ const engineThrowing: ProbeEngine = { }, }; +/** One `where` clause on one row: `{ $in: [...] }`, else equality. */ +const matches = (row: Record, where: Record | undefined): boolean => + Object.entries(where ?? {}).every(([key, want]) => { + const $in = want && typeof want === 'object' ? (want as { $in?: unknown[] }).$in : undefined; + return Array.isArray($in) ? $in.includes(row[key]) : row[key] === want; + }); /** - * An engine over fixed tables: honours `where.id.$in` and `limit`, so the - * roll-up and reference probes read exactly the rows a real engine would give. + * 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 ids = ((query as { where?: { id?: { $in?: unknown[] } } } | undefined)?.where?.id?.$in); - const rows = (tables[object] ?? []).filter((r) => !ids || ids.includes(r.id)); + const rows = (tables[object] ?? []).filter((r) => matches(r, (query as { where?: Record } | undefined)?.where)); return limited(rows, query); }, }); diff --git a/packages/metadata-protocol/src/protocol-authoring-gate.ts b/packages/metadata-protocol/src/protocol-authoring-gate.ts index 2324825fef2..b39496855a8 100644 --- a/packages/metadata-protocol/src/protocol-authoring-gate.ts +++ b/packages/metadata-protocol/src/protocol-authoring-gate.ts @@ -99,7 +99,8 @@ export interface AuthoringGateHost { unknownGrantObjectSaveRefusal: ObjectStackProtocolImplementation['unknownGrantObjectSaveRefusal']; unknownPicklistBindingSaveRefusal: ObjectStackProtocolImplementation['unknownPicklistBindingSaveRefusal']; seedExternalIdSaveRefusal: ObjectStackProtocolImplementation['seedExternalIdSaveRefusal']; - sealedFlowNodeTypeVocabulary: ObjectStackProtocolImplementation['sealedFlowNodeTypeVocabulary']; + /** [#34776] The automation engine's sealed node-type vocabulary ({@link sealedFlowNodeTypeVocabulary}). */ + sealedFlowNodeTypeVocabulary: () => readonly string[] | undefined; } /** The body of `ObjectStackProtocolImplementation#restoredBodyDerivation`; the method's docblock there is its contract. */ @@ -880,8 +881,16 @@ export async function draftPublishJudgement( } /** - * The body of `ObjectStackProtocolImplementation#sealedFlowNodeTypeVocabulary`; - * the method's docblock there is its contract. + * [#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 }, diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index 84008cc2ab4..73dd33deb17 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -1859,21 +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), - sealedFlowNodeTypeVocabulary: (...a) => this.sealedFlowNodeTypeVocabulary(...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); } /** @@ -2239,18 +2226,7 @@ export class ObjectStackProtocolImplementation implements return rlsMembershipResolverKeys.call(host); } - /** - * 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 publish, as {@link rlsMembershipResolverKeys} reads its service, - * and recorded nowhere. `undefined` — the CLI's reading, under which no node - * type is judged — when this 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"). - */ + /** [#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 = { From cd15670b2c7b0c41b976eb4f6bc63d0cb935533b Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 17:51:14 +0000 Subject: [PATCH 07/15] test: the probe doubles refuse a where operator they do not implement Claude-Session: https://claude.ai/code/session_01JQwxbXGvw43spR79ztEvWt Co-authored-by: Claude --- .../src/build-probes-landed-data.test.ts | 10 +++++++--- .../src/build-probes-user-message.test.ts | 10 +++++++--- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/packages/metadata-protocol/src/build-probes-landed-data.test.ts b/packages/metadata-protocol/src/build-probes-landed-data.test.ts index 175bb7d1305..a04bf01ee4a 100644 --- a/packages/metadata-protocol/src/build-probes-landed-data.test.ts +++ b/packages/metadata-protocol/src/build-probes-landed-data.test.ts @@ -15,11 +15,15 @@ import { runBuildProbes, type ProbeAutomation, type ProbeEngine, type RunBuildPr type Row = Record; -/** One `where` clause on one row: `{ $in: [...] }`, else equality. */ +/** 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]) => { - const $in = want && typeof want === 'object' ? (want as { $in?: unknown[] }).$in : undefined; - return Array.isArray($in) ? $in.includes(row[key]) : row[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` and then `limit` (`check:objectql-double-limit`). */ 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 b40b072dc4e..9d09dc3ee5e 100644 --- a/packages/metadata-protocol/src/build-probes-user-message.test.ts +++ b/packages/metadata-protocol/src/build-probes-user-message.test.ts @@ -144,11 +144,15 @@ const engineThrowing: ProbeEngine = { }, }; -/** One `where` clause on one row: `{ $in: [...] }`, else equality. */ +/** 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]) => { - const $in = want && typeof want === 'object' ? (want as { $in?: unknown[] }).$in : undefined; - return Array.isArray($in) ? $in.includes(row[key]) : row[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 From e45bb8924006679f9584e30470fe306ed893e450 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 18:21:53 +0000 Subject: [PATCH 08/15] feat: examples declare their entry states and http timeouts; ADR-0087 entry for the six refusals app-crm and app-showcase declare `initialStates` on their five state machines and `timeoutMs` on the four showcase http nodes, so they raise none of the new findings. One notice-only ADR-0087 ledger entry, `publish-refuses-metadata-the-runtime-ignores`, carries the six refusals to the upgrade guide. Claude-Session: https://claude.ai/code/session_01JQwxbXGvw43spR79ztEvWt Co-authored-by: Claude --- .../34776-publish-checks-build-probes.md | 2 + examples/app-crm/src/objects/lead.object.ts | 3 ++ .../app-crm/src/objects/opportunity.object.ts | 5 +++ .../flows/exchange-rate-sync.flow.ts | 1 + .../src/automation/flows/index.ts | 6 ++- .../src/data/objects/account.object.ts | 4 ++ .../src/data/objects/project.object.ts | 3 ++ .../src/data/objects/task.object.ts | 4 ++ ...sh-refuses-metadata-the-runtime-ignores.ts | 39 +++++++++++++++++++ 9 files changed, 66 insertions(+), 1 deletion(-) create mode 100644 packages/spec/src/migrations/entries/semantic/18.publish-refuses-metadata-the-runtime-ignores.ts diff --git a/.changeset/34776-publish-checks-build-probes.md b/.changeset/34776-publish-checks-build-probes.md index 8673a19a9cc..5a81ab9af42 100644 --- a/.changeset/34776-publish-checks-build-probes.md +++ b/.changeset/34776-publish-checks-build-probes.md @@ -11,6 +11,8 @@ Clause-②: no (narrowing: six publish-time refusals of metadata the schema acce Metadata-protocol: narrowed Skills-docs: follow-up owed — skills/** traps for the six rules + + Six 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. 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/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..a79de12e47d --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/18.publish-refuses-metadata-the-runtime-ignores.ts @@ -0,0 +1,39 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// The upgrade-guide entry of six 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: + 'Six 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); a `boolean` / `toggle` field marked `required` ' + + '(`field-boolean-required`); a `state_machine` validation with no `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 `config.timeoutMs` on the http node; remove `required` from the ' + + 'checkbox and give it `defaultValue: false` (a validation rule says so when the box must be ticked); 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 with no matching edge routes nowhere; an ' + + 'http call with no timeout waits as long as the connection stays open; a required checkbox makes the record form ' + + 'refuse to save the box unchecked, while `false` is never a missing value; 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 ' + + 'five errors is refused with the fix named, and the http timeout is reported as a warning.', + acceptanceCriteria: + 'os validate reports none of the five 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.', +}; From b2b0dbfa1e110d46638276de913027db04575fe4 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 19:33:57 +0000 Subject: [PATCH 09/15] fix: scope the probes' target and parent reads; classify build-probes.ts in the #22661 census The seed-reference target read and the roll-up parent read are scoped to the publishing organization like the sample reads beside them, with a pin for each. `build-probes.ts` calls `referenceTargetOf`, so the second-object read census classifies it. The changeset names the skills follow-up card. Claude-Session: https://claude.ai/code/session_01JQwxbXGvw43spR79ztEvWt Co-authored-by: Claude --- .../34776-publish-checks-build-probes.md | 2 +- .../second-object-read-exposure.pin.test.ts | 10 +++++ .../src/build-probes-landed-data.test.ts | 38 +++++++++++++++++++ .../metadata-protocol/src/build-probes.ts | 9 ++++- 4 files changed, 56 insertions(+), 3 deletions(-) diff --git a/.changeset/34776-publish-checks-build-probes.md b/.changeset/34776-publish-checks-build-probes.md index 5a81ab9af42..6f82236bafd 100644 --- a/.changeset/34776-publish-checks-build-probes.md +++ b/.changeset/34776-publish-checks-build-probes.md @@ -9,7 +9,7 @@ feat(lint): six publish-time checks for metadata that passes the schema and does Clause-②: no (narrowing: six publish-time refusals of metadata the schema accepts today) Metadata-protocol: narrowed -Skills-docs: follow-up owed — skills/** traps for the six rules +Skills-docs: follow-up #35245 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 352a8741e6c..0f5166a6c16 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 @@ -261,6 +261,16 @@ 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 and scoped to the publishing organization like their sample reads, only " + + "to report whether a landed reference resolves (`seed_reference_unresolved`) or a parent's roll-up was ever " + + 'computed (`rollup_never_computed`); 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/metadata-protocol/src/build-probes-landed-data.test.ts b/packages/metadata-protocol/src/build-probes-landed-data.test.ts index a04bf01ee4a..b7f1a4d6ea5 100644 --- a/packages/metadata-protocol/src/build-probes-landed-data.test.ts +++ b/packages/metadata-protocol/src/build-probes-landed-data.test.ts @@ -219,3 +219,41 @@ describe('flow_connector_action_unresolved: a connector step the runtime cannot expect(report.issues).toEqual([]); }); }); + +describe('the target and parent reads are scoped like the sample reads', () => { + /** Records every read's `where`, over the same fixed tables. */ + const recording = (tables: Record) => { + const wheres: Array<[string, Record | undefined]> = []; + const inner = engineOver(tables); + const engine: ProbeEngine = { + find: async (object, query) => { + wheres.push([object, (query as { where?: Record } | undefined)?.where]); + return inner.find(object, query); + }, + }; + return { engine, wheres }; + }; + + it('seed_reference_unresolved: a target row of another organization does not resolve the reference', async () => { + const { engine, wheres } = recording({ + deal: [{ id: 'd1', organization_id: 'o1', acct_ref: 'a9' }], + acct: [{ id: 'a9', organization_id: 'o2' }], + }); + const report = await run({ engine, organizationId: 'o1', published: [{ type: 'seed', name: 'deal_seed' }] }); + expect(codes(report)).toEqual([['seed_reference_unresolved', 'warning', 'acct_ref']]); + expect(wheres.filter(([o]) => o === 'acct')).toEqual([['acct', { id: { $in: ['a9'] }, organization_id: 'o1' }]]); + }); + + it('rollup_never_computed: a parent row of another organization is not judged', async () => { + const { engine, wheres } = 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([]); + for (const [, where] of wheres.filter(([o]) => o === 'acct')) { + expect(where).toEqual({ id: { $in: ['a1'] }, organization_id: 'o1' }); + } + expect(wheres.filter(([o]) => o === 'acct')).toHaveLength(2); + }); +}); diff --git a/packages/metadata-protocol/src/build-probes.ts b/packages/metadata-protocol/src/build-probes.ts index 642dad84663..6fe5a5db8f2 100644 --- a/packages/metadata-protocol/src/build-probes.ts +++ b/packages/metadata-protocol/src/build-probes.ts @@ -637,8 +637,10 @@ export async function runBuildProbes(opts: RunBuildProbesOptions): Promise c && (!childField || (c[childField] !== null && c[childField] !== undefined)) ? idsIn(c[fk]) : []))]; if (parentIds.length === 0) continue; + // Scoped like the sample read above: a parent is judged in the + // organization the children were read in. const parents = asArr(await engine.find(p.name, { - where: { id: { $in: parentIds } }, + where: scoped(organizationId, { id: { $in: parentIds } }), limit: parentIds.length, context: SYSTEM_READ, })).map(asRec).filter((r): r is Rec => !!r); @@ -709,8 +711,11 @@ export async function runBuildProbes(opts: RunBuildProbesOptions): Promise; try { + // Scoped like the sample read above: the edit form resolves a + // reference inside the organization, so a row of another one + // does not resolve it here either. const existing = asArr(await engine.find(target, { - where: { id: { $in: values } }, + where: scoped(organizationId, { id: { $in: values } }), limit: values.length, context: SYSTEM_READ, })).map(asRec); From e4e91312a2c180ee028f378737c5c8c9443d2760 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 20:03:13 +0000 Subject: [PATCH 10/15] fix: contract review round: drop field-boolean-required, scope and project the landed-data probes, honest consequence texts - Remove `field-boolean-required` (rule, explanation, export, pins, ledger and changeset lines): the form treats `false` as present and the server's `required` refuses null, so the flag guards something real. - `state-machine-no-initial-states`: an empty `initialStates` trips it; an `active: false` machine is skipped, as the engine skips it. - `flow-http-timeout-missing`: a positive node-level `timeoutMs` counts, `0` arms no timer, and a `durable: true` node is not reported. - Build probes: the seed check reads the seed's own rows (by its `externalId`), every landed-data read is projected and kept inside an organization the way the reference audit keeps its probe, and the existence checks stay one `id $in` read per organization. - Consequence texts: a stored dangling reference no longer claims the record cannot be saved; the roll-up repair names `os migrate summary-nulls --apply` and the install door; approval and action-binding sentences match the engine; `severity`, `ref` and `initialStates` describes restated. Claude-Session: https://claude.ai/code/session_01JQwxbXGvw43spR79ztEvWt Co-authored-by: Claude --- .../34776-publish-checks-build-probes.md | 17 +- content/docs/references/api/protocol.mdx | 8 +- content/docs/references/data/validation.mdx | 8 +- .../second-object-read-exposure.pin.test.ts | 10 +- packages/lint/src/authoring-rules.ts | 12 +- packages/lint/src/index.ts | 1 - packages/lint/src/lint-flow-patterns.test.ts | 18 +- packages/lint/src/lint-flow-patterns.ts | 32 ++- packages/lint/src/rule-explanations.ts | 33 +-- .../src/runtime-gate.object-writes.test.ts | 4 +- .../src/validate-action-object-binding.ts | 8 +- ...validate-inert-object-declarations.test.ts | 47 ++-- .../src/validate-inert-object-declarations.ts | 52 ++-- .../src/build-probes-landed-data.test.ts | 124 +++++++-- .../src/build-probes-user-message.test.ts | 4 +- .../metadata-protocol/src/build-probes.ts | 238 +++++++++++++----- .../src/build-probes.user-text.ts | 73 +++--- packages/spec/src/api/protocol.zod.ts | 20 +- packages/spec/src/data/validation.zod.ts | 2 +- ...sh-refuses-metadata-the-runtime-ignores.ts | 27 +- 20 files changed, 459 insertions(+), 279 deletions(-) diff --git a/.changeset/34776-publish-checks-build-probes.md b/.changeset/34776-publish-checks-build-probes.md index 6f82236bafd..8472e1111fa 100644 --- a/.changeset/34776-publish-checks-build-probes.md +++ b/.changeset/34776-publish-checks-build-probes.md @@ -5,7 +5,7 @@ '@objectstack/spec': minor --- -feat(lint): six publish-time checks for metadata that passes the schema and does nothing at run time, and four build probes over what landed +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: six publish-time refusals of metadata the schema accepts today) Metadata-protocol: narrowed @@ -13,17 +13,16 @@ Skills-docs: follow-up #35245 -Six authoring rules join the registry the runtime publish gate and `objectstack validate` / `lint` / `compile` run. Each finding names its fix. +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` routes no decision. -- `flow-http-timeout-missing` (warning): an `http` node with no `timeoutMs` waits on a slow upstream for as long as the connection stays open; the engine arms no default timer. -- `field-boolean-required` (error): a `boolean` / `toggle` field marked `required` guards nothing, and the record form refuses to save the box unchecked. Remove `required` (and give it `defaultValue: false`). -- `state-machine-no-initial-states` (error): a `state_machine` validation without `initialStates` lets a record be created already in any state. Add `initialStates`. +- `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. +- `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 required checkbox, a state machine without `initialStates`, a placed action with no object. The fix for each is in the finding. +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 landed sample record whose reference names no row, so the edit form cannot save it) 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` and `packageId`; the publish passes the automation engine's connector lookups and the publishing package. +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 landed sample record whose reference names no row in the publishing organization, so its page shows a reference to nothing) 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` and `packageId`; the publish passes the automation engine's connector lookups and the publishing package. -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`, `FIELD_BOOLEAN_REQUIRED`, `STATE_MACHINE_NO_INITIAL_STATES`, `ACTION_NO_OBJECT_BINDING`; `@objectstack/metadata-protocol` adds the `ProbeAutomation` type; `@objectstack/service-automation` adds `AutomationEngine.getSealedNodeTypeVocabulary()`. `@objectstack/spec` changes only the descriptions of `RuntimeBuildIssueSchema`. +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` type; `@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/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index e9d175a1996..2d71a0a07b8 100644 --- a/content/docs/references/api/protocol.mdx +++ b/content/docs/references/api/protocol.mdx @@ -474,9 +474,9 @@ 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 (`widget_not_probed`, `probes_unavailable`), or what landed reads in a way the person will notice although it may be the truth (`widget_empty_result`, `rollup_never_computed`, `seed_reference_unresolved`, `flow_connector_action_unresolved`). 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, the connector a flow step dispatches. Absent when the finding is about the artifact as a whole. | +| **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. | @@ -2970,9 +2970,9 @@ 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 (`widget_not_probed`, `probes_unavailable`), or what landed reads in a way the person will notice although it may be the truth (`widget_empty_result`, `rollup_never_computed`, `seed_reference_unresolved`, `flow_connector_action_unresolved`). 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, the connector a flow step dispatches. Absent when the finding is about the artifact as a whole. | +| **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. | 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/packages/core/src/security/second-object-read-exposure.pin.test.ts b/packages/core/src/security/second-object-read-exposure.pin.test.ts index 0f5166a6c16..6217b4a5a9c 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 @@ -266,10 +266,12 @@ const CALLERS: Record = { 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 and scoped to the publishing organization like their sample reads, only " + - "to report whether a landed reference resolves (`seed_reference_unresolved`) or a parent's roll-up was ever " + - 'computed (`rollup_never_computed`); 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', + "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', diff --git a/packages/lint/src/authoring-rules.ts b/packages/lint/src/authoring-rules.ts index 02d5abb70f7..4e48111b30e 100644 --- a/packages/lint/src/authoring-rules.ts +++ b/packages/lint/src/authoring-rules.ts @@ -1856,8 +1856,9 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ }, // 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) and the object's action route answers "not found". - // Gating: nothing about the declaration can work. On the runtime door for 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', @@ -1902,10 +1903,9 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ surfaceReason: RUNTIME_NEEDS_FULL_SNAPSHOT, run: (stack) => validateSeedStateMachine(stack), }, - // A required checkbox (the form refuses an unchecked box, so only "on" can be - // saved) and a state machine with no `initialStates` (a record can be born - // in any state). Gating: each declaration works against its author on every - // record. Reads the object's own body alone, so it judges an `object` write + // 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', diff --git a/packages/lint/src/index.ts b/packages/lint/src/index.ts index 7bb2c637431..186a386d1b8 100644 --- a/packages/lint/src/index.ts +++ b/packages/lint/src/index.ts @@ -681,7 +681,6 @@ export { validateFlowNodeExecutors, FLOW_NODE_TYPE_NO_EXECUTOR } from './validat export type { FlowNodeExecutorFinding } from './validate-flow-node-executors.js'; export { validateInertObjectDeclarations, - FIELD_BOOLEAN_REQUIRED, STATE_MACHINE_NO_INITIAL_STATES, } from './validate-inert-object-declarations.js'; export type { InertObjectDeclarationFinding } from './validate-inert-object-declarations.js'; diff --git a/packages/lint/src/lint-flow-patterns.test.ts b/packages/lint/src/lint-flow-patterns.test.ts index 6f56e5b7449..130c3e65a9f 100644 --- a/packages/lint/src/lint-flow-patterns.test.ts +++ b/packages/lint/src/lint-flow-patterns.test.ts @@ -4190,14 +4190,14 @@ describe('flow-approval-decision-unrouted — an approval decision continues onl }); describe('flow-http-timeout-missing — an http node without a timeout of its own', () => { - const httpFlow = (config: Record) => ({ + 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 } }, + { id: 'call', type: 'http', label: 'Call ERP', config: { url: 'https://erp.example.com/orders', ...config }, ...node }, ], edges: [{ id: 'e0', source: 'start', target: 'call' }], }], @@ -4215,4 +4215,18 @@ describe('flow-http-timeout-missing — an http node without a timeout of its ow 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('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 000bbf8e91c..ae8fe661f23 100644 --- a/packages/lint/src/lint-flow-patterns.ts +++ b/packages/lint/src/lint-flow-patterns.ts @@ -385,8 +385,9 @@ export const FLOW_TRY_CATCH_WITHOUT_CATCH = 'flow-try-catch-without-catch'; */ export const FLOW_APPROVAL_DECISION_UNROUTED = 'flow-approval-decision-unrouted'; /** - * An `http` node with no `config.timeoutMs`. `warning`: the executor arms its - * timer only when the key is set. See {@link scanHttpTimeouts}. + * 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'; @@ -1877,26 +1878,37 @@ function scanApprovalDecisionEdges( } /** - * An `http` node with no `config.timeoutMs` has no timer of its own: the - * executor arms one only when the key is set (`service-automation` - * `builtin/http-nodes.ts`), so 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. + * 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 (cfg.timeoutMs !== undefined) continue; + if (armed(cfg.timeoutMs) || armed(node.timeoutMs) || cfg.durable === true) continue; const nodeId = typeof node.id === 'string' ? node.id : 'http'; + const what = cfg.timeoutMs === 0 ? 'sets `config.timeoutMs: 0`, 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}' sets no \`config.timeoutMs\`, so the call has no timeout of its own: an endpoint ` + + `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 number of milliseconds, e.g. `timeoutMs: 10000`.', + hint: 'Set `config.timeoutMs` to a positive number of milliseconds, e.g. `timeoutMs: 10000`.', rule: FLOW_HTTP_TIMEOUT_MISSING, }); } diff --git a/packages/lint/src/rule-explanations.ts b/packages/lint/src/rule-explanations.ts index 3cbc0374316..cba378f810d 100644 --- a/packages/lint/src/rule-explanations.ts +++ b/packages/lint/src/rule-explanations.ts @@ -6290,36 +6290,27 @@ 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 set. Without it 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.', + '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 FIELD_BOOLEAN_REQUIRED_EXPLANATION: RuleExplanation = { - rule: 'field-boolean-required', - covers: 'why a checkbox is never required', - paragraphs: [ - '`required` says a record must carry a value. A `boolean` or `toggle` field always carries one of its two ' + - 'values, and `false` is a value, so the flag guards nothing. The record form reads it the other way: as ' + - '"must be checked". It then refuses to save the box unchecked, and the app can only create records with ' + - 'the box on — the state the control shows by default is the one value it will not save.', - 'Remove `required`, and give the field `defaultValue: false` so a new record starts unchecked. If the box ' + - 'really must be ticked (an accepted agreement), say so with a validation rule.', - ], -}; - 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.', + '`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.', + '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.', ], }; @@ -6329,8 +6320,9 @@ const ACTION_NO_OBJECT_BINDING_EXPLANATION: RuleExplanation = { 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, the ' + - 'button it declares renders nowhere, and the object\'s action route answers "not found".', + '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.', @@ -6575,7 +6567,6 @@ export const RULE_EXPLANATIONS: Readonly> = Obje [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, - [FIELD_BOOLEAN_REQUIRED_EXPLANATION.rule]: FIELD_BOOLEAN_REQUIRED_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, }); diff --git a/packages/lint/src/runtime-gate.object-writes.test.ts b/packages/lint/src/runtime-gate.object-writes.test.ts index 359ec0ca712..7844c61232e 100644 --- a/packages/lint/src/runtime-gate.object-writes.test.ts +++ b/packages/lint/src/runtime-gate.object-writes.test.ts @@ -162,8 +162,8 @@ 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 required checkbox and a state machine with no entry guard, judged on - // the object's own body (`validate-inert-object-declarations.ts`). + // 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 diff --git a/packages/lint/src/validate-action-object-binding.ts b/packages/lint/src/validate-action-object-binding.ts index e6901995572..84c08d2fecd 100644 --- a/packages/lint/src/validate-action-object-binding.ts +++ b/packages/lint/src/validate-action-object-binding.ts @@ -9,8 +9,10 @@ * 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 and a call on an - * object's action route answers "not found". The spec's own note on the + * 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. * @@ -51,7 +53,7 @@ export function validateActionObjectBinding(stack: Record): Act path: `actions[${list.indexOf(action)}].objectName`, message: `Action "${name}" declares ${locations.map((l) => `\`${l}\``).join(', ')} but no \`objectName\`, so it binds ` + - 'to no object: the button never renders, and a call on an object\'s action route answers "not found".', + '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).', diff --git a/packages/lint/src/validate-inert-object-declarations.test.ts b/packages/lint/src/validate-inert-object-declarations.test.ts index cf0ed81763a..0bbf17b6661 100644 --- a/packages/lint/src/validate-inert-object-declarations.test.ts +++ b/packages/lint/src/validate-inert-object-declarations.test.ts @@ -3,7 +3,6 @@ import { describe, expect, it } from 'vitest'; import { runRuntimeAuthoringRules } from './runtime-gate.js'; import { - FIELD_BOOLEAN_REQUIRED, STATE_MACHINE_NO_INITIAL_STATES, validateInertObjectDeclarations, } from './validate-inert-object-declarations.js'; @@ -29,27 +28,6 @@ const machine = (extra: Record = {}) => ({ ...extra, }); -describe('field-boolean-required', () => { - it('refuses a required boolean and a required toggle, at the `required` key', () => { - const findings = validateInertObjectDeclarations({ - objects: [task({ is_done: { type: 'boolean', label: 'Done', required: true }, on: { type: 'toggle', label: 'On', required: true, defaultValue: false } })], - }); - expect(findings.map((f) => [f.rule, f.severity, f.path])).toEqual([ - [FIELD_BOOLEAN_REQUIRED, 'error', 'objects[0].fields.is_done.required'], - [FIELD_BOOLEAN_REQUIRED, 'error', 'objects[0].fields.on.required'], - ]); - // The fix names the default only where the field has none. - expect(findings[0].hint).toContain('defaultValue: false'); - expect(findings[1].hint).not.toContain('defaultValue'); - }); - - it('is silent on an optional boolean and on a required non-boolean', () => { - expect(validateInertObjectDeclarations({ - objects: [task({ is_done: { type: 'boolean', label: 'Done', defaultValue: false }, code: { type: 'text', label: 'Code', required: true } })], - })).toEqual([]); - }); -}); - 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()])] }); @@ -58,6 +36,15 @@ describe('state-machine-no-initial-states', () => { 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' }])], @@ -65,12 +52,16 @@ describe('state-machine-no-initial-states', () => { }); }); -describe('the runtime publish gate refuses an object write carrying either declaration', () => { - it('raises each as an error on an `object` write', () => { - const item = task({ is_done: { type: 'boolean', label: 'Done', required: true }, status: STATUS }, [machine()]); +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 }); - const rules = verdict.errors.map((f) => f.rule); - expect(rules).toContain(FIELD_BOOLEAN_REQUIRED); - expect(rules).toContain(STATE_MACHINE_NO_INITIAL_STATES); + 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 index 47436853238..3c722679f88 100644 --- a/packages/lint/src/validate-inert-object-declarations.ts +++ b/packages/lint/src/validate-inert-object-declarations.ts @@ -1,27 +1,24 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * Two object declarations that pass the schema and then work against their - * author at run time — each a refusal at publish, with the fix named. + * An object declaration that passes the schema and then works against its + * author at run time — a refusal at publish, with the fix named. * - * 1. {@link FIELD_BOOLEAN_REQUIRED} — a `boolean` / `toggle` field marked - * `required`. `required` is a presence contract and a checkbox is never - * absent, so it guards nothing; the record form reads it as "must be - * checked" and refuses to save the box unchecked, so the app can only ever - * create records with the box ON. - * 2. {@link STATE_MACHINE_NO_INITIAL_STATES} — a `state_machine` validation - * with no `initialStates`. `transitions` governs UPDATE only, so without an - * entry guard a record can be CREATED already in any state (born - * `approved`), walking straight past the process the machine declares. + * {@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. * - * Both read the object's own body alone, so the runtime publish gate judges an + * 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 FIELD_BOOLEAN_REQUIRED = 'field-boolean-required'; export const STATE_MACHINE_NO_INITIAL_STATES = 'state-machine-no-initial-states'; export interface InertObjectDeclarationFinding { @@ -33,38 +30,19 @@ export interface InertObjectDeclarationFinding { hint: string; } -const CHECKBOX_TYPES = new Set(['boolean', 'toggle']); - -/** Flag a required checkbox and an entry-unguarded state machine on every object. */ +/** 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; - for (const { rec: field, path: fieldPath } of collectionEntries(obj.fields, `${objPath}.fields`)) { - if (typeof field.type !== 'string' || !CHECKBOX_TYPES.has(field.type) || field.required !== true) continue; - const fieldName = typeof field.name === 'string' ? field.name : fieldPath; - const hasDefault = field.defaultValue !== undefined && field.defaultValue !== null; - findings.push({ - severity: 'error', - rule: FIELD_BOOLEAN_REQUIRED, - where: `object "${objectName}" field "${fieldName}"`, - path: `${fieldPath}.required`, - message: - `Field "${fieldName}" is a ${field.type} marked required. "false" is a legal value, not a missing one, ` + - 'so the flag guards nothing — and the record form reads it as "must be checked" and refuses to save ' + - 'the box unchecked.', - hint: - `Remove \`required\` from "${fieldName}"${hasDefault ? '' : ' and give it `defaultValue: false`'}. ` + - 'If the box really must be ticked, write a validation rule that says so.', - }); - } - 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.initialStates !== undefined) continue; + 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) : []; @@ -75,7 +53,7 @@ export function validateInertObjectDeclarations(stack: Record): where: `object "${objectName}" validation "${ruleName}"`, path: `${objPath}.validations[${validationList.indexOf(rule)}]`, message: - `State machine "${ruleName}" declares no \`initialStates\`. Its \`transitions\` govern updates only, so a ` + + `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` + diff --git a/packages/metadata-protocol/src/build-probes-landed-data.test.ts b/packages/metadata-protocol/src/build-probes-landed-data.test.ts index b7f1a4d6ea5..f0e207cceb4 100644 --- a/packages/metadata-protocol/src/build-probes-landed-data.test.ts +++ b/packages/metadata-protocol/src/build-probes-landed-data.test.ts @@ -26,13 +26,30 @@ const matches = (row: Row, where: Record | undefined): boolean return $in.includes(row[key]); }); -/** Fixed tables; honours `where` and then `limit` (`check:objectql-double-limit`). */ +/** + * 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 } | undefined; - const rows = (tables[object] ?? []).filter((r) => matches(r, q?.where)); - return typeof q?.limit === 'number' ? rows.slice(0, q.limit) : rows; + 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 = { @@ -55,7 +72,8 @@ const ITEMS: Record = { owner: { type: 'user' }, }, }, - 'seed deal_seed': { object: 'deal', records: [] }, + 'seed deal_seed': { object: 'deal', records: [{ name: 'D1' }, { name: 'D2' }] }, + 'seed deal_seed_composite': { object: 'deal', externalId: ['acct_ref', 'name'], records: [{ name: 'D1' }] }, 'dashboard board': { name: 'board', widgets: [{ id: 'w1', dataset: 'deal_totals', values: ['total'] }], @@ -144,7 +162,7 @@ describe('seed_reference_unresolved: a landed reference naming no row', () => { 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', acct_ref: 'a1', owner: 'Jane Smith' }, { id: 'd2', acct_ref: 'a_gone' }], + 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' }], }), @@ -161,17 +179,40 @@ describe('seed_reference_unresolved: a landed reference naming no row', () => { it('every value resolves, or the column is blank: silent', async () => { const report = await run({ - engine: engineOver({ deal: [{ id: 'd1', acct_ref: 'a1', owner: 'u1' }, { id: 'd2', acct_ref: null }], acct: [{ id: 'a1' }], sys_user: [{ id: 'u1' }] }), + 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' }], + }), + published, + }); + expect(report.issues).toEqual([]); + }); + + it('a row the seed did not write is not judged as the seed\'s', async () => { + const report = await run({ + engine: engineOver({ + deal: [{ id: 'd1', name: 'D1', acct_ref: 'a1' }, { id: 'd9', name: 'Typed by a person', acct_ref: 'a_gone' }], + acct: [{ id: 'a1' }], + }), published, }); expect(report.issues).toEqual([]); }); + it('a seed whose key is composite identifies no row by itself, and is not judged', async () => { + const report = await run({ + engine: engineOver({ deal: [{ id: 'd1', name: 'D1', acct_ref: 'a_gone' }], acct: [] }), + published: [{ type: 'seed', name: 'deal_seed_composite' }], + }); + 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', acct_ref: 'a_gone' }]; + if (object === 'deal') return [{ id: 'd1', name: 'D1', acct_ref: 'a_gone' }]; throw new Error('no such table'); }, }, @@ -220,40 +261,81 @@ describe('flow_connector_action_unresolved: a connector step the runtime cannot }); }); -describe('the target and parent reads are scoped like the sample reads', () => { - /** Records every read's `where`, over the same fixed tables. */ +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 wheres: Array<[string, Record | undefined]> = []; + const reads: Read[] = []; const inner = engineOver(tables); const engine: ProbeEngine = { find: async (object, query) => { - wheres.push([object, (query as { where?: Record } | undefined)?.where]); + 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, wheres }; + return { engine, reads }; }; + const seedRowsRead = (r: Read) => r.object === 'deal' && r.where?.name !== undefined; it('seed_reference_unresolved: a target row of another organization does not resolve the reference', async () => { - const { engine, wheres } = recording({ - deal: [{ id: 'd1', organization_id: 'o1', acct_ref: 'a9' }], + 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', published: [{ type: 'seed', name: 'deal_seed' }] }); expect(codes(report)).toEqual([['seed_reference_unresolved', 'warning', 'acct_ref']]); - expect(wheres.filter(([o]) => o === 'acct')).toEqual([['acct', { id: { $in: ['a9'] }, organization_id: 'o1' }]]); + 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 its key, projected to what is judged. (The + // first `deal` read is `seed_not_applied`'s row count.) + expect(reads.find(seedRowsRead)).toEqual({ + object: 'deal', + where: { name: { $in: ['D1', 'D2'] } }, + fields: ['id', 'acct_ref', 'owner'], + context: { isSystem: true, tenantId: 'o1' }, + }); + }); + + 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, 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)!.context).toEqual({ isSystem: true }); + 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, wheres } = recording({ + 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([]); - for (const [, where] of wheres.filter(([o]) => o === 'acct')) { - expect(where).toEqual({ id: { $in: ['a1'] }, organization_id: 'o1' }); - } - expect(wheres.filter(([o]) => o === 'acct')).toHaveLength(2); + 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)).toEqual([ + ['id', 'acct_ref'], + ['id', 'acct_ref', 'amount'], + ]); }); }); 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 9d09dc3ee5e..c60b4aaaff9 100644 --- a/packages/metadata-protocol/src/build-probes-user-message.test.ts +++ b/packages/metadata-protocol/src/build-probes-user-message.test.ts @@ -116,7 +116,7 @@ const ITEMS: Record = { label: DEALS, fields: { acct_ref: { type: 'lookup', reference: 'crm_acct', label: ACCT_REF } }, }, - 'seed crm_deal_seed': { object: 'crm_deal', records: [] }, + 'seed crm_deal_seed': { object: 'crm_deal', records: [{ name: 'Big deal' }] }, 'flow crm_erp_sync': { name: 'crm_erp_sync', label: ERP_SYNC, @@ -439,7 +439,7 @@ const CASES: readonly ProbeCase[] = [ 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', acct_ref: 'Acme Corp' }], crm_acct: [{ id: 'a1' }] }), + engine: engineOver({ crm_deal: [{ id: 'd1', name: 'Big deal', acct_ref: 'Acme Corp' }], crm_acct: [{ id: 'a1' }] }), published: [{ type: 'seed', name: 'crm_deal_seed' }], }), params: (tag) => ({ object: DEALS, field: said(ACCT_REF, tag, 'acct_ref'), target: ACCOUNTS, count: '1' }), diff --git a/packages/metadata-protocol/src/build-probes.ts b/packages/metadata-protocol/src/build-probes.ts index 6fe5a5db8f2..5b9659af01b 100644 --- a/packages/metadata-protocol/src/build-probes.ts +++ b/packages/metadata-protocol/src/build-probes.ts @@ -27,7 +27,7 @@ import type { BuildProbeReport, RuntimeBuildIssue, StandardErrorCode } from '@ob import { resolveI18nLabel, type I18nLabel } from '@objectstack/spec/ui'; import { referenceTargetOf } from '@objectstack/spec/data'; import { collectFlowGraphs } from '@objectstack/spec/automation'; -import { PackageScopedNameRefusedError, describePackageScopedHolder, type PackageScopedRefusal } from '@objectstack/core'; +import { PackageScopedNameRefusedError, describePackageScopedHolder, resolveTenantFieldName, type PackageScopedRefusal } from '@objectstack/core'; import { buildProbeUserMessage, buildProbeUserTextLocale } from './build-probes.user-text.js'; /** @@ -88,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. */ @@ -256,12 +264,6 @@ async function hasRows( /** Rows sampled from an object by the data probes, and distinct values probed per column. */ const PROBE_SAMPLE_ROWS = 50; -/** The `where` a probe read scopes to the publishing organization, beside its own clause. */ -function scoped(organizationId: string | null | undefined, where: Rec = {}): Rec | undefined { - const merged = organizationId ? { ...where, organization_id: organizationId } : where; - return Object.keys(merged).length > 0 ? merged : undefined; -} - /** 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; @@ -277,6 +279,51 @@ 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); +} + +/** 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'; @@ -606,16 +653,25 @@ export async function runBuildProbes(opts: RunBuildProbesOptions): Promise - c && (!childField || (c[childField] !== null && c[childField] !== undefined)) ? idsIn(c[fk]) : []))]; - if (parentIds.length === 0) continue; - // Scoped like the sample read above: a parent is judged in the - // organization the children were read in. - const parents = asArr(await engine.find(p.name, { - where: scoped(organizationId, { id: { $in: parentIds } }), - limit: parentIds.length, context: SYSTEM_READ, })).map(asRec).filter((r): r is Rec => !!r); + const named = new Map(); + for (const c of children) { + if (childField && (c[childField] === null || c[childField] === undefined)) continue; + for (const id of idsIn(c[fk])) pushTo(named, rowOrganization(c, orgColumn, organizationId ?? null), id); + } + if (named.size === 0) continue; + const parents: Rec[] = []; + for (const [organization, list] of named) { + const ids = [...new Set(list)]; + parents.push(...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.some((r) => r[fieldName] !== null && r[fieldName] !== undefined)) continue; issues.push({ layer: 'runtime', @@ -653,11 +716,14 @@ export async function runBuildProbes(opts: RunBuildProbesOptions): Promise x.type === 'seed')) { const seed = asRec(await readItem('seed', p.name)); const objectName = typeof seed?.object === 'string' ? seed.object : undefined; if (!objectName) continue; + const externalId = seed?.externalId === undefined ? 'name' : seed.externalId; + if (typeof externalId !== 'string' || !externalId) continue; + const keys = [...new Set(asArr(seed?.records).map(asRec).flatMap((r): Array => { + const v = r?.[externalId]; + return (typeof v === 'string' && v !== '') || typeof v === 'number' ? [v] : []; + }))].slice(0, PROBE_SAMPLE_ROWS); + if (keys.length === 0) continue; const objectBody = asRec(await readItem('object', objectName)); const refFields = fieldsOf(objectBody).flatMap(([name, def]) => { let target: string | undefined; @@ -696,36 +787,45 @@ export async function runBuildProbes(opts: RunBuildProbesOptions): Promise f.name), ...(orgColumn ? [orgColumn] : [])])], limit: PROBE_SAMPLE_ROWS, - ...(scoped(organizationId) ? { where: scoped(organizationId) } : {}), context: SYSTEM_READ, })).map(asRec).filter((r): r is Rec => !!r); } catch { continue; } for (const { name: field, def, target } of refFields) { - const values = [...new Set(rows.flatMap((r) => idsIn(r[field])))].slice(0, PROBE_SAMPLE_ROWS); - if (values.length === 0) continue; - let found: Set; + 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 { - // Scoped like the sample read above: the edit form resolves a - // reference inside the organization, so a row of another one - // does not resolve it here either. - const existing = asArr(await engine.find(target, { - where: scoped(organizationId, { id: { $in: values } }), - limit: values.length, - context: SYSTEM_READ, - })).map(asRec); - found = new Set(existing.map((r) => String(r?.id ?? r?._id))); + 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 missing = values.filter((v) => !found.has(v)); - if (missing.length === 0) continue; - const shown = missing.slice(0, 5).map((v) => `"${v}"`).join(', '); + const distinct = [...new Set(missing)]; + if (distinct.length === 0) continue; + // The values quoted are the seed rows' own column, read in scope; + // 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', @@ -733,9 +833,9 @@ export async function runBuildProbes(opts: RunBuildProbesOptions): Promise 5 ? ', …' : ''}. The edit form submits the whole record and the engine re-checks ` + - `every reference in it, so those records cannot be saved (\`${field}: reference_not_found\`), whichever field the user changed.`, + `Reference column "${objectName}.${field}" holds ${distinct.length} value(s) on the seed's rows 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 and nothing else will say so.', 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.', @@ -743,7 +843,7 @@ export async function runBuildProbes(opts: RunBuildProbesOptions): Promise `The roll-up field "${p.field}" on "${p.object}" is blank on every record that has related "${p.child}" ` + - `records, so it has not been calculated yet. Edit one of those "${p.child}" records to recalculate it.`, + `records: its stored value was never calculated for them. 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.child}”记录以重新计算。`, + `“${p.object}”的汇总字段“${p.field}”在每条有相关“${p.child}”记录的记录上都是空的:它的存储值从未为这些记录计算过。` + + `请让负责此环境的人重新计算汇总字段(\`os migrate summary-nulls --apply\`)。`, 'zh-Hant': (p) => - `「${p.object}」的匯總欄位「${p.field}」在每筆有相關「${p.child}」記錄的記錄上都是空的,表示它還沒有計算過。` + - `請編輯其中一筆「${p.child}」記錄以重新計算。`, + `「${p.object}」的匯總欄位「${p.field}」在每筆有相關「${p.child}」記錄的記錄上都是空的:它的儲存值從未為這些記錄計算過。` + + `請讓負責此環境的人重新計算匯總欄位(\`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}", así que aún no se ha calculado. Edite uno de esos registros de "${p.child}" para recalcularlo.`, + `relacionados de "${p.child}": su valor almacenado nunca se calculó para ellos. 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.child}" هذه لإعادة حسابه.`, + `حقل التجميع "${p.field}" في "${p.object}" فارغ في كل سجل له سجلات "${p.child}" مرتبطة: لم تُحسب قيمته المخزنة لها قط. ` + + `اطلب من مسؤول هذه البيئة إعادة حساب حقول التجميع (\`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 : il n’a donc pas encore été calculé. Modifiez l’un de ces ` + - `enregistrements « ${p.child} » pour le recalculer.`, + `enregistrements « ${p.child} » liés : sa valeur stockée n’a jamais été calculée pour eux. 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}", então ainda não foi calculado. Edite um desses registros de "${p.child}" para recalculá-lo.`, + `relacionados de "${p.child}": seu valor armazenado nunca foi calculado para eles. 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.child}», чтобы пересчитать его.`, + `«${p.child}»: его сохранённое значение для них ни разу не рассчитывалось. Попросите администратора этой среды ` + + `пересчитать сводные поля (\`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, wurde also noch nicht berechnet. Bearbeiten Sie einen dieser „${p.child}“-Datensätze, um es neu zu berechnen.`, + `leer: Sein gespeicherter Wert wurde für sie nie berechnet. 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.child}」レコードのいずれかを編集して再計算してください。`, + `「${p.object}」の積み上げ集計項目「${p.field}」は、関連する「${p.child}」レコードを持つすべてのレコードで空です。` + + `保存値がこれらのレコードについて一度も計算されていません。この環境の管理者に集計の再計算` + + `(\`os migrate summary-nulls --apply\`)を依頼してください。`, ko: (p) => - `"${p.object}"의 롤업 필드 "${p.field}"가 관련 "${p.child}" 레코드가 있는 모든 레코드에서 비어 있어 아직 계산되지 않았습니다. ` + - `해당 "${p.child}" 레코드 중 하나를 편집하여 다시 계산하세요.`, + `"${p.object}"의 롤업 필드 "${p.field}"가 관련 "${p.child}" 레코드가 있는 모든 레코드에서 비어 있습니다. ` + + `저장된 값이 이 레코드들에 대해 한 번도 계산되지 않았습니다. 이 환경의 관리자에게 롤업 재계산` + + `(\`os migrate summary-nulls --apply\`)을 요청하세요.`, }; -/** `seed_reference_unresolved`: sample records point at records that do not exist, so they cannot be saved. */ +/** `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 those records cannot be saved after an edit. Fix or clear "${p.field}" in the sample data, ` + + `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.object}”示例记录(“${p.field}”中有 ${p.count} 个值)指向不存在的“${p.target}”记录,因此这些记录上的“${p.field}”指向空处。` + `请在示例数据中修正或清空“${p.field}”,然后重新发布。`, 'zh-Hant': (p) => - `部分「${p.object}」示例記錄(「${p.field}」中有 ${p.count} 個值)指向不存在的「${p.target}」記錄,因此這些記錄編輯後無法儲存。` + + `部分「${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, por lo que no se pueden guardar tras editarlos. Corrija o vacíe "${p.field}" en ` + - `los datos de ejemplo y vuelva a publicar.`, + `"${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}" في هذه السجلات إلى أي مكان. صحّح "${p.field}" في البيانات التجريبية أو أفرغه، ثم أعد النشر.`, fr: (p) => `Certains enregistrements d’exemple « ${p.object} » (${p.count} valeur(s) dans « ${p.field} ») pointent vers ` + - `des enregistrements « ${p.target} » inexistants : ils ne peuvent donc pas être enregistrés après une ` + - `modification. Corrigez ou videz « ${p.field} » dans les données d’exemple, puis publiez à nouveau.`, + `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 não podem ser salvos após uma edição. Corrija ou limpe "${p.field}" nos ` + - `dados de exemplo e publique novamente.`, + `"${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.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, und lassen sich daher nach einer Änderung nicht speichern. Korrigieren oder ` + + `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}」はどこにもつながりません。サンプルデータの「${p.field}」を修正するか空にしてから、もう一度公開してください。`, ko: (p) => `일부 "${p.object}" 샘플 레코드("${p.field}"의 값 ${p.count}개)가 존재하지 않는 "${p.target}" 레코드를 가리키므로 ` + - `편집 후 저장할 수 없습니다. 샘플 데이터에서 "${p.field}"를 수정하거나 비운 후 다시 게시하세요.`, + `해당 레코드의 "${p.field}"는 아무 곳으로도 연결되지 않습니다. 샘플 데이터에서 "${p.field}"를 수정하거나 비운 후 다시 게시하세요.`, }; /** diff --git a/packages/spec/src/api/protocol.zod.ts b/packages/spec/src/api/protocol.zod.ts index 0d456476a0c..e6447d140eb 100644 --- a/packages/spec/src/api/protocol.zod.ts +++ b/packages/spec/src/api/protocol.zod.ts @@ -1848,10 +1848,13 @@ export const RuntimeBuildIssueSchema = lazySchema(() => z.object({ '`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`), or what landed reads in a ' - + 'way the person will notice although it may be the truth (`widget_empty_result`, ' - + '`rollup_never_computed`, `seed_reference_unresolved`, ' - + '`flow_connector_action_unresolved`). Neither fails the publish.', + + '(`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`, `flow`).'), @@ -1870,10 +1873,11 @@ export const RuntimeBuildIssueSchema = lazySchema(() => z.object({ + '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, the connector a flow step dispatches. 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 ' 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 index a79de12e47d..643195c1dff 100644 --- 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 @@ -2,7 +2,7 @@ import type { SemanticMigration } from '../../types.js'; -// The upgrade-guide entry of six author-time rules (#34776) that refuse, at +// 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 @@ -10,30 +10,27 @@ import type { SemanticMigration } from '../../types.js'; export const entry: SemanticMigration = { id: 'publish-refuses-metadata-the-runtime-ignores', surface: - 'Six author-time rules, run by the runtime publish gate and by `os validate` / `lint` / `compile` / `build`: ' + '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); a `boolean` / `toggle` field marked `required` ' - + '(`field-boolean-required`); a `state_machine` validation with no `initialStates` ' - + '(`state-machine-no-initial-states`); a standalone action that declares `locations` but no `objectName` ' + + '(`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 `config.timeoutMs` on the http node; remove `required` from the ' - + 'checkbox and give it `defaultValue: false` (a validation rule says so when the box must be ticked); list the ' - + 'states a record may be created in under `initialStates`; set the action\'s `objectName`, or write `locations: []` ' + + '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 with no matching edge routes nowhere; an ' - + 'http call with no timeout waits as long as the connection stays open; a required checkbox makes the record form ' - + 'refuse to save the box unchecked, while `false` is never a missing value; 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 ' - + 'five errors is refused with the fix named, and the http timeout is reported as a warning.', + + '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.', acceptanceCriteria: - 'os validate reports none of the five errors (`flow-node-type-no-executor` is judged only at publish, against the ' + '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.', }; From 7c71a0de528557df74e7838783169e6edd9a14e6 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 20:07:33 +0000 Subject: [PATCH 11/15] docs: regenerate the protocol reference on the merged tree Claude-Session: https://claude.ai/code/session_01JQwxbXGvw43spR79ztEvWt Co-authored-by: Claude --- content/docs/references/api/protocol.mdx | 25 +++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/content/docs/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index 2d71a0a07b8..9c03edef2ae 100644 --- a/content/docs/references/api/protocol.mdx +++ b/content/docs/references/api/protocol.mdx @@ -1,7 +1,7 @@ --- title: Protocol schema — API Protocol reference navTitle: Protocol -description: "Protocol schemas of the ObjectStack API Protocol: AiAgentCapabilities and 147 more — each property with its type, default and a TypeScript example." +description: "Protocol schemas of the ObjectStack API Protocol: AiAgentCapabilities and 148 more — each property with its type, default and a TypeScript example." --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -13,8 +13,8 @@ description: "Protocol schemas of the ObjectStack API Protocol: AiAgentCapabilit ## TypeScript Usage ```typescript -import { AiAgentCapabilitiesSchema, AiAgentChatRequestSchema, AiAgentSummarySchema, AiAgentsResponseSchema, AiChatRequestSchema, AiChatResponseSchema, AiCompleteRequestSchema, AiConversationSchema, AiMessageSchema, AiModelsResponseSchema, AiPendingActionSchema, AiPendingActionStatusSchema, AiStreamChunkSchema, ApproveAiPendingActionResponseSchema, AuditMetaItemRequestSchema, AuditMetaItemResponseSchema, AutomationActionsResponseSchema, AutomationTriggerRequestSchema, AutomationTriggerResponseSchema, BatchDataRequestSchema, BatchDataResponseSchema, BuildProbeReportSchema, CheckPermissionRequestSchema, CheckPermissionResponseSchema, CloneDataResponseSchema, CreateAiConversationRequestSchema, CreateDataRequestSchema, CreateDataResponseSchema, CreateManyDataRequestSchema, CreateManyDataResponseSchema, DeleteDataRequestSchema, DeleteDataResponseSchema, DeleteManyDataRequestSchema, DeleteManyDataResponseSchema, DeleteMetaItemRequestSchema, DeleteMetaItemResponseSchema, DiffMetaItemRequestSchema, DiffMetaItemResponseSchema, DisablePackageRequestSchema, DisablePackageResponseSchema, EnablePackageRequestSchema, EnablePackageResponseSchema, FindDataRequestSchema, FindDataResponseSchema, FindReferencesToMetaResponseSchema, FlowRegistrationSchema, FlowRegistrationRefusalSchema, GetDataRequestSchema, GetDataResponseSchema, GetDiscoveryRequestSchema, GetDiscoveryResponseSchema, GetEffectivePermissionsRequestSchema, GetEffectivePermissionsResponseSchema, GetFieldLabelsRequestSchema, GetFieldLabelsResponseSchema, GetLocalesRequestSchema, GetLocalesResponseSchema, GetMetaDiagnosticsResponseSchema, GetMetaItemCachedRequestSchema, GetMetaItemCachedResponseSchema, GetMetaItemLayeredRequestSchema, GetMetaItemLayeredResponseSchema, GetMetaItemRequestSchema, GetMetaItemResponseSchema, GetMetaItemsRequestSchema, GetMetaItemsResponseSchema, GetMetaTypesRequestSchema, GetMetaTypesResponseSchema, GetNotificationPreferencesRequestSchema, GetNotificationPreferencesResponseSchema, GetObjectPermissionsRequestSchema, GetObjectPermissionsResponseSchema, GetPackageRequestSchema, GetPackageResponseSchema, GetPresenceRequestSchema, GetPresenceResponseSchema, GetPublishedMetaItemResponseSchema, GetRecordFieldAccessResponseSchema, GetTranslationsRequestSchema, GetTranslationsResponseSchema, GetUiViewRequestSchema, GetUiViewResponseSchema, HistoryMetaItemRequestSchema, HistoryMetaItemResponseSchema, HttpFindQueryParamsSchema, InstallPackageRequestSchema, InstallPackageResponseSchema, ListAiConversationsRequestSchema, ListAiConversationsResponseSchema, ListAiPendingActionsRequestSchema, ListAiPendingActionsResponseSchema, ListDraftsResponseSchema, ListNotificationsRequestSchema, ListNotificationsResponseSchema, ListPackagesRequestSchema, ListPackagesResponseSchema, MarkAllNotificationsReadRequestSchema, MarkAllNotificationsReadResponseSchema, MarkNotificationsReadRequestSchema, MarkNotificationsReadResponseSchema, MetadataAuthoringClientSchema, MetadataAuthoringSurfaceSchema, MetadataConflictErrorSchema, NotificationSchema, NotificationPreferencesSchema, PublicFormSubmitResponseSchema, PublishMetaItemRequestSchema, PublishMetaItemResponseSchema, PublishPackageDraftsRequestSchema, PublishPackageDraftsResponseSchema, RealtimeConnectRequestSchema, RealtimeConnectResponseSchema, RealtimeDisconnectRequestSchema, RealtimeDisconnectResponseSchema, RealtimeSubscribeRequestSchema, RealtimeSubscribeResponseSchema, RealtimeUnsubscribeRequestSchema, RealtimeUnsubscribeResponseSchema, RegisterDeviceRequestSchema, RegisterDeviceResponseSchema, RejectAiPendingActionResponseSchema, RollbackMetaItemRequestSchema, RollbackMetaItemResponseSchema, RuntimeAuthoringIssueSchema, RuntimeBuildIssueSchema, SaveMetaItemRequestSchema, SaveMetaItemResponseSchema, SearchAllHitSchema, SearchAllPageHitSchema, SearchAllResponseSchema, SeedAppliedIdListSchema, SeedAppliedLandedSchema, SetPresenceRequestSchema, SetPresenceResponseSchema, UninstallPackageRequestSchema, UninstallPackageResponseSchema, UnregisterDeviceRequestSchema, UnregisterDeviceResponseSchema, UpdateAiConversationRequestSchema, UpdateDataRequestSchema, UpdateDataResponseSchema, UpdateManyDataRequestSchema, UpdateManyDataResponseSchema, UpdateNotificationPreferencesRequestSchema, UpdateNotificationPreferencesResponseSchema, ValidateDataIssueSchema, ValidateDataRequestSchema, ValidateDataResponseSchema } from '@objectstack/spec/api'; -import type { AiAgentCapabilities, AiAgentChatRequest, AiAgentSummary, AiAgentsResponse, AiChatRequest, AiChatResponse, AiCompleteRequest, AiConversation, AiMessage, AiModelsResponse, AiPendingAction, AiPendingActionStatus, AiStreamChunk, ApproveAiPendingActionResponse, AuditMetaItemRequest, AuditMetaItemResponse, AutomationActionsResponse, AutomationTriggerRequest, AutomationTriggerResponse, BatchDataRequest, BatchDataResponse, BuildProbeReport, CheckPermissionRequest, CheckPermissionResponse, CloneDataResponse, CreateAiConversationRequest, CreateDataRequest, CreateDataResponse, CreateManyDataRequest, CreateManyDataResponse, DeleteDataRequest, DeleteDataResponse, DeleteManyDataRequest, DeleteManyDataResponse, DeleteMetaItemRequest, DeleteMetaItemResponse, DiffMetaItemRequest, DiffMetaItemResponse, DisablePackageRequest, DisablePackageResponse, EnablePackageRequest, EnablePackageResponse, FindDataRequest, FindDataResponse, FindReferencesToMetaResponse, FlowRegistration, FlowRegistrationRefusal, GetDataRequest, GetDataResponse, GetDiscoveryRequest, GetDiscoveryResponse, GetEffectivePermissionsRequest, GetEffectivePermissionsResponse, GetFieldLabelsRequest, GetFieldLabelsResponse, GetLocalesRequest, GetLocalesResponse, GetMetaDiagnosticsResponse, GetMetaItemCachedRequest, GetMetaItemCachedResponse, GetMetaItemLayeredRequest, GetMetaItemLayeredResponse, GetMetaItemRequest, GetMetaItemResponse, GetMetaItemsRequest, GetMetaItemsResponse, GetMetaTypesRequest, GetMetaTypesResponse, GetNotificationPreferencesRequest, GetNotificationPreferencesResponse, GetObjectPermissionsRequest, GetObjectPermissionsResponse, GetPackageRequest, GetPackageResponse, GetPresenceRequest, GetPresenceResponse, GetPublishedMetaItemResponse, GetRecordFieldAccessResponse, GetTranslationsRequest, GetTranslationsResponse, GetUiViewRequest, GetUiViewResponse, HistoryMetaItemRequest, HistoryMetaItemResponse, InstallPackageRequest, InstallPackageResponse, ListAiConversationsRequest, ListAiConversationsResponse, ListAiPendingActionsRequest, ListAiPendingActionsResponse, ListDraftsResponse, ListNotificationsRequest, ListNotificationsResponse, ListPackagesRequest, ListPackagesResponse, MarkAllNotificationsReadRequest, MarkAllNotificationsReadResponse, MarkNotificationsReadRequest, MarkNotificationsReadResponse, MetadataAuthoringClient, MetadataAuthoringSurface, MetadataConflictError, Notification, NotificationPreferences, PublicFormSubmitResponse, PublishMetaItemRequest, PublishMetaItemResponse, PublishPackageDraftsRequest, PublishPackageDraftsResponse, RealtimeConnectRequest, RealtimeConnectResponse, RealtimeDisconnectRequest, RealtimeDisconnectResponse, RealtimeSubscribeRequest, RealtimeSubscribeResponse, RealtimeUnsubscribeRequest, RealtimeUnsubscribeResponse, RegisterDeviceRequest, RegisterDeviceResponse, RejectAiPendingActionResponse, RollbackMetaItemRequest, RollbackMetaItemResponse, RuntimeAuthoringIssue, RuntimeBuildIssue, SaveMetaItemRequest, SaveMetaItemResponse, SearchAllHit, SearchAllPageHit, SearchAllResponse, SeedAppliedIdList, SeedAppliedLanded, SetPresenceRequest, SetPresenceResponse, UninstallPackageRequest, UninstallPackageResponse, UnregisterDeviceRequest, UnregisterDeviceResponse, UpdateAiConversationRequest, UpdateDataRequest, UpdateDataResponse, UpdateManyDataRequest, UpdateManyDataResponse, UpdateNotificationPreferencesRequest, UpdateNotificationPreferencesResponse, ValidateDataIssue, ValidateDataRequest, ValidateDataResponse } from '@objectstack/spec/api'; +import { AiAgentCapabilitiesSchema, AiAgentChatRequestSchema, AiAgentSummarySchema, AiAgentsResponseSchema, AiChatRequestSchema, AiChatResponseSchema, AiCompleteRequestSchema, AiConversationSchema, AiConversationMessageSchema, AiMessageSchema, AiModelsResponseSchema, AiPendingActionSchema, AiPendingActionStatusSchema, AiStreamChunkSchema, ApproveAiPendingActionResponseSchema, AuditMetaItemRequestSchema, AuditMetaItemResponseSchema, AutomationActionsResponseSchema, AutomationTriggerRequestSchema, AutomationTriggerResponseSchema, BatchDataRequestSchema, BatchDataResponseSchema, BuildProbeReportSchema, CheckPermissionRequestSchema, CheckPermissionResponseSchema, CloneDataResponseSchema, CreateAiConversationRequestSchema, CreateDataRequestSchema, CreateDataResponseSchema, CreateManyDataRequestSchema, CreateManyDataResponseSchema, DeleteDataRequestSchema, DeleteDataResponseSchema, DeleteManyDataRequestSchema, DeleteManyDataResponseSchema, DeleteMetaItemRequestSchema, DeleteMetaItemResponseSchema, DiffMetaItemRequestSchema, DiffMetaItemResponseSchema, DisablePackageRequestSchema, DisablePackageResponseSchema, EnablePackageRequestSchema, EnablePackageResponseSchema, FindDataRequestSchema, FindDataResponseSchema, FindReferencesToMetaResponseSchema, FlowRegistrationSchema, FlowRegistrationRefusalSchema, GetDataRequestSchema, GetDataResponseSchema, GetDiscoveryRequestSchema, GetDiscoveryResponseSchema, GetEffectivePermissionsRequestSchema, GetEffectivePermissionsResponseSchema, GetFieldLabelsRequestSchema, GetFieldLabelsResponseSchema, GetLocalesRequestSchema, GetLocalesResponseSchema, GetMetaDiagnosticsResponseSchema, GetMetaItemCachedRequestSchema, GetMetaItemCachedResponseSchema, GetMetaItemLayeredRequestSchema, GetMetaItemLayeredResponseSchema, GetMetaItemRequestSchema, GetMetaItemResponseSchema, GetMetaItemsRequestSchema, GetMetaItemsResponseSchema, GetMetaTypesRequestSchema, GetMetaTypesResponseSchema, GetNotificationPreferencesRequestSchema, GetNotificationPreferencesResponseSchema, GetObjectPermissionsRequestSchema, GetObjectPermissionsResponseSchema, GetPackageRequestSchema, GetPackageResponseSchema, GetPresenceRequestSchema, GetPresenceResponseSchema, GetPublishedMetaItemResponseSchema, GetRecordFieldAccessResponseSchema, GetTranslationsRequestSchema, GetTranslationsResponseSchema, GetUiViewRequestSchema, GetUiViewResponseSchema, HistoryMetaItemRequestSchema, HistoryMetaItemResponseSchema, HttpFindQueryParamsSchema, InstallPackageRequestSchema, InstallPackageResponseSchema, ListAiConversationsRequestSchema, ListAiConversationsResponseSchema, ListAiPendingActionsRequestSchema, ListAiPendingActionsResponseSchema, ListDraftsResponseSchema, ListNotificationsRequestSchema, ListNotificationsResponseSchema, ListPackagesRequestSchema, ListPackagesResponseSchema, MarkAllNotificationsReadRequestSchema, MarkAllNotificationsReadResponseSchema, MarkNotificationsReadRequestSchema, MarkNotificationsReadResponseSchema, MetadataAuthoringClientSchema, MetadataAuthoringSurfaceSchema, MetadataConflictErrorSchema, NotificationSchema, NotificationPreferencesSchema, PublicFormSubmitResponseSchema, PublishMetaItemRequestSchema, PublishMetaItemResponseSchema, PublishPackageDraftsRequestSchema, PublishPackageDraftsResponseSchema, RealtimeConnectRequestSchema, RealtimeConnectResponseSchema, RealtimeDisconnectRequestSchema, RealtimeDisconnectResponseSchema, RealtimeSubscribeRequestSchema, RealtimeSubscribeResponseSchema, RealtimeUnsubscribeRequestSchema, RealtimeUnsubscribeResponseSchema, RegisterDeviceRequestSchema, RegisterDeviceResponseSchema, RejectAiPendingActionResponseSchema, RollbackMetaItemRequestSchema, RollbackMetaItemResponseSchema, RuntimeAuthoringIssueSchema, RuntimeBuildIssueSchema, SaveMetaItemRequestSchema, SaveMetaItemResponseSchema, SearchAllHitSchema, SearchAllPageHitSchema, SearchAllResponseSchema, SeedAppliedIdListSchema, SeedAppliedLandedSchema, SetPresenceRequestSchema, SetPresenceResponseSchema, UninstallPackageRequestSchema, UninstallPackageResponseSchema, UnregisterDeviceRequestSchema, UnregisterDeviceResponseSchema, UpdateAiConversationRequestSchema, UpdateDataRequestSchema, UpdateDataResponseSchema, UpdateManyDataRequestSchema, UpdateManyDataResponseSchema, UpdateNotificationPreferencesRequestSchema, UpdateNotificationPreferencesResponseSchema, ValidateDataIssueSchema, ValidateDataRequestSchema, ValidateDataResponseSchema } from '@objectstack/spec/api'; +import type { AiAgentCapabilities, AiAgentChatRequest, AiAgentSummary, AiAgentsResponse, AiChatRequest, AiChatResponse, AiCompleteRequest, AiConversation, AiConversationMessage, AiMessage, AiModelsResponse, AiPendingAction, AiPendingActionStatus, AiStreamChunk, ApproveAiPendingActionResponse, AuditMetaItemRequest, AuditMetaItemResponse, AutomationActionsResponse, AutomationTriggerRequest, AutomationTriggerResponse, BatchDataRequest, BatchDataResponse, BuildProbeReport, CheckPermissionRequest, CheckPermissionResponse, CloneDataResponse, CreateAiConversationRequest, CreateDataRequest, CreateDataResponse, CreateManyDataRequest, CreateManyDataResponse, DeleteDataRequest, DeleteDataResponse, DeleteManyDataRequest, DeleteManyDataResponse, DeleteMetaItemRequest, DeleteMetaItemResponse, DiffMetaItemRequest, DiffMetaItemResponse, DisablePackageRequest, DisablePackageResponse, EnablePackageRequest, EnablePackageResponse, FindDataRequest, FindDataResponse, FindReferencesToMetaResponse, FlowRegistration, FlowRegistrationRefusal, GetDataRequest, GetDataResponse, GetDiscoveryRequest, GetDiscoveryResponse, GetEffectivePermissionsRequest, GetEffectivePermissionsResponse, GetFieldLabelsRequest, GetFieldLabelsResponse, GetLocalesRequest, GetLocalesResponse, GetMetaDiagnosticsResponse, GetMetaItemCachedRequest, GetMetaItemCachedResponse, GetMetaItemLayeredRequest, GetMetaItemLayeredResponse, GetMetaItemRequest, GetMetaItemResponse, GetMetaItemsRequest, GetMetaItemsResponse, GetMetaTypesRequest, GetMetaTypesResponse, GetNotificationPreferencesRequest, GetNotificationPreferencesResponse, GetObjectPermissionsRequest, GetObjectPermissionsResponse, GetPackageRequest, GetPackageResponse, GetPresenceRequest, GetPresenceResponse, GetPublishedMetaItemResponse, GetRecordFieldAccessResponse, GetTranslationsRequest, GetTranslationsResponse, GetUiViewRequest, GetUiViewResponse, HistoryMetaItemRequest, HistoryMetaItemResponse, InstallPackageRequest, InstallPackageResponse, ListAiConversationsRequest, ListAiConversationsResponse, ListAiPendingActionsRequest, ListAiPendingActionsResponse, ListDraftsResponse, ListNotificationsRequest, ListNotificationsResponse, ListPackagesRequest, ListPackagesResponse, MarkAllNotificationsReadRequest, MarkAllNotificationsReadResponse, MarkNotificationsReadRequest, MarkNotificationsReadResponse, MetadataAuthoringClient, MetadataAuthoringSurface, MetadataConflictError, Notification, NotificationPreferences, PublicFormSubmitResponse, PublishMetaItemRequest, PublishMetaItemResponse, PublishPackageDraftsRequest, PublishPackageDraftsResponse, RealtimeConnectRequest, RealtimeConnectResponse, RealtimeDisconnectRequest, RealtimeDisconnectResponse, RealtimeSubscribeRequest, RealtimeSubscribeResponse, RealtimeUnsubscribeRequest, RealtimeUnsubscribeResponse, RegisterDeviceRequest, RegisterDeviceResponse, RejectAiPendingActionResponse, RollbackMetaItemRequest, RollbackMetaItemResponse, RuntimeAuthoringIssue, RuntimeBuildIssue, SaveMetaItemRequest, SaveMetaItemResponse, SearchAllHit, SearchAllPageHit, SearchAllResponse, SeedAppliedIdList, SeedAppliedLanded, SetPresenceRequest, SetPresenceResponse, UninstallPackageRequest, UninstallPackageResponse, UnregisterDeviceRequest, UnregisterDeviceResponse, UpdateAiConversationRequest, UpdateDataRequest, UpdateDataResponse, UpdateManyDataRequest, UpdateManyDataResponse, UpdateNotificationPreferencesRequest, UpdateNotificationPreferencesResponse, ValidateDataIssue, ValidateDataRequest, ValidateDataResponse } from '@objectstack/spec/api'; // Validate data const result = AiAgentCapabilitiesSchema.parse(data); @@ -172,7 +172,7 @@ const result = AiAgentCapabilitiesSchema.parse(data); | **title** | `string` | optional | Title / summary | | **agentId** | `string` | optional | Agent this conversation is bound to | | **userId** | `string` | optional | Owning user | -| **messages** | `({ role: Enum<'system' \| 'user' \| 'assistant' \| 'tool'>; content?: any; parts?: any[] } & Record)[]` | ✅ | Message history | +| **messages** | `({ role: Enum<'system' \| 'user' \| 'assistant' \| 'tool'>; content?: any; parts?: any[]; turnId?: string \| null } & Record)[]` | ✅ | Message history | | **createdAt** | `string` | ✅ | Creation timestamp (ISO 8601) | | **updatedAt** | `string` | ✅ | Last update timestamp (ISO 8601) | | **metadata** | `Record` | optional | Conversation metadata | @@ -184,6 +184,21 @@ const result = AiAgentCapabilitiesSchema.parse(data); | **role** | `Enum<'system' \| 'user' \| 'assistant' \| 'tool'>` | ✅ | Message role | | **content** | `any` | optional | Message content: a string, or an array of content parts | | **parts** | `any[]` | optional | Vercel AI SDK v6 message parts (alternative to `content`) | +| **turnId** | `string \| null` | optional | The turn the server stamped on the message: the `turnId` of the chat request that wrote it. Absent or null on a message stored with no turn | + + +--- + +## AiConversationMessage + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **role** | `Enum<'system' \| 'user' \| 'assistant' \| 'tool'>` | ✅ | Message role | +| **content** | `any` | optional | Message content: a string, or an array of content parts | +| **parts** | `any[]` | optional | Vercel AI SDK v6 message parts (alternative to `content`) | +| **turnId** | `string \| null` | optional | The turn the server stamped on the message: the `turnId` of the chat request that wrote it. Absent or null on a message stored with no turn | --- @@ -2277,7 +2292,7 @@ Install package response | **title** | `string` | optional | Title / summary | | **agentId** | `string` | optional | Agent this conversation is bound to | | **userId** | `string` | optional | Owning user | -| **messages** | `({ role: Enum<'system' \| 'user' \| 'assistant' \| 'tool'>; content?: any; parts?: any[] } & Record)[]` | ✅ | Message history | +| **messages** | `({ role: Enum<'system' \| 'user' \| 'assistant' \| 'tool'>; content?: any; parts?: any[]; turnId?: string \| null } & Record)[]` | ✅ | Message history | | **createdAt** | `string` | ✅ | Creation timestamp (ISO 8601) | | **updatedAt** | `string` | ✅ | Last update timestamp (ISO 8601) | | **metadata** | `Record` | optional | Conversation metadata | From 3cce87cb70c077f160c849550e12503e630822da Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 21:15:36 +0000 Subject: [PATCH 12/15] test(cli): give the conversion-door fixture's http node a node-level timeout The fixture's `http` node set no timeout, so `flow-http-timeout-missing` warned on it and `os validate --strict` turned that warning into exit 1 on the control spelling. The test is about conversion notices, not timeouts: the node now declares `timeoutMs: 10000`, which the rule honours. Claude-Session: https://claude.ai/code/session_01JQwxbXGvw43spR79ztEvWt Co-authored-by: Claude --- packages/cli/test/stack-conversion-record-door.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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' }], From e275c3efac5e95b128dbd2e895c7b24413658e9f Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 21:21:32 +0000 Subject: [PATCH 13/15] =?UTF-8?q?chore(changeset):=20the=20Clause-?= =?UTF-8?q?=E2=91=A1=20line=20counts=20four=20refusals?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Claude-Session: https://claude.ai/code/session_01JQwxbXGvw43spR79ztEvWt Co-authored-by: Claude --- .changeset/34776-publish-checks-build-probes.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/34776-publish-checks-build-probes.md b/.changeset/34776-publish-checks-build-probes.md index 8472e1111fa..383c6693253 100644 --- a/.changeset/34776-publish-checks-build-probes.md +++ b/.changeset/34776-publish-checks-build-probes.md @@ -7,7 +7,7 @@ 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: six publish-time refusals of metadata the schema accepts today) +Clause-②: no (narrowing: four publish-time refusals of metadata the schema accepts today) Metadata-protocol: narrowed Skills-docs: follow-up #35245 From 370c46b5ad01a890b6b064da2def8e1a90c08a7b Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 22:04:12 +0000 Subject: [PATCH 14/15] fix: scope the probes' seed-row and child-sample reads; name the roll-up repair per function - The seed reference probe reads the rows the loader reports it landed (`seedApplied.landed`, passed in as `seedLanded`) by id, instead of matching the seed's key across the object: created rows always, matched rows only when the seed's mode wrote them. - The roll-up probe samples children one organization at a time, under the same context and tenant column as the parent read, and forms each verdict and count inside that organization. - `rollup_never_computed` names `--recompute-undefined-on-empty object.field` for a min, max or avg roll-up, which the plain run does not fill, in its fix and in all eleven user sentences. - Nits: `--strict` exits 1 on the timeout warning (changeset, ledger); the changeset's organization sentence matches the code; the seed message drops "nothing else will say so"; a non-positive `timeoutMs` is named as written. Claude-Session: https://claude.ai/code/session_01JQwxbXGvw43spR79ztEvWt Co-authored-by: Claude --- .../34776-publish-checks-build-probes.md | 6 +- packages/lint/src/lint-flow-patterns.test.ts | 6 + packages/lint/src/lint-flow-patterns.ts | 5 +- .../src/build-probes-landed-data.test.ts | 121 ++++++++++-- .../src/build-probes-user-message.test.ts | 3 +- .../metadata-protocol/src/build-probes.ts | 178 ++++++++++++------ .../src/build-probes.user-text.ts | 73 ++++--- packages/metadata-protocol/src/index.ts | 2 + .../src/protocol-history-and-publish.ts | 3 + ...sh-refuses-metadata-the-runtime-ignores.ts | 3 +- 10 files changed, 297 insertions(+), 103 deletions(-) diff --git a/.changeset/34776-publish-checks-build-probes.md b/.changeset/34776-publish-checks-build-probes.md index 383c6693253..2d2191334b1 100644 --- a/.changeset/34776-publish-checks-build-probes.md +++ b/.changeset/34776-publish-checks-build-probes.md @@ -17,12 +17,12 @@ Five authoring rules join the registry the runtime publish gate and `objectstack - `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. +- `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 landed sample record whose reference names no row in the publishing organization, so its page shows a reference to nothing) 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` and `packageId`; the publish passes the automation engine's connector lookups and the publishing package. +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` type; `@objectstack/service-automation` adds `AutomationEngine.getSealedNodeTypeVocabulary()`. `@objectstack/spec` changes only descriptions: those of `RuntimeBuildIssueSchema`, and that of a state machine validation's `initialStates`. +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/packages/lint/src/lint-flow-patterns.test.ts b/packages/lint/src/lint-flow-patterns.test.ts index 130c3e65a9f..f90504fc0a2 100644 --- a/packages/lint/src/lint-flow-patterns.test.ts +++ b/packages/lint/src/lint-flow-patterns.test.ts @@ -4226,6 +4226,12 @@ describe('flow-http-timeout-missing — an http node without a timeout of its ow 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 ae8fe661f23..6f3919da016 100644 --- a/packages/lint/src/lint-flow-patterns.ts +++ b/packages/lint/src/lint-flow-patterns.ts @@ -1900,7 +1900,10 @@ function scanHttpTimeouts(at: string, nodes: AnyRec[], findings: FlowLintFinding 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'; - const what = cfg.timeoutMs === 0 ? 'sets `config.timeoutMs: 0`, which arms no timer' : 'sets no `config.timeoutMs`'; + // 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)`, diff --git a/packages/metadata-protocol/src/build-probes-landed-data.test.ts b/packages/metadata-protocol/src/build-probes-landed-data.test.ts index f0e207cceb4..dabae6244d4 100644 --- a/packages/metadata-protocol/src/build-probes-landed-data.test.ts +++ b/packages/metadata-protocol/src/build-probes-landed-data.test.ts @@ -73,7 +73,7 @@ const ITEMS: Record = { }, }, 'seed deal_seed': { object: 'deal', records: [{ name: 'D1' }, { name: 'D2' }] }, - 'seed deal_seed_composite': { object: 'deal', externalId: ['acct_ref', 'name'], records: [{ name: 'D1' }] }, + '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'] }], @@ -94,6 +94,10 @@ const run = (opts: Partial & Pick>) => 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' }] }); @@ -166,6 +170,7 @@ describe('seed_reference_unresolved: a landed reference naming no row', () => { acct: [{ id: 'a1' }], sys_user: [{ id: 'u1' }], }), + seedLanded: landedOn('deal', ['d1', 'd2']), published, }); expect(codes(report)).toEqual([ @@ -184,26 +189,38 @@ describe('seed_reference_unresolved: a landed reference naming no row', () => { acct: [{ id: 'a1' }], sys_user: [{ id: 'u1' }], }), + seedLanded: landedOn('deal', ['d1', 'd2']), published, }); expect(report.issues).toEqual([]); }); - it('a row the seed did not write is not judged as the seed\'s', async () => { + 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: 'Typed by a person', acct_ref: 'a_gone' }], + 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 seed whose key is composite identifies no row by itself, and is not judged', async () => { + 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: [{ type: 'seed', name: 'deal_seed_composite' }], + published, }); expect(report.issues).toEqual([]); }); @@ -216,6 +233,7 @@ describe('seed_reference_unresolved: a landed reference naming no row', () => { throw new Error('no such table'); }, }, + seedLanded: landedOn('deal', ['d1']), published, }); expect(report.issues).toEqual([]); @@ -277,28 +295,45 @@ describe('the landed-data reads are scoped like the engine\'s reference audit, a }; return { engine, reads }; }; - const seedRowsRead = (r: Read) => r.object === 'deal' && r.where?.name !== undefined; + 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', published: [{ type: 'seed', name: 'deal_seed' }] }); + 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 its key, projected to what is judged. (The - // first `deal` read is `seed_not_applied`'s row count.) + // 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: { name: { $in: ['D1', 'D2'] } }, + 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: [ @@ -308,7 +343,7 @@ describe('the landed-data reads are scoped like the engine\'s reference audit, a acct: [{ id: 'a1', organization_id: 'o1' }], sys_user: [{ id: 'u1' }], }); - const report = await run({ engine, published: [{ type: 'seed', name: 'deal_seed' }] }); + 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']]); @@ -317,7 +352,6 @@ describe('the landed-data reads are scoped like the engine\'s reference audit, a { isSystem: true, tenantId: 'o1' }, { isSystem: true, tenantId: 'o2' }, ]); - expect(reads.find(seedRowsRead)!.context).toEqual({ isSystem: true }); expect(reads.find(seedRowsRead)!.fields).toEqual(['id', 'acct_ref', 'owner', 'organization_id']); }); @@ -333,9 +367,66 @@ describe('the landed-data reads are scoped like the engine\'s reference audit, a [{ 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)).toEqual([ - ['id', 'acct_ref'], - ['id', 'acct_ref', 'amount'], + 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 c60b4aaaff9..e7a5b165b3c 100644 --- a/packages/metadata-protocol/src/build-probes-user-message.test.ts +++ b/packages/metadata-protocol/src/build-probes-user-message.test.ts @@ -432,7 +432,7 @@ const CASES: readonly ProbeCase[] = [ }), published: [{ type: 'object', name: 'crm_acct' }], }), - params: (tag) => ({ object: ACCOUNTS, field: said(OPEN_DEALS, tag, 'open_deal_count'), child: DEALS }), + params: (tag) => ({ object: ACCOUNTS, field: said(OPEN_DEALS, tag, 'open_deal_count'), child: DEALS, cause: 'fills' }), hidden: ['crm_acct', 'open_deal_count', 'crm_deal'], }, { @@ -440,6 +440,7 @@ const CASES: readonly ProbeCase[] = [ 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' }), diff --git a/packages/metadata-protocol/src/build-probes.ts b/packages/metadata-protocol/src/build-probes.ts index 5b9659af01b..266521d3718 100644 --- a/packages/metadata-protocol/src/build-probes.ts +++ b/packages/metadata-protocol/src/build-probes.ts @@ -153,6 +153,21 @@ export interface RunBuildProbesOptions { * 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[] }; } /** @@ -317,6 +332,27 @@ function rowOrganization(row: Rec, column: string | null, publishing: string | n 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); @@ -666,12 +702,18 @@ export async function runBuildProbes(opts: RunBuildProbesOptions): Promise !!r); - const named = new Map(); - for (const c of children) { - if (childField && (c[childField] === null || c[childField] === undefined)) continue; - for (const id of idsIn(c[fk])) pushTo(named, rowOrganization(c, orgColumn, organizationId ?? null), id); - } - if (named.size === 0) continue; - const parents: Rec[] = []; - for (const [organization, list] of named) { - const ids = [...new Set(list)]; - parents.push(...asArr(await engine.find(p.name, { + const organizations = await probeOrganizations(engine, childObject, organizationId ?? null); + let blank: Rec[] | undefined; + for (const organization of organizations) { + const children = asArr(await engine.find(childObject, { + fields: [...new Set(['id', fk, ...(childField ? [childField] : [])])], + limit: PROBE_SAMPLE_ROWS, + context: landedReadContext(organization), + })).map(asRec).filter((r): r is Rec => !!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)); + })).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 (parents.length === 0 || parents.some((r) => r[fieldName] !== null && r[fieldName] !== undefined)) continue; + 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', @@ -715,19 +763,22 @@ export async function runBuildProbes(opts: RunBuildProbesOptions): Promise [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 externalId = seed?.externalId === undefined ? 'name' : seed.externalId; - if (typeof externalId !== 'string' || !externalId) continue; - const keys = [...new Set(asArr(seed?.records).map(asRec).flatMap((r): Array => { - const v = r?.[externalId]; - return (typeof v === 'string' && v !== '') || typeof v === 'number' ? [v] : []; - }))].slice(0, PROBE_SAMPLE_ROWS); - if (keys.length === 0) 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; @@ -791,10 +847,10 @@ export async function runBuildProbes(opts: RunBuildProbesOptions): Promise f.name), ...(orgColumn ? [orgColumn] : [])])], - limit: PROBE_SAMPLE_ROWS, - context: SYSTEM_READ, + limit: ids.length, + context: landedReadContext(organizationId ?? null), })).map(asRec).filter((r): r is Rec => !!r); } catch { continue; @@ -823,8 +879,8 @@ export async function runBuildProbes(opts: RunBuildProbesOptions): Promise `"${v}"`).join(', '); issues.push({ layer: 'runtime', @@ -833,9 +889,9 @@ export async function runBuildProbes(opts: RunBuildProbesOptions): Promise 5 ? ', …' : ''}. The rows landed as a ` + - 'system write, which is not checked for references, so they point at nothing and nothing else will say so.', + `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.', diff --git a/packages/metadata-protocol/src/build-probes.user-text.ts b/packages/metadata-protocol/src/build-probes.user-text.ts index a13de740cad..e095b09719e 100644 --- a/packages/metadata-protocol/src/build-probes.user-text.ts +++ b/packages/metadata-protocol/src/build-probes.user-text.ts @@ -48,7 +48,7 @@ * | `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` | the parent object, the roll-up field and the child object 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) | * @@ -885,49 +885,80 @@ const WIDGET_EMPTY_RESULT: UserTextEntry = { `예상과 다르다면 읽어 오는 레코드(날짜와 값)를 확인한 후 다시 게시하세요.`, }; -/** `rollup_never_computed`: a roll-up field reads blank on every record that has related records. */ +/** `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. Ask whoever runs this environment to recalculate ` + - `the roll-ups (\`os migrate summary-nulls --apply\`).`, + `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}”记录的记录上都是空的:它的存储值从未为这些记录计算过。` + - `请让负责此环境的人重新计算汇总字段(\`os migrate summary-nulls --apply\`)。`, + (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}」記錄的記錄上都是空的:它的儲存值從未為這些記錄計算過。` + - `請讓負責此環境的人重新計算匯總欄位(\`os migrate summary-nulls --apply\`)。`, + (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. Pida a quien administra este ` + - `entorno que recalcule los resúmenes (\`os migrate summary-nulls --apply\`).`, + `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}" مرتبطة: لم تُحسب قيمته المخزنة لها قط. ` + - `اطلب من مسؤول هذه البيئة إعادة حساب حقول التجميع (\`os migrate summary-nulls --apply\`).`, + (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. Demandez à la ` + - `personne qui gère cet environnement de recalculer les synthèses (\`os migrate summary-nulls --apply\`).`, + `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. Peça a quem administra este ` + - `ambiente que recalcule os resumos (\`os migrate summary-nulls --apply\`).`, + `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}»: его сохранённое значение для них ни разу не рассчитывалось. Попросите администратора этой среды ` + - `пересчитать сводные поля (\`os migrate summary-nulls --apply\`).`, + `«${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. Bitten Sie die Person, die diese Umgebung betreibt, ` + - `die Rollups neu zu berechnen (\`os migrate summary-nulls --apply\`).`, + `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}」レコードを持つすべてのレコードで空です。` + - `保存値がこれらのレコードについて一度も計算されていません。この環境の管理者に集計の再計算` + - `(\`os migrate summary-nulls --apply\`)を依頼してください。`, + `保存値がこれらのレコードについて一度も計算されていません。` + + (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}" 레코드가 있는 모든 레코드에서 비어 있습니다. ` + - `저장된 값이 이 레코드들에 대해 한 번도 계산되지 않았습니다. 이 환경의 관리자에게 롤업 재계산` + - `(\`os migrate summary-nulls --apply\`)을 요청하세요.`, + `저장된 값이 이 레코드들에 대해 한 번도 계산되지 않았습니다. ` + + (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. */ diff --git a/packages/metadata-protocol/src/index.ts b/packages/metadata-protocol/src/index.ts index 2b102ceb6a5..6f8b7689cc7 100644 --- a/packages/metadata-protocol/src/index.ts +++ b/packages/metadata-protocol/src/index.ts @@ -395,4 +395,6 @@ export type { ProbeEngine, ProbeAnalytics, ProbeItemProtocol, + ProbeAutomation, + SeedLandedRows, } from './build-probes.js'; diff --git a/packages/metadata-protocol/src/protocol-history-and-publish.ts b/packages/metadata-protocol/src/protocol-history-and-publish.ts index 424d9308848..925ab97c77c 100644 --- a/packages/metadata-protocol/src/protocol-history-and-publish.ts +++ b/packages/metadata-protocol/src/protocol-history-and-publish.ts @@ -2684,6 +2684,9 @@ export class ProtocolHistoryAndPublishFacet { // 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/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 index 643195c1dff..8a16ecf683c 100644 --- 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 @@ -28,7 +28,8 @@ export const entry: SemanticMigration = { + '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.', + + '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 ' From 812290548fa1dce15dc56312877a132ea6fdb278 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 22:44:06 +0000 Subject: [PATCH 15/15] docs: regenerate the protocol reference on the merged tree Claude-Session: https://claude.ai/code/session_01JQwxbXGvw43spR79ztEvWt Co-authored-by: Claude --- content/docs/references/api/protocol.mdx | 45 ++++++++++++++++++++++-- 1 file changed, 42 insertions(+), 3 deletions(-) diff --git a/content/docs/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index 9c03edef2ae..f24938a4721 100644 --- a/content/docs/references/api/protocol.mdx +++ b/content/docs/references/api/protocol.mdx @@ -1,7 +1,7 @@ --- title: Protocol schema — API Protocol reference navTitle: Protocol -description: "Protocol schemas of the ObjectStack API Protocol: AiAgentCapabilities and 148 more — each property with its type, default and a TypeScript example." +description: "Protocol schemas of the ObjectStack API Protocol: AiAgentCapabilities and 150 more — each property with its type, default and a TypeScript example." --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -13,8 +13,8 @@ description: "Protocol schemas of the ObjectStack API Protocol: AiAgentCapabilit ## TypeScript Usage ```typescript -import { AiAgentCapabilitiesSchema, AiAgentChatRequestSchema, AiAgentSummarySchema, AiAgentsResponseSchema, AiChatRequestSchema, AiChatResponseSchema, AiCompleteRequestSchema, AiConversationSchema, AiConversationMessageSchema, AiMessageSchema, AiModelsResponseSchema, AiPendingActionSchema, AiPendingActionStatusSchema, AiStreamChunkSchema, ApproveAiPendingActionResponseSchema, AuditMetaItemRequestSchema, AuditMetaItemResponseSchema, AutomationActionsResponseSchema, AutomationTriggerRequestSchema, AutomationTriggerResponseSchema, BatchDataRequestSchema, BatchDataResponseSchema, BuildProbeReportSchema, CheckPermissionRequestSchema, CheckPermissionResponseSchema, CloneDataResponseSchema, CreateAiConversationRequestSchema, CreateDataRequestSchema, CreateDataResponseSchema, CreateManyDataRequestSchema, CreateManyDataResponseSchema, DeleteDataRequestSchema, DeleteDataResponseSchema, DeleteManyDataRequestSchema, DeleteManyDataResponseSchema, DeleteMetaItemRequestSchema, DeleteMetaItemResponseSchema, DiffMetaItemRequestSchema, DiffMetaItemResponseSchema, DisablePackageRequestSchema, DisablePackageResponseSchema, EnablePackageRequestSchema, EnablePackageResponseSchema, FindDataRequestSchema, FindDataResponseSchema, FindReferencesToMetaResponseSchema, FlowRegistrationSchema, FlowRegistrationRefusalSchema, GetDataRequestSchema, GetDataResponseSchema, GetDiscoveryRequestSchema, GetDiscoveryResponseSchema, GetEffectivePermissionsRequestSchema, GetEffectivePermissionsResponseSchema, GetFieldLabelsRequestSchema, GetFieldLabelsResponseSchema, GetLocalesRequestSchema, GetLocalesResponseSchema, GetMetaDiagnosticsResponseSchema, GetMetaItemCachedRequestSchema, GetMetaItemCachedResponseSchema, GetMetaItemLayeredRequestSchema, GetMetaItemLayeredResponseSchema, GetMetaItemRequestSchema, GetMetaItemResponseSchema, GetMetaItemsRequestSchema, GetMetaItemsResponseSchema, GetMetaTypesRequestSchema, GetMetaTypesResponseSchema, GetNotificationPreferencesRequestSchema, GetNotificationPreferencesResponseSchema, GetObjectPermissionsRequestSchema, GetObjectPermissionsResponseSchema, GetPackageRequestSchema, GetPackageResponseSchema, GetPresenceRequestSchema, GetPresenceResponseSchema, GetPublishedMetaItemResponseSchema, GetRecordFieldAccessResponseSchema, GetTranslationsRequestSchema, GetTranslationsResponseSchema, GetUiViewRequestSchema, GetUiViewResponseSchema, HistoryMetaItemRequestSchema, HistoryMetaItemResponseSchema, HttpFindQueryParamsSchema, InstallPackageRequestSchema, InstallPackageResponseSchema, ListAiConversationsRequestSchema, ListAiConversationsResponseSchema, ListAiPendingActionsRequestSchema, ListAiPendingActionsResponseSchema, ListDraftsResponseSchema, ListNotificationsRequestSchema, ListNotificationsResponseSchema, ListPackagesRequestSchema, ListPackagesResponseSchema, MarkAllNotificationsReadRequestSchema, MarkAllNotificationsReadResponseSchema, MarkNotificationsReadRequestSchema, MarkNotificationsReadResponseSchema, MetadataAuthoringClientSchema, MetadataAuthoringSurfaceSchema, MetadataConflictErrorSchema, NotificationSchema, NotificationPreferencesSchema, PublicFormSubmitResponseSchema, PublishMetaItemRequestSchema, PublishMetaItemResponseSchema, PublishPackageDraftsRequestSchema, PublishPackageDraftsResponseSchema, RealtimeConnectRequestSchema, RealtimeConnectResponseSchema, RealtimeDisconnectRequestSchema, RealtimeDisconnectResponseSchema, RealtimeSubscribeRequestSchema, RealtimeSubscribeResponseSchema, RealtimeUnsubscribeRequestSchema, RealtimeUnsubscribeResponseSchema, RegisterDeviceRequestSchema, RegisterDeviceResponseSchema, RejectAiPendingActionResponseSchema, RollbackMetaItemRequestSchema, RollbackMetaItemResponseSchema, RuntimeAuthoringIssueSchema, RuntimeBuildIssueSchema, SaveMetaItemRequestSchema, SaveMetaItemResponseSchema, SearchAllHitSchema, SearchAllPageHitSchema, SearchAllResponseSchema, SeedAppliedIdListSchema, SeedAppliedLandedSchema, SetPresenceRequestSchema, SetPresenceResponseSchema, UninstallPackageRequestSchema, UninstallPackageResponseSchema, UnregisterDeviceRequestSchema, UnregisterDeviceResponseSchema, UpdateAiConversationRequestSchema, UpdateDataRequestSchema, UpdateDataResponseSchema, UpdateManyDataRequestSchema, UpdateManyDataResponseSchema, UpdateNotificationPreferencesRequestSchema, UpdateNotificationPreferencesResponseSchema, ValidateDataIssueSchema, ValidateDataRequestSchema, ValidateDataResponseSchema } from '@objectstack/spec/api'; -import type { AiAgentCapabilities, AiAgentChatRequest, AiAgentSummary, AiAgentsResponse, AiChatRequest, AiChatResponse, AiCompleteRequest, AiConversation, AiConversationMessage, AiMessage, AiModelsResponse, AiPendingAction, AiPendingActionStatus, AiStreamChunk, ApproveAiPendingActionResponse, AuditMetaItemRequest, AuditMetaItemResponse, AutomationActionsResponse, AutomationTriggerRequest, AutomationTriggerResponse, BatchDataRequest, BatchDataResponse, BuildProbeReport, CheckPermissionRequest, CheckPermissionResponse, CloneDataResponse, CreateAiConversationRequest, CreateDataRequest, CreateDataResponse, CreateManyDataRequest, CreateManyDataResponse, DeleteDataRequest, DeleteDataResponse, DeleteManyDataRequest, DeleteManyDataResponse, DeleteMetaItemRequest, DeleteMetaItemResponse, DiffMetaItemRequest, DiffMetaItemResponse, DisablePackageRequest, DisablePackageResponse, EnablePackageRequest, EnablePackageResponse, FindDataRequest, FindDataResponse, FindReferencesToMetaResponse, FlowRegistration, FlowRegistrationRefusal, GetDataRequest, GetDataResponse, GetDiscoveryRequest, GetDiscoveryResponse, GetEffectivePermissionsRequest, GetEffectivePermissionsResponse, GetFieldLabelsRequest, GetFieldLabelsResponse, GetLocalesRequest, GetLocalesResponse, GetMetaDiagnosticsResponse, GetMetaItemCachedRequest, GetMetaItemCachedResponse, GetMetaItemLayeredRequest, GetMetaItemLayeredResponse, GetMetaItemRequest, GetMetaItemResponse, GetMetaItemsRequest, GetMetaItemsResponse, GetMetaTypesRequest, GetMetaTypesResponse, GetNotificationPreferencesRequest, GetNotificationPreferencesResponse, GetObjectPermissionsRequest, GetObjectPermissionsResponse, GetPackageRequest, GetPackageResponse, GetPresenceRequest, GetPresenceResponse, GetPublishedMetaItemResponse, GetRecordFieldAccessResponse, GetTranslationsRequest, GetTranslationsResponse, GetUiViewRequest, GetUiViewResponse, HistoryMetaItemRequest, HistoryMetaItemResponse, InstallPackageRequest, InstallPackageResponse, ListAiConversationsRequest, ListAiConversationsResponse, ListAiPendingActionsRequest, ListAiPendingActionsResponse, ListDraftsResponse, ListNotificationsRequest, ListNotificationsResponse, ListPackagesRequest, ListPackagesResponse, MarkAllNotificationsReadRequest, MarkAllNotificationsReadResponse, MarkNotificationsReadRequest, MarkNotificationsReadResponse, MetadataAuthoringClient, MetadataAuthoringSurface, MetadataConflictError, Notification, NotificationPreferences, PublicFormSubmitResponse, PublishMetaItemRequest, PublishMetaItemResponse, PublishPackageDraftsRequest, PublishPackageDraftsResponse, RealtimeConnectRequest, RealtimeConnectResponse, RealtimeDisconnectRequest, RealtimeDisconnectResponse, RealtimeSubscribeRequest, RealtimeSubscribeResponse, RealtimeUnsubscribeRequest, RealtimeUnsubscribeResponse, RegisterDeviceRequest, RegisterDeviceResponse, RejectAiPendingActionResponse, RollbackMetaItemRequest, RollbackMetaItemResponse, RuntimeAuthoringIssue, RuntimeBuildIssue, SaveMetaItemRequest, SaveMetaItemResponse, SearchAllHit, SearchAllPageHit, SearchAllResponse, SeedAppliedIdList, SeedAppliedLanded, SetPresenceRequest, SetPresenceResponse, UninstallPackageRequest, UninstallPackageResponse, UnregisterDeviceRequest, UnregisterDeviceResponse, UpdateAiConversationRequest, UpdateDataRequest, UpdateDataResponse, UpdateManyDataRequest, UpdateManyDataResponse, UpdateNotificationPreferencesRequest, UpdateNotificationPreferencesResponse, ValidateDataIssue, ValidateDataRequest, ValidateDataResponse } from '@objectstack/spec/api'; +import { AiAgentCapabilitiesSchema, AiAgentChatRequestSchema, AiAgentSummarySchema, AiAgentsResponseSchema, AiChatRequestSchema, AiChatResponseSchema, AiCompleteRequestSchema, AiConversationSchema, AiConversationMessageSchema, AiMessageSchema, AiModelsResponseSchema, AiPendingActionSchema, AiPendingActionStatusSchema, AiStreamChunkSchema, ApproveAiPendingActionResponseSchema, AuditMetaItemRequestSchema, AuditMetaItemResponseSchema, AutomationActionsResponseSchema, AutomationTriggerRequestSchema, AutomationTriggerResponseSchema, BatchDataRequestSchema, BatchDataResponseSchema, BuildProbeReportSchema, CheckPermissionRequestSchema, CheckPermissionResponseSchema, CloneDataResponseSchema, CreateAiConversationRequestSchema, CreateDataRequestSchema, CreateDataResponseSchema, CreateManyDataRequestSchema, CreateManyDataResponseSchema, DeleteDataRequestSchema, DeleteDataResponseSchema, DeleteManyDataRequestSchema, DeleteManyDataResponseSchema, DeleteMetaItemRequestSchema, DeleteMetaItemResponseSchema, DestructiveChangeIssueSchema, DiffMetaItemRequestSchema, DiffMetaItemResponseSchema, DisablePackageRequestSchema, DisablePackageResponseSchema, EnablePackageRequestSchema, EnablePackageResponseSchema, FieldStillShownBySchema, FindDataRequestSchema, FindDataResponseSchema, FindReferencesToMetaResponseSchema, FlowRegistrationSchema, FlowRegistrationRefusalSchema, GetDataRequestSchema, GetDataResponseSchema, GetDiscoveryRequestSchema, GetDiscoveryResponseSchema, GetEffectivePermissionsRequestSchema, GetEffectivePermissionsResponseSchema, GetFieldLabelsRequestSchema, GetFieldLabelsResponseSchema, GetLocalesRequestSchema, GetLocalesResponseSchema, GetMetaDiagnosticsResponseSchema, GetMetaItemCachedRequestSchema, GetMetaItemCachedResponseSchema, GetMetaItemLayeredRequestSchema, GetMetaItemLayeredResponseSchema, GetMetaItemRequestSchema, GetMetaItemResponseSchema, GetMetaItemsRequestSchema, GetMetaItemsResponseSchema, GetMetaTypesRequestSchema, GetMetaTypesResponseSchema, GetNotificationPreferencesRequestSchema, GetNotificationPreferencesResponseSchema, GetObjectPermissionsRequestSchema, GetObjectPermissionsResponseSchema, GetPackageRequestSchema, GetPackageResponseSchema, GetPresenceRequestSchema, GetPresenceResponseSchema, GetPublishedMetaItemResponseSchema, GetRecordFieldAccessResponseSchema, GetTranslationsRequestSchema, GetTranslationsResponseSchema, GetUiViewRequestSchema, GetUiViewResponseSchema, HistoryMetaItemRequestSchema, HistoryMetaItemResponseSchema, HttpFindQueryParamsSchema, InstallPackageRequestSchema, InstallPackageResponseSchema, ListAiConversationsRequestSchema, ListAiConversationsResponseSchema, ListAiPendingActionsRequestSchema, ListAiPendingActionsResponseSchema, ListDraftsResponseSchema, ListNotificationsRequestSchema, ListNotificationsResponseSchema, ListPackagesRequestSchema, ListPackagesResponseSchema, MarkAllNotificationsReadRequestSchema, MarkAllNotificationsReadResponseSchema, MarkNotificationsReadRequestSchema, MarkNotificationsReadResponseSchema, MetadataAuthoringClientSchema, MetadataAuthoringSurfaceSchema, MetadataConflictErrorSchema, NotificationSchema, NotificationPreferencesSchema, PublicFormSubmitResponseSchema, PublishMetaItemRequestSchema, PublishMetaItemResponseSchema, PublishPackageDraftsRequestSchema, PublishPackageDraftsResponseSchema, RealtimeConnectRequestSchema, RealtimeConnectResponseSchema, RealtimeDisconnectRequestSchema, RealtimeDisconnectResponseSchema, RealtimeSubscribeRequestSchema, RealtimeSubscribeResponseSchema, RealtimeUnsubscribeRequestSchema, RealtimeUnsubscribeResponseSchema, RegisterDeviceRequestSchema, RegisterDeviceResponseSchema, RejectAiPendingActionResponseSchema, RollbackMetaItemRequestSchema, RollbackMetaItemResponseSchema, RuntimeAuthoringIssueSchema, RuntimeBuildIssueSchema, SaveMetaItemRequestSchema, SaveMetaItemResponseSchema, SearchAllHitSchema, SearchAllPageHitSchema, SearchAllResponseSchema, SeedAppliedIdListSchema, SeedAppliedLandedSchema, SetPresenceRequestSchema, SetPresenceResponseSchema, UninstallPackageRequestSchema, UninstallPackageResponseSchema, UnregisterDeviceRequestSchema, UnregisterDeviceResponseSchema, UpdateAiConversationRequestSchema, UpdateDataRequestSchema, UpdateDataResponseSchema, UpdateManyDataRequestSchema, UpdateManyDataResponseSchema, UpdateNotificationPreferencesRequestSchema, UpdateNotificationPreferencesResponseSchema, ValidateDataIssueSchema, ValidateDataRequestSchema, ValidateDataResponseSchema } from '@objectstack/spec/api'; +import type { AiAgentCapabilities, AiAgentChatRequest, AiAgentSummary, AiAgentsResponse, AiChatRequest, AiChatResponse, AiCompleteRequest, AiConversation, AiConversationMessage, AiMessage, AiModelsResponse, AiPendingAction, AiPendingActionStatus, AiStreamChunk, ApproveAiPendingActionResponse, AuditMetaItemRequest, AuditMetaItemResponse, AutomationActionsResponse, AutomationTriggerRequest, AutomationTriggerResponse, BatchDataRequest, BatchDataResponse, BuildProbeReport, CheckPermissionRequest, CheckPermissionResponse, CloneDataResponse, CreateAiConversationRequest, CreateDataRequest, CreateDataResponse, CreateManyDataRequest, CreateManyDataResponse, DeleteDataRequest, DeleteDataResponse, DeleteManyDataRequest, DeleteManyDataResponse, DeleteMetaItemRequest, DeleteMetaItemResponse, DestructiveChangeIssue, DiffMetaItemRequest, DiffMetaItemResponse, DisablePackageRequest, DisablePackageResponse, EnablePackageRequest, EnablePackageResponse, FieldStillShownBy, FindDataRequest, FindDataResponse, FindReferencesToMetaResponse, FlowRegistration, FlowRegistrationRefusal, GetDataRequest, GetDataResponse, GetDiscoveryRequest, GetDiscoveryResponse, GetEffectivePermissionsRequest, GetEffectivePermissionsResponse, GetFieldLabelsRequest, GetFieldLabelsResponse, GetLocalesRequest, GetLocalesResponse, GetMetaDiagnosticsResponse, GetMetaItemCachedRequest, GetMetaItemCachedResponse, GetMetaItemLayeredRequest, GetMetaItemLayeredResponse, GetMetaItemRequest, GetMetaItemResponse, GetMetaItemsRequest, GetMetaItemsResponse, GetMetaTypesRequest, GetMetaTypesResponse, GetNotificationPreferencesRequest, GetNotificationPreferencesResponse, GetObjectPermissionsRequest, GetObjectPermissionsResponse, GetPackageRequest, GetPackageResponse, GetPresenceRequest, GetPresenceResponse, GetPublishedMetaItemResponse, GetRecordFieldAccessResponse, GetTranslationsRequest, GetTranslationsResponse, GetUiViewRequest, GetUiViewResponse, HistoryMetaItemRequest, HistoryMetaItemResponse, InstallPackageRequest, InstallPackageResponse, ListAiConversationsRequest, ListAiConversationsResponse, ListAiPendingActionsRequest, ListAiPendingActionsResponse, ListDraftsResponse, ListNotificationsRequest, ListNotificationsResponse, ListPackagesRequest, ListPackagesResponse, MarkAllNotificationsReadRequest, MarkAllNotificationsReadResponse, MarkNotificationsReadRequest, MarkNotificationsReadResponse, MetadataAuthoringClient, MetadataAuthoringSurface, MetadataConflictError, Notification, NotificationPreferences, PublicFormSubmitResponse, PublishMetaItemRequest, PublishMetaItemResponse, PublishPackageDraftsRequest, PublishPackageDraftsResponse, RealtimeConnectRequest, RealtimeConnectResponse, RealtimeDisconnectRequest, RealtimeDisconnectResponse, RealtimeSubscribeRequest, RealtimeSubscribeResponse, RealtimeUnsubscribeRequest, RealtimeUnsubscribeResponse, RegisterDeviceRequest, RegisterDeviceResponse, RejectAiPendingActionResponse, RollbackMetaItemRequest, RollbackMetaItemResponse, RuntimeAuthoringIssue, RuntimeBuildIssue, SaveMetaItemRequest, SaveMetaItemResponse, SearchAllHit, SearchAllPageHit, SearchAllResponse, SeedAppliedIdList, SeedAppliedLanded, SetPresenceRequest, SetPresenceResponse, UninstallPackageRequest, UninstallPackageResponse, UnregisterDeviceRequest, UnregisterDeviceResponse, UpdateAiConversationRequest, UpdateDataRequest, UpdateDataResponse, UpdateManyDataRequest, UpdateManyDataResponse, UpdateNotificationPreferencesRequest, UpdateNotificationPreferencesResponse, ValidateDataIssue, ValidateDataRequest, ValidateDataResponse } from '@objectstack/spec/api'; // Validate data const result = AiAgentCapabilitiesSchema.parse(data); @@ -821,6 +821,30 @@ A write-path strip event: caller-supplied fields legally dropped from the payloa | **userMessage** | `string` | optional | The finding's user-facing sentence, 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 `ApiErrorSchema.userMessage`. Present only when the producer authors a user sentence for this `rule`; absent, a consumer renders `message` as before. Consumers render it as received; `rule` stays the stable id and `message` / `hint` stay the developer-facing text. | +--- + +## DestructiveChangeIssue + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **code** | `string` | ✅ | What the save loses: `field_removed`, `field_type_change`, `field_required_no_default`, `currency_mode_to_record` or `currency_field_repointed`. | +| **field** | `string` | optional | The field the finding is about. | +| **message** | `string` | ✅ | The finding in prose. When `stillShownBy` names items, the prose ends by naming them too. | +| **stillShownBy** | `{ type: string; name: string; where: string[]; via?: string; … }[]` | optional | The metadata items that still show the field, computed from the environment's served metadata (one served listing per type: what the code packages register, with this environment's stored active rows folded over them; drafts are not read, and no record is read). On `field_removed` and `field_type_change` findings only; absent on every other code, and absent when it could not be computed: a listing could not be read, a judge threw or could not be loaded, or the retyped field's new definition carries no readable `type` (absent is "not computed", `[]` is "computed, none"). On `field_removed`: the `object`, `view`, `dataset`, `dashboard`, `page`, `flow` and `report` items in which the platform's reference-integrity suite, form-layout check and widget-binding check (`@objectstack/lint`, the judges `os validate` runs) find a reference that resolves with the field and dangles without it, the saved body taken as the save would write it; plus each dashboard widget bound to a dataset dimension or measure that dangles (`via`). A position those judges do not read is not seen, nor is an item of any other type (an app, an action, a permission set), nor code outside the metadata. On `field_type_change`: each filter rule of a served `view` item bound to the saved object that names the field by its bare name and whose operator does not fit the new type, judged by `filterOperatorFieldTypeFit` (an operator is unfit only where a declared-type door refuses it; a filter another door refuses, such as any filter on a field retyped to `formula`, is not named). The rules read are a view item's `config.filter` (the canonical served shape), a flattened list overlay's own `filter`, and the `userFilters.tabs[].filter` of either, rules inside an any-of group included. Filters elsewhere (datasets, dashboards, reports, flows), dotted paths, and comparands are not judged there. The save does not edit any listed item. | + +### Nested Shape: `DestructiveChangeIssue.stillShownBy[number]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **type** | `string` | ✅ | The metadata type of the item: `view` (a list view or a form), `dataset`, `dashboard`, `page`, `flow`, `report`, or `object` (another object, or the saved object's own body). | +| **name** | `string` | ✅ | The item's name, as the served list names it. One item can appear in more than one entry: a dashboard once directly and once per `via` dataset, a view once per unfit `operator`. | +| **where** | `string[]` | ✅ | Each position inside the item that names the field, as a path relative to the item as the served listing presents it: `config.columns[1]` or `config.sections[0].fields[2]` on a view item (the served listing never presents a `{ list, form, listViews }` container, only the view items it expands into), `columns[1]` on a flattened list overlay, `widgets[3]` on a dashboard. The literal `(root)` when the finding sits on the item itself. | +| **via** | `string` | optional | A dashboard widget shows the field through this dataset: it names a dimension or measure of the dataset, and that dimension or measure names the field. | +| **operator** | `string` | optional | On a `field_type_change` entry only: the filter operator, as the view rule spells it, that no longer fits the new type (`filterOperatorFieldTypeFit` answers `unfit`). | + + --- ## DiffMetaItemRequest @@ -965,6 +989,21 @@ Enable package response | **registeredNamespaces** | `string[]` | optional | Namespace prefixes registered by this package | +--- + +## FieldStillShownBy + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **type** | `string` | ✅ | The metadata type of the item: `view` (a list view or a form), `dataset`, `dashboard`, `page`, `flow`, `report`, or `object` (another object, or the saved object's own body). | +| **name** | `string` | ✅ | The item's name, as the served list names it. One item can appear in more than one entry: a dashboard once directly and once per `via` dataset, a view once per unfit `operator`. | +| **where** | `string[]` | ✅ | Each position inside the item that names the field, as a path relative to the item as the served listing presents it: `config.columns[1]` or `config.sections[0].fields[2]` on a view item (the served listing never presents a `{ list, form, listViews }` container, only the view items it expands into), `columns[1]` on a flattened list overlay, `widgets[3]` on a dashboard. The literal `(root)` when the finding sits on the item itself. | +| **via** | `string` | optional | A dashboard widget shows the field through this dataset: it names a dimension or measure of the dataset, and that dimension or measure names the field. | +| **operator** | `string` | optional | On a `field_type_change` entry only: the filter operator, as the view rule spells it, that no longer fits the new type (`filterOperatorFieldTypeFit` answers `unfit`). | + + --- ## FindDataRequest