@composable-os/sdk 0.1.0-beta.11 → 0.1.0-beta.13

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 (104) hide show
  1. package/dist/acknowledge.d.ts +38 -0
  2. package/dist/acknowledge.js +30 -0
  3. package/dist/agreements.d.ts +80 -0
  4. package/dist/agreements.js +109 -0
  5. package/dist/allowance.d.ts +47 -5
  6. package/dist/allowance.js +59 -4
  7. package/dist/automation-check.d.ts +6 -1
  8. package/dist/automation-check.js +93 -8
  9. package/dist/automation.d.ts +62 -4
  10. package/dist/automation.js +32 -9
  11. package/dist/behaviour.js +25 -6
  12. package/dist/calendar-entry.d.ts +97 -0
  13. package/dist/calendar-entry.js +180 -0
  14. package/dist/capacity.js +1 -2
  15. package/dist/checklists.d.ts +41 -0
  16. package/dist/checklists.js +75 -0
  17. package/dist/contract.d.ts +495 -26
  18. package/dist/contract.js +21 -3
  19. package/dist/discount.d.ts +135 -0
  20. package/dist/discount.js +281 -0
  21. package/dist/document.d.ts +2 -1
  22. package/dist/document.js +2 -1
  23. package/dist/field-types.d.ts +1 -1
  24. package/dist/field-types.js +5 -0
  25. package/dist/formula/compile.d.ts +15 -0
  26. package/dist/formula/compile.js +9 -0
  27. package/dist/index.d.ts +17 -0
  28. package/dist/index.js +17 -0
  29. package/dist/intake.d.ts +134 -0
  30. package/dist/intake.js +239 -0
  31. package/dist/journey-signals.d.ts +89 -0
  32. package/dist/journey-signals.js +151 -0
  33. package/dist/manifest.d.ts +944 -56
  34. package/dist/manifest.js +1036 -60
  35. package/dist/mine.d.ts +45 -0
  36. package/dist/mine.js +119 -0
  37. package/dist/occupies.d.ts +64 -0
  38. package/dist/occupies.js +122 -0
  39. package/dist/questions.d.ts +179 -0
  40. package/dist/questions.js +514 -0
  41. package/dist/recurring.d.ts +33 -4
  42. package/dist/recurring.js +50 -3
  43. package/dist/restricted-fields.d.ts +15 -0
  44. package/dist/restricted-fields.js +97 -0
  45. package/dist/rich-text.d.ts +22 -0
  46. package/dist/rich-text.js +91 -0
  47. package/dist/routine-mail.d.ts +400 -0
  48. package/dist/routine-mail.js +955 -0
  49. package/dist/runtime.d.ts +5 -11
  50. package/dist/runtime.js +21 -11
  51. package/dist/screens.d.ts +3 -0
  52. package/dist/screens.js +74 -0
  53. package/dist/sellable.d.ts +153 -2
  54. package/dist/sellable.js +188 -0
  55. package/dist/slug.d.ts +2 -0
  56. package/dist/slug.js +6 -2
  57. package/dist/staffed.d.ts +178 -0
  58. package/dist/staffed.js +287 -0
  59. package/dist/states.d.ts +17 -1
  60. package/dist/states.js +48 -20
  61. package/dist/stock.d.ts +129 -0
  62. package/dist/stock.js +205 -0
  63. package/dist/team.d.ts +28 -0
  64. package/dist/team.js +52 -0
  65. package/dist/testing.d.ts +22 -1
  66. package/dist/testing.js +47 -5
  67. package/dist/worked-on.d.ts +42 -0
  68. package/dist/worked-on.js +79 -0
  69. package/package.json +9 -1
  70. package/src/acknowledge.ts +100 -0
  71. package/src/agreements.ts +185 -0
  72. package/src/allowance.ts +98 -8
  73. package/src/automation-check.ts +120 -9
  74. package/src/automation.ts +78 -10
  75. package/src/behaviour.ts +26 -6
  76. package/src/calendar-entry.ts +258 -0
  77. package/src/capacity.ts +1 -2
  78. package/src/checklists.ts +118 -0
  79. package/src/contract.ts +489 -27
  80. package/src/discount.ts +408 -0
  81. package/src/document.ts +4 -2
  82. package/src/field-types.ts +5 -0
  83. package/src/formula/compile.ts +10 -0
  84. package/src/index.ts +17 -0
  85. package/src/intake.ts +380 -0
  86. package/src/journey-signals.ts +215 -0
  87. package/src/manifest.ts +1236 -65
  88. package/src/mine.ts +161 -0
  89. package/src/occupies.ts +192 -0
  90. package/src/questions.ts +681 -0
  91. package/src/recurring.ts +90 -9
  92. package/src/restricted-fields.ts +129 -0
  93. package/src/rich-text.ts +112 -0
  94. package/src/routine-mail.ts +1272 -0
  95. package/src/runtime.ts +25 -12
  96. package/src/screens.ts +91 -0
  97. package/src/sellable.ts +344 -0
  98. package/src/slug.ts +7 -2
  99. package/src/staffed.ts +474 -0
  100. package/src/states.ts +68 -26
  101. package/src/stock.ts +332 -0
  102. package/src/team.ts +83 -0
  103. package/src/testing.ts +70 -6
  104. package/src/worked-on.ts +134 -0
@@ -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
  }
package/src/automation.ts CHANGED
@@ -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
 
package/src/behaviour.ts CHANGED
@@ -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
  }