@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/dist/manifest.js CHANGED
@@ -3,20 +3,35 @@
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 { ACKNOWLEDGE_NOTICE_BODY_MAX, ACKNOWLEDGE_NOTICE_TITLE_MAX, ACKNOWLEDGE_REMINDER_MAX_DAYS, MUST_READ_SCHEMA, } from "./acknowledge.js";
7
+ import { agreementsManifestSchema, checkObjectAgreements, checkObjectHealthNotes, healthNotesManifestSchema, } from "./agreements.js";
6
8
  import { allowanceManifestSchema, checkObjectAllowance } from "./allowance.js";
7
9
  import { automationManifestSchema } from "./automation.js";
8
- import { checkAutomation } from "./automation-check.js";
10
+ import { checkAutomation, laterObject } from "./automation-check.js";
9
11
  import { checkObjectBehaviour } from "./behaviour.js";
12
+ import { calendarEntryManifestSchema, checkObjectCalendarEntry } from "./calendar-entry.js";
10
13
  import { capacityManifestSchema, checkObjectCapacity, checkObjectClaims, claimsManifestSchema, } from "./capacity.js";
11
- import { HOST_MODULES, STAGE_TYPES, SUPPORTED_CONTRACT_VERSIONS, TOOL_AUDIENCES, TOOL_RISKS, } from "./contract.js";
14
+ import { checklistsManifestSchema, checkObjectChecklists } from "./checklists.js";
15
+ import { HOST_MODULES, STAGE_TYPES, SUPPORTED_CONTRACT_VERSIONS, TODAY_ITEM_COMPARES, TODAY_ITEM_FORMATS, TOOL_AUDIENCES, TOOL_RISKS, } from "./contract.js";
16
+ import { checkObjectDiscount, discountManifestSchema } from "./discount.js";
12
17
  import { checkDocumentSchema, DOCUMENT_MAX_BYTES, DOCUMENT_MAX_PATHS, documentPathNode, } from "./document.js";
13
18
  import { FIELD_TYPES, formulaTypeOf } from "./field-types.js";
14
- import { checkFormula } from "./formula/compile.js";
19
+ import { checkFormula, PUBLISHED_FORMULA_FIELDS } from "./formula/compile.js";
20
+ import { checkObjectIntake, intakeManifestSchema } from "./intake.js";
21
+ import { journeySignalIssues, journeySignalsManifestSchema } from "./journey-signals.js";
22
+ import { checkRoleMine, mineManifestSchema } from "./mine.js";
23
+ import { checkObjectOccupies, occupiesManifestSchema } from "./occupies.js";
15
24
  import { checkObjectRecurring, recurringManifestSchema } from "./recurring.js";
16
25
  import { renamedMessage } from "./renamed.js";
26
+ import { checkRestrictedFields, isRestrictedField } from "./restricted-fields.js";
27
+ import { routineMailIssues, routineMailManifestSchema } from "./routine-mail.js";
17
28
  import { checkObjectSellable, sellableManifestSchema } from "./sellable.js";
29
+ import { checkObjectStaffed, staffedManifestSchema } from "./staffed.js";
18
30
  import { checkObjectStates, resolveFieldPath, statesManifestSchema } from "./states.js";
31
+ import { checkObjectStock, checkObjectStockMoves, stockManifestSchema, stockMovesManifestSchema, } from "./stock.js";
32
+ import { checkObjectTeam, teamManifestSchema } from "./team.js";
19
33
  import { checkObjectUnique, uniqueManifestSchema } from "./unique.js";
34
+ import { checkObjectWorkedOn, workedOnManifestSchema } from "./worked-on.js";
20
35
  export const EXTENSION_ID_RE = /^[a-z][a-z0-9]{1,29}$/;
21
36
  export const OBJECT_NAME_RE = /^[a-z][a-z0-9]{0,29}$/;
22
37
  export const FIELD_NAME_RE = /^[a-z][a-zA-Z0-9]{0,39}$/;
@@ -85,6 +100,8 @@ export const fieldManifestSchema = z.object({
85
100
  default: z.union([z.string().max(1000), z.number(), z.boolean()]).optional(),
86
101
  defaultSetting: z.string().max(40).optional(),
87
102
  personApproves: z.boolean().optional(),
103
+ // Stage 54 step 2 (ADR 0811): only those granted this restricted permission of the pack read it.
104
+ restricted: z.string().max(80).optional(),
88
105
  to: z.string().max(80).optional(),
89
106
  many: z.boolean().optional(),
90
107
  expression: z.string().max(2000).optional(),
@@ -120,19 +137,28 @@ export const PUBLISHED_FIELD_NAMES = [
120
137
  "publishState",
121
138
  "publishAt",
122
139
  ];
140
+ // One condition of `when` (ADRs 0438 and 0689): a state of the record, or of the one `via` points
141
+ // to; or `via` alone, that the record it points to is public. Which shapes hold is checked below.
142
+ const readConditionSchema = z
143
+ .object({
144
+ via: z.string().max(40).optional(),
145
+ field: z.string().max(40).optional(),
146
+ in: z.array(z.string().max(100)).min(1).max(20).optional(),
147
+ })
148
+ .strict();
123
149
  const readDeclarationSchema = z
124
150
  .object({
125
151
  read: z.array(z.string().max(40)).min(1).max(100),
126
- when: z
127
- .object({
128
- via: z.string().max(40).optional(),
129
- field: z.string().max(40),
130
- in: z.array(z.string().max(100)).min(1).max(20),
131
- })
132
- .strict()
133
- .optional(),
152
+ // One condition, or up to three that must all hold (ADR 0689).
153
+ when: z.union([readConditionSchema, z.array(readConditionSchema).min(1).max(3)]).optional(),
134
154
  })
135
155
  .strict();
156
+ /** A `when` as its list of conditions, all of which must hold (ADR 0689). */
157
+ export function whenConditions(when) {
158
+ if (when === undefined)
159
+ return [];
160
+ return Array.isArray(when) ? when : [when];
161
+ }
136
162
  export const stagesManifestSchema = z.object({
137
163
  field: z.string().max(40),
138
164
  stage: z.object({
@@ -151,7 +177,13 @@ export const stagesManifestSchema = z.object({
151
177
  .partialRecord(z.enum(STAGE_TYPES), z.array(z.string().max(40)).max(50))
152
178
  .optional(),
153
179
  });
154
- export const objectManifestSchema = z.object({
180
+ export /** The words of one notice the host sends for an acknowledged object (ADR 0706). */ const ackNotice = z
181
+ .object({
182
+ title: z.string().trim().min(1).max(ACKNOWLEDGE_NOTICE_TITLE_MAX),
183
+ body: z.string().trim().min(1).max(ACKNOWLEDGE_NOTICE_BODY_MAX).optional(),
184
+ })
185
+ .strict();
186
+ const objectManifestSchema = z.object({
155
187
  label: z.string().min(1).max(100),
156
188
  plural: z.string().min(1).max(100),
157
189
  icon: z.string().max(60).optional(),
@@ -168,11 +200,23 @@ export const objectManifestSchema = z.object({
168
200
  stages: stagesManifestSchema.optional(),
169
201
  capacity: capacityManifestSchema.optional(),
170
202
  sellable: sellableManifestSchema.optional(),
203
+ stock: stockManifestSchema.optional(),
204
+ stockMoves: stockMovesManifestSchema.optional(),
171
205
  allowance: allowanceManifestSchema.optional(),
206
+ discount: discountManifestSchema.optional(),
207
+ agreements: agreementsManifestSchema.optional(),
208
+ healthNotes: healthNotesManifestSchema.optional(),
172
209
  states: statesManifestSchema.optional(),
173
210
  claims: claimsManifestSchema.optional(),
174
211
  unique: uniqueManifestSchema.optional(),
175
212
  recurring: recurringManifestSchema.optional(),
213
+ staffed: staffedManifestSchema.optional(),
214
+ workedOn: workedOnManifestSchema.optional(),
215
+ team: teamManifestSchema.optional(),
216
+ occupies: occupiesManifestSchema.optional(),
217
+ calendarEntry: calendarEntryManifestSchema.optional(),
218
+ intake: intakeManifestSchema.optional(),
219
+ checklists: checklistsManifestSchema.optional(),
176
220
  owner: z.string().max(40).optional(),
177
221
  customer: z
178
222
  .object({
@@ -181,6 +225,7 @@ export const objectManifestSchema = z.object({
181
225
  write: z.array(z.string().max(40)).max(100),
182
226
  requireAccess: z.array(z.string().max(40)).max(10).optional(),
183
227
  createOnly: z.array(z.string().max(40)).max(100).optional(),
228
+ delete: z.boolean().optional(),
184
229
  guardians: z
185
230
  .object({ write: z.boolean().optional(), madeBy: z.string().max(40).optional() })
186
231
  .strict()
@@ -235,6 +280,32 @@ export const objectManifestSchema = z.object({
235
280
  content: z.array(z.string().max(40)).min(1).max(40),
236
281
  slug: z.string().max(40).optional(),
237
282
  date: z.string().max(40).optional(),
283
+ publishIn: z.array(z.string().max(100)).min(1).max(20).optional(),
284
+ acknowledge: z
285
+ .object({
286
+ who: z.string().max(40),
287
+ manage: z.string().max(80),
288
+ // ADR 0706: more fields guarded as who must read is, who is told weekly, the words.
289
+ managed: z.array(z.string().max(40)).min(1).max(8).optional(),
290
+ owner: z.string().max(40).optional(),
291
+ notices: z
292
+ .object({
293
+ asked: ackNotice.optional(),
294
+ reminder: ackNotice
295
+ .extend({
296
+ afterDays: z.number().int().min(1).max(ACKNOWLEDGE_REMINDER_MAX_DAYS),
297
+ })
298
+ .strict()
299
+ .optional(),
300
+ outstanding: ackNotice.optional(),
301
+ welcome: ackNotice.optional(),
302
+ })
303
+ .strict()
304
+ .optional(),
305
+ })
306
+ .strict()
307
+ .optional(),
308
+ staffRead: z.boolean().optional(),
238
309
  })
239
310
  .strict()
240
311
  .optional(),
@@ -281,14 +352,24 @@ export const toolManifestSchema = z.object({
281
352
  description: z.string().min(20).max(2000),
282
353
  risk: z.enum(TOOL_RISKS),
283
354
  recordAction: recordActionManifestSchema.optional(),
284
- audiences: z.array(z.enum(TOOL_AUDIENCES)).min(1).max(3).optional(),
355
+ audiences: z.array(z.enum(TOOL_AUDIENCES)).min(1).max(4).optional(),
285
356
  customerFields: z.record(z.string().max(80), z.array(z.string().max(40)).max(50)).optional(),
286
357
  /** The permission a staff caller needs (`<id>:<word>`), for the extension's roles (ADR 0436). */
287
- permission: z.string().max(80).optional(),
358
+ permission: z.union([z.string().max(80), z.array(z.string().max(80)).min(1).max(5)]).optional(),
288
359
  /** Only a person may call it (ADR 0512). */
289
360
  humanOnly: z.literal(true).optional(),
290
361
  /** A person approves anyone else's call (ADR 0552). */
291
362
  personApproves: z.literal(true).optional(),
363
+ /** The grant opens it without the role's limits, on purpose (ADR 0600). */
364
+ grantLiftsRoleLimits: z.literal(true).optional(),
365
+ /** Every staff account may call it, pack roles included; the host decides (ADR 0652). */
366
+ anyStaff: z.literal(true).optional(),
367
+ /** A grantable core permission it needs instead of records:read or records:write (ADR 0652). */
368
+ corePermission: z.string().max(80).optional(),
369
+ /** Input fields the audit log never keeps (ADR 0626). */
370
+ redact: z.array(z.string().max(40)).max(20).optional(),
371
+ /** Answer keys the host never keeps (ADR 0628). */
372
+ redactResult: z.array(z.string().max(40)).max(20).optional(),
292
373
  inputSchema: jsonSchemaObject,
293
374
  outputSchema: jsonSchemaObject,
294
375
  });
@@ -311,9 +392,29 @@ export const roleManifestSchema = z.object({
311
392
  .strict(),
312
393
  ]))
313
394
  .optional(),
395
+ /** Objects whose records the role reaches only for the People its holder looks after (ADR 0889). */
396
+ looksAfter: z.record(z.string().max(80), z.string().max(40)).optional(),
397
+ /** Objects whose records the role reaches only through a live record naming its holder (ADR 0755). */
398
+ mine: z.record(z.string().max(80), mineManifestSchema).optional(),
314
399
  });
400
+ /** A device role (ADR 0781): see `DeviceRoleSpec`. */
401
+ export const deviceRoleManifestSchema = z
402
+ .object({
403
+ label: z.string().min(1).max(60),
404
+ description: z.string().min(10).max(500),
405
+ permissions: z.array(z.string().max(80)).max(20).default([]),
406
+ screen: z
407
+ .object({ block: z.string().min(1).max(80), export: z.string().min(1).max(60) })
408
+ .strict(),
409
+ })
410
+ .strict();
315
411
  /** A role's or a tool's permission: `<extension id>:<word>`. */
316
412
  export const EXTENSION_PERMISSION_RE = /^([a-z][a-z0-9]{1,29}):([a-z][a-zA-Z0-9]{0,39})$/;
413
+ /** A tool's permissions, one or several (any one opens it, ADR 0600); none when it declares none. */
414
+ export function toolPermissions(tool) {
415
+ const p = tool.permission;
416
+ return p === undefined ? [] : typeof p === "string" ? [p] : [...p];
417
+ }
317
418
  export const viewManifestSchema = z.object({
318
419
  label: z.string().min(1).max(100),
319
420
  object: z.string().max(80),
@@ -389,6 +490,86 @@ export const permissionsManifestSchema = z.object({
389
490
  .max(HOST_MODULES.length)
390
491
  .default([]),
391
492
  });
493
+ /** A shipped pack's staff screen (stage 47, ADR 0660): see `ScreenSpec`. */
494
+ export const screenManifestSchema = z
495
+ .object({
496
+ label: z.string().min(1).max(60),
497
+ block: z.string().min(1).max(80),
498
+ export: z.string().min(1).max(60),
499
+ nav: z
500
+ .object({
501
+ group: z.string().min(1).max(40),
502
+ order: z.number().int().min(0).max(1000).optional(),
503
+ })
504
+ .strict()
505
+ .optional(),
506
+ opens: z.array(z.string().max(80)).max(10).default([]),
507
+ writes: z.array(z.string().max(81)).max(10).optional(),
508
+ record: z
509
+ .object({ object: z.string().min(1).max(81), as: z.string().min(1).max(40) })
510
+ .strict()
511
+ .optional(),
512
+ })
513
+ .strict();
514
+ /** A shipped pack's number on Today (stage 60, ADR 0870): see `TodayItemSpec`. */
515
+ export const todayItemManifestSchema = z
516
+ .object({
517
+ label: z.string().min(1).max(60),
518
+ order: z.number().int().min(0).max(1000).optional(),
519
+ // A string, not an enum: a money format is refused by the contract with the reason.
520
+ format: z.string().min(1).max(20),
521
+ sql: z.string().min(1).max(20_000),
522
+ compare: z.enum(TODAY_ITEM_COMPARES).optional(),
523
+ attention: z
524
+ .union([
525
+ z.object({ above: z.number().finite() }).strict(),
526
+ z.object({ below: z.number().finite() }).strict(),
527
+ ])
528
+ .optional(),
529
+ rows: z
530
+ .object({
531
+ sql: z.string().min(1).max(20_000),
532
+ label: z.string().min(1).max(63),
533
+ detail: z.string().min(1).max(63).optional(),
534
+ record: z
535
+ .object({ object: z.string().min(1).max(81), id: z.string().min(1).max(63) })
536
+ .strict(),
537
+ })
538
+ .strict()
539
+ .optional(),
540
+ opens: z.array(z.string().max(80)).max(10),
541
+ web: z
542
+ .object({ screen: z.string().min(1).max(40) })
543
+ .strict()
544
+ .optional(),
545
+ })
546
+ .strict();
547
+ /** At most this many Today items per pack (stage 60). */
548
+ export const MAX_TODAY_ITEMS = 8;
549
+ /** A result column a Today item's rows name: `member`, `person_id`. */
550
+ const COLUMN_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]{0,62}$/;
551
+ /** A block and the component it exports, as a portal section names them (ADR 0710). */
552
+ const sectionBlockSchema = z
553
+ .object({ block: z.string().min(1).max(80), export: z.string().min(1).max(60) })
554
+ .strict();
555
+ /** A shipped pack's section of My account (stage 48, ADR 0710): see `PortalSectionSpec`. */
556
+ export const portalSectionManifestSchema = z
557
+ .object({
558
+ label: z.string().min(1).max(60),
559
+ web: sectionBlockSchema.optional(),
560
+ native: sectionBlockSchema.optional(),
561
+ order: z.number().int(),
562
+ has: z.array(z.string().max(81)).max(10),
563
+ })
564
+ .strict();
565
+ /** Where a pack's section may sit: before the base sections, which start at 60. */
566
+ export const PORTAL_ORDER = { min: 1, max: 59 };
567
+ /** A screen's key, as a tool's: `desk`, `classList`. */
568
+ export const SCREEN_NAME_RE = /^[a-z][a-zA-Z0-9]{0,39}$/;
569
+ /** A block's name: lowercase words joined by hyphens (`bookings-desk`). */
570
+ const BLOCK_NAME_RE = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)+$/;
571
+ /** A component a block exports: `Desk`, `RosterWeek`. */
572
+ const COMPONENT_NAME_RE = /^[A-Z][A-Za-z0-9]{0,59}$/;
392
573
  export const manifestSchema = z.object({
393
574
  id: z.string(),
394
575
  version: z.string(),
@@ -415,8 +596,51 @@ export const manifestSchema = z.object({
415
596
  tools: z.record(z.string(), toolManifestSchema).default({}),
416
597
  automations: z.record(z.string(), automationManifestSchema).default({}),
417
598
  roles: z.record(z.string(), roleManifestSchema).default({}),
599
+ /** A shipped pack's device roles, for an enrolled device (ADR 0781). */
600
+ deviceRoles: z.record(z.string(), deviceRoleManifestSchema).optional(),
418
601
  /** Tool permissions an admin may grant one by one (ADR 0449). */
419
602
  grantable: z.array(z.string().max(80)).max(20).optional(),
603
+ /** A shipped extension's routine mail (ADR 0590). */
604
+ routineMail: routineMailManifestSchema.optional(),
605
+ /** A shipped extension's journey signals (stage 53, ADR 0802). */
606
+ journeySignals: journeySignalsManifestSchema.optional(),
607
+ /** What each grantable permission gives, in plain words, for the admin (ADR 0600). */
608
+ grantableLabels: z.record(z.string().max(80), z.string().min(10).max(300)).optional(),
609
+ /** Tool permissions held by admins and by grant only (ADR 0625). */
610
+ restricted: z.array(z.string().max(80)).max(20).optional(),
611
+ /** The roster's rules this extension sets for the host (ADR 0626). */
612
+ staffing: z
613
+ .object({
614
+ rosters: z.string().max(80),
615
+ /** Who reads and locks pay (ADR 0627): a restricted permission of this extension. */
616
+ pays: z.string().max(80).optional(),
617
+ settings: z
618
+ .object({
619
+ offerCutoffMinutes: z.string().max(64).optional(),
620
+ uncoveredDays: z.string().max(64).optional(),
621
+ payPeriod: z.string().max(64).optional(),
622
+ payPeriodStart: z.string().max(64).optional(),
623
+ payPeriodDay: z.string().max(64).optional(),
624
+ /** Staff record their time (stage 58, ADR 0850): a boolean setting, off by default. */
625
+ recordsTime: z.string().max(64).optional(),
626
+ /** How many days back time may be entered. */
627
+ enterDays: z.string().max(64).optional(),
628
+ /** Hours after a shift's end an open entry is marked finish missing. */
629
+ finishMissingHours: z.string().max(64).optional(),
630
+ /** Minutes an entry may differ from its shift and still match it (ADR 0851). */
631
+ matchMinutes: z.string().max(64).optional(),
632
+ })
633
+ .strict()
634
+ .optional(),
635
+ })
636
+ .strict()
637
+ .optional(),
638
+ /** A shipped pack's staff screens in the product's admin (stage 47, ADR 0660). */
639
+ screens: z.record(z.string(), screenManifestSchema).optional(),
640
+ /** A shipped pack's sections of My account (stage 48, ADR 0710). */
641
+ portal: z.record(z.string(), portalSectionManifestSchema).optional(),
642
+ /** A shipped pack's numbers on the owner's Today (stage 60, ADR 0870). */
643
+ todayItems: z.record(z.string(), todayItemManifestSchema).optional(),
420
644
  });
421
645
  /**
422
646
  * A document field's schema, size and paths (ADR 0445); and that no other type carries them.
@@ -549,9 +773,18 @@ export function toManifest(extension) {
549
773
  risk: tool.risk ?? "write",
550
774
  ...(tool.recordAction ? { recordAction: tool.recordAction } : {}),
551
775
  ...(tool.audiences ? { audiences: [...tool.audiences] } : {}),
552
- ...(tool.permission ? { permission: tool.permission } : {}),
776
+ ...(tool.permission
777
+ ? {
778
+ permission: typeof tool.permission === "string" ? tool.permission : [...tool.permission],
779
+ }
780
+ : {}),
553
781
  ...(tool.humanOnly ? { humanOnly: true } : {}),
554
782
  ...(tool.personApproves ? { personApproves: true } : {}),
783
+ ...(tool.grantLiftsRoleLimits ? { grantLiftsRoleLimits: true } : {}),
784
+ ...(tool.anyStaff ? { anyStaff: true } : {}),
785
+ ...(tool.corePermission ? { corePermission: tool.corePermission } : {}),
786
+ ...(tool.redact?.length ? { redact: [...tool.redact] } : {}),
787
+ ...(tool.redactResult?.length ? { redactResult: [...tool.redactResult] } : {}),
555
788
  ...(tool.customerFields
556
789
  ? {
557
790
  customerFields: Object.fromEntries(Object.entries(tool.customerFields).map(([object, fields]) => [
@@ -576,10 +809,113 @@ export function toManifest(extension) {
576
809
  ...(automation.rails ? { rails: automation.rails } : {}),
577
810
  ...(automation.connections?.length ? { connections: automation.connections } : {}),
578
811
  ...(automation.enabled === false ? { enabled: false } : {}),
812
+ ...(automation.onlyWith?.length ? { onlyWith: [...automation.onlyWith] } : {}),
579
813
  },
580
814
  ])),
581
815
  ...(extension.grantable ? { grantable: [...extension.grantable] } : {}),
816
+ ...(extension.grantableLabels ? { grantableLabels: { ...extension.grantableLabels } } : {}),
817
+ ...(extension.restricted ? { restricted: [...extension.restricted] } : {}),
818
+ ...(extension.staffing
819
+ ? {
820
+ staffing: {
821
+ rosters: extension.staffing.rosters,
822
+ ...(extension.staffing.pays ? { pays: extension.staffing.pays } : {}),
823
+ ...(extension.staffing.settings
824
+ ? { settings: { ...extension.staffing.settings } }
825
+ : {}),
826
+ },
827
+ }
828
+ : {}),
829
+ ...(extension.screens && Object.keys(extension.screens).length
830
+ ? {
831
+ screens: Object.fromEntries(Object.entries(extension.screens).map(([name, screen]) => [
832
+ name,
833
+ {
834
+ label: screen.label,
835
+ block: screen.block,
836
+ export: screen.export,
837
+ ...(screen.nav
838
+ ? {
839
+ nav: {
840
+ group: screen.nav.group,
841
+ ...(screen.nav.order !== undefined ? { order: screen.nav.order } : {}),
842
+ },
843
+ }
844
+ : {}),
845
+ opens: [...(screen.opens ?? [])],
846
+ ...(screen.writes?.length ? { writes: [...screen.writes] } : {}),
847
+ ...(screen.record
848
+ ? { record: { object: screen.record.object, as: screen.record.as } }
849
+ : {}),
850
+ },
851
+ ])),
852
+ }
853
+ : {}),
854
+ ...(extension.deviceRoles && Object.keys(extension.deviceRoles).length
855
+ ? {
856
+ deviceRoles: Object.fromEntries(Object.entries(extension.deviceRoles).map(([name, role]) => [
857
+ name,
858
+ {
859
+ label: role.label,
860
+ description: role.description,
861
+ permissions: [...role.permissions],
862
+ screen: { block: role.screen.block, export: role.screen.export },
863
+ },
864
+ ])),
865
+ }
866
+ : {}),
867
+ ...(extension.todayItems && Object.keys(extension.todayItems).length
868
+ ? {
869
+ todayItems: Object.fromEntries(Object.entries(extension.todayItems).map(([name, item]) => [
870
+ name,
871
+ {
872
+ label: item.label,
873
+ ...(item.order !== undefined ? { order: item.order } : {}),
874
+ format: item.format,
875
+ sql: item.sql,
876
+ ...(item.compare ? { compare: item.compare } : {}),
877
+ ...(item.attention ? { attention: { ...item.attention } } : {}),
878
+ ...(item.rows
879
+ ? {
880
+ rows: {
881
+ sql: item.rows.sql,
882
+ label: item.rows.label,
883
+ ...(item.rows.detail ? { detail: item.rows.detail } : {}),
884
+ record: { object: item.rows.record.object, id: item.rows.record.id },
885
+ },
886
+ }
887
+ : {}),
888
+ opens: [...item.opens],
889
+ ...(item.web ? { web: { screen: item.web.screen } } : {}),
890
+ },
891
+ ])),
892
+ }
893
+ : {}),
894
+ ...(extension.portal && Object.keys(extension.portal).length
895
+ ? {
896
+ portal: Object.fromEntries(Object.entries(extension.portal).map(([key, section]) => [
897
+ key,
898
+ {
899
+ label: section.label,
900
+ ...(section.web
901
+ ? { web: { block: section.web.block, export: section.web.export } }
902
+ : {}),
903
+ ...(section.native
904
+ ? { native: { block: section.native.block, export: section.native.export } }
905
+ : {}),
906
+ order: section.order,
907
+ has: [...section.has],
908
+ },
909
+ ])),
910
+ }
911
+ : {}),
582
912
  ...(extension.requires?.length ? { requires: [...extension.requires] } : {}),
913
+ ...(extension.routineMail && Object.keys(extension.routineMail).length
914
+ ? { routineMail: extension.routineMail }
915
+ : {}),
916
+ ...(extension.journeySignals && Object.keys(extension.journeySignals).length
917
+ ? { journeySignals: extension.journeySignals }
918
+ : {}),
583
919
  roles: Object.fromEntries(Object.entries(extension.roles ?? {}).map(([name, role]) => [
584
920
  name,
585
921
  {
@@ -588,6 +924,9 @@ export function toManifest(extension) {
588
924
  permissions: [...role.permissions],
589
925
  read: [...role.read],
590
926
  ...(role.today ? { today: { ...role.today } } : {}),
927
+ ...(role.looksAfter ? { looksAfter: { ...role.looksAfter } } : {}),
928
+ // Plain data: copied so the manifest shares nothing with the definition.
929
+ ...(role.mine ? { mine: JSON.parse(JSON.stringify(role.mine)) } : {}),
591
930
  },
592
931
  ])),
593
932
  };
@@ -662,10 +1001,26 @@ function coreFormulaRefs(object) {
662
1001
  return {};
663
1002
  return Object.fromEntries(Object.entries(fields).map(([name, type]) => [name, { type, sql: name }]));
664
1003
  }
1004
+ /**
1005
+ * The environment a formula of an object's own field compiles in, as on the host
1006
+ * (formulaEnvironment): its fields, every record's timestamps and, on a publishable object, when
1007
+ * its current version went live and its number (ADR 0706).
1008
+ */
1009
+ export function objectFormulaEnvironment(object) {
1010
+ return {
1011
+ createdAt: { type: "datetime", sql: '"created_at"' },
1012
+ updatedAt: { type: "datetime", sql: '"updated_at"' },
1013
+ ...(object.publishable ? PUBLISHED_FORMULA_FIELDS : {}),
1014
+ ...formulaFields(object.fields),
1015
+ };
1016
+ }
665
1017
  /** Formula environment for a set of field manifests (formula fields compile on demand). */
666
1018
  export function formulaFields(fields) {
667
1019
  const env = {};
668
1020
  for (const [name, field] of Object.entries(fields)) {
1021
+ // A restricted value is in no view, so no formula reads it (ADR 0811).
1022
+ if (isRestrictedField(field))
1023
+ continue;
669
1024
  if (field.type === "formula") {
670
1025
  env[name] = { expression: field.expression ?? "" };
671
1026
  continue;
@@ -676,10 +1031,309 @@ export function formulaFields(fields) {
676
1031
  }
677
1032
  return env;
678
1033
  }
1034
+ /**
1035
+ * A shipped pack's screens (stage 47, ADR 0660), against its own manifest: each names a web block
1036
+ * of this pack and a component it exports (that both exist is the admin's build's check, which
1037
+ * fails on a missing one), and is gated by this pack's own tools, at least one of them for staff
1038
+ * only. A record screen is on one of this pack's objects or a base one. That only a shipped pack
1039
+ * declares screens is the host's check (`cos ext check` and install refuse a runtime one).
1040
+ */
1041
+ export function screenIssues(m) {
1042
+ const issues = [];
1043
+ const add = (path, message) => issues.push({ path, message });
1044
+ for (const [name, screen] of Object.entries(m.screens ?? {})) {
1045
+ const path = `screens.${name}`;
1046
+ if (!SCREEN_NAME_RE.test(name))
1047
+ add(path, `Screen name "${name}" must be camelCase`);
1048
+ if (!BLOCK_NAME_RE.test(screen.block) ||
1049
+ !screen.block.startsWith(`${m.id}-`) ||
1050
+ screen.block.includes("-native-")) {
1051
+ add(`${path}.block`, `"${screen.block}" must be a web block of this pack (${m.id}-<name>, never a native one or another pack's)`);
1052
+ }
1053
+ if (!COMPONENT_NAME_RE.test(screen.export)) {
1054
+ add(`${path}.export`, `"${screen.export}" must be the name of a component (PascalCase)`);
1055
+ }
1056
+ const seen = new Set();
1057
+ let staffOnly = false;
1058
+ screen.opens.forEach((tool, i) => {
1059
+ const at = `${path}.opens.${i}`;
1060
+ if (seen.has(tool))
1061
+ add(at, `"${tool}" is named twice`);
1062
+ seen.add(tool);
1063
+ const spec = Object.hasOwn(m.tools, tool) ? m.tools[tool] : undefined;
1064
+ if (!spec) {
1065
+ add(at, `"${tool}" is not a tool of this pack: a screen is gated by its own pack's tools`);
1066
+ return;
1067
+ }
1068
+ const audiences = spec.audiences ?? ["staff"];
1069
+ if (!audiences.includes("staff")) {
1070
+ add(at, `"${tool}" is not for staff, so no member of staff could open this screen`);
1071
+ }
1072
+ if (audiences.every((a) => a === "staff"))
1073
+ staffOnly = true;
1074
+ });
1075
+ const writes = screen.writes ?? [];
1076
+ writes.forEach((object, i) => {
1077
+ const local = object.startsWith(`${m.id}.`) ? object.slice(m.id.length + 1) : null;
1078
+ if (local === null || !Object.hasOwn(m.objects, local)) {
1079
+ add(`${path}.writes.${i}`, `"${object}" must be an object of this pack (${m.id}.<object>)`);
1080
+ }
1081
+ });
1082
+ if (!screen.opens.length && !writes.length) {
1083
+ add(`${path}.opens`, "A screen names at least one tool (opens) or object (writes) that gates it");
1084
+ }
1085
+ // A record screen is a tab on a staff record page, about that one record: a gate of tools staff
1086
+ // share with customers (a coach logging a client's sets) is staff's there. Any other screen
1087
+ // names a tool for staff only, or writes an object, so no customer's screen becomes a staff one.
1088
+ if (screen.opens.length && !staffOnly && !writes.length && !screen.record) {
1089
+ add(`${path}.opens`, "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");
1090
+ }
1091
+ if (screen.record) {
1092
+ const { object, as } = screen.record;
1093
+ const local = object.startsWith(`${m.id}.`) ? object.slice(m.id.length + 1) : null;
1094
+ const own = local !== null && Object.hasOwn(m.objects, local);
1095
+ if (!own && object !== "person" && object !== "organisation") {
1096
+ add(`${path}.record.object`, `"${object}" must be an object of this pack (${m.id}.<object>), person or organisation`);
1097
+ }
1098
+ if (!FIELD_NAME_RE.test(as))
1099
+ add(`${path}.record.as`, `"${as}" must be a camelCase prop`);
1100
+ }
1101
+ }
1102
+ return issues;
1103
+ }
1104
+ /**
1105
+ * Device roles and the tools open to a device (ADR 0781), against the manifest itself:
1106
+ * - a tool open to `device` is open to nobody else, is a read or a write, and names a
1107
+ * permission of this pack that a device role holds; it is no record action, waits for no
1108
+ * person and is no staff tool's;
1109
+ * - a device role holds at least one permission, each a permission of this pack's device tools
1110
+ * only (never a staff tool's, a staff role's, a grantable or a restricted one), and names its
1111
+ * screen: a web block of this pack and the component it exports.
1112
+ * That only a shipped pack declares device roles is the host's check (`cos ext check` and
1113
+ * install refuse a runtime one).
1114
+ */
1115
+ export function deviceRoleIssues(m) {
1116
+ const issues = [];
1117
+ const add = (path, message) => issues.push({ path, message });
1118
+ const roles = m.deviceRoles ?? {};
1119
+ const held = new Set(Object.values(roles).flatMap((role) => role.permissions));
1120
+ const staffHeld = new Set([
1121
+ ...Object.values(m.roles).flatMap((role) => role.permissions),
1122
+ ...(m.grantable ?? []),
1123
+ ...(m.restricted ?? []),
1124
+ ]);
1125
+ for (const [name, tool] of Object.entries(m.tools)) {
1126
+ const audiences = tool.audiences ?? [];
1127
+ if (!audiences.includes("device"))
1128
+ continue;
1129
+ const path = `tools.${name}`;
1130
+ if (audiences.length !== 1) {
1131
+ add(`${path}.audiences`, 'A tool open to device is open to nobody else: audiences ["device"]');
1132
+ }
1133
+ const permissions = toolPermissions(tool);
1134
+ if (!permissions.length) {
1135
+ add(`${path}.permission`, "A tool open to device names the permission a device role holds");
1136
+ }
1137
+ for (const permission of permissions) {
1138
+ if (!held.has(permission)) {
1139
+ add(`${path}.permission`, `No device role of this pack holds "${permission}"`);
1140
+ }
1141
+ }
1142
+ if (tool.recordAction || tool.grantLiftsRoleLimits) {
1143
+ add(path, "A tool open to device is no record action and lifts no staff role's limits");
1144
+ }
1145
+ }
1146
+ for (const [name, role] of Object.entries(roles)) {
1147
+ const path = `deviceRoles.${name}`;
1148
+ if (!FIELD_NAME_RE.test(name))
1149
+ add(path, `Device role name "${name}" must be camelCase`);
1150
+ if (!role.permissions.length)
1151
+ add(`${path}.permissions`, "A device role holds at least one permission");
1152
+ for (const permission of role.permissions) {
1153
+ const tools = Object.values(m.tools).filter((t) => toolPermissions(t).includes(permission));
1154
+ const ok = EXTENSION_PERMISSION_RE.exec(permission)?.[1] === m.id &&
1155
+ tools.length > 0 &&
1156
+ tools.every((t) => t.audiences?.length === 1 && t.audiences[0] === "device");
1157
+ if (!ok) {
1158
+ add(`${path}.permissions`, `"${permission}" must be the permission of this pack's tools open to device only (audiences ["device"])`);
1159
+ }
1160
+ if (staffHeld.has(permission)) {
1161
+ add(`${path}.permissions`, `"${permission}" is a staff role's, grantable or restricted: a device role's permission is held by devices only`);
1162
+ }
1163
+ }
1164
+ if (!BLOCK_NAME_RE.test(role.screen.block) ||
1165
+ !role.screen.block.startsWith(`${m.id}-`) ||
1166
+ role.screen.block.includes("-native-")) {
1167
+ add(`${path}.screen.block`, `"${role.screen.block}" must be a web block of this pack (${m.id}-<name>, never a native one or another pack's)`);
1168
+ }
1169
+ if (!COMPONENT_NAME_RE.test(role.screen.export)) {
1170
+ add(`${path}.screen.export`, `"${role.screen.export}" must be the name of a component (PascalCase)`);
1171
+ }
1172
+ }
1173
+ return issues;
1174
+ }
1175
+ /**
1176
+ * A shipped pack's Today items (stage 60, ADR 0870), against its own manifest: at most 8, keys
1177
+ * camelCase, a count or a percent (never money: that is the host's, through Finance reports), gated
1178
+ * by this pack's own tools as a screen is (at least one for staff only), rows that open one of
1179
+ * this pack's objects or a base one, and a web screen this pack declares. What the SQL reads,
1180
+ * that it writes nothing and that it returns `value` is the host's check (it has the SQL guards);
1181
+ * so is that only a shipped pack declares items (`cos ext check` and install refuse a runtime one).
1182
+ */
1183
+ export function todayItemIssues(m) {
1184
+ const issues = [];
1185
+ const add = (path, message) => issues.push({ path, message });
1186
+ const items = Object.entries(m.todayItems ?? {});
1187
+ if (items.length > MAX_TODAY_ITEMS) {
1188
+ add("todayItems", `A pack declares at most ${MAX_TODAY_ITEMS} Today items`);
1189
+ }
1190
+ for (const [name, item] of items) {
1191
+ const path = `todayItems.${name}`;
1192
+ if (!SCREEN_NAME_RE.test(name))
1193
+ add(path, `Today item name "${name}" must be camelCase`);
1194
+ if (!TODAY_ITEM_FORMATS.includes(item.format)) {
1195
+ add(`${path}.format`, /money|currency|amount/i.test(item.format)
1196
+ ? "A pack declares no money item: money on Today is the host's, from Finance reports (stage 52)"
1197
+ : `"${item.format}" must be one of ${TODAY_ITEM_FORMATS.join(", ")}`);
1198
+ }
1199
+ const seen = new Set();
1200
+ let staffOnly = false;
1201
+ item.opens.forEach((tool, i) => {
1202
+ const at = `${path}.opens.${i}`;
1203
+ if (seen.has(tool))
1204
+ add(at, `"${tool}" is named twice`);
1205
+ seen.add(tool);
1206
+ const spec = Object.hasOwn(m.tools, tool) ? m.tools[tool] : undefined;
1207
+ if (!spec) {
1208
+ add(at, `"${tool}" is not a tool of this pack: a Today item is gated by its own pack's tools`);
1209
+ return;
1210
+ }
1211
+ const audiences = spec.audiences ?? ["staff"];
1212
+ if (!audiences.includes("staff")) {
1213
+ add(at, `"${tool}" is not for staff, so no member of staff could see this item`);
1214
+ }
1215
+ if (audiences.every((a) => a === "staff"))
1216
+ staffOnly = true;
1217
+ });
1218
+ if (!item.opens.length) {
1219
+ add(`${path}.opens`, "A Today item names at least one of this pack's tools that gates it");
1220
+ }
1221
+ else if (!staffOnly) {
1222
+ add(`${path}.opens`, "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");
1223
+ }
1224
+ if (item.rows) {
1225
+ const { label, detail, record } = item.rows;
1226
+ for (const [key, column] of [
1227
+ ["label", label],
1228
+ ["detail", detail],
1229
+ ["record.id", record.id],
1230
+ ]) {
1231
+ if (column !== undefined && !COLUMN_NAME_RE.test(column)) {
1232
+ add(`${path}.rows.${key}`, `"${column}" must be the name of a column the rows return`);
1233
+ }
1234
+ }
1235
+ const local = record.object.startsWith(`${m.id}.`)
1236
+ ? record.object.slice(m.id.length + 1)
1237
+ : null;
1238
+ const own = local !== null && Object.hasOwn(m.objects, local);
1239
+ if (!own && record.object !== "person" && record.object !== "organisation") {
1240
+ add(`${path}.rows.record.object`, `"${record.object}" must be an object of this pack (${m.id}.<object>), person or organisation`);
1241
+ }
1242
+ }
1243
+ if (item.web && !Object.hasOwn(m.screens ?? {}, item.web.screen)) {
1244
+ add(`${path}.web.screen`, `"${item.web.screen}" is not a screen this pack declares`);
1245
+ }
1246
+ }
1247
+ return issues;
1248
+ }
1249
+ /**
1250
+ * A shipped pack's sections of My account (stage 48, ADR 0710), against its own manifest: each
1251
+ * names a web block of this pack (never a native one) and a native block of this pack, at least
1252
+ * one of the two, each with a component it exports; sits before the base sections; and shows on
1253
+ * records of this pack's own objects that declare a customer (`has`, never empty). What the
1254
+ * blocks are (their skin, their pack, that they call only what a customer or the public may) is
1255
+ * read from their block.json by `cos ext check`; that only a shipped pack declares sections is the
1256
+ * host's check (`cos ext check` and install refuse a runtime one).
1257
+ */
1258
+ export function portalIssues(m) {
1259
+ const issues = [];
1260
+ const add = (path, message) => issues.push({ path, message });
1261
+ for (const [key, section] of Object.entries(m.portal ?? {})) {
1262
+ const path = `portal.${key}`;
1263
+ if (!SCREEN_NAME_RE.test(key))
1264
+ add(path, `Section key "${key}" must be camelCase`);
1265
+ if (!section.web && !section.native) {
1266
+ add(path, "A section names its web block, its native block, or both");
1267
+ }
1268
+ if (section.web) {
1269
+ const { block } = section.web;
1270
+ if (!BLOCK_NAME_RE.test(block) ||
1271
+ !block.startsWith(`${m.id}-`) ||
1272
+ block.includes("-native-")) {
1273
+ add(`${path}.web.block`, `"${block}" must be a web block of this pack (${m.id}-<name>, never a native one or another pack's)`);
1274
+ }
1275
+ }
1276
+ if (section.native) {
1277
+ const { block } = section.native;
1278
+ if (!BLOCK_NAME_RE.test(block) || !block.startsWith(`${m.id}-native-`)) {
1279
+ add(`${path}.native.block`, `"${block}" must be a native block of this pack (${m.id}-native-<name>, never a web one or another pack's)`);
1280
+ }
1281
+ }
1282
+ for (const skin of ["web", "native"]) {
1283
+ const named = section[skin]?.export;
1284
+ if (named !== undefined && !COMPONENT_NAME_RE.test(named)) {
1285
+ add(`${path}.${skin}.export`, `"${named}" must be the name of a component (PascalCase)`);
1286
+ }
1287
+ }
1288
+ if (section.order < PORTAL_ORDER.min || section.order > PORTAL_ORDER.max) {
1289
+ add(`${path}.order`, `A section's order is ${PORTAL_ORDER.min} to ${PORTAL_ORDER.max}: the base sections come after`);
1290
+ }
1291
+ if (!section.has.length) {
1292
+ add(`${path}.has`, "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");
1293
+ }
1294
+ const seen = new Set();
1295
+ section.has.forEach((object, i) => {
1296
+ const at = `${path}.has.${i}`;
1297
+ if (seen.has(object))
1298
+ add(at, `"${object}" is named twice`);
1299
+ seen.add(object);
1300
+ const local = object.startsWith(`${m.id}.`) ? object.slice(m.id.length + 1) : null;
1301
+ const own = local !== null && Object.hasOwn(m.objects, local) ? m.objects[local] : undefined;
1302
+ if (!own) {
1303
+ add(at, `"${object}" must be an object of this pack (${m.id}.<object>)`);
1304
+ }
1305
+ else if (!own.customer) {
1306
+ add(at, `"${object}" declares no customer: a section shows on records that are the customer's own`);
1307
+ }
1308
+ });
1309
+ }
1310
+ return issues;
1311
+ }
679
1312
  /**
680
1313
  * The contract check: structure (zod), names, references, permissions and formulas. Returns
681
1314
  * every issue found (empty when the manifest is valid) and the parsed manifest when it parsed.
682
1315
  */
1316
+ /** Every property name of a JSON schema, at any depth (objects, arrays, unions). */
1317
+ function schemaKeys(schema, into = new Set()) {
1318
+ if (!schema || typeof schema !== "object")
1319
+ return into;
1320
+ const node = schema;
1321
+ const properties = node.properties;
1322
+ if (properties && typeof properties === "object") {
1323
+ for (const [key, value] of Object.entries(properties)) {
1324
+ into.add(key);
1325
+ schemaKeys(value, into);
1326
+ }
1327
+ }
1328
+ for (const key of ["items", "additionalProperties"])
1329
+ schemaKeys(node[key], into);
1330
+ for (const key of ["anyOf", "oneOf", "allOf"]) {
1331
+ if (Array.isArray(node[key]))
1332
+ for (const part of node[key])
1333
+ schemaKeys(part, into);
1334
+ }
1335
+ return into;
1336
+ }
683
1337
  export function validateManifest(input, options = {}) {
684
1338
  const issues = [];
685
1339
  const contract = (path, message) => issues.push({ code: "contract", path, message });
@@ -691,7 +1345,9 @@ export function validateManifest(input, options = {}) {
691
1345
  return { manifest: null, issues };
692
1346
  }
693
1347
  const m = parsed.data;
694
- if (!EXTENSION_ID_RE.test(m.id) || RESERVED_EXTENSION_IDS.has(m.id)) {
1348
+ if (!EXTENSION_ID_RE.test(m.id) ||
1349
+ RESERVED_EXTENSION_IDS.has(m.id) ||
1350
+ options.reservedIds?.includes(m.id)) {
695
1351
  contract("id", `Extension id "${m.id}" must be 2-30 lowercase letters or digits, start with a letter, and not be reserved`);
696
1352
  }
697
1353
  if (!SEMVER_RE.test(m.version))
@@ -834,20 +1490,28 @@ export function validateManifest(input, options = {}) {
834
1490
  contract(`${path}.titleField`, `titleField must be a text-like field (${TEXT_LIKE.join(", ")})`);
835
1491
  }
836
1492
  // Every record's own timestamps can be read too, as on the host (formulaEnvironment).
837
- const env = {
838
- createdAt: { type: "datetime", sql: '"created_at"' },
839
- updatedAt: { type: "datetime", sql: '"updated_at"' },
840
- ...formulaFields(object.fields),
841
- };
1493
+ const env = objectFormulaEnvironment(object);
842
1494
  checkFields(`${path}.fields`, `${m.id}.${name}`, object.fields, env);
843
1495
  checkObjectBehaviour(m, name, object, contract);
844
1496
  checkObjectCapacity(m, name, object, contract);
845
1497
  checkObjectSellable(m, name, object, contract);
1498
+ checkObjectStock(m, name, object, contract);
1499
+ checkObjectStockMoves(m, name, object, contract);
846
1500
  checkObjectAllowance(m, name, object, contract);
1501
+ checkObjectDiscount(m, name, object, contract);
1502
+ checkObjectAgreements(m, name, object, contract);
1503
+ checkObjectHealthNotes(m, name, object, contract);
847
1504
  checkObjectStates(m, name, object, contract);
848
1505
  checkObjectClaims(m, name, object, contract);
849
1506
  checkObjectUnique(m, name, object, contract);
850
1507
  checkObjectRecurring(m, name, object, contract);
1508
+ checkObjectStaffed(m, name, object, contract);
1509
+ checkObjectWorkedOn(m, name, object, contract);
1510
+ checkObjectTeam(m, name, object, contract);
1511
+ checkObjectOccupies(m, name, object, contract);
1512
+ checkObjectCalendarEntry(m, name, object, contract);
1513
+ checkObjectIntake(m, name, object, contract);
1514
+ checkObjectChecklists(m, name, object, contract);
851
1515
  object.requireOneOf?.forEach((group, i) => {
852
1516
  for (const field of group) {
853
1517
  if (!object.fields[field]) {
@@ -929,7 +1593,9 @@ export function validateManifest(input, options = {}) {
929
1593
  }));
930
1594
  for (const { name, object, key, p } of readDeclarations) {
931
1595
  const path = `objects.${name}.${key}`;
932
- if (key === "public" && object.customer) {
1596
+ // A publishable object with an author (ADR 0810) declares both: the author reads the working
1597
+ // copy, the public the published version.
1598
+ if (key === "public" && object.customer && !object.publishable) {
933
1599
  contract(path, "An object declares customer or public, not both");
934
1600
  }
935
1601
  if (key === "signedIn" && object.public) {
@@ -955,32 +1621,57 @@ export function validateManifest(input, options = {}) {
955
1621
  }
956
1622
  if (!p.when)
957
1623
  continue;
958
- let target = object;
959
- let targetName = name;
960
- if (p.when.via !== undefined) {
961
- const via = object.fields[p.when.via];
962
- const local = via?.type === "relation" && !via.many && via.to?.startsWith(`${m.id}.`)
963
- ? via.to.slice(m.id.length + 1)
964
- : null;
965
- const pointed = local ? m.objects[local] : undefined;
966
- if (!pointed || !local) {
967
- contract(`${path}.when.via`, `${key}.when.via must name a relation of ${name} to one record of another of this extension's objects`);
968
- continue;
1624
+ // One condition, or a list of them that must all hold (ADR 0689).
1625
+ const list = Array.isArray(p.when);
1626
+ whenConditions(p.when).forEach((when, i) => {
1627
+ const at = list ? `${path}.when.${i}` : `${path}.when`;
1628
+ let target = object;
1629
+ let targetName = name;
1630
+ if (when.via !== undefined) {
1631
+ const via = object.fields[when.via];
1632
+ const local = via?.type === "relation" && !via.many && via.to?.startsWith(`${m.id}.`)
1633
+ ? via.to.slice(m.id.length + 1)
1634
+ : null;
1635
+ const pointed = local ? m.objects[local] : undefined;
1636
+ if (!pointed || !local) {
1637
+ contract(`${at}.via`, `${key}.when.via must name a relation of ${name} to one record of another of this extension's objects`);
1638
+ return;
1639
+ }
1640
+ target = pointed;
1641
+ targetName = local;
969
1642
  }
970
- target = pointed;
971
- targetName = local;
972
- }
973
- const field = target.fields[p.when.field];
974
- if (!field || field.type !== "select") {
975
- contract(`${path}.when.field`, `${key}.when.field must name a select field of ${targetName}`);
976
- continue;
977
- }
978
- const values = new Set((field.options ?? []).map((o) => (typeof o === "string" ? o : o.value)));
979
- for (const value of p.when.in) {
980
- if (!values.has(value)) {
981
- contract(`${path}.when.in`, `"${value}" is not an option of ${targetName}.${p.when.field}`);
1643
+ if (when.field === undefined && when.in === undefined) {
1644
+ // `via` alone (ADR 0689): the record it points to is one the public reads.
1645
+ if (when.via === undefined) {
1646
+ contract(at, `${key}.when needs a field and its values, or a via`);
1647
+ }
1648
+ else if (key !== "public") {
1649
+ contract(`${at}.via`, "via alone is the public's: it reads the record it points to as the public does");
1650
+ }
1651
+ else if (!target.public) {
1652
+ contract(`${at}.via`, `${targetName} declares no public: via alone means its record is one the public reads`);
1653
+ }
1654
+ else if (whenConditions(target.public.when).some((c) => c.field === undefined)) {
1655
+ contract(`${at}.via`, `${targetName}'s own public.when uses via alone: one step only, no chains`);
1656
+ }
1657
+ return;
982
1658
  }
983
- }
1659
+ if (when.field === undefined || when.in === undefined) {
1660
+ contract(at, `${key}.when names a field and its values (in) together`);
1661
+ return;
1662
+ }
1663
+ const field = target.fields[when.field];
1664
+ if (field?.type !== "select") {
1665
+ contract(`${at}.field`, `${key}.when.field must name a select field of ${targetName}`);
1666
+ return;
1667
+ }
1668
+ const values = new Set((field.options ?? []).map((o) => (typeof o === "string" ? o : o.value)));
1669
+ for (const value of when.in) {
1670
+ if (!values.has(value)) {
1671
+ contract(`${at}.in`, `"${value}" is not an option of ${targetName}.${when.field}`);
1672
+ }
1673
+ }
1674
+ });
984
1675
  }
985
1676
  // Versions (ADR 0446): the content a version keeps is fields of the object's own that a person
986
1677
  // edits, and the host's two published fields are not taken.
@@ -997,7 +1688,9 @@ export function validateManifest(input, options = {}) {
997
1688
  if (!field) {
998
1689
  contract(`${path}.content`, `"${fieldName}" is not a field of ${name}`);
999
1690
  }
1000
- else if (field.type === "formula" || field.readOnly) {
1691
+ else if (field.type === "formula" || (field.readOnly && !object.customer)) {
1692
+ // With an author (ADR 0810) the content is the author's and what the host sets beside it
1693
+ // (what a review is about): a read-only field may be content, a formula still not.
1001
1694
  contract(`${path}.content`, `"${fieldName}" is ${field.type === "formula" ? "a formula" : "read-only"}: content is what staff edit`);
1002
1695
  }
1003
1696
  }
@@ -1020,11 +1713,27 @@ export function validateManifest(input, options = {}) {
1020
1713
  contract(`${path}.date`, "publishable.date is content: list it in content too");
1021
1714
  }
1022
1715
  }
1023
- if (object.public) {
1024
- if (p.slug === undefined) {
1025
- contract(`${path}.slug`, "A publishable object the public reads names its slug field");
1716
+ // The states a record may be published in (ADR 0810): values of the object's states field.
1717
+ if (p.publishIn !== undefined) {
1718
+ const stateField = object.states ? object.fields[object.states.field] : undefined;
1719
+ if (!object.states || stateField?.type !== "select") {
1720
+ contract(`${path}.publishIn`, "publishable.publishIn names states: declare states first");
1721
+ }
1722
+ else {
1723
+ const states = new Set((stateField.options ?? []).map((o) => (typeof o === "string" ? o : o.value)));
1724
+ if (new Set(p.publishIn).size !== p.publishIn.length) {
1725
+ contract(`${path}.publishIn`, "publishable.publishIn lists a state twice");
1726
+ }
1727
+ for (const state of p.publishIn) {
1728
+ if (!states.has(state)) {
1729
+ contract(`${path}.publishIn`, `"${state}" is not a state of ${name} (${object.states.field})`);
1730
+ }
1731
+ }
1026
1732
  }
1027
- // The public reads the published version (ADR 0442): its content, its address and when it
1733
+ }
1734
+ if (object.public) {
1735
+ // Without a slug the public's records are listed only (ADR 0810): content.list, never
1736
+ // content.get. The public reads the published version (ADR 0442): its content, its address and when it
1028
1737
  // went live, and fields the host keeps on the working copy that are not computed from it.
1029
1738
  for (const fieldName of object.public.read) {
1030
1739
  const field = object.fields[fieldName];
@@ -1033,8 +1742,30 @@ export function validateManifest(input, options = {}) {
1033
1742
  }
1034
1743
  }
1035
1744
  }
1036
- if (object.customer || object.customerVia) {
1037
- contract(path, "A publishable object declares no customer or customerVia: what outsiders read of it is its published version");
1745
+ // An author (ADR 0810): the customer reads and writes the working copy; anyone else outside
1746
+ // reads only the published version, never by an address and never whose it is.
1747
+ if (object.customerVia) {
1748
+ contract(path, "A publishable object declares no customerVia: what outsiders read of it is its published version");
1749
+ }
1750
+ if (object.customer) {
1751
+ if (p.slug !== undefined) {
1752
+ contract(`${path}.slug`, "A publishable object with an author (customer) has no slug: its records are listed, not addressed");
1753
+ }
1754
+ if (object.public?.read.includes(object.customer.field)) {
1755
+ contract(`objects.${name}.public.read`, `public.read lists "${object.customer.field}", the author: the public never reads whose it is`);
1756
+ }
1757
+ // The public reads a field that is not content from the working copy, as it is now: one
1758
+ // the author writes would reach the website unapproved (the review of #367).
1759
+ const content = new Set(p.content);
1760
+ for (const field of object.public?.read ?? []) {
1761
+ if (object.customer.write.includes(field) && !content.has(field)) {
1762
+ contract(`objects.${name}.public.read`, `public.read lists "${field}", which the author writes: list it in publishable.content, so the public reads it only as a person published it`);
1763
+ }
1764
+ }
1765
+ // The day it goes live is filled by the publish, which the author's fields refuse.
1766
+ if (p.date !== undefined && object.customer.write.includes(p.date)) {
1767
+ contract(`${path}.date`, `publishable.date "${p.date}" is filled when it is published: the author does not write it`);
1768
+ }
1038
1769
  }
1039
1770
  for (const taken of PUBLISHED_FIELD_NAMES) {
1040
1771
  const clash = Object.hasOwn(object.fields, taken) ||
@@ -1043,6 +1774,51 @@ export function validateManifest(input, options = {}) {
1043
1774
  contract(`objects.${name}.fields.${taken}`, `"${taken}" is the host's on a publishable object`);
1044
1775
  }
1045
1776
  }
1777
+ // Read and understood (stage 38, ADR 0702): who must read is a "must read" document of the
1778
+ // object's own, outside the content; who manages it is a restricted, grantable permission;
1779
+ // and nobody outside the org reads the object.
1780
+ if (p.acknowledge) {
1781
+ const { who, manage } = p.acknowledge;
1782
+ const field = object.fields[who];
1783
+ if (field?.type !== "document" ||
1784
+ JSON.stringify(field.schema) !== JSON.stringify(MUST_READ_SCHEMA)) {
1785
+ contract(`${path}.acknowledge.who`, `acknowledge.who must name a document field of ${name} whose schema is MUST_READ_SCHEMA`);
1786
+ }
1787
+ else if (p.content.includes(who)) {
1788
+ contract(`${path}.acknowledge.who`, "Who must read is not content: it changes at once, not with a publish. Leave it out of content");
1789
+ }
1790
+ if (!(m.restricted ?? []).includes(manage) || !(m.grantable ?? []).includes(manage)) {
1791
+ contract(`${path}.acknowledge.manage`, `acknowledge.manage must be a restricted and grantable permission of this extension (restricted and grantable list "${manage}")`);
1792
+ }
1793
+ if (object.public || object.signedIn) {
1794
+ contract(`${path}.acknowledge`, "An acknowledged object is for staff: it declares no public or signedIn");
1795
+ }
1796
+ // ADR 0706: fields guarded as who must read is are the object's own, outside the content;
1797
+ // the owner told each week is a user field of its own.
1798
+ const managed = p.acknowledge.managed ?? [];
1799
+ managed.forEach((fieldName, i) => {
1800
+ const at = `${path}.acknowledge.managed.${i}`;
1801
+ const f = object.fields[fieldName];
1802
+ if (!f || f.type === "formula" || f.readOnly) {
1803
+ contract(at, `"${fieldName}" is not a field of ${name} a person writes`);
1804
+ }
1805
+ else if (p.content.includes(fieldName) || fieldName === who) {
1806
+ contract(at, fieldName === who
1807
+ ? "Who must read is guarded already: leave it out of managed"
1808
+ : "A managed field is not content: it changes at once, not with a publish");
1809
+ }
1810
+ else if (managed.indexOf(fieldName) !== i) {
1811
+ contract(at, `"${fieldName}" is listed twice`);
1812
+ }
1813
+ });
1814
+ const owner = p.acknowledge.owner;
1815
+ if (owner !== undefined && object.fields[owner]?.type !== "user") {
1816
+ contract(`${path}.acknowledge.owner`, `acknowledge.owner must name a user field of ${name}: who is told who has not confirmed`);
1817
+ }
1818
+ if (p.acknowledge.notices?.outstanding && owner === undefined) {
1819
+ contract(`${path}.acknowledge.notices.outstanding`, "The weekly notice goes to the record's owner: name its user field in acknowledge.owner");
1820
+ }
1821
+ }
1046
1822
  }
1047
1823
  // What a customer reads of a record their own record points to (ADR 0439): fields of this
1048
1824
  // object, through a relation of another of this extension's objects that declares a customer.
@@ -1088,6 +1864,8 @@ export function validateManifest(input, options = {}) {
1088
1864
  contract(`requires.${i}`, `"${required}" is listed twice`);
1089
1865
  }
1090
1866
  }
1867
+ // Restricted fields (ADR 0811): an author's words only a named grant reads.
1868
+ checkRestrictedFields(m, contract);
1091
1869
  // Fields a customer sets only when they make the record (ADR 0507): each one of its write list.
1092
1870
  for (const [name, object] of Object.entries(m.objects)) {
1093
1871
  for (const fieldName of object.customer?.createOnly ?? []) {
@@ -1270,6 +2048,20 @@ export function validateManifest(input, options = {}) {
1270
2048
  if (tool.humanOnly && open.length) {
1271
2049
  contract(`tools.${name}.humanOnly`, `A tool only a person on the staff may call cannot be open to ${open.join(" and ")} callers`);
1272
2050
  }
2051
+ // Open to every staff account, pack roles too (ADR 0652): a person's own, the host's rule
2052
+ // deciding who may do what, so it names no permission a role or a grant would hold.
2053
+ if (tool.anyStaff &&
2054
+ (!tool.humanOnly || open.length || tool.permission || tool.corePermission)) {
2055
+ contract(`tools.${name}.anyStaff`, "A tool every staff account may call is a person's own (humanOnly), for staff only, and names no permission or corePermission");
2056
+ }
2057
+ // A core permission instead of records:read or records:write (ADR 0652): staff only, and not
2058
+ // beside a pack permission (a pack role never holds a core one).
2059
+ if (tool.corePermission !== undefined) {
2060
+ const ns = EXTENSION_PERMISSION_RE.exec(tool.corePermission)?.[1];
2061
+ if (!ns || ns === m.id || open.length || tool.permission) {
2062
+ contract(`tools.${name}.corePermission`, "corePermission names a core permission (<area>:<word>, not this extension's own), for a staff-only tool with no permission");
2063
+ }
2064
+ }
1273
2065
  if (tool.personApproves && (open.length || tool.risk === "read")) {
1274
2066
  contract(`tools.${name}.personApproves`, "A tool a person approves is a staff tool that changes something: not open to customers or the public, and not a read");
1275
2067
  }
@@ -1302,14 +2094,49 @@ export function validateManifest(input, options = {}) {
1302
2094
  }
1303
2095
  }
1304
2096
  if (tool.permission !== undefined) {
1305
- const match = EXTENSION_PERMISSION_RE.exec(tool.permission);
1306
- if (!match || match[1] !== m.id) {
1307
- contract(`tools.${name}.permission`, `A tool's permission is named ${m.id}:<word> (camelCase), not "${tool.permission}"`);
2097
+ const permissions = toolPermissions(tool);
2098
+ for (const permission of permissions) {
2099
+ const match = EXTENSION_PERMISSION_RE.exec(permission);
2100
+ if (!match || match[1] !== m.id) {
2101
+ contract(`tools.${name}.permission`, `A tool's permission is named ${m.id}:<word> (camelCase), not "${permission}"`);
2102
+ }
2103
+ }
2104
+ if (new Set(permissions).size !== permissions.length) {
2105
+ contract(`tools.${name}.permission`, "A tool names each permission once");
1308
2106
  }
1309
- if (tool.audiences && !tool.audiences.includes("staff")) {
2107
+ // A device's tool names the permission its device role holds (ADR 0781).
2108
+ const deviceOnly = tool.audiences?.length === 1 && tool.audiences[0] === "device";
2109
+ if (tool.audiences && !tool.audiences.includes("staff") && !deviceOnly) {
1310
2110
  contract(`tools.${name}.permission`, "A permission is for staff callers; this tool is not open to staff");
1311
2111
  }
1312
2112
  }
2113
+ // Input fields the audit log never keeps (ADR 0626): each a field of the tool's input, at any
2114
+ // depth (the audit's redaction is deep).
2115
+ const inputKeys = schemaKeys(tool.inputSchema);
2116
+ for (const field of tool.redact ?? []) {
2117
+ if (!inputKeys.has(field)) {
2118
+ contract(`tools.${name}.redact`, `"${field}" is not a field of the tool's input`);
2119
+ }
2120
+ }
2121
+ // A tool that takes a restricted field's value by its name, at any depth of its input, keeps it
2122
+ // out of the audit (ADR 0811): it lists it in `redact`.
2123
+ for (const field of inputKeys) {
2124
+ const restrictedField = Object.values(m.objects).some((object) => Object.entries(object.fields).some(([n, f]) => n === field && isRestrictedField(f)));
2125
+ if (restrictedField && !(tool.redact ?? []).includes(field)) {
2126
+ contract(`tools.${name}.redact`, `"${field}" is a restricted field's name: list it in redact, so no audit row keeps it`);
2127
+ }
2128
+ }
2129
+ // Answer keys the host never keeps (ADR 0628): each a key of the tool's answer.
2130
+ for (const field of tool.redactResult ?? []) {
2131
+ const properties = (tool.outputSchema.properties ?? {});
2132
+ if (!Object.hasOwn(properties, field)) {
2133
+ contract(`tools.${name}.redactResult`, `"${field}" is not a key of the tool's answer`);
2134
+ }
2135
+ else if (["id", "count", "records"].includes(field)) {
2136
+ // What the audit log keeps of every write (its record id, a count, the records changed).
2137
+ contract(`tools.${name}.redactResult`, `"${field}" is what the audit log keeps of every call: it cannot be redacted`);
2138
+ }
2139
+ }
1313
2140
  if (tool.recordAction) {
1314
2141
  const action = tool.recordAction;
1315
2142
  if (!known.has(action.object)) {
@@ -1325,15 +2152,121 @@ export function validateManifest(input, options = {}) {
1325
2152
  }
1326
2153
  }
1327
2154
  // Grantable permissions (ADR 0449): permissions this extension's tools declare, for staff.
2155
+ // A permission one of its roles holds is not grantable (ADR 0600): a role's limits (today's
2156
+ // records only) bind what the role gives, and a grant of the same name would lift them.
2157
+ const roleHeld = new Set(Object.values(m.roles).flatMap((role) => role.permissions));
1328
2158
  (m.grantable ?? []).forEach((permission, i) => {
1329
- const tool = Object.values(m.tools).find((t) => t.permission === permission);
2159
+ const tool = Object.values(m.tools).find((t) => toolPermissions(t).includes(permission));
1330
2160
  if (!tool) {
1331
2161
  contract(`grantable.${i}`, `"${permission}" is not the permission of any of this extension's tools (tools.<name>.permission)`);
1332
2162
  }
2163
+ if (roleHeld.has(permission)) {
2164
+ contract(`grantable.${i}`, `"${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`);
2165
+ }
2166
+ });
2167
+ // A tool a role reaches and a grant opens too is the grant's without the role's limits (ADR
2168
+ // 0600): only where the tool says so, so a grantable permission added to a role's own tool is
2169
+ // refused rather than silently lifting the role's today off it.
2170
+ for (const [name, tool] of Object.entries(m.tools)) {
2171
+ const permissions = toolPermissions(tool);
2172
+ const both = permissions.some((p) => roleHeld.has(p)) &&
2173
+ permissions.some((p) => (m.grantable ?? []).includes(p));
2174
+ if (both && !tool.grantLiftsRoleLimits) {
2175
+ contract(`tools.${name}.permission`, "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");
2176
+ }
2177
+ if (tool.grantLiftsRoleLimits && !both) {
2178
+ contract(`tools.${name}.grantLiftsRoleLimits`, "grantLiftsRoleLimits is for a tool naming both a permission a role holds and a grantable one");
2179
+ }
2180
+ }
2181
+ for (const permission of Object.keys(m.grantableLabels ?? {})) {
2182
+ if (!(m.grantable ?? []).includes(permission)) {
2183
+ contract(`grantableLabels.${permission}`, `"${permission}" is not in grantable`);
2184
+ }
2185
+ }
2186
+ // Restricted permissions (ADR 0625): held by admins and by grant only. Each is a permission of
2187
+ // this extension's tools that no role holds; a tool naming one names only restricted ones (or a
2188
+ // member would hold it through the other); and such a tool is staff-only (no audiences opening
2189
+ // it, which its staff-only callers would not survive anyway).
2190
+ const restricted = new Set(m.restricted ?? []);
2191
+ (m.restricted ?? []).forEach((permission, i) => {
2192
+ if (!Object.values(m.tools).some((t) => toolPermissions(t).includes(permission))) {
2193
+ contract(`restricted.${i}`, `"${permission}" is not the permission of any of this extension's tools (tools.<name>.permission)`);
2194
+ }
2195
+ if (roleHeld.has(permission)) {
2196
+ contract(`restricted.${i}`, `"${permission}" is held by a role of this extension: a restricted permission is held by admins and by grant only`);
2197
+ }
1333
2198
  });
2199
+ if (restricted.size !== (m.restricted ?? []).length) {
2200
+ contract("restricted", "A restricted permission is named once");
2201
+ }
2202
+ for (const [name, tool] of Object.entries(m.tools)) {
2203
+ const permissions = toolPermissions(tool);
2204
+ const some = permissions.filter((p) => restricted.has(p));
2205
+ if (some.length && some.length !== permissions.length) {
2206
+ contract(`tools.${name}.permission`, "A tool naming a restricted permission names only restricted ones: any other would open it to everyone holding the tool's own permission");
2207
+ }
2208
+ if (some.length && (tool.audiences ?? []).some((a) => a !== "staff")) {
2209
+ contract(`tools.${name}.audiences`, "A tool with a restricted permission is for staff only");
2210
+ }
2211
+ }
2212
+ // The roster's rules (ADR 0626): who rosters is a restricted permission of this extension, and
2213
+ // the numbers the host reads are its number settings.
2214
+ if (m.staffing) {
2215
+ if (!restricted.has(m.staffing.rosters)) {
2216
+ contract("staffing.rosters", `"${m.staffing.rosters}" must be one of this extension's restricted permissions: who rosters is held by admins and by grant only`);
2217
+ }
2218
+ if (m.staffing.pays !== undefined) {
2219
+ if (!restricted.has(m.staffing.pays) || !(m.grantable ?? []).includes(m.staffing.pays)) {
2220
+ contract("staffing.pays", `"${m.staffing.pays}" must be one of this extension's restricted, grantable permissions: pay is held by admins and by grant only`);
2221
+ }
2222
+ else if (m.staffing.pays === m.staffing.rosters) {
2223
+ contract("staffing.pays", "Pay and rostering are two permissions");
2224
+ }
2225
+ }
2226
+ // The pay period (ADR 0627): a select of weekly, fortnightly and monthly; the date one period
2227
+ // starts (text, YYYY-MM-DD); the day of the month (a number). The roster's numbers are numbers.
2228
+ const PERIODS = new Set(["weekly", "fortnightly", "monthly"]);
2229
+ const types = {
2230
+ recordsTime: "boolean",
2231
+ offerCutoffMinutes: "number",
2232
+ uncoveredDays: "number",
2233
+ payPeriod: "select",
2234
+ payPeriodStart: "text",
2235
+ payPeriodDay: "number",
2236
+ };
2237
+ const pay = ["payPeriod", "payPeriodStart", "payPeriodDay"];
2238
+ const settings = m.staffing.settings ?? {};
2239
+ if (pay.some((k) => settings[k] !== undefined)) {
2240
+ if (m.staffing.pays === undefined) {
2241
+ contract("staffing.settings", "The pay period's settings need staffing.pays");
2242
+ }
2243
+ for (const k of pay) {
2244
+ if (settings[k] === undefined) {
2245
+ contract(`staffing.settings.${k}`, "Declare the pay period's three settings together");
2246
+ }
2247
+ }
2248
+ }
2249
+ for (const [key, setting] of Object.entries(settings)) {
2250
+ if (setting === undefined)
2251
+ continue;
2252
+ const declared = Object.hasOwn(m.settings, setting) ? m.settings[setting] : undefined;
2253
+ const type = types[key] ?? "number";
2254
+ if (declared?.type !== type) {
2255
+ contract(`staffing.settings.${key}`, `"${setting}" must be a ${type} setting of this extension`);
2256
+ }
2257
+ else if (declared.personApproves !== true) {
2258
+ // The roster's numbers decide when offers close and who is warned, and the pay period what
2259
+ // is totalled: a person's to change.
2260
+ contract(`staffing.settings.${key}`, `"${setting}" must be a setting a person approves (personApproves): the roster's numbers are never an AI's to change`);
2261
+ }
2262
+ else if (type === "select" && (declared.options ?? []).some((o) => !PERIODS.has(o.value))) {
2263
+ contract(`staffing.settings.${key}`, `"${setting}" offers only weekly, fortnightly and monthly`);
2264
+ }
2265
+ }
2266
+ }
1334
2267
  // Roles (ADR 0436): each holds permissions this extension's tools declare and reads objects
1335
2268
  // of its own, and nothing else, so a role can never reach past the extension that declares it.
1336
- const declaredPermissions = new Set(Object.values(m.tools).flatMap((tool) => (tool.permission ? [tool.permission] : [])));
2269
+ const declaredPermissions = new Set(Object.values(m.tools).flatMap((tool) => toolPermissions(tool)));
1337
2270
  for (const [name, role] of Object.entries(m.roles)) {
1338
2271
  const path = `roles.${name}`;
1339
2272
  if (!FIELD_NAME_RE.test(name))
@@ -1381,7 +2314,39 @@ export function validateManifest(input, options = {}) {
1381
2314
  }
1382
2315
  }
1383
2316
  }
2317
+ // A role limited to the People its holder looks after (ADR 0889): each object its own, each
2318
+ // path its relation to person, and a team of this extension's to say who looks after whom.
2319
+ const looksAfter = Object.entries(role.looksAfter ?? {});
2320
+ if (looksAfter.length && !Object.values(m.objects).some((o) => o.team)) {
2321
+ contract(`${path}.looksAfter`, "No object of this extension declares a team: nothing says whom its holder looks after");
2322
+ }
2323
+ for (const [object, relation] of looksAfter) {
2324
+ const lp = `${path}.looksAfter.${object}`;
2325
+ const local = object.startsWith(`${m.id}.`) ? object.slice(m.id.length + 1) : null;
2326
+ const target = local && Object.hasOwn(m.objects, local) ? m.objects[local] : undefined;
2327
+ if (!target) {
2328
+ contract(lp, `"${object}" is not an object of this extension`);
2329
+ continue;
2330
+ }
2331
+ const field = Object.hasOwn(target.fields, relation) ? target.fields[relation] : undefined;
2332
+ if (field?.type !== "relation" || field.to !== "person" || field.many) {
2333
+ contract(lp, `"${relation}" must be a relation field (one record) of ${object} to person`);
2334
+ }
2335
+ if (role.today && Object.hasOwn(role.today, object)) {
2336
+ contract(lp, `${object} is limited to today already: one limit an object`);
2337
+ }
2338
+ }
2339
+ // A role reaching records only through a live record naming its holder (ADR 0755).
2340
+ checkRoleMine(m, name, role, contract);
1384
2341
  }
2342
+ for (const issue of deviceRoleIssues(m))
2343
+ contract(issue.path, issue.message);
2344
+ for (const issue of screenIssues(m))
2345
+ contract(issue.path, issue.message);
2346
+ for (const issue of portalIssues(m))
2347
+ contract(issue.path, issue.message);
2348
+ for (const issue of todayItemIssues(m))
2349
+ contract(issue.path, issue.message);
1385
2350
  for (const [name, view] of Object.entries(m.views)) {
1386
2351
  if (!FIELD_NAME_RE.test(name))
1387
2352
  contract(`views.${name}`, "View names must be camelCase");
@@ -1466,13 +2431,17 @@ export function validateManifest(input, options = {}) {
1466
2431
  checkAutomation({ manifest: m, known, objectFields: options.objectFields, contract }, name, automation);
1467
2432
  }
1468
2433
  const perms = m.permissions;
2434
+ // What an automation running only with another extension reads and writes of it (ADR 0812) is
2435
+ // checked when that extension is installed.
2436
+ const later = [...new Set(Object.values(m.automations).flatMap((a) => a.onlyWith ?? []))];
1469
2437
  for (const [key, list] of [
1470
2438
  ["read", perms.read],
1471
2439
  ["write", perms.write],
1472
2440
  ]) {
1473
2441
  list.forEach((object, i) => {
1474
- if (!known.has(object))
2442
+ if (!known.has(object) && !laterObject(later, known, object)) {
1475
2443
  contract(`permissions.${key}.${i}`, `Unknown object "${object}"`);
2444
+ }
1476
2445
  });
1477
2446
  }
1478
2447
  perms.operations.forEach((operation, i) => {
@@ -1483,6 +2452,13 @@ export function validateManifest(input, options = {}) {
1483
2452
  contract(`permissions.operations.${i}`, `Extensions cannot be granted ${operation}`);
1484
2453
  }
1485
2454
  });
2455
+ for (const issue of routineMailIssues(m))
2456
+ contract(issue.path, issue.message);
2457
+ for (const issue of journeySignalIssues(m))
2458
+ contract(issue.path, issue.message);
2459
+ if (perms.modules.includes("routine-mail") && !Object.keys(m.routineMail ?? {}).length) {
2460
+ contract("permissions.modules", 'The "routine-mail" module sends routine mail it declares');
2461
+ }
1486
2462
  const usesOps = perms.read.length > 0 || perms.write.length > 0 || perms.operations.length > 0;
1487
2463
  if (usesOps && !perms.modules.includes("ops")) {
1488
2464
  contract("permissions.modules", 'Object or operation permissions need the "ops" module');