-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathaction-execution.ts
More file actions
1670 lines (1592 loc) · 85.4 KB
/
Copy pathaction-execution.ts
File metadata and controls
1670 lines (1592 loc) · 85.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
/**
* Action-execution subsystem — extracted dispatcher helpers (ADR-0076 D11
* step ③, PR-8). The shared machinery behind server-registered business
* actions: declaration collection/resolution, param enforcement
* (ADR-0104), permission/exposure gates, the engine facade + session shape
* handlers receive, invocation, and the `callData` protocol/ObjectQL data
* bridge. Consumed by the `/actions` domain and the MCP bridge (tool
* invocation path) — extracting it is what turns those two domains into
* mechanical extractions (PR-9).
*
* Depends only on {@link ActionExecutionDeps} — a narrow slice of the
* domain deps contract. NO env-resolution state (kernel/resolver) lives
* here; that stays with the route handlers.
*/
import { validateActionParams, type ActionSession, type ResolvedActionParam } from '@objectstack/spec/ui';
import type { ExecutionContext } from '@objectstack/spec/kernel';
import type { IObjectQLEngine, ServiceSlotContract, ServiceSlotContracts } from '@objectstack/spec/contracts';
import { checkApiExposure } from './api-exposure.js';
// [#9446] The ONE #9378 status table. Imported rather than re-read here: this
// door's blanket `FLOW_FAILED` was the second of three readings of one engine
// result, and a second definition of the rule is what let the doors diverge.
import {
classifyFlowRefusal,
flowIsUnknown,
flowNotFoundMessage,
FLOW_NOT_FOUND_STATUS,
type FlowRefusalCode,
} from './flow-dispatch-status.js';
import type { FlowRunSummary } from '@objectstack/spec/automation';
// [#5138] The ONE 404 envelope a single-record path answers. Imported rather
// than re-spelled so `callData`'s ObjectQL fallback and the protocol service it
// falls back FROM cannot disagree about what "this id names no row" looks like.
// A pure factory — no service resolution — so importing it costs the fallback
// nothing on an assembly where the protocol plugin is absent, which is exactly
// when the fallback runs.
import { recordNotFoundError } from '@objectstack/metadata-protocol';
import { actorUserFromExecutionContext, resolveActorDisplayName } from './security/actor-user.js';
import type { HttpProtocolContext } from './http-dispatcher.js';
import {
GLOBAL_ACTION_OBJECT_KEY,
actionHandlerObjectKeys,
isObjectLessActionKey,
reconcileActionRegistrations as reconcileActionRegistrationsPure,
resolveActionHandlerKeys,
} from '@objectstack/objectql';
// [ADR-0110] The addressing vocabulary and the D5 reconciliation moved to
// @objectstack/objectql (the engine owns the map they describe, and its
// plugin now runs the boot inventory — AppPlugin, the previous host, is
// registered conditionally and never ran it on the `os dev` path). Runtime
// re-exports them so dispatch, the MCP bridge and existing importers keep
// reading the ONE implementation.
export {
GLOBAL_ACTION_OBJECT_KEY,
actionHandlerObjectKeys,
isObjectLessActionKey,
resolveActionHandlerKeys,
};
/** A `sys_`-prefixed object is a system table — off-limits to external MCP agents. */
export function isSystemObjectName(name: string): boolean {
return /^sys_/i.test(name);
}
/**
* Escape hatch: accept param bags that violate the declared contract, the way
* the pre-17 dispatcher did (ADR-0104 D2, 2026-07-30 addendum).
*
* Enforcement is the default. This exists for the operator whose integration
* hits an unforeseen rejection and needs it dispatching again before they can
* reach the caller's code — the violation still logs, so setting this makes the
* drift tolerated, not invisible.
*
* Spelled `OS_ALLOW_*` per Prime Directive #9 and ADR-0110 D6: an opt-OUT of a
* check that ships on, never an opt-IN to a check that ships off.
*/
function laxActionParams(): boolean {
return typeof process !== 'undefined' && process.env?.OS_ALLOW_LAX_ACTION_PARAMS === '1';
}
const _warnedActionParams = new Set<string>();
function warnActionParamsOnce(key: string, message: string): void {
if (_warnedActionParams.has(key)) return;
_warnedActionParams.add(key);
console.warn(message);
}
/**
* The dispatcher facilities the action subsystem may touch.
*
* [#4127 batch 4] `resolveService` is split the same way as the one on
* `DomainHandlerDeps`. This is a NARROWER re-declaration of the same facility
* and it kept returning `any` after the main one stopped — the third copy of
* the pattern, alongside `ResolveOptions` in security/resolve-execution-context.
* A lookup facade has to be typed everywhere it is re-declared, or the copy
* that still says `any` becomes the way around all the others.
*
* [#5155] Both lookups take the REQUEST as their first parameter, for the
* reason spelled out on `DomainHandlerDeps` (of which this is the narrow view
* `HttpDispatcher.actionExecutionDeps` hands out): the object is shared by
* every request the host serves, so the kernel to resolve against is the
* request's, never the facade's.
*/
export interface ActionExecutionDeps {
resolveService<K extends keyof ServiceSlotContracts>(context: HttpProtocolContext, name: K, environmentId?: string): Promise<ServiceSlotContract<K> | undefined>;
resolveService(context: HttpProtocolContext, name: string, environmentId?: string): any;
getObjectQL(context: HttpProtocolContext, environmentId?: string): Promise<IObjectQLEngine | null>;
}
/**
* Direct data service dispatch — replaces broker.call('data.*').
* Tries protocol service first (supports expand/populate), falls back to ObjectQL.
*
* @param requestContext - The request being served (#5155). Carries the kernel
* every service lookup below resolves against; see
* {@link HttpProtocolContext.kernel}.
* @param dataDriver - Optional environment-scoped driver to use instead of kernel default
* @param scopeId - Optional project ID for scoped service resolution (SharedProjectPlugin mode)
*/
export async function callData(deps: ActionExecutionDeps,
requestContext: HttpProtocolContext,
action: string,
params: any,
dataDriver?: any,
scopeId?: string,
executionContext?: ExecutionContext,
): Promise<any> {
// ── Object-level API exposure gate (ADR-0049, #1889) ─────
// Honour the object's `apiEnabled` / `apiMethods` declarations for
// external traffic. System/internal contexts bypass — these flags
// govern API *exposure*, not internal engine self-writes.
if (!executionContext?.isSystem && params?.object) {
let def: any;
try {
const meta = await deps.resolveService(requestContext, 'metadata', scopeId);
def = await (meta as any)?.getObject?.(params.object);
} catch {
def = undefined; // fall open to schema defaults (apiEnabled=true)
}
const gate = checkApiExposure(def, action);
if (!gate.allowed) {
throw { statusCode: gate.status ?? 403, message: gate.reason ?? 'API access denied' };
}
}
const protocol = await deps.resolveService(requestContext, 'protocol', scopeId);
const qlService = dataDriver ?? await deps.getObjectQL(requestContext, scopeId);
const ql = qlService ?? await deps.resolveService(requestContext, 'objectql', scopeId);
const qlOpts = executionContext ? { context: executionContext } : undefined;
const findOpts = (extra?: any) => {
const base = qlOpts ? { ...qlOpts } : {};
return extra ? { ...base, ...extra } : (qlOpts ? base : undefined);
};
if (action === 'create') {
// Prefer the protocol service (validations + RLS + audit), mirroring
// the read paths below. The MCP bridge passes `context.dataDriver` as
// `ql`, which in the multi-env runtime is a RAW db driver with no ORM
// `insert` — so going straight to `ql.insert` broke MCP create_record
// ("ql.insert is not a function") while REST (which uses `createData`)
// worked. Routing writes through the protocol keeps them aligned.
if (protocol && typeof protocol.createData === 'function') {
return await protocol.createData({ object: params.object, data: params.data, ...(scopeId ? { environmentId: scopeId } : {}), context: executionContext });
}
if (ql && typeof ql.insert === 'function') {
const res = await ql.insert(params.object, params.data, qlOpts);
const record = { ...params.data, ...res };
return { object: params.object, id: record.id, record };
}
throw { statusCode: 503, message: 'Data service not available' };
}
if (action === 'get') {
if (protocol && typeof protocol.getData === 'function') {
return await protocol.getData({ object: params.object, id: params.id, expand: params.expand, select: params.select, context: executionContext });
}
if (ql) {
let all = await ql.find(params.object, findOpts({ where: { id: params.id }, limit: 1 }));
if (all && (all as any).value) all = (all as any).value;
if (!all) all = [];
const match = (all as any[]).find((i: any) => i.id === params.id);
// [#5138] Was `: null` — a miss resolved, and `/data` wrapped it as
// `200 { data: null }`. The protocol path this falls back from has
// answered `404 RECORD_NOT_FOUND` since #4435, so the same GET
// answered 200 or 404 depending only on whether the deployment
// registered the protocol slot — a difference the caller cannot see
// and never asked for.
if (!match) throw recordNotFoundError(params.object, params.id);
return { object: params.object, id: params.id, record: match };
}
throw { statusCode: 503, message: 'Data service not available' };
}
if (action === 'update') {
if (protocol && typeof protocol.updateData === 'function') {
return await protocol.updateData({ object: params.object, id: params.id, data: params.data, ...(scopeId ? { environmentId: scopeId } : {}), context: executionContext });
}
if (ql && params.id && typeof ql.update === 'function') {
let all = await ql.find(params.object, findOpts({ where: { id: params.id }, limit: 1 }));
if (all && (all as any).value) all = (all as any).value;
if (!all) all = [];
const existing = (all as any[]).find((i: any) => i.id === params.id);
// [#5138] Was `throw new Error('[ObjectStack] Not Found')`. That
// error carried neither `.status` nor `.statusCode`, so BOTH
// dispatcher exits fell through to their 500 fallback
// (`HttpDispatcher.errorFromThrown`, `dispatcher-plugin`'s
// `errorResponseBase`, and the endpoint executor's `errorAnswer`
// all read `.status` → `.statusCode` → 500). A caller mistake was
// reported as an internal fault and taken to the error reporter
// with it.
if (!existing) throw recordNotFoundError(params.object, params.id);
await ql.update(params.object, params.data, findOpts({ where: { id: params.id } }));
return { object: params.object, id: params.id, record: { ...existing, ...params.data } };
}
throw { statusCode: 503, message: 'Data service not available' };
}
if (action === 'delete') {
if (protocol && typeof protocol.deleteData === 'function') {
return await protocol.deleteData({ object: params.object, id: params.id, ...(scopeId ? { environmentId: scopeId } : {}), context: executionContext });
}
if (ql && typeof ql.delete === 'function') {
// [#5138] There was NO existence check here: the delete ran and the
// answer was `200 { deleted: true }` for any string in the path, so
// a typo'd id, an already-deleted row and a real deletion were
// indistinguishable — the exact shape #4435 removed from the
// protocol's `deleteData`, still live on the path that stands in
// for it. The "assume it worked" answer is the worst of the three
// this fallback gave, because an integrator reading 200 records the
// cleanup as done.
//
// The existence PROBE is a `find`, not a read of what `ql.delete`
// returned. `deleteData` can read its result because `IDataDriver.
// delete` declares `Promise<boolean>` ("true if deleted, false if
// not found"); `ql` here is the ObjectQL ENGINE (or, on the MCP
// multi-env path, a raw driver), and `IDataEngine.delete` declares
// `Promise<any>` — the engine passes its driver's result through
// the hook chain and returns `opCtx.result`. Testing that for
// `=== false` would be reading a signal the contract does not
// promise, which fails silently in the direction this issue is
// about: back to reporting a delete that removed nothing. The probe
// is the same one the sibling `get`/`update` fallbacks already run.
let all = await ql.find(params.object, findOpts({ where: { id: params.id }, limit: 1 }));
if (all && (all as any).value) all = (all as any).value;
if (!all) all = [];
const existing = (all as any[]).find((i: any) => i.id === params.id);
if (!existing) throw recordNotFoundError(params.object, params.id);
await ql.delete(params.object, findOpts({ where: { id: params.id } }));
// [#5581] `success`, not `deleted`. The success body was the other
// half of the same "one `callData`, two answers" defect #5138 fixed
// on the not-found side: the protocol path returns the SPEC's shape
// (`DeleteDataResponseSchema` — `{ object, id, success }`,
// `packages/spec/src/api/protocol.zod.ts:472`) and this fallback
// returned `{ object, id, deleted: true }` — `success` missing, and
// `deleted` declared nowhere in the spec. A client written against
// the declared shape read `success === undefined` off an HTTP 200
// on any deployment that did not register the `protocol` slot, and
// had no way to tell which path had served it.
//
// The spec is the authority, not this literal: `success` is what
// `DeleteDataResponseSchema` declares, what the protocol path has
// returned since #4435, and what the public HTTP docs already
// document (`content/docs/protocol/kernel/http-protocol.mdx`).
// Teaching consumers to read `success ?? deleted` would have been
// the contract-first-forbidden shape — two spellings of one fact,
// kept alive by every reader.
return { object: params.object, id: params.id, success: true };
}
throw { statusCode: 503, message: 'Data service not available' };
}
if (action === 'query' || action === 'find') {
// Build query: use explicit params.query if provided, otherwise extract
// query fields from params. Shared by both paths below — the fallback
// must serve the SAME request the protocol path would have served.
const query = params.query || (() => {
const { object, ...rest } = params;
return rest;
})();
if (protocol && typeof protocol.findData === 'function') {
return await protocol.findData({ object: params.object, query, context: executionContext });
}
if (ql) {
// [#4386] This fallback used to pass only `{ context }` — the
// caller's entire query (where/orderBy/limit/…) was dropped and the
// FULL table came back as an ordinary-looking `{ records, total }`.
// Serve the canonical QueryAST keys both possible recipients
// actually execute (`ql` here is the engine, or on the MCP
// multi-env path a RAW driver reading a QueryAST — same canonical
// keys by design). Anything else — wire spellings (`sort`,
// `select`, …) that need the protocol layer's fold/lowering, or
// capabilities a raw driver would silently drop (`search`,
// `expand`) — is refused loudly rather than part-served: a
// fallback that cannot reproduce the query's semantics must not
// pretend to (route-ownership rule 3).
const FALLBACK_QUERY_KEYS = ['where', 'fields', 'orderBy', 'limit', 'offset'];
const bag: any = {};
const unservable: string[] = [];
for (const [k, v] of Object.entries((query ?? {}) as Record<string, unknown>)) {
if (v == null) continue;
// `context` is SERVER-derived on this path, same as findData's
// unconditional `delete options.context` — a caller-supplied
// one is dropped, never an error and never honoured.
if (k === 'context') continue;
if (FALLBACK_QUERY_KEYS.includes(k)) bag[k] = v;
else unservable.push(k);
}
if (unservable.length > 0) {
throw {
statusCode: 501,
message: `Data query fallback cannot serve ${unservable.map((k) => `'${k}'`).join(', ')}: ` +
'the protocol service (metadata-protocol plugin) is not registered, and without its ' +
`normalization this path serves only canonical QueryAST keys (${FALLBACK_QUERY_KEYS.join(', ')}).`,
};
}
let all = await ql.find(params.object, findOpts(bag));
if (!Array.isArray(all) && all && (all as any).value) all = (all as any).value;
if (!all) all = [];
return { object: params.object, records: all, total: all.length };
}
throw { statusCode: 503, message: 'Data service not available' };
}
if (action === 'aggregate') {
// Aggregate MUST run through the ObjectQL ENGINE (never the raw
// `dataDriver` the MCP bridge threads through for the other verbs):
// only the engine's middleware chain injects RLS/tenant scoping and
// the FLS aggregate-input gate. A raw driver.aggregate() would
// evaluate the query verbatim over every row.
//
// At least one aggregation is REQUIRED: with neither aggregations
// nor groupBy the engine's in-memory path degrades to raw rows,
// and the FLS result masker does not cover the `aggregate` op —
// grouped/aggregated output must stay the only thing this action
// can ever return.
if (!Array.isArray(params.aggregations) || params.aggregations.length === 0) {
throw { statusCode: 400, message: 'aggregate requires at least one aggregation' };
}
const engine = (await deps.getObjectQL(requestContext, scopeId))
?? await deps.resolveService(requestContext, 'objectql', scopeId).catch(() => null);
if (engine && typeof engine.aggregate === 'function') {
const rows = await engine.aggregate(
params.object,
{
...(params.where ? { where: params.where } : {}),
...(params.groupBy ? { groupBy: params.groupBy } : {}),
...(params.aggregations ? { aggregations: params.aggregations } : {}),
...(params.timezone ? { timezone: params.timezone } : {}),
...(executionContext ? { context: executionContext } : {}),
},
);
return { object: params.object, rows: rows ?? [] };
}
throw { statusCode: 503, message: 'Data service not available' };
}
// [#5856] `batch` deliberately has NO arm here. It used to answer
// `{ object, results: [] }` — an HTTP 200 whose body a consumer cannot
// tell apart from "the batch ran and matched nothing" — on a path that
// opened no transaction and wrote nothing. Its safety was never its own:
// no caller of `callData` can spell `batch` (`domains/data.ts` compares
// `parts[1]` against the literal `'query'`; `domains/mcp.ts`,
// `domains/actions.ts` and `invokeBusinessAction` pass literals; the
// declarative endpoint executor is bounded by
// `ApiEndpointSchema.objectParams.operation`, a closed enum of
// find/get/create/update/delete; and `callData` is not part of this
// package's export surface), so the arm's only live effect was to
// pre-decide — wrongly — what the FIRST caller to arrive would get:
// a silent success where every other unhandled action gets a loud
// refusal. Removed under ADR-0049 enforce-or-remove, so `batch` falls to
// the same 400 as any other unknown action. Batching itself is untouched
// and keeps its ONE owner (route-ownership rule 1): both the atomic
// cross-object `POST /batch` and the per-object `POST /data/:object/batch`
// are mounted by `@objectstack/rest`'s `registerBatchEndpoints`
// (ADR-0119) — which is exactly why this dispatcher answers
// `capabilities.transactionalBatch: false` (#5672,
// `http-dispatcher.ts`). Pinned by
// `action-execution-calldata-batch-retired.test.ts`.
throw { statusCode: 400, message: `Unknown data action: ${action}` };
}
/**
* [ADR-0066 D4] Shared capability gate for an action invocation. Returns a
* human-readable error string when the caller's `systemPermissions` don't
* cover the action's declared `requiredPermissions`, or `null` when allowed.
* System/engine self-invocation (`isSystem`) bypasses; an action without
* `requiredPermissions` is ungated. Single-sourced so the REST `/actions/...`
* route and the MCP `run_action` bridge enforce the SAME declaration.
*/
export function actionPermissionError(_deps: ActionExecutionDeps, actionDef: any, ec: any, objectName?: string): string | null {
const required: string[] = Array.isArray(actionDef?.requiredPermissions)
? actionDef.requiredPermissions
: [];
if (required.length === 0) return null;
if (ec?.isSystem) return null;
const held = new Set<string>(ec?.systemPermissions ?? []);
const missing = required.filter((perm) => !held.has(perm));
if (missing.length === 0) return null;
const on = objectName ? ` on '${objectName}'` : '';
return (
`Action '${actionDef?.name ?? 'unknown'}'${on} requires capability ` +
`[${required.join(', ')}] — caller is missing [${missing.join(', ')}]`
);
}
/**
* [ADR-0126 §8 item 2] The activation refusal a DISABLED packaged action is
* answered with — `409 ACTION_DISABLED`.
*
* ## Why 409, and why its own code
*
* The artifact exists and is well-formed; only its current STATE conflicts with
* running it, and flipping the switch makes the identical request succeed —
* 409's meaning, and the same reading `FLOW_DISABLED` got in the #9378 table.
* The code is the action's own rather than a borrowed `FLOW_DISABLED`: a
* `script` action refused under a code naming a flow would send an operator
* looking for a flow that does not exist, and a machine-readable surface must
* not lie about which artifact it is talking about (Route & surface ownership
* rule 4). It joins the `*_DISABLED` family already registered in the ADR-0112
* ledger (`FLOW_DISABLED`, `OBJECT_API_DISABLED`, `OBJECT_PACKAGE_DISABLED`) —
* one census row, no new condition class.
*/
export const ACTION_DISABLED_CODE = 'ACTION_DISABLED';
export const ACTION_DISABLED_STATUS = 409;
/** The shape both doors serve — the wire envelope's three fields (ADR-0112). */
export interface DisabledActionRefusal {
code: typeof ACTION_DISABLED_CODE;
status: typeof ACTION_DISABLED_STATUS;
message: string;
}
/**
* [ADR-0126 §8 item 2] THE CONSULT POINT for the action activation ledger —
* asked by every door that dispatches a DECLARED action.
*
* ## Where this sits, and why it is not one seam deeper
*
* The flow leg could put its consult at `execute()`, "the one seam every entry
* path crosses". Actions have no such seam that can answer the question: the
* two per-type primitives below it (`executeRegisteredAction` →
* `ql.executeAction`, and `dispatchFlowAction`) are addressed by HANDLER KEY
* and by target flow name respectively, and ADR-0110 D2 is explicit that a
* registration key is NOT an action's identity ("`AppPlugin` auto-registers
* body actions under `name`, while user code registers a target-bound script
* action under `target`"). The ledger addresses the declarative NAME, so the
* consult belongs exactly where a resolved DECLARATION exists: the REST
* `/actions` door and the MCP `run_action` bridge, each pinned by its own test.
* Placing it lower would silently miss every target-bound action — a gate that
* looks present and is not.
*
* ⚠️ ObjectQL's `ScopedRepo.execute()` — a hook/action BODY reaching another
* handler in-process via `ctx.api.object(x).execute(...)` — is the third
* `executeAction` caller and is deliberately NOT a consult point: it dispatches
* by key with no declaration, carries no caller identity, and is package code
* calling package code (the class ADR-0126 §2 keeps outside the model for
* `hook`). Recorded rather than left to be discovered.
*
* ## Ordering: authorization first, activation second
*
* Both doors call this AFTER the ADR-0066 D4 capability gate. An unentitled
* caller therefore learns nothing about which packaged actions this
* installation has switched off — the same reason `/automation`'s gates run
* ahead of its service probe (a 403 must not become an oracle).
*
* Returns `undefined` when the action may run. An engine that cannot answer
* (no `isActionEnabled` — a host on an older engine, or a test double) yields
* `undefined` too: absence of a ledger means the packaged default, ACTIVE
* (ADR-0126 §4), which is what a stock boot has always done.
*/
export function disabledActionRefusal(
_deps: ActionExecutionDeps,
ql: any,
actionDef: any,
): DisabledActionRefusal | undefined {
const name = actionDef?.name;
if (typeof name !== 'string' || name === '') return undefined;
if (typeof ql?.isActionEnabled !== 'function') return undefined;
if (ql.isActionEnabled(name) !== false) return undefined;
// The SENTENCE is the engine's (`describeDisabledAction`), so both doors
// state one refusal instead of two that agree today; the fallback covers an
// engine that answers the boolean but not the prose.
const message = typeof ql.describeDisabledAction === 'function'
? String(ql.describeDisabledAction(name))
: `Action '${name}' is disabled for this installation (ADR-0126 §8).`;
return { code: ACTION_DISABLED_CODE, status: ACTION_DISABLED_STATUS, message };
}
/**
* [#2849 / ADR-0011] AI-exposure gate for the MCP action surface. Returns a
* human-readable error string unless the action's author explicitly opted it
* into the AI surface with `ai.exposed: true`, or `null` when exposed.
*
* This gate is the REAL agent-facing boundary for actions: script/body
* handlers execute as TRUSTED application code (the engine facade and
* `ctx.api` run `isSystem` — see {@link buildActionExecutionContext}), so once
* invoked, a body's reads/writes are NOT bounded by the caller's RLS/FLS or an
* agent's data ceiling (ADR-0090 D10). The author's explicit opt-in — not a
* data-layer backstop — therefore decides what AI may trigger. Fail-closed by
* default.
*/
export function actionAiExposureError(_deps: ActionExecutionDeps, actionDef: any, objectName?: string): string | null {
if (actionDef?.ai?.exposed === true) return null;
const on = objectName ? ` on '${objectName}'` : '';
return (
`Action '${actionDef?.name ?? 'unknown'}'${on} is not exposed to AI — ` +
`the app author must opt it in with \`ai: { exposed: true, description: … }\``
);
}
/**
* Whether an action has a headless invocation path (so MCP can run it).
* Mirrors the supported-type set of the (now cloud-side) action-tools
* bridge: `script` needs a handler binding (`target`) or an inline `body`;
* `flow` needs a `target` and an automation service. UI-only types
* (`url`, `modal`, `form`) and `api` have no server dispatch here.
*/
export function isHeadlessInvokableAction(_deps: ActionExecutionDeps, action: any, hasAutomation: boolean): boolean {
const type: string = action?.type ?? 'script';
if (type === 'script') return Boolean(action?.target || action?.body);
if (type === 'flow') return Boolean(action?.target) && hasAutomation;
return false;
}
/**
* The action types a headless caller can actually invoke through a server
* dispatch — the two {@link isHeadlessInvokableAction} accepts. Kept next to
* it so the predicate and the explanation below can never drift apart.
*/
const SERVER_DISPATCHED_ACTION_TYPES: ReadonlySet<string> = new Set(['script', 'flow']);
/**
* Explain why a declared action has NO server-side dispatch — `null` when it
* does have one (`script` / `flow`).
*
* The spec is explicit (`packages/spec/src/ui/action.zod.ts`): every
* non-`script` type dispatches on `target`, and only `flow` has a server-side
* runner (the automation engine). `url` / `modal` / `form` are renderer
* navigation and `api` names a *different* endpoint the client calls itself —
* none of them is the script-handler registry. Pre-#3915 the REST route had
* no type branching at all, so every one of them fell through to
* `executeAction` and came back as the misleading
* `Action '' on object '*' not found`. Naming the type and the prescription
* turns that dead end into an actionable 400.
*/
export function headlessActionTypeError(_deps: ActionExecutionDeps, action: any, objectName?: string): string | null {
const type: string = action?.type ?? 'script';
if (SERVER_DISPATCHED_ACTION_TYPES.has(type)) return null;
const name: string = action?.name ?? 'unknown';
const on = objectName ? ` on '${objectName}'` : '';
const target: string | undefined = typeof action?.target === 'string' ? action.target : undefined;
if (type === 'api') {
return (
`Action '${name}'${on} is \`type: 'api'\` — it dispatches on \`target\`, ` +
`not through the action registry. Call ${target ? `\`${target}\`` : 'its `target` endpoint'} directly` +
`${typeof action?.method === 'string' ? ` (${action.method})` : ''}.`
);
}
return (
`Action '${name}'${on} is \`type: '${type}'\` — a client-side action with no server dispatch. ` +
`The renderer opens its \`target\`${target ? ` ('${target}')` : ''}; there is nothing for the server to run.`
);
}
/**
* The automation service when this kernel has a usable one, else `null` —
* the single availability probe behind `type: 'flow'` dispatch (both the
* headless-invokability filter and the two invoke paths ask through it).
*/
export async function resolveAutomationService(deps: ActionExecutionDeps, requestContext: HttpProtocolContext, envId?: string): Promise<any | null> {
try {
// [#4127 batch 4] Was `: any`, which voided the gate here. `execute` is
// declared on IAutomationService, so this needed no contract work — only
// for someone to notice, and three grep sweeps over `domains/*.ts` never
// reached this file. The lint rule did.
const svc = await deps.resolveService(requestContext, 'automation', envId);
return svc && typeof svc.execute === 'function' ? svc : null;
} catch {
return null; // no automation service on this kernel
}
}
/** Message for a flow action on a kernel with no automation service (a 503-shaped condition). */
export function flowActionUnavailableError(action: any): string {
return `Action '${action?.name ?? 'unknown'}' is a flow but no automation service is available`;
}
/**
* The params bag a flow action hands the automation engine.
*
* Three seeds, weakest first — each only fills a key the stronger one left
* unset:
* 1. the subject record's fields, which populate a flow's named `isInput`
* variables the way the record-change trigger does;
* 2. the row id under the keys a flow author actually writes —
* `recordId` and the `<objectName>Id` camelCase alias — the SAME two
* `POST /automation/:name/trigger` seeds (`domains/automation.ts`), plus
* the action's own declared `recordIdParam` (seeded from `recordIdField`,
* default `id`) when it names a third key;
* 3. the caller's explicit action params, which win outright.
*
* Seed 2 is the one #3915's first pass missed, and only a real run caught it:
* the params bag carried the record's `id` but never `recordId`, so the CRM's
* own `crm_convert_lead` action — which declares `recordIdParam: 'recordId'`
* and whose flow reads `{recordId}` — reached the engine and died at its first
* node ("1 filter condition(s) resolved to nothing"), while the identical run
* through `/automation/crm_convert_lead_wizard/trigger` succeeded. A declared
* `recordIdParam` that nothing honours is the `declared ≠ enforced` shape in
* miniature.
*/
export function seedFlowActionParams(_deps: ActionExecutionDeps,
action: any,
input: {
objectName: string;
record: Record<string, unknown>;
params: Record<string, unknown>;
recordId?: string;
},
): Record<string, unknown> {
const { objectName, record, params, recordId } = input;
const seeded: Record<string, unknown> = { ...record };
// `recordIdField` names the row field whose value seeds the key (default
// `id`) — a declaration may want a non-id value (spec: `token` for
// revoke-session). Fall back to the explicit recordId when the record
// never loaded (a record-less / new-record invocation).
const idField: string = typeof action?.recordIdField === 'string' && action.recordIdField
? action.recordIdField
: 'id';
const rowId: unknown = record?.[idField] ?? (idField === 'id' ? recordId : undefined);
if (rowId != null) {
const keys = new Set<string>(['recordId']);
if (objectName && objectName !== 'global') {
keys.add(`${objectName.replace(/_([a-z])/g, (_m: string, c: string) => c.toUpperCase())}Id`);
}
if (typeof action?.recordIdParam === 'string' && action.recordIdParam) {
keys.add(action.recordIdParam);
}
for (const key of keys) {
if (seeded[key] === undefined) seeded[key] = rowId;
}
}
return { ...seeded, ...params };
}
/**
* Brand for {@link FlowActionRefusal} — `Symbol.for`, so recognition keeps
* working even if two module instances of this file ever coexist (src vs
* dist), where an `instanceof` would silently answer false.
*/
const FLOW_ACTION_REFUSAL_BRAND = Symbol.for('objectstack.runtime.flowActionRefusal');
/**
* The run artefacts a failed flow dispatch carries beside its status and code
* — EXACTLY the two fields the trigger door ships in `error.details` on its
* own `400 FLOW_FAILED` arm (`domains/automation.ts`), same names, same
* source (`AutomationResult.errorMessage` / `.summary`). A third key here is
* a contract widening the #9585 ruling does not cover.
*/
export interface FlowActionRunDetails {
/** The flow AUTHOR's own failure text (`flow.errorMessage`). */
errorMessage?: string;
/** The run's per-node accounting — WHICH node failed (#4354). */
summary?: FlowRunSummary;
}
/**
* [#9585] The typed refusal carrier for a flow ACTION that ran and failed.
*
* Maintainer ruling, 2026-08-19 (Option B on #9585): the `/actions` door must
* deliver the flow author's `errorMessage` and the run `summary` the way the
* trigger door already does — but this door THROWS, and the shared resolver
* (`resolveThrownHttpError`, `@objectstack/types`) builds `details` from a
* closed list that deliberately drops a thrown `.details` (#8016 / #9106).
* Widening that list would let ANY throw anywhere declare wire payload — the
* exact thing #9106 narrowed `code` to prevent, and the rejected Option A.
* So the widening stays out of the shared rule: this named, closed carrier is
* recognised by the `/actions` handler AHEAD of its generic catch
* (`domains/actions.ts`, via {@link isFlowActionRefusal}) and mapped to
* `deps.error(message, status, { code, ...runDetails })` — the trigger door's
* own exit, byte for byte.
*
* A door that does NOT recognise it (the MCP `run_action` bridge, or any
* future caller of {@link dispatchFlowAction}) still serves it exactly as it
* served the plain throw this replaces: `status`, `code` and `message` are
* stamped identically, so `resolveThrownHttpError` reads the same
* `400 FLOW_FAILED` and the same text, and only the run details stay behind.
* Degrading to yesterday's answer — never to a different one — is what makes
* this carrier safe to throw on a path two transports share.
*/
export class FlowActionRefusal extends Error {
/** HTTP status this refusal answers with — the #9378 table's 400 row. */
readonly status: number;
/** ADR-0112 `error.code` — registered, never minted here. */
readonly code: FlowRefusalCode;
/** The two run artefacts the door carries into `error.details`. */
readonly runDetails: FlowActionRunDetails;
constructor(
message: string,
refusal: { status: number; code: FlowRefusalCode },
runDetails: FlowActionRunDetails,
) {
super(message);
this.name = 'FlowActionRefusal';
this.status = refusal.status;
this.code = refusal.code;
this.runDetails = runDetails;
(this as Record<PropertyKey, unknown>)[FLOW_ACTION_REFUSAL_BRAND] = true;
}
}
/**
* Recognition predicate for {@link FlowActionRefusal} — the `/actions`
* handler asks this BEFORE its generic catch logic runs. Brand-based rather
* than `instanceof` (see {@link FLOW_ACTION_REFUSAL_BRAND}); a foreign object
* that merely copies the field names is not recognised, so no script handler
* can impersonate the flow door's channel by throwing a lookalike.
*/
export function isFlowActionRefusal(e: unknown): e is FlowActionRefusal {
return typeof e === 'object' && e !== null
&& (e as Record<PropertyKey, unknown>)[FLOW_ACTION_REFUSAL_BRAND] === true;
}
/**
* Dispatch a `type: 'flow'` action through the automation service.
*
* The ONE implementation both headless surfaces share — the MCP `run_action`
* tool and the REST `/actions/:object/:action` route (#3915, which is exactly
* the asymmetry that let this branch exist on only one of them). Throws on a
* missing automation service and converts a refused or failed dispatch into a
* throw so both callers report failure the same way; returns the raw
* automation result otherwise.
*
* [#9446] **The refusal it throws is the #9378 table, read from the ONE
* definition** (`./flow-dispatch-status.js`) that the trigger door reads too:
*
* | engine exit | this door answers |
* |------------------------|----------------------------|
* | flow not found | `404` |
* | flow disabled | `409` `FLOW_DISABLED` |
* | flow has no start node | `422` `FLOW_NO_START_NODE` |
* | ran and failed | `400` `FLOW_FAILED` |
*
* Maintainer ruling (2026-08-18, verbatim 「同意」): the table is a property of
* the flow-dispatch CONTRACT, not of the trigger route, so this door converges
* on it rather than keeping its own reading. It used to map EVERY
* `success: false` to `400 FLOW_FAILED` under a comment asserting "The flow
* RAN and rejected" — a false statement for the two never-dispatched exits it
* caught, told to a caller whose only machine-readable signal is that code.
*
* The never-dispatched throws carry `status` and `code` and the route serves
* them through `errorFromThrown`; `error.details` there is whatever
* `resolveThrownHttpError` reads off a thrown value, and that resolver's
* closed list stays untouched (#8016 / #9106). [#9585] The ran-and-failed row
* is the one exception, by maintainer ruling: it throws the typed
* {@link FlowActionRefusal} carrier, which the `/actions` handler recognises
* ahead of its generic catch and serves with the trigger door's own
* `errorMessage` / `summary` details — see the carrier's doc for the whole
* mechanism and the fallback story.
*
* Forwarding the caller's identity (rather than just executing the flow) is
* what lets a `runAs: 'user'` flow enforce RLS as the invoker instead of
* falling into the user-less UNSCOPED path (#2849, ADR-0049 / #1888; mirrors
* the record-change trigger's context shape).
*
* The params bag is seeded exactly like `POST /automation/:name/trigger`
* (`domains/automation.ts`) — see {@link seedFlowActionParams}. Invoking a
* flow ACTION and triggering its flow directly must land the same run, or
* "the actions endpoint dispatches flows for you" is a claim the runtime
* doesn't keep.
*/
export async function dispatchFlowAction(deps: ActionExecutionDeps,
requestContext: HttpProtocolContext,
action: any,
wiring: {
objectName: string;
record: Record<string, unknown>;
params: Record<string, unknown>;
recordId?: string;
ec: any;
envId?: string;
},
): Promise<any> {
const { objectName, record, params, recordId, ec, envId } = wiring;
const automation = await resolveAutomationService(deps, requestContext, envId);
if (!automation) {
throw new Error(flowActionUnavailableError(action));
}
// [#9446] Row 1 of the table, answered by the SAME optional `getFlow`
// registry probe the trigger door uses — the engine's not-found exit
// carries no classification, so this is the only way to read it that is not
// a regex over its message. A service that omits `getFlow` cannot be asked
// and dispatches as before.
if (await flowIsUnknown(automation, action.target)) {
const err: any = new Error(flowNotFoundMessage(action.target));
err.status = FLOW_NOT_FOUND_STATUS;
throw err;
}
// Pass a proper AutomationContext (the engine never read the former
// `triggerData` envelope).
const result: any = await automation.execute(action.target, {
record,
...(isObjectLessActionKey(objectName) ? {} : { object: objectName }),
userId: ec?.userId,
...(Array.isArray(ec?.positions) && ec.positions.length ? { positions: ec.positions } : {}),
...(Array.isArray(ec?.permissions) && ec.permissions.length ? { permissions: ec.permissions } : {}),
...(ec?.tenantId ? { tenantId: ec.tenantId } : {}),
params: seedFlowActionParams(deps, action, { objectName, record, params, recordId }),
});
// [#9446] Rows 2-4, read off the PRODUCER's classification through the one
// shared table. What stood here mapped every `success: false` to
// `400 FLOW_FAILED` under a comment claiming "the flow RAN and rejected" —
// false for two of the exits it caught, and the producer's own `code` was
// available and ignored. A disabled flow invoked through an action told the
// caller a run had failed when no node ever executed.
const refusal = classifyFlowRefusal(action.target, result);
if (refusal) {
// The ran-and-failed row keeps THIS door's wording, byte for byte:
// it has been on the wire since #3962, the ruling is about status
// and code, and re-labelling a message nobody asked about would be
// an unruled change riding along. It also names the flow, which
// this door needs and the trigger door does not — the flow name is
// in that route's URL and is nowhere in this one. The two
// never-dispatched rows are NEW here, so they take the shared
// table's message: the producer's own words, exactly as the
// trigger door serves them.
if (refusal.code === 'FLOW_FAILED') {
// [#9585] The typed carrier, run artefacts read EXACTLY as the
// trigger door reads them (`domains/automation.ts`, its 400 arm):
// present when the producer wrote them, never invented. Only this
// row carries them — a never-dispatched refusal has no author
// failure text and no node log to point at, so emitting either
// there would be this door inventing run evidence for a run that
// never started, which is why the two rows below stay plain
// throws.
throw new FlowActionRefusal(
`Flow '${action.target}' failed: ${result.error ?? 'unknown error'}`,
refusal,
{
...(result.errorMessage !== undefined ? { errorMessage: result.errorMessage } : {}),
...(result.summary !== undefined ? { summary: result.summary } : {}),
},
);
}
const err: any = new Error(refusal.message);
err.status = refusal.status;
err.code = refusal.code;
throw err;
}
// An UNCLASSIFIED `success: false` still refuses, and `FLOW_FAILED` stays
// its answer — deliberately NOT the trigger door's 200. This route settled
// in #3962 that failures speak HTTP, so the alternative residual here is
// the `200 {success:true,data:{success:false}}` double envelope that
// ruling removed. `FLOW_FAILED` is what this exit has answered all along;
// narrowing which refusals reach it is this card's change, re-labelling
// the residual is not.
if (result && typeof result === 'object' && 'success' in result && result.success === false) {
const err: any = new Error(`Flow '${action.target}' failed: ${result.error ?? 'unknown error'}`);
err.status = 400;
err.code = 'FLOW_FAILED';
throw err;
}
return result ?? null;
}
/**
* [#7828] Declared semantics only. `confirmText` is UI dialog copy — the
* platform's own authoring convention (#7278/#7309) is actively moving confirm
* questions onto `description`, so keying an AI-facing safety property off
* `confirmText`'s mere presence classifies on copy the author never intended
* as a safety signal, and erodes as that migration proceeds (6 of the 14
* #7309 identity actions flipped to "not destructive" the moment their
* `confirmText` was removed). `mode: 'delete'` and `variant: 'danger'` are
* closed, declared enumerations an author sets on purpose — those remain the
* signal. Maintainer ruling: issue #7828, comment 5265943521 (Option A).
*/
export function actionLooksDestructive(_deps: ActionExecutionDeps, action: any): boolean {
if (action?.ai?.requiresConfirmation !== undefined) return Boolean(action.ai.requiresConfirmation);
return Boolean(action?.mode === 'delete' || action?.variant === 'danger');
}
export function summarizeAction(deps: ActionExecutionDeps, action: any, obj: any, objectName: string): any {
const requiresRecord =
Array.isArray(action?.locations) &&
action.locations.some(
(l: string) =>
l === 'list_item' || l === 'record_header' || l === 'record_more' || l === 'record_related',
);
const description =
(typeof action?.ai?.description === 'string' ? action.ai.description : undefined) ??
(typeof action?.label === 'string' ? action.label : undefined);
const params = summarizeActionParams(deps, action, obj);
return {
name: action.name,
objectName,
...(typeof action?.label === 'string' ? { label: action.label } : {}),
...(description ? { description } : {}),
type: action?.type ?? 'script',
requiresRecord: Boolean(requiresRecord),
requiresConfirmation: actionLooksDestructive(deps, action),
...(params.length > 0 ? { params } : {}),
};
}
export function jsonTypeOf(_deps: ActionExecutionDeps, t: string | undefined): 'string' | 'number' | 'boolean' | 'array' {
switch (t) {
case 'number': case 'currency': case 'percent': case 'rating': case 'slider': case 'autonumber':
return 'number';
case 'boolean': case 'toggle':
return 'boolean';
case 'multiselect': case 'checkboxes': case 'tags':
return 'array';
default:
return 'string';
}
}
export function summarizeActionParams(deps: ActionExecutionDeps, action: any, obj: any): any[] {
const fields: Record<string, any> = obj?.fields ?? {};
const out: any[] = [];
for (const p of (Array.isArray(action?.params) ? action.params : [])) {
const fieldRef: string | undefined = p?.field;
const field = fieldRef ? fields[fieldRef] : undefined;
const name: string | undefined = p?.name ?? fieldRef;
if (!name) continue;
const type = jsonTypeOf(deps, p?.type ?? field?.type);
const label = typeof p?.label === 'string' ? p.label : field?.label;
const help = p?.helpText ?? field?.description;
const description = [label, help].filter(Boolean).join(' — ') || undefined;
const optionSource = p?.options ?? field?.options;
const enumVals = Array.isArray(optionSource)
? optionSource
.map((o: any) => (typeof o === 'string' ? o : o?.value))
.filter((v: any): v is string => typeof v === 'string')
: [];
out.push({
name,
type,
required: Boolean(p?.required ?? field?.required ?? false),
...(description ? { description } : {}),
...(enumVals.length > 0 ? { enum: enumVals } : {}),
});
}
return out;
}
/**
* Resolve an action's declared `params[]` to their effective value-shape
* inputs (ADR-0104 D2). A field-backed param inherits type/multiple/
* options/required from the referenced object field; an inline param
* carries them directly (inline overrides win). `obj` is the action's
* parent object schema (holds `.fields`); pass `undefined` for a global
* action with only inline params.
*/
export function resolveDeclaredActionParams(_deps: ActionExecutionDeps, action: any, obj: any): ResolvedActionParam[] {
const fields: Record<string, any> = obj?.fields ?? {};
const out: ResolvedActionParam[] = [];
for (const p of (Array.isArray(action?.params) ? action.params : [])) {
const fieldRef: string | undefined = p?.field;
const field = fieldRef ? fields[fieldRef] : undefined;
const name: string | undefined = p?.name ?? fieldRef;
if (!name) continue;
out.push({
name,
type: p?.type ?? field?.type,
multiple: p?.multiple ?? field?.multiple,
required: Boolean(p?.required ?? field?.required ?? false),
options: p?.options ?? field?.options,
});
}
return out;
}
/**
* Enforce an action's declared param contract against the request bag
* BEFORE the handler runs (ADR-0104 D2). Returns a `400`-worthy error message
* when the contract is violated, `null` when the bag conforms.
*
* **Strict by default since 17.0** (#3438). R3 asked for a warn-then-error
* window; the ADR's 2026-07-30 addendum declined it on the merits rather than
* postponing the flip by a major. What a violation strands here is a CALLER,
* not data: the rejection is a 400 naming the offending param and the declared
* list, delivered to the developer or agent who can fix it in one edit, and
* undoable with `OS_ALLOW_LAX_ACTION_PARAMS`. Deferring that to 18.0 would have
* charged every deployment a second upgrade ceremony to defer a break that
* costs one edited call. (D1's half went the opposite way for the opposite
* reason — it strands stored rows, which nobody can edit their way out of.)
*
* Actions that declare no `params` keep the pass-through — there is nothing to
* validate against, so existing param-less actions are untouched.
*/
export function enforceActionParams(deps: ActionExecutionDeps,