@composable-os/cli 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 (166) hide show
  1. package/dist/{accounts-UHYLCLEY.js → accounts-GOCNY6WI.js} +17 -13
  2. package/dist/app-RPRZMLU5.js +43 -0
  3. package/dist/app-upload-YJVEKZC6.js +198 -0
  4. package/dist/{blocks-5IFU25J6.js → blocks-DE4RRWPJ.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-ZAWES2UD.js → chunk-6CM3WZG5.js} +13 -2483
  10. package/dist/{chunk-7D4GKZOX.js → chunk-CIBJGB5H.js} +422 -75
  11. package/dist/chunk-EPDTPGZJ.js +330 -0
  12. package/dist/{chunk-LAAL4YGR.js → chunk-HAYF4G5V.js} +66 -23
  13. package/dist/chunk-HCG6T53D.js +61904 -0
  14. package/dist/{chunk-K34UKWEI.js → chunk-JX4IFWNT.js} +64 -32
  15. package/dist/{chunk-6XTU2MTP.js → chunk-KFHKNXGH.js} +632 -418
  16. package/dist/chunk-KMFMD52Z.js +13276 -0
  17. package/dist/{chunk-E4WCYTCT.js → chunk-LX2TTLVY.js} +174 -55
  18. package/dist/{chunk-GYTEW66E.js → chunk-O3R4FS2J.js} +1 -1
  19. package/dist/{chunk-E64SG24J.js → chunk-Q6Y45DY6.js} +25 -2
  20. package/dist/{chunk-MBIKVRAC.js → chunk-QJZGYJVV.js} +823 -44
  21. package/dist/{chunk-PDD2ETVF.js → chunk-QQ3YSL5F.js} +172 -16
  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-NNUCHQ2Y.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
@@ -0,0 +1,332 @@
1
+ // The `stock` behaviour (stage 37, ADR 0680): an object declares that its records are things
2
+ // counted on a shelf (a variant of an item in a shop), and the host keeps how many there are, from
3
+ // a ledger nobody edits, never selling more than there is, for every actor. Its declaration, its
4
+ // manifest schema and its contract checks live here; the host's side is packages/core/src/stock/.
5
+ import { z } from "zod";
6
+ import type { ExtensionManifest, FieldManifest, ObjectManifest } from "./manifest.ts";
7
+ import { moveOrigins } from "./states.ts";
8
+
9
+ /**
10
+ * What customers and the public are told about a record's stock (staff always see the numbers):
11
+ * `availability` (the default), "In stock" or "Sold out"; `low`, "only N left" at or below
12
+ * `lowAt`; `exact`, the number available.
13
+ */
14
+ export const STOCK_SHOW = ["exact", "low", "availability"] as const;
15
+ export type StockShow = (typeof STOCK_SHOW)[number];
16
+
17
+ /**
18
+ * The read-only values the host adds to every record of an object with stock: on hand (what is
19
+ * on the shelf, sold units gone), held (by orders being paid for) and available (on hand less
20
+ * held). An object with stock cannot have fields of these names.
21
+ */
22
+ export const STOCK_VALUES = ["onHand", "held", "available"] as const;
23
+
24
+ /**
25
+ * The kinds of movement in the ledger (ADR 0680). The host writes `opening`, `adjusted` and
26
+ * `sold`; a record's `stockMoves` writes `received`, `written_off`, `used` and `counted` (ADR
27
+ * 0681); a return (stage 37 step 4) writes `returned`.
28
+ */
29
+ export const STOCK_MOVEMENT_KINDS = [
30
+ "opening",
31
+ "received",
32
+ "sold",
33
+ "returned",
34
+ "written_off",
35
+ "counted",
36
+ "adjusted",
37
+ "used",
38
+ ] as const;
39
+ export type StockMovementKind = (typeof STOCK_MOVEMENT_KINDS)[number];
40
+
41
+ /**
42
+ * A number of things on hand (ADR 0680). The host keeps the count from a ledger of movements
43
+ * (opening stock, a correction, a sale) and nobody types it: an order line holds its quantity
44
+ * while the order is unpaid and sells it when it is paid, refused by the database past what is
45
+ * available, in the order's own batch. A refund changes nothing in stock; a return does.
46
+ *
47
+ * - `reorderAt` is this object's number field holding the reorder level (a record at or below it
48
+ * is low); `reorderQty` the number field holding how many to order then.
49
+ * - `show` is what customers and the public are told (default `availability`); `lowAt` is the
50
+ * threshold for `low`.
51
+ * - `notify` is one of this extension's tool permissions: when a write takes a record's on hand to
52
+ * or below its reorder level, the staff who hold it are told, once until it rises above again
53
+ * (ADR 0681). Without it, the admins are told. It needs `reorderAt`.
54
+ * - The object is sellable goods (`sellable.goods`, ADR 0682), or the object a `stockMoves` of
55
+ * this extension moves (a part nobody sells still has stock).
56
+ *
57
+ * An object with stock is not also a capacity (its counter is the stock's), and is not bought by
58
+ * deposit, by subscription or by moving a record (`sellable.deposit`, `recurring`, `moves`).
59
+ */
60
+ export interface StockSpec {
61
+ reorderAt?: string;
62
+ reorderQty?: string;
63
+ show?: StockShow;
64
+ lowAt?: number;
65
+ notify?: string;
66
+ }
67
+
68
+ const fieldName = z.string().max(40);
69
+
70
+ export const stockManifestSchema = z
71
+ .object({
72
+ reorderAt: fieldName.optional(),
73
+ reorderQty: fieldName.optional(),
74
+ show: z.enum(STOCK_SHOW).optional(),
75
+ lowAt: z.number().int().min(1).max(1_000_000).optional(),
76
+ notify: z.string().max(80).optional(),
77
+ })
78
+ .strict();
79
+ export type StockManifest = z.infer<typeof stockManifestSchema>;
80
+
81
+ /** Reports problems with `objects.<name>.stock` through `contract`. */
82
+ export function checkObjectStock(
83
+ m: ExtensionManifest,
84
+ name: string,
85
+ object: ObjectManifest,
86
+ contract: (path: string, message: string) => void,
87
+ ): void {
88
+ const stock = object.stock;
89
+ if (!stock) return;
90
+ const path = `objects.${name}.stock`;
91
+ const fieldOf = (local: string): FieldManifest | undefined =>
92
+ Object.hasOwn(object.fields, local) ? object.fields[local] : undefined;
93
+ for (const key of ["reorderAt", "reorderQty"] as const) {
94
+ const local = stock[key];
95
+ if (local === undefined) continue;
96
+ const field = fieldOf(local);
97
+ if (field?.type !== "number" || field.many) {
98
+ contract(`${path}.${key}`, `"${local}" must be a number field of ${name}`);
99
+ }
100
+ }
101
+ for (const reserved of STOCK_VALUES) {
102
+ if (Object.hasOwn(object.fields, reserved)) {
103
+ contract(
104
+ `objects.${name}.fields.${reserved}`,
105
+ `"${reserved}" is a value the host adds to an object with stock; rename the field`,
106
+ );
107
+ }
108
+ }
109
+ if (object.capacity) {
110
+ contract(path, "An object has stock or a capacity, not both: stock keeps its own counter");
111
+ }
112
+ const sellable = object.sellable;
113
+ if (sellable) {
114
+ for (const key of ["deposit", "recurring", "moves"] as const) {
115
+ if (sellable[key] !== undefined) {
116
+ contract(
117
+ `objects.${name}.sellable.${key}`,
118
+ `A thing in stock is sold whole, on an order: it has no sellable.${key}`,
119
+ );
120
+ }
121
+ }
122
+ }
123
+ if (stock.lowAt !== undefined && stock.show !== "low") {
124
+ contract(`${path}.lowAt`, 'lowAt is the threshold of show: "low"');
125
+ }
126
+ if (stock.show === "low" && stock.lowAt === undefined) {
127
+ contract(`${path}.lowAt`, 'show: "low" needs lowAt, the number at or below which it says so');
128
+ }
129
+ if (stock.notify !== undefined) {
130
+ if (stock.reorderAt === undefined) {
131
+ contract(`${path}.notify`, "notify tells staff of a reorder level: declare reorderAt");
132
+ }
133
+ const permissions = Object.values(m.tools).flatMap((tool) =>
134
+ typeof tool.permission === "string" ? [tool.permission] : [...(tool.permission ?? [])],
135
+ );
136
+ if (!permissions.includes(stock.notify)) {
137
+ contract(
138
+ `${path}.notify`,
139
+ `"${stock.notify}" is not the permission of any of this extension's tools (tools.<name>.permission)`,
140
+ );
141
+ }
142
+ }
143
+ const moved = Object.values(m.objects).some(
144
+ (other) => other.stockMoves && relationTarget(m, other, other.stockMoves.on) === name,
145
+ );
146
+ if (sellable && !sellable.goods) {
147
+ // A thing in stock that is sold is goods (ADR 0682): its orders have a channel and a delivery.
148
+ contract(
149
+ `objects.${name}.sellable.goods`,
150
+ `${name} has stock and is sold: declare sellable.goods (where it is sold)`,
151
+ );
152
+ }
153
+ if (!sellable && !moved) {
154
+ contract(
155
+ path,
156
+ `${name} has stock but is neither sellable goods nor moved by a stockMoves of this extension`,
157
+ );
158
+ }
159
+ }
160
+
161
+ // --- stockMoves (ADR 0681) ------------------------------------------------------------------------
162
+
163
+ /** How a record's move changes stock: units in, units out, or on hand set to a counted number. */
164
+ export const STOCK_MOVES = ["add", "remove", "set"] as const;
165
+ export type StockMove = (typeof STOCK_MOVES)[number];
166
+
167
+ /** The ledger kinds each move may write; the first is the default. */
168
+ export const STOCK_MOVE_KINDS = {
169
+ add: ["received"],
170
+ remove: ["written_off", "used"],
171
+ set: ["counted"],
172
+ } as const satisfies Record<StockMove, readonly StockMovementKind[]>;
173
+
174
+ /**
175
+ * A record's state moves stock (ADR 0681): when it enters `when`, the host writes a movement of
176
+ * `quantity` on the record `on` points to (an object of this extension with stock), in the batch
177
+ * of the write that makes the move, for every actor. A receipt `received` adds; a write-off
178
+ * removes; a count line `set`s on hand to the number counted, the difference worked out when the
179
+ * batch commits.
180
+ *
181
+ * - `when` is a state of this object, or with `through`, of the record `through` points to (a
182
+ * relation, one record, to another object of this extension with states): that record entering
183
+ * `when` moves the stock of every live record of this object pointing to it, in one batch (a
184
+ * count applied moves each of its lines). No declared move leaves `when`: stock moves once.
185
+ * - `kind` is the ledger's kind: `received` for add; `written_off` (default) or `used` for
186
+ * remove; `counted` for set.
187
+ * - `unitCost` (add only) is a number field of the cost of one, in minor units; `note` a text
188
+ * field the ledger keeps.
189
+ * - Every declared move into `when` is by `["host"]`, with the `tools` (humanOnly or
190
+ * personApproves, with a permission) a person makes it through; nothing is created in `when`
191
+ * but by the host. Moving stock is a person's act: an AI's call of the tool waits for a person.
192
+ * - A quantity is a whole number, above 0 (add, remove) or 0 and above (set). Once moved, `on`,
193
+ * `quantity`, `unitCost` and `note` cannot change, and a moved record's lines cannot be added to
194
+ * or changed: the ledger keeps what moved.
195
+ */
196
+ export interface StockMovesSpec {
197
+ move: StockMove;
198
+ on: string;
199
+ quantity: string;
200
+ when: string;
201
+ through?: string;
202
+ kind?: StockMovementKind;
203
+ unitCost?: string;
204
+ note?: string;
205
+ }
206
+
207
+ export const stockMovesManifestSchema = z
208
+ .object({
209
+ move: z.enum(STOCK_MOVES),
210
+ on: fieldName,
211
+ quantity: fieldName,
212
+ when: z.string().min(1).max(100),
213
+ through: fieldName.optional(),
214
+ kind: z.enum(STOCK_MOVEMENT_KINDS).optional(),
215
+ unitCost: fieldName.optional(),
216
+ note: fieldName.optional(),
217
+ })
218
+ .strict();
219
+ export type StockMovesManifest = z.infer<typeof stockMovesManifestSchema>;
220
+
221
+ /** The local name of the object of this extension a one-record relation field points to. */
222
+ function relationTarget(
223
+ m: ExtensionManifest,
224
+ object: ObjectManifest,
225
+ field: string,
226
+ ): string | undefined {
227
+ const f = Object.hasOwn(object.fields, field) ? object.fields[field] : undefined;
228
+ if (f?.type !== "relation" || f.many || !f.to?.startsWith(`${m.id}.`)) return undefined;
229
+ const local = f.to.slice(m.id.length + 1);
230
+ return Object.hasOwn(m.objects, local) ? local : undefined;
231
+ }
232
+
233
+ /** Reports problems with `objects.<name>.stockMoves` through `contract`. */
234
+ export function checkObjectStockMoves(
235
+ m: ExtensionManifest,
236
+ name: string,
237
+ object: ObjectManifest,
238
+ contract: (path: string, message: string) => void,
239
+ ): void {
240
+ const moves = object.stockMoves;
241
+ if (!moves) return;
242
+ const path = `objects.${name}.stockMoves`;
243
+ const fieldOf = (local: string): FieldManifest | undefined =>
244
+ Object.hasOwn(object.fields, local) ? object.fields[local] : undefined;
245
+ const target = relationTarget(m, object, moves.on);
246
+ if (!target) {
247
+ contract(
248
+ `${path}.on`,
249
+ `"${moves.on}" must be a relation field (one record) to an object of this extension with stock`,
250
+ );
251
+ } else if (!m.objects[target]?.stock) {
252
+ contract(`${path}.on`, `${m.id}.${target} must declare stock for its stock to move`);
253
+ }
254
+ const number = (key: "quantity" | "unitCost") => {
255
+ const local = moves[key];
256
+ if (local === undefined) return;
257
+ const field = fieldOf(local);
258
+ if (field?.type !== "number" || field.many) {
259
+ contract(`${path}.${key}`, `"${local}" must be a number field of ${name}`);
260
+ }
261
+ };
262
+ number("quantity");
263
+ number("unitCost");
264
+ if (moves.unitCost !== undefined && moves.move !== "add") {
265
+ contract(`${path}.unitCost`, "Only what comes in (add) has a unit cost");
266
+ }
267
+ if (moves.note !== undefined) {
268
+ const field = fieldOf(moves.note);
269
+ if (field?.type !== "text" || field.many) {
270
+ contract(`${path}.note`, `"${moves.note}" must be a text field of ${name}`);
271
+ }
272
+ }
273
+ const kinds: readonly string[] = STOCK_MOVE_KINDS[moves.move];
274
+ if (moves.kind !== undefined && !kinds.includes(moves.kind)) {
275
+ contract(
276
+ `${path}.kind`,
277
+ `A ${moves.move} writes ${kinds.map((k) => `"${k}"`).join(" or ")}, not "${moves.kind}"`,
278
+ );
279
+ }
280
+ // Whose state moves it: this object's, or the record `through` points to.
281
+ let owner: string | undefined = name;
282
+ if (moves.through !== undefined) {
283
+ owner = relationTarget(m, object, moves.through);
284
+ if (!owner || owner === name) {
285
+ contract(
286
+ `${path}.through`,
287
+ `"${moves.through}" must be a relation field (one record) to another of this extension's objects`,
288
+ );
289
+ return;
290
+ }
291
+ }
292
+ const states = m.objects[owner]?.states;
293
+ if (!states) {
294
+ contract(
295
+ moves.through === undefined ? path : `${path}.through`,
296
+ `${owner} must declare states: entering "${moves.when}" moves the stock`,
297
+ );
298
+ return;
299
+ }
300
+ const stateField = Object.hasOwn(m.objects[owner]?.fields ?? {}, states.field)
301
+ ? m.objects[owner]?.fields[states.field]
302
+ : undefined;
303
+ if (!(stateField?.options ?? []).some((o) => o.value === moves.when)) {
304
+ contract(`${path}.when`, `"${moves.when}" is not a state of ${owner}`);
305
+ }
306
+ if (states.moves.some((move) => moveOrigins(move).includes(moves.when))) {
307
+ contract(
308
+ `${path}.when`,
309
+ `No move may leave "${moves.when}": stock moves once, when a record enters it`,
310
+ );
311
+ }
312
+ // Moving stock is a person's act with the pack's permission (ADR 0681, the review of #422):
313
+ // the host's alone, and the tools a person calls (ADR 0513), so an assistant's or an MCP
314
+ // client's call of them waits for a person, and no customer, member or automation moves stock
315
+ // by moving a record.
316
+ states.moves.forEach((move, i) => {
317
+ if (move.to !== moves.when) return;
318
+ if (move.by.some((mover) => mover !== "host")) {
319
+ contract(
320
+ `objects.${owner}.states.moves.${i}.by`,
321
+ `Entering "${moves.when}" moves stock: declare it by ["host"] with the tools a person makes it through (states.moves.<n>.tools)`,
322
+ );
323
+ }
324
+ });
325
+ const created = states.create?.in?.[moves.when];
326
+ if (created?.some((mover) => mover !== "host")) {
327
+ contract(
328
+ `objects.${owner}.states.create.in.${moves.when}`,
329
+ `Creating a record in "${moves.when}" moves stock: only the host may; create it in another state and move it through a tool`,
330
+ );
331
+ }
332
+ }
@@ -0,0 +1,83 @@
1
+ // A shipped pack's team (stage 56, ADR 0831; built with Programs' coach role, ADR 0889): the staff
2
+ // named on a live record about a Person look after that Person while the record is live. Its
3
+ // declaration, its manifest schema and its contract checks live here; what a pack role reaches
4
+ // through it (`looksAfter`) is the host's (packages/core/src/pack-role-looks-after.ts).
5
+ import { z } from "zod";
6
+ import type { ExtensionManifest, FieldManifest, ObjectManifest } from "./manifest.ts";
7
+
8
+ /**
9
+ * Who on the staff looks after the Person a record is about (ADR 0831): the accounts in its
10
+ * `staff` user fields, while the record is in one of the `live` states of the object's `states`
11
+ * (every record not in the Trash, when the object has no states). A client's program names their
12
+ * coach: `{ person: "person", staff: ["coach"], live: ["generating", "active"] }`.
13
+ *
14
+ * It gives nothing by itself. A pack role that declares `looksAfter` reaches its objects' records
15
+ * only for the People its holder looks after this way (ADR 0889). Only shipped packs and the
16
+ * org's own extensions declare it: who reaches whose records is access.
17
+ */
18
+ export interface TeamSpec {
19
+ /** A relation (one record) to `person`: whom the record is about. */
20
+ person: string;
21
+ /** `user` fields of this object (one account each, each `personApproves`): who looks after them. */
22
+ staff: readonly string[];
23
+ /** The states of the object's `states` in which the record counts. */
24
+ live?: readonly string[];
25
+ }
26
+
27
+ const fieldName = z.string().max(40);
28
+
29
+ export const teamManifestSchema = z
30
+ .object({
31
+ person: fieldName,
32
+ staff: z.array(fieldName).min(1).max(4),
33
+ live: z.array(z.string().min(1).max(100)).min(1).max(20).optional(),
34
+ })
35
+ .strict();
36
+ export type TeamManifest = z.infer<typeof teamManifestSchema>;
37
+
38
+ /** Reports problems with `objects.<name>.team` through `contract`. */
39
+ export function checkObjectTeam(
40
+ _m: ExtensionManifest,
41
+ name: string,
42
+ object: ObjectManifest,
43
+ contract: (path: string, message: string) => void,
44
+ ): void {
45
+ const team = object.team;
46
+ if (!team) return;
47
+ const at = `objects.${name}.team`;
48
+ const own = (local: string): FieldManifest | undefined =>
49
+ Object.hasOwn(object.fields, local) ? object.fields[local] : undefined;
50
+ const person = own(team.person);
51
+ if (person?.type !== "relation" || person.to !== "person" || person.many) {
52
+ contract(`${at}.person`, `"${team.person}" must be a relation field (one record) to person`);
53
+ }
54
+ for (const [i, field] of team.staff.entries()) {
55
+ const staff = own(field);
56
+ if (staff?.type !== "user" || staff.many) {
57
+ contract(`${at}.staff.${i}`, `"${field}" must be a user field of ${name}`);
58
+ } else if (staff.personApproves !== true) {
59
+ // Naming someone in it opens a pack role's reach to the Person (ADR 0889): a person's
60
+ // choice, never the assistant's, an automation's or code's on its own.
61
+ contract(
62
+ `${at}.staff.${i}`,
63
+ `"${field}" must be a field a person approves (personApproves): who reaches whose records is a person's to change`,
64
+ );
65
+ }
66
+ }
67
+ if (new Set(team.staff).size !== team.staff.length) {
68
+ contract(`${at}.staff`, "Name each field once");
69
+ }
70
+ if (team.live) {
71
+ const states = object.states;
72
+ const known = new Set(
73
+ states ? (own(states.field)?.options ?? []).map((option) => option.value) : [],
74
+ );
75
+ if (!states) {
76
+ contract(`${at}.live`, `${name} has no states: leave live out (every record counts)`);
77
+ } else {
78
+ for (const [i, state] of team.live.entries()) {
79
+ if (!known.has(state)) contract(`${at}.live.${i}`, `"${state}" is not a state of ${name}`);
80
+ }
81
+ }
82
+ }
83
+ }
@@ -28,12 +28,14 @@ import {
28
28
  type NotificationSendInput,
29
29
  notificationInput,
30
30
  } from "./automation.ts";
31
+ import { DEFAULT_WAIT_TIMEOUT, NOTIFY_OPERATION } from "./automation-check.ts";
31
32
  import { type AiModule, type Extension, GATEKEEPER_MODULES, type StartedBy } from "./contract.ts";
32
33
  import { validateDocument } from "./document.ts";
33
34
  import type { ExtensionManifest, ManifestIssue, ValidateOptions } from "./manifest.ts";
34
35
  import { CORE_OBJECT_NAMES, toManifest, validateManifest } from "./manifest.ts";
35
36
  import { checkGrant } from "./permissions.ts";
36
37
  import { documentMaxBytesOf, documentSchemaOf } from "./rich-text.ts";
38
+ import type { RoutineSendInput, RoutineSendResult } from "./routine-mail.ts";
37
39
  import { buildContext, type RawHostModules, runExtension } from "./runtime.ts";
38
40
 
39
41
  type Values = Record<string, unknown> & { id: string };
@@ -63,6 +65,18 @@ export interface TestHostOptions {
63
65
  string,
64
66
  (call: { connectionId: string; resource: string; method: string; args: unknown[] }) => unknown
65
67
  >;
68
+ /**
69
+ * What `ctx.routineMail.send` answers (ADR 0590). Every call is recorded in `routineSends`;
70
+ * with no fake each answers one email sent. The host decides who it goes to and what it says,
71
+ * so a pack's test checks which kind, record, message and values it asked for.
72
+ */
73
+ routineMail?: (send: RoutineSendInput) => RoutineSendResult | Promise<RoutineSendResult>;
74
+ }
75
+
76
+ /** A routine email an automation asked the host to send (`ctx.routineMail.send`). */
77
+ export interface RoutineSend extends RoutineSendInput {
78
+ /** The step it was asked in. */
79
+ step: string | null;
66
80
  }
67
81
 
68
82
  /** A call a tool or automation made through `ctx.gatekeeper(name).call(...)`. */
@@ -99,6 +113,13 @@ export interface AutomationRunOptions {
99
113
  runId?: string;
100
114
  /** `event.test`. Default false: the run writes to the in-memory store. */
101
115
  test?: boolean;
116
+ /** `event.originalRunId`: the run a retry's chain began with (ADR 0574). */
117
+ originalRunId?: string;
118
+ /**
119
+ * How many times a `do` step that throws is run again, as the host's Workflow retries a step
120
+ * (the steps before it are not run again). Default 0: a throw fails the run.
121
+ */
122
+ retries?: number;
102
123
  }
103
124
 
104
125
  export interface AutomationRunResult {
@@ -152,6 +173,8 @@ export interface TestHost {
152
173
  notifications: SentNotification[];
153
174
  /** Every call through a gatekeeper module, in order. */
154
175
  gatekeeperCalls: GatekeeperCall[];
176
+ /** Every routine email asked for, in order (ADR 0590). */
177
+ routineSends: RoutineSend[];
155
178
  /**
156
179
  * Runs automation `name` in memory, start to finish: conditions checked on the trigger
157
180
  * record, waits skipped (and recorded), steps held to the declarations.
@@ -160,7 +183,7 @@ export interface TestHost {
160
183
  /**
161
184
  * Publishes a record of a publishable object as a person would (`record.publish`, which no
162
185
  * tool may call): its content fields become the next version, which `record.version` reads.
163
- * Returns the version's number.
186
+ * Refused outside the object's `publishable.publishIn` states. Returns the version's number.
164
187
  */
165
188
  publish(object: string, id: string): number;
166
189
  }
@@ -221,6 +244,16 @@ export function createTestHost(extension: Extension, options: TestHostOptions =
221
244
  if (!content) throw new ExtensionToolError("invalid_input", `${object} is not publishable`);
222
245
  const row = table(object).get(id);
223
246
  if (!row) throw new ExtensionToolError("not_found", `No ${object} with id ${id}`);
247
+ // Only in the states the object lists (ADR 0810), as the host refuses.
248
+ const spec = manifest.objects[local];
249
+ const stateField = spec?.states?.field;
250
+ const publishIn = spec?.publishable?.publishIn;
251
+ if (publishIn && stateField && !publishIn.includes(String(row[stateField] ?? ""))) {
252
+ throw new ExtensionToolError(
253
+ "invalid_input",
254
+ `${object} ${id} is ${String(row[stateField] ?? "in no state")}: it is published only when ${publishIn.join(" or ")}`,
255
+ );
256
+ }
224
257
  const list = versions.get(`${object}|${id}`) ?? [];
225
258
  const version = list.length + 1;
226
259
  list.push({
@@ -483,7 +516,7 @@ export function createTestHost(extension: Extension, options: TestHostOptions =
483
516
  let observer:
484
517
  | ((operation: string, input: Record<string, unknown>, value: unknown) => void)
485
518
  | null = null;
486
- builtIn["notification.send"] = (input) => {
519
+ builtIn[NOTIFY_OPERATION] = (input) => {
487
520
  const notes: string[] = [];
488
521
  const admins = users.filter((u) => u.role === "admin").map((u) => u.id);
489
522
  const ids: string[] = [];
@@ -616,6 +649,27 @@ export function createTestHost(extension: Extension, options: TestHostOptions =
616
649
  types: async () => "",
617
650
  };
618
651
  }
652
+ const routineSends: RoutineSend[] = [];
653
+ if (has("routine-mail")) {
654
+ raw["routine-mail"] = {
655
+ send: async (input) => {
656
+ const send = structuredClone(input) as RoutineSendInput;
657
+ routineSends.push({ ...send, step: currentStep });
658
+ try {
659
+ const value = options.routineMail
660
+ ? await options.routineMail(send)
661
+ : { sent: 1, held: 0, off: false, none: false };
662
+ return { ok: true, value };
663
+ } catch (error) {
664
+ const e = error as { code?: string; message?: string };
665
+ return {
666
+ ok: false,
667
+ error: { code: e.code ?? "internal", message: e.message ?? String(error) },
668
+ };
669
+ }
670
+ },
671
+ };
672
+ }
619
673
  if (has("ai")) {
620
674
  const ai: AiModule = {
621
675
  summarise: async (text) => String(text).slice(0, 100),
@@ -666,6 +720,7 @@ export function createTestHost(extension: Extension, options: TestHostOptions =
666
720
  const event: AutomationEvent = {
667
721
  automation: `${manifest.id}.${name}`,
668
722
  runId: run.runId ?? "arn_TEST",
723
+ ...(run.originalRunId ? { originalRunId: run.originalRunId } : {}),
669
724
  trigger: automation.trigger.type,
670
725
  ...(run.record && row
671
726
  ? {
@@ -712,7 +767,7 @@ export function createTestHost(extension: Extension, options: TestHostOptions =
712
767
  stepName ? `step ${stepName}` : "run (outside a step)";
713
768
  const notificationsBefore = notifications.length;
714
769
  observer = (operation, input, value) => {
715
- if (operation === "notification.send") {
770
+ if (operation === NOTIFY_OPERATION) {
716
771
  if (!declaresNotify(currentStep)) {
717
772
  result.undeclared.push(`${where(currentStep)} sent a notification (not in its notifies)`);
718
773
  }
@@ -742,7 +797,7 @@ export function createTestHost(extension: Extension, options: TestHostOptions =
742
797
  const n = (notifyCounts.get(key) ?? 0) + 1;
743
798
  notifyCounts.set(key, n);
744
799
  const input = notificationInput(event, to, message, `${key}:${n}`);
745
- const sent = await base.ops.call<{ sent: number }>("notification.send", input);
800
+ const sent = await base.ops.call<{ sent: number }>(NOTIFY_OPERATION, input);
746
801
  return { sent: sent.sent };
747
802
  },
748
803
  };
@@ -764,7 +819,15 @@ export function createTestHost(extension: Extension, options: TestHostOptions =
764
819
  const first = calls.length;
765
820
  currentStep = stepName;
766
821
  try {
767
- const value = await fn();
822
+ let value!: T;
823
+ for (let attempt = 0; ; attempt++) {
824
+ try {
825
+ value = await fn();
826
+ break;
827
+ } catch (error) {
828
+ if (attempt >= (run.retries ?? 0)) throw error;
829
+ }
830
+ }
768
831
  result.steps.push({
769
832
  name: stepName,
770
833
  kind: "do",
@@ -792,7 +855,7 @@ export function createTestHost(extension: Extension, options: TestHostOptions =
792
855
  name: stepName,
793
856
  kind: "waitForEvent",
794
857
  value,
795
- skippedMs: durationMs((step.timeout ?? "7 days") as never),
858
+ skippedMs: durationMs((step.timeout ?? DEFAULT_WAIT_TIMEOUT) as never),
796
859
  calls: [],
797
860
  });
798
861
  return value;
@@ -825,6 +888,7 @@ export function createTestHost(extension: Extension, options: TestHostOptions =
825
888
  records,
826
889
  notifications,
827
890
  gatekeeperCalls,
891
+ routineSends,
828
892
  runAutomation,
829
893
  publish,
830
894
  async runTool<T>(