@hyperscale0/udl 2.6.1 → 3.0.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 (213) hide show
  1. package/CHANGELOG.md +2 -330
  2. package/LICENSING.md +1 -2
  3. package/README.md +3 -114
  4. package/TRADEMARKS.md +2 -2
  5. package/dist/diagnostics.d.ts +21 -201
  6. package/dist/diagnostics.d.ts.map +1 -1
  7. package/dist/diagnostics.js +29 -193
  8. package/dist/diagnostics.js.map +1 -1
  9. package/dist/evolution.d.ts +3 -132
  10. package/dist/evolution.d.ts.map +1 -1
  11. package/dist/evolution.js +29 -633
  12. package/dist/evolution.js.map +1 -1
  13. package/dist/finance.d.ts +5 -72
  14. package/dist/finance.d.ts.map +1 -1
  15. package/dist/finance.js +233 -737
  16. package/dist/finance.js.map +1 -1
  17. package/dist/index.d.ts +7 -18
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +7 -12
  20. package/dist/index.js.map +1 -1
  21. package/dist/instrument-references.d.ts.map +1 -1
  22. package/dist/instrument-references.js +3 -2
  23. package/dist/instrument-references.js.map +1 -1
  24. package/dist/schema.d.ts +2079 -4564
  25. package/dist/schema.d.ts.map +1 -1
  26. package/dist/schema.js +270 -1609
  27. package/dist/schema.js.map +1 -1
  28. package/dist/validation.d.ts +8 -104
  29. package/dist/validation.d.ts.map +1 -1
  30. package/dist/validation.js +653 -3271
  31. package/dist/validation.js.map +1 -1
  32. package/docs/README.md +147 -14
  33. package/package.json +7 -11
  34. package/spec/README.md +151 -164
  35. package/spec/darb.udl.json +249 -0
  36. package/spec/udl.schema.json +4104 -3202
  37. package/src/diagnostics.ts +51 -246
  38. package/src/evolution.ts +39 -1045
  39. package/src/finance.ts +287 -1127
  40. package/src/index.ts +18 -142
  41. package/src/instrument-references.ts +3 -2
  42. package/src/schema.ts +285 -1843
  43. package/src/validation.ts +870 -5611
  44. package/conformance/README.md +0 -82
  45. package/conformance/evolution/action-contract.expected.json +0 -10
  46. package/conformance/evolution/action-contract.live.udl +0 -44
  47. package/conformance/evolution/action-contract.next.udl +0 -45
  48. package/conformance/evolution/product-identity.expected.json +0 -10
  49. package/conformance/evolution/product-identity.live.udl +0 -55
  50. package/conformance/evolution/product-identity.next.udl +0 -55
  51. package/conformance/evolution/version-required.expected.json +0 -10
  52. package/conformance/evolution/version-required.live.udl +0 -55
  53. package/conformance/evolution/version-required.next.udl +0 -58
  54. package/conformance/invalid/action-without-transition.expected.json +0 -10
  55. package/conformance/invalid/action-without-transition.udl +0 -60
  56. package/conformance/invalid/agent-description-too-long.expected.json +0 -10
  57. package/conformance/invalid/agent-description-too-long.udl +0 -57
  58. package/conformance/invalid/blank-title.expected.json +0 -10
  59. package/conformance/invalid/blank-title.udl +0 -54
  60. package/conformance/invalid/call-binds-results.expected.json +0 -10
  61. package/conformance/invalid/call-binds-results.udl +0 -314
  62. package/conformance/invalid/call-unknown-action.expected.json +0 -10
  63. package/conformance/invalid/call-unknown-action.udl +0 -314
  64. package/conformance/invalid/composition-dial-duplicate-key.expected.json +0 -10
  65. package/conformance/invalid/composition-dial-duplicate-key.udl +0 -73
  66. package/conformance/invalid/depth-budget.expected.json +0 -10
  67. package/conformance/invalid/depth-budget.udl +0 -49
  68. package/conformance/invalid/duplicate-subject.expected.json +0 -10
  69. package/conformance/invalid/duplicate-subject.udl +0 -230
  70. package/conformance/invalid/forged-effects.expected.json +0 -10
  71. package/conformance/invalid/forged-effects.udl +0 -76
  72. package/conformance/invalid/format-version.expected.json +0 -10
  73. package/conformance/invalid/format-version.udl +0 -54
  74. package/conformance/invalid/instrument-id-not-snake-case.expected.json +0 -10
  75. package/conformance/invalid/instrument-id-not-snake-case.udl +0 -54
  76. package/conformance/invalid/invalid-aggregate-gate-shape.expected.json +0 -10
  77. package/conformance/invalid/invalid-aggregate-gate-shape.udl +0 -1819
  78. package/conformance/invalid/invalid-check-duration.expected.json +0 -10
  79. package/conformance/invalid/invalid-check-duration.udl +0 -219
  80. package/conformance/invalid/invalid-dial-anchor.expected.json +0 -10
  81. package/conformance/invalid/invalid-dial-anchor.udl +0 -219
  82. package/conformance/invalid/invalid-exception-parent-ref.expected.json +0 -10
  83. package/conformance/invalid/invalid-exception-parent-ref.udl +0 -2487
  84. package/conformance/invalid/invalid-exposure-shape.expected.json +0 -10
  85. package/conformance/invalid/invalid-exposure-shape.udl +0 -1819
  86. package/conformance/invalid/invalid-journeys.expected.json +0 -10
  87. package/conformance/invalid/invalid-journeys.udl +0 -77
  88. package/conformance/invalid/invalid-remainder.expected.json +0 -10
  89. package/conformance/invalid/invalid-remainder.udl +0 -220
  90. package/conformance/invalid/invalid-schema-keyword.expected.json +0 -10
  91. package/conformance/invalid/invalid-schema-keyword.udl +0 -220
  92. package/conformance/invalid/invalid-utf8.expected.json +0 -10
  93. package/conformance/invalid/invalid-utf8.udl +0 -1
  94. package/conformance/invalid/leaf-effect-mismatch.expected.json +0 -10
  95. package/conformance/invalid/leaf-effect-mismatch.udl +0 -314
  96. package/conformance/invalid/malformed-json.expected.json +0 -10
  97. package/conformance/invalid/malformed-json.udl +0 -1
  98. package/conformance/invalid/missing-create-action.expected.json +0 -10
  99. package/conformance/invalid/missing-create-action.udl +0 -48
  100. package/conformance/invalid/missing-exception-amount-field.expected.json +0 -10
  101. package/conformance/invalid/missing-exception-amount-field.udl +0 -2487
  102. package/conformance/invalid/missing-exception-contract.expected.json +0 -14
  103. package/conformance/invalid/missing-exception-contract.udl +0 -2523
  104. package/conformance/invalid/missing-exception-reason-field.expected.json +0 -10
  105. package/conformance/invalid/missing-exception-reason-field.udl +0 -2487
  106. package/conformance/invalid/not-an-object.expected.json +0 -10
  107. package/conformance/invalid/not-an-object.udl +0 -1
  108. package/conformance/invalid/payout-reconcile-not-a-bank-debit.expected.json +0 -10
  109. package/conformance/invalid/payout-reconcile-not-a-bank-debit.udl +0 -259
  110. package/conformance/invalid/piece-plan-without-partition.expected.json +0 -10
  111. package/conformance/invalid/piece-plan-without-partition.udl +0 -305
  112. package/conformance/invalid/private-action-independent-approval.expected.json +0 -10
  113. package/conformance/invalid/private-action-independent-approval.udl +0 -314
  114. package/conformance/invalid/quote-freeze-set-incomplete.expected.json +0 -10
  115. package/conformance/invalid/quote-freeze-set-incomplete.udl +0 -261
  116. package/conformance/invalid/quote-named-reference-gate.expected.json +0 -10
  117. package/conformance/invalid/quote-named-reference-gate.udl +0 -50
  118. package/conformance/invalid/reconcile-named-reference-gate.expected.json +0 -10
  119. package/conformance/invalid/reconcile-named-reference-gate.udl +0 -50
  120. package/conformance/invalid/unfund-order-not-reversed.expected.json +0 -10
  121. package/conformance/invalid/unfund-order-not-reversed.udl +0 -314
  122. package/conformance/invalid/unknown-key.expected.json +0 -10
  123. package/conformance/invalid/unknown-key.udl +0 -55
  124. package/conformance/invalid/unknown-reference-gate-field.expected.json +0 -10
  125. package/conformance/invalid/unknown-reference-gate-field.udl +0 -1819
  126. package/conformance/invalid/unknown-required-field.expected.json +0 -10
  127. package/conformance/invalid/unknown-required-field.udl +0 -220
  128. package/conformance/invalid/unreachable-state.expected.json +0 -10
  129. package/conformance/invalid/unreachable-state.udl +0 -55
  130. package/conformance/invalid/wrong-exception-amount-field.expected.json +0 -10
  131. package/conformance/invalid/wrong-exception-amount-field.udl +0 -2487
  132. package/conformance/invalid/wrong-exception-reason-field.expected.json +0 -10
  133. package/conformance/invalid/wrong-exception-reason-field.udl +0 -2487
  134. package/conformance/valid/agent-description.expected.json +0 -6
  135. package/conformance/valid/agent-description.udl +0 -66
  136. package/conformance/valid/attested.expected.json +0 -6
  137. package/conformance/valid/attested.udl +0 -251
  138. package/conformance/valid/cards.expected.json +0 -6
  139. package/conformance/valid/cards.udl +0 -1579
  140. package/conformance/valid/commerce-escrow.expected.json +0 -6
  141. package/conformance/valid/commerce-escrow.udl +0 -1512
  142. package/conformance/valid/compiled-crowdfunding.expected.json +0 -6
  143. package/conformance/valid/compiled-crowdfunding.udl +0 -1843
  144. package/conformance/valid/compiled-watch-club.expected.json +0 -6
  145. package/conformance/valid/compiled-watch-club.udl +0 -2486
  146. package/conformance/valid/complete-contract.expected.json +0 -6
  147. package/conformance/valid/complete-contract.udl +0 -218
  148. package/conformance/valid/effect-signatures.expected.json +0 -6
  149. package/conformance/valid/effect-signatures.udl +0 -75
  150. package/conformance/valid/hand-edited.expected.json +0 -6
  151. package/conformance/valid/hand-edited.udl +0 -1
  152. package/conformance/valid/insured-car-marketplace.expected.json +0 -6
  153. package/conformance/valid/insured-car-marketplace.udl +0 -1050
  154. package/conformance/valid/insured-travel.expected.json +0 -6
  155. package/conformance/valid/insured-travel.udl +0 -3469
  156. package/conformance/valid/minimal.expected.json +0 -6
  157. package/conformance/valid/minimal.udl +0 -62
  158. package/conformance/valid/piece-plan-calls.expected.json +0 -6
  159. package/conformance/valid/piece-plan-calls.udl +0 -314
  160. package/conformance/valid/protection.expected.json +0 -6
  161. package/conformance/valid/protection.udl +0 -1551
  162. package/conformance/valid/string-escaping.expected.json +0 -6
  163. package/conformance/valid/string-escaping.udl +0 -54
  164. package/conformance/valid/vocabulary.expected.json +0 -6
  165. package/conformance/valid/vocabulary.udl +0 -2012
  166. package/dist/allocation.d.ts +0 -60
  167. package/dist/allocation.d.ts.map +0 -1
  168. package/dist/allocation.js +0 -177
  169. package/dist/allocation.js.map +0 -1
  170. package/dist/check-profiles.d.ts +0 -57
  171. package/dist/check-profiles.d.ts.map +0 -1
  172. package/dist/check-profiles.js +0 -62
  173. package/dist/check-profiles.js.map +0 -1
  174. package/dist/distribution.d.ts +0 -15
  175. package/dist/distribution.d.ts.map +0 -1
  176. package/dist/distribution.js +0 -49
  177. package/dist/distribution.js.map +0 -1
  178. package/dist/effects.d.ts +0 -58
  179. package/dist/effects.d.ts.map +0 -1
  180. package/dist/effects.js +0 -1126
  181. package/dist/effects.js.map +0 -1
  182. package/dist/reference.d.ts +0 -3
  183. package/dist/reference.d.ts.map +0 -1
  184. package/dist/reference.js +0 -28
  185. package/dist/reference.js.map +0 -1
  186. package/dist/vocabulary.d.ts +0 -23
  187. package/dist/vocabulary.d.ts.map +0 -1
  188. package/dist/vocabulary.js +0 -1052
  189. package/dist/vocabulary.js.map +0 -1
  190. package/docs/funding-custody.md +0 -165
  191. package/docs/guide/01-a-document.md +0 -37
  192. package/docs/guide/02-money-steps.md +0 -23
  193. package/docs/guide/03-laws.md +0 -18
  194. package/docs/guide/04-fees-and-remainder.md +0 -36
  195. package/docs/guide/05-checks-updates-dials.md +0 -7
  196. package/docs/guide/06-effects.md +0 -11
  197. package/docs/guide/07-evolution.md +0 -11
  198. package/docs/guide/08-implementing.md +0 -13
  199. package/docs/guide/09-schedules-and-allocation.md +0 -132
  200. package/docs/llms-full.txt +0 -2008
  201. package/docs/llms.txt +0 -14
  202. package/docs/piece-plans.md +0 -148
  203. package/docs/reference/canonical.md +0 -16
  204. package/docs/reference/clauses.md +0 -1585
  205. package/docs/reference/cli.md +0 -24
  206. package/docs/reference/diagnostics.md +0 -38
  207. package/skills/udl/SKILL.md +0 -28
  208. package/src/allocation.ts +0 -259
  209. package/src/check-profiles.ts +0 -80
  210. package/src/distribution.ts +0 -61
  211. package/src/effects.ts +0 -1920
  212. package/src/reference.ts +0 -31
  213. package/src/vocabulary.ts +0 -1635
package/src/schema.ts CHANGED
@@ -1,1924 +1,366 @@
1
- import { referencePatternPrefix } from "./reference.js";
2
1
  import { z } from "zod";
3
2
 
4
- import { udlCheckEvidenceProfiles } from "./check-profiles.js";
5
-
6
- export const udlEffectKinds = [
7
- "decides",
8
- "holds",
9
- "moves",
10
- "notifies",
11
- "reads",
12
- "schedules",
13
- ] as const;
14
-
15
- export type UdlEffectKind = (typeof udlEffectKinds)[number];
16
-
17
- export const UDL_FORMAT_VERSION = 1 as const;
18
-
19
- const snakeCasePattern = /^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/;
20
- const camelCasePattern = /^[a-z][A-Za-z0-9]*$/;
21
- const fieldPathPattern = /^[a-z][A-Za-z0-9]*(?:\.[a-z][A-Za-z0-9]*)*$/;
22
- const idPrefixPattern = /^[a-z]{2,8}$/;
23
- const eventNamePattern = /^[a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)+$/;
24
-
25
- const udlSnakeCaseSchema = z
26
- .string()
27
- .regex(snakeCasePattern, "must be a snake_case identifier");
28
- const udlInstrumentIdSchema = udlSnakeCaseSchema.meta({
29
- "x-udl-reference": "instrument",
30
- });
31
- const udlActionNameSchema = z
32
- .string()
33
- .regex(snakeCasePattern, "must be a snake_case action identifier");
34
- const udlFieldNameSchema = z
3
+ export const UDL_FORMAT_VERSION = 3 as const;
4
+ const name = z
35
5
  .string()
36
- .regex(camelCasePattern, "must be a camelCase field name");
37
-
38
- export const udlPublicActionSchema = z
39
- .string()
40
- .regex(camelCasePattern, "must be a camelCase public action name");
41
-
42
- export const udlInstrumentActionIdSchema = z
43
- .string()
44
- .max(160)
45
- .regex(
46
- /^[a-z][a-z0-9_]*\.[a-z][a-z0-9_]*$/,
47
- "must name an instrument action as instrument_id.action_key",
48
- );
49
-
50
- const nonEmptyTextSchema = z
51
- .string()
52
- .refine((value) => value.trim().length > 0, "must not be blank");
53
- // Agent-facing presentation prose. Every MCP tool description an agent reads is
54
- // this string, so it is capped: a 400-character ceiling keeps a 60-tool surface
55
- // under the token budget a client spends before it can pick a tool.
56
- const udlAgentDescriptionSchema = nonEmptyTextSchema.max(400);
57
- const fieldPathSchema = z
6
+ .regex(/^[a-z][a-zA-Z0-9_]*$/)
7
+ .max(80);
8
+ const text = z.string().min(1).max(2048);
9
+ const amount = z.string().regex(/^(0|[1-9][0-9]{0,17})$/);
10
+ const integer = z.number().int().safe();
11
+ const scalar = z.union([z.string(), integer, z.boolean()]);
12
+ const path = z
58
13
  .string()
59
- .regex(fieldPathPattern, "must be a dot-separated camelCase field path");
60
- const instanceValuePathSchema = z
61
- .string()
62
- .regex(
63
- /^(?:fields|refs)\.[a-z][A-Za-z0-9]*$/,
64
- "must name one declared fields.* or refs.* value",
65
- );
66
- const jsonObjectSchema = z.record(z.string(), z.json());
67
- const stringMapSchema = z.record(nonEmptyTextSchema, nonEmptyTextSchema);
68
-
69
- const providerFamilyIds = [
70
- "accounts_ledger_first_party",
71
- "identity_verification",
72
- "national_identity",
73
- "credit_bureau",
74
- "sanctions_screening",
75
- "enforcement_instrument",
76
- "credit_servicing",
77
- "collections_agency",
78
- "settlement_ingestion",
79
- "payouts",
80
- "banking_or_card_issuing",
81
- "insurance_carrier",
82
- "insurance_claims_adjuster",
83
- "air_carrier",
84
- "lodging_supplier",
85
- "email_or_notification",
86
- ] as const;
87
- export const udlProviderFamilyIdSchema = z.enum(providerFamilyIds);
14
+ .regex(/^[a-z][a-zA-Z0-9_]*(?:\.[a-z][a-zA-Z0-9_]*)*$/)
15
+ .max(240);
16
+ const instrumentId = name.meta({ "x-udl-reference": "instrument" });
88
17
 
89
- const udlDeclaredValuePolicySchema = z.enum(["required", "optional", "none"]);
90
-
91
- const udlSubjectSchema = z.strictObject({
92
- declaredValue: udlDeclaredValuePolicySchema,
93
- kind: udlSnakeCaseSchema,
94
- schema: jsonObjectSchema,
95
- title: nonEmptyTextSchema,
96
- version: z.number().int().positive(),
97
- });
98
-
99
- const udlInstrumentSubjectSchema = z.strictObject({
100
- extensible: z.boolean().optional(),
101
- kinds: z.array(udlSnakeCaseSchema).min(1),
102
- });
103
-
104
- const udlExampleSchema = z.strictObject({
105
- input: jsonObjectSchema,
106
- name: nonEmptyTextSchema,
107
- output: z.json().optional(),
108
- });
109
-
110
- const udlLifecycleTransitionSchema = z.strictObject({
111
- from: z.array(udlSnakeCaseSchema).min(1),
112
- to: udlSnakeCaseSchema,
18
+ /** Currency belongs to the document. Accounts and amounts cannot override it. */
19
+ export const udlPartySchema = z.strictObject({
20
+ kind: z.enum(["person", "business", "staff"]),
21
+ role: name.optional(),
113
22
  });
114
23
 
115
- const udlLifecycleSchema = z.strictObject({
116
- initial: udlSnakeCaseSchema,
117
- states: z.array(udlSnakeCaseSchema).min(1),
118
- transitions: z.record(udlActionNameSchema, udlLifecycleTransitionSchema),
119
- });
120
-
121
- const udlUpdatePolicySchema = z.strictObject({
122
- examples: z.array(udlExampleSchema).optional(),
123
- fields: z.array(udlFieldNameSchema).min(1),
124
- states: z.array(udlSnakeCaseSchema).min(1),
125
- });
126
-
127
- const udlDateComparisonOperatorSchema = z.enum([">=", ">", "<=", "<", "=="]);
128
-
129
- const udlDateComparisonSchema = z.strictObject({
130
- localPath: fieldPathSchema,
131
- operator: udlDateComparisonOperatorSchema,
132
- referencedPath: fieldPathSchema,
133
- });
134
-
135
- const udlStoredFieldSchema = z.strictObject({ field: udlFieldNameSchema });
136
- const udlOffsetSchema = z.union([nonEmptyTextSchema, udlStoredFieldSchema]);
137
-
138
- const udlAttestationSchema = z.strictObject({
139
- forAction: udlActionNameSchema.optional(),
140
- action: instanceValuePathSchema,
141
- digest: instanceValuePathSchema,
142
- role: instanceValuePathSchema,
143
- expiresAt: instanceValuePathSchema,
144
- instrument: instanceValuePathSchema,
145
- party: z.string().regex(/^[a-z][A-Za-z0-9_]*$/),
146
- consume: udlActionNameSchema,
147
- });
148
-
149
- const udlGateSchema = z.strictObject({
150
- attests: udlAttestationSchema.optional(),
151
- /** Local field key <- referenced instance path; create actions only. */
152
- bind: z.record(udlFieldNameSchema, fieldPathSchema).optional(),
153
- dateComparison: udlDateComparisonSchema.optional(),
154
- dueBefore: z
155
- .strictObject({ field: udlFieldNameSchema, offset: nonEmptyTextSchema })
156
- .optional(),
157
- field: udlFieldNameSchema,
158
- /** Local instance path === referenced instance path at admission. */
159
- match: z.record(fieldPathSchema, fieldPathSchema).optional(),
160
- /** Opt-in over an optional reference field: absent passes, set is held to the clause. */
24
+ const fieldBase = {
25
+ name,
161
26
  optional: z.literal(true).optional(),
162
- statuses: z.array(udlSnakeCaseSchema).min(1),
163
- /** One dependent ever per referenced instance; create actions only. */
164
- unique: z
165
- .union([
166
- z.literal(true),
167
- z.strictObject({
168
- namespace: udlSnakeCaseSchema,
169
- byFields: z.array(udlFieldNameSchema).min(1).max(8),
170
- }),
171
- ])
172
- .optional(),
173
- });
174
-
175
- const udlBindingSchema = z.discriminatedUnion("from", [
176
- z.strictObject({ from: z.literal("const"), value: z.string() }),
177
- z.strictObject({ from: z.literal("instance"), path: fieldPathSchema }),
178
- z.strictObject({ from: z.literal("input"), path: fieldPathSchema }),
179
- ]);
180
-
181
- const udlStepOperationSchema = z.enum([
182
- "account.escrow.provision",
183
- "account.freeze",
184
- "account.unfreeze",
185
- ]);
186
-
187
- const udlMoveOperationSchema = z.enum([
188
- "internal_transfer.create",
189
- "internal_transfer.reserve",
190
- "internal_transfer.post",
191
- "internal_transfer.void",
192
- ]);
193
-
194
- export const udlKernelOperationSchema = z.enum([
195
- ...udlStepOperationSchema.options,
196
- ...udlMoveOperationSchema.options,
197
- ]);
198
-
199
- const udlStepSchema = z.strictObject({
200
- bind: z.record(fieldPathSchema, udlBindingSchema),
201
- capture: stringMapSchema.optional(),
202
- operation: udlStepOperationSchema,
203
- });
204
-
205
- const udlMoveSchema = z.strictObject({
206
- bind: z.record(fieldPathSchema, udlBindingSchema),
207
- capture: stringMapSchema.optional(),
208
- key: udlSnakeCaseSchema,
209
- operation: udlMoveOperationSchema,
210
- });
211
-
212
- const udlDueRecurrenceSchema = z.strictObject({
213
- countField: udlFieldNameSchema.optional(),
214
- delinquency: z.literal("parent_policy").optional(),
215
- drainAction: udlActionNameSchema.optional(),
216
- period: z.union([
217
- nonEmptyTextSchema,
218
- z.strictObject({
219
- calendar: z.enum(["gregorian", "hijri"]),
220
- monthEnd: z.literal("clamp_to_last_day"),
221
- months: z.number().int().positive(),
222
- }),
223
- ]),
224
- liability: z.literal("one_open").optional(),
225
- untilAction: udlActionNameSchema.optional(),
226
- untilField: udlFieldNameSchema.optional(),
227
- });
228
-
229
- const udlDueParentStatusSchema = z.strictObject({
230
- instrumentId: udlInstrumentIdSchema,
231
- refField: udlFieldNameSchema,
232
- statuses: z.array(udlSnakeCaseSchema).min(1),
233
- });
234
-
235
- const udlDueSchema = z.strictObject({
236
- every: udlDueRecurrenceSchema.optional(),
237
- field: udlFieldNameSchema,
238
- offset: udlOffsetSchema.optional(),
239
- whenParentStatus: udlDueParentStatusSchema.optional(),
240
- });
241
-
242
- const udlDeadlineSchema = z.strictObject({
243
- field: udlFieldNameSchema,
244
- offset: udlOffsetSchema.optional(),
245
- });
246
-
247
- const udlSetsAtSchema = z.strictObject({
248
- field: udlFieldNameSchema,
249
- marker: z.literal(true).optional(),
250
- offset: nonEmptyTextSchema,
251
- });
252
-
253
- const udlQuoteChargeSchema = z.strictObject({
254
- bps: z.number().int().min(0).max(9_999),
255
- withinOffset: nonEmptyTextSchema.optional(),
256
- });
257
-
258
- export const udlQuoteRetainedRoleSchema = z.enum([
259
- "payer",
260
- "beneficiary",
261
- "subjectHolder",
262
- ]);
263
- export type UdlQuoteRetainedRole = z.infer<typeof udlQuoteRetainedRoleSchema>;
264
-
265
- // A priced, expiring offer. The quoting action splits `baseField` into a charge
266
- // and a net at its own clock, freezes the fields the price was read from, and
267
- // stamps an expiry. Only the paired `commit` action may spend the offer, and
268
- // only while it is unexpired and its frozen fields still hold.
269
- const udlQuoteShape = {
270
- /** Date-time whose remaining time picks the charge tier; omit for elapsed age. */
271
- anchorField: udlFieldNameSchema.optional(),
272
- baseField: udlFieldNameSchema,
273
- chargeRef: udlFieldNameSchema,
274
- /** Party role that keeps the quoted charge instead of moving it through an escrow payout action. */
275
- chargeRetainedBy: udlQuoteRetainedRoleSchema.optional(),
276
- charges: z.array(udlQuoteChargeSchema).min(1),
277
- /** Fixed ISO-8601 duration from the quoting action, or a stored deadline. */
278
- expires: z.union([
279
- z.strictObject({ field: udlFieldNameSchema }),
280
- z.strictObject({ offset: nonEmptyTextSchema }),
281
- ]),
282
- fixes: z.array(udlFieldNameSchema).min(1),
283
- netDestinationField: udlFieldNameSchema,
284
- netRef: udlFieldNameSchema,
27
+ description: text.optional(),
285
28
  };
286
- const udlQuoteSchema = z.strictObject(udlQuoteShape);
287
-
288
- /**
289
- * Where a quoting action stamps the instant its offer stops being committable.
290
- * Derived from the author's net ref rather than a fixed name, so two offers on
291
- * one instrument never share the slot.
292
- */
293
- export function quoteExpiresAtRefKey(quote: {
294
- readonly netRef: string;
295
- }): string {
296
- return `${quote.netRef}ExpiresAt`;
297
- }
298
-
299
- /**
300
- * Where a quoting action stamps the fingerprint of the field values it froze.
301
- * The committing action recomputes it against the live fields, which is how an
302
- * offer priced on one set of terms refuses to pay out against another.
303
- */
304
- export function quoteFrozenRefKey(quote: { readonly netRef: string }): string {
305
- return `${quote.netRef}Frozen`;
306
- }
307
-
308
- /**
309
- * Every ref key one quote seeds: the charge and the net the author named, plus
310
- * the two the machinery derives to hold the offer itself. One derivation, read
311
- * by the validator, the compiler, and the runtime alike.
312
- */
313
- export function quoteSeededRefKeys(quote: {
314
- readonly chargeRef: string;
315
- readonly netRef: string;
316
- }): readonly string[] {
317
- return [
318
- quote.chargeRef,
319
- quote.netRef,
320
- quoteExpiresAtRefKey(quote),
321
- quoteFrozenRefKey(quote),
322
- ];
323
- }
324
-
325
- const udlDecisionSchema = z.strictObject({
326
- capability: udlProviderFamilyIdSchema,
327
- deadlineMs: z.number().int().positive().max(15_000),
328
- // A decision that never came back is not an approval. `approve` would let a
329
- // document release money because a counterparty went quiet, so the grammar
330
- // admits only the fail-closed answer. Every published document already
331
- // writes `decline`; widening later is additive, narrowing later would not
332
- // be.
333
- onTimeout: z.literal("decline"),
334
- });
335
-
336
- const udlAggregateCheckSchema = z.discriminatedUnion("kind", [
29
+ export const udlFieldSchema = z.discriminatedUnion("type", [
337
30
  z.strictObject({
338
- amountField: udlFieldNameSchema,
339
- kind: z.literal("sum_at_least"),
340
- targetField: udlFieldNameSchema,
31
+ ...fieldBase,
32
+ type: z.literal("money"),
33
+ value: amount.optional(),
34
+ minimum: amount.optional(),
35
+ maximum: amount.optional(),
341
36
  }),
342
37
  z.strictObject({
343
- amountField: udlFieldNameSchema,
344
- kind: z.literal("sum_below"),
345
- targetField: udlFieldNameSchema,
38
+ ...fieldBase,
39
+ type: z.literal("account"),
40
+ owner: name,
41
+ key: name.optional(),
42
+ book: z.enum(["cash", "claim"]).default("cash"),
43
+ contra: z.literal(true).optional(),
44
+ external: z.literal(true).optional(),
346
45
  }),
347
46
  z.strictObject({
348
- amountField: udlFieldNameSchema,
349
- kind: z.literal("sum_exactly"),
350
- targetField: udlFieldNameSchema,
47
+ ...fieldBase,
48
+ type: z.literal("ref"),
49
+ target: z.union([instrumentId, z.array(instrumentId).min(1).max(16)]),
351
50
  }),
352
- // Siblings summed against a cap read from the LOCKED anchor row's
353
- // machinery-seeded ref (never a stored field on the counted rows).
354
51
  z.strictObject({
355
- amountField: udlFieldNameSchema,
356
- anchorRef: udlFieldNameSchema,
357
- kind: z.literal("sum_within_anchor_ref"),
52
+ ...fieldBase,
53
+ type: z.literal("date"),
54
+ value: z.iso.datetime({ offset: true }).optional(),
358
55
  }),
359
56
  z.strictObject({
360
- kind: z.literal("count_at_least"),
361
- targetField: udlFieldNameSchema,
57
+ ...fieldBase,
58
+ type: z.literal("duration"),
59
+ value: integer.positive().optional(),
362
60
  }),
363
61
  z.strictObject({
364
- kind: z.literal("count_exactly"),
365
- value: z.number().int().min(0),
62
+ ...fieldBase,
63
+ type: z.literal("text"),
64
+ value: text.optional(),
65
+ maxLength: integer.positive().max(2048).optional(),
366
66
  }),
367
67
  z.strictObject({
368
- kind: z.literal("ordered"),
369
- field: udlFieldNameSchema,
370
- positionField: udlFieldNameSchema,
68
+ ...fieldBase,
69
+ type: z.literal("integer"),
70
+ value: integer.optional(),
71
+ minimum: integer.optional(),
72
+ maximum: integer.optional(),
371
73
  }),
372
74
  z.strictObject({
373
- kind: z.literal("schedule"),
374
- positionField: udlFieldNameSchema,
375
- dateField: udlFieldNameSchema,
376
- datesField: udlFieldNameSchema,
377
- amounts: z
378
- .array(
379
- z.strictObject({
380
- amountField: udlFieldNameSchema,
381
- totalField: udlFieldNameSchema,
382
- }),
383
- )
384
- .min(1)
385
- .max(8),
386
- remainder: z.literal("first"),
75
+ ...fieldBase,
76
+ type: z.literal("percent"),
77
+ value: integer.min(0).max(10000).optional(),
78
+ }),
79
+ z.strictObject({
80
+ ...fieldBase,
81
+ type: z.literal("boolean"),
82
+ value: z.boolean().optional(),
83
+ }),
84
+ z.strictObject({
85
+ ...fieldBase,
86
+ type: z.literal("enum"),
87
+ values: z.array(name).min(1).max(64),
88
+ value: name.optional(),
387
89
  }),
388
- z.strictObject({ kind: z.literal("all_in") }),
389
90
  z.strictObject({
390
- field: udlFieldNameSchema,
391
- kind: z.literal("count_equals_field"),
91
+ ...fieldBase,
92
+ type: z.literal("list"),
93
+ item: z.enum(["money", "date", "text", "integer", "ref"]),
94
+ target: instrumentId.optional(),
95
+ maxItems: integer.min(1).max(366),
392
96
  }),
393
97
  ]);
394
98
 
395
- const udlAggregateConditionSchema = z.strictObject({
396
- anchorField: udlFieldNameSchema.optional(),
397
- dueBefore: z
398
- .strictObject({
399
- field: udlFieldNameSchema,
400
- offset: udlOffsetSchema.optional(),
401
- })
99
+ /** Values are constants or resolved typed paths, never executable strings. */
100
+ export const udlValueSchema = z.union([
101
+ z.strictObject({ literal: scalar }),
102
+ z.strictObject({ field: path }),
103
+ ]);
104
+ const value = udlValueSchema;
105
+ const values = z.array(value).min(1).max(256);
106
+
107
+ const selection = z.strictObject({
108
+ instrument: z.union([instrumentId, z.array(instrumentId).min(1).max(16)]),
109
+ reference: name,
110
+ anchor: path,
111
+ states: z.array(name).min(1).max(64),
112
+ limit: integer.min(1).max(366),
113
+ order: z.array(path).min(1).max(4).optional(),
114
+ window: z
115
+ .strictObject({ field: name, milliseconds: integer.positive() })
116
+ .optional(),
117
+ where: z
118
+ .record(path, value)
119
+ .refine(
120
+ (filters) => Object.keys(filters).length <= 8,
121
+ "at most eight selection filters",
122
+ )
123
+ .meta({ maxProperties: 8 })
402
124
  .optional(),
403
- check: udlAggregateCheckSchema,
404
- instrumentId: udlInstrumentIdSchema.optional(),
405
- over: z.enum(["children", "siblings"]),
406
- refField: udlFieldNameSchema,
407
- statuses: z.array(udlSnakeCaseSchema).min(1),
408
- });
409
-
410
- const udlExposureRequirementSchema = z.strictObject({
411
- groupField: udlFieldNameSchema.optional(),
412
- minimumField: udlFieldNameSchema.optional(),
413
- measure: z.strictObject({ allocation: udlSnakeCaseSchema }).optional(),
414
- amountField: udlFieldNameSchema,
415
- anchorField: udlFieldNameSchema,
416
- capField: udlFieldNameSchema,
417
- capOnAnchor: z.literal(true).optional(),
418
- childInstrumentId: udlInstrumentIdSchema,
419
- statuses: z.array(udlSnakeCaseSchema).min(1),
420
- });
421
-
422
- // The tenant-backend decision port: the action's caller asserts the acting
423
- // party, checked at admission against the instrument's party bindings for the
424
- // allowed roles.
425
- const udlPartyRoleSchema = z.string().regex(/^[a-z][A-Za-z0-9_]*$/);
426
-
427
- const udlPortSchema = z.strictObject({
428
- allowedParties: z.array(udlPartyRoleSchema).min(1),
429
- capture: udlFieldNameSchema.optional(),
430
- });
431
-
432
- const udlPayoutSchema = z.strictObject({
433
- amount: instanceValuePathSchema,
434
- beneficiaryField: udlFieldNameSchema,
435
- beneficiaryPartyField: udlFieldNameSchema,
436
- capture: udlFieldNameSchema,
437
- currencyField: udlFieldNameSchema,
438
- sourceAccountField: udlFieldNameSchema,
439
- speed: z.literal("standard"),
440
125
  });
441
126
 
442
- /**
443
- * One expectation an action asserts about money it cannot see yet: how much,
444
- * in which currency, which way, and against whose provider-side row. Evidence
445
- * that lands later either matches under the declared law or the expectation
446
- * breaks: past the window the kernel raises the declared exception child, binds
447
- * the unmatched amount and the break reason onto it, and spends the due
448
- * occurrence. There is no third outcome and no silent wait.
449
- */
450
- const udlReconcileSchema = z.strictObject({
451
- /** `fields.<name>` or `refs.<name>`: the money this action says will land. */
452
- amount: instanceValuePathSchema,
453
- /** Where the matched evidence id lands in refs. */
454
- capture: udlFieldNameSchema,
455
- /** The ref naming the provider-side row the evidence must cite. */
456
- counterpartyRef: udlFieldNameSchema,
457
- currencyField: udlFieldNameSchema,
458
- direction: z.enum(["credit", "debit"]),
459
- /** Exactly one source. A reconcile never reads two ledgers at once. */
460
- evidence: z.enum(["movement", "provider_confirmation", "statement_line"]),
461
- /**
462
- * Where an expectation that never matched lands. The named child instrument
463
- * carries the break, and `maxOpen` caps how many of them one instance may
464
- * hold open at once, the same count measure the aggregate invariants use.
465
- */
466
- exception: z.strictObject({
467
- amountField: udlFieldNameSchema,
468
- childInstrumentId: udlInstrumentIdSchema,
469
- maxOpen: z.number().int().min(1).max(1_000),
470
- reasonField: udlFieldNameSchema,
471
- refField: udlFieldNameSchema,
127
+ /** A finite, ordered calculation graph. Every result is a declared field. */
128
+ export const udlCalculationSchema = z.discriminatedUnion("op", [
129
+ z.strictObject({
130
+ target: name,
131
+ op: z.literal("at"),
132
+ list: path,
133
+ position: value,
472
134
  }),
473
- /**
474
- * How a candidate becomes the match. `exact` demands equal minor units,
475
- * `tolerance` allows a bounded difference, `window` drops the amount test
476
- * for a source that nets several items into one line.
477
- */
478
- match: z.discriminatedUnion("law", [
479
- z.strictObject({ law: z.literal("exact") }),
480
- z.strictObject({
481
- dial: udlSnakeCaseSchema,
482
- law: z.literal("tolerance"),
483
- minorUnits: z.number().int().positive(),
484
- }),
485
- z.strictObject({ law: z.literal("window") }),
486
- ]),
487
- /** Fixed ISO-8601 duration from the expecting action, or a stored deadline. */
488
- within: z.union([
489
- z.strictObject({ field: udlFieldNameSchema }),
490
- z.strictObject({ offset: nonEmptyTextSchema }),
491
- ]),
492
- });
493
-
494
- const udlSignedSumSourceSchema = z.strictObject({
495
- amountField: udlFieldNameSchema,
496
- instrumentId: udlInstrumentIdSchema,
497
- refField: udlFieldNameSchema,
498
- sign: z.enum(["add", "subtract"]),
499
- statuses: z.array(udlSnakeCaseSchema).min(1),
500
- subtotalRef: udlFieldNameSchema,
501
- });
502
-
503
- const udlSignedSumSchema = z.strictObject({
504
- amountRef: udlFieldNameSchema,
505
- onNegative: z.literal("refuse"),
506
- onZero: z.enum(["refuse", "skip_steps"]),
507
- sources: z.array(udlSignedSumSourceSchema).min(1),
508
- });
509
-
510
- const udlDistributeSchema = z.strictObject({
511
- amountRef: udlFieldNameSchema,
512
- onZero: z.enum(["refuse", "skip_steps"]),
513
- pool: z.strictObject({
514
- from: z.literal("parent"),
515
- path: fieldPathSchema,
135
+ z.strictObject({
136
+ target: name,
137
+ op: z.literal("aggregate"),
138
+ selection,
139
+ measure: z.union([z.literal("count"), z.strictObject({ sum: path })]),
516
140
  }),
517
- refField: udlFieldNameSchema,
518
- statuses: z.array(udlSnakeCaseSchema).min(1),
519
- weightField: udlFieldNameSchema,
520
- });
521
-
522
- const udlRemainderCollectedSchema = z.strictObject({
523
- amountField: udlFieldNameSchema,
524
- instrumentId: udlInstrumentIdSchema,
525
- path: z.literal("refs").optional(),
526
- refField: udlFieldNameSchema,
527
- statuses: z.array(udlSnakeCaseSchema).min(1),
528
- });
529
-
530
- const udlRemainderSchema = z.strictObject({
531
- accumulateRef: udlFieldNameSchema.optional(),
532
- amountRef: udlFieldNameSchema,
533
- collected: z.array(udlRemainderCollectedSchema).optional(),
534
- inputKey: udlFieldNameSchema.optional(),
535
- onZero: z.enum(["refuse", "skip_steps"]),
536
- totalPath: instanceValuePathSchema,
537
- subtractPaths: z.array(instanceValuePathSchema).min(1).max(16).optional(),
538
- });
539
-
540
- type UdlCheckRequirementShape = {
541
- checkKind: string;
542
- family: z.infer<typeof udlProviderFamilyIdSchema>;
543
- maxAge?: string;
544
- statuses: string[];
545
- subjectField: string;
546
- };
547
-
548
- const udlCheckRequirementVariants = udlCheckEvidenceProfiles.map((profile) =>
549
141
  z.strictObject({
550
- checkKind: z.literal(profile.checkKind),
551
- family: z.literal(profile.family),
552
- maxAge: nonEmptyTextSchema.optional(),
553
- statuses: z.array(z.enum(profile.statuses)).min(1),
554
- subjectField: udlFieldNameSchema,
142
+ target: name,
143
+ op: z.literal("ratio"),
144
+ amount: value,
145
+ numerator: value,
146
+ denominator: value,
147
+ rounding: z.literal("floor"),
555
148
  }),
556
- ) as unknown as readonly [
557
- z.ZodType<UdlCheckRequirementShape>,
558
- z.ZodType<UdlCheckRequirementShape>,
559
- ...z.ZodType<UdlCheckRequirementShape>[],
560
- ];
561
-
562
- const udlCheckRequirementSchema = z.union(udlCheckRequirementVariants);
563
-
564
- const udlDialSchema = z.discriminatedUnion("kind", [
149
+ z.strictObject({ target: name, op: z.literal("sum"), values }),
565
150
  z.strictObject({
566
- field: udlFieldNameSchema,
567
- key: udlSnakeCaseSchema,
568
- kind: z.literal("window"),
569
- maxOffset: nonEmptyTextSchema.optional(),
570
- minOffset: nonEmptyTextSchema.optional(),
571
- summary: nonEmptyTextSchema,
572
- title: nonEmptyTextSchema,
151
+ target: name,
152
+ op: z.literal("subtract"),
153
+ base: value,
154
+ subtract: values,
573
155
  }),
574
156
  z.strictObject({
575
- action: udlActionNameSchema,
576
- key: udlSnakeCaseSchema,
577
- kind: z.literal("decision_deadline_ms"),
578
- maxMs: z.number().int().positive().max(15_000).optional(),
579
- minMs: z.number().int().positive().max(15_000).optional(),
580
- summary: nonEmptyTextSchema,
581
- title: nonEmptyTextSchema,
157
+ target: name,
158
+ op: z.literal("rate"),
159
+ base: value,
160
+ bps: value,
161
+ rounding: z.literal("floor"),
582
162
  }),
163
+ z.strictObject({ target: name, op: z.literal("minimum"), values }),
583
164
  z.strictObject({
584
- key: udlSnakeCaseSchema,
585
- kind: z.literal("reconcile_tolerance"),
586
- /** Ceiling on the minor units any reconcile may forgive under this dial. */
587
- maxMinorUnits: z.number().int().positive().max(1_000_000),
588
- summary: nonEmptyTextSchema,
589
- title: nonEmptyTextSchema,
165
+ target: name,
166
+ op: z.literal("multiply"),
167
+ amount: value,
168
+ units: value,
590
169
  }),
591
170
  z.strictObject({
592
- key: udlSnakeCaseSchema,
593
- kind: z.literal("unwind_penalty"),
594
- summary: nonEmptyTextSchema,
595
- title: nonEmptyTextSchema,
171
+ target: name,
172
+ op: z.literal("divide"),
173
+ amount: value,
174
+ divisor: value,
175
+ rounding: z.literal("floor"),
176
+ }),
177
+ z.strictObject({
178
+ target: name,
179
+ op: z.literal("shift"),
180
+ date: value,
181
+ milliseconds: value,
182
+ direction: z.enum(["before", "after"]),
596
183
  }),
597
184
  ]);
598
185
 
599
- // A same-instance conservation law: the piece fields (money, minor units)
600
- // must sum exactly to the total field; admission refuses a create whose
601
- // pieces diverge.
602
- // A composition-level dial. Instrument dials tune one instrument's frozen slots;
603
- // this one is a property of the whole product, so it hangs off the document.
604
- // `confirmation_threshold` carries minor units of the kernel currency: a
605
- // money-moving tool call whose declared money inputs sum below the configured
606
- // value skips the explicit confirmation argument.
607
- const udlCompositionDialSchema = z.strictObject({
608
- key: udlSnakeCaseSchema,
609
- kind: z.literal("confirmation_threshold"),
610
- maxMinor: z.number().int().positive().max(1_000_000_000_000).optional(),
611
- summary: nonEmptyTextSchema,
612
- title: nonEmptyTextSchema,
613
- });
614
-
615
- const udlPartitionSchema = z.strictObject({
616
- pieceFields: z.array(udlFieldNameSchema).min(2),
617
- totalField: udlFieldNameSchema,
618
- });
619
-
620
- const udlDerivedAmountSchema = z.strictObject({
621
- field: udlFieldNameSchema,
622
- rounding: z.literal("floor"),
623
- rule: z.discriminatedUnion("kind", [
624
- z.strictObject({
625
- bps: z.union([z.number().int().min(1).max(9_999), udlStoredFieldSchema]),
626
- kind: z.literal("percentage_of"),
627
- }),
628
- z.strictObject({
629
- kind: z.literal("minimum"),
630
- capField: udlFieldNameSchema,
631
- }),
632
- ]),
633
- sourceField: udlFieldNameSchema,
634
- });
635
-
636
- const udlFeeLeafRuleSchema = z.discriminatedUnion("kind", [
186
+ export const udlRequirementSchema = z.discriminatedUnion("kind", [
637
187
  z.strictObject({
638
- bps: z.number().int().min(1).max(9_999),
639
- kind: z.literal("bps"),
188
+ kind: z.literal("hours"),
189
+ at: path,
190
+ start: integer.min(0).max(23),
191
+ end: integer.min(0).max(23),
192
+ timezone: text,
640
193
  }),
641
194
  z.strictObject({
642
- currencyField: udlFieldNameSchema,
643
- field: udlFieldNameSchema,
644
- kind: z.literal("exact"),
195
+ kind: z.literal("compare"),
196
+ left: value,
197
+ operator: z.enum(["==", "!=", "<", "<=", ">", ">="]),
198
+ right: value,
645
199
  }),
646
- ]);
647
-
648
- const nonNegativeDecimalIntegerSchema = z
649
- .string()
650
- .regex(/^(0|[1-9][0-9]*)$/, "must be a nonnegative decimal integer");
651
-
652
- const udlFeeRuleSchema = z.strictObject({
653
- amountField: udlFieldNameSchema,
654
- baseField: udlFieldNameSchema,
655
- bearerField: udlFieldNameSchema,
656
- position: z.enum(["carved", "on_top"]),
657
- rule: z.discriminatedUnion("kind", [
658
- ...udlFeeLeafRuleSchema.options,
659
- z.strictObject({
660
- kind: z.literal("tiered"),
661
- tiers: z
662
- .array(
663
- z.strictObject({
664
- fromInclusive: nonNegativeDecimalIntegerSchema,
665
- rule: udlFeeLeafRuleSchema,
666
- toExclusive: nonNegativeDecimalIntegerSchema.optional(),
667
- }),
668
- )
669
- .min(1)
670
- .max(16),
671
- }),
672
- ]),
673
- });
674
-
675
- const udlDecidedAmountSchema = z.strictObject({
676
- boundField: udlFieldNameSchema,
677
- field: udlFieldNameSchema,
678
- remainderAction: udlActionNameSchema,
679
- });
680
-
681
- const udlEffectRowSchema = z.strictObject({
682
- signature: nonEmptyTextSchema,
683
- source: nonEmptyTextSchema,
684
- });
685
-
686
- const udlNotifyEffectSchema = z.strictObject({
687
- channel: udlSnakeCaseSchema,
688
- role: udlSnakeCaseSchema,
689
- signature: nonEmptyTextSchema,
690
- source: nonEmptyTextSchema,
691
- });
692
-
693
- const udlEffectsShape = {
694
- decides: z.array(udlEffectRowSchema).min(1).optional(),
695
- holds: z.array(udlEffectRowSchema).min(1).optional(),
696
- moves: z.array(udlEffectRowSchema).min(1).optional(),
697
- notifies: z.array(udlNotifyEffectSchema).min(1).optional(),
698
- reads: z.array(udlEffectRowSchema).min(1).optional(),
699
- schedules: z.array(udlEffectRowSchema).min(1).optional(),
700
- } satisfies Record<UdlEffectKind, z.ZodType>;
701
- const udlEffectsSchema = z.strictObject(udlEffectsShape);
702
-
703
- export const udlPieceSchema = z.strictObject({
704
- amount: udlFieldNameSchema,
705
- id: udlSnakeCaseSchema,
706
- refund_to: udlFieldNameSchema,
707
- release_to: udlFieldNameSchema,
708
- });
709
-
710
- export const udlPiecePlanSchema = z.strictObject({
711
- fund_order: z.array(udlSnakeCaseSchema),
712
- id: udlSnakeCaseSchema,
713
- pieces: z.array(udlPieceSchema).min(1).max(256),
714
- refund_order: z.array(udlSnakeCaseSchema),
715
- release_order: z.array(udlSnakeCaseSchema),
716
- total: udlFieldNameSchema,
717
- unfund_order: z.array(udlSnakeCaseSchema),
718
- });
719
-
720
- export const udlPieceStageStageSchema = z.enum([
721
- "fund",
722
- "release",
723
- "refund",
724
- "unfund",
725
- ]);
726
-
727
- export const udlPieceStageSchema = z.strictObject({
728
- plan: udlSnakeCaseSchema,
729
- stage: udlPieceStageStageSchema,
730
- });
731
-
732
- export const udlCallSchema = z.strictObject({
733
- action: z
734
- .string()
735
- .regex(
736
- /^[a-z][a-z0-9_]*\.[a-z][a-z0-9_]*$/,
737
- "must name an action as library_id.action_id",
738
- ),
739
- bind: z.record(udlFieldNameSchema, z.string()),
740
- id: udlSnakeCaseSchema,
741
- });
742
-
743
- export const udlPrivateParameterKindSchema = z.enum([
744
- "account",
745
- "instance",
746
- "money",
747
- "piece",
748
- "text",
749
- ]);
750
-
751
- export const udlPrivateParameterSchema = z.strictObject({
752
- currency: z.string().optional(),
753
- kind: udlPrivateParameterKindSchema,
754
- });
755
-
756
- export const udlPrivateLeafSchema = z.strictObject({
757
- bind: z.record(fieldPathSchema, z.string()),
758
- capture: stringMapSchema.optional(),
759
- effects: z
760
- .array(
761
- z.strictObject({
762
- kind: z.enum(udlEffectKinds),
763
- signature: nonEmptyTextSchema,
764
- }),
765
- )
766
- .min(1, "must declare at least one effect"),
767
- evidence: nonEmptyTextSchema,
768
- id: udlSnakeCaseSchema,
769
- operation: udlKernelOperationSchema,
770
- });
771
-
772
- export const udlPrivateActionSchema = z.strictObject({
773
- approval: z.enum(["inherit", "independent"]),
774
- calls: z.array(udlCallSchema),
775
- leaves: z.array(udlPrivateLeafSchema),
776
- order: z.array(udlSnakeCaseSchema),
777
- parameters: z.record(udlFieldNameSchema, udlPrivateParameterSchema),
778
- principal: z.enum(["api_key", "user_session"]),
779
- recovery: z.enum(["local", "external"]),
780
- });
781
-
782
- export const udlActionLibraryModuleSchema = z.strictObject({
783
- actionOrder: z.array(udlSnakeCaseSchema),
784
- actions: z.record(udlSnakeCaseSchema, udlPrivateActionSchema),
785
- });
786
-
787
- export const udlActionLibrarySchema = z.record(
788
- udlSnakeCaseSchema,
789
- udlActionLibraryModuleSchema,
790
- );
791
-
792
- const templateParametersSchema = z.record(
793
- udlFieldNameSchema,
794
- z.union([z.string(), z.number().int(), z.boolean()]),
795
- );
796
-
797
- const udlAllocationBucketSchema = z.strictObject({
798
- key: z.enum(["principal", "profit", "cost", "fine"]),
799
- source: z.union([
800
- z.strictObject({
801
- from: z.literal("slice"),
802
- amountField: udlFieldNameSchema,
803
- destinationField: udlFieldNameSchema,
804
- }),
805
- z.strictObject({
806
- from: z.literal("children"),
807
- instrumentId: udlInstrumentIdSchema,
808
- refField: udlFieldNameSchema,
809
- statuses: z.array(udlSnakeCaseSchema).min(1),
810
- amountField: udlFieldNameSchema,
811
- destinationField: udlFieldNameSchema,
812
- }),
813
- z.strictObject({
814
- from: z.literal("children"),
815
- template: udlSnakeCaseSchema,
816
- parameters: templateParametersSchema,
817
- refField: udlFieldNameSchema,
818
- statuses: z.array(udlSnakeCaseSchema).min(1),
819
- amountField: udlFieldNameSchema,
820
- destinationField: udlFieldNameSchema,
821
- }),
822
- ]),
823
- });
824
- const udlAllocationSchema = z.strictObject({
825
- sliceInstrumentId: udlInstrumentIdSchema,
826
- sliceRefField: udlFieldNameSchema,
827
- sliceStatuses: z.array(udlSnakeCaseSchema).min(1),
828
- dueField: udlFieldNameSchema,
829
- positionField: udlFieldNameSchema,
830
- earningRuleField: udlFieldNameSchema,
831
- buckets: z.array(udlAllocationBucketSchema).min(2).max(4),
832
- });
833
- const udlAllocateSchema = z.union([
834
200
  z.strictObject({
835
- refField: udlFieldNameSchema.optional(),
836
- mode: z.literal("refund"),
837
- action: udlActionNameSchema.optional(),
838
- assessmentField: udlFieldNameSchema.optional(),
839
- capture: udlFieldNameSchema,
201
+ kind: z.literal("state"),
202
+ reference: path,
203
+ states: z.array(name).min(1).max(64),
840
204
  }),
841
205
  z.strictObject({
842
- refField: udlFieldNameSchema,
843
- mode: z.literal("payment"),
844
- assessment: z.literal("self").optional(),
845
- amountField: udlFieldNameSchema.optional(),
846
- sourceAccountField: udlFieldNameSchema,
847
- paymentIdentityField: udlFieldNameSchema,
848
- capture: udlFieldNameSchema,
206
+ kind: z.literal("unique"),
207
+ namespace: name,
208
+ fields: z.array(path).min(1).max(8),
849
209
  }),
850
210
  z.strictObject({
851
- refField: udlFieldNameSchema.optional(),
852
- mode: z.literal("payoff"),
853
- amountField: udlFieldNameSchema.optional(),
854
- sourceAccountField: udlFieldNameSchema,
855
- paymentIdentityField: udlFieldNameSchema,
856
- capture: udlFieldNameSchema,
211
+ kind: z.literal("aggregate"),
212
+ selection,
213
+ measure: z.union([z.literal("count"), z.strictObject({ sum: path })]),
214
+ operator: z.enum(["==", "<=", ">=", "<", ">"]),
215
+ value,
857
216
  }),
858
217
  z.strictObject({
859
- refField: udlFieldNameSchema.optional(),
860
- mode: z.literal("write_off"),
861
- capture: udlFieldNameSchema,
218
+ kind: z.literal("approval"),
219
+ target: path.default("self"),
220
+ party: name,
221
+ action: name.optional(),
222
+ decision: z.enum(["approved", "declined"]),
223
+ }),
224
+ z.strictObject({
225
+ kind: z.literal("evidence"),
226
+ subject: path,
227
+ family: name,
228
+ check: name,
229
+ result: name,
230
+ maxAge: integer.positive(),
862
231
  }),
863
232
  ]);
864
- const udlContributionsSchema = z.strictObject({
865
- field: udlFieldNameSchema,
866
- amountKey: udlFieldNameSchema,
867
- accountKey: udlFieldNameSchema,
868
- totalField: udlFieldNameSchema,
869
- });
870
-
871
- // These clauses are opt-in. Absent clauses never add defaults to older documents.
872
- const udlFundingSchema = z.strictObject({
873
- obligationField: udlFieldNameSchema,
874
- ticketInstrumentId: udlInstrumentIdSchema,
875
- ticketRefField: udlFieldNameSchema,
876
- ticketAmountField: udlFieldNameSchema,
877
- ticketInvestorField: udlFieldNameSchema,
878
- ticketAccountField: udlFieldNameSchema,
879
- ticketStatus: udlSnakeCaseSchema,
880
- collectAction: udlActionNameSchema,
881
- principalField: udlFieldNameSchema,
882
- sourceAccountPath: instanceValuePathSchema,
883
- destinationAccountField: udlFieldNameSchema,
884
- terms: z.record(udlFieldNameSchema, udlFieldNameSchema),
885
- capture: udlFieldNameSchema,
886
- });
887
- const udlReceiptDistributionSchema = z.strictObject({
888
- roundField: udlFieldNameSchema,
889
- snapshotRef: udlFieldNameSchema,
890
- receiptField: udlFieldNameSchema,
891
- receiptPath: instanceValuePathSchema,
892
- mode: z.enum(["cash", "loss"]),
893
- feeBps: z.number().int().min(0).max(10000),
894
- vatBps: z.number().int().min(0).max(10000),
895
- feeAccountField: udlFieldNameSchema,
896
- taxAccountField: udlFieldNameSchema,
897
- residualAccountField: udlFieldNameSchema,
898
- capture: udlFieldNameSchema,
899
- });
900
-
901
- const udlRequestAuthoritySchema = z.strictObject({
902
- instrumentField: udlFieldNameSchema,
903
- instanceField: udlFieldNameSchema,
904
- actionField: udlFieldNameSchema,
905
- inputField: udlFieldNameSchema,
906
- digestField: udlFieldNameSchema,
907
- roleField: udlFieldNameSchema,
908
- party: udlPartyRoleSchema,
909
- expiresField: udlFieldNameSchema,
910
- });
911
233
 
912
- const udlCascadeEntrySchema = z.union([
234
+ export const udlKernelOperationSchema = z.enum([
235
+ "internal_transfer.create",
236
+ "internal_transfer.reserve",
237
+ "internal_transfer.post",
238
+ "internal_transfer.void",
239
+ ]);
240
+ export const udlMoveSchema = z.discriminatedUnion("operation", [
913
241
  z.strictObject({
914
- instrumentId: udlInstrumentIdSchema,
915
- action: udlActionNameSchema,
916
- inputField: udlFieldNameSchema,
242
+ key: name,
243
+ operation: z.literal("internal_transfer.create"),
244
+ capture: name.optional(),
245
+ amount: value,
246
+ from: path,
247
+ to: path,
917
248
  }),
918
249
  z.strictObject({
919
- instrumentId: udlInstrumentIdSchema,
920
- action: udlActionNameSchema,
921
- refField: udlFieldNameSchema,
922
- statuses: z.array(udlSnakeCaseSchema).min(1),
250
+ key: name,
251
+ operation: z.literal("internal_transfer.reserve"),
252
+ amount: value,
253
+ from: path,
254
+ to: path,
255
+ capture: name,
923
256
  }),
924
- ]);
925
-
926
- const udlActionShape = {
927
- requestAuthority: udlRequestAuthoritySchema.optional(),
928
- funding: udlFundingSchema.optional(),
929
- receiptDistribution: udlReceiptDistributionSchema.optional(),
930
- requiresAllocation: z
931
- .strictObject({
932
- refField: udlFieldNameSchema.optional(),
933
- slice: z.union([z.literal("self"), udlStoredFieldSchema]),
934
- buckets: z
935
- .array(z.enum(["principal", "profit", "cost", "fine"]))
936
- .min(1)
937
- .max(4),
938
- check: z.enum(["settled", "outstanding"]),
939
- })
940
- .optional(),
941
- unique: z
942
- .strictObject({
943
- namespace: udlSnakeCaseSchema,
944
- byFields: z.array(udlFieldNameSchema).min(1).max(8),
945
- })
946
- .optional(),
947
- requiresInput: z
948
- .record(udlFieldNameSchema, instanceValuePathSchema)
949
- .optional(),
950
- engineOwned: z.literal(true).optional(),
951
- captureEngine: z
952
- .record(udlFieldNameSchema, z.enum(["operationId"]))
953
- .optional(),
954
- allocate: udlAllocateSchema.optional(),
955
- contributionStage: z
956
- .strictObject({
957
- stage: z.enum(["fund", "refund"]),
958
- accountPath: instanceValuePathSchema,
959
- })
960
- .optional(),
961
- transitionsRefs: z
962
- .array(
963
- z.strictObject({
964
- field: udlFieldNameSchema,
965
- action: udlActionNameSchema,
966
- }),
967
- )
968
- .min(1)
969
- .max(16)
970
- .optional(),
971
- cascade: z.array(udlCascadeEntrySchema).min(1).max(8).optional(),
972
- agentDescription: udlAgentDescriptionSchema.optional(),
973
- calls: z.array(udlCallSchema).min(1).optional(),
974
- captureInput: z.record(udlFieldNameSchema, udlFieldNameSchema).optional(),
975
- /** Names the quoting action whose offer this action spends. */
976
- commit: udlActionNameSchema.optional(),
977
- decidedAmount: udlDecidedAmountSchema.optional(),
978
- deadline: udlDeadlineSchema.optional(),
979
- decision: udlDecisionSchema.optional(),
980
- distribute: udlDistributeSchema.optional(),
981
- description: nonEmptyTextSchema.optional(),
982
- due: udlDueSchema.optional(),
983
- earnable: z.boolean().optional(),
984
- effects: udlEffectsSchema.optional(),
985
- eventName: z
986
- .string()
987
- .regex(eventNamePattern)
988
- .meta({ "x-udl-reference": "instrument_event" })
989
- .optional(),
990
- examples: z.array(udlExampleSchema).min(1).optional(),
991
- input: jsonObjectSchema.optional(),
992
- moves: z.array(udlMoveSchema).default([]),
993
- payout: udlPayoutSchema.optional(),
994
- pieceStage: udlPieceStageSchema.optional(),
995
- port: udlPortSchema.optional(),
996
- quote: udlQuoteSchema.optional(),
997
- publicAction: udlPublicActionSchema
998
- .optional()
999
- .describe(
1000
- "Author-approved public action name; the containing action key remains the lifecycle and execution identity",
1001
- ),
1002
- principal: z.literal("user_session").optional(),
1003
- reconcile: z.array(udlReconcileSchema).min(1).optional(),
1004
- remainder: udlRemainderSchema.optional(),
1005
- requiresAggregate: z.array(udlAggregateConditionSchema).min(1).optional(),
1006
- requiresChecks: z.array(udlCheckRequirementSchema).optional(),
1007
- requiresDrainedAccount: z.strictObject({ path: fieldPathSchema }).optional(),
1008
- requiresExposure: z.array(udlExposureRequirementSchema).min(1).optional(),
1009
- requiresRefs: z.array(udlGateSchema).min(1).optional(),
1010
- sandboxFailurePoint: z.enum(["funding", "release"]).optional(),
1011
- setsAt: udlSetsAtSchema.optional(),
1012
- signedSum: udlSignedSumSchema.optional(),
1013
- steps: z.array(udlStepSchema).default([]),
1014
- summary: nonEmptyTextSchema,
1015
- updates: z.array(udlFieldNameSchema).min(1).optional(),
1016
- };
1017
- const udlActionSchema = z.strictObject(udlActionShape);
1018
-
1019
- const udlAggregateBaseShape = {
1020
- childInstrumentId: udlInstrumentIdSchema,
1021
- childRefField: udlFieldNameSchema,
1022
- childStatuses: z.array(udlSnakeCaseSchema).min(1),
1023
- parentField: udlFieldNameSchema,
1024
- };
1025
-
1026
- // Two measures, mutually exclusive by strictness: a sum cap over a child money
1027
- // field, or a count cap (optionally windowed to the rolling `days` ending at
1028
- // the child's own as-written date-time value).
1029
- const udlAggregateSchema = z.union([
1030
257
  z.strictObject({
1031
- ...udlAggregateBaseShape,
1032
- childField: udlFieldNameSchema,
258
+ key: name,
259
+ operation: z.literal("internal_transfer.post"),
260
+ capture: name.optional(),
261
+ transfer: path,
1033
262
  }),
1034
263
  z.strictObject({
1035
- ...udlAggregateBaseShape,
1036
- count: z.literal(true),
1037
- window: z
1038
- .strictObject({
1039
- field: udlFieldNameSchema,
1040
- days: z.number().int().min(1).max(3650),
1041
- })
1042
- .optional(),
264
+ key: name,
265
+ operation: z.literal("internal_transfer.void"),
266
+ capture: name.optional(),
267
+ transfer: path,
1043
268
  }),
1044
269
  ]);
1045
-
1046
- const udlInstrumentShape = {
1047
- templateBinding: z
1048
- .strictObject({
1049
- id: udlSnakeCaseSchema,
1050
- parameters: templateParametersSchema,
1051
- })
1052
- .optional(),
1053
- allocation: udlAllocationSchema.optional(),
1054
- contributions: udlContributionsSchema.optional(),
1055
- dateOrder: z
270
+ const clock = z.strictObject({ at: path, offset: integer.optional() });
271
+ export const udlActionSchema = z.strictObject({
272
+ summary: text,
273
+ publicAction: name.optional(),
274
+ event: text,
275
+ actor: z.union([
276
+ z.literal("caller"),
277
+ z.literal("clock"),
278
+ z.strictObject({ party: name }),
279
+ z.strictObject({ parent: instrumentId }),
280
+ ]),
281
+ input: z.array(udlFieldSchema).max(128),
282
+ requires: z.array(udlRequirementSchema).max(128),
283
+ due: clock.optional(),
284
+ deadline: clock.optional(),
285
+ set: z.record(name, value).optional(),
286
+ calculate: z.array(udlCalculationSchema).max(128).optional(),
287
+ moves: z.array(udlMoveSchema).max(256),
288
+ invoke: z
1056
289
  .array(
1057
- z.strictObject({
1058
- beforeField: udlFieldNameSchema,
1059
- afterField: udlFieldNameSchema,
1060
- operator: z.enum(["<", "<="]),
1061
- }),
290
+ z.union([
291
+ z.strictObject({
292
+ instrument: instrumentId,
293
+ action: z.literal("create"),
294
+ input: z.record(name, value),
295
+ }),
296
+ z.strictObject({
297
+ reference: path,
298
+ action: name,
299
+ input: z.record(name, value),
300
+ }),
301
+ z.strictObject({
302
+ selection,
303
+ action: name,
304
+ input: z.record(name, value),
305
+ }),
306
+ ]),
1062
307
  )
1063
- .min(1)
1064
308
  .max(16)
1065
309
  .optional(),
1066
- actionLibrary: udlActionLibrarySchema.optional(),
1067
- actionOrder: z.array(udlActionNameSchema).min(1),
1068
- agentDescription: udlAgentDescriptionSchema.optional(),
1069
- aggregateInvariants: z.array(udlAggregateSchema).min(1).optional(),
1070
- callerParkedStates: z
1071
- .record(udlSnakeCaseSchema, nonEmptyTextSchema)
310
+ approval: z
311
+ .strictObject({
312
+ target: path,
313
+ action: name,
314
+ party: name,
315
+ expires: path,
316
+ input: z.record(name, value),
317
+ decision: z.enum(["approved", "declined"]),
318
+ })
1072
319
  .optional(),
1073
- description: nonEmptyTextSchema.optional(),
1074
- dials: z.array(udlDialSchema).optional(),
1075
- distinctParties: z.literal(true).optional(),
1076
- derivedAmounts: z.array(udlDerivedAmountSchema).min(1).max(64).optional(),
1077
- feeRules: z.array(udlFeeRuleSchema).min(1).max(4).optional(),
1078
- fields: z.record(udlFieldNameSchema, jsonObjectSchema),
1079
- id: udlInstrumentIdSchema,
1080
- idPrefix: z
1081
- .string()
1082
- .regex(idPrefixPattern, "must contain 2 to 8 lowercase letters"),
320
+ });
321
+ export const udlLifecycleSchema = z.strictObject({
322
+ states: z.array(name).min(1).max(64),
323
+ initial: name,
324
+ transitions: z.record(
325
+ name,
326
+ z.strictObject({ from: z.array(name).min(1).max(64), to: name }),
327
+ ),
328
+ });
329
+ export const udlInstrumentSchema = z.strictObject({
330
+ id: instrumentId,
331
+ title: text,
332
+ summary: text,
333
+ fields: z.array(udlFieldSchema).max(256),
334
+ calculate: z.array(udlCalculationSchema).max(128),
1083
335
  lifecycle: udlLifecycleSchema,
1084
- nav: z.array(nonEmptyTextSchema).min(1).optional(),
1085
- parties: z.record(udlPartyRoleSchema, udlFieldNameSchema).optional(),
1086
- partitions: z.array(udlPartitionSchema).min(1).optional(),
1087
- piecePlan: udlPiecePlanSchema.optional(),
1088
- required: z.array(udlFieldNameSchema),
1089
- subject: udlInstrumentSubjectSchema.optional(),
1090
- summary: nonEmptyTextSchema,
1091
- surfaceVisibility: z.enum(["internal", "public", "system"]).optional(),
1092
- templateId: udlSnakeCaseSchema.optional(),
1093
- title: nonEmptyTextSchema,
1094
- update: udlUpdatePolicySchema.optional(),
1095
- actions: z.record(udlActionNameSchema, udlActionSchema),
1096
- };
1097
- const udlInstrumentSchema = z.strictObject(udlInstrumentShape);
1098
-
1099
- type UdlActionClauseTarget = keyof typeof udlActionShape;
1100
- type UdlInstrumentClauseTarget = keyof typeof udlInstrumentShape;
1101
- type UdlActionNestedClauseTarget = `effects.${keyof typeof udlEffectsShape}`;
1102
-
1103
- export type UdlClauseCardinality = "one" | "many";
1104
-
1105
- export interface UdlClauseEffect {
1106
- readonly kind: UdlEffectKind;
1107
- readonly per: "clause" | "element";
1108
- readonly signature:
1109
- | { readonly fixed: string }
1110
- | { readonly fromField: string }
1111
- | { readonly movementClass: true };
1112
- }
1113
-
1114
- interface UdlClauseVocabularyMetadata {
1115
- readonly cardinality?: UdlClauseCardinality;
1116
- readonly effects?: readonly UdlClauseEffect[];
1117
- readonly linearOutputs?: readonly string[];
1118
- readonly linearSink?: true;
1119
- readonly literalKeys?: true;
1120
- readonly spelling: string;
1121
- }
1122
-
1123
- export type UdlClauseVocabularyEntry = UdlClauseVocabularyMetadata &
1124
- (
1125
- | {
1126
- readonly scope: "action";
1127
- readonly target: UdlActionClauseTarget | UdlActionNestedClauseTarget;
1128
- }
1129
- | {
1130
- readonly scope: "instrument";
1131
- readonly target: UdlInstrumentClauseTarget;
1132
- }
1133
- );
1134
-
1135
- export const udlClauseVocabulary = [
1136
- {
1137
- scope: "action",
1138
- spelling: "funding",
1139
- target: "funding",
1140
- cardinality: "one",
1141
- effects: [
1142
- {
1143
- kind: "moves",
1144
- per: "clause",
1145
- signature: { fixed: "transfer.internal" },
1146
- },
1147
- ],
1148
- },
1149
- {
1150
- scope: "action",
1151
- spelling: "receipt distribution",
1152
- target: "receiptDistribution",
1153
- cardinality: "one",
1154
- effects: [
1155
- { kind: "decides", per: "clause", signature: { fixed: "allocation" } },
1156
- { kind: "moves", per: "clause", signature: { fixed: "allocation" } },
1157
- ],
1158
- },
1159
- {
1160
- cardinality: "one",
1161
- scope: "action",
1162
- spelling: "requires allocation",
1163
- target: "requiresAllocation",
1164
- effects: [
1165
- { kind: "decides", per: "clause", signature: { fixed: "allocation" } },
1166
- ],
1167
- },
1168
- {
1169
- cardinality: "one",
1170
- scope: "instrument",
1171
- spelling: "allocation",
1172
- target: "allocation",
1173
- },
1174
- {
1175
- cardinality: "one",
1176
- scope: "instrument",
1177
- spelling: "contributions",
1178
- target: "contributions",
1179
- },
1180
- {
1181
- cardinality: "one",
1182
- scope: "action",
1183
- spelling: "allocate",
1184
- target: "allocate",
1185
- effects: [
1186
- { kind: "decides", per: "clause", signature: { fixed: "allocation" } },
1187
- { kind: "moves", per: "clause", signature: { fixed: "allocation" } },
1188
- ],
1189
- },
1190
- {
1191
- cardinality: "one",
1192
- scope: "action",
1193
- spelling: "contribution stage",
1194
- target: "contributionStage",
1195
- effects: [
1196
- {
1197
- kind: "moves",
1198
- per: "clause",
1199
- signature: { fixed: "transfer.internal" },
1200
- },
1201
- ],
1202
- },
1203
- {
1204
- cardinality: "many",
1205
- scope: "instrument",
1206
- spelling: "date order",
1207
- target: "dateOrder",
1208
- },
1209
- {
1210
- cardinality: "one",
1211
- scope: "action",
1212
- spelling: "unique",
1213
- target: "unique",
1214
- effects: [
1215
- {
1216
- kind: "decides",
1217
- per: "clause",
1218
- signature: { fixed: "subject_unique" },
1219
- },
1220
- ],
1221
- },
1222
- {
1223
- cardinality: "many",
1224
- scope: "action",
1225
- spelling: "transitions refs",
1226
- target: "transitionsRefs",
1227
- effects: [
1228
- {
1229
- kind: "decides",
1230
- per: "element",
1231
- signature: { fixed: "referenced_transition" },
1232
- },
1233
- ],
1234
- },
1235
- {
1236
- cardinality: "many",
1237
- scope: "action",
1238
- spelling: "cascade",
1239
- target: "cascade",
1240
- effects: [
1241
- {
1242
- kind: "decides",
1243
- per: "element",
1244
- signature: { fixed: "cascade_transition" },
1245
- },
1246
- ],
1247
- },
1248
- {
1249
- cardinality: "one",
1250
- literalKeys: true,
1251
- scope: "instrument",
1252
- spelling: "action library",
1253
- target: "actionLibrary",
1254
- },
1255
- {
1256
- cardinality: "one",
1257
- scope: "action",
1258
- spelling: "agent description",
1259
- target: "agentDescription",
1260
- },
1261
- {
1262
- cardinality: "many",
1263
- literalKeys: true,
1264
- scope: "action",
1265
- spelling: "calls",
1266
- target: "calls",
1267
- },
1268
- {
1269
- cardinality: "one",
1270
- scope: "action",
1271
- spelling: "requires input",
1272
- target: "requiresInput",
1273
- literalKeys: true,
1274
- },
1275
- {
1276
- cardinality: "one",
1277
- scope: "action",
1278
- spelling: "engine owned",
1279
- target: "engineOwned",
1280
- },
1281
- {
1282
- cardinality: "one",
1283
- scope: "action",
1284
- spelling: "capture engine",
1285
- target: "captureEngine",
1286
- literalKeys: true,
1287
- },
1288
- {
1289
- cardinality: "one",
1290
- scope: "action",
1291
- spelling: "capture input",
1292
- target: "captureInput",
1293
- },
1294
- {
1295
- cardinality: "one",
1296
- // The committing action consumes the quote through its priced moves.
1297
- // An extra row here would bill the same movement twice.
1298
- effects: [],
1299
- scope: "action",
1300
- spelling: "commit",
1301
- target: "commit",
1302
- },
1303
- {
1304
- cardinality: "one",
1305
- effects: [
1306
- {
1307
- kind: "holds",
1308
- per: "clause",
1309
- signature: { fixed: "quote" },
1310
- },
1311
- {
1312
- kind: "schedules",
1313
- per: "clause",
1314
- signature: { fixed: "expiry" },
1315
- },
1316
- ],
1317
- linearOutputs: ["netRef"],
1318
- scope: "action",
1319
- spelling: "quote",
1320
- target: "quote",
1321
- },
1322
- {
1323
- cardinality: "one",
1324
- linearOutputs: ["field"],
1325
- scope: "action",
1326
- spelling: "decided amount",
1327
- target: "decidedAmount",
1328
- },
1329
- {
1330
- cardinality: "one",
1331
- effects: [
1332
- {
1333
- kind: "schedules",
1334
- per: "clause",
1335
- signature: { fixed: "deadline" },
1336
- },
1337
- ],
1338
- scope: "action",
1339
- spelling: "deadline",
1340
- target: "deadline",
1341
- },
1342
- {
1343
- cardinality: "one",
1344
- effects: [
1345
- {
1346
- kind: "decides",
1347
- per: "clause",
1348
- signature: { fromField: "capability" },
1349
- },
1350
- ],
1351
- scope: "action",
1352
- spelling: "decision",
1353
- target: "decision",
1354
- },
1355
- {
1356
- cardinality: "one",
1357
- linearOutputs: ["amountRef"],
1358
- scope: "action",
1359
- spelling: "computes distribute",
1360
- target: "distribute",
1361
- },
1362
- {
1363
- cardinality: "one",
1364
- scope: "action",
1365
- spelling: "description",
1366
- target: "description",
1367
- },
1368
- {
1369
- cardinality: "one",
1370
- effects: [
1371
- {
1372
- kind: "schedules",
1373
- per: "clause",
1374
- signature: { fixed: "due" },
1375
- },
1376
- ],
1377
- scope: "action",
1378
- spelling: "due",
1379
- target: "due",
1380
- },
1381
- {
1382
- cardinality: "one",
1383
- scope: "action",
1384
- spelling: "earnable",
1385
- target: "earnable",
1386
- },
1387
- {
1388
- cardinality: "one",
1389
- scope: "action",
1390
- spelling: "event name",
1391
- target: "eventName",
1392
- },
1393
- {
1394
- cardinality: "many",
1395
- scope: "action",
1396
- spelling: "examples",
1397
- target: "examples",
1398
- },
1399
- {
1400
- cardinality: "one",
1401
- scope: "action",
1402
- spelling: "input",
1403
- target: "input",
1404
- },
1405
- {
1406
- cardinality: "many",
1407
- effects: [
1408
- {
1409
- kind: "moves",
1410
- per: "element",
1411
- signature: { movementClass: true },
1412
- },
1413
- {
1414
- kind: "holds",
1415
- per: "element",
1416
- signature: { fixed: "reserve" },
1417
- },
1418
- ],
1419
- linearSink: true,
1420
- scope: "action",
1421
- spelling: "moves",
1422
- target: "moves",
1423
- },
1424
- {
1425
- cardinality: "one",
1426
- effects: [
1427
- {
1428
- kind: "moves",
1429
- per: "clause",
1430
- signature: { fixed: "payout.external" },
1431
- },
1432
- ],
1433
- linearSink: true,
1434
- scope: "action",
1435
- spelling: "payout",
1436
- target: "payout",
1437
- },
1438
- {
1439
- cardinality: "one",
1440
- literalKeys: true,
1441
- scope: "instrument",
1442
- spelling: "piece plan",
1443
- target: "piecePlan",
1444
- },
1445
- {
1446
- cardinality: "one",
1447
- literalKeys: true,
1448
- scope: "action",
1449
- spelling: "piece stage",
1450
- target: "pieceStage",
1451
- },
1452
- {
1453
- cardinality: "one",
1454
- effects: [
1455
- {
1456
- kind: "decides",
1457
- per: "clause",
1458
- signature: { fixed: "tenant_port" },
1459
- },
1460
- ],
1461
- scope: "action",
1462
- spelling: "port",
1463
- target: "port",
1464
- },
1465
- {
1466
- cardinality: "one",
1467
- scope: "action",
1468
- spelling: "principal",
1469
- target: "principal",
1470
- },
1471
- {
1472
- cardinality: "one",
1473
- scope: "action",
1474
- spelling: "public action",
1475
- target: "publicAction",
1476
- },
1477
- {
1478
- cardinality: "many",
1479
- effects: [
1480
- {
1481
- kind: "reads",
1482
- per: "element",
1483
- signature: { fixed: "reconcile" },
1484
- },
1485
- ],
1486
- scope: "action",
1487
- spelling: "reconcile",
1488
- target: "reconcile",
1489
- },
1490
- {
1491
- cardinality: "one",
1492
- linearOutputs: ["amountRef"],
1493
- scope: "action",
1494
- spelling: "computes remainder",
1495
- target: "remainder",
1496
- },
1497
- {
1498
- cardinality: "many",
1499
- effects: [
1500
- {
1501
- kind: "reads",
1502
- per: "clause",
1503
- signature: { fixed: "requires_aggregate" },
1504
- },
1505
- ],
1506
- scope: "action",
1507
- spelling: "requires aggregate",
1508
- target: "requiresAggregate",
1509
- },
1510
- {
1511
- cardinality: "many",
1512
- effects: [
1513
- {
1514
- kind: "reads",
1515
- per: "clause",
1516
- signature: { fixed: "requires_checks" },
1517
- },
1518
- ],
1519
- scope: "action",
1520
- spelling: "requires checks",
1521
- target: "requiresChecks",
1522
- },
1523
- {
1524
- cardinality: "one",
1525
- scope: "action",
1526
- spelling: "requires drained",
1527
- target: "requiresDrainedAccount",
1528
- },
1529
- {
1530
- cardinality: "many",
1531
- scope: "action",
1532
- spelling: "requires exposure",
1533
- target: "requiresExposure",
1534
- },
1535
- {
1536
- cardinality: "many",
1537
- effects: [
1538
- {
1539
- kind: "reads",
1540
- per: "clause",
1541
- signature: { fixed: "requires_refs" },
1542
- },
1543
- ],
1544
- scope: "action",
1545
- spelling: "requires refs",
1546
- target: "requiresRefs",
1547
- },
1548
- {
1549
- cardinality: "one",
1550
- scope: "action",
1551
- spelling: "sandbox failure point",
1552
- target: "sandboxFailurePoint",
1553
- },
1554
- {
1555
- cardinality: "one",
1556
- scope: "action",
1557
- spelling: "sets at",
1558
- target: "setsAt",
1559
- },
1560
- {
1561
- cardinality: "one",
1562
- linearOutputs: ["amountRef"],
1563
- scope: "action",
1564
- spelling: "computes signed_sum",
1565
- target: "signedSum",
1566
- },
1567
- {
1568
- cardinality: "many",
1569
- linearSink: true,
1570
- scope: "action",
1571
- spelling: "steps",
1572
- target: "steps",
1573
- },
1574
- {
1575
- cardinality: "one",
1576
- scope: "action",
1577
- spelling: "summary",
1578
- target: "summary",
1579
- },
1580
- {
1581
- cardinality: "many",
1582
- scope: "action",
1583
- spelling: "updates",
1584
- target: "updates",
1585
- },
1586
- {
1587
- cardinality: "many",
1588
- effects: [
1589
- {
1590
- kind: "notifies",
1591
- per: "element",
1592
- signature: { fromField: "channel" },
1593
- },
1594
- ],
1595
- scope: "action",
1596
- spelling: "notify",
1597
- target: "effects.notifies",
1598
- },
1599
- {
1600
- cardinality: "one",
1601
- scope: "instrument",
1602
- spelling: "agent description",
1603
- target: "agentDescription",
1604
- },
1605
- {
1606
- cardinality: "many",
1607
- scope: "instrument",
1608
- spelling: "aggregate invariants",
1609
- target: "aggregateInvariants",
1610
- },
1611
- {
1612
- cardinality: "one",
1613
- scope: "instrument",
1614
- spelling: "caller parked states",
1615
- target: "callerParkedStates",
1616
- },
1617
- {
1618
- cardinality: "one",
1619
- scope: "instrument",
1620
- spelling: "description",
1621
- target: "description",
1622
- },
1623
- {
1624
- cardinality: "many",
1625
- scope: "instrument",
1626
- spelling: "dials",
1627
- target: "dials",
1628
- },
1629
- {
1630
- cardinality: "one",
1631
- scope: "instrument",
1632
- spelling: "distinct parties",
1633
- target: "distinctParties",
1634
- },
1635
- {
1636
- cardinality: "many",
1637
- scope: "instrument",
1638
- spelling: "computes derived",
1639
- target: "derivedAmounts",
1640
- },
1641
- {
1642
- cardinality: "many",
1643
- scope: "instrument",
1644
- spelling: "computes fees",
1645
- target: "feeRules",
1646
- },
1647
- {
1648
- cardinality: "one",
1649
- scope: "instrument",
1650
- spelling: "id prefix",
1651
- target: "idPrefix",
1652
- },
1653
- {
1654
- cardinality: "many",
1655
- scope: "instrument",
1656
- spelling: "nav",
1657
- target: "nav",
1658
- },
1659
- {
1660
- cardinality: "many",
1661
- scope: "instrument",
1662
- spelling: "partitions",
1663
- target: "partitions",
1664
- },
1665
- {
1666
- cardinality: "one",
1667
- scope: "instrument",
1668
- spelling: "subject",
1669
- target: "subject",
1670
- },
1671
- {
1672
- cardinality: "one",
1673
- scope: "instrument",
1674
- spelling: "summary",
1675
- target: "summary",
1676
- },
1677
- {
1678
- cardinality: "one",
1679
- scope: "instrument",
1680
- spelling: "surface visibility",
1681
- target: "surfaceVisibility",
1682
- },
1683
- {
1684
- cardinality: "one",
1685
- scope: "instrument",
1686
- spelling: "template binding",
1687
- target: "templateBinding",
1688
- },
1689
- {
1690
- cardinality: "one",
1691
- scope: "instrument",
1692
- spelling: "template id",
1693
- target: "templateId",
1694
- },
1695
- {
1696
- cardinality: "one",
1697
- scope: "instrument",
1698
- spelling: "title",
1699
- target: "title",
1700
- },
1701
- {
1702
- cardinality: "one",
1703
- scope: "instrument",
1704
- spelling: "update",
1705
- target: "update",
1706
- },
1707
- {
1708
- cardinality: "one",
1709
- effects: [],
1710
- scope: "action",
1711
- spelling: "request authority",
1712
- target: "requestAuthority",
1713
- },
1714
- ] as const satisfies readonly UdlClauseVocabularyEntry[];
1715
-
1716
- const udlDocumentShapeSchema = z.strictObject({
1717
- dials: z.array(udlCompositionDialSchema).min(1).optional(),
1718
- instruments: z.array(udlInstrumentSchema).min(1),
1719
- product: udlSnakeCaseSchema,
1720
- subjects: z.array(udlSubjectSchema),
1721
- title: nonEmptyTextSchema,
336
+ actions: z.record(name, udlActionSchema),
337
+ actionOrder: z.array(name).min(1).max(128),
338
+ invariants: z.array(udlRequirementSchema).max(128).optional(),
339
+ examples: z
340
+ .array(z.strictObject({ name: text, input: z.json() }))
341
+ .max(16)
342
+ .optional(),
343
+ });
344
+ export const udlDocumentSchema = z.strictObject({
1722
345
  udl: z.literal(UDL_FORMAT_VERSION),
1723
- version: z.number().int().positive(),
346
+ version: integer.positive(),
347
+ product: name,
348
+ title: text,
349
+ currency: z.literal("SAR"),
350
+ parties: z.record(name, udlPartySchema),
351
+ instruments: z.array(udlInstrumentSchema).min(1).max(256),
1724
352
  });
1725
353
 
1726
- type ParsedInstrument = z.infer<typeof udlInstrumentSchema>;
1727
-
1728
- const moneyPatterns = new Set(["^[1-9][0-9]{0,17}$", "^(0|[1-9][0-9]{0,17})$"]);
1729
-
1730
- function isMoneyField(
1731
- schema: Readonly<Record<string, unknown>> | undefined,
1732
- ): boolean {
1733
- return (
1734
- typeof schema?.pattern === "string" && moneyPatterns.has(schema.pattern)
1735
- );
1736
- }
1737
-
1738
- function referenceTargets(
1739
- schema: Readonly<Record<string, unknown>>,
1740
- instruments: readonly ParsedInstrument[],
1741
- ): readonly ParsedInstrument[] {
1742
- const prefix = referencePatternPrefix(schema);
1743
- return prefix
1744
- ? instruments.filter((instrument) => instrument.idPrefix === prefix)
1745
- : [];
1746
- }
1747
-
1748
- function declaredMoneyRefKeys(
1749
- instrument: ParsedInstrument,
1750
- ): ReadonlySet<string> {
1751
- return new Set([
1752
- ...Object.values(instrument.actions).flatMap((action) => [
1753
- ...(action.remainder
1754
- ? [
1755
- action.remainder.amountRef,
1756
- ...(action.remainder.accumulateRef
1757
- ? [action.remainder.accumulateRef]
1758
- : []),
1759
- ]
1760
- : []),
1761
- ...(action.signedSum
1762
- ? [
1763
- action.signedSum.amountRef,
1764
- ...action.signedSum.sources.map((source) => source.subtotalRef),
1765
- ]
1766
- : []),
1767
- ...(action.distribute ? [action.distribute.amountRef] : []),
1768
- ...(action.quote ? [action.quote.chargeRef, action.quote.netRef] : []),
1769
- ]),
1770
- ]);
1771
- }
1772
-
1773
- export const udlDocumentSchema = udlDocumentShapeSchema.superRefine(
1774
- (document, context) => {
1775
- document.instruments.forEach((instrument, instrumentIndex) => {
1776
- instrument.derivedAmounts?.forEach((amount, amountIndex) => {
1777
- const base = [
1778
- "instruments",
1779
- instrumentIndex,
1780
- "derivedAmounts",
1781
- amountIndex,
1782
- ] as const;
1783
- if (!isMoneyField(instrument.fields[amount.field])) {
1784
- context.addIssue({
1785
- code: "custom",
1786
- message: `derived amount target ${amount.field} must be a declared money field`,
1787
- path: [...base, "field"],
1788
- });
1789
- }
1790
- if (!isMoneyField(instrument.fields[amount.sourceField])) {
1791
- context.addIssue({
1792
- code: "custom",
1793
- message: `derived amount source ${amount.sourceField} must be a declared money field`,
1794
- path: [...base, "sourceField"],
1795
- });
1796
- }
1797
- if (amount.field === amount.sourceField) {
1798
- context.addIssue({
1799
- code: "custom",
1800
- message: "a derived amount cannot derive from itself",
1801
- path: [...base, "sourceField"],
1802
- });
1803
- }
1804
- });
1805
-
1806
- Object.entries(instrument.actions).forEach(([actionName, action]) => {
1807
- const distribute = action.distribute;
1808
- if (!distribute) return;
1809
- const base = [
1810
- "instruments",
1811
- instrumentIndex,
1812
- "actions",
1813
- actionName,
1814
- "distribute",
1815
- ] as const;
1816
- const refSchema = instrument.fields[distribute.refField];
1817
- const parents = refSchema
1818
- ? referenceTargets(refSchema, document.instruments)
1819
- : [];
1820
- if (parents.length !== 1) {
1821
- context.addIssue({
1822
- code: "custom",
1823
- message: `distribute refField ${distribute.refField} must identify exactly one parent instrument`,
1824
- path: [...base, "refField"],
1825
- });
1826
- }
1827
-
1828
- if (!isMoneyField(instrument.fields[distribute.weightField])) {
1829
- context.addIssue({
1830
- code: "custom",
1831
- message: `distribute weightField ${distribute.weightField} must be a declared money field`,
1832
- path: [...base, "weightField"],
1833
- });
1834
- }
1835
-
1836
- distribute.statuses.forEach((status, statusIndex) => {
1837
- if (instrument.lifecycle.states.includes(status)) return;
1838
- context.addIssue({
1839
- code: "custom",
1840
- message: `distribute status ${status} is not declared by ${instrument.id}`,
1841
- path: [...base, "statuses", statusIndex],
1842
- });
1843
- });
1844
-
1845
- const parent = parents[0];
1846
- if (!parent) return;
1847
- const poolMatch = /^(fields|refs)\.([a-z][A-Za-z0-9]*)$/.exec(
1848
- distribute.pool.path,
1849
- );
1850
- const root = poolMatch?.[1];
1851
- const key = poolMatch?.[2];
1852
- const poolDeclared =
1853
- root === "fields"
1854
- ? isMoneyField(parent.fields[key ?? ""])
1855
- : root === "refs"
1856
- ? declaredMoneyRefKeys(parent).has(key ?? "")
1857
- : false;
1858
- if (!poolDeclared) {
1859
- context.addIssue({
1860
- code: "custom",
1861
- message: `distribute pool ${distribute.pool.path} must be a declared money field or ref of ${parent.id}`,
1862
- path: [...base, "pool", "path"],
1863
- });
1864
- }
1865
- });
1866
- });
1867
- },
1868
- );
1869
-
1870
- export type UdlAllocation = z.infer<typeof udlAllocationSchema>;
1871
- export type UdlAllocate = z.infer<typeof udlAllocateSchema>;
1872
- export type UdlContributions = z.infer<typeof udlContributionsSchema>;
1873
-
1874
- export type UdlAggregate = z.infer<typeof udlAggregateSchema>;
1875
- export type UdlAggregateCondition = z.infer<typeof udlAggregateConditionSchema>;
1876
- export type UdlBinding = z.infer<typeof udlBindingSchema>;
1877
- export type UdlDeclaredValuePolicy = z.infer<
1878
- typeof udlDeclaredValuePolicySchema
1879
- >;
1880
- export type UdlDecision = z.infer<typeof udlDecisionSchema>;
1881
- export type UdlCompositionDial = z.infer<typeof udlCompositionDialSchema>;
1882
- export type UdlDial = z.infer<typeof udlDialSchema>;
1883
354
  export type UdlDocument = z.infer<typeof udlDocumentSchema>;
1884
- export type UdlDue = z.infer<typeof udlDueSchema>;
1885
- export type UdlEffects = z.infer<typeof udlEffectsSchema>;
1886
- export type UdlExample = z.infer<typeof udlExampleSchema>;
1887
- export type UdlDateComparison = z.infer<typeof udlDateComparisonSchema>;
1888
- export type UdlDateComparisonOperator = z.infer<
1889
- typeof udlDateComparisonOperatorSchema
1890
- >;
1891
- export type UdlGate = z.infer<typeof udlGateSchema>;
1892
- export type UdlKernelOperation = z.infer<typeof udlKernelOperationSchema>;
1893
- export type UdlLifecycle = z.infer<typeof udlLifecycleSchema>;
1894
- export type UdlLifecycleTransition = z.infer<
1895
- typeof udlLifecycleTransitionSchema
1896
- >;
1897
355
  export type UdlInstrument = z.infer<typeof udlInstrumentSchema>;
1898
- export type UdlInstrumentSubject = z.infer<typeof udlInstrumentSubjectSchema>;
1899
- export type UdlMove = z.infer<typeof udlMoveSchema>;
1900
- export type UdlPayout = z.infer<typeof udlPayoutSchema>;
1901
- export type UdlQuote = z.infer<typeof udlQuoteSchema>;
1902
- export type UdlProviderFamilyId = z.infer<typeof udlProviderFamilyIdSchema>;
1903
- export type UdlCheckRequirement = z.infer<typeof udlCheckRequirementSchema>;
1904
- export type UdlReconcile = z.infer<typeof udlReconcileSchema>;
1905
- export type UdlRemainder = z.infer<typeof udlRemainderSchema>;
1906
- export type UdlStep = z.infer<typeof udlStepSchema>;
1907
- export type UdlSubject = z.infer<typeof udlSubjectSchema>;
356
+ export type UdlField = z.infer<typeof udlFieldSchema>;
357
+ export type UdlParty = z.infer<typeof udlPartySchema>;
358
+ export type UdlValue = z.infer<typeof udlValueSchema>;
359
+ export type UdlCalculation = z.infer<typeof udlCalculationSchema>;
360
+ export type UdlRequirement = z.infer<typeof udlRequirementSchema>;
1908
361
  export type UdlAction = z.infer<typeof udlActionSchema>;
1909
- export type UdlPiece = z.infer<typeof udlPieceSchema>;
1910
- export type UdlPiecePlan = z.infer<typeof udlPiecePlanSchema>;
1911
- export type UdlPieceStage = z.infer<typeof udlPieceStageSchema>;
1912
- export type UdlPieceStageStage = z.infer<typeof udlPieceStageStageSchema>;
1913
- export type UdlCall = z.infer<typeof udlCallSchema>;
1914
- export type UdlPrivateParameterKind = z.infer<
1915
- typeof udlPrivateParameterKindSchema
1916
- >;
1917
- export type UdlPrivateParameter = z.infer<typeof udlPrivateParameterSchema>;
1918
- export type UdlPrivateLeaf = z.infer<typeof udlPrivateLeafSchema>;
1919
- export type UdlPrivateAction = z.infer<typeof udlPrivateActionSchema>;
1920
- export type UdlActionLibraryModule = z.infer<
1921
- typeof udlActionLibraryModuleSchema
1922
- >;
1923
- export type UdlActionLibrary = z.infer<typeof udlActionLibrarySchema>;
1924
- export type UdlCascadeEntry = z.infer<typeof udlCascadeEntrySchema>;
362
+ export type UdlMove = z.infer<typeof udlMoveSchema>;
363
+ export type UdlLifecycle = z.infer<typeof udlLifecycleSchema>;
364
+ export type UdlKernelOperation = z.infer<typeof udlKernelOperationSchema>;
365
+
366
+ export type UdlSelection = z.infer<typeof selection>;