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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/dist/acknowledge.d.ts +38 -0
  2. package/dist/acknowledge.js +30 -0
  3. package/dist/agreements.d.ts +80 -0
  4. package/dist/agreements.js +109 -0
  5. package/dist/allowance.d.ts +47 -5
  6. package/dist/allowance.js +59 -4
  7. package/dist/automation-check.d.ts +6 -1
  8. package/dist/automation-check.js +93 -8
  9. package/dist/automation.d.ts +62 -4
  10. package/dist/automation.js +32 -9
  11. package/dist/behaviour.js +25 -6
  12. package/dist/calendar-entry.d.ts +97 -0
  13. package/dist/calendar-entry.js +180 -0
  14. package/dist/capacity.js +1 -2
  15. package/dist/checklists.d.ts +41 -0
  16. package/dist/checklists.js +75 -0
  17. package/dist/contract.d.ts +495 -26
  18. package/dist/contract.js +21 -3
  19. package/dist/discount.d.ts +135 -0
  20. package/dist/discount.js +281 -0
  21. package/dist/document.d.ts +2 -1
  22. package/dist/document.js +2 -1
  23. package/dist/field-types.d.ts +1 -1
  24. package/dist/field-types.js +5 -0
  25. package/dist/formula/compile.d.ts +15 -0
  26. package/dist/formula/compile.js +9 -0
  27. package/dist/index.d.ts +17 -0
  28. package/dist/index.js +17 -0
  29. package/dist/intake.d.ts +134 -0
  30. package/dist/intake.js +239 -0
  31. package/dist/journey-signals.d.ts +89 -0
  32. package/dist/journey-signals.js +151 -0
  33. package/dist/manifest.d.ts +944 -56
  34. package/dist/manifest.js +1036 -60
  35. package/dist/mine.d.ts +45 -0
  36. package/dist/mine.js +119 -0
  37. package/dist/occupies.d.ts +64 -0
  38. package/dist/occupies.js +122 -0
  39. package/dist/questions.d.ts +179 -0
  40. package/dist/questions.js +514 -0
  41. package/dist/recurring.d.ts +33 -4
  42. package/dist/recurring.js +50 -3
  43. package/dist/restricted-fields.d.ts +15 -0
  44. package/dist/restricted-fields.js +97 -0
  45. package/dist/rich-text.d.ts +22 -0
  46. package/dist/rich-text.js +91 -0
  47. package/dist/routine-mail.d.ts +400 -0
  48. package/dist/routine-mail.js +955 -0
  49. package/dist/runtime.d.ts +5 -11
  50. package/dist/runtime.js +21 -11
  51. package/dist/screens.d.ts +3 -0
  52. package/dist/screens.js +74 -0
  53. package/dist/sellable.d.ts +153 -2
  54. package/dist/sellable.js +188 -0
  55. package/dist/slug.d.ts +2 -0
  56. package/dist/slug.js +6 -2
  57. package/dist/staffed.d.ts +178 -0
  58. package/dist/staffed.js +287 -0
  59. package/dist/states.d.ts +17 -1
  60. package/dist/states.js +48 -20
  61. package/dist/stock.d.ts +129 -0
  62. package/dist/stock.js +205 -0
  63. package/dist/team.d.ts +28 -0
  64. package/dist/team.js +52 -0
  65. package/dist/testing.d.ts +22 -1
  66. package/dist/testing.js +47 -5
  67. package/dist/worked-on.d.ts +42 -0
  68. package/dist/worked-on.js +79 -0
  69. package/package.json +9 -1
  70. package/src/acknowledge.ts +100 -0
  71. package/src/agreements.ts +185 -0
  72. package/src/allowance.ts +98 -8
  73. package/src/automation-check.ts +120 -9
  74. package/src/automation.ts +78 -10
  75. package/src/behaviour.ts +26 -6
  76. package/src/calendar-entry.ts +258 -0
  77. package/src/capacity.ts +1 -2
  78. package/src/checklists.ts +118 -0
  79. package/src/contract.ts +489 -27
  80. package/src/discount.ts +408 -0
  81. package/src/document.ts +4 -2
  82. package/src/field-types.ts +5 -0
  83. package/src/formula/compile.ts +10 -0
  84. package/src/index.ts +17 -0
  85. package/src/intake.ts +380 -0
  86. package/src/journey-signals.ts +215 -0
  87. package/src/manifest.ts +1236 -65
  88. package/src/mine.ts +161 -0
  89. package/src/occupies.ts +192 -0
  90. package/src/questions.ts +681 -0
  91. package/src/recurring.ts +90 -9
  92. package/src/restricted-fields.ts +129 -0
  93. package/src/rich-text.ts +112 -0
  94. package/src/routine-mail.ts +1272 -0
  95. package/src/runtime.ts +25 -12
  96. package/src/screens.ts +91 -0
  97. package/src/sellable.ts +344 -0
  98. package/src/slug.ts +7 -2
  99. package/src/staffed.ts +474 -0
  100. package/src/states.ts +68 -26
  101. package/src/stock.ts +332 -0
  102. package/src/team.ts +83 -0
  103. package/src/testing.ts +70 -6
  104. package/src/worked-on.ts +134 -0
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";
60
+ import { checkObjectStaffed, staffedManifestSchema } from "./staffed.ts";
37
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,7 @@ 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(),
217
282
  guardians: z
218
283
  .object({ write: z.boolean().optional(), madeBy: z.string().max(40).optional() })
219
284
  .strict()
@@ -273,6 +338,32 @@ export const objectManifestSchema = z.object({
273
338
  content: z.array(z.string().max(40)).min(1).max(40),
274
339
  slug: z.string().max(40).optional(),
275
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(),
276
367
  })
277
368
  .strict()
278
369
  .optional(),
@@ -324,14 +415,24 @@ export const toolManifestSchema = z.object({
324
415
  description: z.string().min(20).max(2000),
325
416
  risk: z.enum(TOOL_RISKS),
326
417
  recordAction: recordActionManifestSchema.optional(),
327
- 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(),
328
419
  customerFields: z.record(z.string().max(80), z.array(z.string().max(40)).max(50)).optional(),
329
420
  /** The permission a staff caller needs (`<id>:<word>`), for the extension's roles (ADR 0436). */
330
- 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(),
331
422
  /** Only a person may call it (ADR 0512). */
332
423
  humanOnly: z.literal(true).optional(),
333
424
  /** A person approves anyone else's call (ADR 0552). */
334
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(),
335
436
  inputSchema: jsonSchemaObject,
336
437
  outputSchema: jsonSchemaObject,
337
438
  });
@@ -359,12 +460,37 @@ export const roleManifestSchema = z.object({
359
460
  ]),
360
461
  )
361
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(),
362
467
  });
363
468
  export type RoleManifest = z.infer<typeof roleManifestSchema>;
364
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
+
365
483
  /** A role's or a tool's permission: `<extension id>:<word>`. */
366
484
  export const EXTENSION_PERMISSION_RE = /^([a-z][a-z0-9]{1,29}):([a-z][a-zA-Z0-9]{0,39})$/;
367
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
+
368
494
  export const viewManifestSchema = z.object({
369
495
  label: z.string().min(1).max(100),
370
496
  object: z.string().max(80),
@@ -454,6 +580,96 @@ export const permissionsManifestSchema = z.object({
454
580
  });
455
581
  export type PermissionsManifest = z.infer<typeof permissionsManifestSchema>;
456
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
+
457
673
  export const manifestSchema = z.object({
458
674
  id: z.string(),
459
675
  version: z.string(),
@@ -480,8 +696,51 @@ export const manifestSchema = z.object({
480
696
  tools: z.record(z.string(), toolManifestSchema).default({}),
481
697
  automations: z.record(z.string(), automationManifestSchema).default({}),
482
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(),
483
701
  /** Tool permissions an admin may grant one by one (ADR 0449). */
484
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(),
485
744
  });
486
745
  export type ExtensionManifest = z.infer<typeof manifestSchema>;
487
746
 
@@ -657,9 +916,19 @@ export function toManifest(extension: Extension): ExtensionManifest {
657
916
  risk: tool.risk ?? "write",
658
917
  ...(tool.recordAction ? { recordAction: tool.recordAction } : {}),
659
918
  ...(tool.audiences ? { audiences: [...tool.audiences] } : {}),
660
- ...(tool.permission ? { permission: tool.permission } : {}),
919
+ ...(tool.permission
920
+ ? {
921
+ permission:
922
+ typeof tool.permission === "string" ? tool.permission : [...tool.permission],
923
+ }
924
+ : {}),
661
925
  ...(tool.humanOnly ? { humanOnly: true as const } : {}),
662
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] } : {}),
663
932
  ...(tool.customerFields
664
933
  ? {
665
934
  customerFields: Object.fromEntries(
@@ -688,11 +957,122 @@ export function toManifest(extension: Extension): ExtensionManifest {
688
957
  ...(automation.rails ? { rails: automation.rails } : {}),
689
958
  ...(automation.connections?.length ? { connections: automation.connections } : {}),
690
959
  ...(automation.enabled === false ? { enabled: false } : {}),
960
+ ...(automation.onlyWith?.length ? { onlyWith: [...automation.onlyWith] } : {}),
691
961
  },
692
962
  ]),
693
963
  ),
694
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
+ : {}),
695
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
+ : {}),
696
1076
  roles: Object.fromEntries(
697
1077
  Object.entries(extension.roles ?? {}).map(([name, role]) => [
698
1078
  name,
@@ -702,6 +1082,9 @@ export function toManifest(extension: Extension): ExtensionManifest {
702
1082
  permissions: [...role.permissions],
703
1083
  read: [...role.read],
704
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)) } : {}),
705
1088
  },
706
1089
  ]),
707
1090
  ),
@@ -797,6 +1180,29 @@ export interface ValidateOptions {
797
1180
  * automation checks; null when unknown (those checks are skipped). Core objects are built in.
798
1181
  */
799
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
+ };
800
1206
  }
801
1207
 
802
1208
  /** Formula environment for a set of field manifests (formula fields compile on demand). */
@@ -805,6 +1211,8 @@ export function formulaFields(
805
1211
  ): Record<string, FormulaFieldRef> {
806
1212
  const env: Record<string, FormulaFieldRef> = {};
807
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;
808
1216
  if (field.type === "formula") {
809
1217
  env[name] = { expression: field.expression ?? "" };
810
1218
  continue;
@@ -815,10 +1223,358 @@ export function formulaFields(
815
1223
  return env;
816
1224
  }
817
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
+
818
1556
  /**
819
1557
  * The contract check: structure (zod), names, references, permissions and formulas. Returns
820
1558
  * every issue found (empty when the manifest is valid) and the parsed manifest when it parsed.
821
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
+
822
1578
  export function validateManifest(
823
1579
  input: unknown,
824
1580
  options: ValidateOptions = {},
@@ -836,7 +1592,11 @@ export function validateManifest(
836
1592
  }
837
1593
  const m = parsed.data;
838
1594
 
839
- 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
+ ) {
840
1600
  contract(
841
1601
  "id",
842
1602
  `Extension id "${m.id}" must be 2-30 lowercase letters or digits, start with a letter, and not be reserved`,
@@ -1005,20 +1765,28 @@ export function validateManifest(
1005
1765
  );
1006
1766
  }
1007
1767
  // Every record's own timestamps can be read too, as on the host (formulaEnvironment).
1008
- const env = {
1009
- createdAt: { type: "datetime", sql: '"created_at"' } as FormulaFieldRef,
1010
- updatedAt: { type: "datetime", sql: '"updated_at"' } as FormulaFieldRef,
1011
- ...formulaFields(object.fields),
1012
- };
1768
+ const env = objectFormulaEnvironment(object);
1013
1769
  checkFields(`${path}.fields`, `${m.id}.${name}`, object.fields, env);
1014
1770
  checkObjectBehaviour(m, name, object, contract);
1015
1771
  checkObjectCapacity(m, name, object, contract);
1016
1772
  checkObjectSellable(m, name, object, contract);
1773
+ checkObjectStock(m, name, object, contract);
1774
+ checkObjectStockMoves(m, name, object, contract);
1017
1775
  checkObjectAllowance(m, name, object, contract);
1776
+ checkObjectDiscount(m, name, object, contract);
1777
+ checkObjectAgreements(m, name, object, contract);
1778
+ checkObjectHealthNotes(m, name, object, contract);
1018
1779
  checkObjectStates(m, name, object, contract);
1019
1780
  checkObjectClaims(m, name, object, contract);
1020
1781
  checkObjectUnique(m, name, object, contract);
1021
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);
1022
1790
  object.requireOneOf?.forEach((group, i) => {
1023
1791
  for (const field of group) {
1024
1792
  if (!object.fields[field]) {
@@ -1110,7 +1878,9 @@ export function validateManifest(
1110
1878
  );
1111
1879
  for (const { name, object, key, p } of readDeclarations) {
1112
1880
  const path = `objects.${name}.${key}`;
1113
- 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) {
1114
1884
  contract(path, "An object declares customer or public, not both");
1115
1885
  }
1116
1886
  if (key === "signedIn" && object.public) {
@@ -1145,36 +1915,69 @@ export function validateManifest(
1145
1915
  }
1146
1916
  }
1147
1917
  if (!p.when) continue;
1148
- let target = object;
1149
- let targetName = name;
1150
- if (p.when.via !== undefined) {
1151
- const via = object.fields[p.when.via];
1152
- const local =
1153
- via?.type === "relation" && !via.many && via.to?.startsWith(`${m.id}.`)
1154
- ? via.to.slice(m.id.length + 1)
1155
- : null;
1156
- const pointed = local ? m.objects[local] : undefined;
1157
- if (!pointed || !local) {
1158
- contract(
1159
- `${path}.when.via`,
1160
- `${key}.when.via must name a relation of ${name} to one record of another of this extension's objects`,
1161
- );
1162
- 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;
1163
1940
  }
1164
- target = pointed;
1165
- targetName = local;
1166
- }
1167
- const field = target.fields[p.when.field];
1168
- if (!field || field.type !== "select") {
1169
- contract(`${path}.when.field`, `${key}.when.field must name a select field of ${targetName}`);
1170
- continue;
1171
- }
1172
- const values = new Set((field.options ?? []).map((o) => (typeof o === "string" ? o : o.value)));
1173
- for (const value of p.when.in) {
1174
- if (!values.has(value)) {
1175
- 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;
1176
1962
  }
1177
- }
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
+ });
1178
1981
  }
1179
1982
 
1180
1983
  // Versions (ADR 0446): the content a version keeps is fields of the object's own that a person
@@ -1190,7 +1993,9 @@ export function validateManifest(
1190
1993
  const field = object.fields[fieldName];
1191
1994
  if (!field) {
1192
1995
  contract(`${path}.content`, `"${fieldName}" is not a field of ${name}`);
1193
- } 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.
1194
1999
  contract(
1195
2000
  `${path}.content`,
1196
2001
  `"${fieldName}" is ${field.type === "formula" ? "a formula" : "read-only"}: content is what staff edit`,
@@ -1217,11 +2022,31 @@ export function validateManifest(
1217
2022
  contract(`${path}.date`, "publishable.date is content: list it in content too");
1218
2023
  }
1219
2024
  }
1220
- if (object.public) {
1221
- if (p.slug === undefined) {
1222
- 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
+ }
1223
2045
  }
1224
- // 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
1225
2050
  // went live, and fields the host keeps on the working copy that are not computed from it.
1226
2051
  for (const fieldName of object.public.read) {
1227
2052
  const field = object.fields[fieldName];
@@ -1233,12 +2058,46 @@ export function validateManifest(
1233
2058
  }
1234
2059
  }
1235
2060
  }
1236
- 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) {
1237
2064
  contract(
1238
2065
  path,
1239
- "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",
1240
2067
  );
1241
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
+ }
1242
2101
  for (const taken of PUBLISHED_FIELD_NAMES) {
1243
2102
  const clash =
1244
2103
  Object.hasOwn(object.fields, taken) ||
@@ -1250,6 +2109,71 @@ export function validateManifest(
1250
2109
  );
1251
2110
  }
1252
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
+ }
1253
2177
  }
1254
2178
 
1255
2179
  // What a customer reads of a record their own record points to (ADR 0439): fields of this
@@ -1307,6 +2231,9 @@ export function validateManifest(
1307
2231
  }
1308
2232
  }
1309
2233
 
2234
+ // Restricted fields (ADR 0811): an author's words only a named grant reads.
2235
+ checkRestrictedFields(m, contract);
2236
+
1310
2237
  // Fields a customer sets only when they make the record (ADR 0507): each one of its write list.
1311
2238
  for (const [name, object] of Object.entries(m.objects)) {
1312
2239
  for (const fieldName of object.customer?.createOnly ?? []) {
@@ -1508,6 +2435,28 @@ export function validateManifest(
1508
2435
  `A tool only a person on the staff may call cannot be open to ${open.join(" and ")} callers`,
1509
2436
  );
1510
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
+ }
1511
2460
  if (tool.personApproves && (open.length || tool.risk === "read")) {
1512
2461
  contract(
1513
2462
  `tools.${name}.personApproves`,
@@ -1560,17 +2509,59 @@ export function validateManifest(
1560
2509
  }
1561
2510
  }
1562
2511
  if (tool.permission !== undefined) {
1563
- const match = EXTENSION_PERMISSION_RE.exec(tool.permission);
1564
- 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) {
1565
2528
  contract(
1566
2529
  `tools.${name}.permission`,
1567
- `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",
1568
2531
  );
1569
2532
  }
1570
- 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)) {
1571
2549
  contract(
1572
- `tools.${name}.permission`,
1573
- "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`,
1574
2565
  );
1575
2566
  }
1576
2567
  }
@@ -1596,20 +2587,156 @@ export function validateManifest(
1596
2587
  }
1597
2588
 
1598
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));
1599
2593
  (m.grantable ?? []).forEach((permission, i) => {
1600
- const tool = Object.values(m.tools).find((t) => t.permission === permission);
2594
+ const tool = Object.values(m.tools).find((t) => toolPermissions(t).includes(permission));
1601
2595
  if (!tool) {
1602
2596
  contract(
1603
2597
  `grantable.${i}`,
1604
2598
  `"${permission}" is not the permission of any of this extension's tools (tools.<name>.permission)`,
1605
2599
  );
1606
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
+ }
1607
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
+ }
1608
2735
 
1609
2736
  // Roles (ADR 0436): each holds permissions this extension's tools declare and reads objects
1610
2737
  // of its own, and nothing else, so a role can never reach past the extension that declares it.
1611
2738
  const declaredPermissions = new Set(
1612
- Object.values(m.tools).flatMap((tool) => (tool.permission ? [tool.permission] : [])),
2739
+ Object.values(m.tools).flatMap((tool) => toolPermissions(tool)),
1613
2740
  );
1614
2741
  for (const [name, role] of Object.entries(m.roles)) {
1615
2742
  const path = `roles.${name}`;
@@ -1662,8 +2789,41 @@ export function validateManifest(
1662
2789
  }
1663
2790
  }
1664
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);
1665
2819
  }
1666
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
+
1667
2827
  for (const [name, view] of Object.entries(m.views)) {
1668
2828
  if (!FIELD_NAME_RE.test(name)) contract(`views.${name}`, "View names must be camelCase");
1669
2829
  if (!known.has(view.object))
@@ -1757,12 +2917,17 @@ export function validateManifest(
1757
2917
  }
1758
2918
 
1759
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 ?? []))];
1760
2923
  for (const [key, list] of [
1761
2924
  ["read", perms.read],
1762
2925
  ["write", perms.write],
1763
2926
  ] as const) {
1764
2927
  list.forEach((object, i) => {
1765
- 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
+ }
1766
2931
  });
1767
2932
  }
1768
2933
  perms.operations.forEach((operation, i) => {
@@ -1772,6 +2937,12 @@ export function validateManifest(
1772
2937
  contract(`permissions.operations.${i}`, `Extensions cannot be granted ${operation}`);
1773
2938
  }
1774
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
+
1775
2946
  const usesOps = perms.read.length > 0 || perms.write.length > 0 || perms.operations.length > 0;
1776
2947
  if (usesOps && !perms.modules.includes("ops")) {
1777
2948
  contract("permissions.modules", 'Object or operation permissions need the "ops" module');