@quad-education/sdk 0.0.0-stage → 0.1.3

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 (69) hide show
  1. package/LICENSE.md +15 -0
  2. package/README.md +106 -2
  3. package/dist/contract-tests/apps.d.ts +373 -0
  4. package/dist/contract-tests/apps.js +309 -0
  5. package/dist/contract-tests/index.d.ts +3 -0
  6. package/dist/contract-tests/index.js +2 -0
  7. package/dist/contract-tests/suite.d.ts +57 -0
  8. package/dist/contract-tests/suite.js +1405 -0
  9. package/dist/src/client/connect.d.ts +10 -0
  10. package/dist/src/client/connect.js +12 -0
  11. package/dist/src/client/create-client.d.ts +14 -0
  12. package/dist/src/client/create-client.js +76 -0
  13. package/dist/src/client/handshake-client.d.ts +16 -0
  14. package/dist/src/client/handshake-client.js +37 -0
  15. package/dist/src/contract/errors.d.ts +8 -0
  16. package/dist/src/contract/errors.js +13 -0
  17. package/dist/src/contract/recipients.d.ts +28 -0
  18. package/dist/src/contract/recipients.js +12 -0
  19. package/dist/src/contract/types.d.ts +442 -0
  20. package/dist/src/contract/types.js +1 -0
  21. package/dist/src/engine/audit.d.ts +27 -0
  22. package/dist/src/engine/audit.js +105 -0
  23. package/dist/src/engine/cron.d.ts +17 -0
  24. package/dist/src/engine/cron.js +143 -0
  25. package/dist/src/engine/db-indexes.d.ts +11 -0
  26. package/dist/src/engine/db-indexes.js +82 -0
  27. package/dist/src/engine/engine.d.ts +156 -0
  28. package/dist/src/engine/engine.js +953 -0
  29. package/dist/src/engine/host.d.ts +39 -0
  30. package/dist/src/engine/host.js +73 -0
  31. package/dist/src/engine/in-process.d.ts +5 -0
  32. package/dist/src/engine/in-process.js +18 -0
  33. package/dist/src/engine/index.d.ts +10 -0
  34. package/dist/src/engine/index.js +8 -0
  35. package/dist/src/engine/query.d.ts +16 -0
  36. package/dist/src/engine/query.js +106 -0
  37. package/dist/src/engine/runner.d.ts +26 -0
  38. package/dist/src/engine/runner.js +260 -0
  39. package/dist/src/engine/state.d.ts +107 -0
  40. package/dist/src/engine/state.js +16 -0
  41. package/dist/src/engine/storage.d.ts +46 -0
  42. package/dist/src/engine/storage.js +86 -0
  43. package/dist/src/engine/tasks.d.ts +17 -0
  44. package/dist/src/engine/tasks.js +245 -0
  45. package/dist/src/engine/validate-input.d.ts +9 -0
  46. package/dist/src/engine/validate-input.js +76 -0
  47. package/dist/src/engine/values.d.ts +10 -0
  48. package/dist/src/engine/values.js +58 -0
  49. package/dist/src/handshake.d.ts +16 -0
  50. package/dist/src/handshake.js +9 -0
  51. package/dist/src/index.d.ts +3 -0
  52. package/dist/src/index.js +4 -0
  53. package/dist/src/jobs/define.d.ts +41 -0
  54. package/dist/src/jobs/define.js +28 -0
  55. package/dist/src/jobs/host.d.ts +13 -0
  56. package/dist/src/jobs/host.js +22 -0
  57. package/dist/src/jobs/index.d.ts +1 -0
  58. package/dist/src/jobs/index.js +2 -0
  59. package/dist/src/jobs/worker.d.ts +17 -0
  60. package/dist/src/jobs/worker.js +25 -0
  61. package/dist/src/platform-types.d.ts +19 -0
  62. package/dist/src/platform-types.js +1 -0
  63. package/dist/src/port-rpc.d.ts +42 -0
  64. package/dist/src/port-rpc.js +85 -0
  65. package/dist/src/protocol.d.ts +41 -0
  66. package/dist/src/protocol.js +45 -0
  67. package/dist/src/testing/index.d.ts +78 -0
  68. package/dist/src/testing/index.js +118 -0
  69. package/package.json +71 -3
@@ -0,0 +1,1405 @@
1
+ /* eslint-disable @typescript-eslint/no-explicit-any -- the suite drives the SDK untyped, like plain JS would */
2
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
3
+ import { eligibleParents } from '@quad-education/canonical';
4
+ import { personasFor, withDerived } from '@quad-education/fictional-school';
5
+ import stored from '@quad-education/fictional-school/dataset' with { type: 'json' };
6
+ import { isQuadError, parentsOf, staffOf, studentsOf } from "../src/index.js";
7
+ import { ACCESS_APP, BASIC_APP, DATA_APP, JOBS_APP, ROLES_APP, TEST_APP, slowGate } from "./apps.js";
8
+ // The fictional school is the oracle: tests compare what the SDK returns with what the
9
+ // dataset says should be visible. They never read an implementation's storage.
10
+ const ds = withDerived(stored);
11
+ const personas = personasFor(ds);
12
+ const persona = (key) => {
13
+ const p = personas.find((x) => x.key === key);
14
+ return { kind: 'user', role: p.role, personId: p.personId };
15
+ };
16
+ const STAFF = persona('primary-teacher');
17
+ const DEPUTY = persona('deputy-principal');
18
+ const STUDENT = persona('student');
19
+ const SIBLINGS_PARENT = persona('parent-of-siblings');
20
+ const SEPARATED_PARENT = persona('separated-parent');
21
+ const SYSTEM = { kind: 'system', appId: 'contract-access' };
22
+ const RESTRICTED_PARENT = persona('restricted-parent');
23
+ const childrenOf = (parentId) => ds.parentStudentLinks
24
+ .filter((l) => l.parentId === parentId && !l.contactRestricted)
25
+ .map((l) => l.studentId);
26
+ async function listAll(collection, options = {}) {
27
+ const items = [];
28
+ let cursor;
29
+ do {
30
+ const page = await collection.list({ ...options, limit: 200, ...(cursor ? { cursor } : {}) });
31
+ items.push(...page.items);
32
+ cursor = page.nextCursor ?? undefined;
33
+ } while (cursor);
34
+ return items;
35
+ }
36
+ async function expectError(promise, code) {
37
+ try {
38
+ await promise;
39
+ }
40
+ catch (e) {
41
+ expect(isQuadError(e), `expected a QuadError, got ${String(e)}`).toBe(true);
42
+ expect(e.code).toBe(code);
43
+ return e;
44
+ }
45
+ throw new Error(`expected ${code}, but the call succeeded`);
46
+ }
47
+ const ids = (records) => records.map((r) => r.id).sort();
48
+ export function defineContractSuite(name, factory) {
49
+ describe(`@quad-education/sdk contract: ${name}`, () => {
50
+ let env;
51
+ const useApp = (app) => {
52
+ beforeEach(async () => {
53
+ env = await factory(app);
54
+ });
55
+ afterEach(async () => {
56
+ await env.dispose();
57
+ });
58
+ };
59
+ describe('auth', () => {
60
+ useApp(TEST_APP);
61
+ it('returns the connected user', async () => {
62
+ const sdk = await env.connect(STAFF);
63
+ const me = await sdk.auth.me();
64
+ const record = ds.staff.find((s) => s.id === STAFF.personId);
65
+ expect(me).toEqual({
66
+ kind: 'user',
67
+ role: 'staff',
68
+ person: {
69
+ id: record.id,
70
+ givenName: record.givenName,
71
+ familyName: record.familyName,
72
+ displayName: `${record.givenName} ${record.familyName}`,
73
+ },
74
+ });
75
+ expect(sdk.appId).toBe(TEST_APP.manifest.id);
76
+ expect(sdk.version).toBe('0.1.3');
77
+ });
78
+ it('knows parents and students', async () => {
79
+ expect((await (await env.connect(STUDENT)).auth.me()).role).toBe('student');
80
+ expect((await (await env.connect(SIBLINGS_PARENT)).auth.me()).role).toBe('parent');
81
+ });
82
+ });
83
+ describe('school: visibility (D4)', () => {
84
+ useApp(TEST_APP);
85
+ it('staff see every student', async () => {
86
+ const sdk = await env.connect(STAFF);
87
+ expect((await listAll(sdk.school.students)).length).toBe(ds.students.length);
88
+ });
89
+ it('a student sees only themselves', async () => {
90
+ const sdk = await env.connect(STUDENT);
91
+ expect(ids(await listAll(sdk.school.students))).toEqual([STUDENT.personId]);
92
+ expect((await listAll(sdk.school.parents)).length).toBe(0);
93
+ expect((await listAll(sdk.school.pastoralNotes)).length).toBe(0);
94
+ });
95
+ it('a parent sees only their own children', async () => {
96
+ const sdk = await env.connect(SIBLINGS_PARENT);
97
+ const expected = childrenOf(SIBLINGS_PARENT.personId).sort();
98
+ expect(expected.length).toBeGreaterThanOrEqual(2);
99
+ expect(ids(await listAll(sdk.school.students))).toEqual(expected);
100
+ expect(ids(await listAll(sdk.school.parents))).toEqual([SIBLINGS_PARENT.personId]);
101
+ });
102
+ it('a separated parent sees their one child', async () => {
103
+ const sdk = await env.connect(SEPARATED_PARENT);
104
+ expect((await listAll(sdk.school.students)).length).toBe(1);
105
+ });
106
+ it('a contact-restricted parent sees no child (D17)', async () => {
107
+ const sdk = await env.connect(RESTRICTED_PARENT);
108
+ expect(await listAll(sdk.school.students)).toEqual([]);
109
+ expect(await listAll(sdk.school.medicalAlerts)).toEqual([]);
110
+ expect(await listAll(sdk.school.parentStudentLinks)).toEqual([]);
111
+ });
112
+ it('get on a record the user cannot see is NOT_FOUND', async () => {
113
+ const sdk = await env.connect(STUDENT);
114
+ const other = ds.students.find((s) => s.id !== STUDENT.personId);
115
+ await expectError(sdk.school.students.get(other.id), 'NOT_FOUND');
116
+ await expectError(sdk.school.students.get('stu-does-not-exist'), 'NOT_FOUND');
117
+ expect((await sdk.school.students.get(STUDENT.personId)).id).toBe(STUDENT.personId);
118
+ });
119
+ it('cohort memberships never reveal classmates', async () => {
120
+ const sdk = await env.connect(STUDENT);
121
+ const studentId = STUDENT.personId;
122
+ const memberships = await listAll(sdk.school.cohortMemberships);
123
+ expect(memberships.length).toBeGreaterThan(0);
124
+ for (const m of memberships) {
125
+ if (m.memberType === 'student')
126
+ expect(m.personId).toBe(studentId);
127
+ }
128
+ });
129
+ it('staff see pastoral notes; students and parents never do', async () => {
130
+ expect((await listAll((await env.connect(STAFF)).school.pastoralNotes)).length).toBe(ds.pastoralNotes.length);
131
+ expect(await listAll((await env.connect(SIBLINGS_PARENT)).school.pastoralNotes)).toEqual([]);
132
+ });
133
+ });
134
+ describe('school: scopes and tiers (D5, D23)', () => {
135
+ describe('with only students.basic:read', () => {
136
+ useApp(BASIC_APP);
137
+ it('returns basic fields and leaves other tiers absent', async () => {
138
+ const sdk = await env.connect(STAFF);
139
+ const { items } = await sdk.school.students.list({ limit: 1 });
140
+ const student = items[0];
141
+ expect(student.givenName).toEqual(expect.any(String));
142
+ expect(student.yearLevel).toEqual(expect.any(String));
143
+ expect('dateOfBirth' in student).toBe(false);
144
+ expect('email' in student).toBe(false);
145
+ expect(student.source).toBe('simulated');
146
+ });
147
+ it('refuses entities with no granted scope', async () => {
148
+ const sdk = await env.connect(STAFF);
149
+ await expectError(sdk.school.parents.list(), 'SCOPE_NOT_GRANTED');
150
+ await expectError(sdk.school.medicalAlerts.get(ds.medicalAlerts[0].id), 'SCOPE_NOT_GRANTED');
151
+ await expectError(sdk.school.calendar.list({ from: '2026-01-01', to: '2027-01-01' }), 'SCOPE_NOT_GRANTED');
152
+ });
153
+ it('still answers school.info', async () => {
154
+ const info = await (await env.connect(STUDENT)).school.info();
155
+ expect(info).toMatchObject({
156
+ name: ds.schools[0].name,
157
+ timezone: 'Australia/Sydney',
158
+ state: 'NSW',
159
+ });
160
+ expect(info.yearLevelLabels.Y0).toBe('Kindergarten');
161
+ });
162
+ });
163
+ describe('with broader scopes', () => {
164
+ useApp(TEST_APP);
165
+ it('includes granted tiers', async () => {
166
+ const sdk = await env.connect(STAFF);
167
+ const student = await sdk.school.students.get(ds.students[0].id);
168
+ expect(student.dateOfBirth).toBe(ds.students[0].dateOfBirth);
169
+ const alert = (await sdk.school.medicalAlerts.list({ limit: 1 })).items[0];
170
+ expect(alert.condition).toEqual(expect.any(String));
171
+ });
172
+ it('shows students and parents only basic staff fields', async () => {
173
+ const staffRecord = (await (await env.connect(SIBLINGS_PARENT)).school.staff.list({ limit: 1 })).items[0];
174
+ expect(staffRecord.givenName).toEqual(expect.any(String));
175
+ expect('email' in staffRecord).toBe(false);
176
+ const asStaff = (await (await env.connect(STAFF)).school.staff.list({ limit: 1 }))
177
+ .items[0];
178
+ expect(asStaff.email).toEqual(expect.any(String));
179
+ });
180
+ it('never shows restriction flags without a pastoral scope', async () => {
181
+ const sdk = await env.connect(STAFF);
182
+ const links = await listAll(sdk.school.parentStudentLinks);
183
+ expect(links.length).toBe(ds.parentStudentLinks.length);
184
+ for (const l of links) {
185
+ expect('contactRestricted' in l).toBe(false);
186
+ expect('restrictionNote' in l).toBe(false);
187
+ }
188
+ });
189
+ });
190
+ });
191
+ describe('app-defined roles are previewed by the persona of the same name (D84)', () => {
192
+ useApp(ROLES_APP);
193
+ it('serves the personas whose role matches an app role, ignoring case, and refuses the rest', async () => {
194
+ const staff = await env.connect(STAFF);
195
+ const student = await env.connect(STUDENT);
196
+ expect((await staff.auth.me()).role).toBe('staff');
197
+ expect((await student.auth.me()).role).toBe('student');
198
+ await expectError(env.connect(SIBLINGS_PARENT).then((p) => p.auth.me()), 'FORBIDDEN');
199
+ });
200
+ it('follows the access rules written for the app role, whatever the case of the key', async () => {
201
+ const staff = await env.connect(STAFF);
202
+ const student = await env.connect(STUDENT);
203
+ const note = await student.db.entity('entry').create({ body: 'mine' });
204
+ await staff.db.entity('entry').create({ body: 'staff note' });
205
+ // `Staff` (capitalised in the schema) gives staff all records; `student` gives a student their own.
206
+ expect((await staff.db.entity('entry').list()).items).toHaveLength(2);
207
+ expect((await student.db.entity('entry').list()).items.map((e) => e.id)).toEqual([
208
+ note.id,
209
+ ]);
210
+ await expectError(student.db.entity('entry').delete(note.id), 'NOT_PERMITTED');
211
+ });
212
+ });
213
+ describe('school: declared fields (D85)', () => {
214
+ useApp(DATA_APP);
215
+ it('returns the core fields and the declared ones, and nothing else that varies', async () => {
216
+ const sdk = await env.connect(STAFF);
217
+ const expected = ds.students[0];
218
+ const student = await sdk.school.students.get(expected.id);
219
+ expect(student.givenName).toBe(expected.givenName);
220
+ expect(student.studentNumber).toBe(expected.studentNumber);
221
+ expect(student.dateOfBirth).toBe(expected.dateOfBirth);
222
+ expect(student.email).toBe(expected.email);
223
+ // yearLevel and preferredName are granted by tier but were not declared.
224
+ expect('yearLevel' in student).toBe(false);
225
+ expect('preferredName' in student).toBe(false);
226
+ for (const s of (await sdk.school.students.list({ limit: 25 })).items) {
227
+ expect('yearLevel' in s).toBe(false);
228
+ expect('preferredName' in s).toBe(false);
229
+ expect('dateOfBirth' in s).toBe(true);
230
+ }
231
+ });
232
+ it('refuses to filter or sort on a field that was not declared, so it cannot be probed', async () => {
233
+ const sdk = await env.connect(STAFF);
234
+ await expectError(sdk.school.students.list({ where: { yearLevel: 'Y9' } }), 'VALIDATION');
235
+ await expectError(sdk.school.students.list({ orderBy: { field: 'preferredName' } }), 'VALIDATION');
236
+ // Declared and core fields still work.
237
+ const name = ds.students[0].familyName;
238
+ const found = await sdk.school.students.list({ where: { familyName: name }, limit: 200 });
239
+ expect(found.items.length).toBeGreaterThan(0);
240
+ expect((await sdk.school.students.list({ where: { dateOfBirth: ds.students[0].dateOfBirth } }))
241
+ .items.length).toBeGreaterThan(0);
242
+ });
243
+ it('strips included school refs the same way', async () => {
244
+ const sdk = await env.connect(STAFF);
245
+ await sdk.db
246
+ .entity('greeting')
247
+ .create({ message: 'hi', studentId: ds.students[0].id, tone: 'warm' });
248
+ const { items } = await sdk.db.entity('greeting').list({ include: ['studentId'] });
249
+ const included = items[0].$included.studentId;
250
+ expect(included.givenName).toBe(ds.students[0].givenName);
251
+ expect('yearLevel' in included).toBe(false);
252
+ expect('dateOfBirth' in included).toBe(true);
253
+ });
254
+ });
255
+ describe('school: no declaration (version 0) still gives every field of the granted tiers', () => {
256
+ useApp(BASIC_APP);
257
+ it('keeps yearLevel and preferredName available', async () => {
258
+ const student = (await (await env.connect(STAFF)).school.students.list({ limit: 1 }))
259
+ .items[0];
260
+ expect('yearLevel' in student).toBe(true);
261
+ });
262
+ });
263
+ describe('school: queries and helpers', () => {
264
+ useApp(TEST_APP);
265
+ it('filters with where, orders and pages without gaps or repeats', async () => {
266
+ const sdk = await env.connect(STAFF);
267
+ const y9 = await listAll(sdk.school.students, { where: { yearLevel: 'Y9' } });
268
+ expect(ids(y9)).toEqual(ids(ds.students.filter((s) => s.yearLevel === 'Y9')));
269
+ const some = await sdk.school.students.list({
270
+ where: { yearLevel: { in: ['Y0', 'Y1'] } },
271
+ limit: 200,
272
+ });
273
+ expect(some.items.every((s) => ['Y0', 'Y1'].includes(s.yearLevel))).toBe(true);
274
+ const ordered = await sdk.school.students.list({
275
+ where: { yearLevel: 'Y9' },
276
+ orderBy: { field: 'familyName' },
277
+ limit: 200,
278
+ });
279
+ const names = ordered.items.map((s) => s.familyName);
280
+ expect(names).toEqual([...names].sort((a, b) => a.localeCompare(b)));
281
+ const small = [];
282
+ let page = await sdk.school.students.list({ limit: 7 });
283
+ small.push(...page.items);
284
+ while (page.nextCursor) {
285
+ page = await sdk.school.students.list({ limit: 7, cursor: page.nextCursor });
286
+ small.push(...page.items);
287
+ }
288
+ expect(small.length).toBe(ds.students.length);
289
+ expect(new Set(small.map((s) => s.id)).size).toBe(ds.students.length);
290
+ });
291
+ it('validates list options', async () => {
292
+ const sdk = await env.connect(STAFF);
293
+ await expectError(sdk.school.students.list({ limit: 500 }), 'VALIDATION');
294
+ await expectError(sdk.school.students.list({ where: { shoeSize: 9 } }), 'VALIDATION');
295
+ await expectError(sdk.school.students.list({ cursor: 'not-a-cursor' }), 'VALIDATION');
296
+ });
297
+ it('finds teams by code and lists their members (D18)', async () => {
298
+ const sdk = await env.connect(STAFF);
299
+ const deputies = await sdk.school.cohorts.byCode('deputy-principal');
300
+ expect(deputies).toMatchObject({ kind: 'team', code: 'deputy-principal' });
301
+ const members = await sdk.school.cohorts.members(deputies.id);
302
+ expect(members.map((m) => m.personId)).toContain(DEPUTY.personId);
303
+ expect(members.every((m) => m.memberType === 'staff')).toBe(true);
304
+ expect(await sdk.school.cohorts.byCode('no-such-team')).toBeNull();
305
+ });
306
+ it('lists a student’s parents and a parent’s children within visibility', async () => {
307
+ const staff = await env.connect(STAFF);
308
+ const parentId = SIBLINGS_PARENT.personId;
309
+ const children = await staff.school.parents.children(parentId);
310
+ expect(ids(children)).toEqual(childrenOf(parentId).sort());
311
+ const parents = await staff.school.students.parents(children[0].id);
312
+ expect(parents.map((p) => p.id)).toContain(parentId);
313
+ const student = await env.connect(STUDENT);
314
+ await expectError(student.school.parents.children(parentId), 'NOT_FOUND');
315
+ });
316
+ it('serves the timetable, which is derived, like any other entity (S4.1)', async () => {
317
+ const english = ds.cohorts.find((c) => c.code === 'y09-english-b');
318
+ const week = { gte: '2026-03-02', lt: '2026-03-09' };
319
+ const expected = ds.lessons
320
+ .filter((l) => l.cohortId === english.id && l.date >= week.gte && l.date < week.lt)
321
+ .map((l) => l.id);
322
+ expect(expected).toHaveLength(4);
323
+ // A published timetable: staff, students and parents all read it.
324
+ for (const who of [STAFF, STUDENT, SIBLINGS_PARENT]) {
325
+ const sdk = await env.connect(who);
326
+ const page = await sdk.school.lessons.list({
327
+ where: { cohortId: english.id, date: week },
328
+ orderBy: { field: 'startsAt' },
329
+ limit: 50,
330
+ });
331
+ expect(page.items.map((l) => l.id)).toEqual(expected);
332
+ expect(page.items[0]).toMatchObject({ cohortId: english.id });
333
+ }
334
+ });
335
+ it('pages through a day of lessons without gaps or repeats, and finds one by id', async () => {
336
+ const sdk = await env.connect(STUDENT);
337
+ const day = '2026-03-03';
338
+ const expected = ds.lessons.filter((l) => l.date === day).map((l) => l.id);
339
+ const seen = [];
340
+ let page = await sdk.school.lessons.list({ where: { date: day }, limit: 100 });
341
+ seen.push(...page.items.map((l) => l.id));
342
+ while (page.nextCursor) {
343
+ page = await sdk.school.lessons.list({
344
+ where: { date: day },
345
+ limit: 100,
346
+ cursor: page.nextCursor,
347
+ });
348
+ seen.push(...page.items.map((l) => l.id));
349
+ }
350
+ expect(seen.slice().sort()).toEqual(expected.slice().sort());
351
+ expect(new Set(seen).size).toBe(expected.length);
352
+ const one = await sdk.school.lessons.get(expected[0]);
353
+ expect(one.id).toBe(expected[0]);
354
+ await expectError(sdk.school.lessons.get('les-20260303-nope-p1'), 'NOT_FOUND');
355
+ });
356
+ it('lists the school day’s periods and rooms', async () => {
357
+ const sdk = await env.connect(STUDENT);
358
+ const periods = await listAll(sdk.school.periods, {});
359
+ expect(periods).toHaveLength(30);
360
+ const rooms = await listAll(sdk.school.rooms, {});
361
+ expect(ids(rooms)).toEqual(ids(ds.rooms));
362
+ });
363
+ it('lists calendar events in a date range', async () => {
364
+ const sdk = await env.connect(STAFF);
365
+ const from = '2026-03-01T00:00:00Z';
366
+ const to = '2026-04-01T00:00:00Z';
367
+ const events = await sdk.school.calendar.list({ from, to });
368
+ const expected = ds.calendarEvents.filter((e) => e.start < to && e.end > from);
369
+ expect(ids(events)).toEqual(ids(expected));
370
+ const y7 = await sdk.school.cohorts.byCode('y07');
371
+ const forY7 = await sdk.school.calendar.list({ from, to, cohortId: y7.id });
372
+ expect(forY7.every((e) => e.cohortIds.length === 0 || e.cohortIds.includes(y7.id))).toBe(true);
373
+ expect(forY7.some((e) => e.title === 'Year 7 camp')).toBe(true);
374
+ });
375
+ });
376
+ describe('db', () => {
377
+ useApp(TEST_APP);
378
+ const studentId = ds.students[0].id;
379
+ it('creates, reads, updates and deletes records with system fields', async () => {
380
+ await env.control.setClock('2026-03-04T03:00:00.000Z');
381
+ const sdk = await env.connect(STAFF);
382
+ const greetings = sdk.db.entity('greeting');
383
+ const created = await greetings.create({ message: 'Hello', studentId, tone: 'warm' });
384
+ expect(created).toMatchObject({
385
+ message: 'Hello',
386
+ tone: 'warm',
387
+ createdAt: '2026-03-04T03:00:00.000Z',
388
+ createdBy: STAFF.personId,
389
+ updatedBy: STAFF.personId,
390
+ });
391
+ expect('note' in created).toBe(false);
392
+ expect(await greetings.get(created.id)).toEqual(created);
393
+ await env.control.setClock('2026-03-05T03:00:00.000Z');
394
+ const deputy = await env.connect(DEPUTY);
395
+ const updated = await deputy.db.entity('greeting').update(created.id, { tone: 'formal' });
396
+ expect(updated).toMatchObject({
397
+ tone: 'formal',
398
+ message: 'Hello',
399
+ createdBy: STAFF.personId,
400
+ updatedBy: DEPUTY.personId,
401
+ updatedAt: '2026-03-05T03:00:00.000Z',
402
+ });
403
+ await greetings.delete(created.id);
404
+ await expectError(greetings.get(created.id), 'NOT_FOUND');
405
+ await expectError(greetings.update(created.id, { tone: 'warm' }), 'NOT_FOUND');
406
+ });
407
+ it('validates input against the schema', async () => {
408
+ const greetings = (await env.connect(STAFF)).db.entity('greeting');
409
+ await expectError(greetings.create({ message: 'Hi', studentId }), 'VALIDATION'); // missing tone
410
+ await expectError(greetings.create({ message: 1, studentId, tone: 'warm' }), 'VALIDATION');
411
+ await expectError(greetings.create({ message: 'Hi', studentId, tone: 'loud' }), 'VALIDATION');
412
+ await expectError(greetings.create({ message: 'Hi', studentId, tone: 'warm', colour: 'red' }), 'VALIDATION');
413
+ await expectError(greetings.create({ message: 'Hi', studentId, tone: 'warm', id: 'mine' }), 'VALIDATION');
414
+ await expectError((await env.connect(STAFF)).db.entity('nope').list(), 'VALIDATION');
415
+ // Names inherited from Object.prototype are neither entities nor fields.
416
+ for (const name of ['toString', 'constructor', '__proto__']) {
417
+ await expectError((await env.connect(STAFF)).db.entity(name).list(), 'VALIDATION');
418
+ }
419
+ await expectError(greetings.create({ message: 'Hi', studentId, tone: 'warm', constructor: 'x' }), 'VALIDATION');
420
+ await expectError(greetings.list({ where: { toString: 'x' } }), 'VALIDATION');
421
+ });
422
+ it('lists with where, orderBy and pagination', async () => {
423
+ const greetings = (await env.connect(STAFF)).db.entity('greeting');
424
+ for (let i = 0; i < 12; i++) {
425
+ await greetings.create({
426
+ message: `m${String(i).padStart(2, '0')}`,
427
+ studentId,
428
+ tone: i % 2 ? 'warm' : 'formal',
429
+ });
430
+ }
431
+ const warm = await greetings.list({ where: { tone: 'warm' }, limit: 200 });
432
+ expect(warm.items).toHaveLength(6);
433
+ const ordered = await greetings.list({
434
+ orderBy: { field: 'message', direction: 'desc' },
435
+ limit: 5,
436
+ });
437
+ expect(ordered.items.map((g) => g.message)).toEqual([
438
+ 'm11',
439
+ 'm10',
440
+ 'm09',
441
+ 'm08',
442
+ 'm07',
443
+ ]);
444
+ const next = await greetings.list({
445
+ orderBy: { field: 'message', direction: 'desc' },
446
+ limit: 5,
447
+ cursor: ordered.nextCursor,
448
+ });
449
+ expect(next.items.map((g) => g.message)).toEqual(['m06', 'm05', 'm04', 'm03', 'm02']);
450
+ });
451
+ it('needs a declared index for orderBy and range filters (D37)', async () => {
452
+ const staff = await env.connect(STAFF);
453
+ const greetings = staff.db.entity('greeting');
454
+ for (let i = 0; i < 6; i++) {
455
+ await greetings.create({
456
+ message: `m${i}`,
457
+ studentId,
458
+ tone: i % 2 ? 'warm' : 'formal',
459
+ note: `n${i}`,
460
+ });
461
+ }
462
+ // Unindexed sorts and ranges are refused, naming the index to add.
463
+ const sort = await expectError(greetings.list({ orderBy: { field: 'note' } }), 'VALIDATION');
464
+ expect(sort.message).toContain("indexes: [['note']]");
465
+ await expectError(greetings.list({ where: { note: { gt: 'n2' } } }), 'VALIDATION');
466
+ await expectError(greetings.list({
467
+ orderBy: [
468
+ { field: 'tone', direction: 'asc' },
469
+ { field: 'message', direction: 'desc' },
470
+ ],
471
+ }), 'VALIDATION');
472
+ // Equality, in and ne work on any field.
473
+ expect((await greetings.list({ where: { note: 'n3' } })).items).toHaveLength(1);
474
+ expect((await greetings.list({ where: { note: { in: ['n1', 'n2'] } } })).items).toHaveLength(2);
475
+ expect((await greetings.list({ where: { note: { ne: 'n0' } } })).items).toHaveLength(5);
476
+ // An index after an equality prefix, with a range on its next field.
477
+ const warm = await greetings.list({
478
+ where: { tone: 'warm', message: { gte: 'm2' } },
479
+ orderBy: { field: 'message', direction: 'desc' },
480
+ });
481
+ expect(warm.items.map((g) => g.message)).toEqual(['m5', 'm3']);
482
+ // id and createdAt are always indexed, even on an entity that declares no indexes.
483
+ const replies = staff.db.entity('reply');
484
+ const greeting = warm.items[0];
485
+ const first = await replies.create({ greetingId: greeting.id, message: 'first' });
486
+ await replies.create({ greetingId: greeting.id, message: 'second' });
487
+ const newest = await replies.list({ orderBy: { field: 'createdAt', direction: 'desc' } });
488
+ expect(newest.items).toHaveLength(2);
489
+ const since = await replies.list({ where: { createdAt: { gte: first.createdAt } } });
490
+ expect(since.items).toHaveLength(2);
491
+ await expectError(replies.list({ orderBy: { field: 'message' } }), 'VALIDATION');
492
+ });
493
+ it('includes refs, filtered by the current user’s visibility', async () => {
494
+ const staff = await env.connect(STAFF);
495
+ const parentId = SIBLINGS_PARENT.personId;
496
+ const child = childrenOf(parentId)[0];
497
+ const stranger = ds.students.find((s) => !childrenOf(parentId).includes(s.id)).id;
498
+ const g1 = await staff.db
499
+ .entity('greeting')
500
+ .create({ message: 'to child', studentId: child, tone: 'warm' });
501
+ await staff.db
502
+ .entity('greeting')
503
+ .create({ message: 'to stranger', studentId: stranger, tone: 'warm' });
504
+ await staff.db.entity('reply').create({ greetingId: g1.id, message: 'thanks' });
505
+ const asStaff = await staff.db
506
+ .entity('greeting')
507
+ .list({ include: ['studentId'], limit: 200 });
508
+ expect(asStaff.items.every((g) => g.$included.studentId?.id === g.studentId)).toBe(true);
509
+ expect('dateOfBirth' in asStaff.items[0].$included.studentId).toBe(true);
510
+ const parent = await env.connect(SIBLINGS_PARENT);
511
+ const asParent = await parent.db
512
+ .entity('greeting')
513
+ .list({ include: ['studentId'], limit: 200 });
514
+ // D25: the greeting about another family's child isn't returned at all.
515
+ expect(asParent.items.map((g) => g.message)).toEqual(['to child']);
516
+ expect(asParent.items[0].$included.studentId.id).toBe(child);
517
+ const replies = await staff.db.entity('reply').list({ include: ['greetingId'] });
518
+ expect(replies.items[0].$included.greetingId.message).toBe('to child');
519
+ await expectError(staff.db.entity('greeting').list({ include: ['message'] }), 'VALIDATION');
520
+ });
521
+ it('survives a restart (page reload)', async () => {
522
+ const created = await (await env.connect(STAFF)).db
523
+ .entity('greeting')
524
+ .create({ message: 'kept', studentId, tone: 'warm' });
525
+ await env.control.restart();
526
+ expect((await (await env.connect(STAFF)).db.entity('greeting').get(created.id)).message).toBe('kept');
527
+ });
528
+ it('resets the store when the schema changes (D12)', async () => {
529
+ const created = await (await env.connect(STAFF)).db
530
+ .entity('greeting')
531
+ .create({ message: 'gone', studentId, tone: 'warm' });
532
+ const changed = {
533
+ ...TEST_APP.schema,
534
+ greeting: {
535
+ ...TEST_APP.schema.greeting,
536
+ fields: {
537
+ ...TEST_APP.schema.greeting.fields,
538
+ extra: { kind: 'text', tier: 'basic', optional: true },
539
+ },
540
+ },
541
+ };
542
+ await env.control.restart({ schema: changed });
543
+ await expectError((await env.connect(STAFF)).db.entity('greeting').get(created.id), 'NOT_FOUND');
544
+ });
545
+ it('drops repeated creates with the same idempotency key', async () => {
546
+ const greetings = (await env.connect(STAFF)).db.entity('greeting');
547
+ const a = await greetings.create({ message: 'once', studentId, tone: 'warm' }, { idempotencyKey: 'k1' });
548
+ const b = await greetings.create({ message: 'once', studentId, tone: 'warm' }, { idempotencyKey: 'k1' });
549
+ expect(b.id).toBe(a.id);
550
+ expect((await greetings.list({ where: { message: 'once' } })).items).toHaveLength(1);
551
+ });
552
+ it('reset clears app data', async () => {
553
+ await (await env.connect(STAFF)).db
554
+ .entity('greeting')
555
+ .create({ message: 'x', studentId, tone: 'warm' });
556
+ await env.control.reset();
557
+ expect((await (await env.connect(STAFF)).db.entity('greeting').list()).items).toEqual([]);
558
+ });
559
+ });
560
+ describe('db access control (D25)', () => {
561
+ useApp(ACCESS_APP);
562
+ const myChild = () => childrenOf(SIBLINGS_PARENT.personId)[0];
563
+ const otherChild = () => ds.students.find((s) => !childrenOf(SIBLINGS_PARENT.personId).includes(s.id) &&
564
+ !childrenOf(SEPARATED_PARENT.personId).includes(s.id)).id;
565
+ async function seed() {
566
+ const staff = await env.connect(STAFF);
567
+ const trip = await staff.db.entity('excursion').create({ title: 'Museum' });
568
+ const mine = await staff.db.entity('consent').create({
569
+ studentId: myChild(),
570
+ excursionId: trip.id,
571
+ status: 'pending',
572
+ staffNote: 'Check medical plan',
573
+ });
574
+ const theirs = await staff.db.entity('consent').create({
575
+ studentId: otherChild(),
576
+ excursionId: trip.id,
577
+ status: 'pending',
578
+ staffNote: 'Private',
579
+ });
580
+ return { staff, trip, mine, theirs };
581
+ }
582
+ it("a parent can't get, list, filter, page or include another family's records", async () => {
583
+ const { staff, mine, theirs } = await seed();
584
+ const parent = await env.connect(SIBLINGS_PARENT);
585
+ const consents = parent.db.entity('consent');
586
+ expect((await consents.list()).items.map((c) => c.id)).toEqual([mine.id]);
587
+ await expectError(consents.get(theirs.id), 'NOT_FOUND');
588
+ expect((await consents.list({ where: { studentId: otherChild() } })).items).toEqual([]);
589
+ expect((await consents.list({ where: { id: theirs.id } })).items).toEqual([]);
590
+ const firstPage = await consents.list({ where: { status: 'pending' }, limit: 1 });
591
+ expect(firstPage.items.map((c) => c.id)).toEqual([mine.id]);
592
+ expect(firstPage.nextCursor).toBeNull(); // the cursor doesn't hint that more records exist
593
+ await staff.db
594
+ .entity('message')
595
+ .create({ studentId: myChild(), consentId: theirs.id, body: 'linked to theirs' });
596
+ await staff.db
597
+ .entity('message')
598
+ .create({ studentId: myChild(), consentId: mine.id, body: 'linked to mine' });
599
+ const messages = await parent.db
600
+ .entity('message')
601
+ .list({ include: ['consentId'], orderBy: { field: 'body' } });
602
+ const included = Object.fromEntries(messages.items.map((m) => [m.body, m.$included.consentId]));
603
+ expect(included['linked to theirs']).toBeNull();
604
+ expect(included['linked to mine'].id).toBe(mine.id);
605
+ expect('staffNote' in included['linked to mine']).toBe(false);
606
+ });
607
+ it('NOT_FOUND for missing and inaccessible records alike, so existence never leaks', async () => {
608
+ const { theirs } = await seed();
609
+ const parent = await env.connect(SIBLINGS_PARENT);
610
+ let missing;
611
+ let hidden;
612
+ try {
613
+ await parent.db.entity('consent').get('consent_does-not-exist');
614
+ }
615
+ catch (e) {
616
+ missing = e;
617
+ }
618
+ try {
619
+ await parent.db.entity('consent').get(theirs.id);
620
+ }
621
+ catch (e) {
622
+ hidden = e;
623
+ }
624
+ expect(missing.code).toBe('NOT_FOUND');
625
+ expect(hidden.code).toBe('NOT_FOUND');
626
+ await expectError(parent.db.entity('consent').update(theirs.id, { status: 'given' }), 'NOT_FOUND');
627
+ });
628
+ it('enforces field visibleTo on reads, filters and writes', async () => {
629
+ const { mine } = await seed();
630
+ const staff = await env.connect(STAFF);
631
+ expect((await staff.db.entity('consent').get(mine.id)).staffNote).toBe('Check medical plan');
632
+ const parent = await env.connect(SIBLINGS_PARENT);
633
+ const asParent = await parent.db.entity('consent').get(mine.id);
634
+ expect('staffNote' in asParent).toBe(false);
635
+ expect((await parent.db.entity('consent').list()).items.every((c) => !('staffNote' in c))).toBe(true);
636
+ await expectError(parent.db.entity('consent').list({ where: { staffNote: 'Check medical plan' } }), 'VALIDATION');
637
+ await expectError(parent.db.entity('consent').update(mine.id, { staffNote: 'mine now' }), 'NOT_PERMITTED');
638
+ const updated = await parent.db.entity('consent').update(mine.id, { status: 'given' });
639
+ expect(updated.status).toBe('given');
640
+ expect('staffNote' in updated).toBe(false);
641
+ expect((await staff.db.entity('consent').get(mine.id)).staffNote).toBe('Check medical plan');
642
+ });
643
+ it('denies roles and operations the entity does not list', async () => {
644
+ const { trip, mine } = await seed();
645
+ const parent = await env.connect(SIBLINGS_PARENT);
646
+ // excursion has no access block: staff-only.
647
+ await expectError(parent.db.entity('excursion').list(), 'NOT_PERMITTED');
648
+ await expectError(parent.db.entity('excursion').get(trip.id), 'NOT_PERMITTED');
649
+ // consent: parents may read and update, not create or delete.
650
+ await expectError(parent.db
651
+ .entity('consent')
652
+ .create({ studentId: myChild(), excursionId: trip.id, status: 'given' }), 'NOT_PERMITTED');
653
+ await expectError(parent.db.entity('consent').delete(mine.id), 'NOT_PERMITTED');
654
+ // message: students have no rules at all.
655
+ const student = await env.connect(STUDENT);
656
+ await expectError(student.db.entity('message').list(), 'NOT_PERMITTED');
657
+ // staff may not update messages (not listed).
658
+ const staff = await env.connect(STAFF);
659
+ const msg = await staff.db.entity('message').create({ studentId: myChild(), body: 'hi' });
660
+ await expectError(staff.db.entity('message').update(msg.id, { body: 'edited' }), 'NOT_PERMITTED');
661
+ });
662
+ it("'own' covers only records the user created", async () => {
663
+ const parent = await env.connect(SIBLINGS_PARENT);
664
+ const staff = await env.connect(STAFF);
665
+ const fromParent = await parent.db
666
+ .entity('message')
667
+ .create({ studentId: myChild(), body: 'from parent' });
668
+ expect(fromParent.createdBy).toBe(SIBLINGS_PARENT.personId);
669
+ expect((await parent.db.entity('message').update(fromParent.id, { body: 'edited' })).body).toBe('edited');
670
+ const fromStaff = await staff.db
671
+ .entity('message')
672
+ .create({ studentId: myChild(), body: 'from staff' });
673
+ await expectError(parent.db.entity('message').update(fromStaff.id, { body: 'hijack' }), 'NOT_PERMITTED');
674
+ await expectError(parent.db.entity('message').delete(fromStaff.id), 'NOT_PERMITTED');
675
+ await parent.db.entity('message').delete(fromParent.id);
676
+ });
677
+ it("can't set or change the subject to a student the user can't see", async () => {
678
+ const { mine } = await seed();
679
+ const parent = await env.connect(SIBLINGS_PARENT);
680
+ await expectError(parent.db.entity('message').create({ studentId: otherChild(), body: 'x' }), 'NOT_PERMITTED');
681
+ await expectError(parent.db.entity('consent').update(mine.id, { studentId: otherChild() }), 'NOT_PERMITTED');
682
+ const own = await parent.db.entity('message').create({ studentId: myChild(), body: 'mine' });
683
+ await expectError(parent.db.entity('message').update(own.id, { studentId: otherChild() }), 'NOT_PERMITTED');
684
+ // A restricted parent can't write about the child they're restricted from (D17).
685
+ const restrictedLink = ds.parentStudentLinks.find((l) => l.parentId === RESTRICTED_PARENT.personId);
686
+ const restricted = await env.connect(RESTRICTED_PARENT);
687
+ await expectError(restricted.db
688
+ .entity('message')
689
+ .create({ studentId: restrictedLink.studentId, body: 'x' }), 'NOT_PERMITTED');
690
+ // Staff can't point a subject at a student who doesn't exist.
691
+ const staff = await env.connect(STAFF);
692
+ await expectError(staff.db.entity('message').create({ studentId: 'stu-nobody', body: 'x' }), 'NOT_PERMITTED');
693
+ });
694
+ it('the separated parent sees only their own child’s records', async () => {
695
+ const staff = await env.connect(STAFF);
696
+ const theirChild = childrenOf(SEPARATED_PARENT.personId)[0];
697
+ const trip = await staff.db.entity('excursion').create({ title: 'Zoo' });
698
+ await staff.db
699
+ .entity('consent')
700
+ .create({ studentId: theirChild, excursionId: trip.id, status: 'pending' });
701
+ await staff.db
702
+ .entity('consent')
703
+ .create({ studentId: myChild(), excursionId: trip.id, status: 'pending' });
704
+ const separated = await env.connect(SEPARATED_PARENT);
705
+ const list = await separated.db.entity('consent').list();
706
+ expect(list.items.map((c) => c.studentId)).toEqual([theirChild]);
707
+ });
708
+ it('the system principal has full access to the app’s own data', async () => {
709
+ const { trip, mine, theirs } = await seed();
710
+ const system = await env.connect(SYSTEM);
711
+ const all = await system.db.entity('consent').list();
712
+ expect(all.items.map((c) => c.id).sort()).toEqual([mine.id, theirs.id].sort());
713
+ expect(all.items.every((c) => 'staffNote' in c)).toBe(true);
714
+ expect((await system.db.entity('excursion').get(trip.id)).title).toBe('Museum');
715
+ const created = await system.db
716
+ .entity('message')
717
+ .create({ studentId: otherChild(), body: 'from a job' });
718
+ expect(created.createdBy).toBe('system:contract-access');
719
+ expect((await system.db.entity('message').update(created.id, { body: 'edited by a job' })).body).toBe('edited by a job');
720
+ await system.db.entity('consent').delete(theirs.id);
721
+ expect((await system.db.entity('consent').list()).items).toHaveLength(1);
722
+ });
723
+ });
724
+ describe('notify (D10, D17)', () => {
725
+ useApp(TEST_APP);
726
+ const message = { type: 'test.message', subject: 'Hello', body: 'Body text' };
727
+ it('delivers to the simulated outbox only', async () => {
728
+ const sdk = await env.connect(STAFF);
729
+ const deputyId = DEPUTY.personId;
730
+ const result = await sdk.notify.send({ ...message, to: { person: deputyId }, link: '/x' });
731
+ expect(result.recipients).toEqual([{ personId: deputyId, role: 'staff' }]);
732
+ const outbox = await env.control.outbox();
733
+ expect(outbox).toHaveLength(1);
734
+ expect(outbox[0]).toMatchObject({
735
+ appId: TEST_APP.manifest.id,
736
+ type: 'test.message',
737
+ channel: 'inApp',
738
+ recipientId: deputyId,
739
+ recipientRole: 'staff',
740
+ sentBy: STAFF.personId,
741
+ simulated: true,
742
+ link: '/x',
743
+ });
744
+ });
745
+ it('rejects undeclared notification types', async () => {
746
+ const sdk = await env.connect(STAFF);
747
+ await expectError(sdk.notify.send({ ...message, type: 'test.undeclared', to: { role: 'staff' } }), 'UNDECLARED_TYPE');
748
+ expect(await env.control.outbox()).toEqual([]);
749
+ });
750
+ it('routes to teams with staffOf (D18)', async () => {
751
+ const sdk = await env.connect(STAFF);
752
+ const team = await sdk.school.cohorts.byCode('deputy-principal');
753
+ const expected = ds.cohortMemberships
754
+ .filter((m) => m.cohortId === team.id)
755
+ .map((m) => m.personId)
756
+ .sort();
757
+ const result = await sdk.notify.send({ ...message, to: staffOf(team.id) });
758
+ expect(result.recipients.map((r) => r.personId).sort()).toEqual(expected);
759
+ });
760
+ it('routes to students of a cohort', async () => {
761
+ const sdk = await env.connect(STAFF);
762
+ const cls = await sdk.school.cohorts.byCode('y03-a');
763
+ const expected = ds.cohortMemberships
764
+ .filter((m) => m.cohortId === cls.id && m.memberType === 'student')
765
+ .map((m) => m.personId)
766
+ .sort();
767
+ const result = await sdk.notify.send({ ...message, to: studentsOf(cls.id) });
768
+ expect(result.recipients.map((r) => r.personId).sort()).toEqual(expected);
769
+ });
770
+ it('parentsOf leaves out restricted and non-correspondence parents', async () => {
771
+ const sdk = await env.connect(STAFF);
772
+ const cases = ds.parentStudentLinks.filter((l) => l.contactRestricted || !l.receivesCorrespondence);
773
+ expect(cases.length).toBeGreaterThan(0);
774
+ for (const link of cases.slice(0, 6)) {
775
+ const result = await sdk.notify.send({ ...message, to: parentsOf(link.studentId) });
776
+ const got = result.recipients.map((r) => r.personId).sort();
777
+ expect(got).toEqual(eligibleParents(ds, link.studentId, 'correspondence').sort());
778
+ expect(got).not.toContain(link.parentId);
779
+ }
780
+ });
781
+ it('parentsOf with purpose consent also leaves out parents who cannot consent', async () => {
782
+ const sdk = await env.connect(STAFF);
783
+ const step = ds.parentStudentLinks.find((l) => !l.contactRestricted && l.receivesCorrespondence && !l.canConsent);
784
+ const result = await sdk.notify.send({
785
+ ...message,
786
+ to: parentsOf(step.studentId, { purpose: 'consent' }),
787
+ });
788
+ expect(result.recipients.map((r) => r.personId)).not.toContain(step.parentId);
789
+ expect(result.recipients.length).toBeGreaterThan(0);
790
+ });
791
+ it('needs regarding for parents addressed directly, and checks it', async () => {
792
+ const sdk = await env.connect(STAFF);
793
+ const restricted = ds.parentStudentLinks.find((l) => l.contactRestricted);
794
+ await expectError(sdk.notify.send({ ...message, to: { person: restricted.parentId } }), 'VALIDATION');
795
+ const suppressed = await sdk.notify.send({
796
+ ...message,
797
+ to: { person: restricted.parentId },
798
+ regarding: { studentId: restricted.studentId },
799
+ });
800
+ expect(suppressed.recipients).toEqual([]);
801
+ const parentId = SIBLINGS_PARENT.personId;
802
+ const ok = await sdk.notify.send({
803
+ ...message,
804
+ to: { person: parentId },
805
+ regarding: { studentId: childrenOf(parentId)[0] },
806
+ });
807
+ expect(ok.recipients).toEqual([{ personId: parentId, role: 'parent' }]);
808
+ expect((await env.control.outbox()).map((e) => e.recipientId)).toEqual([parentId]);
809
+ });
810
+ it('applies D17 even when the app has no pastoral scope', async () => {
811
+ // TEST_APP has no parentStudentLinks.pastoral scope, so it can't see contactRestricted;
812
+ // the previous tests already prove suppression happens anyway.
813
+ expect(TEST_APP.manifest.scopes).not.toContain('parentStudentLinks.pastoral:read');
814
+ });
815
+ it('lets students and parents notify staff only', async () => {
816
+ const parent = await env.connect(SIBLINGS_PARENT);
817
+ await expectError(parent.notify.send({ ...message, to: { role: 'student' } }), 'FORBIDDEN');
818
+ const res = await parent.notify.send({ ...message, to: { person: STAFF.personId } });
819
+ expect(res.recipients).toHaveLength(1);
820
+ });
821
+ it('drops repeats with the same idempotency key', async () => {
822
+ const sdk = await env.connect(STAFF);
823
+ const send = () => sdk.notify.send({ ...message, to: { person: DEPUTY.personId }, idempotencyKey: 'n1' });
824
+ await send();
825
+ await send();
826
+ expect(await env.control.outbox()).toHaveLength(1);
827
+ });
828
+ it('validates recipients', async () => {
829
+ const sdk = await env.connect(STAFF);
830
+ await expectError(sdk.notify.send({ ...message, to: { person: 'nobody' } }), 'VALIDATION');
831
+ await expectError(sdk.notify.send({ ...message, to: [] }), 'VALIDATION');
832
+ await expectError(sdk.notify.send({ ...message, to: { role: 'staff' }, subject: '' }), 'VALIDATION');
833
+ });
834
+ });
835
+ describe('notify: roles outside the manifest', () => {
836
+ useApp({
837
+ ...TEST_APP,
838
+ manifest: { ...TEST_APP.manifest, id: 'staff-only', roles: ['staff'] },
839
+ });
840
+ it('never reaches people whose role the app does not serve', async () => {
841
+ const sdk = await env.connect(STAFF);
842
+ const studentId = ds.students[0].id;
843
+ const res = await sdk.notify.send({
844
+ type: 'test.message',
845
+ subject: 'S',
846
+ body: 'B',
847
+ to: parentsOf(studentId),
848
+ });
849
+ expect(res.recipients).toEqual([]);
850
+ await expectError(sdk.notify.send({
851
+ type: 'test.message',
852
+ subject: 'S',
853
+ body: 'B',
854
+ to: { person: studentId },
855
+ }), 'VALIDATION');
856
+ });
857
+ });
858
+ // ---------------- Slice B ----------------
859
+ const HOUR = 3_600_000;
860
+ const DAY = 24 * HOUR;
861
+ const teamMembers = (code) => {
862
+ const cohort = ds.cohorts.find((c) => c.code === code);
863
+ return ds.cohortMemberships
864
+ .filter((m) => m.cohortId === cohort.id)
865
+ .map((m) => m.personId)
866
+ .sort();
867
+ };
868
+ const SYSTEM_JOBS = { kind: 'system', appId: 'contract-jobs' };
869
+ const approval = { type: 'test.approval', title: 'Approve the excursion' };
870
+ describe('tasks (D6)', () => {
871
+ useApp(JOBS_APP);
872
+ it("mode 'each' gives every assignee their own task and inbox entry", async () => {
873
+ const sdk = await env.connect(STAFF);
874
+ const team = await sdk.school.cohorts.byCode('deputy-principal');
875
+ const { tasks } = await sdk.tasks.assign({ ...approval, assignee: staffOf(team.id) });
876
+ const deputies = teamMembers('deputy-principal');
877
+ expect(tasks).toHaveLength(deputies.length);
878
+ expect(new Set(tasks.map((t) => t.groupId)).size).toBe(1);
879
+ expect(tasks.flatMap((t) => t.assignees).sort()).toEqual(deputies);
880
+ for (const id of deputies)
881
+ expect(await env.control.inbox(id)).toHaveLength(1);
882
+ });
883
+ it("mode 'any' gives one shared task that closes when the first assignee completes it", async () => {
884
+ const sdk = await env.connect(STAFF);
885
+ const team = await sdk.school.cohorts.byCode('deputy-principal');
886
+ const { tasks } = await sdk.tasks.assign({
887
+ ...approval,
888
+ assignee: staffOf(team.id),
889
+ mode: 'any',
890
+ });
891
+ expect(tasks).toHaveLength(1);
892
+ const [first, second] = teamMembers('deputy-principal');
893
+ const done = await (await env.connect({ kind: 'user', role: 'staff', personId: first })).tasks.complete(tasks[0].id, {
894
+ outcome: 'approved',
895
+ });
896
+ expect(done).toMatchObject({ status: 'completed', completedBy: first, outcome: 'approved' });
897
+ expect(await env.control.inbox(second)).toEqual([]);
898
+ await expectError((await env.connect({ kind: 'user', role: 'staff', personId: second })).tasks.complete(tasks[0].id), 'VALIDATION');
899
+ });
900
+ it('an approval routed to the deputy-principal team reaches only its members (D18)', async () => {
901
+ const sdk = await env.connect(STAFF);
902
+ const team = await sdk.school.cohorts.byCode('deputy-principal');
903
+ await sdk.tasks.assign({ ...approval, assignee: staffOf(team.id), mode: 'any' });
904
+ const deputies = new Set(teamMembers('deputy-principal'));
905
+ for (const s of ds.staff) {
906
+ expect((await env.control.inbox(s.id)).length, s.positionTitle).toBe(deputies.has(s.id) ? 1 : 0);
907
+ }
908
+ });
909
+ it('permission slips never reach a restricted or non-consenting parent (D17)', async () => {
910
+ const sdk = await env.connect(STAFF);
911
+ const cases = ds.parentStudentLinks.filter((l) => l.contactRestricted || !l.receivesCorrespondence || !l.canConsent);
912
+ expect(cases.length).toBeGreaterThan(10);
913
+ for (const link of cases) {
914
+ const { tasks } = await sdk.tasks.assign({
915
+ type: 'test.consent',
916
+ title: 'Excursion permission',
917
+ assignee: parentsOf(link.studentId, { purpose: 'consent' }),
918
+ idempotencyKey: `slip:${link.studentId}`,
919
+ });
920
+ const assignees = tasks.flatMap((t) => t.assignees);
921
+ expect(assignees).not.toContain(link.parentId);
922
+ expect(assignees.sort()).toEqual(eligibleParents(ds, link.studentId, 'consent').sort());
923
+ expect(await env.control.inbox(link.parentId)).toEqual([]);
924
+ }
925
+ const suppressed = (await env.control.auditLog()).filter((e) => e.action === 'task.suppressed');
926
+ expect(suppressed.length).toBeGreaterThan(0);
927
+ expect(suppressed.every((e) => e.visibility === 'cio')).toBe(true);
928
+ expect(new Set(suppressed.map((e) => e.data.reason))).toEqual(new Set(['restricted', 'no-correspondence', 'cannot-consent']));
929
+ });
930
+ it('needs regarding for parents addressed directly, and checks it', async () => {
931
+ const sdk = await env.connect(STAFF);
932
+ const restricted = ds.parentStudentLinks.find((l) => l.contactRestricted);
933
+ await expectError(sdk.tasks.assign({ ...approval, assignee: { person: restricted.parentId } }), 'VALIDATION');
934
+ const { tasks } = await sdk.tasks.assign({
935
+ ...approval,
936
+ assignee: { person: restricted.parentId },
937
+ regarding: { studentId: restricted.studentId },
938
+ });
939
+ expect(tasks).toEqual([]);
940
+ });
941
+ it('rejects undeclared task types and lets students and parents assign only to staff', async () => {
942
+ const staff = await env.connect(STAFF);
943
+ await expectError(staff.tasks.assign({ ...approval, type: 'test.nope', assignee: { role: 'staff' } }), 'UNDECLARED_TYPE');
944
+ const parent = await env.connect(SIBLINGS_PARENT);
945
+ await expectError(parent.tasks.assign({ ...approval, assignee: { role: 'parent' } }), 'FORBIDDEN');
946
+ const { tasks } = await parent.tasks.assign({
947
+ ...approval,
948
+ assignee: { person: STAFF.personId },
949
+ });
950
+ expect(tasks).toHaveLength(1);
951
+ });
952
+ it('only an assignee can complete a task, never another user or the system principal', async () => {
953
+ const staff = await env.connect(STAFF);
954
+ const child = childrenOf(SIBLINGS_PARENT.personId)[0];
955
+ const { tasks } = await staff.tasks.assign({
956
+ type: 'test.consent',
957
+ title: 'Permission',
958
+ assignee: { person: SIBLINGS_PARENT.personId },
959
+ regarding: { studentId: child },
960
+ });
961
+ const task = tasks[0];
962
+ await expectError(staff.tasks.complete(task.id), 'NOT_ASSIGNEE');
963
+ await expectError((await env.connect(SYSTEM_JOBS)).tasks.complete(task.id), 'NOT_ASSIGNEE');
964
+ await expectError((await env.connect(SEPARATED_PARENT)).tasks.complete(task.id), 'NOT_FOUND');
965
+ const parent = await env.connect(SIBLINGS_PARENT);
966
+ expect((await parent.tasks.list({ assignedToMe: true, status: 'open' })).items.map((t) => t.id)).toEqual([task.id]);
967
+ const done = await parent.tasks.complete(task.id, { outcome: 'given' });
968
+ expect(done).toMatchObject({ status: 'completed', outcome: 'given', assignedToMe: true });
969
+ expect('assignees' in done).toBe(false); // only staff see who else was assigned
970
+ expect(await env.control.inbox(SIBLINGS_PARENT.personId)).toEqual([]);
971
+ expect((await staff.tasks.get(task.id)).status).toBe('completed');
972
+ });
973
+ it('the creator, staff or system can cancel; an assignee parent cannot', async () => {
974
+ const staff = await env.connect(STAFF);
975
+ const child = childrenOf(SIBLINGS_PARENT.personId)[0];
976
+ const make = async () => (await staff.tasks.assign({
977
+ ...approval,
978
+ assignee: { person: SIBLINGS_PARENT.personId },
979
+ regarding: { studentId: child },
980
+ })).tasks[0];
981
+ const a = await make();
982
+ await expectError((await env.connect(SIBLINGS_PARENT)).tasks.cancel(a.id), 'NOT_PERMITTED');
983
+ expect((await staff.tasks.cancel(a.id)).status).toBe('cancelled');
984
+ await expectError(staff.tasks.cancel(a.id), 'VALIDATION');
985
+ const b = await make();
986
+ expect((await (await env.connect(SYSTEM_JOBS)).tasks.cancel(b.id)).status).toBe('cancelled');
987
+ expect(await env.control.inbox(SIBLINGS_PARENT.personId)).toEqual([]);
988
+ });
989
+ it('drops repeated assigns with the same idempotency key, and survives a restart', async () => {
990
+ const sdk = await env.connect(STAFF);
991
+ const first = await sdk.tasks.assign({
992
+ ...approval,
993
+ assignee: { person: DEPUTY.personId },
994
+ idempotencyKey: 'once',
995
+ });
996
+ const again = await sdk.tasks.assign({
997
+ ...approval,
998
+ assignee: { person: DEPUTY.personId },
999
+ idempotencyKey: 'once',
1000
+ });
1001
+ expect(again.tasks.map((t) => t.id)).toEqual(first.tasks.map((t) => t.id));
1002
+ await env.control.restart();
1003
+ expect(await env.control.inbox(DEPUTY.personId)).toHaveLength(1);
1004
+ expect((await (await env.connect(STAFF)).tasks.get(first.tasks[0].id)).title).toBe(approval.title);
1005
+ });
1006
+ it('a task about a student goes only to people who can see that student (D25)', async () => {
1007
+ const staff = await env.connect(STAFF);
1008
+ const cls = await staff.school.cohorts.byCode('y03-a');
1009
+ const classmates = ds.cohortMemberships
1010
+ .filter((m) => m.cohortId === cls.id && m.memberType === 'student')
1011
+ .map((m) => m.personId);
1012
+ const subject = classmates[0];
1013
+ const { tasks } = await staff.tasks.assign({
1014
+ ...approval,
1015
+ assignee: studentsOf(cls.id),
1016
+ regarding: { studentId: subject },
1017
+ });
1018
+ // Classmates can't see the subject student, so only the subject gets it.
1019
+ expect(tasks.flatMap((t) => t.assignees)).toEqual([subject]);
1020
+ for (const other of classmates.slice(1, 4))
1021
+ expect(await env.control.inbox(other)).toEqual([]);
1022
+ const asSubject = await env.connect({ kind: 'user', role: 'student', personId: subject });
1023
+ expect((await asSubject.tasks.list()).items).toHaveLength(1);
1024
+ });
1025
+ it("can't create a task about a student you can't see", async () => {
1026
+ const theirs = ds.students.find((x) => !childrenOf(SIBLINGS_PARENT.personId).includes(x.id)).id;
1027
+ const parent = await env.connect(SIBLINGS_PARENT);
1028
+ await expectError(parent.tasks.assign({
1029
+ ...approval,
1030
+ assignee: { person: STAFF.personId },
1031
+ regarding: { studentId: theirs },
1032
+ }), 'NOT_PERMITTED');
1033
+ const restrictedLink = ds.parentStudentLinks.find((l) => l.parentId === RESTRICTED_PARENT.personId);
1034
+ await expectError((await env.connect(RESTRICTED_PARENT)).tasks.assign({
1035
+ ...approval,
1036
+ assignee: { person: STAFF.personId },
1037
+ regarding: { studentId: restrictedLink.studentId },
1038
+ }), 'NOT_PERMITTED');
1039
+ const { tasks } = await parent.tasks.assign({
1040
+ ...approval,
1041
+ assignee: { person: STAFF.personId },
1042
+ regarding: { studentId: childrenOf(SIBLINGS_PARENT.personId)[0] },
1043
+ });
1044
+ expect((await (await env.connect(STAFF)).tasks.get(tasks[0].id)).regardingStudentId).toBe(childrenOf(SIBLINGS_PARENT.personId)[0]);
1045
+ });
1046
+ });
1047
+ describe('schedule and cron (D7, D8, D20)', () => {
1048
+ useApp(JOBS_APP);
1049
+ const logs = async () => (await (await env.connect(STAFF)).db.entity('jobLog').list({ limit: 200 })).items;
1050
+ it('runs a scheduled job at its time, not before, as the user who scheduled it (D7)', async () => {
1051
+ await env.control.setClock('2026-03-04T00:00:00.000Z');
1052
+ const sdk = await env.connect(STAFF);
1053
+ const s = await sdk.schedule.at({
1054
+ job: 'follow-up',
1055
+ when: '2026-03-04T01:00:00.000Z',
1056
+ payload: { greetingId: 'g1' },
1057
+ });
1058
+ expect(s).toMatchObject({
1059
+ job: 'follow-up',
1060
+ status: 'pending',
1061
+ createdBy: STAFF.personId,
1062
+ runsAs: 'user',
1063
+ });
1064
+ expect(await env.control.runDueJobs()).toEqual([]);
1065
+ await env.control.advanceClock(HOUR);
1066
+ const ran = await env.control.runDueJobs();
1067
+ expect(ran).toEqual([
1068
+ {
1069
+ runId: `sched:${s.id}`,
1070
+ jobName: 'follow-up',
1071
+ scheduledFor: '2026-03-04T01:00:00.000Z',
1072
+ ok: true,
1073
+ },
1074
+ ]);
1075
+ const [log] = await logs();
1076
+ expect(log).toMatchObject({
1077
+ jobName: 'follow-up',
1078
+ principal: 'user',
1079
+ note: '{"greetingId":"g1"}',
1080
+ createdBy: STAFF.personId,
1081
+ });
1082
+ expect((await sdk.schedule.list()).map((x) => x.status)).toEqual(['done']);
1083
+ expect(await env.control.runDueJobs()).toEqual([]);
1084
+ });
1085
+ it("a user-scheduled job can't read or write beyond the scheduling user's access (D7)", async () => {
1086
+ await env.control.setClock('2026-03-04T00:00:00.000Z');
1087
+ const staff = await env.connect(STAFF);
1088
+ const theirs = ds.students.find((x) => !childrenOf(SIBLINGS_PARENT.personId).includes(x.id)).id;
1089
+ const other = await staff.db
1090
+ .entity('greeting')
1091
+ .create({ message: 'other family', studentId: theirs, tone: 'warm' });
1092
+ const parent = await env.connect(SIBLINGS_PARENT);
1093
+ const s = await parent.schedule.at({
1094
+ job: 'probe',
1095
+ when: '2026-03-04T00:00:00Z',
1096
+ payload: { otherGreetingId: other.id },
1097
+ });
1098
+ expect(s.runsAs).toBe('user');
1099
+ const [run] = await env.control.runDueJobs();
1100
+ expect(run?.ok).toBe(true);
1101
+ const [probe] = (await staff.db.entity('probe').list()).items;
1102
+ expect(probe).toMatchObject({
1103
+ principal: `parent:${SIBLINGS_PARENT.personId}`,
1104
+ studentsSeen: childrenOf(SIBLINGS_PARENT.personId).length,
1105
+ otherFamilyVisible: false,
1106
+ staffOnlyWriteAllowed: false,
1107
+ createdBy: SIBLINGS_PARENT.personId,
1108
+ });
1109
+ expect((await staff.db.entity('jobLog').list()).items).toEqual([]);
1110
+ });
1111
+ it("a job scheduled from inside a user's job runs as that user too, never as the system", async () => {
1112
+ await env.control.setClock('2026-03-04T00:00:00.000Z');
1113
+ await (await env.connect(SIBLINGS_PARENT)).schedule.at({ job: 'chain', when: '2026-03-04T00:00:00Z' });
1114
+ expect((await env.control.runDueJobs()).map((r) => r.jobName)).toEqual(['chain']);
1115
+ expect((await env.control.runDueJobs()).map((r) => r.jobName)).toEqual(['probe']);
1116
+ const [probe] = (await (await env.connect(STAFF)).db.entity('probe').list()).items;
1117
+ expect(probe).toMatchObject({
1118
+ principal: `parent:${SIBLINGS_PARENT.personId}`,
1119
+ staffOnlyWriteAllowed: false,
1120
+ });
1121
+ });
1122
+ it('cron jobs, and jobs scheduled from a system job, run as the system principal', async () => {
1123
+ await env.control.setClock('2026-03-04T00:00:00.000Z');
1124
+ const system = await env.connect(SYSTEM_JOBS);
1125
+ const s = await system.schedule.at({ job: 'chain', when: '2026-03-04T00:00:00Z' });
1126
+ expect(s).toMatchObject({ runsAs: 'system', createdBy: 'system:contract-jobs' });
1127
+ await env.control.runDueJobs();
1128
+ await env.control.runDueJobs();
1129
+ const [probe] = (await (await env.connect(STAFF)).db.entity('probe').list()).items;
1130
+ expect(probe).toMatchObject({
1131
+ principal: 'system',
1132
+ studentsSeen: 200,
1133
+ staffOnlyWriteAllowed: true,
1134
+ });
1135
+ });
1136
+ it('any role the app serves can schedule; people see and cancel only their own', async () => {
1137
+ await env.control.setClock('2026-03-04T00:00:00.000Z');
1138
+ const parent = await env.connect(SIBLINGS_PARENT);
1139
+ const student = await env.connect(STUDENT);
1140
+ const staff = await env.connect(STAFF);
1141
+ const p = await parent.schedule.at({ job: 'follow-up', when: '2026-03-05T00:00:00Z' });
1142
+ await student.schedule.at({ job: 'follow-up', when: '2026-03-05T00:00:00Z' });
1143
+ await expectError(staff.schedule.at({ job: 'weekly', when: '2026-03-04T01:00:00Z' }), 'UNDECLARED_TYPE');
1144
+ await expectError(staff.schedule.at({ job: 'follow-up', when: 'tomorrow' }), 'VALIDATION');
1145
+ expect((await parent.schedule.list()).map((x) => x.id)).toEqual([p.id]);
1146
+ expect(await staff.schedule.list()).toEqual([]);
1147
+ await expectError(staff.schedule.cancel(p.id), 'NOT_FOUND');
1148
+ expect((await (await env.connect(SYSTEM_JOBS)).schedule.list()).length).toBe(2);
1149
+ expect((await parent.schedule.cancel(p.id)).status).toBe('cancelled');
1150
+ await env.control.advanceClock(DAY);
1151
+ expect((await env.control.runDueJobs()).length).toBe(1); // only the student's
1152
+ });
1153
+ it('cron follows the school timezone, and missed runs collapse into one catch-up run', async () => {
1154
+ await env.control.setClock('2026-03-04T00:00:00.000Z'); // Wednesday, 11:00 in Sydney
1155
+ await env.control.restart(); // the cron baseline starts at this instant
1156
+ const sdk = await env.connect(STAFF);
1157
+ const [weekly] = await sdk.cron.list();
1158
+ // Monday 9 March 07:00 AEDT (UTC+11) is Sunday 20:00 UTC.
1159
+ expect(weekly).toMatchObject({ name: 'weekly', nextRunAt: '2026-03-08T20:00:00.000Z' });
1160
+ await env.control.advanceClock(21 * DAY); // three Mondays pass
1161
+ const ran = await env.control.runDueJobs();
1162
+ expect(ran).toEqual([
1163
+ {
1164
+ runId: 'cron:weekly:2026-03-22T20:00:00.000Z',
1165
+ jobName: 'weekly',
1166
+ scheduledFor: '2026-03-22T20:00:00.000Z',
1167
+ ok: true,
1168
+ },
1169
+ ]);
1170
+ expect(await env.control.runDueJobs()).toEqual([]);
1171
+ expect((await env.control.outbox()).map((e) => e.recipientId).sort()).toEqual(teamMembers('deputy-principal'));
1172
+ // After DST ends (5 April), Monday 07:00 AEST is 21:00 UTC.
1173
+ expect((await sdk.cron.list())[0].nextRunAt).toBe('2026-03-29T20:00:00.000Z');
1174
+ await env.control.advanceClock(14 * DAY);
1175
+ expect((await env.control.runDueJobs())[0]?.scheduledFor).toBe('2026-04-05T21:00:00.000Z');
1176
+ });
1177
+ it('never overlaps runs of the same job', async () => {
1178
+ await env.control.setClock('2026-03-04T00:00:00.000Z');
1179
+ slowGate.reset();
1180
+ const staff = await env.connect(STAFF);
1181
+ await staff.schedule.at({ job: 'slow', when: '2026-03-04T00:00:00Z', idempotencyKey: 'a' });
1182
+ await staff.schedule.at({ job: 'slow', when: '2026-03-04T00:00:00Z', idempotencyKey: 'b' });
1183
+ const firstBatch = env.control.runDueJobs();
1184
+ await new Promise((r) => setTimeout(r, 20));
1185
+ expect(await env.control.runDueJobs()).toEqual([]); // the second waits while the first runs
1186
+ expect((await env.control.runs()).map((r) => r.status).sort()).toEqual([
1187
+ 'pending',
1188
+ 'running',
1189
+ ]);
1190
+ slowGate.release();
1191
+ expect(await firstBatch).toHaveLength(1);
1192
+ const secondBatch = await env.control.runDueJobs();
1193
+ expect(secondBatch).toHaveLength(1);
1194
+ expect((await logs()).length).toBe(2);
1195
+ });
1196
+ it('retries a failing run, with the same runId, up to three attempts', async () => {
1197
+ await env.control.setClock('2026-03-04T00:00:00.000Z');
1198
+ const s = await (await env.connect(STAFF)).schedule.at({ job: 'flaky', when: '2026-03-04T00:00:00Z' });
1199
+ expect((await env.control.runDueJobs())[0]?.ok).toBe(false);
1200
+ expect((await env.control.runDueJobs())[0]?.ok).toBe(false);
1201
+ expect((await env.control.runDueJobs())[0]).toMatchObject({
1202
+ runId: `sched:${s.id}`,
1203
+ ok: true,
1204
+ });
1205
+ const [run] = await env.control.runs();
1206
+ expect(run).toMatchObject({ status: 'succeeded', attempts: 3 });
1207
+ const outcomes = (await env.control.auditLog())
1208
+ .filter((e) => e.action === 'job.run')
1209
+ .map((e) => e.data.outcome);
1210
+ expect(outcomes).toEqual(['failed', 'failed', 'succeeded']);
1211
+ });
1212
+ it('redelivery reuses the runId, and idempotency keys drop the repeats', async () => {
1213
+ await env.control.setClock('2026-03-04T00:00:00.000Z');
1214
+ await env.control.restart();
1215
+ await env.control.advanceClock(7 * DAY);
1216
+ const [first] = await env.control.runDueJobs();
1217
+ const counts = async () => ({
1218
+ logs: (await logs()).length,
1219
+ outbox: (await env.control.outbox()).length,
1220
+ appAudit: (await env.control.auditLog()).filter((e) => e.source === 'app').length,
1221
+ });
1222
+ const before = await counts();
1223
+ expect(before.logs).toBe(1);
1224
+ await env.control.redeliver(first.runId);
1225
+ const [again] = await env.control.runDueJobs();
1226
+ expect(again).toMatchObject({ runId: first.runId, ok: true });
1227
+ expect(await counts()).toEqual(before);
1228
+ const run = (await env.control.runs()).find((r) => r.id === first.runId);
1229
+ expect(run.deliveries).toBe(2);
1230
+ expect((await env.control.auditLog()).some((e) => e.action === 'job.redelivered')).toBe(true);
1231
+ });
1232
+ });
1233
+ describe('audit (D19)', () => {
1234
+ useApp({
1235
+ ...JOBS_APP,
1236
+ manifest: { ...JOBS_APP.manifest, scopes: [...TEST_APP.manifest.scopes] },
1237
+ });
1238
+ it('stamps actor and time on app entries, and won’t let the app set them', async () => {
1239
+ await env.control.setClock('2026-03-04T03:00:00.000Z');
1240
+ const sdk = await env.connect(STAFF);
1241
+ const entry = await sdk.audit.record({
1242
+ action: 'greeting.approved',
1243
+ summary: 'Approved',
1244
+ entity: 'greeting',
1245
+ recordId: 'g1',
1246
+ });
1247
+ expect(entry).toMatchObject({
1248
+ source: 'app',
1249
+ actor: STAFF.personId,
1250
+ at: '2026-03-04T03:00:00.000Z',
1251
+ appId: 'contract-jobs',
1252
+ action: 'greeting.approved',
1253
+ });
1254
+ for (const forged of [
1255
+ { actor: 'someone-else' },
1256
+ { source: 'platform' },
1257
+ { at: '2020-01-01T00:00:00Z' },
1258
+ ]) {
1259
+ await expectError(sdk.audit.record({ action: 'x.y', summary: 's', ...forged }), 'VALIDATION');
1260
+ }
1261
+ await expectError(sdk.audit.record({ action: 'Not An Action', summary: 's' }), 'VALIDATION');
1262
+ const again = await sdk.audit.record({
1263
+ action: 'x.once',
1264
+ summary: 's',
1265
+ idempotencyKey: 'k',
1266
+ });
1267
+ expect((await sdk.audit.record({ action: 'x.once', summary: 's', idempotencyKey: 'k' })).id).toBe(again.id);
1268
+ });
1269
+ it('records platform entries for tasks, notifications, suppressions, jobs and sensitive reads', async () => {
1270
+ await env.control.setClock('2026-03-04T00:00:00.000Z');
1271
+ const staff = await env.connect(STAFF);
1272
+ const { tasks } = await staff.tasks.assign({
1273
+ ...approval,
1274
+ assignee: { person: DEPUTY.personId },
1275
+ });
1276
+ await (await env.connect(DEPUTY)).tasks.complete(tasks[0].id);
1277
+ const other = await staff.tasks.assign({
1278
+ ...approval,
1279
+ assignee: { person: DEPUTY.personId },
1280
+ });
1281
+ await staff.tasks.cancel(other.tasks[0].id);
1282
+ const restricted = ds.parentStudentLinks.find((l) => l.contactRestricted);
1283
+ await staff.notify.send({
1284
+ type: 'test.message',
1285
+ to: parentsOf(restricted.studentId),
1286
+ subject: 'S',
1287
+ body: 'B',
1288
+ });
1289
+ await staff.schedule.at({ job: 'follow-up', when: '2026-03-04T00:00:00Z' });
1290
+ await env.control.runDueJobs();
1291
+ await staff.school.students.list({ limit: 5 }); // basic: no sensitive-read entry
1292
+ await staff.school.medicalAlerts.list({ limit: 3 });
1293
+ await staff.school.pastoralNotes.get(ds.pastoralNotes[0].id);
1294
+ const log = await env.control.auditLog();
1295
+ const actions = log.map((e) => e.action);
1296
+ for (const a of [
1297
+ 'task.assigned',
1298
+ 'task.completed',
1299
+ 'task.cancelled',
1300
+ 'notification.sent',
1301
+ 'notification.suppressed',
1302
+ 'job.run',
1303
+ ]) {
1304
+ expect(actions, a).toContain(a);
1305
+ }
1306
+ const reads = log.filter((e) => e.action === 'school.sensitive-read');
1307
+ expect(reads.map((e) => [e.entity, e.data.recordCount, e.visibility])).toEqual([
1308
+ ['medicalAlerts', 3, 'cio'],
1309
+ ['pastoralNotes', 1, 'cio'],
1310
+ ]);
1311
+ const suppressed = log.find((e) => e.action === 'notification.suppressed');
1312
+ expect(suppressed).toMatchObject({
1313
+ visibility: 'cio',
1314
+ data: { recipientId: restricted.parentId, reason: 'restricted' },
1315
+ });
1316
+ expect(log.every((e) => e.source === 'platform' || e.source === 'app')).toBe(true);
1317
+ });
1318
+ it('audit.list returns app-recorded entries only, never platform ones', async () => {
1319
+ await env.control.setClock('2026-03-04T00:00:00.000Z');
1320
+ const staff = await env.connect(STAFF);
1321
+ await staff.school.medicalAlerts.list({ limit: 1 });
1322
+ await staff.tasks.assign({ ...approval, assignee: { person: DEPUTY.personId } });
1323
+ await staff.notify.send({
1324
+ type: 'test.message',
1325
+ to: { person: DEPUTY.personId },
1326
+ subject: 'S',
1327
+ body: 'B',
1328
+ });
1329
+ await staff.audit.record({ action: 'staff.note', summary: 'by staff' });
1330
+ const parent = await env.connect(SIBLINGS_PARENT);
1331
+ await parent.audit.record({ action: 'parent.note', summary: 'by parent' });
1332
+ expect((await env.control.auditLog()).some((e) => e.source === 'platform')).toBe(true);
1333
+ const asStaff = (await staff.audit.list({ limit: 200 })).items;
1334
+ expect(asStaff.map((e) => e.action)).toEqual(['staff.note', 'parent.note']);
1335
+ expect(asStaff.every((e) => e.source === 'app' && !('visibility' in e))).toBe(true);
1336
+ expect((await parent.audit.list()).items.map((e) => e.action)).toEqual(['parent.note']);
1337
+ expect((await (await env.connect(SYSTEM_JOBS)).audit.list()).items.every((e) => e.source === 'app')).toBe(true);
1338
+ });
1339
+ it('entries about a student follow that student’s visibility (D25)', async () => {
1340
+ const mine = childrenOf(SIBLINGS_PARENT.personId)[0];
1341
+ const theirs = ds.students.find((x) => !childrenOf(SIBLINGS_PARENT.personId).includes(x.id)).id;
1342
+ const parent = await env.connect(SIBLINGS_PARENT);
1343
+ const entry = await parent.audit.record({
1344
+ action: 'consent.given',
1345
+ summary: 'Given',
1346
+ regarding: { studentId: mine },
1347
+ });
1348
+ expect(entry.regardingStudentId).toBe(mine);
1349
+ await expectError(parent.audit.record({
1350
+ action: 'consent.given',
1351
+ summary: 'x',
1352
+ regarding: { studentId: theirs },
1353
+ }), 'NOT_PERMITTED');
1354
+ const student = await env.connect(STUDENT);
1355
+ await expectError(student.audit.record({ action: 'x.y', summary: 'x', regarding: { studentId: theirs } }), 'NOT_PERMITTED');
1356
+ expect((await student.audit.record({
1357
+ action: 'x.y',
1358
+ summary: 'me',
1359
+ regarding: { studentId: STUDENT.personId },
1360
+ })).actor).toBe(STUDENT.personId);
1361
+ // Staff see entries about students they can see (every student, under this school's policy).
1362
+ expect((await (await env.connect(STAFF)).audit.list()).items.map((e) => e.action)).toEqual(['consent.given', 'x.y']);
1363
+ });
1364
+ it('is append-only: the SDK can only add and list, and entries never change', async () => {
1365
+ const sdk = await env.connect(STAFF);
1366
+ expect(Object.keys(sdk.audit).sort()).toEqual(['list', 'record']);
1367
+ const entry = await sdk.audit.record({ action: 'x.kept', summary: 'kept' });
1368
+ await sdk.audit.record({ action: 'x.later', summary: 'later' });
1369
+ await env.control.restart();
1370
+ const [same] = (await (await env.connect(STAFF)).audit.list({ action: 'x.kept' })).items;
1371
+ expect(same).toEqual(entry);
1372
+ });
1373
+ });
1374
+ describe('clock controls (D14)', () => {
1375
+ useApp(TEST_APP);
1376
+ it('advances a frozen clock', async () => {
1377
+ await env.control.setClock('2026-03-04T00:00:00.000Z');
1378
+ await env.control.advanceClock(DAY);
1379
+ expect((await env.connect(STAFF)).clock.now()).toBe('2026-03-05T00:00:00.000Z');
1380
+ });
1381
+ });
1382
+ describe('clock (D14, D21)', () => {
1383
+ useApp(TEST_APP);
1384
+ it('follows the engine clock', async () => {
1385
+ await env.control.setClock('2026-03-04T14:30:00.000Z');
1386
+ const sdk = await env.connect(STAFF);
1387
+ expect(sdk.clock.now()).toBe('2026-03-04T14:30:00.000Z');
1388
+ });
1389
+ it('gives today in the school timezone, not the browser’s', async () => {
1390
+ // 14:30 UTC on 4 March is 01:30 on 5 March in Sydney (AEDT, UTC+11).
1391
+ await env.control.setClock('2026-03-04T14:30:00.000Z');
1392
+ const sdk = await env.connect(STAFF);
1393
+ expect(sdk.clock.today()).toBe('2026-03-05');
1394
+ await env.control.setClock('2026-06-04T13:59:00.000Z'); // 23:59 AEST
1395
+ expect((await env.connect(STAFF)).clock.today()).toBe('2026-06-04');
1396
+ });
1397
+ it('runs in real time by default', async () => {
1398
+ await env.control.setClock(null);
1399
+ const sdk = await env.connect(STAFF);
1400
+ const drift = Math.abs(Date.parse(sdk.clock.now()) - Date.now());
1401
+ expect(drift).toBeLessThan(5000);
1402
+ });
1403
+ });
1404
+ });
1405
+ }