diff --git a/.changeset/32861-flow-answer-dropped-fields.md b/.changeset/32861-flow-answer-dropped-fields.md new file mode 100644 index 00000000000..a7c6d754ec5 --- /dev/null +++ b/.changeset/32861-flow-answer-dropped-fields.md @@ -0,0 +1,14 @@ +--- +'@objectstack/spec': patch +'@objectstack/service-automation': patch +--- + +fix(automation): a flow run's answer names the fields its write steps did not store, so a record button whose flow writes a read-only field no longer answers a plain success + +Clause-②: yes (widening) +Metadata-protocol: none + +- **`@objectstack/spec`: `AutomationResult.droppedFields?: DroppedFieldsEvent[]`**, mirrored on `TriggerFlowResponseSchema.data.droppedFields` (the parity guard binds the two member for member). The element is the data engine's own `DroppedFieldsEventSchema` (`object`, `fields`, `reason`), so there is no new vocabulary. Set on a terminal success only, and only when a write step dropped a field; absent otherwise. +- **`@objectstack/service-automation`**: a `create_record` / `update_record` step whose caller-supplied values the engine legally stripped (a `readonly` field, a `readonlyWhen` lock, a computed field, …) already succeeded with a warning on its step; it now also carries the structured events, and the run's terminal answer folds them, one event per object and reason. A drop before a pause reaches the answer the resumed run gives, and a field named means at least one write dropped it. A `subflow` child that completes without pausing rolls its drops up onto its parent's answer; a child that paused, and a `map` item's run, do not yet (#33019), so for those an absent member is not proof that nothing was dropped. The run's outcome does not change: `success`, `status` and `summary` read as before. + +Every door that relays the run's answer carries it unchanged: an action of `type: 'flow'` (`POST /api/v1/actions/:object/:action`, `POST /api/v1/actions/:object/:action/:recordId`, the MCP `run_action` tool), `POST /api/v1/automation/:name/trigger`, and the resume door that delivers a paused run's final answer (`POST /api/v1/automation/:name/runs/:runId/resume`, the MCP `resume_run` tool). A caller that reads the answer can now tell the person who clicked that, for example, `status` did not take effect because it is read-only. diff --git a/content/docs/references/api/automation-api.mdx b/content/docs/references/api/automation-api.mdx index eea45d9f755..841f608deba 100644 --- a/content/docs/references/api/automation-api.mdx +++ b/content/docs/references/api/automation-api.mdx @@ -1141,6 +1141,7 @@ const result = AutomationApiErrorCode.parse(data); | **flowLabel** | `string` | optional | The flow definition's authored `label`, copied verbatim so a runner can name the flow (header, completion toast) and translate it against `flows..label`. Set on every result of an evaluation of a registered flow (paused and terminal alike); absent on a refusal carrying `code`. For a subflow chain it is the addressed (parent) run's flow. Never defaulted to the API name | | **refusalMessage** | `string` | optional | Rendered refusal, set when `status` is `refused` - the `end` node's `message` template interpolated against the run's variables, so it names the record. Authored per-record text (not a flow-level copy like the two above); absent on every other status. A runner shows it with Close only | | **summary** | `{ selected: integer; acted: integer; skipped: integer; unmeasured?: integer; … }` | optional | What the run did - records selected / acted on, gate skips, per-node status. Set on a TERMINAL result (a paused run has not finished doing it yet). | +| **droppedFields** | `{ object: string; fields: string[]; reason: Enum<'readonly' \| 'readonly_when' \| 'primary_key' \| 'computed' \| 'stored_expression'> }[]` | optional | Caller-supplied field values a write step of the run did not store (e.g. a `readonly` field an `update_record` step wrote): the data engine's own drop events, one per object and reason in first-seen order; a field named means at least one write dropped it, not every write. The steps still succeeded and the run's outcome is unchanged - this tells the caller which values never landed. Set on a terminal success only, and only when a field was dropped. Delegated writes: a `subflow` child that completes without pausing rolls its drops up here; a child that paused, and a `map` item's run, do not yet, so an absent member is not proof that a delegated write dropped nothing. | --- diff --git a/packages/runtime/src/action-flow-dropped-fields-relay.test.ts b/packages/runtime/src/action-flow-dropped-fields-relay.test.ts new file mode 100644 index 00000000000..201d9731dbb --- /dev/null +++ b/packages/runtime/src/action-flow-dropped-fields-relay.test.ts @@ -0,0 +1,115 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * #32861 — the action door relays the run's `droppedFields` to whoever pressed + * the button, through BOTH entrances to `dispatchFlowAction`: REST + * `POST /actions/:object/:action` (`HttpDispatcher.handleActions`, whose + * `data` is the run's `AutomationResult`) and the MCP `run_action` bridge + * (`invokeBusinessAction`, whose `result` is the same value). + * + * The door adds nothing and strips nothing — measured before this card: it + * relays the result whole, so the run's answer is the one place the drop + * could go missing, and that is where #32861 put it + * (`service-automation`'s `run-dropped-fields.ts`). These pins hold the + * door's half of the bargain with a scripted automation service, so a later + * re-shaping of the door's answer (a projection, an allow-list) cannot drop + * the member without going red. The wire half — the real engine, a real + * read-only strip — is `@objectstack/verify`'s + * `action-flow-dropped-fields.test.ts`. + */ + +import { describe, it, expect, vi } from 'vitest'; + +import { HttpDispatcher } from './http-dispatcher.js'; +import { callData, invokeBusinessAction } from './action-execution.js'; + +// Paid at collection, not inside a case's clock (check:test-source-alias). +import '@objectstack/metadata'; + +const OBJECT = 'afr_report'; +const FLOW = 'afr_submit'; +const ACTION = 'submit_for_approval'; +const MEMBER_EC = { userId: 'user_1', systemPermissions: [] as string[] }; + +const DROPPED = [{ object: OBJECT, fields: ['status'], reason: 'readonly' }]; + +function makeDoor(result: Record) { + const execute = vi.fn(async () => result); + const getFlow = vi.fn(async (name: string) => (name === FLOW ? { name, type: 'autolaunched', runAs: 'user' } : null)); + const automation = { execute, getFlow }; + + const action = { + name: ACTION, label: 'Submit for approval', objectName: OBJECT, type: 'flow', target: FLOW, + ai: { exposed: true, description: 'Submits the report for approval for this test.' }, + }; + const objectDef = { name: OBJECT, actions: [action] }; + const schemaOf = (n: string) => (n === OBJECT ? objectDef : undefined); + const ql: any = { + executeAction: vi.fn(async () => ({ ran: 'script' })), + getSchema: schemaOf, + registry: { getObject: schemaOf, getItem: () => undefined }, + find: vi.fn(async () => []), + insert: vi.fn(), update: vi.fn(), delete: vi.fn(), + }; + const metadata: any = { + load: vi.fn(async () => null), + loadDiagnosed: vi.fn(async () => ({ data: null, degraded: false, errors: [] })), + listObjects: vi.fn(async () => [objectDef]), + getObject: vi.fn(async (n: string) => schemaOf(n)), + }; + const resolve = (n: string) => + n === 'objectql' || n === 'data' ? ql : n === 'metadata' ? metadata : n === 'automation' ? automation : null; + const kernel: any = { getService: resolve, getServiceAsync: async (n: string) => resolve(n), context: { getService: resolve } }; + + const viaRest = async (): Promise => { + const res: any = await new HttpDispatcher(kernel).handleActions(`/${OBJECT}/${ACTION}`, 'POST', {}, { + request: {}, environmentId: 'platform', executionContext: MEMBER_EC, + } as any); + expect(res.response?.status).toBe(200); + return res.response?.body?.data; + }; + + const viaMcp = async (): Promise => { + const request: any = { request: {}, environmentId: 'platform', executionContext: MEMBER_EC }; + const deps: any = { + resolveService: async (_ctx: any, name: string) => (name === 'automation' ? automation : undefined), + getObjectQL: async () => ql, + }; + const answered: any = await invokeBusinessAction(deps, request, ACTION, { objectName: OBJECT } as any, { + driver: undefined, + envId: 'platform', + ec: MEMBER_EC, + getMeta: () => ({ listObjects: async () => [objectDef] }), + callData: (a, params, dataDriver, scopeId, execCtx) => + callData(deps, request, a, params, dataDriver, scopeId, execCtx), + }); + return answered.result; + }; + + return { viaRest, viaMcp, execute }; +} + +const ENTRANCES = ['REST /actions', 'MCP run_action'] as const; + +describe('the action door relays the run\'s droppedFields (#32861)', () => { + for (const entrance of ENTRANCES) { + it(`${entrance}: a run that dropped a read-only field answers it to the caller, beside an unchanged success`, async () => { + const door = makeDoor({ success: true, output: {}, droppedFields: DROPPED }); + + const answer = entrance === 'REST /actions' ? await door.viaRest() : await door.viaMcp(); + + expect(door.execute).toHaveBeenCalledTimes(1); + expect(answer.success).toBe(true); + expect(answer.droppedFields).toEqual(DROPPED); + }); + + it(`${entrance}: a run that dropped nothing answers without the member`, async () => { + const door = makeDoor({ success: true, output: {} }); + + const answer = entrance === 'REST /actions' ? await door.viaRest() : await door.viaMcp(); + + expect(answer.success).toBe(true); + expect('droppedFields' in answer).toBe(false); + }); + } +}); diff --git a/packages/services/service-automation/src/builtin/crud-nodes.ts b/packages/services/service-automation/src/builtin/crud-nodes.ts index b5fa1492f79..e8198559c64 100644 --- a/packages/services/service-automation/src/builtin/crud-nodes.ts +++ b/packages/services/service-automation/src/builtin/crud-nodes.ts @@ -778,7 +778,11 @@ export function registerCrudNodes(engine: AutomationEngine, ctx: PluginContext): ...(droppedFields.length > 0 ? { droppedFields } : {}), }, ...(dropped.length > 0 - ? { warnings: dropped.map((e) => droppedFieldsWarning('create_record', e)) } + ? { + warnings: dropped.map((e) => droppedFieldsWarning('create_record', e)), + // #32861 — the events themselves, for the run's answer. + droppedFields: dropped, + } : {}), metrics: { acted: 1 }, }; @@ -926,7 +930,11 @@ export function registerCrudNodes(engine: AutomationEngine, ctx: PluginContext): ...(droppedFields.length > 0 ? { droppedFields } : {}), }, ...(dropped.length > 0 - ? { warnings: dropped.map((e) => droppedFieldsWarning('update_record', e)) } + ? { + warnings: dropped.map((e) => droppedFieldsWarning('update_record', e)), + // #32861 — the events themselves, for the run's answer. + droppedFields: dropped, + } : {}), metrics: { acted: writtenRowCount(result) }, }; diff --git a/packages/services/service-automation/src/builtin/subflow-node.ts b/packages/services/service-automation/src/builtin/subflow-node.ts index b9e53a5c12a..f74fd9c219e 100644 --- a/packages/services/service-automation/src/builtin/subflow-node.ts +++ b/packages/services/service-automation/src/builtin/subflow-node.ts @@ -209,6 +209,11 @@ export function registerSubflowNode(engine: AutomationEngine, ctx: PluginContext success: true as const, output: { output: child.output ?? null }, ...(metrics ? { metrics } : {}), + // #32861 — the values the child's write steps did not store ride up + // onto this step, so the parent's answer (`AutomationResult.droppedFields`) + // tells the caller about a drop its delegated write met. Set by the + // child's terminal success only, so a failed child carries none. + ...(child.droppedFields?.length ? { droppedFields: child.droppedFields } : {}), }; // [#18110] The child REFUSED — an `end` inside it declared diff --git a/packages/services/service-automation/src/dag-traversal.ts b/packages/services/service-automation/src/dag-traversal.ts index ce8ebb87037..aca7bf1a896 100644 --- a/packages/services/service-automation/src/dag-traversal.ts +++ b/packages/services/service-automation/src/dag-traversal.ts @@ -21,6 +21,7 @@ import { isGuardRefusal } from './guard-refusal.js'; import { gradeAfterTenantCurrencyReadFault } from './builtin/template.js'; import { attachCarriedRefusal, readCarriedRefusal } from './inner-refusal.js'; import { summarizeRun } from './run-summary.js'; +import { withDroppedFields } from './run-dropped-fields.js'; import { describeThrownForLog } from './thrown-cause-diagnostics.js'; // The values below (`AutomationEngine` for its public static // `MAX_NODE_REENTRIES`) are read only inside the function bodies, at call time, @@ -414,6 +415,7 @@ export async function executeNode( durationMs: Date.now() - stepStart, error: { code: 'NODE_FAILURE', message: errMsg }, ...(result.warnings?.length ? { warnings: result.warnings } : {}), + ...(result.droppedFields?.length ? { droppedFields: result.droppedFields } : {}), // #4354 — a node that failed PART WAY may still have written // rows; dropping its counts would understate what the run did. ...(result.metrics ? { metrics: result.metrics } : {}), @@ -494,6 +496,9 @@ export async function executeNode( completedAt: new Date().toISOString(), durationMs: Date.now() - stepStart, ...(result.warnings?.length ? { warnings: result.warnings } : {}), + // #32861 — the structured events behind those warnings, folded + // onto the run's terminal answer (`dropEventsOf`). + ...(result.droppedFields?.length ? { droppedFields: result.droppedFields } : {}), ...(result.metrics ? { metrics: result.metrics } : {}), }); @@ -1358,7 +1363,8 @@ export async function executeWithoutRetry( const successMessage = this.renderFlowTerminalMessage( flowName, 'successMessage', flow.successMessage, variables, runContext, ); - return { success: true, output, durationMs, successMessage, flowLabel: flow.label, summary }; + // #32861 — same fold as `execute()`'s terminal exit, over this attempt's steps. + return { success: true, output, durationMs, successMessage, flowLabel: flow.label, summary, ...withDroppedFields(steps) }; } catch (err: unknown) { // [#15788] The THIRD producer: an attempt that reached a refusing // `end`. A flow under `errorHandling.strategy: 'retry'` is handed diff --git a/packages/services/service-automation/src/engine.ts b/packages/services/service-automation/src/engine.ts index a1760269d00..f8c74eba373 100644 --- a/packages/services/service-automation/src/engine.ts +++ b/packages/services/service-automation/src/engine.ts @@ -67,6 +67,8 @@ import { runTriggerUserId, type SeededRunContext } from './runtime-identity.js'; import { flowContentChecksum } from './flow-identity.js'; import { carriedRefusalOfResult, readCarriedRefusal, type CarriedRefusal } from './inner-refusal.js'; import { summarizeRun } from './run-summary.js'; +import { withDroppedFields } from './run-dropped-fields.js'; +import type { DroppedFieldsEvent } from '@objectstack/spec/data'; // #5660 — the degrade registration reports a FOREIGN failure (a third-party // provider factory's text), so it renders it as structured `meta` rather than // interpolating it into the log message. See ./thrown-cause-diagnostics.ts. @@ -432,6 +434,16 @@ export interface NodeExecutionResult { * copies them onto the {@link StepLogEntry}. */ warnings?: string[]; + /** + * #32861: the data engine's own drop events behind the strip warnings + * above — the structured half a write node (`create_record` / + * `update_record`) received from `onFieldsDropped`. Copied onto the + * {@link StepLogEntry} beside `warnings`, and folded from there onto the + * run's terminal answer (`AutomationResult.droppedFields`), so the door + * that started the run can tell its caller which values never landed. + * Omitted when nothing was dropped. + */ + droppedFields?: DroppedFieldsEvent[]; /** Used by decision nodes — returns the selected branch label */ branchLabel?: string; /** @@ -1109,6 +1121,14 @@ export interface StepLogEntry { * partially didn't land instead of a silent success. */ warnings?: string[]; + /** + * #32861: the structured drop events behind those warnings + * ({@link NodeExecutionResult.droppedFields}). On the step, not in a + * run-scoped side table, so a run that pauses keeps them with the steps it + * persists and the resumed run's terminal answer folds the whole run + * (`dropEventsOf`). + */ + droppedFields?: DroppedFieldsEvent[]; /** * #1479: structured-region grouping. When a step ran inside a `loop` / * `parallel` / `try_catch` body region, these tag it with its **immediate** @@ -7639,6 +7659,9 @@ export class AutomationEngine implements IAutomationService { // (a `subflow` roll-up, a runtime test asserting the sweep wrote // something) never has to re-read the run to learn what it did. summary, + // #32861 — the values a write step did not store, so the door + // that started the run can tell its caller. Omitted when none. + ...withDroppedFields(steps), }; } catch (err: unknown) { // [#15788] The run REFUSED — an `end` node declaring diff --git a/packages/services/service-automation/src/run-dropped-fields.test.ts b/packages/services/service-automation/src/run-dropped-fields.test.ts new file mode 100644 index 00000000000..931c364a922 --- /dev/null +++ b/packages/services/service-automation/src/run-dropped-fields.test.ts @@ -0,0 +1,238 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * #32861 — a write step whose caller-supplied values the data engine legally + * stripped (a `readonly` field) succeeds and records the strip on its step + * (#3407), but the run's ANSWER carried nothing of it: a record button whose + * flow wrote a read-only `status` answered a plain success and the person who + * clicked it was told nothing. `AutomationResult.droppedFields` carries the + * engine's own drop events on the terminal answer. + * + * These pins drive the real engine with a stub data engine that fires + * `onFieldsDropped` exactly as ObjectQL does (the engine side is pinned in + * `packages/objectql`, the door side in `@objectstack/verify`'s + * `action-flow-dropped-fields.test.ts`). + */ +import { describe, it, expect } from 'vitest'; +import type { AutomationContext } from '@objectstack/spec/contracts'; +import { defineActionDescriptor } from '@objectstack/spec/automation'; +import { AutomationEngine } from './engine.js'; +import type { NodeExecutor, StepLogEntry } from './engine.js'; +import { InMemorySuspendedRunStore } from './suspended-run-store.js'; +import { registerCrudNodes } from './builtin/crud-nodes.js'; +import { registerSubflowNode } from './builtin/subflow-node.js'; +import { dropEventsOf } from './run-dropped-fields.js'; + +type Drop = { object: string; fields: string[]; reason: 'readonly' | 'readonly_when' | 'primary_key' | 'computed' | 'stored_expression' }; + +function makeLogger(): any { + const l: any = { info() {}, warn() {}, error() {}, debug() {} }; + l.child = () => l; + return l; +} + +/** A data engine whose writes report `drops(fields)` through the caller's `onFieldsDropped`. */ +function fakeData(drops: (object: string, fields: Record) => Drop[]) { + return { + async insert(object: string, fields: any, opts: any) { + for (const e of drops(object, fields)) opts?.onFieldsDropped?.(e); + return { id: `${object}_1`, ...fields }; + }, + async update(object: string, fields: any, opts: any) { + for (const e of drops(object, fields)) opts?.onFieldsDropped?.(e); + return { id: 'r1', ...fields }; + }, + }; +} + +/** `status` is `readonly: true` on `expense_report`; every other field lands. */ +const READONLY_STATUS = (object: string, fields: Record): Drop[] => + object === 'expense_report' && 'status' in fields ? [{ object, fields: ['status'], reason: 'readonly' }] : []; + +function makeEngine() { + const logger = makeLogger(); + const data = fakeData(READONLY_STATUS); + const ctx: any = { logger, getService: (n: string) => (n === 'data' ? data : undefined) }; + const engine = new AutomationEngine(logger, new InMemorySuspendedRunStore()); + registerCrudNodes(engine, ctx); + registerSubflowNode(engine, ctx); + return engine; +} + +/** start → update_record(expense_report, `fields`) → end: the #32666 shape. */ +function submitFlow(name: string, fields: Record) { + return { + name, label: name, type: 'autolaunched', runAs: 'user', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'submit', type: 'update_record', label: 'Submit', config: { objectName: 'expense_report', filter: { id: 'r1' }, fields } }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'submit' }, + { id: 'e2', source: 'submit', target: 'end' }, + ], + } as never; +} + +const CALLER = { userId: 'u1' } as AutomationContext; + +describe('AutomationResult.droppedFields (#32861)', () => { + it('the #32666 shape: the answer names the read-only field the step dropped, and the run still succeeds', async () => { + const engine = makeEngine(); + engine.registerFlow('submit_for_approval', submitFlow('submit_for_approval', { status: 'submitted', note: 'please' })); + + const res = await engine.execute('submit_for_approval', CALLER); + + expect(res.success).toBe(true); + expect(res.status).toBeUndefined(); + expect(res.droppedFields).toEqual([{ object: 'expense_report', fields: ['status'], reason: 'readonly' }]); + // The outcome semantics are unchanged: the summary reads as before. + expect(res.summary?.failed).toBe(0); + expect(res.summary?.acted).toBe(1); + }); + + it('a write that drops nothing answers without the member at all (omitted, never [])', async () => { + const engine = makeEngine(); + engine.registerFlow('add_note', submitFlow('add_note', { note: 'please' })); + + const res = await engine.execute('add_note', CALLER); + + expect(res.success).toBe(true); + expect('droppedFields' in res).toBe(false); + }); + + it('create_record drops ride the answer too', async () => { + const engine = makeEngine(); + engine.registerFlow('file_report', { + name: 'file_report', label: 'file_report', type: 'autolaunched', runAs: 'user', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'make', type: 'create_record', label: 'Make', config: { objectName: 'expense_report', fields: { name: 'Q4', status: 'approved' } } }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'make' }, + { id: 'e2', source: 'make', target: 'end' }, + ], + } as never); + + const res = await engine.execute('file_report', CALLER); + + expect(res.droppedFields).toEqual([{ object: 'expense_report', fields: ['status'], reason: 'readonly' }]); + }); + + it('a drop before a pause reaches the answer the resumed run finally gives', async () => { + const engine = makeEngine(); + engine.registerNodeExecutor({ + type: 'hold', + descriptor: defineActionDescriptor({ type: 'hold', version: '1.0.0', name: 'Hold', supportsPause: true, resumeAuthority: 'any' }), + async execute() { return { success: true, suspend: true, correlation: 'held' }; }, + } as NodeExecutor); + engine.registerFlow('submit_then_confirm', { + name: 'submit_then_confirm', label: 'submit_then_confirm', type: 'autolaunched', runAs: 'user', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'submit', type: 'update_record', label: 'Submit', config: { objectName: 'expense_report', filter: { id: 'r1' }, fields: { status: 'submitted' } } }, + { id: 'hold', type: 'hold', label: 'Hold' }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'submit' }, + { id: 'e2', source: 'submit', target: 'hold' }, + { id: 'e3', source: 'hold', target: 'end' }, + ], + } as never); + + const paused = await engine.execute('submit_then_confirm', CALLER); + expect(paused.status).toBe('paused'); + // A paused run has not finished: nothing is said yet. + expect('droppedFields' in paused).toBe(false); + + const done = await engine.resume(paused.runId!); + expect(done.success).toBe(true); + expect(done.droppedFields).toEqual([{ object: 'expense_report', fields: ['status'], reason: 'readonly' }]); + }); + + it('a run under errorHandling.strategy \'retry\' answers the drop from the attempt that completed', async () => { + // The third terminal-success exit: `retryExecution` hands every attempt + // to `executeWithoutRetry`, whose completion is the run's answer. + const engine = makeEngine(); + let attempts = 0; + engine.registerNodeExecutor({ + type: 'flaky', + async execute() { + attempts++; + return attempts === 1 ? { success: false, error: 'transient 503' } : { success: true }; + }, + } as never); + engine.registerFlow('submit_with_retry', { + name: 'submit_with_retry', label: 'submit_with_retry', type: 'autolaunched', runAs: 'user', + errorHandling: { strategy: 'retry', maxRetries: 1, backoffMs: 0 }, + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'submit', type: 'update_record', label: 'Submit', config: { objectName: 'expense_report', filter: { id: 'r1' }, fields: { status: 'submitted' } } }, + { id: 'notify', type: 'flaky', label: 'Notify' }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'submit' }, + { id: 'e2', source: 'submit', target: 'notify' }, + { id: 'e3', source: 'notify', target: 'end' }, + ], + } as never); + + const res = await engine.execute('submit_with_retry', CALLER); + + expect(attempts).toBe(2); // the ladder really ran: attempt 1 failed, attempt 2 completed + expect(res.success).toBe(true); + expect(res.droppedFields).toEqual([{ object: 'expense_report', fields: ['status'], reason: 'readonly' }]); + }); + + it('a subflow child\'s drop rides up onto the parent\'s answer', async () => { + const engine = makeEngine(); + engine.registerFlow('child_submit', submitFlow('child_submit', { status: 'submitted' })); + engine.registerFlow('parent_button', { + name: 'parent_button', label: 'parent_button', type: 'autolaunched', runAs: 'user', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'sub', type: 'subflow', label: 'Sub', config: { flowName: 'child_submit' } }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'sub' }, + { id: 'e2', source: 'sub', target: 'end' }, + ], + } as never); + + const res = await engine.execute('parent_button', CALLER); + + expect(res.success).toBe(true); + expect(res.droppedFields).toEqual([{ object: 'expense_report', fields: ['status'], reason: 'readonly' }]); + }); +}); + +describe('dropEventsOf — the fold over the step log', () => { + const AT = '2026-11-13T00:00:00.000Z'; + const step = (nodeId: string, droppedFields?: Drop[]): StepLogEntry => ({ + nodeId, nodeType: 'update_record', status: 'success', startedAt: AT, ...(droppedFields ? { droppedFields } : {}), + }); + + it('coalesces one event per (object, reason), fields in first-seen order — a loop of thirty is one fact', () => { + const steps = [ + ...Array.from({ length: 30 }, (_, i) => step(`w${i}`, [{ object: 'expense_report', fields: ['status'], reason: 'readonly' }])), + step('w30', [{ object: 'expense_report', fields: ['approved_at', 'status'], reason: 'readonly' }]), + step('w31', [{ object: 'expense_report', fields: ['amount'], reason: 'readonly_when' }]), + step('w32', [{ object: 'expense_line', fields: ['status'], reason: 'readonly' }]), + ]; + expect(dropEventsOf(steps)).toEqual([ + { object: 'expense_report', fields: ['status', 'approved_at'], reason: 'readonly' }, + { object: 'expense_report', fields: ['amount'], reason: 'readonly_when' }, + { object: 'expense_line', fields: ['status'], reason: 'readonly' }, + ]); + }); + + it('answers undefined, not [], for a log with no drop', () => { + expect(dropEventsOf([step('a'), step('b', [])])).toBeUndefined(); + }); +}); diff --git a/packages/services/service-automation/src/run-dropped-fields.ts b/packages/services/service-automation/src/run-dropped-fields.ts new file mode 100644 index 00000000000..127c6147389 --- /dev/null +++ b/packages/services/service-automation/src/run-dropped-fields.ts @@ -0,0 +1,58 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { DroppedFieldsEvent } from '@objectstack/spec/data'; +import type { StepLogEntry } from './engine.js'; + +/** + * Fold a run's step log into the `droppedFields` its terminal answer carries + * (#32861, `AutomationResult.droppedFields`). + * + * A write step whose caller-supplied values the data engine legally stripped + * (a `readonly` field, a `readonlyWhen` lock, …) succeeds and says so in its + * `warnings` (#3407); the structured events behind those warnings ride the + * step as `droppedFields`. Before this fold they stopped there, so the run + * answered a plain success and a record button whose flow wrote a read-only + * `status` told the person who clicked it nothing. + * + * The fold is over the FLAT step log, like `summarizeRun`: a structured + * region's body steps are already spliced into it, and a run resumed from a + * pause carries the steps it ran before the pause — so a drop before a + * `screen` node still reaches the answer the run finally gives. + * + * Coalesced, not concatenated: one event per `(object, reason)`, its `fields` + * the union in first-seen order. A loop that writes thirty rows and drops + * `status` on each is one fact for the caller ("status did not take effect"), + * not thirty, and the answer stays bounded by the schema rather than by the + * run's length. The element is the engine's own event, unchanged in shape — + * no new vocabulary. + * + * Returns `undefined` — never `[]` — when nothing was dropped, so the member + * is omitted on every run that dropped nothing. + */ +export function dropEventsOf(steps: readonly StepLogEntry[]): DroppedFieldsEvent[] | undefined { + const byKey = new Map(); + for (const step of steps) { + for (const e of step.droppedFields ?? []) { + const key = `${e.reason}\u0000${e.object}`; + const held = byKey.get(key); + if (!held) { + byKey.set(key, { object: e.object, fields: [...e.fields], reason: e.reason }); + continue; + } + for (const f of e.fields) if (!held.fields.includes(f)) held.fields.push(f); + } + } + const events = [...byKey.values()].filter((e) => e.fields.length > 0); + return events.length > 0 ? events : undefined; +} + +/** + * The spread every terminal-success exit applies: `{ droppedFields }` when + * {@link dropEventsOf} found any, `{}` otherwise — one spelling for the + * omit-when-empty rule at all three exits (`execute()`, a retried attempt, + * a resumed run). + */ +export function withDroppedFields(steps: readonly StepLogEntry[]): { droppedFields?: DroppedFieldsEvent[] } { + const droppedFields = dropEventsOf(steps); + return droppedFields ? { droppedFields } : {}; +} diff --git a/packages/services/service-automation/src/run-resume.ts b/packages/services/service-automation/src/run-resume.ts index 7572dcccbf5..de95662e1e5 100644 --- a/packages/services/service-automation/src/run-resume.ts +++ b/packages/services/service-automation/src/run-resume.ts @@ -24,6 +24,7 @@ import { refuseNode } from './guard-refusal.js'; import { describeThrownForLog } from './thrown-cause-diagnostics.js'; import { carriedRefusalOfResult, readCarriedRefusal } from './inner-refusal.js'; import { summarizeRun } from './run-summary.js'; +import { withDroppedFields } from './run-dropped-fields.js'; import { noteTenantCurrencyReadFault } from './builtin/template.js'; import { mapItemCancelledVariable, type MapItemCancelledMarker } from './builtin/map-node.js'; // The values below (`buildRunTrigger`, `FlowRefusalSignal`, `isRefusalSignal`, @@ -1965,6 +1966,9 @@ export async function resumeInternal( ), flowLabel: flow.label, summary, + // #32861 — like `summary`, over the WHOLE run: a drop before + // the pause reaches the answer the run finally gives. + ...withDroppedFields(steps), }; } catch (err: unknown) { // [#15788] A resumed run reached a refusing `end` — the SECOND diff --git a/packages/spec/src/api/automation-api.zod.test.ts b/packages/spec/src/api/automation-api.zod.test.ts index 00f8626db5f..45e2bf710c0 100644 --- a/packages/spec/src/api/automation-api.zod.test.ts +++ b/packages/spec/src/api/automation-api.zod.test.ts @@ -444,6 +444,22 @@ describe('TriggerFlowResponseSchema', () => { expect(result.data.summary?.acted).toBe(1); }); + // #32861 — `AutomationResult.droppedFields`: the schema strips undeclared + // keys, so this holds the member's SURVIVAL on the relayed answer, and that + // its element is the data engine's own drop event (no second vocabulary). + it('keeps droppedFields on a finished run, element for element, and refuses an off-vocabulary reason', () => { + const dropped = [{ object: 'expense_report', fields: ['status'], reason: 'readonly' as const }]; + const result = TriggerFlowResponseSchema.parse({ + success: true, + data: { success: true, status: 'completed', droppedFields: dropped }, + }); + expect(result.data.droppedFields).toEqual(dropped); + expect(TriggerFlowResponseSchema.safeParse({ + success: true, + data: { success: true, droppedFields: [{ object: 'expense_report', fields: ['status'], reason: 'locked' }] }, + }).success).toBe(false); + }); + // `AutomationResult.flowLabel` — the flow's authored label, which a runner // shows (and translates) in its header and completion toast. The compile- // time `TriggerFlowDataMatchesContract` guard above holds the member's diff --git a/packages/spec/src/api/automation-api.zod.ts b/packages/spec/src/api/automation-api.zod.ts index 767587bb7ef..cb09df1362f 100644 --- a/packages/spec/src/api/automation-api.zod.ts +++ b/packages/spec/src/api/automation-api.zod.ts @@ -5,6 +5,7 @@ import { BaseResponseSchema } from './contract.zod'; import { ErrorCode } from './error-code-ledger.zod'; import { FlowSchema } from '../automation/flow.zod'; import { ExecutionLogSchema, ExecutionStatus, FlowRunSummarySchema } from '../automation/execution.zod'; +import { DroppedFieldsEventSchema } from '../data/data-engine.zod'; /** * Automation API Protocol @@ -482,6 +483,20 @@ export const TriggerFlowResponseSchema = lazySchema(() => BaseResponseSchema.ext + 'status. Set on a TERMINAL result (a paused run has not finished doing ' + 'it yet).', ), + // #32861 — mirrors `AutomationResult.droppedFields`; the element IS the + // data engine's `DroppedFieldsEventSchema`, so no new vocabulary. The + // paused-child and `map`-item roll-up the describe says is not built yet + // is #33019. + droppedFields: z.array(DroppedFieldsEventSchema).optional().describe( + 'Caller-supplied field values a write step of the run did not store (e.g. a `readonly` ' + + 'field an `update_record` step wrote): the data engine\'s own drop events, one per object ' + + 'and reason in first-seen order; a field named means at least one write dropped it, not every ' + + 'write. The steps still succeeded and the run\'s outcome is unchanged - this tells ' + + 'the caller which values never landed. Set on a terminal success only, and only when ' + + 'a field was dropped. Delegated writes: a `subflow` child that completes without pausing ' + + 'rolls its drops up here; a child that paused, and a `map` item\'s run, do not yet, ' + + 'so an absent member is not proof that a delegated write dropped nothing.', + ), }), })); export type TriggerFlowResponse = z.input; diff --git a/packages/spec/src/contracts/automation-service.ts b/packages/spec/src/contracts/automation-service.ts index 44594a5d8c6..6ee9e725666 100644 --- a/packages/spec/src/contracts/automation-service.ts +++ b/packages/spec/src/contracts/automation-service.ts @@ -22,6 +22,7 @@ import type { ExecutionContext } from '../kernel/execution-context.zod'; import type { JobRunTrigger } from './job-service'; import type { FlowRegistration } from '../api/protocol.zod'; import type { FlowInnerRefusal } from '../api/automation-api.zod'; +import type { DroppedFieldsEvent } from '../data/data-engine.zod'; /** * The write a record-triggered run was dispatched inside (#28251) — see @@ -823,6 +824,36 @@ export interface AutomationResult { * answer without a second round-trip through `getRun`. */ summary?: FlowRunSummary; + /** + * #32861: the caller-supplied field values a write step of this run did + * NOT store — each element the data engine's own + * {@link DroppedFieldsEvent} (`object`, `fields`, `reason`), as the + * `create_record` / `update_record` step received it — one event per + * `(object, reason)`, its `fields` the union in first-seen order, so a + * loop that drops `status` on thirty rows is one fact, not thirty. A + * field named means at least one write dropped it, not every write. + * + * The step reports the strip as a warning and SUCCEEDS (#3407): a + * `readonly` field the flow wrote was removed from the payload and the + * write committed without it. Before this member that fact stopped at the + * run log, so a record button whose flow wrote a read-only `status` + * answered a plain success and the person who clicked it was told + * nothing. It rides the answer so the door that started the run can tell + * them, the way a record save's `droppedFields` already does. + * + * ⛔ Not a failure, and it moves nothing else: `success`, `status` and + * `summary` read exactly as they would without it. Set on a TERMINAL + * success only (the run's own write steps, before and after any pause + * it resumed from), and only when at least one step dropped a field — + * absent, never `[]`, otherwise. + * + * Delegated writes, as built: a `subflow` child that completes without + * pausing rolls its drops up onto this answer; a child that paused, and + * a `map` item's run, do not yet (#33019) — unlike {@link summary}, + * which credits all three. Until then an absent member is not proof + * that a delegated write dropped nothing. + */ + droppedFields?: DroppedFieldsEvent[]; } /** diff --git a/packages/verify/src/action-flow-dropped-fields.test.ts b/packages/verify/src/action-flow-dropped-fields.test.ts new file mode 100644 index 00000000000..8557c9525d0 --- /dev/null +++ b/packages/verify/src/action-flow-dropped-fields.test.ts @@ -0,0 +1,158 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * #32861 — a record button (an action of `type: 'flow'`) whose autolaunched + * flow writes a `readonly: true` field, on the real kernel through + * `actions.run` — the in-process twin of `POST /api/v1/actions/:object/:action` + * (`handle.ts` drives the runtime's `HttpDispatcher`, so it answers through the + * same `dispatchFlowAction` the MCP `run_action` bridge reaches). + * + * The shape is #32666's: an object whose `status` is `readonly: true`, a flow + * whose `update_record` step writes `status` (and a writable `note` beside it, + * the control that the write itself landed), and a record action naming the + * flow. The engine strips `status` for a non-system caller, the step succeeds + * with a warning, and the run completes. + * + * Before the run's answer carried the drop (origin/main 04c35f09, and the + * ablation leg of this branch, which strips the carry): the click answered + * a plain success — no word that `status` never landed — while the record + * stayed `draft`. The answer now + * carries `droppedFields`, the data engine's own drop events; the outcome + * (`success`, `summary`) is unchanged, and a click whose write drops nothing + * answers without the member. + * + * ⚠️ This suite resolves `@objectstack/runtime` and + * `@objectstack/service-automation` through their BUILT `dist/`. Rebuild both + * before trusting a run of this file — and especially an ablated one. + */ + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; + +import { defineStack } from '@objectstack/spec'; +// The harness loads these two inside a function body; paid here, during collection, not in a clocked window. +import '@objectstack/service-datasource'; +import '@objectstack/service-automation'; +import { ObjectSchema, Field } from '@objectstack/spec/data'; +import type { Flow } from '@objectstack/spec/automation'; + +import { bootStack, type VerifyStack } from './harness.js'; +import { warmUpBoot } from './boot-warm-up.testkit.js'; + +// Booting the full in-process stack runs well past vitest's 5s default. +const BOOT_TIMEOUT = 120_000; + +// The boot's first load, paid during collection (see `boot-warm-up.testkit.ts`). +await warmUpBoot({ automation: true }, { requires: ['automation'] }); + +const REPORT = 'afd_report'; + +/** `status` is read-only to every non-system writer; `note` is writable. */ +const Report = ObjectSchema.create({ + name: REPORT, + sharingModel: 'public_read_write', + label: 'Report', + pluralLabel: 'Reports', + fields: { + name: Field.text({ label: 'Name', required: true }), + status: Field.text({ label: 'Status', readonly: true }), + note: Field.text({ label: 'Note' }), + }, +}); + +/** start → update_record(the clicked report, `fields`) → end. */ +function writer(name: string, fields: Record): Flow { + return { + name, + label: name, + type: 'autolaunched', + status: 'active', + runAs: 'user', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { + id: 'write', + type: 'update_record', + label: 'Write', + config: { objectName: REPORT, filter: { id: { dialect: 'cel', source: 'record.id' } }, fields }, + }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'write' }, + { id: 'e2', source: 'write', target: 'end' }, + ], + } as Flow; +} + +const SUBMIT = 'afd_submit'; +const ADD_NOTE = 'afd_add_note'; + +const fixtureStack = defineStack({ + manifest: { + id: 'com.objectstack.verify.action-flow-dropped-fields', + namespace: 'afd', + version: '0.0.0', + type: 'app', + name: 'Action Flow Dropped Fields Fixture', + description: 'A report whose status is read-only, and two record buttons whose flows write it.', + }, + requires: ['automation'], + objects: [Report], + flows: [writer(SUBMIT, { status: 'submitted', note: 'submitted by the button' }), writer(ADD_NOTE, { note: 'noted by the button' })], + actions: [ + { name: 'submit_for_approval', label: 'Submit for approval', objectName: REPORT, type: 'flow', target: SUBMIT, locations: ['record_header'] }, + { name: 'add_note', label: 'Add note', objectName: REPORT, type: 'flow', target: ADD_NOTE, locations: ['record_header'] }, + ], +} as never); + +let stack: VerifyStack; +let admin: string; + +beforeAll(async () => { + stack = await bootStack(fixtureStack as never, { automation: true }); + // The seeded dev admin: a signed-in person, NOT the system principal, so the + // engine strips a read-only field it writes. + admin = await stack.signIn(); +}, BOOT_TIMEOUT); + +afterAll(async () => { + await stack?.stop().catch(() => undefined); +}); + +/** A fresh `draft` report, seeded by the system principal (who may write `status`). */ +async function draftReport(name: string): Promise { + const row = await stack.hooks.run(REPORT, 'insert', { name, status: 'draft' }, { system: true }); + return String((row as { id: unknown }).id); +} + +async function reportRow(id: string): Promise> { + const [row] = await stack.rows(REPORT, { id }); + return row as Record; +} + +describe('a record button whose flow drops a read-only field (#32861, the #32666 shape)', () => { + it('answers the drop to the person who clicked: droppedFields names `status`, and the run still succeeded', async () => { + const id = await draftReport('drop'); + + const answer = (await stack.actions.run(REPORT, 'submit_for_approval', { as: admin, recordId: id })) as Record; + + expect(answer.success).toBe(true); + expect(answer.droppedFields).toEqual([{ object: REPORT, fields: ['status'], reason: 'readonly' }]); + // The outcome semantics are unchanged: a dropped field is not a failure. + expect(answer.summary?.failed).toBe(0); + // The record: `status` never landed, the writable field beside it did. + const row = await reportRow(id); + expect(row.status).toBe('draft'); + expect(row.note).toBe('submitted by the button'); + }); + + it('a click whose write drops nothing answers without the member', async () => { + const id = await draftReport('clean'); + + const answer = (await stack.actions.run(REPORT, 'add_note', { as: admin, recordId: id })) as Record; + + expect(answer.success).toBe(true); + expect('droppedFields' in answer).toBe(false); + expect((await reportRow(id)).note).toBe('noted by the button'); + }); +});