@fabricorg/platform 1.5.1 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +27 -2
  3. package/dist/actions/index.cjs +6 -6
  4. package/dist/actions/index.d.cts +79 -2
  5. package/dist/actions/index.d.ts +79 -2
  6. package/dist/actions/index.js +1 -1
  7. package/dist/certification/index.cjs +8 -7
  8. package/dist/certification/index.d.cts +1 -0
  9. package/dist/certification/index.d.ts +1 -0
  10. package/dist/certification/index.js +5 -4
  11. package/dist/{chunk-VZ6C4LXC.cjs → chunk-45OKKLNY.cjs} +17 -9
  12. package/dist/chunk-45OKKLNY.cjs.map +1 -0
  13. package/dist/{chunk-2W6FORTE.js → chunk-6QX4I45I.js} +5 -2
  14. package/dist/chunk-6QX4I45I.js.map +1 -0
  15. package/dist/chunk-D4SWRBUH.cjs +22 -0
  16. package/dist/chunk-D4SWRBUH.cjs.map +1 -0
  17. package/dist/{chunk-KIVQBZOA.cjs → chunk-DBTAUI6C.cjs} +10 -4
  18. package/dist/chunk-DBTAUI6C.cjs.map +1 -0
  19. package/dist/{chunk-DDO4EQ2J.js → chunk-EMSAFNPX.js} +3 -3
  20. package/dist/{chunk-DDO4EQ2J.js.map → chunk-EMSAFNPX.js.map} +1 -1
  21. package/dist/{chunk-JFVEPAED.js → chunk-GU3LZWJD.js} +17 -9
  22. package/dist/chunk-GU3LZWJD.js.map +1 -0
  23. package/dist/chunk-LFE74IJX.js +20 -0
  24. package/dist/chunk-LFE74IJX.js.map +1 -0
  25. package/dist/{chunk-PFKTD7V5.cjs → chunk-MCWSUGB3.cjs} +4 -4
  26. package/dist/{chunk-PFKTD7V5.cjs.map → chunk-MCWSUGB3.cjs.map} +1 -1
  27. package/dist/{chunk-JG35DT2G.js → chunk-MLBALEUR.js} +5 -2
  28. package/dist/chunk-MLBALEUR.js.map +1 -0
  29. package/dist/{chunk-MC3GSVJ6.js → chunk-PDN5DOLQ.js} +17 -4
  30. package/dist/chunk-PDN5DOLQ.js.map +1 -0
  31. package/dist/{chunk-CXR6KEKQ.cjs → chunk-SNTV45LH.cjs} +5 -2
  32. package/dist/chunk-SNTV45LH.cjs.map +1 -0
  33. package/dist/{chunk-GRBZYDEV.js → chunk-WNZP53GI.js} +9 -3
  34. package/dist/chunk-WNZP53GI.js.map +1 -0
  35. package/dist/{chunk-ZBXFRJON.cjs → chunk-WQ3BYI7T.cjs} +20 -7
  36. package/dist/chunk-WQ3BYI7T.cjs.map +1 -0
  37. package/dist/{chunk-MSABJAED.cjs → chunk-XCAOO6KG.cjs} +5 -2
  38. package/dist/chunk-XCAOO6KG.cjs.map +1 -0
  39. package/dist/discovery/index.cjs +12 -0
  40. package/dist/discovery/index.cjs.map +1 -0
  41. package/dist/discovery/index.d.cts +10 -0
  42. package/dist/discovery/index.d.ts +10 -0
  43. package/dist/discovery/index.js +3 -0
  44. package/dist/discovery/index.js.map +1 -0
  45. package/dist/governance/index.d.cts +1 -0
  46. package/dist/governance/index.d.ts +1 -0
  47. package/dist/index.cjs +71 -66
  48. package/dist/index.d.cts +3 -2
  49. package/dist/index.d.ts +3 -2
  50. package/dist/index.js +9 -8
  51. package/dist/manifest/index.cjs +10 -9
  52. package/dist/manifest/index.d.cts +3 -2
  53. package/dist/manifest/index.d.ts +3 -2
  54. package/dist/manifest/index.js +4 -3
  55. package/dist/modules/index.cjs +11 -10
  56. package/dist/modules/index.d.cts +1 -0
  57. package/dist/modules/index.d.ts +1 -0
  58. package/dist/modules/index.js +3 -2
  59. package/dist/policies/index.cjs +9 -9
  60. package/dist/policies/index.d.cts +15 -1
  61. package/dist/policies/index.d.ts +15 -1
  62. package/dist/policies/index.js +1 -1
  63. package/dist/projections/index.cjs +6 -5
  64. package/dist/projections/index.d.cts +2 -1
  65. package/dist/projections/index.d.ts +2 -1
  66. package/dist/projections/index.js +2 -1
  67. package/dist/testing/index.d.cts +1 -0
  68. package/dist/testing/index.d.ts +1 -0
  69. package/package.json +11 -1
  70. package/dist/chunk-2W6FORTE.js.map +0 -1
  71. package/dist/chunk-CXR6KEKQ.cjs.map +0 -1
  72. package/dist/chunk-GRBZYDEV.js.map +0 -1
  73. package/dist/chunk-JFVEPAED.js.map +0 -1
  74. package/dist/chunk-JG35DT2G.js.map +0 -1
  75. package/dist/chunk-KIVQBZOA.cjs.map +0 -1
  76. package/dist/chunk-MC3GSVJ6.js.map +0 -1
  77. package/dist/chunk-MSABJAED.cjs.map +0 -1
  78. package/dist/chunk-VZ6C4LXC.cjs.map +0 -1
  79. package/dist/chunk-ZBXFRJON.cjs.map +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,37 @@
1
1
  # @fabricorg/platform
2
2
 
3
+ ## 1.7.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 8c7d2a1: Make policy resolution invocation-aware and record which policy snapshot was used.
8
+
9
+ - `@fabricorg/platform-host`: `resolvePolicies` now receives the new exported `ResolvePoliciesInput`, which extends `ActionExecutionAuthorizationInput` with `declaredPolicyIds`. It adds `actionInvocationId`, `invocation`, `executionReason`, and `parameters`. The `parameters` are the schema-parsed durable (post-redaction) parameters, the same value passed to `authorizeExecution`, not the caller's original input. Two invocations by the same actor for the same action can now be told apart. Existing resolvers keep working because the input only gained fields.
10
+ - `@fabricorg/platform`: new `PolicyAuthorityReference` (`snapshotId`, optional `contentHash`), an opaque consumer-defined reference that Platform does not interpret. It is an optional `authority` on `RuntimePolicyDefinition` and on `PolicyDispatchEvidence`. `evaluatePolicyDefinition` copies a definition's `authority` into the outcome's `dispatchEvidence` for code, data, and hybrid policies, including missing-evaluator blocks. Hosts persist it with the policy evaluation. Definitions without `authority` produce unchanged evidence.
11
+ - Host keeps the first persisted policy evaluation per invocation and policy, so a resolver must return the same snapshot for an `actionInvocationId` on every attempt (`initial`, `recovery`, `approval_resume`).
12
+
13
+ - 8e631b0: Actions can now refuse a submission before Host records anything for it. Before this, `submitAction` persisted an invocation's parameters before anything validated them: the action's schema ran only at execution. An action whose parameters must be checked against trusted context, such as a secret reference the tenant's secret store must hold, could refuse at execution, but the refused value was already in the invocation record. `redactActionParameters` could strip values, but it is synchronous, gets no tenant or actor, and is an option the application has to remember to wire.
14
+
15
+ - **`@fabricorg/platform`: `ActionDefinition.admitSubmission`** (optional). It is an async check that receives `ActionAdmissionInput`: `actionId`, `tenantId`, `spaceId`, `actorId`, `actorType`, the submitted `parameters` and a `signal` typed as the new structural `ActionAdmissionSignal` (so the `actions` entry still compiles without DOM or Node type libraries; Host passes a real `AbortSignal`). It answers `ActionAdmissionDecision`, which is `{ admitted: true }` or `{ admitted: false, code }`. The code must be fixed text chosen by the action, never a submitted value. `ActionContext.admittedAt` (optional) is how a handler learns that the host admitted its invocation. Module and action registration now reject an `admitSubmission` that is not a function. A host that does not know the field ignores it, so a handler that depends on admission should refuse without `ctx.admittedAt`.
16
+ - **`@fabricorg/platform-host`: ordering.** `submitAction` runs the check on every submission of an action that declares it: inline, dispatched, offline replays, and re-submissions under an existing idempotency key. It runs after entitlement and `authorize`, so an unauthorized submitter never reaches it. It is the last await before `createActionInvocation`: for such an action, provenance normalization, `composition.resolveInitiatingReleaseDigest` and runtime evidence run before it, and redaction, the parameter digest and the authorization-binding check after it. Actions without the check keep the previous order (redaction, digest and binding check before provenance normalization and the composition callback). The check gets the submission's trusted scope and actor, never scope taken from the parameters, and a copy of the parameters made for it alone. For an action with the check, Host persists its own copy, taken when `submitAction` was called, so neither the caller nor the check holds a reference to what is stored (tests "the persisted parameters are the copy that was checked …" and "a parameter getter is read exactly once …" in `tests/submission-admission.test.ts`).
17
+ - **`@fabricorg/platform-host`: one snapshot of the submission's identity.** `submitAction` now reads the scalar fields of the caller's `SubmitActionInput` (`actionId`, `tenantId`, `spaceId`, `actorId`, `actorType`, `correlationId`, `causationId`, `executionReason`, `idempotencyKey`, `authorizationBindingId`) once, before its first await, and every later step uses those values (`snapshotSubmission`, `src/submission-snapshot.ts`). Before this, Host reread the caller's object after awaiting `checkEntitlement`, `authorize` and the composition callback, so a caller that changed `tenantId`, `actorId` or `actionId` during those awaits could get an invocation persisted and executed under values that were never authorized. This affects every action (tests "changing the caller's input while admission awaits …", "… while authorize awaits …" and "the identity snapshot still applies …"). A scalar field that holds an object, a function or a symbol, a read of one that throws, or an input that is not an object makes `submitAction` throw an `Error` with a fixed message and record nothing; in each case the field does not yield a value of its declared type.
18
+ - **Parameters, provenance and binding.** For an action that declares `admitSubmission`, Host reads each of the three once, before its first await, and keeps its own copies. Parameters are copied as JSON data: `null`, strings, booleans, finite numbers, dense arrays, and objects whose prototype is `Object.prototype` or `null`; each own enumerable string-keyed property is read once, `undefined` values are left out, and symbol keys and non-enumerable properties are skipped. Anything else is refused as `invalid_parameters` before the check runs: a Proxy, a function, a symbol, a bigint, `NaN` or `Infinity`, a Date, a Map, a class instance, an ArrayBuffer, a SharedArrayBuffer, a typed array or DataView (so no caller-held view can write to a checked value), an array hole or `undefined` element, a cycle, or a getter that throws. Provenance and binding are copied field by field, each declared field read once from an own or inherited property, so class instances are accepted and undeclared fields are not kept. For every other action nothing about these three fields changes: Host reads them from the caller's input at the same points and as often as before, and `redactActionParameters`, the digest, the store, the handler and `provenance.onTrace` get what they got before (tests under "an action without admitSubmission: everything but the identity snapshot is as before"). The composition callback, `composition.resolveInitiatingReleaseDigest`, now gets a view of the submission instead of the caller's object, for every action: its scalar fields are the snapshot's, so the release evidence it resolves is for the tenant, actor and action Host persists (before, a caller that changed `tenantId` while `authorize` awaited could have the callback resolve another tenant's release digest, which Host then persisted under the original tenant). For an action without the check, the view's `parameters`, `provenance` and `authorizationBinding` read and assign the caller's input, so the callback reaches the same objects as before; other properties of the caller's object are not on the view (test "scope, actor and action changed while authorize awaits do not reach the composition callback …").
19
+ - **Fail-closed behaviour.** Only `{ admitted: true }` admits, read as an own data property. `submitAction` throws the new `ActionAdmissionError` (`code: "ACTION_ADMISSION_REFUSED"`, `actionId`, `refusal`, and `refusalCode` for a refusal) in each of these cases: a refusal whose code matches `^[a-z][A-Za-z0-9_.:-]{0,127}$` (`refused`); a throw or a non-function check (`failed`); an answer that does not settle within the new `admissionTimeoutMs` option, default 10 000 (`timed_out`); any other answer (`invalid_decision`); and parameters that are not JSON data (`invalid_parameters`). The deadline is judged when the answer settles, on the monotonic clock (`performance.now()`), not by a race with a timer. An answer or throw that settles `admissionTimeoutMs` or more after the call is `timed_out` even when its handler runs before the timer, as when the check blocked the event loop past the deadline (test "an answer that settles after admissionTimeoutMs is refused even when the check blocked the event loop …"). The timer only ends the wait on a promise that never settles. Every `timed_out` refusal aborts the check's signal before `submitAction` throws. Host writes nothing for a refused submission: no invocation, no idempotency key (the key stays free), no event, no policy record and no error. The error message names the action, the refusal and the check's code only. It never contains a submitted value or anything the check threw. `admissionTimeoutMs` must be a whole number from 1 to 2 147 483 647, the largest delay `setTimeout` honours. Otherwise `createGovernedActionHost` throws: NaN, Infinity, 0, negatives, fractions and 2^31 are refused.
20
+ - **Durable evidence and execution.** An admitted invocation records `ActionInvocationRecord.admittedAt`, which is set on creation and never patched. Host passes it to the handler as `ActionContext.admittedAt`. Host refuses to execute an invocation of an action that declares `admitSubmission` when its record has no `admittedAt`, whether inline, from the worker or after an approval. The invocation fails with a fixed message and the handler does not run. Such a record comes from an older Host, a direct store write, or a custom store that does not persist `admittedAt`. Custom `PlatformHostStore` implementations should store and return `admittedAt`. Until they do, actions that declare `admitSubmission` fail at execution, and nothing else changes.
21
+ - **PostgreSQL.** `ensureSchema()` applies migration 6 (`invocation_admission`), which adds the nullable `action_invocations.admitted_at timestamptz` column with no default. Existing rows and rows of actions without the check stay `NULL`.
22
+ - **Rollout order.** The PostgreSQL store names `admitted_at` only when it inserts an admitted invocation, and every invocation read selects `*` and treats a missing column as no `admittedAt`. So actions without `admitSubmission` are submitted, read back and executed on a schema without migration 6, as before (live test "without migration 6, an action without admitSubmission is submitted …"). Before submitting an action that declares `admitSubmission`: (1) run `ensureSchema()`; without migration 6 such a submission fails with an error naming the migration and writes nothing. (2) Upgrade every Host process, workers included. An older worker executes such an invocation without checking `admittedAt`, and an older submitter persists its parameters unchecked. A handler that requires `ctx.admittedAt` still refuses to act under an older Host.
23
+ - **Telemetry.** `invocation.admission_refused` (`fabric.platform.invocation.admission_refused`) is emitted with the `refusal` attribute. A refused submission emits no `invocation.submitted`.
24
+ - **Compatibility.** Every addition is optional. Actions without `admitSubmission` run no check, record no `admittedAt`, get no new parameter refusal and see their parameters, provenance and binding handled as before; the one change for them is that the scalar fields are read once at submission, so a change the caller makes to one of them while `submitAction` awaits is no longer read, and a scalar field that does not yield a value of its declared type is refused with the fixed message above. Rejecting non-JSON parameters for every action would have refused Dates, Maps and class instances that existing callers may pass, a breaking change this minor does not make. On PostgreSQL, only the insert of an admitted invocation names the new `admitted_at` column, so migration 6 is needed only before the first action that declares `admitSubmission` is submitted, as the rollout order above says. `redactActionParameters` stays defense in depth. For an action with the check, it runs on Host's copy after admission.
25
+
26
+ ## 1.6.0
27
+
28
+ ### Minor Changes
29
+
30
+ - 0b437ed: Add validated action/view discovery surface declarations with required reasons for internal entries.
31
+ Preserve them in public manifests and validate normalized manifests. Omitted declarations retain
32
+ public discovery and unchanged serialized shape. Discovery metadata never changes Host authority;
33
+ external catalogs must withhold internal entries and apply audience disclosure independently.
34
+
3
35
  ## 1.5.1
4
36
 
5
37
  ### Patch Changes
package/README.md CHANGED
@@ -23,7 +23,7 @@ const greet: ActionDefinition<unknown> = {
23
23
 
24
24
  That's the smallest unit. From here, you compose actions into a `FabricModule<TDb>`, register the module at startup, and call `invokeAction("demo.greet", ...)` from any of three call paths (authenticated user, signed token, or system/agent). Every call passes through the same pipeline: **policy → state machine → handler → adapters → events → projections.**
25
25
 
26
- For a complete walkthrough see https://platform.fabric.pro/docs/getting-started/quickstart.
26
+ For a complete walkthrough see https://platform.techfabric.com/docs/getting-started/quickstart.
27
27
 
28
28
  ## Why use this
29
29
 
@@ -42,6 +42,7 @@ That's what this package gives you. Nothing more.
42
42
  | Subpath | What you get |
43
43
  |---|---|
44
44
  | `@fabricorg/platform` | Re-exports everything below |
45
+ | `@fabricorg/platform/discovery` | Portable discovery-surface declarations and validation |
45
46
  | `@fabricorg/platform/actions` | `ActionDefinition`, `ActionContext`, `SagaImplementation` |
46
47
  | `@fabricorg/platform/policies` | `PolicyEvaluator`, `PolicyContext`, code/data/hybrid evaluation |
47
48
  | `@fabricorg/platform/state-machines` | `StateMachineDefinition`, structural and guard-aware transition evaluation |
@@ -102,6 +103,8 @@ const json = JSON.stringify(manifest, null, 2);
102
103
 
103
104
  An entity schema does not validate arbitrary writes through `TDb`. Persisted-record validation requires an explicit Host/database adapter. When an action declares `resultSchema`, Platform Host validates the public result after the handler and before events or adapters; failure rolls back domain writes only when the Host store has a transaction provider that includes them.
104
105
 
106
+ An action may also declare `admitSubmission`, an async check that decides whether a submission may be recorded at all. It receives the trusted `tenantId`, `spaceId`, `actorId` and `actorType`, the submitted parameters and a `signal` (`ActionAdmissionSignal`, a structural subset of `AbortSignal`; Host passes a real one), and answers `{ admitted: true }` or `{ admitted: false, code }` with a fixed code. `@fabricorg/platform-host` 7.3.0 and later runs it after authorizing the submitter and before writing anything for the submission, refuses on a throw, timeout or any other answer, and passes the admission time to the handler as `ActionContext.admittedAt`. An older host ignores the field, so a handler that relies on it should refuse without `ctx.admittedAt`. Registration rejects an `admitSubmission` that is not a function.
107
+
105
108
  ## The action lifecycle
106
109
 
107
110
  Every `invokeAction(id, params)` call goes through:
@@ -174,7 +177,29 @@ See [`CHANGELOG.md`](./CHANGELOG.md) for release history.
174
177
 
175
178
  ## Documentation
176
179
 
177
- Full reference docs at https://platform.fabric.pro
180
+ Full reference docs at https://platform.techfabric.com
181
+
182
+ ## Discovery surface declarations
183
+
184
+ Actions and views can declare `surface: "internal"` with a non-blank `surfaceReason`.
185
+ Omission means public discovery. Registration, manifest export and manifest normalization reject
186
+ unknown surfaces and missing reasons. Public manifests retain both fields, so contract digests
187
+ cover the declaration. Existing declarations without these fields preserve their exported shape.
188
+
189
+ External catalog consumers must omit internal entries, including their reason and schemas, and
190
+ apply their existing audience disclosure rules to public entries. This is discovery metadata:
191
+ it does not grant invocation/read access, bypass policy, or stop authorized workers from running
192
+ internal actions through the governed Host. A public entry is not a promise of an authored route.
193
+
194
+ `surface` controls definition discovery, while action `execution.sensitivity` and view
195
+ `usage.classification` describe execution/data disclosure. These are independent declarations.
196
+ `assertSurfaceDeclaration` is available from the root and `@fabricorg/platform/discovery`.
197
+ Reasons are authored public-package metadata; authors must keep them free of secrets.
198
+
199
+ No first-party compiler or generator artifact applies discovery filtering. All deliberately
200
+ retain internal contracts for trusted assembly and worker integration; none implements external
201
+ catalog disclosure. A usage contract or generated schema must not
202
+ be served as an audience catalog without the internal-surface and audience filters above.
178
203
 
179
204
  ## License
180
205
 
@@ -1,28 +1,28 @@
1
1
  'use strict';
2
2
 
3
- var chunkMSABJAED_cjs = require('../chunk-MSABJAED.cjs');
3
+ var chunkXCAOO6KG_cjs = require('../chunk-XCAOO6KG.cjs');
4
4
 
5
5
 
6
6
 
7
7
  Object.defineProperty(exports, "ACTOR_TYPES", {
8
8
  enumerable: true,
9
- get: function () { return chunkMSABJAED_cjs.ACTOR_TYPES; }
9
+ get: function () { return chunkXCAOO6KG_cjs.ACTOR_TYPES; }
10
10
  });
11
11
  Object.defineProperty(exports, "assertActionId", {
12
12
  enumerable: true,
13
- get: function () { return chunkMSABJAED_cjs.assertActionId; }
13
+ get: function () { return chunkXCAOO6KG_cjs.assertActionId; }
14
14
  });
15
15
  Object.defineProperty(exports, "assertActorType", {
16
16
  enumerable: true,
17
- get: function () { return chunkMSABJAED_cjs.assertActorType; }
17
+ get: function () { return chunkXCAOO6KG_cjs.assertActorType; }
18
18
  });
19
19
  Object.defineProperty(exports, "createActionRegistry", {
20
20
  enumerable: true,
21
- get: function () { return chunkMSABJAED_cjs.createActionRegistry; }
21
+ get: function () { return chunkXCAOO6KG_cjs.createActionRegistry; }
22
22
  });
23
23
  Object.defineProperty(exports, "isActorType", {
24
24
  enumerable: true,
25
- get: function () { return chunkMSABJAED_cjs.isActorType; }
25
+ get: function () { return chunkXCAOO6KG_cjs.isActorType; }
26
26
  });
27
27
  //# sourceMappingURL=index.cjs.map
28
28
  //# sourceMappingURL=index.cjs.map
@@ -1,3 +1,5 @@
1
+ import { SurfaceDeclaration } from '../discovery/index.cjs';
2
+
1
3
  type ActionId = `${string}.${string}`;
2
4
  interface SchemaParseIssue {
3
5
  path: PropertyKey[];
@@ -38,7 +40,72 @@ interface ActionContext<TDb = unknown> {
38
40
  };
39
41
  db: TDb;
40
42
  services?: FabricRuntimeServices;
43
+ /**
44
+ * When the host admitted this invocation's submission through the
45
+ * action's `admitSubmission` check, read from the durable invocation
46
+ * record. Absent when the action declares no check, or when the runtime
47
+ * that built this context does not run declared admission checks (a host
48
+ * older than the one that introduced them). A handler whose action
49
+ * declares `admitSubmission` can refuse to run without it.
50
+ */
51
+ admittedAt?: Date;
41
52
  }
53
+ /**
54
+ * Trusted facts a host gives an action's `admitSubmission` check. Scope and
55
+ * actor come from the host's authenticated submission, never from the
56
+ * parameters.
57
+ */
58
+ interface ActionAdmissionInput {
59
+ readonly actionId: ActionId;
60
+ readonly tenantId: string;
61
+ readonly spaceId: string;
62
+ readonly actorId: string;
63
+ readonly actorType: ActorType;
64
+ /**
65
+ * The submitted parameters, unvalidated, as a copy made for this check.
66
+ * `@fabricorg/platform-host` records its own copy of the same value, taken
67
+ * before the check ran, and only if the check admits it; changing this
68
+ * copy changes nothing the host records.
69
+ */
70
+ readonly parameters: Readonly<Record<string, unknown>>;
71
+ /**
72
+ * Aborted when the host's admission deadline passes. Hosts pass an
73
+ * `AbortSignal`. `@fabricorg/platform-host` refuses an answer that settles
74
+ * at or after the deadline, even one that settles before the abort.
75
+ */
76
+ readonly signal: ActionAdmissionSignal;
77
+ }
78
+ /**
79
+ * The part of an `AbortSignal` an admission check can rely on. Declared
80
+ * structurally so this module compiles without DOM or Node type libraries; a
81
+ * host passes a real `AbortSignal`, which satisfies it.
82
+ */
83
+ interface ActionAdmissionSignal {
84
+ readonly aborted: boolean;
85
+ addEventListener(type: "abort", listener: () => void, options?: {
86
+ once?: boolean;
87
+ }): void;
88
+ removeEventListener(type: "abort", listener: () => void): void;
89
+ }
90
+ /**
91
+ * An admission check's answer. Only `{ admitted: true }` admits. A refusal's
92
+ * `code` must be a fixed code chosen by the action (lower-case first letter,
93
+ * then letters, digits, `_`, `.`, `:` or `-`, at most 128 characters), never
94
+ * a submitted value: the host puts it in the error it throws.
95
+ */
96
+ type ActionAdmissionDecision = {
97
+ readonly admitted: true;
98
+ } | {
99
+ readonly admitted: false;
100
+ readonly code: string;
101
+ };
102
+ /**
103
+ * Decides whether a submission may be recorded at all. A host that supports
104
+ * it runs the check after authorizing the submitter and before it writes
105
+ * anything durable for the submission; a refusal, a throw, a timeout or any
106
+ * answer other than `{ admitted: true }` refuses the submission.
107
+ */
108
+ type ActionAdmission = (input: ActionAdmissionInput) => Promise<ActionAdmissionDecision>;
42
109
  interface ActionResult {
43
110
  success: boolean;
44
111
  data?: Record<string, unknown>;
@@ -63,11 +130,21 @@ interface ActionStateMachineBinding {
63
130
  targetState: string | ((params: unknown) => string);
64
131
  getEntityId: (params: unknown) => string | undefined;
65
132
  }
66
- interface ActionDefinition<TDb = unknown> {
133
+ interface ActionDefinition<TDb = unknown> extends SurfaceDeclaration {
67
134
  actionId: ActionId;
68
135
  namespace: string;
69
136
  version: number;
70
137
  schema: SchemaValidator;
138
+ /**
139
+ * Optional check a host runs on every submission before it records
140
+ * anything durable for it (invocation, idempotency key, events, errors).
141
+ * Use it when parameters must be validated against trusted context, for
142
+ * example a secret reference the tenant's secret store must hold, before
143
+ * they may be persisted. `@fabricorg/platform-host` runs it from the
144
+ * release that introduced it; an older host ignores it, so a handler that
145
+ * relies on it should require `ActionContext.admittedAt`.
146
+ */
147
+ admitSubmission?: ActionAdmission;
71
148
  /** Optional validation contract for the public handler result data. */
72
149
  resultSchema?: SchemaValidator;
73
150
  handler?: ActionHandler<TDb>;
@@ -182,4 +259,4 @@ interface ActionRegistry<TDb = unknown> {
182
259
  }
183
260
  declare function createActionRegistry<TDb = unknown>(definitions?: readonly ActionDefinition<TDb>[]): ActionRegistry<TDb>;
184
261
 
185
- export { ACTOR_TYPES, type ActionCompletionMode, type ActionConnectivity, type ActionConsistency, type ActionContext, type ActionDataSensitivity, type ActionDefinition, type ActionExecutionContract, type ActionHandler, type ActionId, type ActionIdempotencyStance, type ActionRegistry, type ActionResult, type ActionStateMachineBinding, type ActionStatus, type ActorType, type AdapterStep, type AdapterStepRetryPolicy, type AuthorityMoment, type FabricRuntimeServices, type SagaChildActionInput, type SagaCompletion, type SagaCompletionEvent, type SagaContext, type SagaImplementation, type SagaRunChild, type SchemaParseIssue, type SchemaParseResult, type SchemaValidator, assertActionId, assertActorType, createActionRegistry, isActorType };
262
+ export { ACTOR_TYPES, type ActionAdmission, type ActionAdmissionDecision, type ActionAdmissionInput, type ActionAdmissionSignal, type ActionCompletionMode, type ActionConnectivity, type ActionConsistency, type ActionContext, type ActionDataSensitivity, type ActionDefinition, type ActionExecutionContract, type ActionHandler, type ActionId, type ActionIdempotencyStance, type ActionRegistry, type ActionResult, type ActionStateMachineBinding, type ActionStatus, type ActorType, type AdapterStep, type AdapterStepRetryPolicy, type AuthorityMoment, type FabricRuntimeServices, type SagaChildActionInput, type SagaCompletion, type SagaCompletionEvent, type SagaContext, type SagaImplementation, type SagaRunChild, type SchemaParseIssue, type SchemaParseResult, type SchemaValidator, assertActionId, assertActorType, createActionRegistry, isActorType };
@@ -1,3 +1,5 @@
1
+ import { SurfaceDeclaration } from '../discovery/index.js';
2
+
1
3
  type ActionId = `${string}.${string}`;
2
4
  interface SchemaParseIssue {
3
5
  path: PropertyKey[];
@@ -38,7 +40,72 @@ interface ActionContext<TDb = unknown> {
38
40
  };
39
41
  db: TDb;
40
42
  services?: FabricRuntimeServices;
43
+ /**
44
+ * When the host admitted this invocation's submission through the
45
+ * action's `admitSubmission` check, read from the durable invocation
46
+ * record. Absent when the action declares no check, or when the runtime
47
+ * that built this context does not run declared admission checks (a host
48
+ * older than the one that introduced them). A handler whose action
49
+ * declares `admitSubmission` can refuse to run without it.
50
+ */
51
+ admittedAt?: Date;
41
52
  }
53
+ /**
54
+ * Trusted facts a host gives an action's `admitSubmission` check. Scope and
55
+ * actor come from the host's authenticated submission, never from the
56
+ * parameters.
57
+ */
58
+ interface ActionAdmissionInput {
59
+ readonly actionId: ActionId;
60
+ readonly tenantId: string;
61
+ readonly spaceId: string;
62
+ readonly actorId: string;
63
+ readonly actorType: ActorType;
64
+ /**
65
+ * The submitted parameters, unvalidated, as a copy made for this check.
66
+ * `@fabricorg/platform-host` records its own copy of the same value, taken
67
+ * before the check ran, and only if the check admits it; changing this
68
+ * copy changes nothing the host records.
69
+ */
70
+ readonly parameters: Readonly<Record<string, unknown>>;
71
+ /**
72
+ * Aborted when the host's admission deadline passes. Hosts pass an
73
+ * `AbortSignal`. `@fabricorg/platform-host` refuses an answer that settles
74
+ * at or after the deadline, even one that settles before the abort.
75
+ */
76
+ readonly signal: ActionAdmissionSignal;
77
+ }
78
+ /**
79
+ * The part of an `AbortSignal` an admission check can rely on. Declared
80
+ * structurally so this module compiles without DOM or Node type libraries; a
81
+ * host passes a real `AbortSignal`, which satisfies it.
82
+ */
83
+ interface ActionAdmissionSignal {
84
+ readonly aborted: boolean;
85
+ addEventListener(type: "abort", listener: () => void, options?: {
86
+ once?: boolean;
87
+ }): void;
88
+ removeEventListener(type: "abort", listener: () => void): void;
89
+ }
90
+ /**
91
+ * An admission check's answer. Only `{ admitted: true }` admits. A refusal's
92
+ * `code` must be a fixed code chosen by the action (lower-case first letter,
93
+ * then letters, digits, `_`, `.`, `:` or `-`, at most 128 characters), never
94
+ * a submitted value: the host puts it in the error it throws.
95
+ */
96
+ type ActionAdmissionDecision = {
97
+ readonly admitted: true;
98
+ } | {
99
+ readonly admitted: false;
100
+ readonly code: string;
101
+ };
102
+ /**
103
+ * Decides whether a submission may be recorded at all. A host that supports
104
+ * it runs the check after authorizing the submitter and before it writes
105
+ * anything durable for the submission; a refusal, a throw, a timeout or any
106
+ * answer other than `{ admitted: true }` refuses the submission.
107
+ */
108
+ type ActionAdmission = (input: ActionAdmissionInput) => Promise<ActionAdmissionDecision>;
42
109
  interface ActionResult {
43
110
  success: boolean;
44
111
  data?: Record<string, unknown>;
@@ -63,11 +130,21 @@ interface ActionStateMachineBinding {
63
130
  targetState: string | ((params: unknown) => string);
64
131
  getEntityId: (params: unknown) => string | undefined;
65
132
  }
66
- interface ActionDefinition<TDb = unknown> {
133
+ interface ActionDefinition<TDb = unknown> extends SurfaceDeclaration {
67
134
  actionId: ActionId;
68
135
  namespace: string;
69
136
  version: number;
70
137
  schema: SchemaValidator;
138
+ /**
139
+ * Optional check a host runs on every submission before it records
140
+ * anything durable for it (invocation, idempotency key, events, errors).
141
+ * Use it when parameters must be validated against trusted context, for
142
+ * example a secret reference the tenant's secret store must hold, before
143
+ * they may be persisted. `@fabricorg/platform-host` runs it from the
144
+ * release that introduced it; an older host ignores it, so a handler that
145
+ * relies on it should require `ActionContext.admittedAt`.
146
+ */
147
+ admitSubmission?: ActionAdmission;
71
148
  /** Optional validation contract for the public handler result data. */
72
149
  resultSchema?: SchemaValidator;
73
150
  handler?: ActionHandler<TDb>;
@@ -182,4 +259,4 @@ interface ActionRegistry<TDb = unknown> {
182
259
  }
183
260
  declare function createActionRegistry<TDb = unknown>(definitions?: readonly ActionDefinition<TDb>[]): ActionRegistry<TDb>;
184
261
 
185
- export { ACTOR_TYPES, type ActionCompletionMode, type ActionConnectivity, type ActionConsistency, type ActionContext, type ActionDataSensitivity, type ActionDefinition, type ActionExecutionContract, type ActionHandler, type ActionId, type ActionIdempotencyStance, type ActionRegistry, type ActionResult, type ActionStateMachineBinding, type ActionStatus, type ActorType, type AdapterStep, type AdapterStepRetryPolicy, type AuthorityMoment, type FabricRuntimeServices, type SagaChildActionInput, type SagaCompletion, type SagaCompletionEvent, type SagaContext, type SagaImplementation, type SagaRunChild, type SchemaParseIssue, type SchemaParseResult, type SchemaValidator, assertActionId, assertActorType, createActionRegistry, isActorType };
262
+ export { ACTOR_TYPES, type ActionAdmission, type ActionAdmissionDecision, type ActionAdmissionInput, type ActionAdmissionSignal, type ActionCompletionMode, type ActionConnectivity, type ActionConsistency, type ActionContext, type ActionDataSensitivity, type ActionDefinition, type ActionExecutionContract, type ActionHandler, type ActionId, type ActionIdempotencyStance, type ActionRegistry, type ActionResult, type ActionStateMachineBinding, type ActionStatus, type ActorType, type AdapterStep, type AdapterStepRetryPolicy, type AuthorityMoment, type FabricRuntimeServices, type SagaChildActionInput, type SagaCompletion, type SagaCompletionEvent, type SagaContext, type SagaImplementation, type SagaRunChild, type SchemaParseIssue, type SchemaParseResult, type SchemaValidator, assertActionId, assertActorType, createActionRegistry, isActorType };
@@ -1,3 +1,3 @@
1
- export { ACTOR_TYPES, assertActionId, assertActorType, createActionRegistry, isActorType } from '../chunk-2W6FORTE.js';
1
+ export { ACTOR_TYPES, assertActionId, assertActorType, createActionRegistry, isActorType } from '../chunk-6QX4I45I.js';
2
2
  //# sourceMappingURL=index.js.map
3
3
  //# sourceMappingURL=index.js.map
@@ -1,25 +1,26 @@
1
1
  'use strict';
2
2
 
3
- var chunkPFKTD7V5_cjs = require('../chunk-PFKTD7V5.cjs');
4
- require('../chunk-ZBXFRJON.cjs');
5
- require('../chunk-KIVQBZOA.cjs');
3
+ var chunkMCWSUGB3_cjs = require('../chunk-MCWSUGB3.cjs');
4
+ require('../chunk-WQ3BYI7T.cjs');
5
+ require('../chunk-DBTAUI6C.cjs');
6
6
  require('../chunk-IFW43ELT.cjs');
7
- require('../chunk-CXR6KEKQ.cjs');
7
+ require('../chunk-SNTV45LH.cjs');
8
+ require('../chunk-D4SWRBUH.cjs');
8
9
  require('../chunk-2AE6TMAX.cjs');
9
10
 
10
11
 
11
12
 
12
13
  Object.defineProperty(exports, "STRICT_EXECUTION_CONTRACT_PROFILE", {
13
14
  enumerable: true,
14
- get: function () { return chunkPFKTD7V5_cjs.STRICT_EXECUTION_CONTRACT_PROFILE; }
15
+ get: function () { return chunkMCWSUGB3_cjs.STRICT_EXECUTION_CONTRACT_PROFILE; }
15
16
  });
16
17
  Object.defineProperty(exports, "STRICT_EXECUTION_CONTRACT_PROFILE_ID", {
17
18
  enumerable: true,
18
- get: function () { return chunkPFKTD7V5_cjs.STRICT_EXECUTION_CONTRACT_PROFILE_ID; }
19
+ get: function () { return chunkMCWSUGB3_cjs.STRICT_EXECUTION_CONTRACT_PROFILE_ID; }
19
20
  });
20
21
  Object.defineProperty(exports, "executionContractProfile", {
21
22
  enumerable: true,
22
- get: function () { return chunkPFKTD7V5_cjs.executionContractProfile; }
23
+ get: function () { return chunkMCWSUGB3_cjs.executionContractProfile; }
23
24
  });
24
25
  //# sourceMappingURL=index.cjs.map
25
26
  //# sourceMappingURL=index.cjs.map
@@ -1,6 +1,7 @@
1
1
  import { ActionCompletionMode } from '../actions/index.cjs';
2
2
  import { ModuleManifest } from '../manifest/index.cjs';
3
3
  import { FabricModule } from '../modules/index.cjs';
4
+ import '../discovery/index.cjs';
4
5
  import '../objects/index.cjs';
5
6
  import '../policies/index.cjs';
6
7
  import '../state-machines/index.cjs';
@@ -1,6 +1,7 @@
1
1
  import { ActionCompletionMode } from '../actions/index.js';
2
2
  import { ModuleManifest } from '../manifest/index.js';
3
3
  import { FabricModule } from '../modules/index.js';
4
+ import '../discovery/index.js';
4
5
  import '../objects/index.js';
5
6
  import '../policies/index.js';
6
7
  import '../state-machines/index.js';
@@ -1,8 +1,9 @@
1
- export { STRICT_EXECUTION_CONTRACT_PROFILE, STRICT_EXECUTION_CONTRACT_PROFILE_ID, executionContractProfile } from '../chunk-DDO4EQ2J.js';
2
- import '../chunk-MC3GSVJ6.js';
3
- import '../chunk-GRBZYDEV.js';
1
+ export { STRICT_EXECUTION_CONTRACT_PROFILE, STRICT_EXECUTION_CONTRACT_PROFILE_ID, executionContractProfile } from '../chunk-EMSAFNPX.js';
2
+ import '../chunk-PDN5DOLQ.js';
3
+ import '../chunk-WNZP53GI.js';
4
4
  import '../chunk-ZAEVQSB5.js';
5
- import '../chunk-JG35DT2G.js';
5
+ import '../chunk-MLBALEUR.js';
6
+ import '../chunk-LFE74IJX.js';
6
7
  import '../chunk-B5DOGDPG.js';
7
8
  //# sourceMappingURL=index.js.map
8
9
  //# sourceMappingURL=index.js.map
@@ -147,13 +147,21 @@ async function evaluatePolicyDefinitions(policies, ctx) {
147
147
  return outcomes;
148
148
  }
149
149
  async function evaluatePolicyDefinition(policy, ctx) {
150
- if (policy.kind === "data") {
151
- return evaluateDataPolicy(policy, ctx);
152
- }
153
- if (policy.kind === "code") {
154
- return evaluateCodePolicy(policy, ctx);
155
- }
156
- return evaluateHybridPolicy(policy, ctx);
150
+ const authority = policy.authority ? { ...policy.authority } : void 0;
151
+ const outcome = policy.kind === "data" ? await evaluateDataPolicy(policy, ctx) : policy.kind === "code" ? await evaluateCodePolicy(policy, ctx) : await evaluateHybridPolicy(policy, ctx);
152
+ if (!authority) return outcome;
153
+ return {
154
+ ...outcome,
155
+ dispatchEvidence: {
156
+ ...outcome.dispatchEvidence ?? {
157
+ policyKind: policy.kind,
158
+ policyId: policy.policyId,
159
+ policyVersion: policy.policyVersion,
160
+ dispatchPath: []
161
+ },
162
+ authority
163
+ }
164
+ };
157
165
  }
158
166
  async function evaluateCodePolicy(policy, ctx) {
159
167
  const codeEvaluatorPolicyId = policy.codeEvaluatorPolicyId ?? policy.policyId;
@@ -657,5 +665,5 @@ exports.evaluatePolicyDefinitions = evaluatePolicyDefinitions;
657
665
  exports.evaluateRegisteredPolicies = evaluateRegisteredPolicies;
658
666
  exports.validateDataPolicyDefinition = validateDataPolicyDefinition;
659
667
  exports.validatePolicyGuidance = validatePolicyGuidance;
660
- //# sourceMappingURL=chunk-VZ6C4LXC.cjs.map
661
- //# sourceMappingURL=chunk-VZ6C4LXC.cjs.map
668
+ //# sourceMappingURL=chunk-45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CAAA;AACpC,EAAA,OAAO,OAAO,QAAA,CAAS,QAAA,CAAS,MAAA,GAAS,CAAC,KAAK,CAAC,CAAA;AACjD;AAEO,SAAS,wBAAwB,QAAA,EAAsD;AAC7F,EAAA,OACC,QAAA,CAAS,IAAA,CAAK,CAAC,OAAA,KAAY,QAAQ,MAAA,KAAW,OAAO,CAAA,IACrD,QAAA,CAAS,IAAA,CAAK,CAAC,OAAA,KAAY,OAAA,CAAQ,WAAW,MAAM,CAAA;AAEtD","file":"chunk-45OKKLNY.cjs","sourcesContent":["import type { ActionId, ActorType, FabricRuntimeServices } from \"../actions\";\n\nexport type PolicyEvaluationResult = \"pass\" | \"warn\" | \"block\";\n\nexport type PolicyKind = \"code\" | \"data\" | \"hybrid\";\n\nexport type PolicyId = `${string}.v${number}`;\n\nexport type PolicyEvaluationMode = \"preview\" | \"execute\";\n\nexport function assertPolicyId(policyId: string): asserts policyId is PolicyId {\n\tif (!/^[a-z][a-z0-9_-]*(\\.[a-z][a-z0-9_-]*)*\\.v[0-9]+$/.test(policyId)) {\n\t\tthrow new Error(`Invalid policy ID: ${policyId}`);\n\t}\n}\n\nexport interface PolicyContext<TDb = unknown> {\n\ttenantId: string;\n\tspaceId: string;\n\tactionInvocationId: string;\n\tactionId: string;\n\t/** Authenticated actor identity supplied by the host. Omitted only by legacy hosts and previews. */\n\tactorId?: string;\n\tactorType?: ActorType;\n\tparameters: unknown;\n\tdb: TDb;\n\tnow?: Date;\n\tmode?: PolicyEvaluationMode;\n\t/**\n\t * Optional runtime services bag, mirroring {@link FabricRuntimeServices} on\n\t * `ActionContext`. Lets the host inject dependencies (HTTP clients, secret\n\t * managers, external policy engines such as OPA, feature flags, etc.) that\n\t * a code policy evaluator may need without resorting to module-level\n\t * globals. The shape is opaque to the platform — adapters narrow it.\n\t */\n\tservices?: FabricRuntimeServices;\n\t/** Explicit code-policy catalog for this runtime; absence fails closed. */\n\tresolveCodePolicy?: (policyId: PolicyId) => PolicyEvaluator | undefined;\n}\n\nexport interface PolicyFact {\n\tname: string;\n\tvalue: unknown;\n\tlabel?: string;\n}\n\nexport type PolicyCorrectiveActionKind = \"invoke_action\" | \"navigate\" | \"manual\";\n\nexport interface PolicyCorrectiveActionBase {\n\tkind: PolicyCorrectiveActionKind;\n\tlabel: string;\n\tdescription?: string;\n\trequiresRole?: string[];\n\trequiresConfirmation?: boolean;\n}\n\nexport interface PolicyInvokeActionCorrectiveAction extends PolicyCorrectiveActionBase {\n\tkind: \"invoke_action\";\n\tactionId: ActionId;\n\tparameters?: Record<string, unknown>;\n}\n\nexport interface PolicyNavigateCorrectiveAction extends PolicyCorrectiveActionBase {\n\tkind: \"navigate\";\n\troute?: string;\n\ttarget?: {\n\t\tsurface?: string;\n\t\ttab?: string;\n\t\tfield?: string;\n\t};\n}\n\nexport interface PolicyManualCorrectiveAction extends PolicyCorrectiveActionBase {\n\tkind: \"manual\";\n}\n\nexport type PolicyCorrectiveAction =\n\t| PolicyInvokeActionCorrectiveAction\n\t| PolicyNavigateCorrectiveAction\n\t| PolicyManualCorrectiveAction;\n\nexport interface PolicyGuidance {\n\tsummary?: string;\n\tfactsUsed: PolicyFact[];\n\tcorrectiveActions: PolicyCorrectiveAction[];\n}\n\nexport interface PolicyGuidanceValidationResult {\n\tvalid: boolean;\n\terrors: string[];\n}\n\nexport function validatePolicyGuidance(guidance: unknown): PolicyGuidanceValidationResult {\n\tconst errors: string[] = [];\n\n\tif (!isPlainRecord(guidance)) {\n\t\treturn { valid: false, errors: [\"guidance must be an object\"] };\n\t}\n\n\tif (guidance.summary !== undefined && typeof guidance.summary !== \"string\") {\n\t\terrors.push(\"guidance.summary must be a string when present\");\n\t}\n\n\tif (!Array.isArray(guidance.factsUsed)) {\n\t\terrors.push(\"guidance.factsUsed must be an array\");\n\t} else {\n\t\tguidance.factsUsed.forEach((fact, index) => {\n\t\t\tif (!isPlainRecord(fact)) {\n\t\t\t\terrors.push(`guidance.factsUsed[${index}] must be an object`);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (typeof fact.name !== \"string\" || fact.name.length === 0) {\n\t\t\t\terrors.push(`guidance.factsUsed[${index}].name must be a non-empty string`);\n\t\t\t}\n\t\t\tif (fact.label !== undefined && typeof fact.label !== \"string\") {\n\t\t\t\terrors.push(`guidance.factsUsed[${index}].label must be a string when present`);\n\t\t\t}\n\t\t});\n\t}\n\n\tif (!Array.isArray(guidance.correctiveActions)) {\n\t\terrors.push(\"guidance.correctiveActions must be an array\");\n\t} else {\n\t\tguidance.correctiveActions.forEach((action, index) => {\n\t\t\terrors.push(...validatePolicyCorrectiveAction(action, index));\n\t\t});\n\t}\n\n\treturn { valid: errors.length === 0, errors };\n}\n\nfunction validatePolicyCorrectiveAction(action: unknown, index: number): string[] {\n\tconst errors: string[] = [];\n\tconst prefix = `guidance.correctiveActions[${index}]`;\n\n\tif (!isPlainRecord(action)) {\n\t\treturn [`${prefix} must be an object`];\n\t}\n\n\tif (\n\t\taction.kind !== \"invoke_action\" &&\n\t\taction.kind !== \"navigate\" &&\n\t\taction.kind !== \"manual\"\n\t) {\n\t\terrors.push(`${prefix}.kind must be \"invoke_action\" | \"navigate\" | \"manual\"`);\n\t}\n\tif (typeof action.label !== \"string\" || action.label.length === 0) {\n\t\terrors.push(`${prefix}.label must be a non-empty string`);\n\t}\n\tif (action.description !== undefined && typeof action.description !== \"string\") {\n\t\terrors.push(`${prefix}.description must be a string when present`);\n\t}\n\tif (action.requiresConfirmation !== undefined && typeof action.requiresConfirmation !== \"boolean\") {\n\t\terrors.push(`${prefix}.requiresConfirmation must be a boolean when present`);\n\t}\n\tif (action.requiresRole !== undefined) {\n\t\tif (!Array.isArray(action.requiresRole)) {\n\t\t\terrors.push(`${prefix}.requiresRole must be an array when present`);\n\t\t} else if (action.requiresRole.some((role) => typeof role !== \"string\" || role.length === 0)) {\n\t\t\terrors.push(`${prefix}.requiresRole must contain only non-empty strings`);\n\t\t}\n\t}\n\n\tif (action.kind === \"invoke_action\") {\n\t\tif (typeof action.actionId !== \"string\" || action.actionId.length === 0) {\n\t\t\terrors.push(`${prefix}.actionId must be a non-empty string for invoke_action`);\n\t\t}\n\t\tif (action.parameters !== undefined && !isPlainRecord(action.parameters)) {\n\t\t\terrors.push(`${prefix}.parameters must be an object when present`);\n\t\t}\n\t}\n\n\tif (action.kind === \"navigate\") {\n\t\tif (action.route !== undefined && typeof action.route !== \"string\") {\n\t\t\terrors.push(`${prefix}.route must be a string when present`);\n\t\t}\n\t\tif (action.target !== undefined && !isPlainRecord(action.target)) {\n\t\t\terrors.push(`${prefix}.target must be an object when present`);\n\t\t}\n\t}\n\n\treturn errors;\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nexport interface PolicyOutcome {\n\tpolicyId: PolicyId;\n\tpolicyVersion: number;\n\tpolicyKind?: PolicyKind;\n\tresult: PolicyEvaluationResult;\n\treason?: string;\n\tguidance?: PolicyGuidance;\n\tmetadata?: Record<string, unknown>;\n\tdispatchEvidence?: PolicyDispatchEvidence;\n}\n\nexport interface PolicyEvaluator<TDb = unknown> {\n\tpolicyId: PolicyId;\n\tversion: number;\n\tkind?: Extract<PolicyKind, \"code\">;\n\tpreviewSafe?: boolean;\n\tevaluate: (ctx: PolicyContext<TDb>) => Promise<PolicyOutcome>;\n}\n\nexport type DataPolicySource = \"parameters\" | \"context\";\n\nexport type DataPolicyLiteral = string | number | boolean | null;\n\nexport type DataPolicyComparisonOperator =\n\t| \"exists\"\n\t| \"equals\"\n\t| \"notEquals\"\n\t| \"gt\"\n\t| \"gte\"\n\t| \"lt\"\n\t| \"lte\";\n\nexport interface DataPolicySourceReference {\n\tsource: DataPolicySource;\n\tpath: string;\n}\n\nexport type DataPolicyCondition =\n\t| {\n\t\t\tconditionId: string;\n\t\t\ttype: \"always\";\n\t\t\tresult: PolicyEvaluationResult;\n\t\t\treason?: string;\n\t\t}\n\t| {\n\t\t\tconditionId: string;\n\t\t\ttype: \"parameter\";\n\t\t\tpath: string;\n\t\t\toperator: DataPolicyComparisonOperator;\n\t\t\tvalue?: DataPolicyLiteral;\n\t\t\tonPass?: PolicyEvaluationResult;\n\t\t\tonFail?: PolicyEvaluationResult;\n\t\t\treason?: string;\n\t\t}\n\t| {\n\t\t\tconditionId: string;\n\t\t\ttype: \"comparison\";\n\t\t\tleft: DataPolicySourceReference;\n\t\t\toperator: DataPolicyComparisonOperator;\n\t\t\tvalue?: DataPolicyLiteral;\n\t\t\tonPass?: PolicyEvaluationResult;\n\t\t\tonFail?: PolicyEvaluationResult;\n\t\t\treason?: string;\n\t\t}\n\t| {\n\t\t\tconditionId: string;\n\t\t\ttype: \"all\" | \"any\";\n\t\t\tconditions: DataPolicyCondition[];\n\t\t\tonPass?: PolicyEvaluationResult;\n\t\t\tonFail?: PolicyEvaluationResult;\n\t\t\treason?: string;\n\t\t}\n\t| {\n\t\t\tconditionId: string;\n\t\t\ttype: \"not\";\n\t\t\tcondition: DataPolicyCondition;\n\t\t\tonPass?: PolicyEvaluationResult;\n\t\t\tonFail?: PolicyEvaluationResult;\n\t\t\treason?: string;\n\t\t};\n\nexport interface DataPolicyDefinition {\n\tconditions: DataPolicyCondition[];\n\tdefaultResult?: PolicyEvaluationResult;\n\treason?: string;\n}\n\nexport interface DataPolicyValidationResult {\n\tvalid: boolean;\n\terrors: string[];\n}\n\nconst DATA_POLICY_MAX_DEPTH = 5;\nconst DATA_POLICY_MAX_CONDITIONS_PER_NODE = 20;\nconst DATA_POLICY_MAX_TOTAL_CONDITIONS = 100;\nconst DATA_POLICY_MAX_PATH_SEGMENTS = 12;\nconst DATA_POLICY_MAX_STRING_LENGTH = 500;\n\nconst DATA_POLICY_CONTEXT_PATHS = Object.freeze([\n\t\"tenantId\",\n\t\"spaceId\",\n\t\"actionInvocationId\",\n\t\"actionId\",\n\t\"mode\",\n]);\n\nconst DATA_POLICY_COMPARISON_OPERATORS: readonly DataPolicyComparisonOperator[] = Object.freeze([\n\t\"exists\",\n\t\"equals\",\n\t\"notEquals\",\n\t\"gt\",\n\t\"gte\",\n\t\"lt\",\n\t\"lte\",\n]);\n\nconst POLICY_RESULTS: readonly PolicyEvaluationResult[] = Object.freeze([\"pass\", \"warn\", \"block\"]);\n\nexport interface PolicyFallbackDefinition {\n\tcodeEvaluatorPolicyId: PolicyId;\n\tonResults?: PolicyEvaluationResult[];\n\ttriggers?: PolicyFallbackTrigger[];\n\treason?: string;\n}\n\nexport type PolicyFallbackTrigger =\n\t| \"data_result\"\n\t| \"missing_data_definition\"\n\t| \"invalid_data_definition\";\n\nexport interface DataPolicyConditionResult {\n\tconditionId: string;\n\tpassed: boolean;\n\tresult: PolicyEvaluationResult;\n\treason?: string;\n}\n\n/**\n * Opaque, consumer-defined reference to the immutable policy authority or\n * snapshot a runtime policy definition was resolved from. Platform records it\n * in dispatch evidence and does not interpret it.\n */\nexport interface PolicyAuthorityReference {\n\tsnapshotId: string;\n\tcontentHash?: string;\n}\n\nexport interface RuntimePolicyDefinition {\n\tpolicyId: PolicyId;\n\tpolicyVersion: number;\n\tkind: PolicyKind;\n\t/** Snapshot/authority this definition came from; copied into dispatch evidence. */\n\tauthority?: PolicyAuthorityReference;\n\tdataDefinition?: DataPolicyDefinition;\n\tcodeEvaluatorPolicyId?: PolicyId;\n\tfallback?: PolicyFallbackDefinition;\n}\n\nexport interface PolicyDispatchEvidence {\n\tpolicyKind: PolicyKind;\n\tpolicyId?: PolicyId;\n\tpolicyVersion?: number;\n\t/** Snapshot/authority the evaluated definition was resolved from, when supplied. */\n\tauthority?: PolicyAuthorityReference;\n\tdispatchPath: Array<\"data\" | \"code\" | \"fallback\">;\n\tdata?: {\n\t\tdefinitionVersion: number;\n\t\tdefinitionStatus: \"evaluated\" | \"missing\" | \"invalid\";\n\t\tconditionResults: DataPolicyConditionResult[];\n\t\tvalidationErrors?: string[];\n\t};\n\tcode?: {\n\t\trequestedPolicyId?: PolicyId;\n\t\tpolicyId: PolicyId;\n\t\tversion?: number;\n\t\tregistered: boolean;\n\t\tskipped?: boolean;\n\t\tskipReason?: string;\n\t};\n\tfallback?: {\n\t\tused: boolean;\n\t\ttrigger: PolicyFallbackTrigger | \"not_triggered\";\n\t\treason: string;\n\t\tfromResult?: PolicyEvaluationResult;\n\t\tdefinitionVersion: number;\n\t\tcodeEvaluatorPolicyId: PolicyId;\n\t};\n\t/**\n\t * Provenance for the engine that produced this decision when a code\n\t * evaluator delegates to an external policy engine (OPA, Cedar, Cerbos,\n\t * Topaz, etc.). Fabric's `policyId` / `policyVersion` remain canonical for\n\t * audit; this block carries deployment provenance (decision path, bundle\n\t * revision, decision ID, input hash). Adapters populate it; the platform\n\t * keeps `metadata` open-ended so engine-specific typing can live in the\n\t * adapter package.\n\t */\n\tengine?: {\n\t\tname: string;\n\t\tversion?: string;\n\t\tmetadata?: Record<string, unknown>;\n\t};\n}\n\nexport interface PolicyRegistry {\n\tregister(evaluator: PolicyEvaluator): void;\n\tregisterIfMissing(evaluator: PolicyEvaluator): void;\n\tresolve(policyId: PolicyId): PolicyEvaluator | undefined;\n\tids(): PolicyId[];\n}\n\nexport function createPolicyRegistry(evaluators: readonly PolicyEvaluator[] = []): PolicyRegistry {\n\tconst policies = new Map<PolicyId, PolicyEvaluator>();\n\tconst register = (evaluator: PolicyEvaluator): void => {\n\t\tassertPolicyId(evaluator.policyId);\n\t\tconst existing = policies.get(evaluator.policyId);\n\t\tif (existing && existing !== evaluator) throw new Error(`Conflicting policy registration for \"${evaluator.policyId}\". A different evaluator is already registered.`);\n\t\tpolicies.set(evaluator.policyId, evaluator);\n\t};\n\tfor (const evaluator of evaluators) register(evaluator);\n\treturn {\n\t\tregister,\n\t\tregisterIfMissing(evaluator) {\n\t\t\tconst existing = policies.get(evaluator.policyId);\n\t\t\tif (!existing) register(evaluator);\n\t\t\telse if (existing !== evaluator) throw new Error(`Conflicting policy registration for \"${evaluator.policyId}\". A different evaluator is already registered.`);\n\t\t},\n\t\tresolve: (policyId) => policies.get(policyId),\n\t\tids: () => Array.from(policies.keys()),\n\t};\n}\n\nexport async function evaluateRegisteredPolicies(\n\tpolicyIds: PolicyId[],\n\tctx: PolicyContext,\n): Promise<PolicyOutcome[]> {\n\treturn evaluatePolicyDefinitions(\n\t\tpolicyIds.map((policyId) => ({\n\t\t\tpolicyId,\n\t\t\tpolicyVersion: parsePolicyVersion(policyId),\n\t\t\tkind: \"code\",\n\t\t\tcodeEvaluatorPolicyId: policyId,\n\t\t})),\n\t\tctx,\n\t);\n}\n\nexport async function evaluatePolicyDefinitions(\n\tpolicies: RuntimePolicyDefinition[],\n\tctx: PolicyContext,\n): Promise<PolicyOutcome[]> {\n\tconst outcomes: PolicyOutcome[] = [];\n\n\tfor (const policy of policies) {\n\t\tassertPolicyId(policy.policyId);\n\t\toutcomes.push(await evaluatePolicyDefinition(policy, ctx));\n\t}\n\n\treturn outcomes;\n}\n\nexport async function evaluatePolicyDefinition(\n\tpolicy: RuntimePolicyDefinition,\n\tctx: PolicyContext,\n): Promise<PolicyOutcome> {\n\t// Copy before awaiting so a resolver that mutates or replaces a cached\n\t// definition mid-evaluation cannot change the authority this outcome records.\n\tconst authority = policy.authority ? { ...policy.authority } : undefined;\n\tconst outcome =\n\t\tpolicy.kind === \"data\"\n\t\t\t? await evaluateDataPolicy(policy, ctx)\n\t\t\t: policy.kind === \"code\"\n\t\t\t\t? await evaluateCodePolicy(policy, ctx)\n\t\t\t\t: await evaluateHybridPolicy(policy, ctx);\n\tif (!authority) return outcome;\n\treturn {\n\t\t...outcome,\n\t\tdispatchEvidence: {\n\t\t\t...(outcome.dispatchEvidence ?? {\n\t\t\t\tpolicyKind: policy.kind,\n\t\t\t\tpolicyId: policy.policyId,\n\t\t\t\tpolicyVersion: policy.policyVersion,\n\t\t\t\tdispatchPath: [],\n\t\t\t}),\n\t\t\tauthority,\n\t\t},\n\t};\n}\n\nasync function evaluateCodePolicy(\n\tpolicy: RuntimePolicyDefinition,\n\tctx: PolicyContext,\n): Promise<PolicyOutcome> {\n\tconst codeEvaluatorPolicyId = policy.codeEvaluatorPolicyId ?? policy.policyId;\n\tconst evaluator = ctx.resolveCodePolicy?.(codeEvaluatorPolicyId);\n\n\tif (!evaluator) {\n\t\treturn {\n\t\t\tpolicyId: policy.policyId,\n\t\t\tpolicyVersion: policy.policyVersion,\n\t\t\tpolicyKind: policy.kind,\n\t\t\tresult: \"block\",\n\t\t\treason: `No evaluator registered for policy ${codeEvaluatorPolicyId}`,\n\t\t\tmetadata: {\n\t\t\t\tmissingCodeEvaluatorPolicyId: codeEvaluatorPolicyId,\n\t\t\t},\n\t\t\tdispatchEvidence: {\n\t\t\t\tpolicyKind: policy.kind,\n\t\t\t\tpolicyId: policy.policyId,\n\t\t\t\tpolicyVersion: policy.policyVersion,\n\t\t\t\tdispatchPath: [\"code\"],\n\t\t\t\tcode: {\n\t\t\t\t\trequestedPolicyId: codeEvaluatorPolicyId,\n\t\t\t\t\tpolicyId: codeEvaluatorPolicyId,\n\t\t\t\t\tregistered: false,\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t}\n\n\tif (ctx.mode === \"preview\" && evaluator.previewSafe !== true) {\n\t\tconst skipReason =\n\t\t\t`Policy ${evaluator.policyId} skipped in preview mode ` +\n\t\t\t`(evaluator is not declared previewSafe)`;\n\t\treturn {\n\t\t\tpolicyId: policy.policyId,\n\t\t\tpolicyVersion: policy.policyVersion,\n\t\t\tpolicyKind: policy.kind,\n\t\t\tresult: \"warn\",\n\t\t\treason: skipReason,\n\t\t\tmetadata: {\n\t\t\t\tcodePolicyId: evaluator.policyId,\n\t\t\t\tcodePolicyVersion: evaluator.version,\n\t\t\t\tpreviewSkipped: true,\n\t\t\t},\n\t\t\tdispatchEvidence: {\n\t\t\t\tpolicyKind: policy.kind,\n\t\t\t\tpolicyId: policy.policyId,\n\t\t\t\tpolicyVersion: policy.policyVersion,\n\t\t\t\tdispatchPath: [\"code\"],\n\t\t\t\tcode: {\n\t\t\t\t\trequestedPolicyId: codeEvaluatorPolicyId,\n\t\t\t\t\tpolicyId: evaluator.policyId,\n\t\t\t\t\tversion: evaluator.version,\n\t\t\t\t\tregistered: true,\n\t\t\t\t\tskipped: true,\n\t\t\t\t\tskipReason,\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t}\n\n\tconst outcome = await evaluator.evaluate(ctx);\n\treturn normalizeOutcome(policy, outcome, {\n\t\tpolicyKind: policy.kind,\n\t\tpolicyId: policy.policyId,\n\t\tpolicyVersion: policy.policyVersion,\n\t\tdispatchPath: [\"code\"],\n\t\tcode: {\n\t\t\trequestedPolicyId: codeEvaluatorPolicyId,\n\t\t\tpolicyId: evaluator.policyId,\n\t\t\tversion: evaluator.version,\n\t\t\tregistered: true,\n\t\t},\n\t});\n}\n\nasync function evaluateHybridPolicy(\n\tpolicy: RuntimePolicyDefinition,\n\tctx: PolicyContext,\n): Promise<PolicyOutcome> {\n\tconst dataOutcome = evaluateDataPolicy(policy, ctx);\n\tconst fallback = policy.fallback;\n\tconst fallbackDecision = fallback\n\t\t? resolveFallbackDecision(policy, dataOutcome, fallback)\n\t\t: { shouldFallback: false, trigger: \"not_triggered\" as const };\n\n\tif (!fallback || !fallbackDecision.shouldFallback) {\n\t\tif (fallback && dataOutcome.dispatchEvidence) {\n\t\t\treturn {\n\t\t\t\t...dataOutcome,\n\t\t\t\tdispatchEvidence: {\n\t\t\t\t\t...dataOutcome.dispatchEvidence,\n\t\t\t\t\tfallback: {\n\t\t\t\t\t\tused: false,\n\t\t\t\t\t\ttrigger: \"not_triggered\",\n\t\t\t\t\t\treason: \"Data policy result did not trigger fallback\",\n\t\t\t\t\t\tfromResult: dataOutcome.result,\n\t\t\t\t\t\tdefinitionVersion: policy.policyVersion,\n\t\t\t\t\t\tcodeEvaluatorPolicyId: fallback.codeEvaluatorPolicyId,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\treturn dataOutcome;\n\t}\n\n\tconst codePolicy: RuntimePolicyDefinition = {\n\t\tpolicyId: policy.policyId,\n\t\tpolicyVersion: policy.policyVersion,\n\t\tkind: \"hybrid\",\n\t\tcodeEvaluatorPolicyId: fallback.codeEvaluatorPolicyId,\n\t};\n\tconst codeOutcome = await evaluateCodePolicy(codePolicy, ctx);\n\n\treturn normalizeOutcome(policy, codeOutcome, {\n\t\t...(codeOutcome.dispatchEvidence ?? {\n\t\t\tpolicyKind: \"hybrid\",\n\t\t\tpolicyId: policy.policyId,\n\t\t\tpolicyVersion: policy.policyVersion,\n\t\t\tdispatchPath: [\"code\"],\n\t\t}),\n\t\tpolicyKind: \"hybrid\",\n\t\tpolicyId: policy.policyId,\n\t\tpolicyVersion: policy.policyVersion,\n\t\tdispatchPath: [\"data\", \"fallback\", \"code\"],\n\t\tdata: dataOutcome.dispatchEvidence?.data,\n\t\tfallback: {\n\t\t\tused: true,\n\t\t\ttrigger: fallbackDecision.trigger,\n\t\t\treason: fallback.reason ?? \"Data policy result triggered code fallback\",\n\t\t\tfromResult: dataOutcome.result,\n\t\t\tdefinitionVersion: policy.policyVersion,\n\t\t\tcodeEvaluatorPolicyId: fallback.codeEvaluatorPolicyId,\n\t\t},\n\t});\n}\n\nfunction resolveFallbackDecision(\n\tpolicy: RuntimePolicyDefinition,\n\tdataOutcome: PolicyOutcome,\n\tfallback: PolicyFallbackDefinition,\n): { shouldFallback: boolean; trigger: PolicyFallbackTrigger | \"not_triggered\" } {\n\tconst allowedTriggers = fallback.triggers ?? [\n\t\t\"data_result\",\n\t\t\"missing_data_definition\",\n\t\t\"invalid_data_definition\",\n\t];\n\tconst definitionStatus = dataOutcome.dispatchEvidence?.data?.definitionStatus;\n\n\tif (definitionStatus === \"missing\") {\n\t\treturn {\n\t\t\tshouldFallback: allowedTriggers.includes(\"missing_data_definition\"),\n\t\t\ttrigger: \"missing_data_definition\",\n\t\t};\n\t}\n\n\tif (definitionStatus === \"invalid\") {\n\t\treturn {\n\t\t\tshouldFallback: allowedTriggers.includes(\"invalid_data_definition\"),\n\t\t\ttrigger: \"invalid_data_definition\",\n\t\t};\n\t}\n\n\tconst fallbackResults = fallback.onResults ?? [\"warn\", \"block\"];\n\treturn {\n\t\tshouldFallback:\n\t\t\tpolicy.kind === \"hybrid\" &&\n\t\t\tallowedTriggers.includes(\"data_result\") &&\n\t\t\tfallbackResults.includes(dataOutcome.result),\n\t\ttrigger: \"data_result\",\n\t};\n}\n\nfunction evaluateDataPolicy(policy: RuntimePolicyDefinition, ctx: PolicyContext): PolicyOutcome {\n\tconst definition = policy.dataDefinition;\n\n\tif (!definition) {\n\t\treturn {\n\t\t\tpolicyId: policy.policyId,\n\t\t\tpolicyVersion: policy.policyVersion,\n\t\t\tpolicyKind: policy.kind,\n\t\t\tresult: \"block\",\n\t\t\treason: \"Data policy definition is missing\",\n\t\t\tdispatchEvidence: {\n\t\t\t\tpolicyKind: policy.kind,\n\t\t\t\tpolicyId: policy.policyId,\n\t\t\t\tpolicyVersion: policy.policyVersion,\n\t\t\t\tdispatchPath: [\"data\"],\n\t\t\t\tdata: {\n\t\t\t\t\tdefinitionVersion: policy.policyVersion,\n\t\t\t\t\tdefinitionStatus: \"missing\",\n\t\t\t\t\tconditionResults: [],\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t}\n\n\tconst validation = validateDataPolicyDefinition(definition);\n\tif (!validation.valid) {\n\t\treturn {\n\t\t\tpolicyId: policy.policyId,\n\t\t\tpolicyVersion: policy.policyVersion,\n\t\t\tpolicyKind: policy.kind,\n\t\t\tresult: \"block\",\n\t\t\treason: `Invalid data policy definition: ${validation.errors.join(\"; \")}`,\n\t\t\tmetadata: {\n\t\t\t\tvalidationErrors: validation.errors,\n\t\t\t},\n\t\t\tdispatchEvidence: {\n\t\t\t\tpolicyKind: policy.kind,\n\t\t\t\tpolicyId: policy.policyId,\n\t\t\t\tpolicyVersion: policy.policyVersion,\n\t\t\t\tdispatchPath: [\"data\"],\n\t\t\t\tdata: {\n\t\t\t\t\tdefinitionVersion: policy.policyVersion,\n\t\t\t\t\tdefinitionStatus: \"invalid\",\n\t\t\t\t\tconditionResults: [],\n\t\t\t\t\tvalidationErrors: validation.errors,\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t}\n\n\tconst evaluations = definition.conditions.map((condition) => evaluateDataPolicyCondition(condition, ctx));\n\tconst conditionResults = evaluations.flatMap((evaluation) => evaluation.evidence);\n\tconst topLevelResults = evaluations.map((evaluation) => evaluation.result);\n\tconst aggregate =\n\t\ttopLevelResults.find((result) => result.result === \"block\") ??\n\t\ttopLevelResults.find((result) => result.result === \"warn\");\n\tconst result = aggregate?.result ?? definition.defaultResult ?? \"pass\";\n\n\treturn {\n\t\tpolicyId: policy.policyId,\n\t\tpolicyVersion: policy.policyVersion,\n\t\tpolicyKind: policy.kind,\n\t\tresult,\n\t\treason: aggregate?.reason ?? definition.reason,\n\t\tmetadata: {\n\t\t\tconditionCount: definition.conditions.length,\n\t\t\tfailedConditionId: aggregate?.conditionId,\n\t\t},\n\t\tdispatchEvidence: {\n\t\t\tpolicyKind: policy.kind,\n\t\t\tpolicyId: policy.policyId,\n\t\t\tpolicyVersion: policy.policyVersion,\n\t\t\tdispatchPath: [\"data\"],\n\t\t\tdata: {\n\t\t\t\tdefinitionVersion: policy.policyVersion,\n\t\t\t\tdefinitionStatus: \"evaluated\",\n\t\t\t\tconditionResults,\n\t\t\t},\n\t\t},\n\t};\n}\n\nexport function validateDataPolicyDefinition(\n\tdefinition: DataPolicyDefinition,\n): DataPolicyValidationResult {\n\tconst errors: string[] = [];\n\n\tif (!Array.isArray(definition.conditions) || definition.conditions.length === 0) {\n\t\terrors.push(\"conditions must contain at least one condition\");\n\t} else if (definition.conditions.length > DATA_POLICY_MAX_CONDITIONS_PER_NODE) {\n\t\terrors.push(\n\t\t\t`conditions must contain at most ${DATA_POLICY_MAX_CONDITIONS_PER_NODE} top-level conditions`,\n\t\t);\n\t}\n\n\tif (definition.defaultResult && !POLICY_RESULTS.includes(definition.defaultResult)) {\n\t\terrors.push(\"defaultResult must be pass, warn, or block\");\n\t}\n\n\tlet totalConditions = 0;\n\tfor (const condition of definition.conditions ?? []) {\n\t\tvalidateDataPolicyCondition(condition, errors, 1, () => {\n\t\t\ttotalConditions += 1;\n\t\t});\n\t}\n\n\tif (totalConditions > DATA_POLICY_MAX_TOTAL_CONDITIONS) {\n\t\terrors.push(`policy must contain at most ${DATA_POLICY_MAX_TOTAL_CONDITIONS} total conditions`);\n\t}\n\n\treturn { valid: errors.length === 0, errors };\n}\n\nfunction validateDataPolicyCondition(\n\tcondition: DataPolicyCondition,\n\terrors: string[],\n\tdepth: number,\n\tcount: () => void,\n): void {\n\tcount();\n\n\tif (!condition || typeof condition !== \"object\") {\n\t\terrors.push(\"condition must be an object\");\n\t\treturn;\n\t}\n\n\tif (depth > DATA_POLICY_MAX_DEPTH) {\n\t\terrors.push(`condition depth must not exceed ${DATA_POLICY_MAX_DEPTH}`);\n\t\treturn;\n\t}\n\n\tif (!isNonEmptyBoundedString(condition.conditionId)) {\n\t\terrors.push(\"conditionId must be a non-empty bounded string\");\n\t}\n\n\tvalidateOptionalPolicyResult(\"onPass\" in condition ? condition.onPass : undefined, \"onPass\", errors);\n\tvalidateOptionalPolicyResult(\"onFail\" in condition ? condition.onFail : undefined, \"onFail\", errors);\n\n\tif (condition.reason !== undefined && !isNonEmptyBoundedString(condition.reason)) {\n\t\terrors.push(`condition ${condition.conditionId} reason must be a bounded string`);\n\t}\n\n\tif (condition.type === \"always\") {\n\t\tif (!POLICY_RESULTS.includes(condition.result)) {\n\t\t\terrors.push(`condition ${condition.conditionId} result must be pass, warn, or block`);\n\t\t}\n\t\treturn;\n\t}\n\n\tif (condition.type === \"parameter\") {\n\t\tvalidatePath(condition.path, `condition ${condition.conditionId} path`, errors);\n\t\tvalidateComparison(condition.operator, condition.value, condition.conditionId, errors);\n\t\treturn;\n\t}\n\n\tif (condition.type === \"comparison\") {\n\t\tvalidateSourceReference(condition.left, condition.conditionId, errors);\n\t\tvalidateComparison(condition.operator, condition.value, condition.conditionId, errors);\n\t\treturn;\n\t}\n\n\tif (condition.type === \"all\" || condition.type === \"any\") {\n\t\tif (!Array.isArray(condition.conditions) || condition.conditions.length === 0) {\n\t\t\terrors.push(`condition ${condition.conditionId} must contain child conditions`);\n\t\t\treturn;\n\t\t}\n\n\t\tif (condition.conditions.length > DATA_POLICY_MAX_CONDITIONS_PER_NODE) {\n\t\t\terrors.push(\n\t\t\t\t`condition ${condition.conditionId} must contain at most ${DATA_POLICY_MAX_CONDITIONS_PER_NODE} child conditions`,\n\t\t\t);\n\t\t}\n\n\t\tfor (const child of condition.conditions) {\n\t\t\tvalidateDataPolicyCondition(child, errors, depth + 1, count);\n\t\t}\n\t\treturn;\n\t}\n\n\tif (condition.type === \"not\") {\n\t\tvalidateDataPolicyCondition(condition.condition, errors, depth + 1, count);\n\t\treturn;\n\t}\n\n\terrors.push(`condition ${condition.conditionId} has unsupported type`);\n}\n\nfunction validateOptionalPolicyResult(\n\tresult: PolicyEvaluationResult | undefined,\n\tfieldName: string,\n\terrors: string[],\n): void {\n\tif (result !== undefined && !POLICY_RESULTS.includes(result)) {\n\t\terrors.push(`${fieldName} must be pass, warn, or block`);\n\t}\n}\n\nfunction validateSourceReference(\n\treference: DataPolicySourceReference,\n\tconditionId: string,\n\terrors: string[],\n): void {\n\tif (!reference || typeof reference !== \"object\") {\n\t\terrors.push(`condition ${conditionId} left must be a source reference`);\n\t\treturn;\n\t}\n\n\tif (reference.source !== \"parameters\" && reference.source !== \"context\") {\n\t\terrors.push(`condition ${conditionId} source must be parameters or context`);\n\t}\n\n\tvalidatePath(reference.path, `condition ${conditionId} left.path`, errors);\n\n\tif (reference.source === \"context\" && !DATA_POLICY_CONTEXT_PATHS.includes(reference.path)) {\n\t\terrors.push(`condition ${conditionId} uses an unsupported context path`);\n\t}\n}\n\nfunction validateComparison(\n\toperator: DataPolicyComparisonOperator,\n\tvalue: DataPolicyLiteral | undefined,\n\tconditionId: string,\n\terrors: string[],\n): void {\n\tif (!DATA_POLICY_COMPARISON_OPERATORS.includes(operator)) {\n\t\terrors.push(`condition ${conditionId} has unsupported operator`);\n\t\treturn;\n\t}\n\n\tif (operator === \"exists\") {\n\t\treturn;\n\t}\n\n\tif (!isDataPolicyLiteral(value)) {\n\t\terrors.push(`condition ${conditionId} comparison value must be a bounded literal`);\n\t\treturn;\n\t}\n\n\tif ([\"gt\", \"gte\", \"lt\", \"lte\"].includes(operator) && typeof value !== \"number\") {\n\t\terrors.push(`condition ${conditionId} numeric comparison requires a number value`);\n\t}\n}\n\nfunction validatePath(path: string, fieldName: string, errors: string[]): void {\n\tif (!isNonEmptyBoundedString(path)) {\n\t\terrors.push(`${fieldName} must be a non-empty bounded string`);\n\t\treturn;\n\t}\n\n\tconst segments = path.split(\".\");\n\tif (segments.length > DATA_POLICY_MAX_PATH_SEGMENTS) {\n\t\terrors.push(`${fieldName} must contain at most ${DATA_POLICY_MAX_PATH_SEGMENTS} segments`);\n\t\treturn;\n\t}\n\n\tfor (const segment of segments) {\n\t\tif (!/^[A-Za-z][A-Za-z0-9_-]*$/.test(segment)) {\n\t\t\terrors.push(`${fieldName} contains an invalid path segment`);\n\t\t\treturn;\n\t\t}\n\n\t\tif ([\"__proto__\", \"constructor\", \"prototype\"].includes(segment)) {\n\t\t\terrors.push(`${fieldName} contains a forbidden path segment`);\n\t\t\treturn;\n\t\t}\n\t}\n}\n\nfunction isDataPolicyLiteral(value: unknown): value is DataPolicyLiteral {\n\tif (value === null || typeof value === \"number\" || typeof value === \"boolean\") {\n\t\treturn true;\n\t}\n\n\treturn typeof value === \"string\" && value.length <= DATA_POLICY_MAX_STRING_LENGTH;\n}\n\nfunction isNonEmptyBoundedString(value: unknown): value is string {\n\treturn typeof value === \"string\" && value.length > 0 && value.length <= DATA_POLICY_MAX_STRING_LENGTH;\n}\n\nfunction evaluateDataPolicyCondition(\n\tcondition: DataPolicyCondition,\n\tctx: PolicyContext,\n): { result: DataPolicyConditionResult; evidence: DataPolicyConditionResult[] } {\n\tif (condition.type === \"always\") {\n\t\tconst result = {\n\t\t\tconditionId: condition.conditionId,\n\t\t\tpassed: condition.result === \"pass\",\n\t\t\tresult: condition.result,\n\t\t\treason: condition.reason,\n\t\t};\n\t\treturn { result, evidence: [result] };\n\t}\n\n\tif (condition.type === \"all\" || condition.type === \"any\") {\n\t\tconst childEvaluations = condition.conditions.map((child) => evaluateDataPolicyCondition(child, ctx));\n\t\tconst passed =\n\t\t\tcondition.type === \"all\"\n\t\t\t\t? childEvaluations.every((evaluation) => evaluation.result.passed)\n\t\t\t\t: childEvaluations.some((evaluation) => evaluation.result.passed);\n\t\tconst result = {\n\t\t\tconditionId: condition.conditionId,\n\t\t\tpassed,\n\t\t\tresult: passed ? (condition.onPass ?? \"pass\") : (condition.onFail ?? \"block\"),\n\t\t\treason: passed ? undefined : condition.reason,\n\t\t};\n\n\t\treturn {\n\t\t\tresult,\n\t\t\tevidence: [result, ...childEvaluations.flatMap((evaluation) => evaluation.evidence)],\n\t\t};\n\t}\n\n\tif (condition.type === \"not\") {\n\t\tconst childEvaluation = evaluateDataPolicyCondition(condition.condition, ctx);\n\t\tconst passed = !childEvaluation.result.passed;\n\t\tconst result = {\n\t\t\tconditionId: condition.conditionId,\n\t\t\tpassed,\n\t\t\tresult: passed ? (condition.onPass ?? \"pass\") : (condition.onFail ?? \"block\"),\n\t\t\treason: passed ? undefined : condition.reason,\n\t\t};\n\n\t\treturn { result, evidence: [result, ...childEvaluation.evidence] };\n\t}\n\n\tif (condition.type !== \"parameter\" && condition.type !== \"comparison\") {\n\t\tconst result: DataPolicyConditionResult = {\n\t\t\tconditionId: condition.conditionId,\n\t\t\tpassed: false,\n\t\t\tresult: \"block\",\n\t\t\treason: \"Unsupported data policy condition type\",\n\t\t};\n\t\treturn { result, evidence: [result] };\n\t}\n\n\tconst value =\n\t\tcondition.type === \"parameter\"\n\t\t\t? readPath(ctx.parameters, condition.path)\n\t\t\t: readDataPolicySource(ctx, condition.left);\n\tconst operator = condition.operator;\n\tconst expected = condition.value;\n\tconst passed = evaluateOperator(value, operator, expected);\n\tconst result = {\n\t\tconditionId: condition.conditionId,\n\t\tpassed,\n\t\tresult: passed ? (condition.onPass ?? \"pass\") : (condition.onFail ?? \"block\"),\n\t\treason: passed ? undefined : condition.reason,\n\t};\n\treturn { result, evidence: [result] };\n}\n\nfunction evaluateOperator(\n\tactual: unknown,\n\toperator: DataPolicyComparisonOperator,\n\texpected: unknown,\n): boolean {\n\tswitch (operator) {\n\t\tcase \"exists\":\n\t\t\treturn actual !== undefined && actual !== null && actual !== \"\";\n\t\tcase \"equals\":\n\t\t\treturn actual === expected;\n\t\tcase \"notEquals\":\n\t\t\treturn actual !== expected;\n\t\tcase \"gt\":\n\t\t\treturn typeof actual === \"number\" && typeof expected === \"number\" && actual > expected;\n\t\tcase \"gte\":\n\t\t\treturn typeof actual === \"number\" && typeof expected === \"number\" && actual >= expected;\n\t\tcase \"lt\":\n\t\t\treturn typeof actual === \"number\" && typeof expected === \"number\" && actual < expected;\n\t\tcase \"lte\":\n\t\t\treturn typeof actual === \"number\" && typeof expected === \"number\" && actual <= expected;\n\t}\n}\n\nfunction readDataPolicySource(ctx: PolicyContext, reference: DataPolicySourceReference): unknown {\n\tif (reference.source === \"parameters\") {\n\t\treturn readPath(ctx.parameters, reference.path);\n\t}\n\n\treturn readPath(\n\t\t{\n\t\t\ttenantId: ctx.tenantId,\n\t\t\tspaceId: ctx.spaceId,\n\t\t\tactionInvocationId: ctx.actionInvocationId,\n\t\t\tactionId: ctx.actionId,\n\t\t\tmode: ctx.mode,\n\t\t},\n\t\treference.path,\n\t);\n}\n\nfunction readPath(source: unknown, path: string): unknown {\n\tif (!source || typeof source !== \"object\") {\n\t\treturn undefined;\n\t}\n\n\treturn path.split(\".\").reduce<unknown>((current, segment) => {\n\t\tif (!current || typeof current !== \"object\") {\n\t\t\treturn undefined;\n\t\t}\n\n\t\treturn (current as Record<string, unknown>)[segment];\n\t}, source);\n}\n\nfunction normalizeOutcome(\n\tpolicy: RuntimePolicyDefinition,\n\toutcome: PolicyOutcome,\n\tdispatchEvidence: PolicyDispatchEvidence,\n): PolicyOutcome {\n\tif (outcome.guidance !== undefined) {\n\t\tconst guidanceValidation = validatePolicyGuidance(outcome.guidance);\n\t\tif (!guidanceValidation.valid) {\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid guidance for policy ${outcome.policyId}: ${guidanceValidation.errors.join(\"; \")}`,\n\t\t\t);\n\t\t}\n\t}\n\n\t// The platform owns the dispatch envelope (kind, id, version, path,\n\t// data/code/fallback blocks). Engine provenance is evaluator-controlled —\n\t// preserve it so BYO-engine adapters (OPA, Cedar, ...) can attach decision\n\t// path, bundle revision, decision ID, input hash, etc.\n\tconst engine = outcome.dispatchEvidence?.engine;\n\treturn {\n\t\t...outcome,\n\t\tpolicyId: policy.policyId,\n\t\tpolicyVersion: policy.policyVersion,\n\t\tpolicyKind: policy.kind,\n\t\tmetadata: {\n\t\t\t...(outcome.metadata ?? {}),\n\t\t\tcodePolicyId: dispatchEvidence.code?.policyId ?? outcome.policyId,\n\t\t\tcodePolicyVersion: dispatchEvidence.code?.version ?? outcome.policyVersion,\n\t\t},\n\t\tdispatchEvidence: engine ? { ...dispatchEvidence, engine } : dispatchEvidence,\n\t};\n}\n\nfunction parsePolicyVersion(policyId: PolicyId): number {\n\tconst segments = policyId.split(\".v\");\n\treturn Number(segments[segments.length - 1] ?? 1);\n}\n\nexport function aggregatePolicyOutcomes(outcomes: PolicyOutcome[]): PolicyOutcome | undefined {\n\treturn (\n\t\toutcomes.find((outcome) => outcome.result === \"block\") ??\n\t\toutcomes.find((outcome) => outcome.result === \"warn\")\n\t);\n}\n"]}