@composable-os/cli 0.1.0-beta.11 → 0.1.0-beta.14

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 (166) hide show
  1. package/dist/{accounts-UHYLCLEY.js → accounts-GOCNY6WI.js} +17 -13
  2. package/dist/app-OSPZHKOI.js +43 -0
  3. package/dist/app-upload-LH4PXKI4.js +198 -0
  4. package/dist/{blocks-5IFU25J6.js → blocks-6DZIP47W.js} +207 -25
  5. package/dist/{chunk-XIDLW3EP.js → chunk-2B6YUYZV.js} +23499 -11766
  6. package/dist/{run-7P4RQALH.js → chunk-2CCHB37H.js} +9 -146
  7. package/dist/{chunk-DU6OIFOU.js → chunk-3OGDWKJ3.js} +530 -434
  8. package/dist/{chunk-DHS2CV2M.js → chunk-5D7BDF4Y.js} +15 -13
  9. package/dist/{chunk-MBIKVRAC.js → chunk-5YDYQM6V.js} +830 -47
  10. package/dist/{chunk-ZAWES2UD.js → chunk-6CM3WZG5.js} +13 -2483
  11. package/dist/{chunk-7D4GKZOX.js → chunk-CIBJGB5H.js} +422 -75
  12. package/dist/chunk-EPDTPGZJ.js +330 -0
  13. package/dist/{chunk-LAAL4YGR.js → chunk-HAYF4G5V.js} +66 -23
  14. package/dist/chunk-HCG6T53D.js +61904 -0
  15. package/dist/{chunk-K34UKWEI.js → chunk-JX4IFWNT.js} +64 -32
  16. package/dist/{chunk-6XTU2MTP.js → chunk-KFHKNXGH.js} +632 -418
  17. package/dist/chunk-KMFMD52Z.js +13276 -0
  18. package/dist/{chunk-E4WCYTCT.js → chunk-LX2TTLVY.js} +174 -55
  19. package/dist/{chunk-PDD2ETVF.js → chunk-O37YUZ52.js} +172 -16
  20. package/dist/{chunk-GYTEW66E.js → chunk-O3R4FS2J.js} +1 -1
  21. package/dist/{chunk-E64SG24J.js → chunk-Q6Y45DY6.js} +25 -2
  22. package/dist/chunk-RGKJKC5T.js +876 -0
  23. package/dist/{chunk-YFTLIEWU.js → chunk-RSEWEFAV.js} +12 -2
  24. package/dist/{chunk-2ABSVMGB.js → chunk-SMJZIK2O.js} +1 -1
  25. package/dist/{chunk-LO6WGU5Y.js → chunk-U72NEGCT.js} +8089 -3464
  26. package/dist/{chunk-P6UWZ6QQ.js → chunk-Z4IKF23A.js} +11 -7
  27. package/dist/{chunk-2IVEVPMY.js → chunk-Z7OVQ6BC.js} +105 -61
  28. package/dist/{chunk-6UWRT4VM.js → chunk-ZJSFX4RD.js} +175 -3
  29. package/dist/{cli-5UNY5G5L.js → cli-OKQHHSOE.js} +17 -25
  30. package/dist/{cli-UYZMVQMR.js → cli-VYSD2S4Z.js} +227 -81
  31. package/dist/cli.js +5 -5
  32. package/dist/{client-repo-SE4EKG6W.js → client-repo-MPCPTXLF.js} +7 -5
  33. package/dist/create.js +5 -5
  34. package/dist/{fields-FTWWMD7N.js → fields-GTHE6TTS.js} +27 -3
  35. package/dist/gateway-DPPEQZT4.js +25 -0
  36. package/dist/grants-6JY4XZO7.js +27 -0
  37. package/dist/invoke-MRONRZ5Q.js +33 -0
  38. package/dist/moves-UAUCMWL5.js +36 -0
  39. package/dist/{order-U4KZLLSJ.js → order-RKLGT74L.js} +2 -2
  40. package/dist/{person-UHLVBVLR.js → person-YOZTFV4Q.js} +11 -10
  41. package/dist/plan-on-sale-H4F26YIN.js +26 -0
  42. package/dist/platform/migrations/0730_practitioners.sql +79 -0
  43. package/dist/platform/migrations/0750_routine_mail.sql +98 -0
  44. package/dist/platform/migrations/0770_clear_fixed_role_grants.sql +64 -0
  45. package/dist/platform/migrations/0810_recurrence_exceptions.sql +66 -0
  46. package/dist/platform/migrations/0811_staff_time.sql +109 -0
  47. package/dist/platform/migrations/0812_staff_offers.sql +112 -0
  48. package/dist/platform/migrations/0813_pay_periods.sql +241 -0
  49. package/dist/platform/migrations/0814_staff_feed.sql +47 -0
  50. package/dist/platform/migrations/0815_checklists.sql +237 -0
  51. package/dist/platform/migrations/0816_checklist_schedules.sql +121 -0
  52. package/dist/platform/migrations/0817_checklist_day_window.sql +35 -0
  53. package/dist/platform/migrations/0850_agreements.sql +271 -0
  54. package/dist/platform/migrations/0851_agreement_acceptances.sql +387 -0
  55. package/dist/platform/migrations/0853_agreement_enforcement.sql +58 -0
  56. package/dist/platform/migrations/0854_agreement_copy.sql +149 -0
  57. package/dist/platform/migrations/0855_agreement_retention.sql +279 -0
  58. package/dist/platform/migrations/0856_subscription_cooling_off.sql +159 -0
  59. package/dist/platform/migrations/0857_agreement_copy_guardian.sql +337 -0
  60. package/dist/platform/migrations/0858_agreement_desk.sql +175 -0
  61. package/dist/platform/migrations/0910_routine_messages.sql +99 -0
  62. package/dist/platform/migrations/0911_texts.sql +60 -0
  63. package/dist/platform/migrations/0913_contact_consent.sql +93 -0
  64. package/dist/platform/migrations/0916_contact_mailbox_index.sql +29 -0
  65. package/dist/platform/migrations/0930_stock_movements.sql +95 -0
  66. package/dist/platform/migrations/0931_stock_low.sql +25 -0
  67. package/dist/platform/migrations/0932_order_delivery.sql +78 -0
  68. package/dist/platform/migrations/0950_order_adjustments.sql +111 -0
  69. package/dist/platform/migrations/0951_order_price_guards.sql +33 -0
  70. package/dist/platform/migrations/0952_order_paid_another_way.sql +194 -0
  71. package/dist/platform/migrations/0953_discount_uses.sql +183 -0
  72. package/dist/platform/migrations/0955_folded_addresses.sql +92 -0
  73. package/dist/platform/migrations/0970_published_text.sql +59 -0
  74. package/dist/platform/migrations/0971_publish_acks.sql +68 -0
  75. package/dist/platform/migrations/0990_customer_email_change.sql +65 -0
  76. package/dist/platform/migrations/1010_intake_links.sql +148 -0
  77. package/dist/platform/migrations/1030_invoices.sql +747 -0
  78. package/dist/platform/migrations/1031_invoice_orders.sql +327 -0
  79. package/dist/platform/migrations/1050_inbox_conversations.sql +83 -0
  80. package/dist/platform/migrations/1090_staff_hours.sql +43 -0
  81. package/dist/platform/migrations/1091_staff_time_margins.sql +12 -0
  82. package/dist/platform/migrations/1092_client_guard.sql +26 -0
  83. package/dist/platform/migrations/1095_thing_time.sql +70 -0
  84. package/dist/platform/migrations/1130_devices.sql +162 -0
  85. package/dist/platform/migrations/1135_person_codes.sql +88 -0
  86. package/dist/platform/migrations/1150_finance_periods.sql +316 -0
  87. package/dist/platform/migrations/1151_payouts.sql +202 -0
  88. package/dist/platform/migrations/1153_finance_money_dates.sql +18 -0
  89. package/dist/platform/migrations/1170_journeys.sql +318 -0
  90. package/dist/platform/migrations/1171_person_birthday.sql +52 -0
  91. package/dist/platform/migrations/1175_person_signals.sql +29 -0
  92. package/dist/platform/migrations/1190_restricted_values.sql +25 -0
  93. package/dist/platform/migrations/1230_note_levels.sql +113 -0
  94. package/dist/platform/migrations/1231_person_carers.sql +33 -0
  95. package/dist/platform/migrations/1232_note_kinds.sql +122 -0
  96. package/dist/platform/migrations/1270_time_entries.sql +145 -0
  97. package/dist/platform/migrations/1271_leave.sql +249 -0
  98. package/dist/platform/migrations/1273_time_entry_reopened.sql +21 -0
  99. package/dist/platform/migrations/1330_accounting.sql +260 -0
  100. package/dist/platform/migrations/1350_customer_feed.sql +24 -0
  101. package/dist/platform/migrations/1390_locations.sql +77 -0
  102. package/dist/platform/migrations/1410_outside_copy.sql +213 -0
  103. package/dist/platform/migrations/1430_inbox_activities.sql +231 -0
  104. package/dist/platform/migrations/1450_wrong_guesses.sql +23 -0
  105. package/dist/platform/sdk/acknowledge.ts +100 -0
  106. package/dist/platform/sdk/agreements.ts +185 -0
  107. package/dist/platform/sdk/allowance.ts +98 -8
  108. package/dist/platform/sdk/automation-check.ts +120 -9
  109. package/dist/platform/sdk/automation.ts +78 -10
  110. package/dist/platform/sdk/behaviour.ts +26 -6
  111. package/dist/platform/sdk/calendar-entry.ts +258 -0
  112. package/dist/platform/sdk/capacity.ts +1 -2
  113. package/dist/platform/sdk/checklists.ts +118 -0
  114. package/dist/platform/sdk/contract.ts +489 -27
  115. package/dist/platform/sdk/discount.ts +408 -0
  116. package/dist/platform/sdk/document.ts +4 -2
  117. package/dist/platform/sdk/field-types.ts +5 -0
  118. package/dist/platform/sdk/formula/compile.ts +10 -0
  119. package/dist/platform/sdk/index.ts +17 -0
  120. package/dist/platform/sdk/intake.ts +380 -0
  121. package/dist/platform/sdk/journey-signals.ts +215 -0
  122. package/dist/platform/sdk/manifest.ts +1236 -65
  123. package/dist/platform/sdk/mine.ts +161 -0
  124. package/dist/platform/sdk/occupies.ts +192 -0
  125. package/dist/platform/sdk/questions.ts +681 -0
  126. package/dist/platform/sdk/recurring.ts +90 -9
  127. package/dist/platform/sdk/restricted-fields.ts +129 -0
  128. package/dist/platform/sdk/rich-text.ts +112 -0
  129. package/dist/platform/sdk/routine-mail.ts +1272 -0
  130. package/dist/platform/sdk/runtime.ts +25 -12
  131. package/dist/platform/sdk/screens.ts +91 -0
  132. package/dist/platform/sdk/sellable.ts +344 -0
  133. package/dist/platform/sdk/slug.ts +7 -2
  134. package/dist/platform/sdk/staffed.ts +474 -0
  135. package/dist/platform/sdk/states.ts +68 -26
  136. package/dist/platform/sdk/stock.ts +332 -0
  137. package/dist/platform/sdk/team.ts +83 -0
  138. package/dist/platform/sdk/testing.ts +70 -6
  139. package/dist/platform/sdk/worked-on.ts +134 -0
  140. package/dist/{products-2H5DR232.js → products-GCQLSZ3U.js} +2 -2
  141. package/dist/run-7ID64RA6.js +65 -0
  142. package/dist/run-FH7OGGTV.js +131 -0
  143. package/dist/run-OYZIAP6M.js +3363 -0
  144. package/dist/{run-ZCGFMEZF.js → run-QOFRRSZV.js} +41 -60
  145. package/dist/{run-PO3W5BFA.js → run-TJAEWR5U.js} +21 -51
  146. package/dist/{src-I3IJ4NKC.js → src-52VERUPK.js} +306 -4
  147. package/dist/src-PHRELWN5.js +40 -0
  148. package/dist/{visibility-TVXZ67FD.js → visibility-SZCINPP4.js} +21 -4
  149. package/package.json +2 -2
  150. package/dist/chunk-2TWV3SVB.js +0 -349
  151. package/dist/chunk-2XC5JLBO.js +0 -1931
  152. package/dist/chunk-324WJXNP.js +0 -320
  153. package/dist/chunk-6ELZRNUU.js +0 -116
  154. package/dist/chunk-6WGFA2IV.js +0 -643
  155. package/dist/chunk-7CQGMVDO.js +0 -63
  156. package/dist/chunk-7OGCMQXG.js +0 -284
  157. package/dist/chunk-FJIZGS5Q.js +0 -698
  158. package/dist/chunk-UB4I2QKR.js +0 -31575
  159. package/dist/chunk-WHKJGF36.js +0 -2418
  160. package/dist/chunk-YNUZRTPH.js +0 -182
  161. package/dist/chunk-ZZFWMVJO.js +0 -704
  162. package/dist/grants-LOW6TSWD.js +0 -32
  163. package/dist/invoke-6KVT6WJI.js +0 -41
  164. package/dist/moves-E2HKYCTK.js +0 -41
  165. package/dist/plan-on-sale-TJPFCNL7.js +0 -26
  166. package/dist/src-CRO35DYY.js +0 -46
@@ -5,6 +5,7 @@
5
5
  // packages/core/src/allowance/.
6
6
  import { z } from "zod";
7
7
  import type { ExtensionManifest, FieldManifest, ObjectManifest } from "./manifest.ts";
8
+ import { moveOrigins } from "./states.ts";
8
9
 
9
10
  /** What a holder's uses are counted over. Weeks start on Monday; both in the holder's zone. */
10
11
  export const ALLOWANCE_PERIODS = ["total", "week", "month"] as const;
@@ -29,12 +30,19 @@ export const ALLOWANCE_VALUES = ["used", "left"] as const;
29
30
  * 16:00, `below: 960`). An empty holder field sets no bound.
30
31
  *
31
32
  * A spender with no value for `field` meets no condition that sets a limit.
33
+ *
34
+ * - `value` (stage 49, ADR 0764), in place of `field`: what every record of the spender is, a fixed
35
+ * word compared with `in` ("sessions": an appointment, never a class). No caller sets it.
36
+ * - `empty` (stage 49, ADR 0764): `"none"` makes an empty holder field for `in` allow nothing
37
+ * instead of anything: a pass that names no services covers no appointment. Left out, `"any"`.
32
38
  */
33
39
  export interface AllowanceCondition {
34
- field: string;
40
+ field?: string;
41
+ value?: string;
35
42
  in?: string | readonly string[];
36
43
  atLeast?: string | number;
37
44
  below?: string | number;
45
+ empty?: "any" | "none";
38
46
  }
39
47
 
40
48
  /** What a holder may be spent on: an object that declares `allowance.spends`, and conditions. */
@@ -92,7 +100,8 @@ export interface AllowanceHolderSpec {
92
100
  * be live then. Left out: the time of the spend.
93
101
  * - `copy`: read-only fields of its own the host fills, at create and at each spend, from one
94
102
  * relation away (`{ classType: "class.classType" }`), so a holder's `when` can read them and no
95
- * caller can set them.
103
+ * caller can set them. `<relation>.id` is the related record's own id (`{ serviceId:
104
+ * "service.id" }`, ADR 0764): an appointment's service, which its kind and length follow.
96
105
  * - `local`: read-only number fields of its own the host fills from `at` in `zone` (a timezone
97
106
  * field of its own or one relation away; the organisation's when left out or empty):
98
107
  * `weekday` (1 Monday to 7 Sunday) and `minute` (minutes since local midnight).
@@ -100,6 +109,12 @@ export interface AllowanceHolderSpec {
100
109
  * A record created into a spend state with it set takes the use of the record it names: in the
101
110
  * same batch the host moves that record to `state` (a return state) and spends from the same
102
111
  * holder, so a move never fails for want of a use the member already had.
112
+ * - `fixed` (ADR 0764): fields of its own that change only by such a move, never by an update,
113
+ * for every caller but the host (an appointment's times and service): a session a late cancel
114
+ * used never comes back by moving its time first.
115
+ * - `anchor` (ADR 0764): `{ field, from }`, a read-only datetime field the host sets at create:
116
+ * the moved record's, or else its own `from` (its start). A window may count from it, so a
117
+ * moved record keeps the late point of the one it replaced. It is fixed too.
103
118
  * - `paidBy`: holders of other extensions that may pay for it, by object (`memberships.pass`) or
104
119
  * by extension (`memberships`). Left out, only this extension's holders. A holder naming a
105
120
  * spender of another extension that does not list it is refused at install.
@@ -108,6 +123,12 @@ export interface AllowanceHolderSpec {
108
123
  * its order). Only the host and this extension's own code set it, never a customer, and it
109
124
  * cannot change while the record is in a spend state.
110
125
  *
126
+ * - `released` (stage 44 step 7, ADR 0647): a state of `returnIn` the host moves a record into
127
+ * when the holder it spent from is ended early by its payer's cooling off and the record's time
128
+ * is still ahead (a class not yet started): its use is returned and its place freed, as any move
129
+ * into a return state does. Each state a record holds a use in (`spendIn`) needs a move into it
130
+ * by the host. Left out, such records are kept.
131
+ *
111
132
  * Every field a holder's condition reads must be one the host fills (`copy` or `local`), so no
112
133
  * caller (a customer, staff, an AI) sets what pays for it.
113
134
  */
@@ -119,9 +140,15 @@ export interface AllowanceSpenderSpec {
119
140
  at?: string;
120
141
  copy?: Readonly<Record<string, string>>;
121
142
  local?: { weekday?: string; minute?: string; zone?: string };
122
- movedFrom?: { field: string; state: string };
143
+ movedFrom?: {
144
+ field: string;
145
+ state: string;
146
+ fixed?: readonly string[];
147
+ anchor?: { field: string; from: string };
148
+ };
123
149
  paidBy?: readonly string[];
124
150
  waived?: string;
151
+ released?: string;
125
152
  }
126
153
 
127
154
  /** The allowance behaviour: an object holds uses or spends them, never both. */
@@ -133,10 +160,12 @@ const stateValue = z.string().min(1).max(100);
133
160
 
134
161
  const conditionSchema = z
135
162
  .object({
136
- field: fieldName,
163
+ field: fieldName.optional(),
164
+ value: z.string().min(1).max(100).optional(),
137
165
  in: z.union([fieldName, z.array(z.string().max(200)).min(1).max(100)]).optional(),
138
166
  atLeast: z.union([fieldName, z.number()]).optional(),
139
167
  below: z.union([fieldName, z.number()]).optional(),
168
+ empty: z.enum(["any", "none"]).optional(),
140
169
  })
141
170
  .strict();
142
171
 
@@ -180,9 +209,18 @@ export const allowanceManifestSchema = z.union([
180
209
  })
181
210
  .strict()
182
211
  .optional(),
183
- movedFrom: z.object({ field: fieldName, state: stateValue }).strict().optional(),
212
+ movedFrom: z
213
+ .object({
214
+ field: fieldName,
215
+ state: stateValue,
216
+ fixed: z.array(fieldName).min(1).max(10).optional(),
217
+ anchor: z.object({ field: fieldName, from: fieldName }).strict().optional(),
218
+ })
219
+ .strict()
220
+ .optional(),
184
221
  paidBy: z.array(path).min(1).max(20).optional(),
185
222
  waived: fieldName.optional(),
223
+ released: stateValue.optional(),
186
224
  })
187
225
  .strict(),
188
226
  })
@@ -364,10 +402,22 @@ export function checkObjectAllowance(
364
402
  if (ops.length !== 1) {
365
403
  contract(cp, "A condition compares with exactly one of in, atLeast and below");
366
404
  }
367
- const field = fieldOf(spender, clause.field);
368
- if (!field || field.type === "formula") {
405
+ if ((clause.field === undefined) === (clause.value === undefined)) {
406
+ contract(cp, "A condition reads exactly one of field and value");
407
+ }
408
+ if (clause.value !== undefined && clause.in === undefined) {
409
+ contract(`${cp}.value`, "A fixed value is compared with in");
410
+ }
411
+ if (clause.empty !== undefined && clause.in === undefined) {
412
+ contract(`${cp}.empty`, "empty says what an empty in allows: it needs in");
413
+ }
414
+ // A fixed word (`value`) is what every record of the spender is: only the holder's is read.
415
+ const field = clause.field === undefined ? null : fieldOf(spender, clause.field);
416
+ if (clause.field === undefined) {
417
+ // Nothing of the spender to check.
418
+ } else if (!field || field.type === "formula") {
369
419
  contract(`${cp}.field`, `"${clause.field}" must be a field of ${spenderName}`);
370
- } else if (!filledBy.has(clause.field)) {
420
+ } else if (!filledBy.has(clause.field as string)) {
371
421
  contract(
372
422
  `${cp}.field`,
373
423
  `"${clause.field}" must be a field ${spenderName}'s host fills (its copy or local), so no caller sets what pays for it`,
@@ -432,6 +482,8 @@ export function checkObjectAllowance(
432
482
  }
433
483
  const other = ownObject(relation.to);
434
484
  if (!other) return null; // Another extension's object or a core one: the host checks.
485
+ // The related record's own id (ADR 0764): what it is, which only the relation sets.
486
+ if (target === "id") return { type: "text" } as FieldManifest;
435
487
  const field = fieldOf(other[1], target);
436
488
  if (!field) contract(p, `"${target}" is not a field of ${other[0]}`);
437
489
  return field;
@@ -495,6 +547,27 @@ export function checkObjectAllowance(
495
547
  }
496
548
  notCustomerWritten(s.waived, `${sp}.waived`, "whether it spends a use");
497
549
  }
550
+ if (s.released !== undefined) {
551
+ if (!s.returnIn.includes(s.released)) {
552
+ contract(
553
+ `${sp}.released`,
554
+ `"${s.released}" must be one of returnIn: a released record gives its use back`,
555
+ );
556
+ } else if (object.states) {
557
+ for (const from of s.spendIn) {
558
+ const ok = object.states.moves.some(
559
+ (move) =>
560
+ move.to === s.released && moveOrigins(move).includes(from) && move.by.includes("host"),
561
+ );
562
+ if (!ok) {
563
+ contract(
564
+ `${sp}.released`,
565
+ `A move from "${from}" into "${s.released}" by the host must be declared: the host releases it`,
566
+ );
567
+ }
568
+ }
569
+ }
570
+ }
498
571
  if (s.movedFrom) {
499
572
  const rel = fieldOf(object, s.movedFrom.field);
500
573
  if (rel?.type !== "relation" || rel.many || (rel.to !== `${m.id}.${name}` && rel.to !== name)) {
@@ -503,6 +576,23 @@ export function checkObjectAllowance(
503
576
  `"${s.movedFrom.field}" must be a relation field (one record) to ${m.id}.${name}`,
504
577
  );
505
578
  }
579
+ for (const f of s.movedFrom.fixed ?? []) {
580
+ if (!fieldOf(object, f))
581
+ contract(`${sp}.movedFrom.fixed`, `"${f}" is not a field of ${name}`);
582
+ }
583
+ if (s.movedFrom.anchor) {
584
+ const { field, from } = s.movedFrom.anchor;
585
+ const a = fieldOf(object, field);
586
+ if (a?.type !== "datetime" || a.many || !a.readOnly) {
587
+ contract(
588
+ `${sp}.movedFrom.anchor.field`,
589
+ `"${field}" must be a read-only datetime field of ${name}: the host sets it`,
590
+ );
591
+ }
592
+ if (fieldOf(object, from)?.type !== "datetime") {
593
+ contract(`${sp}.movedFrom.anchor.from`, `"${from}" must be a datetime field of ${name}`);
594
+ }
595
+ }
506
596
  if (!s.returnIn.includes(s.movedFrom.state)) {
507
597
  contract(
508
598
  `${sp}.movedFrom.state`,
@@ -4,13 +4,18 @@
4
4
  // to add, the step name that is repeated.
5
5
  import {
6
6
  type AutomationManifest,
7
+ type Duration,
7
8
  durationMs,
9
+ MAX_MOMENT_MINUTES,
8
10
  type Recipient,
9
11
  type ValueMatch,
10
12
  } from "./automation.ts";
11
13
  import type { ViewFilter } from "./contract.ts";
12
14
  import type { FieldTypeName } from "./field-types.ts";
13
- import type { ExtensionManifest } from "./manifest.ts";
15
+ import { checkFormula } from "./formula/compile.ts";
16
+ // A function, read at call time: manifest.ts imports this file too.
17
+ import { type ExtensionManifest, objectFormulaEnvironment } from "./manifest.ts";
18
+ import { resolveFieldPath } from "./states.ts";
14
19
 
15
20
  /** Waits in one run (sleeps plus waitForEvent timeouts) add up to at most this. */
16
21
  export const MAX_TOTAL_WAIT_DAYS = 365;
@@ -137,9 +142,20 @@ function fieldsOf(
137
142
  if (object.startsWith(`${m.id}.`)) {
138
143
  const own = m.objects[object.slice(m.id.length + 1)];
139
144
  if (!own) return null;
145
+ // A formula whose value is a date or a time counts as one (ADR 0706): a date-relative trigger
146
+ // on it reads its rec_* column, as on any date field (a procedure's next review).
147
+ const env = objectFormulaEnvironment(own);
148
+ const typeOf = (name: string, f: (typeof own.fields)[string]): FieldTypeName => {
149
+ if (f.type !== "formula") return f.type;
150
+ const compiled = checkFormula(f.expression ?? "", { fields: env }, name);
151
+ return compiled.ok &&
152
+ (compiled.formula.type === "date" || compiled.formula.type === "datetime")
153
+ ? compiled.formula.type
154
+ : f.type;
155
+ };
140
156
  return {
141
157
  ...RECORD_FIELDS,
142
- ...Object.fromEntries(Object.entries(own.fields).map(([name, f]) => [name, f.type])),
158
+ ...Object.fromEntries(Object.entries(own.fields).map(([name, f]) => [name, typeOf(name, f)])),
143
159
  };
144
160
  }
145
161
  const core = CORE_AUTOMATION_FIELDS[object] ?? BASE_AUTOMATION_FIELDS[object];
@@ -237,6 +253,73 @@ function filterFields(filter: ViewFilter): string[] {
237
253
  const isStageType = (match: ValueMatch | undefined): boolean =>
238
254
  typeof match === "object" && match !== null && "stageType" in match;
239
255
 
256
+ /**
257
+ * A `dateRelative` trigger's minutes read per record (ADR 0570): `field` is a number field this
258
+ * extension declares on the trigger object or one relation away, `setting` one of its number
259
+ * settings, and each declares a `max` of at most a week, which bounds the records the host reads.
260
+ */
261
+ function checkMomentMinutes(
262
+ ctx: AutomationCheckContext,
263
+ object: string | null,
264
+ minutes: { field?: string; setting?: string },
265
+ path: string,
266
+ ): void {
267
+ const m = ctx.manifest;
268
+ const { contract } = ctx;
269
+ const capped = (max: number | undefined) => max !== undefined && max <= MAX_MOMENT_MINUTES;
270
+ if (minutes.field !== undefined) {
271
+ const own = object?.startsWith(`${m.id}.`) ? m.objects[object.slice(m.id.length + 1)] : null;
272
+ const field =
273
+ own && minutes.field.split(".").length <= 2
274
+ ? resolveFieldPath(m, own, minutes.field)
275
+ : undefined;
276
+ if (!own) {
277
+ contract(
278
+ `${path}.field`,
279
+ "Minutes read from a field need a trigger object of this extension",
280
+ );
281
+ } else if (field?.type !== "number") {
282
+ contract(
283
+ `${path}.field`,
284
+ `"${minutes.field}" must be a number field of ${object} or one relation away, declared by ${m.id}`,
285
+ );
286
+ } else if (!capped(field.max)) {
287
+ contract(
288
+ `${path}.field`,
289
+ `"${minutes.field}" must declare a max of at most ${MAX_MOMENT_MINUTES}`,
290
+ );
291
+ }
292
+ }
293
+ if (minutes.setting !== undefined) {
294
+ const setting = Object.hasOwn(m.settings ?? {}, minutes.setting)
295
+ ? m.settings?.[minutes.setting]
296
+ : undefined;
297
+ if (setting?.type !== "number") {
298
+ contract(`${path}.setting`, `"${minutes.setting}" must be a number setting of ${m.id}`);
299
+ } else if (!capped(setting.max)) {
300
+ contract(
301
+ `${path}.setting`,
302
+ `"${minutes.setting}" must declare a max of at most ${MAX_MOMENT_MINUTES}`,
303
+ );
304
+ }
305
+ }
306
+ }
307
+
308
+ /**
309
+ * True when `object` is of an extension in `onlyWith` that is not installed (no object of it is
310
+ * `known`): what an automation running only with it names of it is checked once it is (ADR 0812).
311
+ */
312
+ export function laterObject(
313
+ onlyWith: readonly string[],
314
+ known: ReadonlySet<string>,
315
+ object: string,
316
+ ): boolean {
317
+ const ext = object.split(".")[0] as string;
318
+ if (!object.includes(".") || !onlyWith.includes(ext)) return false;
319
+ for (const name of known) if (name.startsWith(`${ext}.`)) return false;
320
+ return true;
321
+ }
322
+
240
323
  /** Reports problems with `automations.<name>` through `ctx.contract`. */
241
324
  export function checkAutomation(
242
325
  ctx: AutomationCheckContext,
@@ -251,6 +334,10 @@ export function checkAutomation(
251
334
  const canWrite = (object: string) => own(object) || perms.write.includes(object);
252
335
  const canRead = (object: string) => canWrite(object) || perms.read.includes(object);
253
336
  const trigger = automation.trigger;
337
+ // An object of an extension the automation runs only with (ADR 0812) is unknown while that
338
+ // extension is not installed: it is checked when it is, and the automation waits until then.
339
+ const known = (object: string) =>
340
+ ctx.known.has(object) || laterObject(automation.onlyWith ?? [], ctx.known, object);
254
341
  const object = triggerObject(trigger);
255
342
  const base = object !== null && Object.hasOwn(BASE_AUTOMATION_FIELDS, object);
256
343
  const fields = object && (ctx.known.has(object) || base) ? fieldsOf(ctx, object) : null;
@@ -262,6 +349,15 @@ export function checkAutomation(
262
349
  if (!NAME_RE.test(name)) {
263
350
  contract(path, `Automation name "${name}" must be camelCase letters and digits, e.g. wonDeal`);
264
351
  }
352
+ // 0. The extensions it runs only with: never itself, each once, none it already requires.
353
+ (automation.onlyWith ?? []).forEach((id, i) => {
354
+ const at = `${path}.onlyWith.${i}`;
355
+ if (id === m.id) contract(at, "An automation of an extension always runs with it");
356
+ else if ((automation.onlyWith ?? []).indexOf(id) !== i) contract(at, `"${id}" is listed twice`);
357
+ else if (m.requires?.includes(id)) {
358
+ contract(at, `The extension requires ${id}, so it is always installed: remove it here`);
359
+ }
360
+ });
265
361
  // 1. The trigger.
266
362
  if (base && !perms.operations.includes(`${object}.get`)) {
267
363
  contract(
@@ -269,7 +365,7 @@ export function checkAutomation(
269
365
  `An automation started by ${object} reads it: add "${object}.get" to permissions.operations`,
270
366
  );
271
367
  }
272
- if (object !== null && !ctx.known.has(object) && !base) {
368
+ if (object !== null && !known(object) && !base) {
273
369
  contract(
274
370
  `${path}.trigger.object`,
275
371
  `Unknown object "${object}". Use a core object (person, organisation, task, activity) or ` +
@@ -326,12 +422,27 @@ export function checkAutomation(
326
422
  case "schedule":
327
423
  for (const issue of cronIssues(trigger.cron)) contract(`${path}.trigger.cron`, issue);
328
424
  break;
329
- case "dateRelative":
330
- requireField(`${path}.trigger.field`, trigger.field, ["date", "datetime"]);
425
+ case "dateRelative": {
426
+ const minutes = trigger.minutesBefore ?? trigger.minutesAfter;
427
+ // A moment some minutes from a field is an instant: the field is a datetime (ADR 0570).
428
+ requireField(
429
+ `${path}.trigger.field`,
430
+ trigger.field,
431
+ minutes === undefined ? ["date", "datetime"] : ["datetime"],
432
+ );
331
433
  if (trigger.zoneField !== undefined) {
332
434
  requireField(`${path}.trigger.zoneField`, trigger.zoneField, ["timezone"]);
333
435
  }
436
+ if (minutes !== undefined && typeof minutes === "object") {
437
+ checkMomentMinutes(
438
+ ctx,
439
+ object,
440
+ minutes,
441
+ `${path}.trigger.${trigger.minutesBefore !== undefined ? "minutesBefore" : "minutesAfter"}`,
442
+ );
443
+ }
334
444
  break;
445
+ }
335
446
  case "manual":
336
447
  break;
337
448
  case "approvalDecided":
@@ -341,7 +452,7 @@ export function checkAutomation(
341
452
  `"${trigger.operation}" is not an operation name, e.g. record.update`,
342
453
  );
343
454
  }
344
- if (trigger.object !== undefined && !ctx.known.has(trigger.object)) {
455
+ if (trigger.object !== undefined && !known(trigger.object)) {
345
456
  contract(`${path}.trigger.object`, `Unknown object "${trigger.object}"`);
346
457
  }
347
458
  break;
@@ -466,7 +577,7 @@ export function checkAutomation(
466
577
  break;
467
578
  default: {
468
579
  for (const read of step.reads ?? []) {
469
- if (!ctx.known.has(read)) {
580
+ if (!known(read)) {
470
581
  contract(`${at}.reads`, `Unknown object "${read}"`);
471
582
  } else if (!canRead(read)) {
472
583
  contract(`${at}.reads`, `Step reads ${read}: add "${read}" to permissions.read`);
@@ -474,7 +585,7 @@ export function checkAutomation(
474
585
  }
475
586
  (step.writes ?? []).forEach((write, j) => {
476
587
  const wat = `${at}.writes.${j}`;
477
- if (!ctx.known.has(write.object)) {
588
+ if (!known(write.object)) {
478
589
  contract(`${wat}.object`, `Unknown object "${write.object}"`);
479
590
  } else if (!canWrite(write.object)) {
480
591
  contract(
@@ -527,7 +638,7 @@ export function checkAutomation(
527
638
 
528
639
  function safeDuration(duration: number | string): number | null {
529
640
  try {
530
- return durationMs(duration as never);
641
+ return durationMs(duration as Duration);
531
642
  } catch {
532
643
  return null;
533
644
  }
@@ -15,6 +15,7 @@ import {
15
15
  type FilterOp,
16
16
  GATEKEEPER_MODULES,
17
17
  type GatekeeperModuleName,
18
+ STAGE_TYPES,
18
19
  type StageType,
19
20
  type ViewFilter,
20
21
  } from "./contract.ts";
@@ -35,13 +36,15 @@ const UNIT_MS: Record<string, number> = {
35
36
  week: 604_800_000,
36
37
  };
37
38
 
39
+ const DURATION_RE = /^\s*(\d+(?:\.\d+)?)\s+(second|minute|hour|day|week)s?\s*$/;
40
+
38
41
  /** Milliseconds in a duration. Throws on a malformed one. */
39
42
  export function durationMs(duration: Duration): number {
40
43
  if (typeof duration === "number") {
41
44
  if (!Number.isFinite(duration) || duration < 0) throw new Error("Durations are >= 0 ms");
42
45
  return duration;
43
46
  }
44
- const match = /^\s*(\d+(?:\.\d+)?)\s+(second|minute|hour|day|week)s?\s*$/.exec(duration);
47
+ const match = DURATION_RE.exec(duration);
45
48
  if (!match) throw new Error(`"${duration}" is not a duration like "3 days" or "90 minutes"`);
46
49
  return Math.round(Number(match[1]) * (UNIT_MS[match[2] as string] as number));
47
50
  }
@@ -122,11 +125,22 @@ export type AutomationTrigger =
122
125
  * of `object`; 0 is the day itself. Evaluated once a day, in the automation timezone; or,
123
126
  * with `zoneField`, in each record's own time zone (ADR 0460): the day of the date and
124
127
  * "today" are both that zone's, and the run starts in the first hour of that local day.
128
+ *
129
+ * Or, instead of `offsetDays`, `minutesBefore` or `minutesAfter` a datetime field (ADR
130
+ * 0570): the run starts within about a minute of that moment, once per record and value of
131
+ * the field (a record whose time changes is due again at its new time). The minutes may be a
132
+ * number, or read per record (a number field of the record or one relation away, else the
133
+ * extension's number setting), as a window's are (ADR 0505). A moment missed by more than
134
+ * 15 minutes (a record made after it) is not run.
125
135
  */
126
136
  type: "dateRelative";
127
137
  object: string;
128
138
  field: string;
129
- offsetDays: number;
139
+ offsetDays?: number;
140
+ /** Minutes before the datetime field (ADR 0570); not with `offsetDays` or `minutesAfter`. */
141
+ minutesBefore?: MomentMinutes;
142
+ /** Minutes after the datetime field (ADR 0570); not with `offsetDays` or `minutesBefore`. */
143
+ minutesAfter?: MomentMinutes;
130
144
  /** A `timezone` field of `object`: count days in the zone each record names. */
131
145
  zoneField?: string;
132
146
  }
@@ -177,6 +191,17 @@ export type AutomationTrigger =
177
191
  from?: "person" | "organisation" | "either";
178
192
  };
179
193
 
194
+ /**
195
+ * A `dateRelative` trigger's minutes (ADR 0570): a number (0 to 10,080, a week), or a number read
196
+ * per record: `field`, a number field of the trigger object or one relation away that this
197
+ * extension declares (`classType.reminderMinutes`), and when it is empty `setting`, this
198
+ * extension's number setting. The field and the setting declare a `max` of at most 10,080.
199
+ */
200
+ export type MomentMinutes = number | { field?: string; setting?: string };
201
+
202
+ /** The most minutes a `dateRelative` trigger's moment may be from its field (a week). */
203
+ export const MAX_MOMENT_MINUTES = 10_080;
204
+
180
205
  export type AutomationTriggerType = AutomationTrigger["type"];
181
206
  export const AUTOMATION_TRIGGER_TYPES = [
182
207
  "record",
@@ -290,7 +315,10 @@ export type OnRejected = "stop" | "continue" | { notify: Recipient; message?: st
290
315
 
291
316
  /** Per-automation limits, within the host's maxima (Settings shows both). */
292
317
  export interface AutomationRails {
293
- /** Default 60. Above it the automation auto-pauses and admins are notified. */
318
+ /**
319
+ * Default 60. Runs above it wait their turn and start on the next minutes' ticks, never dropped
320
+ * (ADR 0573); only a backlog of thousands (a runaway) pauses the automation.
321
+ */
294
322
  maxRunsPerMinute?: number;
295
323
  /** Default 500 writes an hour across all its runs. */
296
324
  maxWritesPerHour?: number;
@@ -306,6 +334,11 @@ export interface AutomationEvent {
306
334
  /** `<extension>.<automation>` */
307
335
  automation: string;
308
336
  runId: string;
337
+ /**
338
+ * A retry's first run: the run its chain of retries began with (ADR 0574). Key a send by it
339
+ * (`originalRunId ?? runId`) so a retried run never sends again what an earlier one sent.
340
+ */
341
+ originalRunId?: string;
309
342
  trigger: AutomationTriggerType;
310
343
  /** The trigger record (record, fieldChanged, dateRelative, manual), as read when the run started. */
311
344
  record?: {
@@ -399,6 +432,16 @@ export interface AutomationSpec<T extends AutomationTrigger = AutomationTrigger>
399
432
  * first install reads it; after that, on or off is the person's choice.
400
433
  */
401
434
  enabled?: boolean;
435
+ /**
436
+ * Other extensions, by id, this automation runs only with (ADR 0812): the extension installs
437
+ * without them, and the automation is listed as waiting and starts no run until every one is
438
+ * installed and on. Its trigger, steps and permissions may name their objects; those are
439
+ * checked at this extension's next install or upgrade while they are installed (`cos ext check`
440
+ * installs them from the directories beside it first), and listed as broken if one does not
441
+ * exist. Use it for one automation that needs another pack; `requires` makes the whole
442
+ * extension need it.
443
+ */
444
+ onlyWith?: readonly string[];
402
445
  run(event: AutomationEvent, step: AutomationStepApi, ctx: AutomationContext): Promise<unknown>;
403
446
  }
404
447
 
@@ -415,12 +458,25 @@ const scalar = z.union([z.string().max(500), z.number(), z.boolean(), z.null()])
415
458
  export const valueMatchSchema = z.union([
416
459
  scalar,
417
460
  z.object({ in: z.array(scalar).min(1).max(50) }).strict(),
418
- z.object({ stageType: z.enum(["open", "won", "lost"]) }).strict(),
461
+ z.object({ stageType: z.enum(STAGE_TYPES) }).strict(),
419
462
  ]);
420
463
 
421
464
  const objectName = z.string().min(1).max(80);
422
465
  const fieldName = z.string().min(1).max(80);
423
466
 
467
+ const momentMinutesSchema = z.union([
468
+ z.number().int().min(0).max(MAX_MOMENT_MINUTES),
469
+ z
470
+ .object({
471
+ field: z.string().min(1).max(200).optional(),
472
+ setting: z.string().min(1).max(80).optional(),
473
+ })
474
+ .strict()
475
+ .refine((m) => m.field !== undefined || m.setting !== undefined, {
476
+ message: "name a field, a setting or both",
477
+ }),
478
+ ]);
479
+
424
480
  export const automationTriggerSchema = z.discriminatedUnion("type", [
425
481
  z
426
482
  .object({
@@ -446,10 +502,20 @@ export const automationTriggerSchema = z.discriminatedUnion("type", [
446
502
  type: z.literal("dateRelative"),
447
503
  object: objectName,
448
504
  field: fieldName,
449
- offsetDays: z.number().int().min(-365).max(365),
505
+ offsetDays: z.number().int().min(-365).max(365).optional(),
506
+ minutesBefore: momentMinutesSchema.optional(),
507
+ minutesAfter: momentMinutesSchema.optional(),
450
508
  zoneField: fieldName.optional(),
451
509
  })
452
- .strict(),
510
+ .strict()
511
+ .refine(
512
+ (t) =>
513
+ [t.offsetDays, t.minutesBefore, t.minutesAfter].filter((v) => v !== undefined).length === 1,
514
+ { message: "give exactly one of offsetDays, minutesBefore and minutesAfter" },
515
+ )
516
+ .refine((t) => t.zoneField === undefined || t.offsetDays !== undefined, {
517
+ message: "zoneField counts days: use it with offsetDays only",
518
+ }),
453
519
  z
454
520
  .object({
455
521
  type: z.literal("manual"),
@@ -494,10 +560,7 @@ export const automationConnectionSchema = z
494
560
  })
495
561
  .strict();
496
562
 
497
- export const durationSchema = z.union([
498
- z.number().int().min(0),
499
- z.string().regex(/^\s*\d+(?:\.\d+)?\s+(second|minute|hour|day|week)s?\s*$/),
500
- ]);
563
+ export const durationSchema = z.union([z.number().int().min(0), z.string().regex(DURATION_RE)]);
501
564
 
502
565
  export const recipientSchema = z.union([
503
566
  z.literal("admins"),
@@ -618,6 +681,11 @@ export const automationManifestSchema = z.object({
618
681
  rails: automationRailsSchema.optional(),
619
682
  connections: z.array(automationConnectionSchema).max(10).optional(),
620
683
  enabled: z.boolean().optional(),
684
+ onlyWith: z
685
+ .array(z.string().regex(/^[a-z][a-z0-9]*$/))
686
+ .min(1)
687
+ .max(5)
688
+ .optional(),
621
689
  });
622
690
  export type AutomationManifest = z.infer<typeof automationManifestSchema>;
623
691
 
@@ -48,6 +48,22 @@ export function checkObjectBehaviour(
48
48
  const stages = object.stages;
49
49
  if (stages) {
50
50
  const sp = `${path}.stages`;
51
+ // Fields the stage behaviour keeps itself: requiring one either always holds or, for a
52
+ // closed date on an open stage, never can (the behaviour clears it first). A status or closed
53
+ // date that is not read-only is reported as such below, once.
54
+ const kept = new Set(
55
+ [
56
+ ...[stages.status, stages.closedDate].filter((f) => f && fieldOf(f)?.readOnly),
57
+ stages.probability?.field,
58
+ stages.probability?.overridden,
59
+ ].filter((f): f is string => f !== undefined),
60
+ );
61
+ const requirable = (local: string) => {
62
+ const field = fieldOf(local);
63
+ return field !== undefined && field.type !== "formula" && local !== stages.field;
64
+ };
65
+ const keptMessage = (local: string) =>
66
+ `"${local}" is kept by the stage behaviour itself and cannot be required`;
51
67
  const stageTarget = relationTo(fieldOf(stages.field));
52
68
  const stageObject = ownObject(stageTarget);
53
69
  if (!stageObject) {
@@ -84,13 +100,16 @@ export function checkObjectBehaviour(
84
100
  `"${stages.stage.requiredFields}" must be a multiSelect field of ${stageTarget}`,
85
101
  );
86
102
  } else {
103
+ // A read-only field may be required (ADR 0750): a fact the host sets, such as the
104
+ // time a quote was accepted, which then gates the stage for every actor.
87
105
  for (const option of required.options ?? []) {
88
- const target = fieldOf(option.value);
89
- if (!target || target.type === "formula" || target.readOnly) {
106
+ if (!requirable(option.value)) {
90
107
  contract(
91
108
  `${sp}.stage.requiredFields`,
92
- `Option "${option.value}" must name a writable field of ${name}`,
109
+ `Option "${option.value}" must name a field of ${name} other than a formula or the stage field`,
93
110
  );
111
+ } else if (kept.has(option.value)) {
112
+ contract(`${sp}.stage.requiredFields`, `Option ${keptMessage(option.value)}`);
94
113
  }
95
114
  }
96
115
  }
@@ -175,12 +194,13 @@ export function checkObjectBehaviour(
175
194
  }
176
195
  for (const [type, list] of Object.entries(stages.requiredByType ?? {})) {
177
196
  for (const local of list ?? []) {
178
- const field = fieldOf(local);
179
- if (!field || field.type === "formula" || field.readOnly) {
197
+ if (!requirable(local)) {
180
198
  contract(
181
199
  `${sp}.requiredByType.${type}`,
182
- `"${local}" must be a writable field of ${name}`,
200
+ `"${local}" must be a field of ${name} other than a formula or the stage field`,
183
201
  );
202
+ } else if (kept.has(local)) {
203
+ contract(`${sp}.requiredByType.${type}`, keptMessage(local));
184
204
  }
185
205
  }
186
206
  }