@composable-os/sdk 0.1.0-beta.10 → 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 (105) 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.d.ts +69 -0
  15. package/dist/capacity.js +63 -2
  16. package/dist/checklists.d.ts +41 -0
  17. package/dist/checklists.js +75 -0
  18. package/dist/contract.d.ts +527 -26
  19. package/dist/contract.js +21 -3
  20. package/dist/discount.d.ts +135 -0
  21. package/dist/discount.js +281 -0
  22. package/dist/document.d.ts +2 -1
  23. package/dist/document.js +2 -1
  24. package/dist/field-types.d.ts +1 -1
  25. package/dist/field-types.js +5 -0
  26. package/dist/formula/compile.d.ts +15 -0
  27. package/dist/formula/compile.js +9 -0
  28. package/dist/index.d.ts +17 -0
  29. package/dist/index.js +17 -0
  30. package/dist/intake.d.ts +134 -0
  31. package/dist/intake.js +239 -0
  32. package/dist/journey-signals.d.ts +89 -0
  33. package/dist/journey-signals.js +151 -0
  34. package/dist/manifest.d.ts +1060 -60
  35. package/dist/manifest.js +1111 -61
  36. package/dist/mine.d.ts +45 -0
  37. package/dist/mine.js +119 -0
  38. package/dist/occupies.d.ts +64 -0
  39. package/dist/occupies.js +122 -0
  40. package/dist/questions.d.ts +179 -0
  41. package/dist/questions.js +514 -0
  42. package/dist/recurring.d.ts +33 -4
  43. package/dist/recurring.js +50 -3
  44. package/dist/restricted-fields.d.ts +15 -0
  45. package/dist/restricted-fields.js +97 -0
  46. package/dist/rich-text.d.ts +22 -0
  47. package/dist/rich-text.js +91 -0
  48. package/dist/routine-mail.d.ts +400 -0
  49. package/dist/routine-mail.js +955 -0
  50. package/dist/runtime.d.ts +5 -11
  51. package/dist/runtime.js +21 -11
  52. package/dist/screens.d.ts +3 -0
  53. package/dist/screens.js +74 -0
  54. package/dist/sellable.d.ts +231 -2
  55. package/dist/sellable.js +342 -1
  56. package/dist/slug.d.ts +2 -0
  57. package/dist/slug.js +6 -2
  58. package/dist/staffed.d.ts +178 -0
  59. package/dist/staffed.js +287 -0
  60. package/dist/states.d.ts +74 -4
  61. package/dist/states.js +154 -58
  62. package/dist/stock.d.ts +129 -0
  63. package/dist/stock.js +205 -0
  64. package/dist/team.d.ts +28 -0
  65. package/dist/team.js +52 -0
  66. package/dist/testing.d.ts +22 -1
  67. package/dist/testing.js +47 -5
  68. package/dist/worked-on.d.ts +42 -0
  69. package/dist/worked-on.js +79 -0
  70. package/package.json +9 -1
  71. package/src/acknowledge.ts +100 -0
  72. package/src/agreements.ts +185 -0
  73. package/src/allowance.ts +98 -8
  74. package/src/automation-check.ts +120 -9
  75. package/src/automation.ts +78 -10
  76. package/src/behaviour.ts +26 -6
  77. package/src/calendar-entry.ts +258 -0
  78. package/src/capacity.ts +103 -2
  79. package/src/checklists.ts +118 -0
  80. package/src/contract.ts +514 -27
  81. package/src/discount.ts +408 -0
  82. package/src/document.ts +4 -2
  83. package/src/field-types.ts +5 -0
  84. package/src/formula/compile.ts +10 -0
  85. package/src/index.ts +17 -0
  86. package/src/intake.ts +380 -0
  87. package/src/journey-signals.ts +215 -0
  88. package/src/manifest.ts +1313 -66
  89. package/src/mine.ts +161 -0
  90. package/src/occupies.ts +192 -0
  91. package/src/questions.ts +681 -0
  92. package/src/recurring.ts +90 -9
  93. package/src/restricted-fields.ts +129 -0
  94. package/src/rich-text.ts +112 -0
  95. package/src/routine-mail.ts +1272 -0
  96. package/src/runtime.ts +25 -12
  97. package/src/screens.ts +91 -0
  98. package/src/sellable.ts +595 -1
  99. package/src/slug.ts +7 -2
  100. package/src/staffed.ts +474 -0
  101. package/src/states.ts +220 -64
  102. package/src/stock.ts +332 -0
  103. package/src/team.ts +83 -0
  104. package/src/testing.ts +70 -6
  105. package/src/worked-on.ts +134 -0
package/src/manifest.ts CHANGED
@@ -3,25 +3,42 @@
3
3
  // diffs and reconciles the manifest. `validateManifest` is the contract check `extension.check`
4
4
  // runs; it returns structured issues a model can act on.
5
5
  import { z } from "zod";
6
+ import {
7
+ ACKNOWLEDGE_NOTICE_BODY_MAX,
8
+ ACKNOWLEDGE_NOTICE_TITLE_MAX,
9
+ ACKNOWLEDGE_REMINDER_MAX_DAYS,
10
+ MUST_READ_SCHEMA,
11
+ } from "./acknowledge.ts";
12
+ import {
13
+ agreementsManifestSchema,
14
+ checkObjectAgreements,
15
+ checkObjectHealthNotes,
16
+ healthNotesManifestSchema,
17
+ } from "./agreements.ts";
6
18
  import { allowanceManifestSchema, checkObjectAllowance } from "./allowance.ts";
7
19
  import { automationManifestSchema } from "./automation.ts";
8
- import { checkAutomation } from "./automation-check.ts";
20
+ import { checkAutomation, laterObject } from "./automation-check.ts";
9
21
  import { checkObjectBehaviour } from "./behaviour.ts";
22
+ import { calendarEntryManifestSchema, checkObjectCalendarEntry } from "./calendar-entry.ts";
10
23
  import {
11
24
  capacityManifestSchema,
12
25
  checkObjectCapacity,
13
26
  checkObjectClaims,
14
27
  claimsManifestSchema,
15
28
  } from "./capacity.ts";
29
+ import { checklistsManifestSchema, checkObjectChecklists } from "./checklists.ts";
16
30
  import {
17
31
  type Extension,
18
32
  HOST_MODULES,
19
33
  type HostModuleName,
20
34
  STAGE_TYPES,
21
35
  SUPPORTED_CONTRACT_VERSIONS,
36
+ TODAY_ITEM_COMPARES,
37
+ TODAY_ITEM_FORMATS,
22
38
  TOOL_AUDIENCES,
23
39
  TOOL_RISKS,
24
40
  } from "./contract.ts";
41
+ import { checkObjectDiscount, discountManifestSchema } from "./discount.ts";
25
42
  import {
26
43
  checkDocumentSchema,
27
44
  DOCUMENT_MAX_BYTES,
@@ -30,12 +47,27 @@ import {
30
47
  documentPathNode,
31
48
  } from "./document.ts";
32
49
  import { FIELD_TYPES, type FieldTypeName, formulaTypeOf } from "./field-types.ts";
33
- import { checkFormula, type FormulaFieldRef } from "./formula/compile.ts";
50
+ import { checkFormula, type FormulaFieldRef, PUBLISHED_FORMULA_FIELDS } from "./formula/compile.ts";
51
+ import { checkObjectIntake, intakeManifestSchema } from "./intake.ts";
52
+ import { journeySignalIssues, journeySignalsManifestSchema } from "./journey-signals.ts";
53
+ import { checkRoleMine, mineManifestSchema } from "./mine.ts";
54
+ import { checkObjectOccupies, occupiesManifestSchema } from "./occupies.ts";
34
55
  import { checkObjectRecurring, recurringManifestSchema } from "./recurring.ts";
35
56
  import { renamedMessage } from "./renamed.ts";
57
+ import { checkRestrictedFields, isRestrictedField } from "./restricted-fields.ts";
58
+ import { routineMailIssues, routineMailManifestSchema } from "./routine-mail.ts";
36
59
  import { checkObjectSellable, sellableManifestSchema } from "./sellable.ts";
37
- import { checkObjectStates, statesManifestSchema } from "./states.ts";
60
+ import { checkObjectStaffed, staffedManifestSchema } from "./staffed.ts";
61
+ import { checkObjectStates, resolveFieldPath, statesManifestSchema } from "./states.ts";
62
+ import {
63
+ checkObjectStock,
64
+ checkObjectStockMoves,
65
+ stockManifestSchema,
66
+ stockMovesManifestSchema,
67
+ } from "./stock.ts";
68
+ import { checkObjectTeam, teamManifestSchema } from "./team.ts";
38
69
  import { checkObjectUnique, uniqueManifestSchema } from "./unique.ts";
70
+ import { checkObjectWorkedOn, workedOnManifestSchema } from "./worked-on.ts";
39
71
 
40
72
  export const EXTENSION_ID_RE = /^[a-z][a-z0-9]{1,29}$/;
41
73
  export const OBJECT_NAME_RE = /^[a-z][a-z0-9]{0,29}$/;
@@ -108,6 +140,8 @@ export const fieldManifestSchema = z.object({
108
140
  default: z.union([z.string().max(1000), z.number(), z.boolean()]).optional(),
109
141
  defaultSetting: z.string().max(40).optional(),
110
142
  personApproves: z.boolean().optional(),
143
+ // Stage 54 step 2 (ADR 0811): only those granted this restricted permission of the pack read it.
144
+ restricted: z.string().max(80).optional(),
111
145
  to: z.string().max(80).optional(),
112
146
  many: z.boolean().optional(),
113
147
  expression: z.string().max(2000).optional(),
@@ -150,20 +184,30 @@ export const PUBLISHED_FIELD_NAMES = [
150
184
  "publishAt",
151
185
  ] as const;
152
186
 
187
+ // One condition of `when` (ADRs 0438 and 0689): a state of the record, or of the one `via` points
188
+ // to; or `via` alone, that the record it points to is public. Which shapes hold is checked below.
189
+ const readConditionSchema = z
190
+ .object({
191
+ via: z.string().max(40).optional(),
192
+ field: z.string().max(40).optional(),
193
+ in: z.array(z.string().max(100)).min(1).max(20).optional(),
194
+ })
195
+ .strict();
196
+
153
197
  const readDeclarationSchema = z
154
198
  .object({
155
199
  read: z.array(z.string().max(40)).min(1).max(100),
156
- when: z
157
- .object({
158
- via: z.string().max(40).optional(),
159
- field: z.string().max(40),
160
- in: z.array(z.string().max(100)).min(1).max(20),
161
- })
162
- .strict()
163
- .optional(),
200
+ // One condition, or up to three that must all hold (ADR 0689).
201
+ when: z.union([readConditionSchema, z.array(readConditionSchema).min(1).max(3)]).optional(),
164
202
  })
165
203
  .strict();
166
204
 
205
+ /** A `when` as its list of conditions, all of which must hold (ADR 0689). */
206
+ export function whenConditions<C>(when: C | readonly C[] | undefined): readonly C[] {
207
+ if (when === undefined) return [];
208
+ return Array.isArray(when) ? when : [when as C];
209
+ }
210
+
167
211
  export const stagesManifestSchema = z.object({
168
212
  field: z.string().max(40),
169
213
  stage: z.object({
@@ -184,7 +228,15 @@ export const stagesManifestSchema = z.object({
184
228
  });
185
229
  export type StagesManifest = z.infer<typeof stagesManifestSchema>;
186
230
 
187
- export const objectManifestSchema = z.object({
231
+ export /** The words of one notice the host sends for an acknowledged object (ADR 0706). */
232
+ const ackNotice = z
233
+ .object({
234
+ title: z.string().trim().min(1).max(ACKNOWLEDGE_NOTICE_TITLE_MAX),
235
+ body: z.string().trim().min(1).max(ACKNOWLEDGE_NOTICE_BODY_MAX).optional(),
236
+ })
237
+ .strict();
238
+
239
+ const objectManifestSchema = z.object({
188
240
  label: z.string().min(1).max(100),
189
241
  plural: z.string().min(1).max(100),
190
242
  icon: z.string().max(60).optional(),
@@ -201,11 +253,23 @@ export const objectManifestSchema = z.object({
201
253
  stages: stagesManifestSchema.optional(),
202
254
  capacity: capacityManifestSchema.optional(),
203
255
  sellable: sellableManifestSchema.optional(),
256
+ stock: stockManifestSchema.optional(),
257
+ stockMoves: stockMovesManifestSchema.optional(),
204
258
  allowance: allowanceManifestSchema.optional(),
259
+ discount: discountManifestSchema.optional(),
260
+ agreements: agreementsManifestSchema.optional(),
261
+ healthNotes: healthNotesManifestSchema.optional(),
205
262
  states: statesManifestSchema.optional(),
206
263
  claims: claimsManifestSchema.optional(),
207
264
  unique: uniqueManifestSchema.optional(),
208
265
  recurring: recurringManifestSchema.optional(),
266
+ staffed: staffedManifestSchema.optional(),
267
+ workedOn: workedOnManifestSchema.optional(),
268
+ team: teamManifestSchema.optional(),
269
+ occupies: occupiesManifestSchema.optional(),
270
+ calendarEntry: calendarEntryManifestSchema.optional(),
271
+ intake: intakeManifestSchema.optional(),
272
+ checklists: checklistsManifestSchema.optional(),
209
273
  owner: z.string().max(40).optional(),
210
274
  customer: z
211
275
  .object({
@@ -214,6 +278,11 @@ export const objectManifestSchema = z.object({
214
278
  write: z.array(z.string().max(40)).max(100),
215
279
  requireAccess: z.array(z.string().max(40)).max(10).optional(),
216
280
  createOnly: z.array(z.string().max(40)).max(100).optional(),
281
+ delete: z.boolean().optional(),
282
+ guardians: z
283
+ .object({ write: z.boolean().optional(), madeBy: z.string().max(40).optional() })
284
+ .strict()
285
+ .optional(),
217
286
  })
218
287
  .strict()
219
288
  .optional(),
@@ -269,6 +338,32 @@ export const objectManifestSchema = z.object({
269
338
  content: z.array(z.string().max(40)).min(1).max(40),
270
339
  slug: z.string().max(40).optional(),
271
340
  date: z.string().max(40).optional(),
341
+ publishIn: z.array(z.string().max(100)).min(1).max(20).optional(),
342
+ acknowledge: z
343
+ .object({
344
+ who: z.string().max(40),
345
+ manage: z.string().max(80),
346
+ // ADR 0706: more fields guarded as who must read is, who is told weekly, the words.
347
+ managed: z.array(z.string().max(40)).min(1).max(8).optional(),
348
+ owner: z.string().max(40).optional(),
349
+ notices: z
350
+ .object({
351
+ asked: ackNotice.optional(),
352
+ reminder: ackNotice
353
+ .extend({
354
+ afterDays: z.number().int().min(1).max(ACKNOWLEDGE_REMINDER_MAX_DAYS),
355
+ })
356
+ .strict()
357
+ .optional(),
358
+ outstanding: ackNotice.optional(),
359
+ welcome: ackNotice.optional(),
360
+ })
361
+ .strict()
362
+ .optional(),
363
+ })
364
+ .strict()
365
+ .optional(),
366
+ staffRead: z.boolean().optional(),
272
367
  })
273
368
  .strict()
274
369
  .optional(),
@@ -320,12 +415,24 @@ export const toolManifestSchema = z.object({
320
415
  description: z.string().min(20).max(2000),
321
416
  risk: z.enum(TOOL_RISKS),
322
417
  recordAction: recordActionManifestSchema.optional(),
323
- audiences: z.array(z.enum(TOOL_AUDIENCES)).min(1).max(3).optional(),
418
+ audiences: z.array(z.enum(TOOL_AUDIENCES)).min(1).max(4).optional(),
324
419
  customerFields: z.record(z.string().max(80), z.array(z.string().max(40)).max(50)).optional(),
325
420
  /** The permission a staff caller needs (`<id>:<word>`), for the extension's roles (ADR 0436). */
326
- permission: z.string().max(80).optional(),
421
+ permission: z.union([z.string().max(80), z.array(z.string().max(80)).min(1).max(5)]).optional(),
327
422
  /** Only a person may call it (ADR 0512). */
328
423
  humanOnly: z.literal(true).optional(),
424
+ /** A person approves anyone else's call (ADR 0552). */
425
+ personApproves: z.literal(true).optional(),
426
+ /** The grant opens it without the role's limits, on purpose (ADR 0600). */
427
+ grantLiftsRoleLimits: z.literal(true).optional(),
428
+ /** Every staff account may call it, pack roles included; the host decides (ADR 0652). */
429
+ anyStaff: z.literal(true).optional(),
430
+ /** A grantable core permission it needs instead of records:read or records:write (ADR 0652). */
431
+ corePermission: z.string().max(80).optional(),
432
+ /** Input fields the audit log never keeps (ADR 0626). */
433
+ redact: z.array(z.string().max(40)).max(20).optional(),
434
+ /** Answer keys the host never keeps (ADR 0628). */
435
+ redactResult: z.array(z.string().max(40)).max(20).optional(),
329
436
  inputSchema: jsonSchemaObject,
330
437
  outputSchema: jsonSchemaObject,
331
438
  });
@@ -337,12 +444,53 @@ export const roleManifestSchema = z.object({
337
444
  description: z.string().min(10).max(500),
338
445
  permissions: z.array(z.string().max(80)).max(20).default([]),
339
446
  read: z.array(z.string().max(80)).max(20).default([]),
447
+ /** Objects whose records the role reaches only on the organisation's local today (ADR 0553). */
448
+ today: z
449
+ .record(
450
+ z.string().max(80),
451
+ z.union([
452
+ z.string().max(122),
453
+ z
454
+ .object({
455
+ at: z.string().max(122),
456
+ until: z.string().max(122).optional(),
457
+ zone: z.string().max(122).optional(),
458
+ })
459
+ .strict(),
460
+ ]),
461
+ )
462
+ .optional(),
463
+ /** Objects whose records the role reaches only for the People its holder looks after (ADR 0889). */
464
+ looksAfter: z.record(z.string().max(80), z.string().max(40)).optional(),
465
+ /** Objects whose records the role reaches only through a live record naming its holder (ADR 0755). */
466
+ mine: z.record(z.string().max(80), mineManifestSchema).optional(),
340
467
  });
341
468
  export type RoleManifest = z.infer<typeof roleManifestSchema>;
342
469
 
470
+ /** A device role (ADR 0781): see `DeviceRoleSpec`. */
471
+ export const deviceRoleManifestSchema = z
472
+ .object({
473
+ label: z.string().min(1).max(60),
474
+ description: z.string().min(10).max(500),
475
+ permissions: z.array(z.string().max(80)).max(20).default([]),
476
+ screen: z
477
+ .object({ block: z.string().min(1).max(80), export: z.string().min(1).max(60) })
478
+ .strict(),
479
+ })
480
+ .strict();
481
+ export type DeviceRoleManifest = z.infer<typeof deviceRoleManifestSchema>;
482
+
343
483
  /** A role's or a tool's permission: `<extension id>:<word>`. */
344
484
  export const EXTENSION_PERMISSION_RE = /^([a-z][a-z0-9]{1,29}):([a-z][a-zA-Z0-9]{0,39})$/;
345
485
 
486
+ /** A tool's permissions, one or several (any one opens it, ADR 0600); none when it declares none. */
487
+ export function toolPermissions(tool: {
488
+ permission?: string | readonly string[] | undefined;
489
+ }): string[] {
490
+ const p = tool.permission;
491
+ return p === undefined ? [] : typeof p === "string" ? [p] : [...p];
492
+ }
493
+
346
494
  export const viewManifestSchema = z.object({
347
495
  label: z.string().min(1).max(100),
348
496
  object: z.string().max(80),
@@ -432,6 +580,96 @@ export const permissionsManifestSchema = z.object({
432
580
  });
433
581
  export type PermissionsManifest = z.infer<typeof permissionsManifestSchema>;
434
582
 
583
+ /** A shipped pack's staff screen (stage 47, ADR 0660): see `ScreenSpec`. */
584
+ export const screenManifestSchema = z
585
+ .object({
586
+ label: z.string().min(1).max(60),
587
+ block: z.string().min(1).max(80),
588
+ export: z.string().min(1).max(60),
589
+ nav: z
590
+ .object({
591
+ group: z.string().min(1).max(40),
592
+ order: z.number().int().min(0).max(1000).optional(),
593
+ })
594
+ .strict()
595
+ .optional(),
596
+ opens: z.array(z.string().max(80)).max(10).default([]),
597
+ writes: z.array(z.string().max(81)).max(10).optional(),
598
+ record: z
599
+ .object({ object: z.string().min(1).max(81), as: z.string().min(1).max(40) })
600
+ .strict()
601
+ .optional(),
602
+ })
603
+ .strict();
604
+ export type ScreenManifest = z.infer<typeof screenManifestSchema>;
605
+
606
+ /** A shipped pack's number on Today (stage 60, ADR 0870): see `TodayItemSpec`. */
607
+ export const todayItemManifestSchema = z
608
+ .object({
609
+ label: z.string().min(1).max(60),
610
+ order: z.number().int().min(0).max(1000).optional(),
611
+ // A string, not an enum: a money format is refused by the contract with the reason.
612
+ format: z.string().min(1).max(20),
613
+ sql: z.string().min(1).max(20_000),
614
+ compare: z.enum(TODAY_ITEM_COMPARES).optional(),
615
+ attention: z
616
+ .union([
617
+ z.object({ above: z.number().finite() }).strict(),
618
+ z.object({ below: z.number().finite() }).strict(),
619
+ ])
620
+ .optional(),
621
+ rows: z
622
+ .object({
623
+ sql: z.string().min(1).max(20_000),
624
+ label: z.string().min(1).max(63),
625
+ detail: z.string().min(1).max(63).optional(),
626
+ record: z
627
+ .object({ object: z.string().min(1).max(81), id: z.string().min(1).max(63) })
628
+ .strict(),
629
+ })
630
+ .strict()
631
+ .optional(),
632
+ opens: z.array(z.string().max(80)).max(10),
633
+ web: z
634
+ .object({ screen: z.string().min(1).max(40) })
635
+ .strict()
636
+ .optional(),
637
+ })
638
+ .strict();
639
+ export type TodayItemManifest = z.infer<typeof todayItemManifestSchema>;
640
+
641
+ /** At most this many Today items per pack (stage 60). */
642
+ export const MAX_TODAY_ITEMS = 8;
643
+ /** A result column a Today item's rows name: `member`, `person_id`. */
644
+ const COLUMN_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]{0,62}$/;
645
+
646
+ /** A block and the component it exports, as a portal section names them (ADR 0710). */
647
+ const sectionBlockSchema = z
648
+ .object({ block: z.string().min(1).max(80), export: z.string().min(1).max(60) })
649
+ .strict();
650
+
651
+ /** A shipped pack's section of My account (stage 48, ADR 0710): see `PortalSectionSpec`. */
652
+ export const portalSectionManifestSchema = z
653
+ .object({
654
+ label: z.string().min(1).max(60),
655
+ web: sectionBlockSchema.optional(),
656
+ native: sectionBlockSchema.optional(),
657
+ order: z.number().int(),
658
+ has: z.array(z.string().max(81)).max(10),
659
+ })
660
+ .strict();
661
+ export type PortalSectionManifest = z.infer<typeof portalSectionManifestSchema>;
662
+
663
+ /** Where a pack's section may sit: before the base sections, which start at 60. */
664
+ export const PORTAL_ORDER = { min: 1, max: 59 } as const;
665
+
666
+ /** A screen's key, as a tool's: `desk`, `classList`. */
667
+ export const SCREEN_NAME_RE = /^[a-z][a-zA-Z0-9]{0,39}$/;
668
+ /** A block's name: lowercase words joined by hyphens (`bookings-desk`). */
669
+ const BLOCK_NAME_RE = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)+$/;
670
+ /** A component a block exports: `Desk`, `RosterWeek`. */
671
+ const COMPONENT_NAME_RE = /^[A-Z][A-Za-z0-9]{0,59}$/;
672
+
435
673
  export const manifestSchema = z.object({
436
674
  id: z.string(),
437
675
  version: z.string(),
@@ -458,8 +696,51 @@ export const manifestSchema = z.object({
458
696
  tools: z.record(z.string(), toolManifestSchema).default({}),
459
697
  automations: z.record(z.string(), automationManifestSchema).default({}),
460
698
  roles: z.record(z.string(), roleManifestSchema).default({}),
699
+ /** A shipped pack's device roles, for an enrolled device (ADR 0781). */
700
+ deviceRoles: z.record(z.string(), deviceRoleManifestSchema).optional(),
461
701
  /** Tool permissions an admin may grant one by one (ADR 0449). */
462
702
  grantable: z.array(z.string().max(80)).max(20).optional(),
703
+ /** A shipped extension's routine mail (ADR 0590). */
704
+ routineMail: routineMailManifestSchema.optional(),
705
+ /** A shipped extension's journey signals (stage 53, ADR 0802). */
706
+ journeySignals: journeySignalsManifestSchema.optional(),
707
+ /** What each grantable permission gives, in plain words, for the admin (ADR 0600). */
708
+ grantableLabels: z.record(z.string().max(80), z.string().min(10).max(300)).optional(),
709
+ /** Tool permissions held by admins and by grant only (ADR 0625). */
710
+ restricted: z.array(z.string().max(80)).max(20).optional(),
711
+ /** The roster's rules this extension sets for the host (ADR 0626). */
712
+ staffing: z
713
+ .object({
714
+ rosters: z.string().max(80),
715
+ /** Who reads and locks pay (ADR 0627): a restricted permission of this extension. */
716
+ pays: z.string().max(80).optional(),
717
+ settings: z
718
+ .object({
719
+ offerCutoffMinutes: z.string().max(64).optional(),
720
+ uncoveredDays: z.string().max(64).optional(),
721
+ payPeriod: z.string().max(64).optional(),
722
+ payPeriodStart: z.string().max(64).optional(),
723
+ payPeriodDay: z.string().max(64).optional(),
724
+ /** Staff record their time (stage 58, ADR 0850): a boolean setting, off by default. */
725
+ recordsTime: z.string().max(64).optional(),
726
+ /** How many days back time may be entered. */
727
+ enterDays: z.string().max(64).optional(),
728
+ /** Hours after a shift's end an open entry is marked finish missing. */
729
+ finishMissingHours: z.string().max(64).optional(),
730
+ /** Minutes an entry may differ from its shift and still match it (ADR 0851). */
731
+ matchMinutes: z.string().max(64).optional(),
732
+ })
733
+ .strict()
734
+ .optional(),
735
+ })
736
+ .strict()
737
+ .optional(),
738
+ /** A shipped pack's staff screens in the product's admin (stage 47, ADR 0660). */
739
+ screens: z.record(z.string(), screenManifestSchema).optional(),
740
+ /** A shipped pack's sections of My account (stage 48, ADR 0710). */
741
+ portal: z.record(z.string(), portalSectionManifestSchema).optional(),
742
+ /** A shipped pack's numbers on the owner's Today (stage 60, ADR 0870). */
743
+ todayItems: z.record(z.string(), todayItemManifestSchema).optional(),
463
744
  });
464
745
  export type ExtensionManifest = z.infer<typeof manifestSchema>;
465
746
 
@@ -635,8 +916,19 @@ export function toManifest(extension: Extension): ExtensionManifest {
635
916
  risk: tool.risk ?? "write",
636
917
  ...(tool.recordAction ? { recordAction: tool.recordAction } : {}),
637
918
  ...(tool.audiences ? { audiences: [...tool.audiences] } : {}),
638
- ...(tool.permission ? { permission: tool.permission } : {}),
919
+ ...(tool.permission
920
+ ? {
921
+ permission:
922
+ typeof tool.permission === "string" ? tool.permission : [...tool.permission],
923
+ }
924
+ : {}),
639
925
  ...(tool.humanOnly ? { humanOnly: true as const } : {}),
926
+ ...(tool.personApproves ? { personApproves: true as const } : {}),
927
+ ...(tool.grantLiftsRoleLimits ? { grantLiftsRoleLimits: true as const } : {}),
928
+ ...(tool.anyStaff ? { anyStaff: true as const } : {}),
929
+ ...(tool.corePermission ? { corePermission: tool.corePermission } : {}),
930
+ ...(tool.redact?.length ? { redact: [...tool.redact] } : {}),
931
+ ...(tool.redactResult?.length ? { redactResult: [...tool.redactResult] } : {}),
640
932
  ...(tool.customerFields
641
933
  ? {
642
934
  customerFields: Object.fromEntries(
@@ -665,11 +957,122 @@ export function toManifest(extension: Extension): ExtensionManifest {
665
957
  ...(automation.rails ? { rails: automation.rails } : {}),
666
958
  ...(automation.connections?.length ? { connections: automation.connections } : {}),
667
959
  ...(automation.enabled === false ? { enabled: false } : {}),
960
+ ...(automation.onlyWith?.length ? { onlyWith: [...automation.onlyWith] } : {}),
668
961
  },
669
962
  ]),
670
963
  ),
671
964
  ...(extension.grantable ? { grantable: [...extension.grantable] } : {}),
965
+ ...(extension.grantableLabels ? { grantableLabels: { ...extension.grantableLabels } } : {}),
966
+ ...(extension.restricted ? { restricted: [...extension.restricted] } : {}),
967
+ ...(extension.staffing
968
+ ? {
969
+ staffing: {
970
+ rosters: extension.staffing.rosters,
971
+ ...(extension.staffing.pays ? { pays: extension.staffing.pays } : {}),
972
+ ...(extension.staffing.settings
973
+ ? { settings: { ...extension.staffing.settings } }
974
+ : {}),
975
+ },
976
+ }
977
+ : {}),
978
+ ...(extension.screens && Object.keys(extension.screens).length
979
+ ? {
980
+ screens: Object.fromEntries(
981
+ Object.entries(extension.screens).map(([name, screen]) => [
982
+ name,
983
+ {
984
+ label: screen.label,
985
+ block: screen.block,
986
+ export: screen.export,
987
+ ...(screen.nav
988
+ ? {
989
+ nav: {
990
+ group: screen.nav.group,
991
+ ...(screen.nav.order !== undefined ? { order: screen.nav.order } : {}),
992
+ },
993
+ }
994
+ : {}),
995
+ opens: [...(screen.opens ?? [])],
996
+ ...(screen.writes?.length ? { writes: [...screen.writes] } : {}),
997
+ ...(screen.record
998
+ ? { record: { object: screen.record.object, as: screen.record.as } }
999
+ : {}),
1000
+ },
1001
+ ]),
1002
+ ),
1003
+ }
1004
+ : {}),
1005
+ ...(extension.deviceRoles && Object.keys(extension.deviceRoles).length
1006
+ ? {
1007
+ deviceRoles: Object.fromEntries(
1008
+ Object.entries(extension.deviceRoles).map(([name, role]) => [
1009
+ name,
1010
+ {
1011
+ label: role.label,
1012
+ description: role.description,
1013
+ permissions: [...role.permissions],
1014
+ screen: { block: role.screen.block, export: role.screen.export },
1015
+ },
1016
+ ]),
1017
+ ),
1018
+ }
1019
+ : {}),
1020
+ ...(extension.todayItems && Object.keys(extension.todayItems).length
1021
+ ? {
1022
+ todayItems: Object.fromEntries(
1023
+ Object.entries(extension.todayItems).map(([name, item]) => [
1024
+ name,
1025
+ {
1026
+ label: item.label,
1027
+ ...(item.order !== undefined ? { order: item.order } : {}),
1028
+ format: item.format,
1029
+ sql: item.sql,
1030
+ ...(item.compare ? { compare: item.compare } : {}),
1031
+ ...(item.attention ? { attention: { ...item.attention } } : {}),
1032
+ ...(item.rows
1033
+ ? {
1034
+ rows: {
1035
+ sql: item.rows.sql,
1036
+ label: item.rows.label,
1037
+ ...(item.rows.detail ? { detail: item.rows.detail } : {}),
1038
+ record: { object: item.rows.record.object, id: item.rows.record.id },
1039
+ },
1040
+ }
1041
+ : {}),
1042
+ opens: [...item.opens],
1043
+ ...(item.web ? { web: { screen: item.web.screen } } : {}),
1044
+ },
1045
+ ]),
1046
+ ),
1047
+ }
1048
+ : {}),
1049
+ ...(extension.portal && Object.keys(extension.portal).length
1050
+ ? {
1051
+ portal: Object.fromEntries(
1052
+ Object.entries(extension.portal).map(([key, section]) => [
1053
+ key,
1054
+ {
1055
+ label: section.label,
1056
+ ...(section.web
1057
+ ? { web: { block: section.web.block, export: section.web.export } }
1058
+ : {}),
1059
+ ...(section.native
1060
+ ? { native: { block: section.native.block, export: section.native.export } }
1061
+ : {}),
1062
+ order: section.order,
1063
+ has: [...section.has],
1064
+ },
1065
+ ]),
1066
+ ),
1067
+ }
1068
+ : {}),
672
1069
  ...(extension.requires?.length ? { requires: [...extension.requires] } : {}),
1070
+ ...(extension.routineMail && Object.keys(extension.routineMail).length
1071
+ ? { routineMail: extension.routineMail }
1072
+ : {}),
1073
+ ...(extension.journeySignals && Object.keys(extension.journeySignals).length
1074
+ ? { journeySignals: extension.journeySignals }
1075
+ : {}),
673
1076
  roles: Object.fromEntries(
674
1077
  Object.entries(extension.roles ?? {}).map(([name, role]) => [
675
1078
  name,
@@ -678,6 +1081,10 @@ export function toManifest(extension: Extension): ExtensionManifest {
678
1081
  description: role.description,
679
1082
  permissions: [...role.permissions],
680
1083
  read: [...role.read],
1084
+ ...(role.today ? { today: { ...role.today } } : {}),
1085
+ ...(role.looksAfter ? { looksAfter: { ...role.looksAfter } } : {}),
1086
+ // Plain data: copied so the manifest shares nothing with the definition.
1087
+ ...(role.mine ? { mine: JSON.parse(JSON.stringify(role.mine)) } : {}),
681
1088
  },
682
1089
  ]),
683
1090
  ),
@@ -773,6 +1180,29 @@ export interface ValidateOptions {
773
1180
  * automation checks; null when unknown (those checks are skipped). Core objects are built in.
774
1181
  */
775
1182
  objectFields?: (object: string) => Record<string, FieldTypeName> | null;
1183
+ /**
1184
+ * Further ids no extension may take: the host passes the namespaces of its own permissions
1185
+ * (`agreements`, `orders`, `people`, …), derived from its permission list, so a pack can never
1186
+ * declare a core permission such as `agreements:manage` as its own grantable one.
1187
+ */
1188
+ reservedIds?: readonly string[];
1189
+ }
1190
+
1191
+ /**
1192
+ * The environment a formula of an object's own field compiles in, as on the host
1193
+ * (formulaEnvironment): its fields, every record's timestamps and, on a publishable object, when
1194
+ * its current version went live and its number (ADR 0706).
1195
+ */
1196
+ export function objectFormulaEnvironment(object: {
1197
+ fields: Record<string, FieldManifest>;
1198
+ publishable?: unknown;
1199
+ }): Record<string, FormulaFieldRef> {
1200
+ return {
1201
+ createdAt: { type: "datetime", sql: '"created_at"' },
1202
+ updatedAt: { type: "datetime", sql: '"updated_at"' },
1203
+ ...(object.publishable ? PUBLISHED_FORMULA_FIELDS : {}),
1204
+ ...formulaFields(object.fields),
1205
+ };
776
1206
  }
777
1207
 
778
1208
  /** Formula environment for a set of field manifests (formula fields compile on demand). */
@@ -781,6 +1211,8 @@ export function formulaFields(
781
1211
  ): Record<string, FormulaFieldRef> {
782
1212
  const env: Record<string, FormulaFieldRef> = {};
783
1213
  for (const [name, field] of Object.entries(fields)) {
1214
+ // A restricted value is in no view, so no formula reads it (ADR 0811).
1215
+ if (isRestrictedField(field)) continue;
784
1216
  if (field.type === "formula") {
785
1217
  env[name] = { expression: field.expression ?? "" };
786
1218
  continue;
@@ -791,10 +1223,358 @@ export function formulaFields(
791
1223
  return env;
792
1224
  }
793
1225
 
1226
+ /**
1227
+ * A shipped pack's screens (stage 47, ADR 0660), against its own manifest: each names a web block
1228
+ * of this pack and a component it exports (that both exist is the admin's build's check, which
1229
+ * fails on a missing one), and is gated by this pack's own tools, at least one of them for staff
1230
+ * only. A record screen is on one of this pack's objects or a base one. That only a shipped pack
1231
+ * declares screens is the host's check (`cos ext check` and install refuse a runtime one).
1232
+ */
1233
+ export function screenIssues(m: ExtensionManifest): { path: string; message: string }[] {
1234
+ const issues: { path: string; message: string }[] = [];
1235
+ const add = (path: string, message: string) => issues.push({ path, message });
1236
+ for (const [name, screen] of Object.entries(m.screens ?? {})) {
1237
+ const path = `screens.${name}`;
1238
+ if (!SCREEN_NAME_RE.test(name)) add(path, `Screen name "${name}" must be camelCase`);
1239
+ if (
1240
+ !BLOCK_NAME_RE.test(screen.block) ||
1241
+ !screen.block.startsWith(`${m.id}-`) ||
1242
+ screen.block.includes("-native-")
1243
+ ) {
1244
+ add(
1245
+ `${path}.block`,
1246
+ `"${screen.block}" must be a web block of this pack (${m.id}-<name>, never a native one or another pack's)`,
1247
+ );
1248
+ }
1249
+ if (!COMPONENT_NAME_RE.test(screen.export)) {
1250
+ add(`${path}.export`, `"${screen.export}" must be the name of a component (PascalCase)`);
1251
+ }
1252
+ const seen = new Set<string>();
1253
+ let staffOnly = false;
1254
+ screen.opens.forEach((tool, i) => {
1255
+ const at = `${path}.opens.${i}`;
1256
+ if (seen.has(tool)) add(at, `"${tool}" is named twice`);
1257
+ seen.add(tool);
1258
+ const spec = Object.hasOwn(m.tools, tool) ? m.tools[tool] : undefined;
1259
+ if (!spec) {
1260
+ add(at, `"${tool}" is not a tool of this pack: a screen is gated by its own pack's tools`);
1261
+ return;
1262
+ }
1263
+ const audiences = spec.audiences ?? ["staff"];
1264
+ if (!audiences.includes("staff")) {
1265
+ add(at, `"${tool}" is not for staff, so no member of staff could open this screen`);
1266
+ }
1267
+ if (audiences.every((a) => a === "staff")) staffOnly = true;
1268
+ });
1269
+ const writes = screen.writes ?? [];
1270
+ writes.forEach((object, i) => {
1271
+ const local = object.startsWith(`${m.id}.`) ? object.slice(m.id.length + 1) : null;
1272
+ if (local === null || !Object.hasOwn(m.objects, local)) {
1273
+ add(`${path}.writes.${i}`, `"${object}" must be an object of this pack (${m.id}.<object>)`);
1274
+ }
1275
+ });
1276
+ if (!screen.opens.length && !writes.length) {
1277
+ add(
1278
+ `${path}.opens`,
1279
+ "A screen names at least one tool (opens) or object (writes) that gates it",
1280
+ );
1281
+ }
1282
+ // A record screen is a tab on a staff record page, about that one record: a gate of tools staff
1283
+ // share with customers (a coach logging a client's sets) is staff's there. Any other screen
1284
+ // names a tool for staff only, or writes an object, so no customer's screen becomes a staff one.
1285
+ if (screen.opens.length && !staffOnly && !writes.length && !screen.record) {
1286
+ add(
1287
+ `${path}.opens`,
1288
+ "A screen's gate names at least one tool for staff only: a tool open to customers or the public is never the only gate",
1289
+ );
1290
+ }
1291
+ if (screen.record) {
1292
+ const { object, as } = screen.record;
1293
+ const local = object.startsWith(`${m.id}.`) ? object.slice(m.id.length + 1) : null;
1294
+ const own = local !== null && Object.hasOwn(m.objects, local);
1295
+ if (!own && object !== "person" && object !== "organisation") {
1296
+ add(
1297
+ `${path}.record.object`,
1298
+ `"${object}" must be an object of this pack (${m.id}.<object>), person or organisation`,
1299
+ );
1300
+ }
1301
+ if (!FIELD_NAME_RE.test(as)) add(`${path}.record.as`, `"${as}" must be a camelCase prop`);
1302
+ }
1303
+ }
1304
+ return issues;
1305
+ }
1306
+
1307
+ /**
1308
+ * Device roles and the tools open to a device (ADR 0781), against the manifest itself:
1309
+ * - a tool open to `device` is open to nobody else, is a read or a write, and names a
1310
+ * permission of this pack that a device role holds; it is no record action, waits for no
1311
+ * person and is no staff tool's;
1312
+ * - a device role holds at least one permission, each a permission of this pack's device tools
1313
+ * only (never a staff tool's, a staff role's, a grantable or a restricted one), and names its
1314
+ * screen: a web block of this pack and the component it exports.
1315
+ * That only a shipped pack declares device roles is the host's check (`cos ext check` and
1316
+ * install refuse a runtime one).
1317
+ */
1318
+ export function deviceRoleIssues(m: ExtensionManifest): { path: string; message: string }[] {
1319
+ const issues: { path: string; message: string }[] = [];
1320
+ const add = (path: string, message: string) => issues.push({ path, message });
1321
+ const roles = m.deviceRoles ?? {};
1322
+ const held = new Set(Object.values(roles).flatMap((role) => role.permissions));
1323
+ const staffHeld = new Set([
1324
+ ...Object.values(m.roles).flatMap((role) => role.permissions),
1325
+ ...(m.grantable ?? []),
1326
+ ...(m.restricted ?? []),
1327
+ ]);
1328
+ for (const [name, tool] of Object.entries(m.tools)) {
1329
+ const audiences = tool.audiences ?? [];
1330
+ if (!audiences.includes("device")) continue;
1331
+ const path = `tools.${name}`;
1332
+ if (audiences.length !== 1) {
1333
+ add(
1334
+ `${path}.audiences`,
1335
+ 'A tool open to device is open to nobody else: audiences ["device"]',
1336
+ );
1337
+ }
1338
+ const permissions = toolPermissions(tool);
1339
+ if (!permissions.length) {
1340
+ add(`${path}.permission`, "A tool open to device names the permission a device role holds");
1341
+ }
1342
+ for (const permission of permissions) {
1343
+ if (!held.has(permission)) {
1344
+ add(`${path}.permission`, `No device role of this pack holds "${permission}"`);
1345
+ }
1346
+ }
1347
+ if (tool.recordAction || tool.grantLiftsRoleLimits) {
1348
+ add(path, "A tool open to device is no record action and lifts no staff role's limits");
1349
+ }
1350
+ }
1351
+ for (const [name, role] of Object.entries(roles)) {
1352
+ const path = `deviceRoles.${name}`;
1353
+ if (!FIELD_NAME_RE.test(name)) add(path, `Device role name "${name}" must be camelCase`);
1354
+ if (!role.permissions.length)
1355
+ add(`${path}.permissions`, "A device role holds at least one permission");
1356
+ for (const permission of role.permissions) {
1357
+ const tools = Object.values(m.tools).filter((t) => toolPermissions(t).includes(permission));
1358
+ const ok =
1359
+ EXTENSION_PERMISSION_RE.exec(permission)?.[1] === m.id &&
1360
+ tools.length > 0 &&
1361
+ tools.every((t) => t.audiences?.length === 1 && t.audiences[0] === "device");
1362
+ if (!ok) {
1363
+ add(
1364
+ `${path}.permissions`,
1365
+ `"${permission}" must be the permission of this pack's tools open to device only (audiences ["device"])`,
1366
+ );
1367
+ }
1368
+ if (staffHeld.has(permission)) {
1369
+ add(
1370
+ `${path}.permissions`,
1371
+ `"${permission}" is a staff role's, grantable or restricted: a device role's permission is held by devices only`,
1372
+ );
1373
+ }
1374
+ }
1375
+ if (
1376
+ !BLOCK_NAME_RE.test(role.screen.block) ||
1377
+ !role.screen.block.startsWith(`${m.id}-`) ||
1378
+ role.screen.block.includes("-native-")
1379
+ ) {
1380
+ add(
1381
+ `${path}.screen.block`,
1382
+ `"${role.screen.block}" must be a web block of this pack (${m.id}-<name>, never a native one or another pack's)`,
1383
+ );
1384
+ }
1385
+ if (!COMPONENT_NAME_RE.test(role.screen.export)) {
1386
+ add(
1387
+ `${path}.screen.export`,
1388
+ `"${role.screen.export}" must be the name of a component (PascalCase)`,
1389
+ );
1390
+ }
1391
+ }
1392
+ return issues;
1393
+ }
1394
+
1395
+ /**
1396
+ * A shipped pack's Today items (stage 60, ADR 0870), against its own manifest: at most 8, keys
1397
+ * camelCase, a count or a percent (never money: that is the host's, through Finance reports), gated
1398
+ * by this pack's own tools as a screen is (at least one for staff only), rows that open one of
1399
+ * this pack's objects or a base one, and a web screen this pack declares. What the SQL reads,
1400
+ * that it writes nothing and that it returns `value` is the host's check (it has the SQL guards);
1401
+ * so is that only a shipped pack declares items (`cos ext check` and install refuse a runtime one).
1402
+ */
1403
+ export function todayItemIssues(m: ExtensionManifest): { path: string; message: string }[] {
1404
+ const issues: { path: string; message: string }[] = [];
1405
+ const add = (path: string, message: string) => issues.push({ path, message });
1406
+ const items = Object.entries(m.todayItems ?? {});
1407
+ if (items.length > MAX_TODAY_ITEMS) {
1408
+ add("todayItems", `A pack declares at most ${MAX_TODAY_ITEMS} Today items`);
1409
+ }
1410
+ for (const [name, item] of items) {
1411
+ const path = `todayItems.${name}`;
1412
+ if (!SCREEN_NAME_RE.test(name)) add(path, `Today item name "${name}" must be camelCase`);
1413
+ if (!(TODAY_ITEM_FORMATS as readonly string[]).includes(item.format)) {
1414
+ add(
1415
+ `${path}.format`,
1416
+ /money|currency|amount/i.test(item.format)
1417
+ ? "A pack declares no money item: money on Today is the host's, from Finance reports (stage 52)"
1418
+ : `"${item.format}" must be one of ${TODAY_ITEM_FORMATS.join(", ")}`,
1419
+ );
1420
+ }
1421
+ const seen = new Set<string>();
1422
+ let staffOnly = false;
1423
+ item.opens.forEach((tool, i) => {
1424
+ const at = `${path}.opens.${i}`;
1425
+ if (seen.has(tool)) add(at, `"${tool}" is named twice`);
1426
+ seen.add(tool);
1427
+ const spec = Object.hasOwn(m.tools, tool) ? m.tools[tool] : undefined;
1428
+ if (!spec) {
1429
+ add(
1430
+ at,
1431
+ `"${tool}" is not a tool of this pack: a Today item is gated by its own pack's tools`,
1432
+ );
1433
+ return;
1434
+ }
1435
+ const audiences = spec.audiences ?? ["staff"];
1436
+ if (!audiences.includes("staff")) {
1437
+ add(at, `"${tool}" is not for staff, so no member of staff could see this item`);
1438
+ }
1439
+ if (audiences.every((a) => a === "staff")) staffOnly = true;
1440
+ });
1441
+ if (!item.opens.length) {
1442
+ add(`${path}.opens`, "A Today item names at least one of this pack's tools that gates it");
1443
+ } else if (!staffOnly) {
1444
+ add(
1445
+ `${path}.opens`,
1446
+ "A Today item's gate names at least one tool for staff only: a tool open to customers or the public is never the only gate",
1447
+ );
1448
+ }
1449
+ if (item.rows) {
1450
+ const { label, detail, record } = item.rows;
1451
+ for (const [key, column] of [
1452
+ ["label", label],
1453
+ ["detail", detail],
1454
+ ["record.id", record.id],
1455
+ ] as const) {
1456
+ if (column !== undefined && !COLUMN_NAME_RE.test(column)) {
1457
+ add(`${path}.rows.${key}`, `"${column}" must be the name of a column the rows return`);
1458
+ }
1459
+ }
1460
+ const local = record.object.startsWith(`${m.id}.`)
1461
+ ? record.object.slice(m.id.length + 1)
1462
+ : null;
1463
+ const own = local !== null && Object.hasOwn(m.objects, local);
1464
+ if (!own && record.object !== "person" && record.object !== "organisation") {
1465
+ add(
1466
+ `${path}.rows.record.object`,
1467
+ `"${record.object}" must be an object of this pack (${m.id}.<object>), person or organisation`,
1468
+ );
1469
+ }
1470
+ }
1471
+ if (item.web && !Object.hasOwn(m.screens ?? {}, item.web.screen)) {
1472
+ add(`${path}.web.screen`, `"${item.web.screen}" is not a screen this pack declares`);
1473
+ }
1474
+ }
1475
+ return issues;
1476
+ }
1477
+
1478
+ /**
1479
+ * A shipped pack's sections of My account (stage 48, ADR 0710), against its own manifest: each
1480
+ * names a web block of this pack (never a native one) and a native block of this pack, at least
1481
+ * one of the two, each with a component it exports; sits before the base sections; and shows on
1482
+ * records of this pack's own objects that declare a customer (`has`, never empty). What the
1483
+ * blocks are (their skin, their pack, that they call only what a customer or the public may) is
1484
+ * read from their block.json by `cos ext check`; that only a shipped pack declares sections is the
1485
+ * host's check (`cos ext check` and install refuse a runtime one).
1486
+ */
1487
+ export function portalIssues(m: ExtensionManifest): { path: string; message: string }[] {
1488
+ const issues: { path: string; message: string }[] = [];
1489
+ const add = (path: string, message: string) => issues.push({ path, message });
1490
+ for (const [key, section] of Object.entries(m.portal ?? {})) {
1491
+ const path = `portal.${key}`;
1492
+ if (!SCREEN_NAME_RE.test(key)) add(path, `Section key "${key}" must be camelCase`);
1493
+ if (!section.web && !section.native) {
1494
+ add(path, "A section names its web block, its native block, or both");
1495
+ }
1496
+ if (section.web) {
1497
+ const { block } = section.web;
1498
+ if (
1499
+ !BLOCK_NAME_RE.test(block) ||
1500
+ !block.startsWith(`${m.id}-`) ||
1501
+ block.includes("-native-")
1502
+ ) {
1503
+ add(
1504
+ `${path}.web.block`,
1505
+ `"${block}" must be a web block of this pack (${m.id}-<name>, never a native one or another pack's)`,
1506
+ );
1507
+ }
1508
+ }
1509
+ if (section.native) {
1510
+ const { block } = section.native;
1511
+ if (!BLOCK_NAME_RE.test(block) || !block.startsWith(`${m.id}-native-`)) {
1512
+ add(
1513
+ `${path}.native.block`,
1514
+ `"${block}" must be a native block of this pack (${m.id}-native-<name>, never a web one or another pack's)`,
1515
+ );
1516
+ }
1517
+ }
1518
+ for (const skin of ["web", "native"] as const) {
1519
+ const named = section[skin]?.export;
1520
+ if (named !== undefined && !COMPONENT_NAME_RE.test(named)) {
1521
+ add(`${path}.${skin}.export`, `"${named}" must be the name of a component (PascalCase)`);
1522
+ }
1523
+ }
1524
+ if (section.order < PORTAL_ORDER.min || section.order > PORTAL_ORDER.max) {
1525
+ add(
1526
+ `${path}.order`,
1527
+ `A section's order is ${PORTAL_ORDER.min} to ${PORTAL_ORDER.max}: the base sections come after`,
1528
+ );
1529
+ }
1530
+ if (!section.has.length) {
1531
+ add(
1532
+ `${path}.has`,
1533
+ "A section names at least one object whose records are the customer's: a page anyone may open is a page the client links to, not a section",
1534
+ );
1535
+ }
1536
+ const seen = new Set<string>();
1537
+ section.has.forEach((object, i) => {
1538
+ const at = `${path}.has.${i}`;
1539
+ if (seen.has(object)) add(at, `"${object}" is named twice`);
1540
+ seen.add(object);
1541
+ const local = object.startsWith(`${m.id}.`) ? object.slice(m.id.length + 1) : null;
1542
+ const own = local !== null && Object.hasOwn(m.objects, local) ? m.objects[local] : undefined;
1543
+ if (!own) {
1544
+ add(at, `"${object}" must be an object of this pack (${m.id}.<object>)`);
1545
+ } else if (!own.customer) {
1546
+ add(
1547
+ at,
1548
+ `"${object}" declares no customer: a section shows on records that are the customer's own`,
1549
+ );
1550
+ }
1551
+ });
1552
+ }
1553
+ return issues;
1554
+ }
1555
+
794
1556
  /**
795
1557
  * The contract check: structure (zod), names, references, permissions and formulas. Returns
796
1558
  * every issue found (empty when the manifest is valid) and the parsed manifest when it parsed.
797
1559
  */
1560
+ /** Every property name of a JSON schema, at any depth (objects, arrays, unions). */
1561
+ function schemaKeys(schema: unknown, into: Set<string> = new Set()): Set<string> {
1562
+ if (!schema || typeof schema !== "object") return into;
1563
+ const node = schema as Record<string, unknown>;
1564
+ const properties = node.properties;
1565
+ if (properties && typeof properties === "object") {
1566
+ for (const [key, value] of Object.entries(properties as Record<string, unknown>)) {
1567
+ into.add(key);
1568
+ schemaKeys(value, into);
1569
+ }
1570
+ }
1571
+ for (const key of ["items", "additionalProperties"]) schemaKeys(node[key], into);
1572
+ for (const key of ["anyOf", "oneOf", "allOf"]) {
1573
+ if (Array.isArray(node[key])) for (const part of node[key] as unknown[]) schemaKeys(part, into);
1574
+ }
1575
+ return into;
1576
+ }
1577
+
798
1578
  export function validateManifest(
799
1579
  input: unknown,
800
1580
  options: ValidateOptions = {},
@@ -812,7 +1592,11 @@ export function validateManifest(
812
1592
  }
813
1593
  const m = parsed.data;
814
1594
 
815
- if (!EXTENSION_ID_RE.test(m.id) || RESERVED_EXTENSION_IDS.has(m.id)) {
1595
+ if (
1596
+ !EXTENSION_ID_RE.test(m.id) ||
1597
+ RESERVED_EXTENSION_IDS.has(m.id) ||
1598
+ options.reservedIds?.includes(m.id)
1599
+ ) {
816
1600
  contract(
817
1601
  "id",
818
1602
  `Extension id "${m.id}" must be 2-30 lowercase letters or digits, start with a letter, and not be reserved`,
@@ -981,20 +1765,28 @@ export function validateManifest(
981
1765
  );
982
1766
  }
983
1767
  // Every record's own timestamps can be read too, as on the host (formulaEnvironment).
984
- const env = {
985
- createdAt: { type: "datetime", sql: '"created_at"' } as FormulaFieldRef,
986
- updatedAt: { type: "datetime", sql: '"updated_at"' } as FormulaFieldRef,
987
- ...formulaFields(object.fields),
988
- };
1768
+ const env = objectFormulaEnvironment(object);
989
1769
  checkFields(`${path}.fields`, `${m.id}.${name}`, object.fields, env);
990
1770
  checkObjectBehaviour(m, name, object, contract);
991
1771
  checkObjectCapacity(m, name, object, contract);
992
1772
  checkObjectSellable(m, name, object, contract);
1773
+ checkObjectStock(m, name, object, contract);
1774
+ checkObjectStockMoves(m, name, object, contract);
993
1775
  checkObjectAllowance(m, name, object, contract);
1776
+ checkObjectDiscount(m, name, object, contract);
1777
+ checkObjectAgreements(m, name, object, contract);
1778
+ checkObjectHealthNotes(m, name, object, contract);
994
1779
  checkObjectStates(m, name, object, contract);
995
1780
  checkObjectClaims(m, name, object, contract);
996
1781
  checkObjectUnique(m, name, object, contract);
997
1782
  checkObjectRecurring(m, name, object, contract);
1783
+ checkObjectStaffed(m, name, object, contract);
1784
+ checkObjectWorkedOn(m, name, object, contract);
1785
+ checkObjectTeam(m, name, object, contract);
1786
+ checkObjectOccupies(m, name, object, contract);
1787
+ checkObjectCalendarEntry(m, name, object, contract);
1788
+ checkObjectIntake(m, name, object, contract);
1789
+ checkObjectChecklists(m, name, object, contract);
998
1790
  object.requireOneOf?.forEach((group, i) => {
999
1791
  for (const field of group) {
1000
1792
  if (!object.fields[field]) {
@@ -1086,7 +1878,9 @@ export function validateManifest(
1086
1878
  );
1087
1879
  for (const { name, object, key, p } of readDeclarations) {
1088
1880
  const path = `objects.${name}.${key}`;
1089
- if (key === "public" && object.customer) {
1881
+ // A publishable object with an author (ADR 0810) declares both: the author reads the working
1882
+ // copy, the public the published version.
1883
+ if (key === "public" && object.customer && !object.publishable) {
1090
1884
  contract(path, "An object declares customer or public, not both");
1091
1885
  }
1092
1886
  if (key === "signedIn" && object.public) {
@@ -1121,36 +1915,69 @@ export function validateManifest(
1121
1915
  }
1122
1916
  }
1123
1917
  if (!p.when) continue;
1124
- let target = object;
1125
- let targetName = name;
1126
- if (p.when.via !== undefined) {
1127
- const via = object.fields[p.when.via];
1128
- const local =
1129
- via?.type === "relation" && !via.many && via.to?.startsWith(`${m.id}.`)
1130
- ? via.to.slice(m.id.length + 1)
1131
- : null;
1132
- const pointed = local ? m.objects[local] : undefined;
1133
- if (!pointed || !local) {
1134
- contract(
1135
- `${path}.when.via`,
1136
- `${key}.when.via must name a relation of ${name} to one record of another of this extension's objects`,
1137
- );
1138
- continue;
1918
+ // One condition, or a list of them that must all hold (ADR 0689).
1919
+ const list = Array.isArray(p.when);
1920
+ whenConditions(p.when).forEach((when, i) => {
1921
+ const at = list ? `${path}.when.${i}` : `${path}.when`;
1922
+ let target = object;
1923
+ let targetName = name;
1924
+ if (when.via !== undefined) {
1925
+ const via = object.fields[when.via];
1926
+ const local =
1927
+ via?.type === "relation" && !via.many && via.to?.startsWith(`${m.id}.`)
1928
+ ? via.to.slice(m.id.length + 1)
1929
+ : null;
1930
+ const pointed = local ? m.objects[local] : undefined;
1931
+ if (!pointed || !local) {
1932
+ contract(
1933
+ `${at}.via`,
1934
+ `${key}.when.via must name a relation of ${name} to one record of another of this extension's objects`,
1935
+ );
1936
+ return;
1937
+ }
1938
+ target = pointed;
1939
+ targetName = local;
1139
1940
  }
1140
- target = pointed;
1141
- targetName = local;
1142
- }
1143
- const field = target.fields[p.when.field];
1144
- if (!field || field.type !== "select") {
1145
- contract(`${path}.when.field`, `${key}.when.field must name a select field of ${targetName}`);
1146
- continue;
1147
- }
1148
- const values = new Set((field.options ?? []).map((o) => (typeof o === "string" ? o : o.value)));
1149
- for (const value of p.when.in) {
1150
- if (!values.has(value)) {
1151
- contract(`${path}.when.in`, `"${value}" is not an option of ${targetName}.${p.when.field}`);
1941
+ if (when.field === undefined && when.in === undefined) {
1942
+ // `via` alone (ADR 0689): the record it points to is one the public reads.
1943
+ if (when.via === undefined) {
1944
+ contract(at, `${key}.when needs a field and its values, or a via`);
1945
+ } else if (key !== "public") {
1946
+ contract(
1947
+ `${at}.via`,
1948
+ "via alone is the public's: it reads the record it points to as the public does",
1949
+ );
1950
+ } else if (!target.public) {
1951
+ contract(
1952
+ `${at}.via`,
1953
+ `${targetName} declares no public: via alone means its record is one the public reads`,
1954
+ );
1955
+ } else if (whenConditions(target.public.when).some((c) => c.field === undefined)) {
1956
+ contract(
1957
+ `${at}.via`,
1958
+ `${targetName}'s own public.when uses via alone: one step only, no chains`,
1959
+ );
1960
+ }
1961
+ return;
1152
1962
  }
1153
- }
1963
+ if (when.field === undefined || when.in === undefined) {
1964
+ contract(at, `${key}.when names a field and its values (in) together`);
1965
+ return;
1966
+ }
1967
+ const field = target.fields[when.field];
1968
+ if (field?.type !== "select") {
1969
+ contract(`${at}.field`, `${key}.when.field must name a select field of ${targetName}`);
1970
+ return;
1971
+ }
1972
+ const values = new Set(
1973
+ (field.options ?? []).map((o) => (typeof o === "string" ? o : o.value)),
1974
+ );
1975
+ for (const value of when.in) {
1976
+ if (!values.has(value)) {
1977
+ contract(`${at}.in`, `"${value}" is not an option of ${targetName}.${when.field}`);
1978
+ }
1979
+ }
1980
+ });
1154
1981
  }
1155
1982
 
1156
1983
  // Versions (ADR 0446): the content a version keeps is fields of the object's own that a person
@@ -1166,7 +1993,9 @@ export function validateManifest(
1166
1993
  const field = object.fields[fieldName];
1167
1994
  if (!field) {
1168
1995
  contract(`${path}.content`, `"${fieldName}" is not a field of ${name}`);
1169
- } else if (field.type === "formula" || field.readOnly) {
1996
+ } else if (field.type === "formula" || (field.readOnly && !object.customer)) {
1997
+ // With an author (ADR 0810) the content is the author's and what the host sets beside it
1998
+ // (what a review is about): a read-only field may be content, a formula still not.
1170
1999
  contract(
1171
2000
  `${path}.content`,
1172
2001
  `"${fieldName}" is ${field.type === "formula" ? "a formula" : "read-only"}: content is what staff edit`,
@@ -1193,11 +2022,31 @@ export function validateManifest(
1193
2022
  contract(`${path}.date`, "publishable.date is content: list it in content too");
1194
2023
  }
1195
2024
  }
1196
- if (object.public) {
1197
- if (p.slug === undefined) {
1198
- contract(`${path}.slug`, "A publishable object the public reads names its slug field");
2025
+ // The states a record may be published in (ADR 0810): values of the object's states field.
2026
+ if (p.publishIn !== undefined) {
2027
+ const stateField = object.states ? object.fields[object.states.field] : undefined;
2028
+ if (!object.states || stateField?.type !== "select") {
2029
+ contract(`${path}.publishIn`, "publishable.publishIn names states: declare states first");
2030
+ } else {
2031
+ const states = new Set(
2032
+ (stateField.options ?? []).map((o) => (typeof o === "string" ? o : o.value)),
2033
+ );
2034
+ if (new Set(p.publishIn).size !== p.publishIn.length) {
2035
+ contract(`${path}.publishIn`, "publishable.publishIn lists a state twice");
2036
+ }
2037
+ for (const state of p.publishIn) {
2038
+ if (!states.has(state)) {
2039
+ contract(
2040
+ `${path}.publishIn`,
2041
+ `"${state}" is not a state of ${name} (${object.states.field})`,
2042
+ );
2043
+ }
2044
+ }
1199
2045
  }
1200
- // The public reads the published version (ADR 0442): its content, its address and when it
2046
+ }
2047
+ if (object.public) {
2048
+ // Without a slug the public's records are listed only (ADR 0810): content.list, never
2049
+ // content.get. The public reads the published version (ADR 0442): its content, its address and when it
1201
2050
  // went live, and fields the host keeps on the working copy that are not computed from it.
1202
2051
  for (const fieldName of object.public.read) {
1203
2052
  const field = object.fields[fieldName];
@@ -1209,12 +2058,46 @@ export function validateManifest(
1209
2058
  }
1210
2059
  }
1211
2060
  }
1212
- if (object.customer || object.customerVia) {
2061
+ // An author (ADR 0810): the customer reads and writes the working copy; anyone else outside
2062
+ // reads only the published version, never by an address and never whose it is.
2063
+ if (object.customerVia) {
1213
2064
  contract(
1214
2065
  path,
1215
- "A publishable object declares no customer or customerVia: what outsiders read of it is its published version",
2066
+ "A publishable object declares no customerVia: what outsiders read of it is its published version",
1216
2067
  );
1217
2068
  }
2069
+ if (object.customer) {
2070
+ if (p.slug !== undefined) {
2071
+ contract(
2072
+ `${path}.slug`,
2073
+ "A publishable object with an author (customer) has no slug: its records are listed, not addressed",
2074
+ );
2075
+ }
2076
+ if (object.public?.read.includes(object.customer.field)) {
2077
+ contract(
2078
+ `objects.${name}.public.read`,
2079
+ `public.read lists "${object.customer.field}", the author: the public never reads whose it is`,
2080
+ );
2081
+ }
2082
+ // The public reads a field that is not content from the working copy, as it is now: one
2083
+ // the author writes would reach the website unapproved (the review of #367).
2084
+ const content = new Set(p.content);
2085
+ for (const field of object.public?.read ?? []) {
2086
+ if (object.customer.write.includes(field) && !content.has(field)) {
2087
+ contract(
2088
+ `objects.${name}.public.read`,
2089
+ `public.read lists "${field}", which the author writes: list it in publishable.content, so the public reads it only as a person published it`,
2090
+ );
2091
+ }
2092
+ }
2093
+ // The day it goes live is filled by the publish, which the author's fields refuse.
2094
+ if (p.date !== undefined && object.customer.write.includes(p.date)) {
2095
+ contract(
2096
+ `${path}.date`,
2097
+ `publishable.date "${p.date}" is filled when it is published: the author does not write it`,
2098
+ );
2099
+ }
2100
+ }
1218
2101
  for (const taken of PUBLISHED_FIELD_NAMES) {
1219
2102
  const clash =
1220
2103
  Object.hasOwn(object.fields, taken) ||
@@ -1226,6 +2109,71 @@ export function validateManifest(
1226
2109
  );
1227
2110
  }
1228
2111
  }
2112
+ // Read and understood (stage 38, ADR 0702): who must read is a "must read" document of the
2113
+ // object's own, outside the content; who manages it is a restricted, grantable permission;
2114
+ // and nobody outside the org reads the object.
2115
+ if (p.acknowledge) {
2116
+ const { who, manage } = p.acknowledge;
2117
+ const field = object.fields[who];
2118
+ if (
2119
+ field?.type !== "document" ||
2120
+ JSON.stringify(field.schema) !== JSON.stringify(MUST_READ_SCHEMA)
2121
+ ) {
2122
+ contract(
2123
+ `${path}.acknowledge.who`,
2124
+ `acknowledge.who must name a document field of ${name} whose schema is MUST_READ_SCHEMA`,
2125
+ );
2126
+ } else if (p.content.includes(who)) {
2127
+ contract(
2128
+ `${path}.acknowledge.who`,
2129
+ "Who must read is not content: it changes at once, not with a publish. Leave it out of content",
2130
+ );
2131
+ }
2132
+ if (!(m.restricted ?? []).includes(manage) || !(m.grantable ?? []).includes(manage)) {
2133
+ contract(
2134
+ `${path}.acknowledge.manage`,
2135
+ `acknowledge.manage must be a restricted and grantable permission of this extension (restricted and grantable list "${manage}")`,
2136
+ );
2137
+ }
2138
+ if (object.public || object.signedIn) {
2139
+ contract(
2140
+ `${path}.acknowledge`,
2141
+ "An acknowledged object is for staff: it declares no public or signedIn",
2142
+ );
2143
+ }
2144
+ // ADR 0706: fields guarded as who must read is are the object's own, outside the content;
2145
+ // the owner told each week is a user field of its own.
2146
+ const managed = p.acknowledge.managed ?? [];
2147
+ managed.forEach((fieldName, i) => {
2148
+ const at = `${path}.acknowledge.managed.${i}`;
2149
+ const f = object.fields[fieldName];
2150
+ if (!f || f.type === "formula" || f.readOnly) {
2151
+ contract(at, `"${fieldName}" is not a field of ${name} a person writes`);
2152
+ } else if (p.content.includes(fieldName) || fieldName === who) {
2153
+ contract(
2154
+ at,
2155
+ fieldName === who
2156
+ ? "Who must read is guarded already: leave it out of managed"
2157
+ : "A managed field is not content: it changes at once, not with a publish",
2158
+ );
2159
+ } else if (managed.indexOf(fieldName) !== i) {
2160
+ contract(at, `"${fieldName}" is listed twice`);
2161
+ }
2162
+ });
2163
+ const owner = p.acknowledge.owner;
2164
+ if (owner !== undefined && object.fields[owner]?.type !== "user") {
2165
+ contract(
2166
+ `${path}.acknowledge.owner`,
2167
+ `acknowledge.owner must name a user field of ${name}: who is told who has not confirmed`,
2168
+ );
2169
+ }
2170
+ if (p.acknowledge.notices?.outstanding && owner === undefined) {
2171
+ contract(
2172
+ `${path}.acknowledge.notices.outstanding`,
2173
+ "The weekly notice goes to the record's owner: name its user field in acknowledge.owner",
2174
+ );
2175
+ }
2176
+ }
1229
2177
  }
1230
2178
 
1231
2179
  // What a customer reads of a record their own record points to (ADR 0439): fields of this
@@ -1283,6 +2231,9 @@ export function validateManifest(
1283
2231
  }
1284
2232
  }
1285
2233
 
2234
+ // Restricted fields (ADR 0811): an author's words only a named grant reads.
2235
+ checkRestrictedFields(m, contract);
2236
+
1286
2237
  // Fields a customer sets only when they make the record (ADR 0507): each one of its write list.
1287
2238
  for (const [name, object] of Object.entries(m.objects)) {
1288
2239
  for (const fieldName of object.customer?.createOnly ?? []) {
@@ -1295,6 +2246,24 @@ export function validateManifest(
1295
2246
  }
1296
2247
  }
1297
2248
 
2249
+ // The family link (ADR 0540): who made a record is a relation to one person the host sets, never
2250
+ // one the customer writes.
2251
+ for (const [name, object] of Object.entries(m.objects)) {
2252
+ const madeBy = object.customer?.guardians?.madeBy;
2253
+ if (madeBy === undefined) continue;
2254
+ const path = `objects.${name}.customer.guardians.madeBy`;
2255
+ const field = object.fields[madeBy];
2256
+ if (field?.type !== "relation" || field.to !== "person" || field.many) {
2257
+ contract(path, `"${madeBy}" must be a relation of ${name} to one person`);
2258
+ } else if (!field.readOnly) {
2259
+ contract(path, `"${madeBy}" must be readOnly: the host sets it, nobody edits it`);
2260
+ } else if (madeBy === object.customer?.field) {
2261
+ contract(path, "madeBy cannot be the customer field");
2262
+ } else if (object.customer?.write.includes(madeBy)) {
2263
+ contract(path, `"${madeBy}" is set by the host: customer.write may not list it`);
2264
+ }
2265
+ }
2266
+
1298
2267
  // A customer's write that needs access to what it points to (stage 42, ADR 0478): relations of
1299
2268
  // the object to one record of another of this extension's objects that declares `access`.
1300
2269
  for (const [name, object] of Object.entries(m.objects)) {
@@ -1466,6 +2435,34 @@ export function validateManifest(
1466
2435
  `A tool only a person on the staff may call cannot be open to ${open.join(" and ")} callers`,
1467
2436
  );
1468
2437
  }
2438
+ // Open to every staff account, pack roles too (ADR 0652): a person's own, the host's rule
2439
+ // deciding who may do what, so it names no permission a role or a grant would hold.
2440
+ if (
2441
+ tool.anyStaff &&
2442
+ (!tool.humanOnly || open.length || tool.permission || tool.corePermission)
2443
+ ) {
2444
+ contract(
2445
+ `tools.${name}.anyStaff`,
2446
+ "A tool every staff account may call is a person's own (humanOnly), for staff only, and names no permission or corePermission",
2447
+ );
2448
+ }
2449
+ // A core permission instead of records:read or records:write (ADR 0652): staff only, and not
2450
+ // beside a pack permission (a pack role never holds a core one).
2451
+ if (tool.corePermission !== undefined) {
2452
+ const ns = EXTENSION_PERMISSION_RE.exec(tool.corePermission)?.[1];
2453
+ if (!ns || ns === m.id || open.length || tool.permission) {
2454
+ contract(
2455
+ `tools.${name}.corePermission`,
2456
+ "corePermission names a core permission (<area>:<word>, not this extension's own), for a staff-only tool with no permission",
2457
+ );
2458
+ }
2459
+ }
2460
+ if (tool.personApproves && (open.length || tool.risk === "read")) {
2461
+ contract(
2462
+ `tools.${name}.personApproves`,
2463
+ "A tool a person approves is a staff tool that changes something: not open to customers or the public, and not a read",
2464
+ );
2465
+ }
1469
2466
  if (open.length && tool.risk !== "read" && tool.risk !== "write") {
1470
2467
  contract(
1471
2468
  `tools.${name}.risk`,
@@ -1512,17 +2509,59 @@ export function validateManifest(
1512
2509
  }
1513
2510
  }
1514
2511
  if (tool.permission !== undefined) {
1515
- const match = EXTENSION_PERMISSION_RE.exec(tool.permission);
1516
- if (!match || match[1] !== m.id) {
2512
+ const permissions = toolPermissions(tool);
2513
+ for (const permission of permissions) {
2514
+ const match = EXTENSION_PERMISSION_RE.exec(permission);
2515
+ if (!match || match[1] !== m.id) {
2516
+ contract(
2517
+ `tools.${name}.permission`,
2518
+ `A tool's permission is named ${m.id}:<word> (camelCase), not "${permission}"`,
2519
+ );
2520
+ }
2521
+ }
2522
+ if (new Set(permissions).size !== permissions.length) {
2523
+ contract(`tools.${name}.permission`, "A tool names each permission once");
2524
+ }
2525
+ // A device's tool names the permission its device role holds (ADR 0781).
2526
+ const deviceOnly = tool.audiences?.length === 1 && tool.audiences[0] === "device";
2527
+ if (tool.audiences && !tool.audiences.includes("staff") && !deviceOnly) {
1517
2528
  contract(
1518
2529
  `tools.${name}.permission`,
1519
- `A tool's permission is named ${m.id}:<word> (camelCase), not "${tool.permission}"`,
2530
+ "A permission is for staff callers; this tool is not open to staff",
1520
2531
  );
1521
2532
  }
1522
- if (tool.audiences && !tool.audiences.includes("staff")) {
2533
+ }
2534
+ // Input fields the audit log never keeps (ADR 0626): each a field of the tool's input, at any
2535
+ // depth (the audit's redaction is deep).
2536
+ const inputKeys = schemaKeys(tool.inputSchema);
2537
+ for (const field of tool.redact ?? []) {
2538
+ if (!inputKeys.has(field)) {
2539
+ contract(`tools.${name}.redact`, `"${field}" is not a field of the tool's input`);
2540
+ }
2541
+ }
2542
+ // A tool that takes a restricted field's value by its name, at any depth of its input, keeps it
2543
+ // out of the audit (ADR 0811): it lists it in `redact`.
2544
+ for (const field of inputKeys) {
2545
+ const restrictedField = Object.values(m.objects).some((object) =>
2546
+ Object.entries(object.fields).some(([n, f]) => n === field && isRestrictedField(f)),
2547
+ );
2548
+ if (restrictedField && !(tool.redact ?? []).includes(field)) {
1523
2549
  contract(
1524
- `tools.${name}.permission`,
1525
- "A permission is for staff callers; this tool is not open to staff",
2550
+ `tools.${name}.redact`,
2551
+ `"${field}" is a restricted field's name: list it in redact, so no audit row keeps it`,
2552
+ );
2553
+ }
2554
+ }
2555
+ // Answer keys the host never keeps (ADR 0628): each a key of the tool's answer.
2556
+ for (const field of tool.redactResult ?? []) {
2557
+ const properties = (tool.outputSchema.properties ?? {}) as Record<string, unknown>;
2558
+ if (!Object.hasOwn(properties, field)) {
2559
+ contract(`tools.${name}.redactResult`, `"${field}" is not a key of the tool's answer`);
2560
+ } else if (["id", "count", "records"].includes(field)) {
2561
+ // What the audit log keeps of every write (its record id, a count, the records changed).
2562
+ contract(
2563
+ `tools.${name}.redactResult`,
2564
+ `"${field}" is what the audit log keeps of every call: it cannot be redacted`,
1526
2565
  );
1527
2566
  }
1528
2567
  }
@@ -1548,20 +2587,156 @@ export function validateManifest(
1548
2587
  }
1549
2588
 
1550
2589
  // Grantable permissions (ADR 0449): permissions this extension's tools declare, for staff.
2590
+ // A permission one of its roles holds is not grantable (ADR 0600): a role's limits (today's
2591
+ // records only) bind what the role gives, and a grant of the same name would lift them.
2592
+ const roleHeld = new Set(Object.values(m.roles).flatMap((role) => role.permissions));
1551
2593
  (m.grantable ?? []).forEach((permission, i) => {
1552
- const tool = Object.values(m.tools).find((t) => t.permission === permission);
2594
+ const tool = Object.values(m.tools).find((t) => toolPermissions(t).includes(permission));
1553
2595
  if (!tool) {
1554
2596
  contract(
1555
2597
  `grantable.${i}`,
1556
2598
  `"${permission}" is not the permission of any of this extension's tools (tools.<name>.permission)`,
1557
2599
  );
1558
2600
  }
2601
+ if (roleHeld.has(permission)) {
2602
+ contract(
2603
+ `grantable.${i}`,
2604
+ `"${permission}" is held by a role of this extension, so it cannot be granted one by one: name a permission of its own on the tools a grant opens`,
2605
+ );
2606
+ }
2607
+ });
2608
+ // A tool a role reaches and a grant opens too is the grant's without the role's limits (ADR
2609
+ // 0600): only where the tool says so, so a grantable permission added to a role's own tool is
2610
+ // refused rather than silently lifting the role's today off it.
2611
+ for (const [name, tool] of Object.entries(m.tools)) {
2612
+ const permissions = toolPermissions(tool);
2613
+ const both =
2614
+ permissions.some((p) => roleHeld.has(p)) &&
2615
+ permissions.some((p) => (m.grantable ?? []).includes(p));
2616
+ if (both && !tool.grantLiftsRoleLimits) {
2617
+ contract(
2618
+ `tools.${name}.permission`,
2619
+ "This tool names a permission a role holds and a grantable one, so a grant would open it without the role's limits: set grantLiftsRoleLimits if that is meant, or give the grant a tool of its own",
2620
+ );
2621
+ }
2622
+ if (tool.grantLiftsRoleLimits && !both) {
2623
+ contract(
2624
+ `tools.${name}.grantLiftsRoleLimits`,
2625
+ "grantLiftsRoleLimits is for a tool naming both a permission a role holds and a grantable one",
2626
+ );
2627
+ }
2628
+ }
2629
+ for (const permission of Object.keys(m.grantableLabels ?? {})) {
2630
+ if (!(m.grantable ?? []).includes(permission)) {
2631
+ contract(`grantableLabels.${permission}`, `"${permission}" is not in grantable`);
2632
+ }
2633
+ }
2634
+ // Restricted permissions (ADR 0625): held by admins and by grant only. Each is a permission of
2635
+ // this extension's tools that no role holds; a tool naming one names only restricted ones (or a
2636
+ // member would hold it through the other); and such a tool is staff-only (no audiences opening
2637
+ // it, which its staff-only callers would not survive anyway).
2638
+ const restricted = new Set(m.restricted ?? []);
2639
+ (m.restricted ?? []).forEach((permission, i) => {
2640
+ if (!Object.values(m.tools).some((t) => toolPermissions(t).includes(permission))) {
2641
+ contract(
2642
+ `restricted.${i}`,
2643
+ `"${permission}" is not the permission of any of this extension's tools (tools.<name>.permission)`,
2644
+ );
2645
+ }
2646
+ if (roleHeld.has(permission)) {
2647
+ contract(
2648
+ `restricted.${i}`,
2649
+ `"${permission}" is held by a role of this extension: a restricted permission is held by admins and by grant only`,
2650
+ );
2651
+ }
1559
2652
  });
2653
+ if (restricted.size !== (m.restricted ?? []).length) {
2654
+ contract("restricted", "A restricted permission is named once");
2655
+ }
2656
+ for (const [name, tool] of Object.entries(m.tools)) {
2657
+ const permissions = toolPermissions(tool);
2658
+ const some = permissions.filter((p) => restricted.has(p));
2659
+ if (some.length && some.length !== permissions.length) {
2660
+ contract(
2661
+ `tools.${name}.permission`,
2662
+ "A tool naming a restricted permission names only restricted ones: any other would open it to everyone holding the tool's own permission",
2663
+ );
2664
+ }
2665
+ if (some.length && (tool.audiences ?? []).some((a) => a !== "staff")) {
2666
+ contract(`tools.${name}.audiences`, "A tool with a restricted permission is for staff only");
2667
+ }
2668
+ }
2669
+ // The roster's rules (ADR 0626): who rosters is a restricted permission of this extension, and
2670
+ // the numbers the host reads are its number settings.
2671
+ if (m.staffing) {
2672
+ if (!restricted.has(m.staffing.rosters)) {
2673
+ contract(
2674
+ "staffing.rosters",
2675
+ `"${m.staffing.rosters}" must be one of this extension's restricted permissions: who rosters is held by admins and by grant only`,
2676
+ );
2677
+ }
2678
+ if (m.staffing.pays !== undefined) {
2679
+ if (!restricted.has(m.staffing.pays) || !(m.grantable ?? []).includes(m.staffing.pays)) {
2680
+ contract(
2681
+ "staffing.pays",
2682
+ `"${m.staffing.pays}" must be one of this extension's restricted, grantable permissions: pay is held by admins and by grant only`,
2683
+ );
2684
+ } else if (m.staffing.pays === m.staffing.rosters) {
2685
+ contract("staffing.pays", "Pay and rostering are two permissions");
2686
+ }
2687
+ }
2688
+ // The pay period (ADR 0627): a select of weekly, fortnightly and monthly; the date one period
2689
+ // starts (text, YYYY-MM-DD); the day of the month (a number). The roster's numbers are numbers.
2690
+ const PERIODS = new Set(["weekly", "fortnightly", "monthly"]);
2691
+ const types: Record<string, "boolean" | "number" | "select" | "text"> = {
2692
+ recordsTime: "boolean",
2693
+ offerCutoffMinutes: "number",
2694
+ uncoveredDays: "number",
2695
+ payPeriod: "select",
2696
+ payPeriodStart: "text",
2697
+ payPeriodDay: "number",
2698
+ };
2699
+ const pay = ["payPeriod", "payPeriodStart", "payPeriodDay"];
2700
+ const settings = m.staffing.settings ?? {};
2701
+ if (pay.some((k) => (settings as Record<string, unknown>)[k] !== undefined)) {
2702
+ if (m.staffing.pays === undefined) {
2703
+ contract("staffing.settings", "The pay period's settings need staffing.pays");
2704
+ }
2705
+ for (const k of pay) {
2706
+ if ((settings as Record<string, unknown>)[k] === undefined) {
2707
+ contract(`staffing.settings.${k}`, "Declare the pay period's three settings together");
2708
+ }
2709
+ }
2710
+ }
2711
+ for (const [key, setting] of Object.entries(settings)) {
2712
+ if (setting === undefined) continue;
2713
+ const declared = Object.hasOwn(m.settings, setting) ? m.settings[setting] : undefined;
2714
+ const type = types[key] ?? "number";
2715
+ if (declared?.type !== type) {
2716
+ contract(
2717
+ `staffing.settings.${key}`,
2718
+ `"${setting}" must be a ${type} setting of this extension`,
2719
+ );
2720
+ } else if (declared.personApproves !== true) {
2721
+ // The roster's numbers decide when offers close and who is warned, and the pay period what
2722
+ // is totalled: a person's to change.
2723
+ contract(
2724
+ `staffing.settings.${key}`,
2725
+ `"${setting}" must be a setting a person approves (personApproves): the roster's numbers are never an AI's to change`,
2726
+ );
2727
+ } else if (type === "select" && (declared.options ?? []).some((o) => !PERIODS.has(o.value))) {
2728
+ contract(
2729
+ `staffing.settings.${key}`,
2730
+ `"${setting}" offers only weekly, fortnightly and monthly`,
2731
+ );
2732
+ }
2733
+ }
2734
+ }
1560
2735
 
1561
2736
  // Roles (ADR 0436): each holds permissions this extension's tools declare and reads objects
1562
2737
  // of its own, and nothing else, so a role can never reach past the extension that declares it.
1563
2738
  const declaredPermissions = new Set(
1564
- Object.values(m.tools).flatMap((tool) => (tool.permission ? [tool.permission] : [])),
2739
+ Object.values(m.tools).flatMap((tool) => toolPermissions(tool)),
1565
2740
  );
1566
2741
  for (const [name, role] of Object.entries(m.roles)) {
1567
2742
  const path = `roles.${name}`;
@@ -1586,8 +2761,69 @@ export function validateManifest(
1586
2761
  );
1587
2762
  }
1588
2763
  }
2764
+ // A role limited to today (ADR 0553): each object its own, each path a datetime on it (or
2765
+ // one relation away, through another of its objects).
2766
+ for (const [object, limit] of Object.entries(role.today ?? {})) {
2767
+ const tp = `${path}.today.${object}`;
2768
+ const local = object.startsWith(`${m.id}.`) ? object.slice(m.id.length + 1) : null;
2769
+ const target = local && Object.hasOwn(m.objects, local) ? m.objects[local] : undefined;
2770
+ if (!target) {
2771
+ contract(tp, `"${object}" is not an object of this extension`);
2772
+ continue;
2773
+ }
2774
+ const spec = typeof limit === "string" ? { at: limit } : limit;
2775
+ const prefix = (p: string) => (p.includes(".") ? p.split(".")[0] : null);
2776
+ const paths: [string | undefined, string][] = [
2777
+ [spec.at, "datetime"],
2778
+ [spec.until, "datetime"],
2779
+ [spec.zone, "timezone"],
2780
+ ];
2781
+ for (const [p, type] of paths) {
2782
+ if (p === undefined) continue;
2783
+ const field = p.split(".").length <= 2 ? resolveFieldPath(m, target, p) : undefined;
2784
+ if (field?.type !== type || field.many) {
2785
+ contract(tp, `"${p}" must be a ${type} field of ${object}, or one relation away`);
2786
+ }
2787
+ if (prefix(p) !== prefix(spec.at)) {
2788
+ contract(tp, `"${p}" must be read through the same relation as "${spec.at}"`);
2789
+ }
2790
+ }
2791
+ }
2792
+ // A role limited to the People its holder looks after (ADR 0889): each object its own, each
2793
+ // path its relation to person, and a team of this extension's to say who looks after whom.
2794
+ const looksAfter = Object.entries(role.looksAfter ?? {});
2795
+ if (looksAfter.length && !Object.values(m.objects).some((o) => o.team)) {
2796
+ contract(
2797
+ `${path}.looksAfter`,
2798
+ "No object of this extension declares a team: nothing says whom its holder looks after",
2799
+ );
2800
+ }
2801
+ for (const [object, relation] of looksAfter) {
2802
+ const lp = `${path}.looksAfter.${object}`;
2803
+ const local = object.startsWith(`${m.id}.`) ? object.slice(m.id.length + 1) : null;
2804
+ const target = local && Object.hasOwn(m.objects, local) ? m.objects[local] : undefined;
2805
+ if (!target) {
2806
+ contract(lp, `"${object}" is not an object of this extension`);
2807
+ continue;
2808
+ }
2809
+ const field = Object.hasOwn(target.fields, relation) ? target.fields[relation] : undefined;
2810
+ if (field?.type !== "relation" || field.to !== "person" || field.many) {
2811
+ contract(lp, `"${relation}" must be a relation field (one record) of ${object} to person`);
2812
+ }
2813
+ if (role.today && Object.hasOwn(role.today, object)) {
2814
+ contract(lp, `${object} is limited to today already: one limit an object`);
2815
+ }
2816
+ }
2817
+ // A role reaching records only through a live record naming its holder (ADR 0755).
2818
+ checkRoleMine(m, name, role, contract);
1589
2819
  }
1590
2820
 
2821
+ for (const issue of deviceRoleIssues(m)) contract(issue.path, issue.message);
2822
+
2823
+ for (const issue of screenIssues(m)) contract(issue.path, issue.message);
2824
+ for (const issue of portalIssues(m)) contract(issue.path, issue.message);
2825
+ for (const issue of todayItemIssues(m)) contract(issue.path, issue.message);
2826
+
1591
2827
  for (const [name, view] of Object.entries(m.views)) {
1592
2828
  if (!FIELD_NAME_RE.test(name)) contract(`views.${name}`, "View names must be camelCase");
1593
2829
  if (!known.has(view.object))
@@ -1681,12 +2917,17 @@ export function validateManifest(
1681
2917
  }
1682
2918
 
1683
2919
  const perms = m.permissions;
2920
+ // What an automation running only with another extension reads and writes of it (ADR 0812) is
2921
+ // checked when that extension is installed.
2922
+ const later = [...new Set(Object.values(m.automations).flatMap((a) => a.onlyWith ?? []))];
1684
2923
  for (const [key, list] of [
1685
2924
  ["read", perms.read],
1686
2925
  ["write", perms.write],
1687
2926
  ] as const) {
1688
2927
  list.forEach((object, i) => {
1689
- if (!known.has(object)) contract(`permissions.${key}.${i}`, `Unknown object "${object}"`);
2928
+ if (!known.has(object) && !laterObject(later, known, object)) {
2929
+ contract(`permissions.${key}.${i}`, `Unknown object "${object}"`);
2930
+ }
1690
2931
  });
1691
2932
  }
1692
2933
  perms.operations.forEach((operation, i) => {
@@ -1696,6 +2937,12 @@ export function validateManifest(
1696
2937
  contract(`permissions.operations.${i}`, `Extensions cannot be granted ${operation}`);
1697
2938
  }
1698
2939
  });
2940
+ for (const issue of routineMailIssues(m)) contract(issue.path, issue.message);
2941
+ for (const issue of journeySignalIssues(m)) contract(issue.path, issue.message);
2942
+ if (perms.modules.includes("routine-mail") && !Object.keys(m.routineMail ?? {}).length) {
2943
+ contract("permissions.modules", 'The "routine-mail" module sends routine mail it declares');
2944
+ }
2945
+
1699
2946
  const usesOps = perms.read.length > 0 || perms.write.length > 0 || perms.operations.length > 0;
1700
2947
  if (usesOps && !perms.modules.includes("ops")) {
1701
2948
  contract("permissions.modules", 'Object or operation permissions need the "ops" module');