@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/dist/evolution.js CHANGED
@@ -1,636 +1,32 @@
1
- import { UDL_LIMITS } from "./limits.js";
2
- import { deriveUdlActionEffects } from "./effects.js";
3
- import { udlClauseVocabulary } from "./schema.js";
4
- import { UdlError } from "./validation.js";
5
1
  import { issue } from "./diagnostics.js";
6
- /** Project an open .udl instrument into the evolution engine's exact semantic shape. */
7
- export function snapshotUdlInstrument(instrument) {
8
- const required = new Set(instrument.required);
9
- return {
10
- templateBinding: instrument.templateBinding ?? null,
11
- allocation: instrument.allocation ?? null,
12
- contributions: instrument.contributions ?? null,
13
- dateOrder: instrument.dateOrder ?? [],
14
- actionOrder: [...instrument.actionOrder],
15
- aggregateInvariants: (instrument.aggregateInvariants ?? []).map(aggregateInvariantKey),
16
- callerParkedStates: instrument.callerParkedStates ?? {},
17
- derivedAmounts: (instrument.derivedAmounts ?? []).map((amount) => amount.rule.kind === "minimum"
18
- ? `${amount.field}=min(${amount.sourceField},${amount.rule.capField})`
19
- : `${amount.field}=floor(${amount.sourceField}*${typeof amount.rule.bps === "number" ? amount.rule.bps : `fields.${amount.rule.bps.field}`}/10000)`),
20
- dials: instrument.dials ?? [],
21
- ...(instrument.distinctParties ? { distinctParties: true } : {}),
22
- ...(instrument.feeRules
23
- ? {
24
- feeRules: instrument.feeRules.map((fee) => ({
25
- ...fee,
26
- rule: fee.rule.kind === "tiered"
27
- ? {
28
- ...fee.rule,
29
- tiers: fee.rule.tiers.map((tier) => ({
30
- ...tier,
31
- rule: { ...tier.rule },
32
- })),
33
- }
34
- : { ...fee.rule },
35
- })),
36
- }
37
- : {}),
38
- fields: Object.fromEntries(Object.entries(instrument.fields).map(([field, schema]) => [
39
- field,
40
- { required: required.has(field), schema: withoutProse(schema) },
41
- ])),
42
- id: instrument.id,
43
- idPrefix: instrument.idPrefix,
44
- initial: instrument.lifecycle.initial,
45
- nav: instrument.nav ?? [],
46
- parties: compactStringRecord(instrument.parties),
47
- partitions: (instrument.partitions ?? []).map((partition) => `${partition.totalField} = ${[...partition.pieceFields].sort().join(" + ")}`),
48
- states: [...instrument.lifecycle.states],
49
- subjects: instrument.subject ? [...instrument.subject.kinds] : [],
50
- subjectExtensible: instrument.subject?.extensible ?? false,
51
- surfaceVisibility: instrument.surfaceVisibility ?? null,
52
- templateId: instrument.templateId ?? null,
53
- transitions: Object.fromEntries(Object.entries(instrument.lifecycle.transitions).map(([action, transition]) => [
54
- action,
55
- { from: [...transition.from], to: transition.to },
56
- ])),
57
- quotes: Object.fromEntries(Object.entries(instrument.actions)
58
- .filter(([, action]) => action.quote)
59
- .map(([name, action]) => [name, action.quote])),
60
- updateFields: instrument.update?.fields ?? [],
61
- updateExamples: instrument.update?.examples ?? null,
62
- updateStates: instrument.update?.states ?? [],
63
- actions: Object.fromEntries(instrument.actionOrder.map((action) => [
64
- action,
65
- snapshotUdlAction(instrument.actions[action]),
66
- ])),
67
- };
68
- }
69
- /**
70
- * Compare two product definitions under the append-only evolution law.
71
- *
72
- * Both documents must already have passed `validateUdl`. The diff walks
73
- * straight into `stableStringify`, so an unvalidated document with a cycle in
74
- * it throws a RangeError out of here where the validator would have returned a
75
- * clean `resource_limit` issue: parse first, then diff.
76
- */
77
- export function diffValidatedUdlEvolution(previous, next) {
78
- return diffValidatedUdlEvolutionMessages(previous, next).map((message) => {
79
- const instrumentId = /^([^:]+): /.exec(message)?.[1];
80
- const instrumentIndex = previous.instruments.findIndex((instrument) => instrument.id === instrumentId);
81
- const base = instrumentIndex < 0
82
- ? "$.instruments"
83
- : `$.instruments[${instrumentIndex}]`;
84
- return evolutionIssue(message, base);
85
- });
86
- }
87
- function diffValidatedUdlEvolutionMessages(previous, next) {
88
- const violations = [];
89
- if (previous.product !== next.product) {
90
- violations.push(`product id changed from ${previous.product} to ${next.product}`);
91
- }
92
- if (next.version < previous.version) {
93
- violations.push(`product version moved backward from ${previous.version} to ${next.version}`);
94
- }
95
- let semanticChange = false;
96
- const previousSubjects = new Map(previous.subjects.map((subject) => [subject.kind, subject]));
97
- const nextSubjects = new Map(next.subjects.map((subject) => [subject.kind, subject]));
98
- for (const [kind, subject] of previousSubjects) {
99
- const current = nextSubjects.get(kind);
100
- if (!current) {
101
- semanticChange = true;
102
- violations.push(`subject kind ${kind} was removed or renamed`);
103
- }
104
- else if (stableStringify(subject) !== stableStringify(current)) {
105
- semanticChange = true;
106
- violations.push(`subject kind ${kind} changed after becoming live`);
107
- }
108
- }
109
- for (const kind of nextSubjects.keys()) {
110
- if (!previousSubjects.has(kind))
111
- semanticChange = true;
112
- }
113
- const previousInstruments = new Map(previous.instruments.map((instrument) => [instrument.id, snapshotUdlInstrument(instrument)]));
114
- const nextInstruments = new Map(next.instruments.map((instrument) => [instrument.id, snapshotUdlInstrument(instrument)]));
115
- for (const [id, instrument] of previousInstruments) {
116
- const current = nextInstruments.get(id);
117
- if (!current) {
118
- semanticChange = true;
119
- violations.push(`${id}: live instrument was removed from the product`);
120
- continue;
121
- }
122
- if (stableStringify(instrument) !== stableStringify(current)) {
123
- semanticChange = true;
124
- }
125
- violations.push(...diffInstrumentEvolutionMessages(instrument, current));
126
- }
127
- for (const id of nextInstruments.keys()) {
128
- if (!previousInstruments.has(id))
129
- semanticChange = true;
130
- }
131
- if (semanticChange && next.version <= previous.version) {
132
- violations.push(`product definition changed without increasing version ${previous.version}`);
133
- }
134
- return violations;
135
- }
136
- /** Diff one instrument snapshot. An empty result means the change is additive. */
137
- export function diffInstrumentEvolution(previous, next) {
138
- return diffInstrumentEvolutionMessages(previous, next).map((message) => evolutionIssue(message, "$.instruments"));
139
- }
140
- function diffInstrumentEvolutionMessages(previous, next) {
141
- if (previous.id !== next.id) {
142
- return [`instrument id changed from ${previous.id} to ${next.id}`];
143
- }
144
- const violations = [];
145
- if (previous.idPrefix !== next.idPrefix) {
146
- violations.push(`instance id prefix changed from ${previous.idPrefix} to ${next.idPrefix}`);
147
- }
148
- if (previous.initial !== next.initial) {
149
- violations.push(`initial lifecycle state changed from ${previous.initial} to ${next.initial}`);
150
- }
151
- violations.push(...removedSetEntries(previous.states, next.states, (state) => `lifecycle state ${state} was removed or renamed`));
152
- for (const [action, transition] of Object.entries(previous.transitions)) {
153
- const current = next.transitions[action];
154
- if (!current) {
155
- violations.push(`transition for action ${action} was removed or renamed`);
156
- continue;
157
- }
158
- if (transition.to !== current.to) {
159
- violations.push(`transition for action ${action} changed its target state from ${transition.to} to ${current.to}`);
160
- }
161
- violations.push(...removedSetEntries(transition.from, current.from, (state) => `transition for action ${action} no longer fires from state ${state}`));
162
- }
163
- violations.push(...diffFields(previous.fields, next.fields));
164
- if (Boolean(previous.distinctParties) !== Boolean(next.distinctParties)) {
165
- violations.push("distinct-party admission changed after becoming live");
166
- }
167
- if (previous.actionOrder) {
168
- const previousActions = new Set(previous.actionOrder);
169
- const retainedActionOrder = (next.actionOrder ?? []).filter((action) => previousActions.has(action));
170
- if (stableStringify(previous.actionOrder) !==
171
- stableStringify(retainedActionOrder)) {
172
- violations.push("instrument action order changed after becoming live");
173
- }
174
- }
175
- violations.push(...diffActions(previous.actions, next.actions));
176
- violations.push(...diffParties(previous.parties, next.parties));
177
- for (const key of [
178
- "allocation",
179
- "contributions",
180
- "dateOrder",
181
- "templateBinding",
182
- ]) {
183
- if (stableStringify(previous[key] ?? (key === "dateOrder" ? [] : null)) !==
184
- stableStringify(next[key] ?? (key === "dateOrder" ? [] : null)))
185
- violations.push(`${key} contract changed`);
186
- }
187
- violations.push(...diffAggregates(previous, next));
188
- if (stableStringify(Object.keys(previous.callerParkedStates ?? {}).sort()) !==
189
- stableStringify(Object.keys(next.callerParkedStates ?? {}).sort())) {
190
- violations.push("caller-parked state annotations changed");
191
- }
192
- if (stableStringify(previous.dials ?? []) !== stableStringify(next.dials ?? [])) {
193
- violations.push("instrument dials changed after becoming live");
194
- }
195
- if ((previous.surfaceVisibility ?? null) !== (next.surfaceVisibility ?? null)) {
196
- violations.push("instrument surface visibility changed after becoming live");
197
- }
198
- if ((previous.templateId ?? null) !== (next.templateId ?? null)) {
199
- violations.push("instrument archetype template changed after becoming live");
200
- }
201
- if (previous.subjectExtensible && !next.subjectExtensible) {
202
- violations.push("tenant-defined subject kinds are no longer accepted");
203
- }
204
- if (stableStringify(previous.derivedAmounts ?? []) !==
205
- stableStringify(next.derivedAmounts ?? [])) {
206
- violations.push("derived amount rules changed; derived money arithmetic is frozen once live");
207
- }
208
- if (stableStringify(previous.feeRules ?? []) !==
209
- stableStringify(next.feeRules ?? [])) {
210
- violations.push("feeRules changed; fee calculation and settlement funding are frozen once live");
211
- }
212
- violations.push(...removedSetEntries(previous.partitions, next.partitions, (law) => `partition law [${law}] was removed`), ...next.partitions
213
- .filter((law) => !previous.partitions.includes(law))
214
- .map((law) => `partition law [${law}] was added, which can reject existing callers`));
215
- violations.push(...diffQuotes(previous.quotes, next.quotes));
216
- violations.push(...removedSetEntries(previous.subjects, next.subjects, (kind) => `subject kind ${kind} was removed, rejecting linked instances`), ...removedSetEntries(previous.updateFields, next.updateFields, (field) => `update policy no longer permits field ${field}`), ...removedSetEntries(previous.updateStates, next.updateStates, (state) => `update policy no longer permits state ${state}`));
217
- return violations.map((violation) => `${next.id}: ${violation}`);
218
- }
219
- function evolutionIssue(message, instrumentBase) {
220
- if (message.startsWith("product id changed"))
221
- return issue("UDL7001", "$.product", message);
222
- if (message.startsWith("product version moved backward"))
223
- return issue("UDL7001", "$.version", message);
224
- if (message.startsWith("product definition changed"))
225
- return issue("UDL7002", "$.version", message);
226
- if (message.startsWith("subject kind "))
227
- return issue("UDL7001", "$.subjects", message);
228
- const instrumentMatch = /^([^:]+): (.*)$/.exec(message);
229
- const detail = instrumentMatch?.[2] ?? message;
230
- const transitionAction = /^transition for action ([a-z][a-z0-9_]*)/.exec(detail)?.[1];
231
- if (transitionAction)
232
- return issue("UDL7001", `${instrumentBase}.lifecycle.transitions.${transitionAction}`, message);
233
- const action = /^action ([a-z][a-z0-9_]*)/.exec(detail)?.[1];
234
- if (action)
235
- return issue("UDL7001", `${instrumentBase}.actions.${action}`, message);
236
- if (detail.includes("instrument id"))
237
- return issue("UDL7001", instrumentBase, message);
238
- if (detail.includes("id prefix") ||
239
- detail.includes("lifecycle") ||
240
- detail.includes("transition") ||
241
- detail.includes("initial") ||
242
- detail.includes("live instrument was removed"))
243
- return issue("UDL7001", `${instrumentBase}.lifecycle`, message);
244
- if (detail.startsWith("field "))
245
- return issue("UDL7001", `${instrumentBase}.fields`, message);
246
- if (detail.includes("move") ||
247
- detail.includes("payout") ||
248
- detail.includes("fee") ||
249
- detail.includes("quote") ||
250
- detail.includes("derived amount") ||
251
- detail.includes("partition") ||
252
- detail.includes("distribution") ||
253
- detail.includes("signed child sum") ||
254
- detail.includes("earnable"))
255
- return issue("UDL7001", `${instrumentBase}.actions`, message);
256
- if (detail.includes("gate") ||
257
- detail.includes("check prerequisite") ||
258
- detail.includes("reconcile expectation") ||
259
- detail.includes("drained-account") ||
260
- detail.includes("exposure") ||
261
- detail.includes("aggregate"))
262
- return issue("UDL7001", `${instrumentBase}.actions`, message);
263
- if (detail.startsWith("action ") ||
264
- detail.includes("action order") ||
265
- detail.includes("step count"))
266
- return issue("UDL7001", `${instrumentBase}.actions`, message);
267
- return issue("UDL7001", instrumentBase, message);
268
- }
269
- function snapshotUdlAction(definition) {
270
- return {
271
- requiresInput: definition.requiresInput ?? null,
272
- engineOwned: definition.engineOwned ?? null,
273
- captureEngine: definition.captureEngine ?? null,
274
- requiresAllocation: definition.requiresAllocation ?? null,
275
- allocate: definition.allocate ?? null,
276
- contributionStage: definition.contributionStage ?? null,
277
- transitionsRefs: definition.transitionsRefs ?? [],
278
- captureInput: definition.captureInput ?? null,
279
- commit: definition.commit ?? null,
280
- deadline: definition.deadline ?? null,
281
- decision: definition.decision ?? null,
282
- principal: definition.principal ?? null,
283
- remainder: definition.remainder ?? null,
284
- requiresChecks: definition.requiresChecks ?? [],
285
- sandboxFailurePoint: definition.sandboxFailurePoint ?? null,
286
- updates: definition.updates ?? [],
287
- distribute: definition.distribute ?? null,
288
- due: definition.due ?? null,
289
- earnable: definition.earnable ?? false,
290
- effects: definition.effects ??
291
- deriveUdlActionEffects(definition, udlClauseVocabulary),
292
- eventName: definition.eventName ?? null,
293
- input: definition.input ? snapshotJsonSchemaFields(definition.input) : null,
294
- inputConstraints: definition.input
295
- ? snapshotJsonSchemaConstraints(definition.input)
296
- : null,
297
- payout: definition.payout ?? null,
298
- port: definition.port ?? null,
299
- publicAction: definition.publicAction ?? null,
300
- setsAt: definition.setsAt ?? null,
301
- signedSum: definition.signedSum ?? null,
302
- cascade: definition.cascade
303
- ? definition.cascade.map((entry) => ({ ...entry }))
304
- : null,
305
- moves: definition.moves.map((move) => ({
306
- bind: move.bind,
307
- capture: move.capture ?? {},
308
- key: move.key,
309
- operation: move.operation,
310
- })),
311
- requiresAggregate: definition.requiresAggregate ?? [],
312
- requiresDrainedAccount: definition.requiresDrainedAccount ?? null,
313
- requiresExposure: definition.requiresExposure ?? [],
314
- unique: definition.unique ?? null,
315
- requiresRefs: definition.requiresRefs ?? [],
316
- reconcile: definition.reconcile ?? null,
317
- steps: definition.steps.map((step) => ({
318
- bind: step.bind,
319
- capture: step.capture ?? {},
320
- operation: step.operation,
321
- })),
322
- };
323
- }
324
- function snapshotJsonSchemaFields(schema) {
325
- const properties = recordValue(schema.properties);
326
- const required = new Set(Array.isArray(schema.required)
327
- ? schema.required.filter((value) => typeof value === "string")
328
- : []);
329
- return Object.fromEntries(Object.entries(properties).map(([field, fieldSchema]) => [
330
- field,
331
- { required: required.has(field), schema: withoutProse(fieldSchema) },
332
- ]));
333
- }
334
- /**
335
- * Descriptions are prose for readers, not shape: a wording fix in a std
336
- * template must land on a live flow as an extension, never as a refusal.
337
- */
338
- function withoutProse(value, depth = 1) {
339
- if (depth > UDL_LIMITS.maxDepth)
340
- throw nestingExceeded();
341
- if (Array.isArray(value)) {
342
- return value.map((item) => withoutProse(item, depth + 1));
343
- }
344
- if (value === null || typeof value !== "object")
345
- return value;
346
- return Object.fromEntries(Object.entries(value)
347
- .filter(([key]) => key !== "description")
348
- .map(([key, entry]) => [key, withoutProse(entry, depth + 1)]));
349
- }
350
- function nestingExceeded() {
351
- return new UdlError([
352
- issue("UDL1004", "$", `UDL nesting exceeds ${UDL_LIMITS.maxDepth} levels`),
353
- ]);
354
- }
355
- function snapshotJsonSchemaConstraints(schema) {
356
- const { properties: _properties, required: _required, ...constraints } = schema;
357
- return constraints;
358
- }
359
- function diffFields(previous, next) {
360
- const violations = [];
361
- for (const [field, descriptor] of Object.entries(previous)) {
362
- const current = next[field];
363
- if (!current) {
364
- violations.push(`field ${field} was removed or renamed`);
365
- continue;
366
- }
367
- if (!descriptor.required && current.required) {
368
- violations.push(`field ${field} became required, tightening the schema`);
369
- }
370
- if (stableStringify(descriptor.schema) !== stableStringify(current.schema)) {
371
- violations.push(`field ${field} schema changed; a live field schema is frozen`);
372
- }
373
- }
374
- for (const [field, descriptor] of Object.entries(next)) {
375
- if (!previous[field] && descriptor.required) {
376
- violations.push(`field ${field} was added as required, which rejects existing instances (only optional fields are additive)`);
377
- }
378
- }
379
- return violations;
380
- }
381
- function diffActions(previous, next) {
382
- const violations = [];
383
- for (const [action, descriptor] of Object.entries(previous)) {
384
- const current = next[action];
385
- if (!current) {
386
- violations.push(`action ${action} was removed or renamed`);
387
- continue;
388
- }
389
- if (descriptor.moves.length !== current.moves.length) {
390
- violations.push(`action ${action} changed its move count from ${descriptor.moves.length} to ${current.moves.length}; money movement is frozen once live`);
391
- }
392
- else {
393
- descriptor.moves.forEach((move, index) => {
394
- const nextMove = current.moves[index];
395
- if (stableStringify(move) !== stableStringify(nextMove)) {
396
- violations.push(`action ${action} changed move ${move.key} at index ${index}; money movement is frozen once live`);
397
- }
398
- });
399
- }
400
- if (descriptor.steps.length !== current.steps.length) {
401
- violations.push(`action ${action} changed its step count from ${descriptor.steps.length} to ${current.steps.length}; a live action's steps are frozen`);
402
- }
403
- else {
404
- descriptor.steps.forEach((step, index) => {
405
- const nextStep = current.steps[index];
406
- if (stableStringify(step) === stableStringify(nextStep))
407
- return;
408
- violations.push(`action ${action} changed step ${index} (${step.operation}); a live action's steps are frozen`);
409
- });
410
- }
411
- violations.push(...diffInput(action, descriptor.input ?? {}, current.input ?? {}));
412
- // A action gaining its first input is additive (per-field checks still catch
413
- // added-as-required); once an input is live, its schema envelope is frozen.
414
- if (descriptor.input !== null &&
415
- stableStringify(descriptor.inputConstraints) !==
416
- stableStringify(current.inputConstraints)) {
417
- violations.push(`action ${action} changed its input schema beyond declared fields; a live action input is frozen`);
418
- }
419
- if (stableStringify(descriptor.requiresRefs) !==
420
- stableStringify(current.requiresRefs)) {
421
- violations.push(`action ${action} changed its cross-instrument gates`);
422
- }
423
- if (stableStringify(descriptor.requiresAggregate) !==
424
- stableStringify(current.requiresAggregate)) {
425
- violations.push(`action ${action} changed its aggregate admission gates`);
426
- }
427
- if (stableStringify(descriptor.requiresDrainedAccount) !==
428
- stableStringify(current.requiresDrainedAccount)) {
429
- violations.push(`action ${action} changed its drained-account gate`);
430
- }
431
- if (stableStringify(descriptor.unique ?? null) !==
432
- stableStringify(current.unique ?? null)) {
433
- violations.push(`action ${action} changed its subject uniqueness claim`);
434
- }
435
- if (descriptor.requiresExposure !== undefined &&
436
- stableStringify(descriptor.requiresExposure) !==
437
- stableStringify(current.requiresExposure)) {
438
- violations.push(`action ${action} changed its exposure admission gates`);
439
- }
440
- if (descriptor.reconcile !== undefined &&
441
- stableStringify(descriptor.reconcile) !==
442
- stableStringify(current.reconcile)) {
443
- violations.push(`action ${action} changed its reconcile expectations`);
444
- }
445
- if (stableStringify(descriptor.payout ?? null) !==
446
- stableStringify(current.payout ?? null)) {
447
- violations.push(`action ${action} changed its payout intent`);
448
- }
449
- for (const key of [
450
- "requiresInput",
451
- "engineOwned",
452
- "captureEngine",
453
- "requiresAllocation",
454
- "allocate",
455
- "contributionStage",
456
- "transitionsRefs",
457
- ]) {
458
- if (stableStringify(descriptor[key] ?? (key === "transitionsRefs" ? [] : null)) !==
459
- stableStringify(current[key] ?? (key === "transitionsRefs" ? [] : null)))
460
- violations.push(`action ${action} changed its ${key} contract`);
461
- }
462
- if (descriptor.earnable !== current.earnable) {
463
- violations.push(`action ${action} changed its earnable flag`);
464
- }
465
- if (descriptor.effects !== undefined &&
466
- stableStringify(descriptor.effects) !== stableStringify(current.effects)) {
467
- violations.push(`action ${action} changed its derived effects`);
468
- }
469
- if (descriptor.eventName !== current.eventName) {
470
- violations.push(`action ${action} changed its event name`);
471
- }
472
- if (stableStringify(descriptor.due) !== stableStringify(current.due)) {
473
- violations.push(`action ${action} changed its due condition`);
474
- }
475
- if (stableStringify(descriptor.deadline) !== stableStringify(current.deadline)) {
476
- violations.push(`action ${action} changed its admission deadline`);
477
- }
478
- if (stableStringify(descriptor.decision) !== stableStringify(current.decision)) {
479
- violations.push(`action ${action} changed its provider decision`);
480
- }
481
- if ((descriptor.principal ?? null) !== (current.principal ?? null)) {
482
- violations.push(`action ${action} changed its caller principal`);
483
- }
484
- if (stableStringify(descriptor.remainder ?? null) !==
485
- stableStringify(current.remainder ?? null)) {
486
- violations.push(`action ${action} changed its remainder rule`);
487
- }
488
- if (stableStringify(descriptor.requiresChecks ?? []) !==
489
- stableStringify(current.requiresChecks ?? [])) {
490
- violations.push(`action ${action} changed its check prerequisites`);
491
- }
492
- // A failure point only adds a sandbox refusal for one documented amount, so
493
- // declaring one on an action that had none is additive; changing or
494
- // removing a declared one rewrites what a sandbox integration relies on.
495
- if (descriptor.sandboxFailurePoint &&
496
- descriptor.sandboxFailurePoint !== (current.sandboxFailurePoint ?? null)) {
497
- violations.push(`action ${action} changed its sandbox failure point`);
498
- }
499
- if (stableStringify(descriptor.updates ?? []) !==
500
- stableStringify(current.updates ?? [])) {
501
- violations.push(`action ${action} changed its field updates`);
502
- }
503
- if (stableStringify(descriptor.distribute) !==
504
- stableStringify(current.distribute)) {
505
- violations.push(`action ${action} changed its distribution rule; money distribution is frozen once live`);
506
- }
507
- if (descriptor.captureInput !== undefined &&
508
- stableStringify(descriptor.captureInput) !==
509
- stableStringify(current.captureInput)) {
510
- violations.push(`action ${action} changed its captured receipt input`);
511
- }
512
- if (stableStringify(descriptor.port) !== stableStringify(current.port)) {
513
- violations.push(`action ${action} changed its decision port`);
514
- }
515
- if (descriptor.publicAction != null &&
516
- descriptor.publicAction !== current.publicAction) {
517
- violations.push(`action ${action} changed its public action`);
518
- }
519
- if (stableStringify(descriptor.setsAt) !== stableStringify(current.setsAt)) {
520
- violations.push(`action ${action} changed its computed timestamp`);
521
- }
522
- if (descriptor.signedSum !== undefined &&
523
- stableStringify(descriptor.signedSum) !==
524
- stableStringify(current.signedSum)) {
525
- violations.push(`action ${action} changed its signed child sum`);
526
- }
527
- if (descriptor.cascade !== undefined &&
528
- stableStringify(descriptor.cascade) !== stableStringify(current.cascade)) {
529
- violations.push(`action ${action} changed its cascade rules`);
530
- }
531
- }
532
- for (const [action, descriptor] of Object.entries(next)) {
533
- if (previous[action] || descriptor.payout == null)
534
- continue;
535
- violations.push(`action ${action} added a payout intent; external money movement is frozen once live`);
536
- }
537
- return violations;
538
- }
539
- function diffInput(action, previous, next) {
540
- const violations = [];
541
- for (const [field, descriptor] of Object.entries(previous)) {
542
- const current = next[field];
543
- if (!current) {
544
- // Compiled action inputs are strict objects, so a removed field starts
545
- // rejecting every caller that still sends it -- same law as instrument fields.
546
- violations.push(`action ${action} input field ${field} was removed or renamed`);
547
- continue;
548
- }
549
- if (!descriptor.required && current.required) {
550
- violations.push(`action ${action} input field ${field} became required, tightening the action input`);
551
- }
552
- if (stableStringify(descriptor.schema) !== stableStringify(current.schema)) {
553
- violations.push(`action ${action} input field ${field} schema changed; a live action input schema is frozen`);
554
- }
555
- }
556
- for (const [field, descriptor] of Object.entries(next)) {
557
- if (!previous[field] && descriptor.required) {
558
- violations.push(`action ${action} input field ${field} was added as required, tightening the action input`);
559
- }
560
- }
561
- return violations;
562
- }
563
- function diffParties(previous, next) {
564
- const violations = [];
565
- for (const [role, field] of Object.entries(previous)) {
566
- const current = next[role];
567
- if (!current)
568
- violations.push(`party role ${role} was removed or renamed`);
569
- else if (current !== field) {
570
- violations.push(`party role ${role} moved from field ${field} to ${current}`);
571
- }
572
- }
573
- return violations;
574
- }
575
- function diffAggregates(previous, next) {
576
- return [
577
- ...removedSetEntries(previous.aggregateInvariants, next.aggregateInvariants, (key) => `aggregate invariant [${key}] was removed`),
578
- ...next.aggregateInvariants
579
- .filter((key) => !previous.aggregateInvariants.includes(key))
580
- .map((key) => `aggregate invariant [${key}] was added, which can reject existing instances`),
581
- ];
582
- }
583
- function diffQuotes(previous, next) {
584
- if (previous === null || previous === undefined)
585
- return [];
586
- if (next === null || next === undefined)
587
- return ["quote policy was removed"];
588
- return stableStringify(previous) === stableStringify(next)
589
- ? []
590
- : [
591
- "quote policy changed; the charge schedule, the frozen fields, and the refund destination are frozen once live",
592
- ];
593
- }
594
- function aggregateInvariantKey(invariant) {
595
- const measure = "childField" in invariant
596
- ? invariant.childField
597
- : `count${invariant.window ? `[${invariant.window.field} per ${invariant.window.days}d]` : ""}`;
598
- return `${invariant.childInstrumentId}.${measure} within ${invariant.parentField} via ${invariant.childRefField} while ${[...invariant.childStatuses].sort().join(",")}`;
599
- }
600
- function removedSetEntries(previous, next, message) {
601
- const current = new Set(next);
602
- return previous.filter((entry) => !current.has(entry)).map(message);
603
- }
604
- function compactStringRecord(value) {
605
- return Object.fromEntries(Object.entries(value ?? {}).filter((entry) => typeof entry[1] === "string"));
606
- }
607
- function recordValue(value) {
608
- return value !== null && typeof value === "object" && !Array.isArray(value)
609
- ? value
610
- : {};
611
- }
612
- /**
613
- * The comparison key every diff above is written against. It recurses, so it
614
- * carries the same depth budget the validator applies to a document: a
615
- * snapshot is never deeper than the document it came from, and the deepest
616
- * conformance document reaches 12 of the 24 levels. A cycle is infinite depth
617
- * and lands here rather than exhausting the call stack.
618
- */
619
- function stableStringify(value, depth = 1) {
620
- if (depth > UDL_LIMITS.maxDepth)
621
- throw nestingExceeded();
622
- if (value === null || typeof value !== "object") {
623
- return JSON.stringify(value) ?? "null";
624
- }
625
- if (Array.isArray(value)) {
626
- // An arrow, not a bare reference: `map` would pass the index as the depth.
627
- return `[${value.map((item) => stableStringify(item, depth + 1)).join(",")}]`;
628
- }
629
- const entries = Object.entries(value)
630
- .filter(([, entry]) => entry !== undefined)
631
- .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0));
632
- return `{${entries
633
- .map(([key, entry]) => `${JSON.stringify(key)}:${stableStringify(entry, depth + 1)}`)
634
- .join(",")}}`;
2
+ function stable(value) {
3
+ if (Array.isArray(value))
4
+ return "[" + value.map(stable).join(",") + "]";
5
+ if (value && typeof value === "object")
6
+ return ("{" +
7
+ Object.entries(value)
8
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
9
+ .map(([key, entry]) => JSON.stringify(key) + ":" + stable(entry))
10
+ .join(",") +
11
+ "}");
12
+ return JSON.stringify(value) ?? "undefined";
13
+ }
14
+ /** Existing instruments are frozen; a live document may add independent instruments. */
15
+ export function diffValidatedUdlEvolution(live, next) {
16
+ const issues = [];
17
+ const refuse = (path, message) => issues.push(issue("UDL7001", path, message));
18
+ if (live.product !== next.product || live.currency !== next.currency)
19
+ refuse("$", "product identity and currency are immutable");
20
+ for (const [name, party] of Object.entries(live.parties))
21
+ if (stable(party) !== stable(next.parties[name]))
22
+ refuse(`$.parties.${name}`, "a live party cannot change or disappear");
23
+ for (const instrument of live.instruments) {
24
+ const updated = next.instruments.find((i) => i.id === instrument.id);
25
+ if (!updated || stable(instrument) !== stable(updated))
26
+ refuse(`$.instruments.${instrument.id}`, "a live instrument cannot change or disappear; recreate development estates");
27
+ }
28
+ if (stable(live) !== stable(next) && next.version <= live.version)
29
+ issues.push(issue("UDL7002", "$.version", "a changed document needs a higher version"));
30
+ return issues;
635
31
  }
636
32
  //# sourceMappingURL=evolution.js.map