@directive-run/core 1.4.0 → 1.6.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 (73) hide show
  1. package/dist/adapter-utils.cjs +1 -1
  2. package/dist/adapter-utils.d.cts +1 -1
  3. package/dist/adapter-utils.d.ts +1 -1
  4. package/dist/adapter-utils.js +1 -1
  5. package/dist/{chunk-FK7BD7XT.js → chunk-EH2Q754B.js} +3 -3
  6. package/dist/chunk-EH2Q754B.js.map +1 -0
  7. package/dist/chunk-EOLY64E6.cjs +3 -0
  8. package/dist/chunk-EOLY64E6.cjs.map +1 -0
  9. package/dist/chunk-K3KVGWLP.cjs +3 -0
  10. package/dist/chunk-K3KVGWLP.cjs.map +1 -0
  11. package/dist/chunk-OVNPYGYJ.js +3 -0
  12. package/dist/chunk-OVNPYGYJ.js.map +1 -0
  13. package/dist/chunk-QOK7CHOW.js +16 -0
  14. package/dist/chunk-QOK7CHOW.js.map +1 -0
  15. package/dist/{chunk-DDUARSUH.cjs → chunk-S3CFYDIB.cjs} +3 -3
  16. package/dist/chunk-S3CFYDIB.cjs.map +1 -0
  17. package/dist/chunk-T4ZO4IYL.cjs +16 -0
  18. package/dist/chunk-T4ZO4IYL.cjs.map +1 -0
  19. package/dist/chunk-T6IJUWYR.js +3 -0
  20. package/dist/chunk-T6IJUWYR.js.map +1 -0
  21. package/dist/{helpers-BUY1lYCX.d.cts → helpers-BwAThjnJ.d.ts} +12 -2
  22. package/dist/{helpers-D6LcRum7.d.ts → helpers-CG27mEGG.d.cts} +12 -2
  23. package/dist/index.cjs +4 -1
  24. package/dist/index.cjs.map +1 -1
  25. package/dist/index.d.cts +413 -5
  26. package/dist/index.d.ts +413 -5
  27. package/dist/index.js +4 -1
  28. package/dist/index.js.map +1 -1
  29. package/dist/internals.cjs +1 -1
  30. package/dist/internals.d.cts +86 -40
  31. package/dist/internals.d.ts +86 -40
  32. package/dist/internals.js +1 -1
  33. package/dist/plugins/index.cjs +1 -1
  34. package/dist/plugins/index.cjs.map +1 -1
  35. package/dist/plugins/index.d.cts +11 -8
  36. package/dist/plugins/index.d.ts +11 -8
  37. package/dist/plugins/index.js +1 -1
  38. package/dist/plugins/index.js.map +1 -1
  39. package/dist/{plugins-Dy1C8GtT.d.cts → plugins-DvrsPhzx.d.cts} +471 -68
  40. package/dist/{plugins-Dy1C8GtT.d.ts → plugins-DvrsPhzx.d.ts} +471 -68
  41. package/dist/system-5BSCMT63.cjs +2 -0
  42. package/dist/{system-2THXJBFM.cjs.map → system-5BSCMT63.cjs.map} +1 -1
  43. package/dist/system-DMJ6XEJ7.js +2 -0
  44. package/dist/{system-JIO36ALC.js.map → system-DMJ6XEJ7.js.map} +1 -1
  45. package/dist/testing.cjs +1 -1
  46. package/dist/testing.cjs.map +1 -1
  47. package/dist/testing.d.cts +1 -1
  48. package/dist/testing.d.ts +1 -1
  49. package/dist/testing.js +1 -1
  50. package/dist/testing.js.map +1 -1
  51. package/dist/worker.cjs +1 -1
  52. package/dist/worker.cjs.map +1 -1
  53. package/dist/worker.d.cts +1 -1
  54. package/dist/worker.d.ts +1 -1
  55. package/dist/worker.js +1 -1
  56. package/dist/worker.js.map +1 -1
  57. package/package.json +1 -1
  58. package/dist/chunk-4CMO5OVZ.js +0 -3
  59. package/dist/chunk-4CMO5OVZ.js.map +0 -1
  60. package/dist/chunk-BEJ6ICA7.cjs +0 -3
  61. package/dist/chunk-BEJ6ICA7.cjs.map +0 -1
  62. package/dist/chunk-DDUARSUH.cjs.map +0 -1
  63. package/dist/chunk-E2WETPLH.js +0 -3
  64. package/dist/chunk-E2WETPLH.js.map +0 -1
  65. package/dist/chunk-FK7BD7XT.js.map +0 -1
  66. package/dist/chunk-LFMRWCIG.js +0 -16
  67. package/dist/chunk-LFMRWCIG.js.map +0 -1
  68. package/dist/chunk-TUS5WDVE.cjs +0 -3
  69. package/dist/chunk-TUS5WDVE.cjs.map +0 -1
  70. package/dist/chunk-VSHSYVSY.cjs +0 -16
  71. package/dist/chunk-VSHSYVSY.cjs.map +0 -1
  72. package/dist/system-2THXJBFM.cjs +0 -2
  73. package/dist/system-JIO36ALC.js +0 -2
@@ -226,6 +226,264 @@ interface DefinitionMeta {
226
226
  [key: string]: unknown;
227
227
  }
228
228
 
229
+ /**
230
+ * Data-configuration predicates and templates.
231
+ *
232
+ * A {@link FactPredicate} is a declarative, serializable boolean spec over a
233
+ * module's fact namespace — the data form of a constraint `when`, an effect
234
+ * `on`, or a boolean derivation. A {@link FactTemplate} is the value-producing
235
+ * counterpart: a fact-interpolating string.
236
+ *
237
+ * Convention: `$` marks an operator/expression node inside a predicate or
238
+ * template body (`$eq`, `$gte`, `$all`, `$template`, `$set`, `$ref`).
239
+ * Definition arms (`compute`, `handler`, `patch`) stay sigil-free.
240
+ *
241
+ * Operators are `$`-prefixed so they can never collide with a fact key —
242
+ * schema keys starting with `$` are rejected at registration.
243
+ */
244
+ /** Comparison operator names — the `$`-prefixed keys inside an operator object. */
245
+ type PredicateOp = "$eq" | "$ne" | "$in" | "$nin" | "$exists" | "$gt" | "$gte" | "$lt" | "$lte" | "$between" | "$matches" | "$startsWith" | "$endsWith" | "$contains" | "$changed";
246
+ /** Combinator node keys. */
247
+ type PredicateCombinatorKey = "$all" | "$any" | "$not";
248
+ /**
249
+ * `true` when `V` supports relational operators (`$gt` … `$between`).
250
+ * `[V]` tuple-wrapping suppresses distribution over union-typed facts.
251
+ */
252
+ type IsOrderable<V> = [V] extends [number | bigint | Date] ? true : [V] extends [string] ? true : false;
253
+ /**
254
+ * The operator object permitted for a fact of type `V`. Built as a
255
+ * **per-operator union** (one operator per member) rather than an
256
+ * intersection — a typo'd operator (`$eqq`) then matches no member and is a
257
+ * compile error, and a relational operator on a non-orderable fact resolves
258
+ * to `never`.
259
+ *
260
+ * One operator per object — for two operators on the same fact, write the
261
+ * array form or `$all`. This is by design (the type is the source of truth).
262
+ *
263
+ * `$matches` requires `RegExp`. The runtime throws on string operands.
264
+ *
265
+ * @example
266
+ * ```ts
267
+ * const op1: OperatorObject<number> = { $gte: 30 };
268
+ * const op2: OperatorObject<string> = { $matches: /^J/i };
269
+ * const op3: OperatorObject<string> = { $in: ["red", "yellow"] };
270
+ * const op4: OperatorObject<string> = { $startsWith: "Ada" };
271
+ * const op5: OperatorObject<string> = { $endsWith: ".com" };
272
+ * ```
273
+ */
274
+ type OperatorObject<V> = {
275
+ $eq: V;
276
+ } | {
277
+ $ne: V;
278
+ } | {
279
+ $in: readonly V[];
280
+ } | {
281
+ $nin: readonly V[];
282
+ } | {
283
+ $exists: boolean;
284
+ } | {
285
+ $changed: true;
286
+ } | (IsOrderable<V> extends true ? {
287
+ $gt: V;
288
+ } | {
289
+ $gte: V;
290
+ } | {
291
+ $lt: V;
292
+ } | {
293
+ $lte: V;
294
+ } | {
295
+ $between: readonly [V, V];
296
+ } : never) | ([V] extends [string] ? {
297
+ $matches: RegExp;
298
+ } | {
299
+ $contains: string;
300
+ } | {
301
+ $startsWith: string;
302
+ } | {
303
+ $endsWith: string;
304
+ } : never) | ([V] extends [readonly (infer E)[]] ? {
305
+ $contains: E;
306
+ } : never);
307
+ /**
308
+ * The spec for a single fact key: a bare value (equality), an operator
309
+ * object, or — for an object-typed fact — a nested predicate (partial match).
310
+ */
311
+ type PredicateField<V> = V | OperatorObject<V> | ([V] extends [readonly unknown[]] ? never : [V] extends [object] ? PredicateObject<V> : never);
312
+ /**
313
+ * Object form — every key is a fact name, every value a
314
+ * {@link PredicateField}. Multiple keys are AND-ed. A nested object value
315
+ * recurses (partial match), which is how cross-module namespaced predicates
316
+ * (`{ self: { phase: "red" }, auth: { token: { $exists: true } } }`) work.
317
+ */
318
+ type PredicateObject<F> = {
319
+ [K in keyof F]?: PredicateField<F[K]>;
320
+ };
321
+ /** Array form — explicit clauses, AND-ed. The codegen/devtools-friendly form. */
322
+ type PredicateClause<F> = {
323
+ [K in keyof F]: {
324
+ readonly fact: K;
325
+ readonly op: PredicateOp;
326
+ readonly value: unknown;
327
+ };
328
+ }[keyof F];
329
+ /** Combinator node — exactly one of `$all` / `$any` / `$not`. */
330
+ type PredicateCombinator<F> = {
331
+ $all: readonly FactPredicate<F>[];
332
+ $any?: never;
333
+ $not?: never;
334
+ } | {
335
+ $any: readonly FactPredicate<F>[];
336
+ $all?: never;
337
+ $not?: never;
338
+ } | {
339
+ $not: FactPredicate<F>;
340
+ $all?: never;
341
+ $any?: never;
342
+ };
343
+ /**
344
+ * A declarative boolean spec over a fact namespace `F`. The data form of a
345
+ * constraint `when`, an effect `on`, or a boolean derivation. Accepts an
346
+ * object form, an array-of-clauses form, or a combinator node.
347
+ *
348
+ * Keys are **fact names only** — derivations are not addressable from inside
349
+ * a predicate. To gate on a derivation, either reference the underlying fact
350
+ * the derivation reads, or fall back to the function form of `when` / `on`.
351
+ *
352
+ * @example
353
+ * ```ts
354
+ * // Object form (the common case)
355
+ * const p1: FactPredicate<{ phase: string; elapsed: number }> = {
356
+ * phase: "red",
357
+ * elapsed: { $gte: 30 },
358
+ * };
359
+ *
360
+ * // Combinator form
361
+ * const p2: FactPredicate<{ phase: string }> = {
362
+ * $any: [{ phase: "red" }, { phase: "yellow" }],
363
+ * };
364
+ * ```
365
+ */
366
+ type FactPredicate<F> = PredicateObject<F> | readonly PredicateClause<F>[] | PredicateCombinator<F>;
367
+ /**
368
+ * A fact-interpolating string expression. `${key}` placeholders are replaced
369
+ * with the named fact's value; `$${` emits a literal `${`. The value-producing
370
+ * counterpart to {@link FactPredicate} — usable as a string derivation, a
371
+ * constraint `require` field value, or an event `patch` value.
372
+ *
373
+ * @example { $template: "Phase ${phase} for ${elapsed}s" }
374
+ */
375
+ interface FactTemplate {
376
+ readonly $template: string;
377
+ }
378
+ /**
379
+ * *Note: despite the "Selector" name, this does not select from facts — it
380
+ * projects fields of the requirement payload for stable-stringification.*
381
+ *
382
+ * A resolver dedup key written as data: an ordered list of requirement-payload
383
+ * field names. `key: ["type", "to"]` dedupes requirements by those fields.
384
+ *
385
+ * @example
386
+ * ```ts
387
+ * resolvers: {
388
+ * fetch: {
389
+ * requirement: "FETCH",
390
+ * key: ["url", "method"] satisfies KeySelector<{ url: string; method: string }>,
391
+ * resolve: doFetch,
392
+ * },
393
+ * }
394
+ * ```
395
+ */
396
+ type KeySelector<R> = readonly (keyof R & string)[];
397
+ /**
398
+ * *Note: Directive's `$ref` is **not** a JSON Pointer or JSON Schema `$ref`.
399
+ * It is a payload field copy — equivalent to `event.payload[key]`. Renaming
400
+ * to `$from` is tracked as a possible v1.6+ additive alias.*
401
+ *
402
+ * A typed single-field copy from an event payload. Lives in the patch-spec
403
+ * namespace — used inside a {@link PatchSpec} `$set` value.
404
+ *
405
+ * @example
406
+ * ```ts
407
+ * patch: { $set: { userId: { $ref: "id" } satisfies PayloadRef<{ id: string }> } }
408
+ * ```
409
+ */
410
+ interface PayloadRef<P> {
411
+ readonly $ref: keyof P & string;
412
+ }
413
+ /**
414
+ * A patch value: a literal, a typed payload copy, or (for string facts) a
415
+ * template. Lives in the patch-spec namespace — used inside a {@link PatchSpec}
416
+ * `$set` block.
417
+ *
418
+ * @example
419
+ * ```ts
420
+ * const v1: PatchValue<boolean, { active: boolean }> = true;
421
+ * const v2: PatchValue<string, { name: string }> = { $ref: "name" };
422
+ * const v3: PatchValue<string, { name: string }> = { $template: "user ${name}" };
423
+ * ```
424
+ */
425
+ type PatchValue<V, P> = V | PayloadRef<P> | ([V] extends [string] ? FactTemplate : never);
426
+ /**
427
+ * An event handler written as data: assigns facts from literals, payload
428
+ * fields (`$ref`), or interpolated strings (`$template`).
429
+ *
430
+ * @example
431
+ * ```ts
432
+ * const spec: PatchSpec<{ status: string; label: string }, { name: string }> = {
433
+ * $set: {
434
+ * status: "active",
435
+ * label: { $template: "user ${name}" },
436
+ * },
437
+ * };
438
+ * ```
439
+ */
440
+ interface PatchSpec<F, P> {
441
+ readonly $set: {
442
+ [K in keyof F]?: PatchValue<F[K], P>;
443
+ };
444
+ }
445
+ /**
446
+ * The per-clause result of an explained predicate evaluation. One entry per
447
+ * leaf operator (`$eq`, `$gte`, …); combinator nodes (`$all`, `$any`, `$not`)
448
+ * may also appear as headers when the runtime emits them — hence the union
449
+ * over {@link PredicateCombinatorKey}.
450
+ *
451
+ * @example
452
+ * ```ts
453
+ * const result: ClauseResult = {
454
+ * path: "elapsed",
455
+ * op: "$gte",
456
+ * expected: 30,
457
+ * actual: 20,
458
+ * pass: false,
459
+ * };
460
+ * ```
461
+ */
462
+ interface ClauseResult {
463
+ /** Dotted path to the fact (`elapsed`, `auth.token`). */
464
+ readonly path: string;
465
+ /** The operator applied (`$gte`, `$eq`, …) — `$eq` for a bare value. */
466
+ readonly op: PredicateOp | PredicateCombinatorKey;
467
+ /**
468
+ * The value the predicate expected. For combinator clauses (`$all`,
469
+ * `$any`, `$not`) this is the child count.
470
+ */
471
+ readonly expected: unknown;
472
+ /**
473
+ * The actual fact value at evaluation time. For combinator clauses this
474
+ * is the number of child clauses that passed.
475
+ */
476
+ readonly actual: unknown;
477
+ /** Whether this clause passed. */
478
+ readonly pass: boolean;
479
+ /**
480
+ * Children of a combinator clause (`$all`, `$any`, `$not`). Preserves the
481
+ * tree shape of the original predicate so renderers (devtools,
482
+ * `system.explain()`) can indent nested clauses.
483
+ */
484
+ readonly children?: ClauseResult[];
485
+ }
486
+
229
487
  /**
230
488
  * Requirement Types - Type definitions for requirements and constraints
231
489
  */
@@ -268,47 +526,23 @@ type RequirementsSchema = Record<string, RequirementPayloadSchema>;
268
526
  * - No requirements: `null` or `[]`
269
527
  */
270
528
  type RequirementOutput$1<R extends Requirement = Requirement> = R | R[] | null;
271
- /**
272
- * Resolver-to-constraint binding mode (RFC-1: Resolver Constraint-Binding).
273
- *
274
- * Controls whether fact writes from a resolver are *bound* to the constraint
275
- * that triggered them. When the binding is `'auto'`, every write performed by
276
- * the resolver re-evaluates the constraint's `when()` predicate against the
277
- * latest facts; if `when()` no longer holds, the write is dropped, the
278
- * resolver's {@link AbortController} is aborted, and `ctx.signal.aborted`
279
- * becomes `true` so the resolver can early-exit on its next checkpoint.
280
- *
281
- * Binding is **one-shot per resolver invocation**: once `when()` flips to
282
- * `false`, the binding stays deactivated even if `when()` would later flip
283
- * back to `true` mid-resolver. This prevents a resolver from "resurrecting"
284
- * a stale intent after the user has moved past it.
285
- *
286
- * - `'none'` (default): Current behavior. Every fact write succeeds.
287
- * - `'auto'`: Writes are gated by the constraint's `when()` predicate. The
288
- * predicate **must be synchronous** for `bind: 'auto'`; async constraints
289
- * cannot be bound (their `when()` cannot be re-evaluated cheaply on every
290
- * set).
291
- *
292
- * @example
293
- * ```ts
294
- * constraints: {
295
- * leaveParty: {
296
- * when: (f) => f.status === 'mutating',
297
- * require: { type: 'EXECUTE_ACTION' },
298
- * bind: 'auto', // resolver tail won't clobber `status = 'left'`
299
- * },
300
- * }
301
- * ```
302
- */
303
- type ConstraintBindMode = "none" | "auto";
304
529
  /** Constraint definition */
305
530
  interface ConstraintDef<S extends Schema, R extends Requirement = Requirement> {
306
531
  /** Priority for ordering (higher runs first) */
307
532
  priority?: number;
308
533
  /** Mark this constraint as async (avoids runtime detection) */
309
534
  async?: boolean;
310
- /** Condition function (sync or async) */
311
- when: (facts: Facts<S>) => boolean | Promise<boolean>;
535
+ /**
536
+ * Condition the constraint requires. Either:
537
+ * - a function (sync or async) `(facts) => boolean`, or
538
+ * - a declarative {@link FactPredicate} spec — serializable, inspectable,
539
+ * always synchronous; e.g. `{ phase: "red", elapsed: { $gte: 30 } }`.
540
+ *
541
+ * A data `when` is normalized to a wrapper function at registration; the
542
+ * wrapper still reads through the tracked facts proxy, so auto-tracking
543
+ * captures both fact and derivation deps correctly.
544
+ */
545
+ when: ((facts: Facts<S>) => boolean | Promise<boolean>) | FactPredicate<InferSchema<S>>;
312
546
  /**
313
547
  * Requirement(s) to produce when condition is met.
314
548
  * - Single requirement: `{ type: "RESTOCK", sku: "ABC" }`
@@ -320,21 +554,26 @@ interface ConstraintDef<S extends Schema, R extends Requirement = Requirement> {
320
554
  /** Timeout for async constraints (ms) */
321
555
  timeout?: number;
322
556
  /**
323
- * Resolver-to-constraint binding mode (RFC-1).
324
- *
325
- * When `'auto'`, fact writes from the resolver triggered by this
326
- * constraint are dropped (and the resolver is aborted) once `when()`
327
- * flips to false. Defaults to `'none'` (current behavior preserved).
557
+ * Fact keys whose **value the resolver compare-and-swaps**. Writes to
558
+ * these facts land only if they still hold the snapshot value taken at
559
+ * resolver dispatch; otherwise the write is dropped and the resolver
560
+ * aborted.
328
561
  *
329
- * **Forbidden on async constraints** (`async: true`): the binding
330
- * checker re-evaluates `when()` synchronously on every fact write,
331
- * which is incompatible with async predicates. Setting `bind: 'auto'`
332
- * on an async constraint logs a dev-mode warning and is treated as
333
- * `'none'`.
562
+ * This is value-based per-fact compare-and-swap with one-shot
563
+ * fact-level poisoning not a lock, not document versioning. Writes
564
+ * to facts not listed always land; `when()` is not consulted. Omit for
565
+ * no binding (default). Ignored on async constraints.
334
566
  *
335
- * @see {@link ConstraintBindMode}
567
+ * @example
568
+ * ```ts
569
+ * executeAction: {
570
+ * when: (f) => f.status === 'mutating',
571
+ * require: { type: 'EXECUTE_ACTION' },
572
+ * owns: ['status'], // the resolver owns `status`
573
+ * }
574
+ * ```
336
575
  */
337
- bind?: ConstraintBindMode;
576
+ owns?: readonly string[];
338
577
  /**
339
578
  * Constraint IDs whose resolvers must complete before this constraint is evaluated.
340
579
  * If a dependency's `when()` returns false (no requirements), this constraint proceeds.
@@ -435,6 +674,15 @@ interface EffectDef<S extends Schema> {
435
674
  run(facts: Facts<S>, prev: InferSchema<S> | null): void | EffectCleanup | Promise<void | EffectCleanup>;
436
675
  /** Optional explicit dependencies for optimization */
437
676
  deps?: Array<keyof InferSchema<S>>;
677
+ /**
678
+ * Optional declarative trigger — a {@link FactPredicate} that gates whether
679
+ * `run()` fires: even when a dependency changes, the effect runs only if
680
+ * the predicate currently holds. Mutually exclusive with `deps` — the
681
+ * predicate supplies its own deps via static extraction.
682
+ *
683
+ * @example on: { phase: "red", elapsed: { $gte: 30 } }
684
+ */
685
+ on?: FactPredicate<InferSchema<S>>;
438
686
  /** Optional metadata for debugging and devtools (never read on hot path). */
439
687
  meta?: DefinitionMeta;
440
688
  }
@@ -620,8 +868,13 @@ interface ResolverDef<S extends Schema, R extends Requirement = Requirement> {
620
868
  * - Function: type guard predicate (e.g., `requirement: (req) => req.type === "FETCH_USER"`)
621
869
  */
622
870
  requirement: string | ((req: Requirement) => req is R);
623
- /** Custom key function for deduplication */
624
- key?: RequirementKeyFn<R>;
871
+ /**
872
+ * Custom dedup key for the resolver. Either:
873
+ * - a `RequirementKeyFn<R>` function, or
874
+ * - a {@link KeySelector} array of requirement-payload field names:
875
+ * `key: ["type", "to"]` builds a stable dedup key from those fields.
876
+ */
877
+ key?: RequirementKeyFn<R> | KeySelector<R>;
625
878
  /** Retry policy */
626
879
  retry?: RetryPolicy;
627
880
  /** Timeout for resolver execution (ms) */
@@ -1388,9 +1641,10 @@ type TypedDerivationFn<M extends ModuleSchema, K extends keyof GetDerivationsSch
1388
1641
  * Typed derivations definition using the module schema.
1389
1642
  * Each derivation key must match schema.derivations and return the declared type.
1390
1643
  */
1644
+ type TypedDerivationT<M extends ModuleSchema, K extends keyof GetDerivationsSchema<M>> = InferSchemaType<GetDerivationsSchema<M>[K]>;
1391
1645
  type TypedDerivationsDef<M extends ModuleSchema> = {
1392
1646
  [K in keyof GetDerivationsSchema<M>]: TypedDerivationFn<M, K> | {
1393
- compute: TypedDerivationFn<M, K>;
1647
+ compute: TypedDerivationFn<M, K> | ([TypedDerivationT<M, K>] extends [boolean] ? FactPredicate<InferFacts<M>> : never) | ([TypedDerivationT<M, K>] extends [string] ? FactTemplate : never);
1394
1648
  meta?: DefinitionMeta;
1395
1649
  };
1396
1650
  };
@@ -1407,6 +1661,15 @@ type TypedEventsDef<M extends ModuleSchema> = {
1407
1661
  [K in keyof GetEventsSchema<M>]: TypedEventHandlerFn<M, K> | {
1408
1662
  handler: TypedEventHandlerFn<M, K>;
1409
1663
  meta?: DefinitionMeta;
1664
+ } | {
1665
+ /**
1666
+ * Declarative event body: assigns facts from literals, payload
1667
+ * fields ({@link KeySelector}), or interpolated strings
1668
+ * ({@link FactTemplate}). Use instead of `handler` for simple
1669
+ * "set facts from event payload" events.
1670
+ */
1671
+ patch: PatchSpec<InferFacts<M>, InferEventPayloadFromSchema<GetEventsSchema<M>[K]>>;
1672
+ meta?: DefinitionMeta;
1410
1673
  };
1411
1674
  };
1412
1675
  /**
@@ -1421,8 +1684,12 @@ interface TypedConstraintDef<M extends ModuleSchema> {
1421
1684
  priority?: number;
1422
1685
  /** Mark this constraint as async */
1423
1686
  async?: boolean;
1424
- /** Condition function */
1425
- when: (facts: Facts<M["facts"]>) => boolean | Promise<boolean>;
1687
+ /**
1688
+ * Condition the constraint requires. Either a function (sync or async)
1689
+ * `(facts) => boolean`, or a declarative {@link FactPredicate} spec
1690
+ * (e.g. `{ phase: "red", elapsed: { $gte: 30 } }`).
1691
+ */
1692
+ when: ((facts: Facts<M["facts"]>) => boolean | Promise<boolean>) | FactPredicate<InferFacts<M>>;
1426
1693
  /**
1427
1694
  * Requirement(s) to produce when condition is met.
1428
1695
  */
@@ -1430,10 +1697,12 @@ interface TypedConstraintDef<M extends ModuleSchema> {
1430
1697
  /** Timeout for async constraints (ms) */
1431
1698
  timeout?: number;
1432
1699
  /**
1433
- * Resolver-to-constraint binding mode (RFC-1).
1434
- * Defaults to `'none'`. See {@link ConstraintBindMode}.
1700
+ * Fact keys whose **value the resolver compare-and-swaps**. Writes to
1701
+ * these facts land only if they still hold the snapshot value taken at
1702
+ * resolver dispatch; otherwise the write is dropped and the resolver
1703
+ * aborted. Omit for no binding (default). Ignored on async constraints.
1435
1704
  */
1436
- bind?: ConstraintBindMode;
1705
+ owns?: readonly string[];
1437
1706
  /**
1438
1707
  * Constraint IDs whose resolvers must complete before this constraint is evaluated.
1439
1708
  * If a dependency's `when()` returns false (no requirements), this constraint proceeds.
@@ -1466,8 +1735,12 @@ interface CrossModuleConstraintDef<M extends ModuleSchema, Deps extends CrossMod
1466
1735
  priority?: number;
1467
1736
  /** Mark this constraint as async */
1468
1737
  async?: boolean;
1469
- /** Condition function with cross-module facts access */
1470
- when: (facts: CrossModuleFactsWithSelf<M, Deps>) => boolean | Promise<boolean>;
1738
+ /**
1739
+ * Condition the constraint requires. Either a function (sync or async)
1740
+ * with cross-module facts access, or a nested {@link FactPredicate}:
1741
+ * `{ self: { phase: "red" }, auth: { token: { $exists: true } } }`.
1742
+ */
1743
+ when: ((facts: CrossModuleFactsWithSelf<M, Deps>) => boolean | Promise<boolean>) | FactPredicate<CrossModuleFactsWithSelf<M, Deps>>;
1471
1744
  /**
1472
1745
  * Requirement(s) to produce when condition is met.
1473
1746
  */
@@ -1475,10 +1748,12 @@ interface CrossModuleConstraintDef<M extends ModuleSchema, Deps extends CrossMod
1475
1748
  /** Timeout for async constraints (ms) */
1476
1749
  timeout?: number;
1477
1750
  /**
1478
- * Resolver-to-constraint binding mode (RFC-1).
1479
- * Defaults to `'none'`. See {@link ConstraintBindMode}.
1751
+ * Fact keys whose **value the resolver compare-and-swaps**. Writes to
1752
+ * these facts land only if they still hold the snapshot value taken at
1753
+ * resolver dispatch; otherwise the write is dropped and the resolver
1754
+ * aborted. Omit for no binding (default). Ignored on async constraints.
1480
1755
  */
1481
- bind?: ConstraintBindMode;
1756
+ owns?: readonly string[];
1482
1757
  /**
1483
1758
  * Constraint IDs whose resolvers must complete before this constraint is evaluated.
1484
1759
  * If a dependency's `when()` returns false (no requirements), this constraint proceeds.
@@ -1511,6 +1786,11 @@ interface CrossModuleEffectDef<M extends ModuleSchema, Deps extends CrossModuleD
1511
1786
  run: (facts: CrossModuleFactsWithSelf<M, Deps>, prev: CrossModuleFactsWithSelf<M, Deps> | undefined) => void | EffectCleanup | Promise<void | EffectCleanup>;
1512
1787
  /** Optional dependency keys to filter when effect runs */
1513
1788
  deps?: string[];
1789
+ /**
1790
+ * Optional declarative trigger — a {@link FactPredicate} that gates whether
1791
+ * `run()` fires. Mutually exclusive with `deps`.
1792
+ */
1793
+ on?: FactPredicate<CrossModuleFactsWithSelf<M, Deps>>;
1514
1794
  /** Optional metadata for debugging and devtools (never read on hot path). */
1515
1795
  meta?: DefinitionMeta;
1516
1796
  }
@@ -1532,7 +1812,7 @@ type CrossModuleDerivationFn<M extends ModuleSchema, Deps extends CrossModuleDep
1532
1812
  */
1533
1813
  type CrossModuleDerivationsDef<M extends ModuleSchema, Deps extends CrossModuleDeps> = {
1534
1814
  [K in keyof GetDerivationsSchema<M>]: CrossModuleDerivationFn<M, Deps, K> | {
1535
- compute: CrossModuleDerivationFn<M, Deps, K>;
1815
+ compute: CrossModuleDerivationFn<M, Deps, K> | ([TypedDerivationT<M, K>] extends [boolean] ? FactPredicate<CrossModuleFactsWithSelf<M, Deps>> : never) | ([TypedDerivationT<M, K>] extends [string] ? FactTemplate : never);
1536
1816
  meta?: DefinitionMeta;
1537
1817
  };
1538
1818
  };
@@ -1583,8 +1863,12 @@ type ExtractRequirement<M extends ModuleSchema, T extends keyof GetRequirementsS
1583
1863
  interface TypedResolverDef<M extends ModuleSchema, T extends keyof GetRequirementsSchema<M> & string> {
1584
1864
  /** Requirement type to handle */
1585
1865
  requirement: T;
1586
- /** Custom key function for deduplication */
1587
- key?: (req: ExtractRequirement<M, T>) => string;
1866
+ /**
1867
+ * Custom dedup key. Either a `(req) => string` function, or a
1868
+ * {@link KeySelector} array of requirement-payload field names
1869
+ * (`["type", "to"]`) that builds a stable key from those fields.
1870
+ */
1871
+ key?: ((req: ExtractRequirement<M, T>) => string) | KeySelector<ExtractRequirement<M, T>>;
1588
1872
  /** Retry policy */
1589
1873
  retry?: RetryPolicy;
1590
1874
  /** Timeout for resolver execution (ms) */
@@ -1845,6 +2129,11 @@ interface SystemInspection {
1845
2129
  hitCount: number;
1846
2130
  lastActiveAt: number | null;
1847
2131
  meta?: DefinitionMeta;
2132
+ /**
2133
+ * The data-form predicate spec (when the constraint's `when` is declarative),
2134
+ * exposed for devtools and `explain()` rendering.
2135
+ */
2136
+ whenSpec?: FactPredicate<Record<string, unknown>>;
1848
2137
  }>;
1849
2138
  resolvers: Record<string, ResolverStatus>;
1850
2139
  /** All defined resolver names and their requirement types */
@@ -2095,7 +2384,7 @@ interface ResolversControl<M extends ModuleSchema = ModuleSchema> {
2095
2384
  interface DynamicConstraintDef<M extends ModuleSchema = ModuleSchema> {
2096
2385
  priority?: number;
2097
2386
  async?: boolean;
2098
- when: (facts: Readonly<InferSchema<M["facts"]>>) => boolean | Promise<boolean>;
2387
+ when: ((facts: Readonly<InferSchema<M["facts"]>>) => boolean | Promise<boolean>) | FactPredicate<InferSchema<M["facts"]>>;
2099
2388
  require: {
2100
2389
  type: string;
2101
2390
  [key: string]: unknown;
@@ -2118,15 +2407,27 @@ interface DynamicConstraintDef<M extends ModuleSchema = ModuleSchema> {
2118
2407
  interface DynamicEffectDef<M extends ModuleSchema = ModuleSchema> {
2119
2408
  run: (facts: Readonly<InferSchema<M["facts"]>>, prev: InferSchema<M["facts"]> | null) => void | (() => void) | Promise<void | (() => void)>;
2120
2409
  deps?: Array<string & keyof InferSchema<M["facts"]>>;
2410
+ /**
2411
+ * Optional declarative trigger — a {@link FactPredicate} that gates whether
2412
+ * `run()` fires. Mutually exclusive with `deps`.
2413
+ */
2414
+ on?: FactPredicate<InferSchema<M["facts"]>>;
2121
2415
  meta?: DefinitionMeta;
2122
2416
  }
2123
2417
  /** Resolver definition for dynamic registration — typed context.facts, relaxed requirement */
2124
2418
  interface DynamicResolverDef<M extends ModuleSchema = ModuleSchema> {
2125
2419
  requirement: string;
2126
- key?: (req: {
2420
+ /**
2421
+ * Custom dedup key. Either a `(req) => string` function, or a
2422
+ * {@link KeySelector} array of requirement-payload field names.
2423
+ */
2424
+ key?: ((req: {
2425
+ type: string;
2426
+ [key: string]: unknown;
2427
+ }) => string) | KeySelector<{
2127
2428
  type: string;
2128
2429
  [key: string]: unknown;
2129
- }) => string;
2430
+ }>;
2130
2431
  retry?: RetryPolicy;
2131
2432
  timeout?: number;
2132
2433
  batch?: BatchConfig;
@@ -2185,6 +2486,11 @@ type ObservationEvent = {
2185
2486
  type: "constraint.evaluate";
2186
2487
  id: string;
2187
2488
  active: boolean;
2489
+ /**
2490
+ * Per-clause breakdown of a data-form predicate evaluation. Present
2491
+ * only when the constraint's `when` is a {@link FactPredicate}.
2492
+ */
2493
+ whenExplain?: ClauseResult[];
2188
2494
  } | {
2189
2495
  type: "constraint.error";
2190
2496
  id: string;
@@ -2214,6 +2520,53 @@ type ObservationEvent = {
2214
2520
  resolver: string;
2215
2521
  requirementId: string;
2216
2522
  error: unknown;
2523
+ } | {
2524
+ /**
2525
+ * A real per-write rejection. A bound resolver's owned-fact write was
2526
+ * dropped because the fact was changed by something outside the
2527
+ * resolver between the resolver's baseline and its next write (RFC-0003
2528
+ * optimistic-concurrency check). `reason` keeps the observation protocol
2529
+ * backend-neutral — future write-rejecting backends can report other
2530
+ * reasons without a new event type.
2531
+ *
2532
+ * `kind` discriminates this `"rejection"` arm from the `"summary"` arm:
2533
+ * `fact`/`expected`/`actual` exist only here; `dropped` only on the
2534
+ * summary. TypeScript forces the narrow.
2535
+ *
2536
+ * @example
2537
+ * ```ts
2538
+ * system.observe((e) => {
2539
+ * if (e.type === "resolver.write.rejected") {
2540
+ * if (e.kind === "summary") {
2541
+ * console.warn(`[rejected] ${e.resolver}: ${e.dropped} more writes dropped`);
2542
+ * } else {
2543
+ * console.warn(`[rejected] ${e.resolver} dropped ${e.fact}`);
2544
+ * }
2545
+ * }
2546
+ * });
2547
+ * ```
2548
+ */
2549
+ type: "resolver.write.rejected";
2550
+ kind: "rejection";
2551
+ resolver: string;
2552
+ requirementId: string;
2553
+ reason: "clobbered";
2554
+ fact: string;
2555
+ expected: unknown;
2556
+ actual: unknown;
2557
+ } | {
2558
+ /**
2559
+ * The per-resolver suppression summary: emitted once when a single
2560
+ * resolver instance exceeds the per-instance write-rejection cap (10).
2561
+ * Further per-write `"rejection"` events for that instance are dropped;
2562
+ * `dropped` reports how many were suppressed.
2563
+ */
2564
+ type: "resolver.write.rejected";
2565
+ kind: "summary";
2566
+ resolver: string;
2567
+ requirementId: string;
2568
+ reason: "clobbered";
2569
+ dropped: number;
2217
2570
  } | {
2218
2571
  type: "effect.run";
2219
2572
  id: string;
@@ -2517,8 +2870,11 @@ interface Plugin<M extends ModuleSchema = ModuleSchema> {
2517
2870
  * Called after a constraint's `when` function is evaluated.
2518
2871
  * @param id - The constraint ID
2519
2872
  * @param active - Whether the constraint is active (when returned true)
2873
+ * @param whenExplain - For data-form constraints, the per-clause breakdown
2874
+ * (which clauses passed, which failed, against what fact values). Omitted
2875
+ * for function-form `when`.
2520
2876
  */
2521
- onConstraintEvaluate?: (id: string, active: boolean) => void;
2877
+ onConstraintEvaluate?: (id: string, active: boolean, whenExplain?: ClauseResult[]) => void;
2522
2878
  /**
2523
2879
  * Called when a constraint's `when` function throws an error.
2524
2880
  * @param id - The constraint ID
@@ -2574,6 +2930,53 @@ interface Plugin<M extends ModuleSchema = ModuleSchema> {
2574
2930
  * @param req - The requirement that was canceled
2575
2931
  */
2576
2932
  onResolverCancel?: (resolver: string, req: RequirementWithId) => void;
2933
+ /**
2934
+ * Called when a resolver's write is rejected by the runtime. The only
2935
+ * `reason` today is `"clobbered"`: a bound resolver (RFC-0003) dropped a
2936
+ * write to an owned fact because the fact was changed by something outside
2937
+ * the resolver between the resolver's baseline and its next write — the
2938
+ * resolver's `AbortController` is aborted in the same step. See
2939
+ * {@link createBoundFacts} for the per-fact optimistic-concurrency model.
2940
+ * `reason` keeps the hook backend-neutral.
2941
+ *
2942
+ * The `event` is a discriminated union on `kind`:
2943
+ * - `"rejection"` — a real per-write rejection; carries
2944
+ * `fact`/`expected`/`actual`.
2945
+ * - `"summary"` — the per-resolver suppression summary, emitted once when a
2946
+ * single resolver instance exceeds the per-instance write-rejection cap
2947
+ * (10); carries `dropped` (the count of suppressed `"rejection"` events).
2948
+ *
2949
+ * @param event - The write-rejection event (discriminated on `kind`).
2950
+ *
2951
+ * @example
2952
+ * ```ts
2953
+ * const myPlugin: Plugin = {
2954
+ * name: "write-rejection-logger",
2955
+ * onResolverWriteRejected(event) {
2956
+ * if (event.kind === "summary") {
2957
+ * console.warn(`[${event.resolver}] suppressed ${event.dropped} write rejections`);
2958
+ * return;
2959
+ * }
2960
+ * console.warn(`[clobber] ${event.resolver}: ${event.fact} expected=${JSON.stringify(event.expected)} actual=${JSON.stringify(event.actual)}`);
2961
+ * },
2962
+ * };
2963
+ * ```
2964
+ */
2965
+ onResolverWriteRejected?: (event: {
2966
+ kind: "rejection";
2967
+ resolver: string;
2968
+ req: RequirementWithId;
2969
+ reason: "clobbered";
2970
+ fact: string;
2971
+ expected: unknown;
2972
+ actual: unknown;
2973
+ } | {
2974
+ kind: "summary";
2975
+ resolver: string;
2976
+ req: RequirementWithId;
2977
+ reason: "clobbered";
2978
+ dropped: number;
2979
+ }) => void;
2577
2980
  /**
2578
2981
  * Called when an effect runs.
2579
2982
  * @param id - The effect ID
@@ -2643,4 +3046,4 @@ interface Plugin<M extends ModuleSchema = ModuleSchema> {
2643
3046
  onTraceComplete?: (entry: TraceEntry) => void;
2644
3047
  }
2645
3048
 
2646
- export { type SystemInspection as $, type AnySystem as A, type BatchConfig as B, type CrossModuleDeps as C, type DefinitionMeta as D, type EffectsDef as E, type Facts as F, type InferFacts as G, type HistoryAPI as H, type InferDerivations as I, type InferRequirementTypes as J, type InferRequirements as K, type InferSchemaType as L, type ModuleSchema as M, type NamespacedSystem as N, type InferSelectorState as O, type Plugin as P, type MetaAccessor as Q, type RequirementWithId as R, type SchemaType as S, type TypedDerivationsDef as T, type MetaMatch as U, type ObservationEvent as V, type RetryPolicy as W, type Schema as X, type Snapshot as Y, type System as Z, type SystemConfig as _, type TypedEventsDef as a, type SystemMode as a0, type SystemSnapshot as a1, type TraceEntry as a2, isNamespacedSystem as a3, isSingleModuleSystem as a4, type FactsStore as a5, type ConstraintsDef as a6, type ConstraintState as a7, type ResolversDef as a8, type ConstraintBindMode as a9, type FactKeys as aA, type FactReturnType as aB, type FlexibleEventHandler as aC, type HistoryConfig as aD, type InferEventPayloadFromSchema as aE, type InferRequirementPayloadFromSchema as aF, type InferSchema as aG, type MutableNamespacedFacts as aH, type NamespacedDerivations as aI, type NamespacedEventsAccessor as aJ, type NamespacedFacts as aK, type ObservableKeys as aL, type RequirementExplanation as aM, type RequirementOutput as aN, type RequirementPayloadSchema$1 as aO, type RequirementsSchema as aP, type ResolverContext as aQ, type ResolversControl as aR, type SnapshotMeta as aS, type SystemEvent as aT, type TraceConfig as aU, type TypedConstraintDef as aV, type TypedResolverContext as aW, type TypedResolverDef as aX, type UnionEvents as aY, type RequirementOutput$1 as aZ, type ResolverStatus as aa, type FactChange as ab, type ReconcileResult as ac, type RecoveryStrategy as ad, type ErrorSource as ae, type RetryLaterConfig as af, type BatchItemResult as ag, type BatchResolveResults as ah, type ConstraintsControl as ai, type CrossModuleConstraintDef as aj, type CrossModuleDerivationFn as ak, type CrossModuleEffectDef as al, type CrossModuleFactsWithSelf as am, type DerivationKeys as an, type DerivationReturnType as ao, type DerivationsControl as ap, type DerivationsSchema as aq, type DeriveAccessor as ar, type DispatchEventsFromSchema as as, type EffectCleanup as at, type EffectsControl as au, type EventPayloadSchema as av, type EventsAccessor as aw, type EventsAccessorFromSchema as ax, type EventsDef as ay, type EventsSchema as az, type TypedConstraintsDef as b, type TypedResolversDef as c, type ModuleHooks as d, type CrossModuleDerivationsDef as e, type CrossModuleEffectsDef as f, type CrossModuleConstraintsDef as g, type ModuleDef as h, type CreateSystemOptionsSingle as i, type SingleModuleSystem as j, type ModulesMap as k, type CreateSystemOptionsNamed as l, type TraceOption as m, type ErrorBoundaryConfig as n, type Requirement as o, type RequirementKeyFn as p, DirectiveError as q, type DistributableSnapshot as r, type DistributableSnapshotOptions as s, type DynamicConstraintDef as t, type DynamicEffectDef as u, type DynamicResolverDef as v, type FactsSnapshot as w, type HistoryOption as x, type HistoryState as y, type InferEvents as z };
3049
+ export { type OperatorObject as $, type AnySystem as A, type BatchConfig as B, type ClauseResult as C, type DefinitionMeta as D, type EffectsDef as E, type FactTemplate as F, type FactsSnapshot as G, type HistoryAPI as H, type HistoryOption as I, type HistoryState as J, type InferDerivations as K, type InferEvents as L, type ModuleSchema as M, type NamespacedSystem as N, type InferFacts as O, type PatchSpec as P, type InferRequirementTypes as Q, type RequirementWithId as R, type SchemaType as S, type TypedDerivationsDef as T, type InferRequirements as U, type InferSchemaType as V, type InferSelectorState as W, type KeySelector as X, type MetaAccessor as Y, type MetaMatch as Z, type ObservationEvent as _, type FactPredicate as a, type RequirementsSchema as a$, type PatchValue as a0, type PayloadRef as a1, type PredicateClause as a2, type PredicateCombinator as a3, type PredicateCombinatorKey as a4, type PredicateObject as a5, type PredicateOp as a6, type RetryPolicy as a7, type Schema as a8, type Snapshot as a9, type DerivationReturnType as aA, type DerivationsControl as aB, type DerivationsSchema as aC, type DeriveAccessor as aD, type DispatchEventsFromSchema as aE, type EffectCleanup as aF, type EffectsControl as aG, type EventPayloadSchema as aH, type EventsAccessor as aI, type EventsAccessorFromSchema as aJ, type EventsDef as aK, type EventsSchema as aL, type FactKeys as aM, type FactReturnType as aN, type FlexibleEventHandler as aO, type HistoryConfig as aP, type InferEventPayloadFromSchema as aQ, type InferRequirementPayloadFromSchema as aR, type InferSchema as aS, type MutableNamespacedFacts as aT, type NamespacedDerivations as aU, type NamespacedEventsAccessor as aV, type NamespacedFacts as aW, type ObservableKeys as aX, type RequirementExplanation as aY, type RequirementOutput as aZ, type RequirementPayloadSchema$1 as a_, type System as aa, type SystemConfig as ab, type SystemInspection as ac, type SystemMode as ad, type SystemSnapshot as ae, type TraceEntry as af, isNamespacedSystem as ag, isSingleModuleSystem as ah, type FactsStore as ai, type ConstraintsDef as aj, type ConstraintState as ak, type ResolversDef as al, type ResolverStatus as am, type FactChange as an, type ReconcileResult as ao, type RecoveryStrategy as ap, type ErrorSource as aq, type RetryLaterConfig as ar, type BatchItemResult as as, type BatchResolveResults as at, type ConstraintsControl as au, type CrossModuleConstraintDef as av, type CrossModuleDerivationFn as aw, type CrossModuleEffectDef as ax, type CrossModuleFactsWithSelf as ay, type DerivationKeys as az, type Facts as b, type ResolverContext as b0, type ResolversControl as b1, type SnapshotMeta as b2, type SystemEvent as b3, type TraceConfig as b4, type TypedConstraintDef as b5, type TypedResolverContext as b6, type TypedResolverDef as b7, type UnionEvents as b8, type RequirementOutput$1 as b9, type TypedEventsDef as c, type TypedConstraintsDef as d, type TypedResolversDef as e, type ModuleHooks as f, type CrossModuleDeps as g, type CrossModuleDerivationsDef as h, type CrossModuleEffectsDef as i, type CrossModuleConstraintsDef as j, type ModuleDef as k, type CreateSystemOptionsSingle as l, type SingleModuleSystem as m, type ModulesMap as n, type CreateSystemOptionsNamed as o, type Plugin as p, type TraceOption as q, type ErrorBoundaryConfig as r, type Requirement as s, type RequirementKeyFn as t, DirectiveError as u, type DistributableSnapshot as v, type DistributableSnapshotOptions as w, type DynamicConstraintDef as x, type DynamicEffectDef as y, type DynamicResolverDef as z };