@composable-os/sdk 0.0.0-stage → 0.1.0-beta.11

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 (81) hide show
  1. package/LICENSE +109 -0
  2. package/dist/allowance.d.ts +198 -0
  3. package/dist/allowance.js +374 -0
  4. package/dist/automation-check.d.ts +38 -0
  5. package/dist/automation-check.js +454 -0
  6. package/dist/automation.d.ts +767 -0
  7. package/dist/automation.js +303 -0
  8. package/dist/behaviour.d.ts +3 -0
  9. package/dist/behaviour.js +153 -0
  10. package/dist/capacity.d.ts +146 -0
  11. package/dist/capacity.js +189 -0
  12. package/dist/contract.d.ts +851 -0
  13. package/dist/contract.js +42 -0
  14. package/dist/document.d.ts +211 -0
  15. package/dist/document.js +726 -0
  16. package/dist/field-types.d.ts +11 -0
  17. package/dist/field-types.js +98 -0
  18. package/dist/formula/ast.d.ts +67 -0
  19. package/dist/formula/ast.js +22 -0
  20. package/dist/formula/compile.d.ts +37 -0
  21. package/dist/formula/compile.js +379 -0
  22. package/dist/formula/index.d.ts +3 -0
  23. package/dist/formula/index.js +4 -0
  24. package/dist/formula/parser.d.ts +13 -0
  25. package/dist/formula/parser.js +365 -0
  26. package/dist/index.d.ts +20 -0
  27. package/dist/index.js +24 -0
  28. package/dist/manifest.d.ts +1708 -0
  29. package/dist/manifest.js +1494 -0
  30. package/dist/media.d.ts +41 -0
  31. package/dist/media.js +90 -0
  32. package/dist/permissions.d.ts +17 -0
  33. package/dist/permissions.js +44 -0
  34. package/dist/recurring.d.ts +114 -0
  35. package/dist/recurring.js +173 -0
  36. package/dist/renamed.d.ts +16 -0
  37. package/dist/renamed.js +59 -0
  38. package/dist/rich-text-fixture.d.ts +121 -0
  39. package/dist/rich-text-fixture.js +67 -0
  40. package/dist/rich-text.d.ts +48 -0
  41. package/dist/rich-text.js +184 -0
  42. package/dist/runtime.d.ts +95 -0
  43. package/dist/runtime.js +312 -0
  44. package/dist/sellable.d.ts +331 -0
  45. package/dist/sellable.js +746 -0
  46. package/dist/slug.d.ts +11 -0
  47. package/dist/slug.js +23 -0
  48. package/dist/states.d.ts +292 -0
  49. package/dist/states.js +383 -0
  50. package/dist/testing.d.ts +151 -0
  51. package/dist/testing.js +679 -0
  52. package/dist/unique.d.ts +20 -0
  53. package/dist/unique.js +58 -0
  54. package/package.json +34 -4
  55. package/src/allowance.ts +522 -0
  56. package/src/automation-check.ts +534 -0
  57. package/src/automation.ts +743 -0
  58. package/src/behaviour.ts +215 -0
  59. package/src/capacity.ts +303 -0
  60. package/src/contract.ts +909 -0
  61. package/src/document.ts +935 -0
  62. package/src/field-types.ts +111 -0
  63. package/src/formula/ast.ts +72 -0
  64. package/src/formula/compile.ts +454 -0
  65. package/src/formula/index.ts +4 -0
  66. package/src/formula/parser.ts +417 -0
  67. package/src/index.ts +36 -0
  68. package/src/manifest.ts +1785 -0
  69. package/src/media.ts +108 -0
  70. package/src/permissions.ts +60 -0
  71. package/src/recurring.ts +321 -0
  72. package/src/renamed.ts +63 -0
  73. package/src/rich-text-fixture.ts +68 -0
  74. package/src/rich-text.ts +221 -0
  75. package/src/runtime.ts +410 -0
  76. package/src/sellable.ts +1138 -0
  77. package/src/slug.ts +25 -0
  78. package/src/states.ts +598 -0
  79. package/src/testing.ts +847 -0
  80. package/src/unique.ts +81 -0
  81. package/README.md +0 -3
package/dist/states.js ADDED
@@ -0,0 +1,383 @@
1
+ // The `states` behaviour (ADR 0425): an object declares a small, fixed state machine and the host
2
+ // holds every write to it. Its declaration, its manifest schema and its contract checks live
3
+ // here; the host's side is packages/core/src/records/states.ts, on the transition engine it
4
+ // shares with `stages`.
5
+ import { z } from "zod";
6
+ /**
7
+ * Who may make a move. `staff`: anyone working for the organisation (people, their assistants,
8
+ * MCP clients, automations and extensions acting for them). `customer`: a signed-in customer, on
9
+ * their own record. `host`: platform code only (a payment confirmation, an expiry); no caller of
10
+ * an operation can make it.
11
+ */
12
+ export const MOVERS = ["staff", "customer", "host"];
13
+ const fieldName = z.string().max(40);
14
+ const stateValue = z.string().min(1).max(100);
15
+ const fieldPath = z.string().min(1).max(122);
16
+ const windowNumber = (number) => z.union([
17
+ number,
18
+ fieldPath,
19
+ z
20
+ .object({ field: fieldPath.optional(), setting: z.string().min(1).max(40).optional() })
21
+ .strict()
22
+ .refine((n) => n.field !== undefined || n.setting !== undefined, "Name a field or a setting"),
23
+ ]);
24
+ export const windowBoundSchema = z.union([
25
+ fieldPath,
26
+ z
27
+ .object({
28
+ at: fieldPath,
29
+ daysBefore: windowNumber(z.number().int().min(-366).max(366)).optional(),
30
+ minutesBefore: windowNumber(z.number().int().min(-527_040).max(527_040)).optional(),
31
+ zone: fieldPath.optional(),
32
+ })
33
+ .strict(),
34
+ ]);
35
+ const staffOnlyPaths = z.union([fieldPath, z.array(fieldPath).min(1).max(4)]);
36
+ const moveWindow = z
37
+ .object({ from: windowBoundSchema.optional(), until: windowBoundSchema.optional() })
38
+ .strict()
39
+ .refine((w) => w.from !== undefined || w.until !== undefined, "A window needs from or until");
40
+ export const statesManifestSchema = z.object({
41
+ field: fieldName,
42
+ initial: stateValue,
43
+ moves: z
44
+ .array(z.object({
45
+ from: z.union([stateValue, z.array(stateValue).min(1).max(50)]),
46
+ to: stateValue,
47
+ by: z.array(z.enum(MOVERS)).min(1).max(MOVERS.length),
48
+ requires: z.array(fieldName).max(50).optional(),
49
+ final: z.boolean().optional(),
50
+ window: moveWindow.optional(),
51
+ staffOnly: staffOnlyPaths.optional(),
52
+ tools: z.array(z.string().min(1).max(40)).min(1).max(10).optional(),
53
+ bindsStaff: z.boolean().optional(),
54
+ }))
55
+ .max(200),
56
+ create: z
57
+ .object({
58
+ in: z
59
+ .record(stateValue, z.array(z.enum(MOVERS)).min(1).max(MOVERS.length))
60
+ .refine((r) => Object.keys(r).length <= 20, "At most 20 states")
61
+ .optional(),
62
+ window: moveWindow.optional(),
63
+ staffOnly: staffOnlyPaths.optional(),
64
+ closed: staffOnlyPaths.optional(),
65
+ })
66
+ .strict()
67
+ .optional(),
68
+ requests: z
69
+ .record(z.string().regex(/^[a-z][a-z0-9_]{0,39}$/), z.array(stateValue).min(1).max(10))
70
+ .refine((r) => Object.keys(r).length <= 10, "At most 10 requests")
71
+ .optional(),
72
+ follows: z
73
+ .object({
74
+ relation: fieldName,
75
+ when: z
76
+ .record(stateValue, stateValue)
77
+ .refine((r) => Object.keys(r).length >= 1 && Object.keys(r).length <= 10, "1 to 10 states"),
78
+ from: z.array(stateValue).min(1).max(20),
79
+ })
80
+ .strict()
81
+ .optional(),
82
+ after: z
83
+ .array(z
84
+ .object({
85
+ from: z.union([stateValue, z.array(stateValue).min(1).max(20)]),
86
+ to: stateValue,
87
+ at: fieldPath,
88
+ minutesAfter: z.number().int().min(0).max(10_080).optional(),
89
+ ifAnyIn: z.array(stateValue).min(1).max(20).optional(),
90
+ })
91
+ .strict())
92
+ .min(1)
93
+ .max(4)
94
+ .optional(),
95
+ });
96
+ /** A staff-only rule's paths, as a list (ADR 0505). */
97
+ export function staffOnlyPathsOf(value) {
98
+ return value === undefined ? [] : typeof value === "string" ? [value] : value;
99
+ }
100
+ /** The states a move leaves, as a list. */
101
+ export function moveOrigins(move) {
102
+ return typeof move.from === "string" ? [move.from] : move.from;
103
+ }
104
+ /** Reports problems with `objects.<name>.states` through `contract`. */
105
+ export function checkObjectStates(m, name, object, contract) {
106
+ const states = object.states;
107
+ if (!states)
108
+ return;
109
+ const sp = `objects.${name}.states`;
110
+ if (object.stages) {
111
+ contract(sp, "An object has one lifecycle: declare stages or states, not both");
112
+ }
113
+ const fieldOf = (local) => Object.hasOwn(object.fields, local) ? object.fields[local] : undefined;
114
+ const field = fieldOf(states.field);
115
+ if (field?.type !== "select") {
116
+ contract(`${sp}.field`, `"${states.field}" must be a select field of ${name}`);
117
+ return;
118
+ }
119
+ if (field.readOnly) {
120
+ contract(`${sp}.field`, "The state field cannot be read-only: the moves say who may change it");
121
+ }
122
+ if (field.editableOptions) {
123
+ contract(`${sp}.field`, "The state field cannot have editableOptions: states are fixed in the declaration");
124
+ }
125
+ const values = new Set((field.options ?? []).map((o) => o.value));
126
+ const isState = (value) => values.has(value);
127
+ if (!isState(states.initial)) {
128
+ contract(`${sp}.initial`, `"${states.initial}" is not an option of ${states.field}`);
129
+ }
130
+ if (field.default !== undefined && field.default !== states.initial) {
131
+ contract(`${sp}.initial`, `${states.field}'s default must be the initial state "${states.initial}", or be left out`);
132
+ }
133
+ const seen = new Set();
134
+ const finals = new Set(states.moves.filter((move) => move.final).map((move) => move.to));
135
+ states.moves.forEach((move, i) => {
136
+ const mp = `${sp}.moves.${i}`;
137
+ if (!isState(move.to))
138
+ contract(`${mp}.to`, `"${move.to}" is not an option of ${states.field}`);
139
+ if (new Set(move.by).size !== move.by.length)
140
+ contract(`${mp}.by`, "List each mover once");
141
+ if (finals.has(move.to) && !move.final) {
142
+ contract(`${mp}.final`, `Another move into "${move.to}" is final; every move into a state must agree`);
143
+ }
144
+ if (move.final && move.to === states.initial) {
145
+ contract(`${mp}.final`, "The initial state cannot be final");
146
+ }
147
+ for (const from of moveOrigins(move)) {
148
+ if (!isState(from)) {
149
+ contract(`${mp}.from`, `"${from}" is not an option of ${states.field}`);
150
+ }
151
+ if (from === move.to)
152
+ contract(`${mp}.from`, `A move cannot go from "${from}" to itself`);
153
+ if (finals.has(from)) {
154
+ contract(`${mp}.from`, `"${from}" is final: nothing moves out of it`);
155
+ }
156
+ const key = JSON.stringify([from, move.to]);
157
+ if (seen.has(key)) {
158
+ contract(mp, `The move from "${from}" to "${move.to}" is declared twice`);
159
+ }
160
+ seen.add(key);
161
+ }
162
+ for (const local of move.requires ?? []) {
163
+ const required = fieldOf(local);
164
+ if (!required || required.type === "formula" || local === states.field) {
165
+ contract(`${mp}.requires`, `"${local}" must be a field of ${name} other than a formula or the state field`);
166
+ }
167
+ else if (required.readOnly && move.by.some((mover) => mover !== "host")) {
168
+ // Only the host writes a read-only field, so only a host move can fill it.
169
+ contract(`${mp}.requires`, `"${local}" is read-only, so only a move made by the host alone can require it`);
170
+ }
171
+ }
172
+ });
173
+ // Windows, staff-only rules and requests (ADR 0503; two relations and settings, ADR 0505).
174
+ const { checkPath, checkWindow } = windowChecks(m, object, name, contract);
175
+ states.moves.forEach((move, i) => {
176
+ const mp = `${sp}.moves.${i}`;
177
+ // A window binds customers, or staff too with bindsStaff (ADR 0551); staffOnly customers.
178
+ if (move.staffOnly && !move.by.includes("customer")) {
179
+ contract(mp, "staffOnly binds customers: the move must list customer in by");
180
+ }
181
+ if (move.window && !move.by.includes("customer") && !move.bindsStaff) {
182
+ contract(mp, "A window binds customers: the move must list customer in by, or bind staff (bindsStaff)");
183
+ }
184
+ checkWindow(move.window, `${mp}.window`);
185
+ for (const p of staffOnlyPathsOf(move.staffOnly))
186
+ checkPath(p, `${mp}.staffOnly`, "boolean");
187
+ // A move only named tools may make (ADR 0513): each a person's, with a permission.
188
+ for (const tool of move.tools ?? []) {
189
+ const spec = m.tools?.[tool];
190
+ if (!spec) {
191
+ contract(`${mp}.tools`, `"${tool}" is not a tool of this extension`);
192
+ }
193
+ else if ((!spec.humanOnly && !spec.personApproves) || !spec.permission) {
194
+ contract(`${mp}.tools`, `"${tool}" must be humanOnly or personApproves and declare a permission: the move is a person's act with it`);
195
+ }
196
+ }
197
+ if (move.bindsStaff && (!move.window || (!move.by.includes("staff") && !move.tools))) {
198
+ contract(`${mp}.bindsStaff`, "bindsStaff needs a window, and staff in by or named tools");
199
+ }
200
+ if (move.tools && move.by.includes("staff")) {
201
+ contract(`${mp}.tools`, "A move named tools may make is not also open to all staff: drop staff from by");
202
+ }
203
+ });
204
+ if (states.create) {
205
+ for (const state of Object.keys(states.create.in ?? {})) {
206
+ if (!isState(state))
207
+ contract(`${sp}.create.in`, `"${state}" is not an option of ${states.field}`);
208
+ if (finals.has(state))
209
+ contract(`${sp}.create.in`, `"${state}" is final: nothing is created in it`);
210
+ }
211
+ checkWindow(states.create.window, `${sp}.create.window`);
212
+ for (const p of staffOnlyPathsOf(states.create.staffOnly)) {
213
+ checkPath(p, `${sp}.create.staffOnly`, "boolean");
214
+ }
215
+ for (const p of staffOnlyPathsOf(states.create.closed)) {
216
+ checkPath(p, `${sp}.create.closed`, "boolean");
217
+ }
218
+ }
219
+ if (states.follows) {
220
+ const fp = `${sp}.follows`;
221
+ const f = states.follows;
222
+ const rel = fieldOf(f.relation);
223
+ const target = rel?.type === "relation" && !rel.many && rel.to?.startsWith(`${m.id}.`)
224
+ ? m.objects[rel.to.slice(m.id.length + 1)]
225
+ : undefined;
226
+ if (!target?.states) {
227
+ contract(`${fp}.relation`, `"${f.relation}" must be a relation (one record) of ${name} to another of this extension's objects that declares states`);
228
+ }
229
+ else {
230
+ // A parent whose places other records draw on as a pool: its counter counts claims that
231
+ // are not its own, which the cascade's check at commit cannot read (ADR 0550).
232
+ const pooled = Object.values(m.objects).some((other) => {
233
+ const poolField = other.capacity?.pool;
234
+ const relTo = poolField ? other.fields[poolField]?.to : undefined;
235
+ return relTo === rel?.to || relTo === rel?.to?.slice(m.id.length + 1);
236
+ });
237
+ if (pooled) {
238
+ contract(`${fp}.relation`, `${rel?.to ?? f.relation} is a pool other records draw places from: a cascade cannot follow it`);
239
+ }
240
+ const parentStates = new Set((target.fields[target.states.field]?.options ?? []).map((o) => o.value));
241
+ for (const [when, to] of Object.entries(f.when)) {
242
+ if (!parentStates.has(when)) {
243
+ contract(`${fp}.when`, `"${when}" is not a state of ${rel?.to ?? f.relation}`);
244
+ }
245
+ for (const from of f.from) {
246
+ if (!isState(from))
247
+ contract(`${fp}.from`, `"${from}" is not an option of ${states.field}`);
248
+ else if (!states.moves.some((move) => move.to === to && move.by.includes("host") && moveOrigins(move).includes(from))) {
249
+ contract(`${fp}.when`, `${name} needs a host move from "${from}" to "${to}"`);
250
+ }
251
+ }
252
+ }
253
+ }
254
+ }
255
+ // Timed moves (ADR 0550): a declared host move each, and a moment the sweep reads in SQL.
256
+ (states.after ?? []).forEach((rule, i) => {
257
+ const tp = `${sp}.after.${i}`;
258
+ if (!isState(rule.to))
259
+ contract(`${tp}.to`, `"${rule.to}" is not an option of ${states.field}`);
260
+ for (const from of moveOrigins(rule)) {
261
+ if (!isState(from)) {
262
+ contract(`${tp}.from`, `"${from}" is not an option of ${states.field}`);
263
+ }
264
+ else if (!states.moves.some((move) => move.to === rule.to && move.by.includes("host") && moveOrigins(move).includes(from))) {
265
+ contract(`${tp}.from`, `${name} needs a host move from "${from}" to "${rule.to}"`);
266
+ }
267
+ }
268
+ const parts = rule.at.split(".");
269
+ const at = parts.length <= 2 ? resolveFieldPath(m, object, rule.at) : undefined;
270
+ const via = parts.length === 2 ? fieldOf(parts[0]) : undefined;
271
+ const ownTarget = via?.type === "relation" && !via.many && via.to?.startsWith(`${m.id}.`);
272
+ if (at?.type !== "datetime" || at.many || (parts.length === 2 && !ownTarget)) {
273
+ contract(`${tp}.at`, `"${rule.at}" must be a datetime field of ${name}, or <relation>.<field> on another of this extension's objects`);
274
+ }
275
+ if (rule.ifAnyIn) {
276
+ if (parts.length !== 2) {
277
+ contract(`${tp}.ifAnyIn`, "ifAnyIn needs at one relation away: the records it compares");
278
+ }
279
+ for (const state of rule.ifAnyIn) {
280
+ if (!isState(state)) {
281
+ contract(`${tp}.ifAnyIn`, `"${state}" is not an option of ${states.field}`);
282
+ }
283
+ }
284
+ }
285
+ });
286
+ for (const [request, targets] of Object.entries(states.requests ?? {})) {
287
+ const rp = `${sp}.requests.${request}`;
288
+ if (isState(request))
289
+ contract(rp, `"${request}" is a state; a request needs its own name`);
290
+ if (new Set(targets).size !== targets.length)
291
+ contract(rp, "List each state once");
292
+ for (const to of targets) {
293
+ if (!isState(to))
294
+ contract(rp, `"${to}" is not an option of ${states.field}`);
295
+ else if (!states.moves.some((move) => move.to === to)) {
296
+ contract(rp, `No move goes to "${to}"`);
297
+ }
298
+ }
299
+ }
300
+ }
301
+ /**
302
+ * The checks of window paths and numbers (ADRs 0503 and 0505): for a `states` declaration, and
303
+ * for any other declaration that names a moment the same way (a waitlist's cut-off, ADR 0520).
304
+ */
305
+ export function windowChecks(m, object, name, contract) {
306
+ const checkPath = (at, path, type) => {
307
+ const field = resolveFieldPath(m, object, at);
308
+ // A staff-only rule may read a formula: the host computes it in the view (a boolean one).
309
+ const formulaOk = type === "boolean" && field?.type === "formula";
310
+ if ((field?.type !== type && !formulaOk) || field?.many) {
311
+ contract(path, `"${at}" must be a ${type} field of ${name}, or <relation>.<field> through up to two relations (one record each), every field on the way declared by this extension`);
312
+ }
313
+ };
314
+ const checkNumber = (value, path) => {
315
+ if (typeof value === "string")
316
+ checkPath(value, path, "number");
317
+ else if (typeof value === "object") {
318
+ if (value.field !== undefined)
319
+ checkPath(value.field, `${path}.field`, "number");
320
+ if (value.setting !== undefined) {
321
+ const settings = m.settings ?? {};
322
+ const setting = Object.hasOwn(settings, value.setting)
323
+ ? settings[value.setting]
324
+ : undefined;
325
+ if (setting?.type !== "number") {
326
+ contract(`${path}.setting`, `"${value.setting}" must be a number setting of ${m.id}`);
327
+ }
328
+ }
329
+ }
330
+ };
331
+ const checkBound = (bound, path) => {
332
+ const b = typeof bound === "string" ? { at: bound } : bound;
333
+ checkPath(b.at, `${path}.at`, "datetime");
334
+ for (const key of ["daysBefore", "minutesBefore"]) {
335
+ checkNumber(b[key], `${path}.${key}`);
336
+ }
337
+ if (b.zone !== undefined)
338
+ checkPath(b.zone, `${path}.zone`, "timezone");
339
+ };
340
+ const checkWindow = (window, path) => {
341
+ for (const end of ["from", "until"]) {
342
+ const bound = window?.[end];
343
+ if (bound !== undefined)
344
+ checkBound(bound, `${path}.${end}`);
345
+ }
346
+ };
347
+ return { checkPath, checkNumber, checkBound, checkWindow };
348
+ }
349
+ /**
350
+ * The field a path names (ADR 0503; two relations from ADR 0505): `field` on the object, or
351
+ * `relation.field` / `relation.relation.field` through relations of one record. Every field on
352
+ * the way is this extension's: a field of one of its objects, or one it adds to another object
353
+ * (`fields: { "programs.classtype": { … } }`). Undefined when the path names no such field.
354
+ */
355
+ export function resolveFieldPath(m, object, path) {
356
+ const parts = path.split(".");
357
+ if (parts.length > 3)
358
+ return undefined;
359
+ const added = m.fields ?? {};
360
+ /** The fields this extension declares on an object (by its full name), or on `object`. */
361
+ const fieldsOn = (target) => {
362
+ if (target === null)
363
+ return object.fields;
364
+ if (target.startsWith(`${m.id}.`)) {
365
+ const local = target.slice(m.id.length + 1);
366
+ return Object.hasOwn(m.objects, local) ? m.objects[local]?.fields : undefined;
367
+ }
368
+ return Object.hasOwn(added, target) ? added[target] : undefined;
369
+ };
370
+ let on = null;
371
+ for (const [i, part] of parts.entries()) {
372
+ const fields = fieldsOn(on);
373
+ const field = fields && Object.hasOwn(fields, part) ? fields[part] : undefined;
374
+ if (!field)
375
+ return undefined;
376
+ if (i === parts.length - 1)
377
+ return field;
378
+ if (field.type !== "relation" || field.many || !field.to)
379
+ return undefined;
380
+ on = field.to.includes(".") ? field.to : `${m.id}.${field.to}`;
381
+ }
382
+ return undefined;
383
+ }
@@ -0,0 +1,151 @@
1
+ import { type AutomationEvent, type AutomationTestStep, type NotificationSendInput } from "./automation.ts";
2
+ import { type AiModule, type Extension, type StartedBy } from "./contract.ts";
3
+ import type { ExtensionManifest, ManifestIssue, ValidateOptions } from "./manifest.ts";
4
+ type Values = Record<string, unknown> & {
5
+ id: string;
6
+ };
7
+ type OperationFake = (input: Record<string, unknown>) => unknown;
8
+ export interface TestHostOptions {
9
+ /** Seed records by object name (`organisation`, `example.project`). */
10
+ records?: Record<string, Values[]>;
11
+ /** Fakes for operations the harness does not implement, by name. */
12
+ operations?: Record<string, OperationFake>;
13
+ /** Fakes for the AI module. Default: deterministic stand-ins. */
14
+ ai?: Partial<AiModule>;
15
+ /** Passed to validateManifest. */
16
+ validate?: ValidateOptions;
17
+ /**
18
+ * Users `notification.send` resolves (`{ role: "admin" }`, `managerOf`). Default one admin,
19
+ * `usr_admin`.
20
+ */
21
+ users?: {
22
+ id: string;
23
+ role: "admin" | "member" | "viewer";
24
+ }[];
25
+ /**
26
+ * Fakes for the gatekeepers the extension declares in `permissions.modules`, by name: what a
27
+ * session method returns for `call(connectionId, resource, method, ...args)`. Every call is
28
+ * recorded in `gatekeeperCalls`. A declared gatekeeper with no fake answers `{ status: "pending" }`
29
+ * (a person would approve it), with one connection per declared automation connection.
30
+ */
31
+ gatekeepers?: Record<string, (call: {
32
+ connectionId: string;
33
+ resource: string;
34
+ method: string;
35
+ args: unknown[];
36
+ }) => unknown>;
37
+ }
38
+ /** A call a tool or automation made through `ctx.gatekeeper(name).call(...)`. */
39
+ export interface GatekeeperCall {
40
+ gatekeeper: string;
41
+ connectionId: string;
42
+ resource: string;
43
+ method: string;
44
+ args: unknown[];
45
+ /** The step it was made in (null: outside a step, or a tool). */
46
+ step: string | null;
47
+ }
48
+ /** A notification the in-memory `notification.send` delivered. */
49
+ export interface SentNotification extends Omit<NotificationSendInput, "type" | "dedupeKey"> {
50
+ type: string;
51
+ dedupeKey: string | null;
52
+ /** Resolved, deduplicated recipients. */
53
+ userIds: string[];
54
+ notes: string[];
55
+ /** The step that sent it (null: outside a step). */
56
+ step: string | null;
57
+ }
58
+ export interface AutomationRunOptions {
59
+ /** The trigger record, from the seeded `records`. */
60
+ record?: {
61
+ object: string;
62
+ id: string;
63
+ };
64
+ change?: AutomationEvent["change"];
65
+ period?: string;
66
+ manual?: AutomationEvent["manual"];
67
+ approval?: AutomationEvent["approval"];
68
+ /** waitForEvent payloads by step name. Default null (the wait timed out). */
69
+ events?: Record<string, unknown>;
70
+ runId?: string;
71
+ /** `event.test`. Default false: the run writes to the in-memory store. */
72
+ test?: boolean;
73
+ }
74
+ export interface AutomationRunResult {
75
+ /** False when the declared conditions did not match the trigger record (nothing ran). */
76
+ matched: boolean;
77
+ /** What `run` returned. */
78
+ value: unknown;
79
+ /** Set when `run` threw (a step failed, or an undeclared step name). */
80
+ error: {
81
+ code: string;
82
+ message: string;
83
+ } | null;
84
+ /** Every step in the order it ran; waits carry `skippedMs`. */
85
+ steps: (AutomationTestStep & {
86
+ calls: TestHost["calls"];
87
+ })[];
88
+ /** Record writes the run made (operation, object, the created or changed id). */
89
+ writes: {
90
+ step: string | null;
91
+ operation: string;
92
+ object: string | null;
93
+ id: string | null;
94
+ }[];
95
+ notifications: SentNotification[];
96
+ /** Effects no declaration covers, e.g. "step notifyOwner wrote task (not in its writes)". */
97
+ undeclared: string[];
98
+ }
99
+ /** Thrown into `run` when it uses a step name it did not declare (the host refuses it too). */
100
+ export declare class AutomationStepError extends Error {
101
+ name: string;
102
+ readonly code = "undeclared_step";
103
+ }
104
+ export declare class ExtensionToolError extends Error {
105
+ readonly code: string;
106
+ readonly details?: unknown | undefined;
107
+ name: string;
108
+ constructor(code: string, message: string, details?: unknown | undefined);
109
+ }
110
+ export interface TestHost {
111
+ manifest: ExtensionManifest;
112
+ /** Contract and formula issues (`extension.check` minus typecheck and dry-run reconcile). */
113
+ issues: ManifestIssue[];
114
+ /**
115
+ * Runs a tool like the host does: input and output validated, ctx from in-memory modules.
116
+ * `caller` is who started it (`ctx.caller`, ADR 0436); default the staff user `usr_admin`.
117
+ */
118
+ runTool<T = unknown>(tool: string, input: unknown, options?: {
119
+ caller?: StartedBy;
120
+ }): Promise<T>;
121
+ /** Every codemode:ops call, in order (allowed or refused). */
122
+ calls: {
123
+ operation: string;
124
+ input: unknown;
125
+ allowed: boolean;
126
+ }[];
127
+ logs: {
128
+ level: string;
129
+ message: string;
130
+ data: unknown;
131
+ }[];
132
+ storage: Map<string, unknown>;
133
+ records: Map<string, Map<string, Values>>;
134
+ /** Every notification sent through the in-memory `notification.send`. */
135
+ notifications: SentNotification[];
136
+ /** Every call through a gatekeeper module, in order. */
137
+ gatekeeperCalls: GatekeeperCall[];
138
+ /**
139
+ * Runs automation `name` in memory, start to finish: conditions checked on the trigger
140
+ * record, waits skipped (and recorded), steps held to the declarations.
141
+ */
142
+ runAutomation(name: string, options?: AutomationRunOptions): Promise<AutomationRunResult>;
143
+ /**
144
+ * Publishes a record of a publishable object as a person would (`record.publish`, which no
145
+ * tool may call): its content fields become the next version, which `record.version` reads.
146
+ * Returns the version's number.
147
+ */
148
+ publish(object: string, id: string): number;
149
+ }
150
+ export declare function createTestHost(extension: Extension, options?: TestHostOptions): TestHost;
151
+ export {};