@fabricorg/platform 1.8.0 → 1.9.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # @fabricorg/platform
2
2
 
3
+ ## 1.9.0
4
+
5
+ ### Minor Changes
6
+
7
+ - e32ee98: Add opt-in tenant/space/vendor circuit-breaker isolation (issue #52). Platform exports `AdapterCircuitBreakerScope` and `scopedAdapterCircuitBreakerKey` from the root and adapters subpath, accepts optional scope in providers, and adds registry `key` and `getByKey` APIs. Host passes trusted invocation tenant/space scope to providers.
8
+
9
+ The default `adapterType:operation` key and its shared failure domain are unchanged. Consumers can inject `new AdapterCircuitBreakerRegistry({ key: scopedAdapterCircuitBreakerKey })` to prevent one tenant's failures from refusing another tenant's calls. The helper encodes components, distinguishes absent space/vendor from empty values, and uses a separate vendor-specific unscoped namespace when scope is absent. Calls without scope share that namespace; tenant isolation requires scope. Keys appear in telemetry and errors, so use non-secret identifiers.
10
+
11
+ The first config seen for a key wins, including custom keys; later conflicting configs reuse the existing breaker without throwing. Existing one-argument providers remain compatible. Host's `workspace:^` Platform peer declaration is unchanged: passing an extra argument is compatible with older implementations, and Host adds no runtime import of the new helper. Release tooling resolves the workspace peer against the released Platform version.
12
+
13
+ - 4e429a3: Add `RetryableExecutionError` and `isRetryableExecutionError` to Platform's root and policies exports (issue #56). The error accepts a message and optional cause; its stable name and `EXECUTION_RETRYABLE` code support recognition across package copies.
14
+
15
+ Host adds `retryableExecutionMaxAttempts` (positive integer, default 5). During governance before policy-evaluation persistence, the error is rethrown unchanged for a leased, idempotent invocation below that cap, excluding approval resume. Workers report it through `onError`, stop the heartbeat, and can reclaim the invocation after lease expiry. Cycle results and `worker.cycle.completed` telemetry include an optional `deferred` count when positive; it counts every `RetryableExecutionError` that escapes execution, and those do not increment `failed`.
16
+
17
+ The retry region covers parameter validation, mutation-governance resolution and its single-record checkpoint write, HITL evaluation and its single-record checkpoint write, entitlement, execution authorization, policy resolution, and policy evaluation. Host reuses persisted mutation-governance and HITL decisions through checkpoint guards. The region ends before the first policy-evaluation record is written. Policy persistence, `ComplianceBlocked`, obligation listing/resolution/persistence, state-machine checks, the handler transaction, handlers, adapters, and finalization retain their existing failure/reconciliation/recovery semantics.
18
+
19
+ **Release note: failure semantics (issue #56).** Previously a transient thrown governance error terminally failed the invocation. Opting into `RetryableExecutionError` now leaves an eligible invocation `running` for lease-based recovery, with no failure/status write and no policy evidence written by that attempt. Unleased inline execution, approval resume, non-idempotent actions, and attempts at the cap fail with an explanatory message through the existing redactor. Approval resume's temporary lease does not establish that a recovery worker is configured. Obligation-resolver and policy/obligation-persistence errors remain terminal. Application callbacks should be repeatable and use stable invocation-scoped evidence. Host's Platform peer range remains `workspace:^` so published packages require the Platform release containing the new runtime exports.
20
+
3
21
  ## 1.8.0
4
22
 
5
23
  ### Minor Changes
package/README.md CHANGED
@@ -110,6 +110,16 @@ An action may also declare `admitSubmission`, an async check that decides whethe
110
110
  Every `invokeAction(id, params)` call goes through:
111
111
 
112
112
  1. **`evaluatePolicies`** — every policy registered for the action runs (code/data/hybrid). A single `block` halts the invocation. Policies may return `guidance` (`factsUsed` + typed `correctiveActions`) so hosts can show exactly why a block happened and what the operator can do next. Corrective actions declare `kind: "invoke_action" | "navigate" | "manual"` so UIs do not guess whether a remediation is executable.
113
+
114
+ Code-policy evaluators may throw `RetryableExecutionError(message, { cause })` for transient
115
+ dependency failures. Import it and `isRetryableExecutionError` from `@fabricorg/platform` or
116
+ `@fabricorg/platform/policies`. The predicate recognises matching `name` and `code` across package
117
+ copies. Platform propagates this error; Platform Host retries pre-handler governance only for a
118
+ leased, idempotent invocation below its `retryableExecutionMaxAttempts` cap (default 5), after
119
+ lease expiry, before policy evidence is written. Inline execution, non-idempotent actions,
120
+ approval resume, and exhausted attempts fail terminally. Obligation resolution and persistence
121
+ are outside this retry region. This signal does not change handler or adapter retry behavior.
122
+
113
123
  2. **State-machine validation** — if the action's target entity is bound to a state machine, the Host reads authoritative state at the mutation boundary, validates the requested transition, and executes its guard with trusted entity, actor, parameter, invocation, and database context. A false or throwing guard fails closed.
114
124
  3. **Handler** — `actionDef.handler(ctx, params)` runs inside a single `TDb` transaction. Handler parses its own input via its `schema` (single source of truth).
115
125
  4. **Adapters** — for each `actionDef.adapterSteps`, the registered implementation runs via `executeWithAdapterRetry` (idempotent retry, exponential backoff, and an optional per-adapter circuit breaker; see [Adapter circuit breakers](#adapter-circuit-breakers)). Adapters may classify outcomes as `success`, `transient_failure`, `permanent_failure`, `timeout`, or `ambiguous`; only transient idempotent outcomes are retried. Ambiguous outcomes are routed to `reconciliation_required` with durable evidence.
@@ -133,8 +143,34 @@ const sendAdapter: AdapterImplementation = {
133
143
  };
134
144
  ```
135
145
 
136
- `AdapterCircuitBreakerRegistry` creates one `InMemoryAdapterCircuitBreaker` per `adapterType:operation`
137
- from each adapter's own config, on first use, and none for an adapter without a config.
146
+ `AdapterCircuitBreakerRegistry` creates one `InMemoryAdapterCircuitBreaker` per key
147
+ (default `adapterType:operation`) from an adapter's config on first use, and none for an adapter
148
+ without a config. The first config seen for a key wins: later conflicting configs reuse the existing
149
+ breaker without throwing. Adapters sharing a key should use the same configuration.
150
+
151
+ The default key is shared across tenants, spaces, and vendors within one registry. Failures for one
152
+ tenant can therefore open the breaker for another. Opt into isolation when failure domains differ:
153
+
154
+ ```ts
155
+ import { AdapterCircuitBreakerRegistry, scopedAdapterCircuitBreakerKey } from "@fabricorg/platform/adapters";
156
+
157
+ const breakers = new AdapterCircuitBreakerRegistry({ key: scopedAdapterCircuitBreakerKey });
158
+ const scope = { tenantId: "tenant-1", spaceId: "space-1" };
159
+ const breaker = breakers.forAdapter(sendAdapter, scope);
160
+ // Exact custom-key lookup without creating a breaker:
161
+ breakers.getByKey(scopedAdapterCircuitBreakerKey(sendAdapter, scope));
162
+ ```
163
+
164
+ The helper URI-encodes tenant, space, vendor, and adapter identifiers to avoid delimiter collisions,
165
+ ending with the readable `adapterType:operation` for ordinary identifiers. Missing space or vendor
166
+ is distinct from an empty string (`vendor` is required by the TypeScript adapter contract).
167
+ Undefined scope uses a separate vendor-specific `unscoped` namespace rather than rejecting the call.
168
+ Calls without scope share that namespace; pass scope for tenant isolation. Keys appear
169
+ in telemetry and errors, so use non-secret identifiers.
170
+ Breakers are never evicted: a scoped key creates one breaker per tenant, space, vendor and operation
171
+ for the life of the registry, and those keys are high-cardinality, so do not use them as metric labels. `get(type, operation)` retains its default-key
172
+ lookup; use `getByKey(key)` for custom keys. A custom `key(adapter, scope)` can select other failure domains.
173
+
138
174
  `executeWithAdapterRetry({ ..., circuitBreaker })` asks it for admission immediately before every
139
175
  attempt, with no await between admission and the `execute` call, and records the outcome of every
140
176
  attempt that reached `execute`. Put any awaited work an attempt needs first (for example, writing
@@ -1,64 +1,68 @@
1
1
  'use strict';
2
2
 
3
- var chunkIF6NJORI_cjs = require('../chunk-IF6NJORI.cjs');
3
+ var chunkAFXKSIVI_cjs = require('../chunk-AFXKSIVI.cjs');
4
4
 
5
5
 
6
6
 
7
7
  Object.defineProperty(exports, "AdapterCircuitBreakerRegistry", {
8
8
  enumerable: true,
9
- get: function () { return chunkIF6NJORI_cjs.AdapterCircuitBreakerRegistry; }
9
+ get: function () { return chunkAFXKSIVI_cjs.AdapterCircuitBreakerRegistry; }
10
10
  });
11
11
  Object.defineProperty(exports, "AdapterCircuitOpenError", {
12
12
  enumerable: true,
13
- get: function () { return chunkIF6NJORI_cjs.AdapterCircuitOpenError; }
13
+ get: function () { return chunkAFXKSIVI_cjs.AdapterCircuitOpenError; }
14
14
  });
15
15
  Object.defineProperty(exports, "AdapterRegistry", {
16
16
  enumerable: true,
17
- get: function () { return chunkIF6NJORI_cjs.AdapterRegistry; }
17
+ get: function () { return chunkAFXKSIVI_cjs.AdapterRegistry; }
18
18
  });
19
19
  Object.defineProperty(exports, "InMemoryAdapterCircuitBreaker", {
20
20
  enumerable: true,
21
- get: function () { return chunkIF6NJORI_cjs.InMemoryAdapterCircuitBreaker; }
21
+ get: function () { return chunkAFXKSIVI_cjs.InMemoryAdapterCircuitBreaker; }
22
22
  });
23
23
  Object.defineProperty(exports, "MissingAdapterRegistrationError", {
24
24
  enumerable: true,
25
- get: function () { return chunkIF6NJORI_cjs.MissingAdapterRegistrationError; }
25
+ get: function () { return chunkAFXKSIVI_cjs.MissingAdapterRegistrationError; }
26
26
  });
27
27
  Object.defineProperty(exports, "assertAdapterCircuitBreakerConfig", {
28
28
  enumerable: true,
29
- get: function () { return chunkIF6NJORI_cjs.assertAdapterCircuitBreakerConfig; }
29
+ get: function () { return chunkAFXKSIVI_cjs.assertAdapterCircuitBreakerConfig; }
30
30
  });
31
31
  Object.defineProperty(exports, "assertAdapterOutcomeConsistency", {
32
32
  enumerable: true,
33
- get: function () { return chunkIF6NJORI_cjs.assertAdapterOutcomeConsistency; }
33
+ get: function () { return chunkAFXKSIVI_cjs.assertAdapterOutcomeConsistency; }
34
34
  });
35
35
  Object.defineProperty(exports, "classifyAdapterOutcome", {
36
36
  enumerable: true,
37
- get: function () { return chunkIF6NJORI_cjs.classifyAdapterOutcome; }
37
+ get: function () { return chunkAFXKSIVI_cjs.classifyAdapterOutcome; }
38
38
  });
39
39
  Object.defineProperty(exports, "classifyCircuitBreakerOutcome", {
40
40
  enumerable: true,
41
- get: function () { return chunkIF6NJORI_cjs.classifyCircuitBreakerOutcome; }
41
+ get: function () { return chunkAFXKSIVI_cjs.classifyCircuitBreakerOutcome; }
42
42
  });
43
43
  Object.defineProperty(exports, "executeWithAdapterRetry", {
44
44
  enumerable: true,
45
- get: function () { return chunkIF6NJORI_cjs.executeWithAdapterRetry; }
45
+ get: function () { return chunkAFXKSIVI_cjs.executeWithAdapterRetry; }
46
46
  });
47
47
  Object.defineProperty(exports, "getRetryDelayMs", {
48
48
  enumerable: true,
49
- get: function () { return chunkIF6NJORI_cjs.getRetryDelayMs; }
49
+ get: function () { return chunkAFXKSIVI_cjs.getRetryDelayMs; }
50
50
  });
51
51
  Object.defineProperty(exports, "isAdapterCircuitOpenError", {
52
52
  enumerable: true,
53
- get: function () { return chunkIF6NJORI_cjs.isAdapterCircuitOpenError; }
53
+ get: function () { return chunkAFXKSIVI_cjs.isAdapterCircuitOpenError; }
54
54
  });
55
55
  Object.defineProperty(exports, "resolveAdapterRetryPolicy", {
56
56
  enumerable: true,
57
- get: function () { return chunkIF6NJORI_cjs.resolveAdapterRetryPolicy; }
57
+ get: function () { return chunkAFXKSIVI_cjs.resolveAdapterRetryPolicy; }
58
+ });
59
+ Object.defineProperty(exports, "scopedAdapterCircuitBreakerKey", {
60
+ enumerable: true,
61
+ get: function () { return chunkAFXKSIVI_cjs.scopedAdapterCircuitBreakerKey; }
58
62
  });
59
63
  Object.defineProperty(exports, "shouldRetryAdapterOutcome", {
60
64
  enumerable: true,
61
- get: function () { return chunkIF6NJORI_cjs.shouldRetryAdapterOutcome; }
65
+ get: function () { return chunkAFXKSIVI_cjs.shouldRetryAdapterOutcome; }
62
66
  });
63
67
  //# sourceMappingURL=index.cjs.map
64
68
  //# sourceMappingURL=index.cjs.map
@@ -72,7 +72,7 @@ interface AdapterCircuitAdmission {
72
72
  * Implement it to plug in a shared or distributed breaker.
73
73
  */
74
74
  interface AdapterCircuitBreaker {
75
- /** `adapterType:operation` this breaker guards. */
75
+ /** Registry key this breaker guards; defaults to `adapterType:operation`. */
76
76
  readonly key: string;
77
77
  readonly mode: "monitor" | "enforce";
78
78
  /** Current state, applying any elapsed cooldown or manual override. */
@@ -273,28 +273,60 @@ declare class InMemoryAdapterCircuitBreaker implements AdapterCircuitBreaker {
273
273
  private flush;
274
274
  private deliver;
275
275
  }
276
- /** Supplies the breaker, if any, that guards an adapter. */
276
+ /** Trusted invocation context available when selecting an adapter breaker. */
277
+ interface AdapterCircuitBreakerScope {
278
+ tenantId: string;
279
+ spaceId?: string;
280
+ }
281
+ /**
282
+ * Key by tenant, optional space, vendor, and adapter operation. Components are
283
+ * URI-encoded to distinguish embedded delimiters; ordinary adapter identifiers
284
+ * remain readable as the trailing `adapterType:operation`.
285
+ *
286
+ * Missing scope uses a separate `unscoped` namespace (still split by vendor)
287
+ * rather than rejecting the call. Calls without scope share that
288
+ * namespace; callers must supply scope for tenant isolation. Missing space or
289
+ * vendor is distinct from an empty string. `vendor` is required by the public
290
+ * adapter type, but its absence is tolerated for JavaScript callers.
291
+ * Keys appear in errors and telemetry: use non-secret identifiers.
292
+ */
293
+ declare function scopedAdapterCircuitBreakerKey(adapter: AdapterImplementation, scope: AdapterCircuitBreakerScope | undefined): string;
294
+ /** Supplies the breaker, if any, that guards an adapter in invocation scope. */
277
295
  interface AdapterCircuitBreakerProvider {
278
- forAdapter(adapter: AdapterImplementation): AdapterCircuitBreaker | undefined;
296
+ forAdapter(adapter: AdapterImplementation, scope?: AdapterCircuitBreakerScope): AdapterCircuitBreaker | undefined;
279
297
  }
280
298
  interface AdapterCircuitBreakerRegistryOptions {
299
+ /**
300
+ * Defaults to `adapterType:operation`, shared across tenants and vendors in
301
+ * this registry. Use {@link scopedAdapterCircuitBreakerKey} for tenant,
302
+ * space, and vendor isolation. The first config seen for a key wins;
303
+ * later conflicting configs reuse that breaker without throwing. Breakers
304
+ * are never evicted, and scoped keys are high-cardinality: avoid them as
305
+ * metric labels.
306
+ */
307
+ key?: (adapter: AdapterImplementation, scope: AdapterCircuitBreakerScope | undefined) => string;
281
308
  /** Epoch-millisecond clock handed to every breaker. Defaults to `Date.now`. */
282
309
  now?: () => number;
283
310
  onEvent?: AdapterCircuitBreakerEventListener;
284
311
  }
285
312
  /**
286
313
  * Lazily creates one {@link InMemoryAdapterCircuitBreaker} per
287
- * `adapterType:operation`, from that adapter's own `circuitBreaker` config.
314
+ * key, from that adapter's own `circuitBreaker` config. The default key is
315
+ * `adapterType:operation`, shared across tenants and vendors; override it with
316
+ * {@link AdapterCircuitBreakerRegistryOptions.key} to isolate invocation scopes.
288
317
  * Adapters without a config get no breaker. The first config seen for a key
289
- * wins; share a registry only between hosts that register the same adapters.
318
+ * wins; later conflicting configs reuse the existing breaker without throwing.
319
+ * Share a key only between adapters intended to use the same configuration.
290
320
  */
291
321
  declare class AdapterCircuitBreakerRegistry implements AdapterCircuitBreakerProvider {
292
322
  private readonly options;
293
323
  private readonly breakers;
294
324
  constructor(options?: AdapterCircuitBreakerRegistryOptions);
295
- forAdapter(adapter: AdapterImplementation): InMemoryAdapterCircuitBreaker | undefined;
296
- /** The breaker already created for `adapterType:operation`, if any. */
325
+ forAdapter(adapter: AdapterImplementation, scope?: AdapterCircuitBreakerScope): InMemoryAdapterCircuitBreaker | undefined;
326
+ /** Looks up the default `adapterType:operation` key without creating a breaker. */
297
327
  get(adapterType: string, operation: string): InMemoryAdapterCircuitBreaker | undefined;
328
+ /** Looks up an exact key, including a custom key, without creating a breaker. */
329
+ getByKey(key: string): InMemoryAdapterCircuitBreaker | undefined;
298
330
  }
299
331
  /**
300
332
  * Thrown by `executeWithAdapterRetry` when an `enforce`-mode breaker refuses
@@ -425,7 +457,8 @@ type AdapterCircuitBreakerManualOverride = "force_open" | "force_closed";
425
457
  /**
426
458
  * Per-adapter circuit-breaker configuration, read by
427
459
  * {@link AdapterCircuitBreakerRegistry} (and so by Platform Host) to create one
428
- * in-process {@link InMemoryAdapterCircuitBreaker} per `adapterType:operation`.
460
+ * in-process {@link InMemoryAdapterCircuitBreaker} per registry key (default
461
+ * `adapterType:operation`; configurable through the registry `key` option).
429
462
  * Validated by {@link assertAdapterCircuitBreakerConfig}.
430
463
  */
431
464
  interface AdapterCircuitBreakerConfig {
@@ -558,4 +591,4 @@ declare function shouldRetryAdapterOutcome(kind: AdapterOutcomeKind, idempotent:
558
591
  declare function assertAdapterOutcomeConsistency(result: AdapterExecutionResult): void;
559
592
  declare function executeWithAdapterRetry<T>(options: ExecuteWithRetryOptions<T>): Promise<T>;
560
593
 
561
- export { type AcceptedExternalOperation, type AdapterAttempt, type AdapterCircuitAdmission, type AdapterCircuitBreaker, type AdapterCircuitBreakerConfig, type AdapterCircuitBreakerEvent, type AdapterCircuitBreakerEventListener, type AdapterCircuitBreakerEventReason, type AdapterCircuitBreakerManualOverride, type AdapterCircuitBreakerProvider, AdapterCircuitBreakerRegistry, type AdapterCircuitBreakerRegistryOptions, AdapterCircuitOpenError, type AdapterCircuitOutcome, type AdapterCircuitState, type AdapterExecutionContext, type AdapterExecutionResult, type AdapterExecutor, type AdapterImplementation, type AdapterOutcomeEvidence, type AdapterOutcomeKind, AdapterRegistry, type AdapterRetryPolicy, type ExecuteWithRetryOptions, InMemoryAdapterCircuitBreaker, type InMemoryAdapterCircuitBreakerOptions, MissingAdapterRegistrationError, type ResolvedAdapterRetryPolicy, assertAdapterCircuitBreakerConfig, assertAdapterOutcomeConsistency, classifyAdapterOutcome, classifyCircuitBreakerOutcome, executeWithAdapterRetry, getRetryDelayMs, isAdapterCircuitOpenError, resolveAdapterRetryPolicy, shouldRetryAdapterOutcome };
594
+ export { type AcceptedExternalOperation, type AdapterAttempt, type AdapterCircuitAdmission, type AdapterCircuitBreaker, type AdapterCircuitBreakerConfig, type AdapterCircuitBreakerEvent, type AdapterCircuitBreakerEventListener, type AdapterCircuitBreakerEventReason, type AdapterCircuitBreakerManualOverride, type AdapterCircuitBreakerProvider, AdapterCircuitBreakerRegistry, type AdapterCircuitBreakerRegistryOptions, type AdapterCircuitBreakerScope, AdapterCircuitOpenError, type AdapterCircuitOutcome, type AdapterCircuitState, type AdapterExecutionContext, type AdapterExecutionResult, type AdapterExecutor, type AdapterImplementation, type AdapterOutcomeEvidence, type AdapterOutcomeKind, AdapterRegistry, type AdapterRetryPolicy, type ExecuteWithRetryOptions, InMemoryAdapterCircuitBreaker, type InMemoryAdapterCircuitBreakerOptions, MissingAdapterRegistrationError, type ResolvedAdapterRetryPolicy, assertAdapterCircuitBreakerConfig, assertAdapterOutcomeConsistency, classifyAdapterOutcome, classifyCircuitBreakerOutcome, executeWithAdapterRetry, getRetryDelayMs, isAdapterCircuitOpenError, resolveAdapterRetryPolicy, scopedAdapterCircuitBreakerKey, shouldRetryAdapterOutcome };
@@ -72,7 +72,7 @@ interface AdapterCircuitAdmission {
72
72
  * Implement it to plug in a shared or distributed breaker.
73
73
  */
74
74
  interface AdapterCircuitBreaker {
75
- /** `adapterType:operation` this breaker guards. */
75
+ /** Registry key this breaker guards; defaults to `adapterType:operation`. */
76
76
  readonly key: string;
77
77
  readonly mode: "monitor" | "enforce";
78
78
  /** Current state, applying any elapsed cooldown or manual override. */
@@ -273,28 +273,60 @@ declare class InMemoryAdapterCircuitBreaker implements AdapterCircuitBreaker {
273
273
  private flush;
274
274
  private deliver;
275
275
  }
276
- /** Supplies the breaker, if any, that guards an adapter. */
276
+ /** Trusted invocation context available when selecting an adapter breaker. */
277
+ interface AdapterCircuitBreakerScope {
278
+ tenantId: string;
279
+ spaceId?: string;
280
+ }
281
+ /**
282
+ * Key by tenant, optional space, vendor, and adapter operation. Components are
283
+ * URI-encoded to distinguish embedded delimiters; ordinary adapter identifiers
284
+ * remain readable as the trailing `adapterType:operation`.
285
+ *
286
+ * Missing scope uses a separate `unscoped` namespace (still split by vendor)
287
+ * rather than rejecting the call. Calls without scope share that
288
+ * namespace; callers must supply scope for tenant isolation. Missing space or
289
+ * vendor is distinct from an empty string. `vendor` is required by the public
290
+ * adapter type, but its absence is tolerated for JavaScript callers.
291
+ * Keys appear in errors and telemetry: use non-secret identifiers.
292
+ */
293
+ declare function scopedAdapterCircuitBreakerKey(adapter: AdapterImplementation, scope: AdapterCircuitBreakerScope | undefined): string;
294
+ /** Supplies the breaker, if any, that guards an adapter in invocation scope. */
277
295
  interface AdapterCircuitBreakerProvider {
278
- forAdapter(adapter: AdapterImplementation): AdapterCircuitBreaker | undefined;
296
+ forAdapter(adapter: AdapterImplementation, scope?: AdapterCircuitBreakerScope): AdapterCircuitBreaker | undefined;
279
297
  }
280
298
  interface AdapterCircuitBreakerRegistryOptions {
299
+ /**
300
+ * Defaults to `adapterType:operation`, shared across tenants and vendors in
301
+ * this registry. Use {@link scopedAdapterCircuitBreakerKey} for tenant,
302
+ * space, and vendor isolation. The first config seen for a key wins;
303
+ * later conflicting configs reuse that breaker without throwing. Breakers
304
+ * are never evicted, and scoped keys are high-cardinality: avoid them as
305
+ * metric labels.
306
+ */
307
+ key?: (adapter: AdapterImplementation, scope: AdapterCircuitBreakerScope | undefined) => string;
281
308
  /** Epoch-millisecond clock handed to every breaker. Defaults to `Date.now`. */
282
309
  now?: () => number;
283
310
  onEvent?: AdapterCircuitBreakerEventListener;
284
311
  }
285
312
  /**
286
313
  * Lazily creates one {@link InMemoryAdapterCircuitBreaker} per
287
- * `adapterType:operation`, from that adapter's own `circuitBreaker` config.
314
+ * key, from that adapter's own `circuitBreaker` config. The default key is
315
+ * `adapterType:operation`, shared across tenants and vendors; override it with
316
+ * {@link AdapterCircuitBreakerRegistryOptions.key} to isolate invocation scopes.
288
317
  * Adapters without a config get no breaker. The first config seen for a key
289
- * wins; share a registry only between hosts that register the same adapters.
318
+ * wins; later conflicting configs reuse the existing breaker without throwing.
319
+ * Share a key only between adapters intended to use the same configuration.
290
320
  */
291
321
  declare class AdapterCircuitBreakerRegistry implements AdapterCircuitBreakerProvider {
292
322
  private readonly options;
293
323
  private readonly breakers;
294
324
  constructor(options?: AdapterCircuitBreakerRegistryOptions);
295
- forAdapter(adapter: AdapterImplementation): InMemoryAdapterCircuitBreaker | undefined;
296
- /** The breaker already created for `adapterType:operation`, if any. */
325
+ forAdapter(adapter: AdapterImplementation, scope?: AdapterCircuitBreakerScope): InMemoryAdapterCircuitBreaker | undefined;
326
+ /** Looks up the default `adapterType:operation` key without creating a breaker. */
297
327
  get(adapterType: string, operation: string): InMemoryAdapterCircuitBreaker | undefined;
328
+ /** Looks up an exact key, including a custom key, without creating a breaker. */
329
+ getByKey(key: string): InMemoryAdapterCircuitBreaker | undefined;
298
330
  }
299
331
  /**
300
332
  * Thrown by `executeWithAdapterRetry` when an `enforce`-mode breaker refuses
@@ -425,7 +457,8 @@ type AdapterCircuitBreakerManualOverride = "force_open" | "force_closed";
425
457
  /**
426
458
  * Per-adapter circuit-breaker configuration, read by
427
459
  * {@link AdapterCircuitBreakerRegistry} (and so by Platform Host) to create one
428
- * in-process {@link InMemoryAdapterCircuitBreaker} per `adapterType:operation`.
460
+ * in-process {@link InMemoryAdapterCircuitBreaker} per registry key (default
461
+ * `adapterType:operation`; configurable through the registry `key` option).
429
462
  * Validated by {@link assertAdapterCircuitBreakerConfig}.
430
463
  */
431
464
  interface AdapterCircuitBreakerConfig {
@@ -558,4 +591,4 @@ declare function shouldRetryAdapterOutcome(kind: AdapterOutcomeKind, idempotent:
558
591
  declare function assertAdapterOutcomeConsistency(result: AdapterExecutionResult): void;
559
592
  declare function executeWithAdapterRetry<T>(options: ExecuteWithRetryOptions<T>): Promise<T>;
560
593
 
561
- export { type AcceptedExternalOperation, type AdapterAttempt, type AdapterCircuitAdmission, type AdapterCircuitBreaker, type AdapterCircuitBreakerConfig, type AdapterCircuitBreakerEvent, type AdapterCircuitBreakerEventListener, type AdapterCircuitBreakerEventReason, type AdapterCircuitBreakerManualOverride, type AdapterCircuitBreakerProvider, AdapterCircuitBreakerRegistry, type AdapterCircuitBreakerRegistryOptions, AdapterCircuitOpenError, type AdapterCircuitOutcome, type AdapterCircuitState, type AdapterExecutionContext, type AdapterExecutionResult, type AdapterExecutor, type AdapterImplementation, type AdapterOutcomeEvidence, type AdapterOutcomeKind, AdapterRegistry, type AdapterRetryPolicy, type ExecuteWithRetryOptions, InMemoryAdapterCircuitBreaker, type InMemoryAdapterCircuitBreakerOptions, MissingAdapterRegistrationError, type ResolvedAdapterRetryPolicy, assertAdapterCircuitBreakerConfig, assertAdapterOutcomeConsistency, classifyAdapterOutcome, classifyCircuitBreakerOutcome, executeWithAdapterRetry, getRetryDelayMs, isAdapterCircuitOpenError, resolveAdapterRetryPolicy, shouldRetryAdapterOutcome };
594
+ export { type AcceptedExternalOperation, type AdapterAttempt, type AdapterCircuitAdmission, type AdapterCircuitBreaker, type AdapterCircuitBreakerConfig, type AdapterCircuitBreakerEvent, type AdapterCircuitBreakerEventListener, type AdapterCircuitBreakerEventReason, type AdapterCircuitBreakerManualOverride, type AdapterCircuitBreakerProvider, AdapterCircuitBreakerRegistry, type AdapterCircuitBreakerRegistryOptions, type AdapterCircuitBreakerScope, AdapterCircuitOpenError, type AdapterCircuitOutcome, type AdapterCircuitState, type AdapterExecutionContext, type AdapterExecutionResult, type AdapterExecutor, type AdapterImplementation, type AdapterOutcomeEvidence, type AdapterOutcomeKind, AdapterRegistry, type AdapterRetryPolicy, type ExecuteWithRetryOptions, InMemoryAdapterCircuitBreaker, type InMemoryAdapterCircuitBreakerOptions, MissingAdapterRegistrationError, type ResolvedAdapterRetryPolicy, assertAdapterCircuitBreakerConfig, assertAdapterOutcomeConsistency, classifyAdapterOutcome, classifyCircuitBreakerOutcome, executeWithAdapterRetry, getRetryDelayMs, isAdapterCircuitOpenError, resolveAdapterRetryPolicy, scopedAdapterCircuitBreakerKey, shouldRetryAdapterOutcome };
@@ -1,3 +1,3 @@
1
- export { AdapterCircuitBreakerRegistry, AdapterCircuitOpenError, AdapterRegistry, InMemoryAdapterCircuitBreaker, MissingAdapterRegistrationError, assertAdapterCircuitBreakerConfig, assertAdapterOutcomeConsistency, classifyAdapterOutcome, classifyCircuitBreakerOutcome, executeWithAdapterRetry, getRetryDelayMs, isAdapterCircuitOpenError, resolveAdapterRetryPolicy, shouldRetryAdapterOutcome } from '../chunk-5FOCPRTR.js';
1
+ export { AdapterCircuitBreakerRegistry, AdapterCircuitOpenError, AdapterRegistry, InMemoryAdapterCircuitBreaker, MissingAdapterRegistrationError, assertAdapterCircuitBreakerConfig, assertAdapterOutcomeConsistency, classifyAdapterOutcome, classifyCircuitBreakerOutcome, executeWithAdapterRetry, getRetryDelayMs, isAdapterCircuitOpenError, resolveAdapterRetryPolicy, scopedAdapterCircuitBreakerKey, shouldRetryAdapterOutcome } from '../chunk-Q4Q4JPR3.js';
2
2
  //# sourceMappingURL=index.js.map
3
3
  //# sourceMappingURL=index.js.map
@@ -1,3 +1,16 @@
1
+ // policies/retryable-execution.ts
2
+ var RetryableExecutionError = class extends Error {
3
+ name = "RetryableExecutionError";
4
+ code = "EXECUTION_RETRYABLE";
5
+ constructor(message, options) {
6
+ super(message, options);
7
+ }
8
+ };
9
+ function isRetryableExecutionError(error) {
10
+ if (error instanceof RetryableExecutionError) return true;
11
+ return typeof error === "object" && error !== null && error.name === "RetryableExecutionError" && error.code === "EXECUTION_RETRYABLE";
12
+ }
13
+
1
14
  // policies/index.ts
2
15
  function assertPolicyId(policyId) {
3
16
  if (!/^[a-z][a-z0-9_-]*(\.[a-z][a-z0-9_-]*)*\.v[0-9]+$/.test(policyId)) {
@@ -655,6 +668,6 @@ function aggregatePolicyOutcomes(outcomes) {
655
668
  return outcomes.find((outcome) => outcome.result === "block") ?? outcomes.find((outcome) => outcome.result === "warn");
656
669
  }
657
670
 
658
- export { aggregatePolicyOutcomes, assertPolicyId, createPolicyRegistry, evaluatePolicyDefinition, evaluatePolicyDefinitions, evaluateRegisteredPolicies, validateDataPolicyDefinition, validatePolicyGuidance };
659
- //# sourceMappingURL=chunk-GU3LZWJD.js.map
660
- //# sourceMappingURL=chunk-GU3LZWJD.js.map
671
+ export { RetryableExecutionError, aggregatePolicyOutcomes, assertPolicyId, createPolicyRegistry, evaluatePolicyDefinition, evaluatePolicyDefinitions, evaluateRegisteredPolicies, isRetryableExecutionError, validateDataPolicyDefinition, validatePolicyGuidance };
672
+ //# sourceMappingURL=chunk-AFXFAEWA.js.map
673
+ //# sourceMappingURL=chunk-AFXFAEWA.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../policies/retryable-execution.ts","../policies/index.ts"],"names":["result","passed"],"mappings":";AACO,IAAM,uBAAA,GAAN,cAAsC,KAAA,CAAM;AAAA,EAChC,IAAA,GAAO,yBAAA;AAAA,EAChB,IAAA,GAAO,qBAAA;AAAA,EAEhB,WAAA,CAAY,SAAiB,OAAA,EAA+B;AAC3D,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AS,EAAE,GAAG,gBAAA,EAAkB,QAAO,GAAI;AAAA,GAC9D;AACD;AAEA,SAAS,mBAAmB,QAAA,EAA4B;AACvD,EAAA,MAAM,QAAA,GAAW,QAAA,CAAS,KAAA,CAAM,IAAI,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-AFXFAEWA.js","sourcesContent":["/** A transient execution dependency failure; the host decides whether retry is safe. */\nexport class RetryableExecutionError extends Error {\n\toverride readonly name = \"RetryableExecutionError\";\n\treadonly code = \"EXECUTION_RETRYABLE\" as const;\n\n\tconstructor(message: string, options?: { cause?: unknown }) {\n\t\tsuper(message, options);\n\t}\n}\n\n/**\n * Recognise a RetryableExecutionError, including one constructed by a second\n * package copy (for example ESM and CommonJS builds loaded side by side).\n */\nexport function isRetryableExecutionError(error: unknown): error is RetryableExecutionError {\n\tif (error instanceof RetryableExecutionError) return true;\n\treturn (\n\t\ttypeof error === \"object\" &&\n\t\terror !== null &&\n\t\t(error as { name?: unknown }).name === \"RetryableExecutionError\" &&\n\t\t(error as { code?: unknown }).code === \"EXECUTION_RETRYABLE\"\n\t);\n}\n","export { RetryableExecutionError, isRetryableExecutionError } from \"./retryable-execution\";\n\nimport 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"]}
@@ -277,15 +277,24 @@ var InMemoryAdapterCircuitBreaker = class {
277
277
  }
278
278
  }
279
279
  };
280
+ function scopedAdapterCircuitBreakerKey(adapter, scope) {
281
+ return [
282
+ scope === void 0 ? "unscoped" : `tenant=${encodeURIComponent(scope.tenantId)}`,
283
+ scope?.spaceId === void 0 ? "space" : `space=${encodeURIComponent(scope.spaceId)}`,
284
+ adapter.vendor === void 0 ? "vendor" : `vendor=${encodeURIComponent(adapter.vendor)}`,
285
+ encodeURIComponent(adapter.adapterType),
286
+ encodeURIComponent(adapter.operation)
287
+ ].join(":");
288
+ }
280
289
  var AdapterCircuitBreakerRegistry = class {
281
290
  constructor(options = {}) {
282
291
  this.options = options;
283
292
  }
284
293
  options;
285
294
  breakers = /* @__PURE__ */ new Map();
286
- forAdapter(adapter) {
295
+ forAdapter(adapter, scope) {
287
296
  if (!adapter.circuitBreaker) return void 0;
288
- const key = `${adapter.adapterType}:${adapter.operation}`;
297
+ const key = this.options.key?.(adapter, scope) ?? `${adapter.adapterType}:${adapter.operation}`;
289
298
  let breaker = this.breakers.get(key);
290
299
  if (!breaker) {
291
300
  breaker = new InMemoryAdapterCircuitBreaker({
@@ -298,9 +307,13 @@ var AdapterCircuitBreakerRegistry = class {
298
307
  }
299
308
  return breaker;
300
309
  }
301
- /** The breaker already created for `adapterType:operation`, if any. */
310
+ /** Looks up the default `adapterType:operation` key without creating a breaker. */
302
311
  get(adapterType, operation) {
303
- return this.breakers.get(`${adapterType}:${operation}`);
312
+ return this.getByKey(`${adapterType}:${operation}`);
313
+ }
314
+ /** Looks up an exact key, including a custom key, without creating a breaker. */
315
+ getByKey(key) {
316
+ return this.breakers.get(key);
304
317
  }
305
318
  };
306
319
  var AdapterCircuitOpenError = class extends Error {
@@ -521,6 +534,7 @@ exports.executeWithAdapterRetry = executeWithAdapterRetry;
521
534
  exports.getRetryDelayMs = getRetryDelayMs;
522
535
  exports.isAdapterCircuitOpenError = isAdapterCircuitOpenError;
523
536
  exports.resolveAdapterRetryPolicy = resolveAdapterRetryPolicy;
537
+ exports.scopedAdapterCircuitBreakerKey = scopedAdapterCircuitBreakerKey;
524
538
  exports.shouldRetryAdapterOutcome = shouldRetryAdapterOutcome;
525
- //# sourceMappingURL=chunk-IF6NJORI.cjs.map
526
- //# sourceMappingURL=chunk-IF6NJORI.cjs.map
539
+ //# sourceMappingURL=chunk-AFXKSIVI.cjs.map
540
+ //# sourceMappingURL=chunk-AFXKSIVI.cjs.map