@composable-os/sdk 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 (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
@@ -0,0 +1,129 @@
1
+ import { z } from "zod";
2
+ import type { ExtensionManifest, ObjectManifest } from "./manifest.ts";
3
+ /**
4
+ * What customers and the public are told about a record's stock (staff always see the numbers):
5
+ * `availability` (the default), "In stock" or "Sold out"; `low`, "only N left" at or below
6
+ * `lowAt`; `exact`, the number available.
7
+ */
8
+ export declare const STOCK_SHOW: readonly ["exact", "low", "availability"];
9
+ export type StockShow = (typeof STOCK_SHOW)[number];
10
+ /**
11
+ * The read-only values the host adds to every record of an object with stock: on hand (what is
12
+ * on the shelf, sold units gone), held (by orders being paid for) and available (on hand less
13
+ * held). An object with stock cannot have fields of these names.
14
+ */
15
+ export declare const STOCK_VALUES: readonly ["onHand", "held", "available"];
16
+ /**
17
+ * The kinds of movement in the ledger (ADR 0680). The host writes `opening`, `adjusted` and
18
+ * `sold`; a record's `stockMoves` writes `received`, `written_off`, `used` and `counted` (ADR
19
+ * 0681); a return (stage 37 step 4) writes `returned`.
20
+ */
21
+ export declare const STOCK_MOVEMENT_KINDS: readonly ["opening", "received", "sold", "returned", "written_off", "counted", "adjusted", "used"];
22
+ export type StockMovementKind = (typeof STOCK_MOVEMENT_KINDS)[number];
23
+ /**
24
+ * A number of things on hand (ADR 0680). The host keeps the count from a ledger of movements
25
+ * (opening stock, a correction, a sale) and nobody types it: an order line holds its quantity
26
+ * while the order is unpaid and sells it when it is paid, refused by the database past what is
27
+ * available, in the order's own batch. A refund changes nothing in stock; a return does.
28
+ *
29
+ * - `reorderAt` is this object's number field holding the reorder level (a record at or below it
30
+ * is low); `reorderQty` the number field holding how many to order then.
31
+ * - `show` is what customers and the public are told (default `availability`); `lowAt` is the
32
+ * threshold for `low`.
33
+ * - `notify` is one of this extension's tool permissions: when a write takes a record's on hand to
34
+ * or below its reorder level, the staff who hold it are told, once until it rises above again
35
+ * (ADR 0681). Without it, the admins are told. It needs `reorderAt`.
36
+ * - The object is sellable goods (`sellable.goods`, ADR 0682), or the object a `stockMoves` of
37
+ * this extension moves (a part nobody sells still has stock).
38
+ *
39
+ * An object with stock is not also a capacity (its counter is the stock's), and is not bought by
40
+ * deposit, by subscription or by moving a record (`sellable.deposit`, `recurring`, `moves`).
41
+ */
42
+ export interface StockSpec {
43
+ reorderAt?: string;
44
+ reorderQty?: string;
45
+ show?: StockShow;
46
+ lowAt?: number;
47
+ notify?: string;
48
+ }
49
+ export declare const stockManifestSchema: z.ZodObject<{
50
+ reorderAt: z.ZodOptional<z.ZodString>;
51
+ reorderQty: z.ZodOptional<z.ZodString>;
52
+ show: z.ZodOptional<z.ZodEnum<{
53
+ exact: "exact";
54
+ low: "low";
55
+ availability: "availability";
56
+ }>>;
57
+ lowAt: z.ZodOptional<z.ZodNumber>;
58
+ notify: z.ZodOptional<z.ZodString>;
59
+ }, z.core.$strict>;
60
+ export type StockManifest = z.infer<typeof stockManifestSchema>;
61
+ /** Reports problems with `objects.<name>.stock` through `contract`. */
62
+ export declare function checkObjectStock(m: ExtensionManifest, name: string, object: ObjectManifest, contract: (path: string, message: string) => void): void;
63
+ /** How a record's move changes stock: units in, units out, or on hand set to a counted number. */
64
+ export declare const STOCK_MOVES: readonly ["add", "remove", "set"];
65
+ export type StockMove = (typeof STOCK_MOVES)[number];
66
+ /** The ledger kinds each move may write; the first is the default. */
67
+ export declare const STOCK_MOVE_KINDS: {
68
+ readonly add: readonly ["received"];
69
+ readonly remove: readonly ["written_off", "used"];
70
+ readonly set: readonly ["counted"];
71
+ };
72
+ /**
73
+ * A record's state moves stock (ADR 0681): when it enters `when`, the host writes a movement of
74
+ * `quantity` on the record `on` points to (an object of this extension with stock), in the batch
75
+ * of the write that makes the move, for every actor. A receipt `received` adds; a write-off
76
+ * removes; a count line `set`s on hand to the number counted, the difference worked out when the
77
+ * batch commits.
78
+ *
79
+ * - `when` is a state of this object, or with `through`, of the record `through` points to (a
80
+ * relation, one record, to another object of this extension with states): that record entering
81
+ * `when` moves the stock of every live record of this object pointing to it, in one batch (a
82
+ * count applied moves each of its lines). No declared move leaves `when`: stock moves once.
83
+ * - `kind` is the ledger's kind: `received` for add; `written_off` (default) or `used` for
84
+ * remove; `counted` for set.
85
+ * - `unitCost` (add only) is a number field of the cost of one, in minor units; `note` a text
86
+ * field the ledger keeps.
87
+ * - Every declared move into `when` is by `["host"]`, with the `tools` (humanOnly or
88
+ * personApproves, with a permission) a person makes it through; nothing is created in `when`
89
+ * but by the host. Moving stock is a person's act: an AI's call of the tool waits for a person.
90
+ * - A quantity is a whole number, above 0 (add, remove) or 0 and above (set). Once moved, `on`,
91
+ * `quantity`, `unitCost` and `note` cannot change, and a moved record's lines cannot be added to
92
+ * or changed: the ledger keeps what moved.
93
+ */
94
+ export interface StockMovesSpec {
95
+ move: StockMove;
96
+ on: string;
97
+ quantity: string;
98
+ when: string;
99
+ through?: string;
100
+ kind?: StockMovementKind;
101
+ unitCost?: string;
102
+ note?: string;
103
+ }
104
+ export declare const stockMovesManifestSchema: z.ZodObject<{
105
+ move: z.ZodEnum<{
106
+ set: "set";
107
+ add: "add";
108
+ remove: "remove";
109
+ }>;
110
+ on: z.ZodString;
111
+ quantity: z.ZodString;
112
+ when: z.ZodString;
113
+ through: z.ZodOptional<z.ZodString>;
114
+ kind: z.ZodOptional<z.ZodEnum<{
115
+ used: "used";
116
+ opening: "opening";
117
+ received: "received";
118
+ sold: "sold";
119
+ returned: "returned";
120
+ written_off: "written_off";
121
+ counted: "counted";
122
+ adjusted: "adjusted";
123
+ }>>;
124
+ unitCost: z.ZodOptional<z.ZodString>;
125
+ note: z.ZodOptional<z.ZodString>;
126
+ }, z.core.$strict>;
127
+ export type StockMovesManifest = z.infer<typeof stockMovesManifestSchema>;
128
+ /** Reports problems with `objects.<name>.stockMoves` through `contract`. */
129
+ export declare function checkObjectStockMoves(m: ExtensionManifest, name: string, object: ObjectManifest, contract: (path: string, message: string) => void): void;
package/dist/stock.js ADDED
@@ -0,0 +1,205 @@
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 { moveOrigins } from "./states.js";
7
+ /**
8
+ * What customers and the public are told about a record's stock (staff always see the numbers):
9
+ * `availability` (the default), "In stock" or "Sold out"; `low`, "only N left" at or below
10
+ * `lowAt`; `exact`, the number available.
11
+ */
12
+ export const STOCK_SHOW = ["exact", "low", "availability"];
13
+ /**
14
+ * The read-only values the host adds to every record of an object with stock: on hand (what is
15
+ * on the shelf, sold units gone), held (by orders being paid for) and available (on hand less
16
+ * held). An object with stock cannot have fields of these names.
17
+ */
18
+ export const STOCK_VALUES = ["onHand", "held", "available"];
19
+ /**
20
+ * The kinds of movement in the ledger (ADR 0680). The host writes `opening`, `adjusted` and
21
+ * `sold`; a record's `stockMoves` writes `received`, `written_off`, `used` and `counted` (ADR
22
+ * 0681); a return (stage 37 step 4) writes `returned`.
23
+ */
24
+ export const STOCK_MOVEMENT_KINDS = [
25
+ "opening",
26
+ "received",
27
+ "sold",
28
+ "returned",
29
+ "written_off",
30
+ "counted",
31
+ "adjusted",
32
+ "used",
33
+ ];
34
+ const fieldName = z.string().max(40);
35
+ export const stockManifestSchema = z
36
+ .object({
37
+ reorderAt: fieldName.optional(),
38
+ reorderQty: fieldName.optional(),
39
+ show: z.enum(STOCK_SHOW).optional(),
40
+ lowAt: z.number().int().min(1).max(1_000_000).optional(),
41
+ notify: z.string().max(80).optional(),
42
+ })
43
+ .strict();
44
+ /** Reports problems with `objects.<name>.stock` through `contract`. */
45
+ export function checkObjectStock(m, name, object, contract) {
46
+ const stock = object.stock;
47
+ if (!stock)
48
+ return;
49
+ const path = `objects.${name}.stock`;
50
+ const fieldOf = (local) => Object.hasOwn(object.fields, local) ? object.fields[local] : undefined;
51
+ for (const key of ["reorderAt", "reorderQty"]) {
52
+ const local = stock[key];
53
+ if (local === undefined)
54
+ continue;
55
+ const field = fieldOf(local);
56
+ if (field?.type !== "number" || field.many) {
57
+ contract(`${path}.${key}`, `"${local}" must be a number field of ${name}`);
58
+ }
59
+ }
60
+ for (const reserved of STOCK_VALUES) {
61
+ if (Object.hasOwn(object.fields, reserved)) {
62
+ contract(`objects.${name}.fields.${reserved}`, `"${reserved}" is a value the host adds to an object with stock; rename the field`);
63
+ }
64
+ }
65
+ if (object.capacity) {
66
+ contract(path, "An object has stock or a capacity, not both: stock keeps its own counter");
67
+ }
68
+ const sellable = object.sellable;
69
+ if (sellable) {
70
+ for (const key of ["deposit", "recurring", "moves"]) {
71
+ if (sellable[key] !== undefined) {
72
+ contract(`objects.${name}.sellable.${key}`, `A thing in stock is sold whole, on an order: it has no sellable.${key}`);
73
+ }
74
+ }
75
+ }
76
+ if (stock.lowAt !== undefined && stock.show !== "low") {
77
+ contract(`${path}.lowAt`, 'lowAt is the threshold of show: "low"');
78
+ }
79
+ if (stock.show === "low" && stock.lowAt === undefined) {
80
+ contract(`${path}.lowAt`, 'show: "low" needs lowAt, the number at or below which it says so');
81
+ }
82
+ if (stock.notify !== undefined) {
83
+ if (stock.reorderAt === undefined) {
84
+ contract(`${path}.notify`, "notify tells staff of a reorder level: declare reorderAt");
85
+ }
86
+ const permissions = Object.values(m.tools).flatMap((tool) => typeof tool.permission === "string" ? [tool.permission] : [...(tool.permission ?? [])]);
87
+ if (!permissions.includes(stock.notify)) {
88
+ contract(`${path}.notify`, `"${stock.notify}" is not the permission of any of this extension's tools (tools.<name>.permission)`);
89
+ }
90
+ }
91
+ const moved = Object.values(m.objects).some((other) => other.stockMoves && relationTarget(m, other, other.stockMoves.on) === name);
92
+ if (sellable && !sellable.goods) {
93
+ // A thing in stock that is sold is goods (ADR 0682): its orders have a channel and a delivery.
94
+ contract(`objects.${name}.sellable.goods`, `${name} has stock and is sold: declare sellable.goods (where it is sold)`);
95
+ }
96
+ if (!sellable && !moved) {
97
+ contract(path, `${name} has stock but is neither sellable goods nor moved by a stockMoves of this extension`);
98
+ }
99
+ }
100
+ // --- stockMoves (ADR 0681) ------------------------------------------------------------------------
101
+ /** How a record's move changes stock: units in, units out, or on hand set to a counted number. */
102
+ export const STOCK_MOVES = ["add", "remove", "set"];
103
+ /** The ledger kinds each move may write; the first is the default. */
104
+ export const STOCK_MOVE_KINDS = {
105
+ add: ["received"],
106
+ remove: ["written_off", "used"],
107
+ set: ["counted"],
108
+ };
109
+ export const stockMovesManifestSchema = z
110
+ .object({
111
+ move: z.enum(STOCK_MOVES),
112
+ on: fieldName,
113
+ quantity: fieldName,
114
+ when: z.string().min(1).max(100),
115
+ through: fieldName.optional(),
116
+ kind: z.enum(STOCK_MOVEMENT_KINDS).optional(),
117
+ unitCost: fieldName.optional(),
118
+ note: fieldName.optional(),
119
+ })
120
+ .strict();
121
+ /** The local name of the object of this extension a one-record relation field points to. */
122
+ function relationTarget(m, object, field) {
123
+ const f = Object.hasOwn(object.fields, field) ? object.fields[field] : undefined;
124
+ if (f?.type !== "relation" || f.many || !f.to?.startsWith(`${m.id}.`))
125
+ return undefined;
126
+ const local = f.to.slice(m.id.length + 1);
127
+ return Object.hasOwn(m.objects, local) ? local : undefined;
128
+ }
129
+ /** Reports problems with `objects.<name>.stockMoves` through `contract`. */
130
+ export function checkObjectStockMoves(m, name, object, contract) {
131
+ const moves = object.stockMoves;
132
+ if (!moves)
133
+ return;
134
+ const path = `objects.${name}.stockMoves`;
135
+ const fieldOf = (local) => Object.hasOwn(object.fields, local) ? object.fields[local] : undefined;
136
+ const target = relationTarget(m, object, moves.on);
137
+ if (!target) {
138
+ contract(`${path}.on`, `"${moves.on}" must be a relation field (one record) to an object of this extension with stock`);
139
+ }
140
+ else if (!m.objects[target]?.stock) {
141
+ contract(`${path}.on`, `${m.id}.${target} must declare stock for its stock to move`);
142
+ }
143
+ const number = (key) => {
144
+ const local = moves[key];
145
+ if (local === undefined)
146
+ return;
147
+ const field = fieldOf(local);
148
+ if (field?.type !== "number" || field.many) {
149
+ contract(`${path}.${key}`, `"${local}" must be a number field of ${name}`);
150
+ }
151
+ };
152
+ number("quantity");
153
+ number("unitCost");
154
+ if (moves.unitCost !== undefined && moves.move !== "add") {
155
+ contract(`${path}.unitCost`, "Only what comes in (add) has a unit cost");
156
+ }
157
+ if (moves.note !== undefined) {
158
+ const field = fieldOf(moves.note);
159
+ if (field?.type !== "text" || field.many) {
160
+ contract(`${path}.note`, `"${moves.note}" must be a text field of ${name}`);
161
+ }
162
+ }
163
+ const kinds = STOCK_MOVE_KINDS[moves.move];
164
+ if (moves.kind !== undefined && !kinds.includes(moves.kind)) {
165
+ contract(`${path}.kind`, `A ${moves.move} writes ${kinds.map((k) => `"${k}"`).join(" or ")}, not "${moves.kind}"`);
166
+ }
167
+ // Whose state moves it: this object's, or the record `through` points to.
168
+ let owner = name;
169
+ if (moves.through !== undefined) {
170
+ owner = relationTarget(m, object, moves.through);
171
+ if (!owner || owner === name) {
172
+ contract(`${path}.through`, `"${moves.through}" must be a relation field (one record) to another of this extension's objects`);
173
+ return;
174
+ }
175
+ }
176
+ const states = m.objects[owner]?.states;
177
+ if (!states) {
178
+ contract(moves.through === undefined ? path : `${path}.through`, `${owner} must declare states: entering "${moves.when}" moves the stock`);
179
+ return;
180
+ }
181
+ const stateField = Object.hasOwn(m.objects[owner]?.fields ?? {}, states.field)
182
+ ? m.objects[owner]?.fields[states.field]
183
+ : undefined;
184
+ if (!(stateField?.options ?? []).some((o) => o.value === moves.when)) {
185
+ contract(`${path}.when`, `"${moves.when}" is not a state of ${owner}`);
186
+ }
187
+ if (states.moves.some((move) => moveOrigins(move).includes(moves.when))) {
188
+ contract(`${path}.when`, `No move may leave "${moves.when}": stock moves once, when a record enters it`);
189
+ }
190
+ // Moving stock is a person's act with the pack's permission (ADR 0681, the review of #422):
191
+ // the host's alone, and the tools a person calls (ADR 0513), so an assistant's or an MCP
192
+ // client's call of them waits for a person, and no customer, member or automation moves stock
193
+ // by moving a record.
194
+ states.moves.forEach((move, i) => {
195
+ if (move.to !== moves.when)
196
+ return;
197
+ if (move.by.some((mover) => mover !== "host")) {
198
+ contract(`objects.${owner}.states.moves.${i}.by`, `Entering "${moves.when}" moves stock: declare it by ["host"] with the tools a person makes it through (states.moves.<n>.tools)`);
199
+ }
200
+ });
201
+ const created = states.create?.in?.[moves.when];
202
+ if (created?.some((mover) => mover !== "host")) {
203
+ contract(`objects.${owner}.states.create.in.${moves.when}`, `Creating a record in "${moves.when}" moves stock: only the host may; create it in another state and move it through a tool`);
204
+ }
205
+ }
package/dist/team.d.ts ADDED
@@ -0,0 +1,28 @@
1
+ import { z } from "zod";
2
+ import type { ExtensionManifest, ObjectManifest } from "./manifest.ts";
3
+ /**
4
+ * Who on the staff looks after the Person a record is about (ADR 0831): the accounts in its
5
+ * `staff` user fields, while the record is in one of the `live` states of the object's `states`
6
+ * (every record not in the Trash, when the object has no states). A client's program names their
7
+ * coach: `{ person: "person", staff: ["coach"], live: ["generating", "active"] }`.
8
+ *
9
+ * It gives nothing by itself. A pack role that declares `looksAfter` reaches its objects' records
10
+ * only for the People its holder looks after this way (ADR 0889). Only shipped packs and the
11
+ * org's own extensions declare it: who reaches whose records is access.
12
+ */
13
+ export interface TeamSpec {
14
+ /** A relation (one record) to `person`: whom the record is about. */
15
+ person: string;
16
+ /** `user` fields of this object (one account each, each `personApproves`): who looks after them. */
17
+ staff: readonly string[];
18
+ /** The states of the object's `states` in which the record counts. */
19
+ live?: readonly string[];
20
+ }
21
+ export declare const teamManifestSchema: z.ZodObject<{
22
+ person: z.ZodString;
23
+ staff: z.ZodArray<z.ZodString>;
24
+ live: z.ZodOptional<z.ZodArray<z.ZodString>>;
25
+ }, z.core.$strict>;
26
+ export type TeamManifest = z.infer<typeof teamManifestSchema>;
27
+ /** Reports problems with `objects.<name>.team` through `contract`. */
28
+ export declare function checkObjectTeam(_m: ExtensionManifest, name: string, object: ObjectManifest, contract: (path: string, message: string) => void): void;
package/dist/team.js ADDED
@@ -0,0 +1,52 @@
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
+ const fieldName = z.string().max(40);
7
+ export const teamManifestSchema = z
8
+ .object({
9
+ person: fieldName,
10
+ staff: z.array(fieldName).min(1).max(4),
11
+ live: z.array(z.string().min(1).max(100)).min(1).max(20).optional(),
12
+ })
13
+ .strict();
14
+ /** Reports problems with `objects.<name>.team` through `contract`. */
15
+ export function checkObjectTeam(_m, name, object, contract) {
16
+ const team = object.team;
17
+ if (!team)
18
+ return;
19
+ const at = `objects.${name}.team`;
20
+ const own = (local) => Object.hasOwn(object.fields, local) ? object.fields[local] : undefined;
21
+ const person = own(team.person);
22
+ if (person?.type !== "relation" || person.to !== "person" || person.many) {
23
+ contract(`${at}.person`, `"${team.person}" must be a relation field (one record) to person`);
24
+ }
25
+ for (const [i, field] of team.staff.entries()) {
26
+ const staff = own(field);
27
+ if (staff?.type !== "user" || staff.many) {
28
+ contract(`${at}.staff.${i}`, `"${field}" must be a user field of ${name}`);
29
+ }
30
+ else if (staff.personApproves !== true) {
31
+ // Naming someone in it opens a pack role's reach to the Person (ADR 0889): a person's
32
+ // choice, never the assistant's, an automation's or code's on its own.
33
+ contract(`${at}.staff.${i}`, `"${field}" must be a field a person approves (personApproves): who reaches whose records is a person's to change`);
34
+ }
35
+ }
36
+ if (new Set(team.staff).size !== team.staff.length) {
37
+ contract(`${at}.staff`, "Name each field once");
38
+ }
39
+ if (team.live) {
40
+ const states = object.states;
41
+ const known = new Set(states ? (own(states.field)?.options ?? []).map((option) => option.value) : []);
42
+ if (!states) {
43
+ contract(`${at}.live`, `${name} has no states: leave live out (every record counts)`);
44
+ }
45
+ else {
46
+ for (const [i, state] of team.live.entries()) {
47
+ if (!known.has(state))
48
+ contract(`${at}.live.${i}`, `"${state}" is not a state of ${name}`);
49
+ }
50
+ }
51
+ }
52
+ }
package/dist/testing.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { type AutomationEvent, type AutomationTestStep, type NotificationSendInput } from "./automation.ts";
2
2
  import { type AiModule, type Extension, type StartedBy } from "./contract.ts";
3
3
  import type { ExtensionManifest, ManifestIssue, ValidateOptions } from "./manifest.ts";
4
+ import type { RoutineSendInput, RoutineSendResult } from "./routine-mail.ts";
4
5
  type Values = Record<string, unknown> & {
5
6
  id: string;
6
7
  };
@@ -34,6 +35,17 @@ export interface TestHostOptions {
34
35
  method: string;
35
36
  args: unknown[];
36
37
  }) => unknown>;
38
+ /**
39
+ * What `ctx.routineMail.send` answers (ADR 0590). Every call is recorded in `routineSends`;
40
+ * with no fake each answers one email sent. The host decides who it goes to and what it says,
41
+ * so a pack's test checks which kind, record, message and values it asked for.
42
+ */
43
+ routineMail?: (send: RoutineSendInput) => RoutineSendResult | Promise<RoutineSendResult>;
44
+ }
45
+ /** A routine email an automation asked the host to send (`ctx.routineMail.send`). */
46
+ export interface RoutineSend extends RoutineSendInput {
47
+ /** The step it was asked in. */
48
+ step: string | null;
37
49
  }
38
50
  /** A call a tool or automation made through `ctx.gatekeeper(name).call(...)`. */
39
51
  export interface GatekeeperCall {
@@ -70,6 +82,13 @@ export interface AutomationRunOptions {
70
82
  runId?: string;
71
83
  /** `event.test`. Default false: the run writes to the in-memory store. */
72
84
  test?: boolean;
85
+ /** `event.originalRunId`: the run a retry's chain began with (ADR 0574). */
86
+ originalRunId?: string;
87
+ /**
88
+ * How many times a `do` step that throws is run again, as the host's Workflow retries a step
89
+ * (the steps before it are not run again). Default 0: a throw fails the run.
90
+ */
91
+ retries?: number;
73
92
  }
74
93
  export interface AutomationRunResult {
75
94
  /** False when the declared conditions did not match the trigger record (nothing ran). */
@@ -135,6 +154,8 @@ export interface TestHost {
135
154
  notifications: SentNotification[];
136
155
  /** Every call through a gatekeeper module, in order. */
137
156
  gatekeeperCalls: GatekeeperCall[];
157
+ /** Every routine email asked for, in order (ADR 0590). */
158
+ routineSends: RoutineSend[];
138
159
  /**
139
160
  * Runs automation `name` in memory, start to finish: conditions checked on the trigger
140
161
  * record, waits skipped (and recorded), steps held to the declarations.
@@ -143,7 +164,7 @@ export interface TestHost {
143
164
  /**
144
165
  * Publishes a record of a publishable object as a person would (`record.publish`, which no
145
166
  * tool may call): its content fields become the next version, which `record.version` reads.
146
- * Returns the version's number.
167
+ * Refused outside the object's `publishable.publishIn` states. Returns the version's number.
147
168
  */
148
169
  publish(object: string, id: string): number;
149
170
  }
package/dist/testing.js CHANGED
@@ -20,6 +20,7 @@
20
20
  // to the automation's declarations like the host does. Writes and notifications a step did not
21
21
  // declare are listed in `undeclared`.
22
22
  import { durationMs, notificationInput, } from "./automation.js";
23
+ import { DEFAULT_WAIT_TIMEOUT, NOTIFY_OPERATION } from "./automation-check.js";
23
24
  import { GATEKEEPER_MODULES } from "./contract.js";
24
25
  import { validateDocument } from "./document.js";
25
26
  import { CORE_OBJECT_NAMES, toManifest, validateManifest } from "./manifest.js";
@@ -89,6 +90,13 @@ export function createTestHost(extension, options = {}) {
89
90
  const row = table(object).get(id);
90
91
  if (!row)
91
92
  throw new ExtensionToolError("not_found", `No ${object} with id ${id}`);
93
+ // Only in the states the object lists (ADR 0810), as the host refuses.
94
+ const spec = manifest.objects[local];
95
+ const stateField = spec?.states?.field;
96
+ const publishIn = spec?.publishable?.publishIn;
97
+ if (publishIn && stateField && !publishIn.includes(String(row[stateField] ?? ""))) {
98
+ throw new ExtensionToolError("invalid_input", `${object} ${id} is ${String(row[stateField] ?? "in no state")}: it is published only when ${publishIn.join(" or ")}`);
99
+ }
92
100
  const list = versions.get(`${object}|${id}`) ?? [];
93
101
  const version = list.length + 1;
94
102
  list.push({
@@ -333,7 +341,7 @@ export function createTestHost(extension, options = {}) {
333
341
  const delivered = new Set();
334
342
  let currentStep = null;
335
343
  let observer = null;
336
- builtIn["notification.send"] = (input) => {
344
+ builtIn[NOTIFY_OPERATION] = (input) => {
337
345
  const notes = [];
338
346
  const admins = users.filter((u) => u.role === "admin").map((u) => u.id);
339
347
  const ids = [];
@@ -471,6 +479,28 @@ export function createTestHost(extension, options = {}) {
471
479
  types: async () => "",
472
480
  };
473
481
  }
482
+ const routineSends = [];
483
+ if (has("routine-mail")) {
484
+ raw["routine-mail"] = {
485
+ send: async (input) => {
486
+ const send = structuredClone(input);
487
+ routineSends.push({ ...send, step: currentStep });
488
+ try {
489
+ const value = options.routineMail
490
+ ? await options.routineMail(send)
491
+ : { sent: 1, held: 0, off: false, none: false };
492
+ return { ok: true, value };
493
+ }
494
+ catch (error) {
495
+ const e = error;
496
+ return {
497
+ ok: false,
498
+ error: { code: e.code ?? "internal", message: e.message ?? String(error) },
499
+ };
500
+ }
501
+ },
502
+ };
503
+ }
474
504
  if (has("ai")) {
475
505
  const ai = {
476
506
  summarise: async (text) => String(text).slice(0, 100),
@@ -513,6 +543,7 @@ export function createTestHost(extension, options = {}) {
513
543
  const event = {
514
544
  automation: `${manifest.id}.${name}`,
515
545
  runId: run.runId ?? "arn_TEST",
546
+ ...(run.originalRunId ? { originalRunId: run.originalRunId } : {}),
516
547
  trigger: automation.trigger.type,
517
548
  ...(run.record && row
518
549
  ? {
@@ -555,7 +586,7 @@ export function createTestHost(extension, options = {}) {
555
586
  const where = (stepName) => stepName ? `step ${stepName}` : "run (outside a step)";
556
587
  const notificationsBefore = notifications.length;
557
588
  observer = (operation, input, value) => {
558
- if (operation === "notification.send") {
589
+ if (operation === NOTIFY_OPERATION) {
559
590
  if (!declaresNotify(currentStep)) {
560
591
  result.undeclared.push(`${where(currentStep)} sent a notification (not in its notifies)`);
561
592
  }
@@ -582,7 +613,7 @@ export function createTestHost(extension, options = {}) {
582
613
  const n = (notifyCounts.get(key) ?? 0) + 1;
583
614
  notifyCounts.set(key, n);
584
615
  const input = notificationInput(event, to, message, `${key}:${n}`);
585
- const sent = await base.ops.call("notification.send", input);
616
+ const sent = await base.ops.call(NOTIFY_OPERATION, input);
586
617
  return { sent: sent.sent };
587
618
  },
588
619
  };
@@ -602,7 +633,17 @@ export function createTestHost(extension, options = {}) {
602
633
  const first = calls.length;
603
634
  currentStep = stepName;
604
635
  try {
605
- const value = await fn();
636
+ let value;
637
+ for (let attempt = 0;; attempt++) {
638
+ try {
639
+ value = await fn();
640
+ break;
641
+ }
642
+ catch (error) {
643
+ if (attempt >= (run.retries ?? 0))
644
+ throw error;
645
+ }
646
+ }
606
647
  result.steps.push({
607
648
  name: stepName,
608
649
  kind: "do",
@@ -631,7 +672,7 @@ export function createTestHost(extension, options = {}) {
631
672
  name: stepName,
632
673
  kind: "waitForEvent",
633
674
  value,
634
- skippedMs: durationMs((step.timeout ?? "7 days")),
675
+ skippedMs: durationMs((step.timeout ?? DEFAULT_WAIT_TIMEOUT)),
635
676
  calls: [],
636
677
  });
637
678
  return value;
@@ -665,6 +706,7 @@ export function createTestHost(extension, options = {}) {
665
706
  records,
666
707
  notifications,
667
708
  gatekeeperCalls,
709
+ routineSends,
668
710
  runAutomation,
669
711
  publish,
670
712
  async runTool(tool, input, options = {}) {
@@ -0,0 +1,42 @@
1
+ import { z } from "zod";
2
+ import type { ExtensionManifest, ObjectManifest } from "./manifest.ts";
3
+ /**
4
+ * Time can be recorded against this record (ADR 0850): a job a tradesperson spends three hours
5
+ * on. A staff member's **time entry** is the one record of time worked; an entry against a shift
6
+ * (a `staffed` record) is against the roster, an entry against a `workedOn` record is against the
7
+ * job, and an entry against neither is other work. The record keeps no hours of its own: its
8
+ * time is the entries against it, read through the host (the same entries pay counts), never a
9
+ * second "time spent" record, and never in a `rec_*` view.
10
+ *
11
+ * - `live`: the states of the object's `states` in which time may be recorded against it. A
12
+ * record in any other state, or in the Trash, takes no new time.
13
+ * - `title`: a field of this object, shown on the entry, the timesheet and the export.
14
+ * - `kind` (optional): a relation (one record) of this object, shown as the export's kind.
15
+ * - `place` (optional): a field, or `relation.field`, shown beside the entry.
16
+ * - `readers`: a permission of this extension's tools: who reads the time recorded against a
17
+ * record (person, date, minutes and state; never a note).
18
+ * - `partOf` (optional), on a `staffed` object only (a scheduled visit to a site): a relation (one
19
+ * record) to another of this extension's objects that declares `workedOn` (the job); time
20
+ * recorded against the visit also counts to it.
21
+ *
22
+ * Only shipped packs and the org's own extensions declare it: time worked feeds pay.
23
+ */
24
+ export interface WorkedOnSpec {
25
+ live: readonly string[];
26
+ title: string;
27
+ kind?: string;
28
+ place?: string;
29
+ readers: string;
30
+ partOf?: string;
31
+ }
32
+ export declare const workedOnManifestSchema: z.ZodObject<{
33
+ live: z.ZodArray<z.ZodString>;
34
+ title: z.ZodString;
35
+ kind: z.ZodOptional<z.ZodString>;
36
+ place: z.ZodOptional<z.ZodString>;
37
+ readers: z.ZodString;
38
+ partOf: z.ZodOptional<z.ZodString>;
39
+ }, z.core.$strict>;
40
+ export type WorkedOnManifest = z.infer<typeof workedOnManifestSchema>;
41
+ /** Reports problems with `objects.<name>.workedOn` through `contract`. */
42
+ export declare function checkObjectWorkedOn(m: ExtensionManifest, name: string, object: ObjectManifest, contract: (path: string, message: string) => void): void;