@quad-education/sdk 0.1.3 → 0.2.0

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 (54) hide show
  1. package/README.md +2 -0
  2. package/dist/contract-tests/apps.d.ts +105 -0
  3. package/dist/contract-tests/apps.js +167 -0
  4. package/dist/contract-tests/harness.d.ts +11 -0
  5. package/dist/contract-tests/harness.js +40 -0
  6. package/dist/contract-tests/helpers.d.ts +5 -0
  7. package/dist/contract-tests/helpers.js +25 -0
  8. package/dist/contract-tests/index.d.ts +4 -2
  9. package/dist/contract-tests/index.js +3 -1
  10. package/dist/contract-tests/standalone-apps.d.ts +183 -0
  11. package/dist/contract-tests/standalone-apps.js +178 -0
  12. package/dist/contract-tests/standalone.d.ts +2 -0
  13. package/dist/contract-tests/standalone.js +709 -0
  14. package/dist/contract-tests/suite.d.ts +10 -3
  15. package/dist/contract-tests/suite.js +536 -44
  16. package/dist/src/client/connect.d.ts +13 -3
  17. package/dist/src/client/connect.js +21 -3
  18. package/dist/src/client/handshake-client.d.ts +2 -0
  19. package/dist/src/client/handshake-client.js +2 -0
  20. package/dist/src/client/http-transport.d.ts +18 -0
  21. package/dist/src/client/http-transport.js +76 -0
  22. package/dist/src/client/live.d.ts +39 -0
  23. package/dist/src/client/live.js +122 -0
  24. package/dist/src/contract/errors.d.ts +1 -1
  25. package/dist/src/contract/principals.d.ts +30 -0
  26. package/dist/src/contract/principals.js +12 -0
  27. package/dist/src/contract/recipients.d.ts +8 -2
  28. package/dist/src/contract/types.d.ts +18 -2
  29. package/dist/src/contract/types.js +1 -1
  30. package/dist/src/engine/audit.d.ts +2 -2
  31. package/dist/src/engine/audit.js +8 -6
  32. package/dist/src/engine/db-indexes.js +6 -1
  33. package/dist/src/engine/engine.d.ts +60 -22
  34. package/dist/src/engine/engine.js +281 -162
  35. package/dist/src/engine/host.d.ts +2 -2
  36. package/dist/src/engine/host.js +1 -1
  37. package/dist/src/engine/in-process.d.ts +2 -2
  38. package/dist/src/engine/index.d.ts +3 -1
  39. package/dist/src/engine/index.js +1 -0
  40. package/dist/src/engine/memory-store.d.ts +32 -0
  41. package/dist/src/engine/memory-store.js +123 -0
  42. package/dist/src/engine/runner.d.ts +2 -2
  43. package/dist/src/engine/runner.js +31 -26
  44. package/dist/src/engine/state.d.ts +21 -15
  45. package/dist/src/engine/state.js +31 -3
  46. package/dist/src/engine/store.d.ts +48 -0
  47. package/dist/src/engine/store.js +1 -0
  48. package/dist/src/engine/tasks.d.ts +4 -6
  49. package/dist/src/engine/tasks.js +27 -24
  50. package/dist/src/index.d.ts +1 -0
  51. package/dist/src/index.js +1 -0
  52. package/dist/src/jobs/define.d.ts +2 -2
  53. package/dist/src/platform-types.d.ts +2 -2
  54. package/package.json +4 -4
@@ -3,8 +3,10 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
3
3
  import { eligibleParents } from '@quad-education/canonical';
4
4
  import { personasFor, withDerived } from '@quad-education/fictional-school';
5
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";
6
+ import { parentsOf, staffOf, studentsOf } from "../src/index.js";
7
+ import { ACCESS_APP, ACCOUNT_APP, AWARDS_APP, BASIC_APP, DATA_APP, DEMOGRAPHICS_APP, HR_APP, JOBS_APP, ROLES_APP, TEST_APP, WELLBEING_APP, slowGate, } from "./apps.js";
8
+ import { expectError, ids, listAll } from "./helpers.js";
9
+ import { defineStandaloneSections } from "./standalone.js";
8
10
  // The fictional school is the oracle: tests compare what the SDK returns with what the
9
11
  // dataset says should be visible. They never read an implementation's storage.
10
12
  const ds = withDerived(stored);
@@ -23,29 +25,9 @@ const RESTRICTED_PARENT = persona('restricted-parent');
23
25
  const childrenOf = (parentId) => ds.parentStudentLinks
24
26
  .filter((l) => l.parentId === parentId && !l.contactRestricted)
25
27
  .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) {
28
+ export function defineContractSuite(name, factory, options = {}) {
29
+ const school = options.school !== false;
30
+ const schoolDescribe = school ? describe : describe.skip;
49
31
  describe(`@quad-education/sdk contract: ${name}`, () => {
50
32
  let env;
51
33
  const useApp = (app) => {
@@ -56,7 +38,190 @@ export function defineContractSuite(name, factory) {
56
38
  await env.dispose();
57
39
  });
58
40
  };
59
- describe('auth', () => {
41
+ describe('accounts and guests (V2c, D100)', () => {
42
+ useApp(ACCOUNT_APP);
43
+ const account = (accountId, ...roles) => ({
44
+ kind: 'account',
45
+ accountId,
46
+ roles,
47
+ });
48
+ const ADA = account('acc-ada', 'Teacher');
49
+ const BEN = account('acc-ben', 'Teacher', 'Student');
50
+ const CAI = account('acc-cai', 'Student');
51
+ const DEE = account('acc-dee', 'Student');
52
+ const GUEST1 = { kind: 'guest', guestId: 'guest-1' };
53
+ const GUEST2 = { kind: 'guest', guestId: 'guest-2' };
54
+ const notes = (sdk) => sdk.db.entity('note');
55
+ it('says who an account and a guest are', async () => {
56
+ expect(await (await env.connect(ADA)).auth.me()).toEqual({
57
+ kind: 'account',
58
+ account: { id: 'acc-ada', displayName: 'Ada Teacher' },
59
+ roles: ['Teacher'],
60
+ });
61
+ expect((await (await env.connect(BEN)).auth.me()).roles).toEqual(['Teacher', 'Student']);
62
+ expect(await (await env.connect(GUEST1)).auth.me()).toEqual({
63
+ kind: 'guest',
64
+ guest: { id: 'guest-1' },
65
+ });
66
+ });
67
+ it('refuses a role the app does not have, and guests when the app does not handle them', async () => {
68
+ const janitor = account('acc-ada', 'Janitor');
69
+ await expectError((await env.connect(janitor)).auth.me(), 'FORBIDDEN');
70
+ await env.control.restart({ manifest: { ...ACCOUNT_APP.manifest, guests: false } });
71
+ await expectError((await env.connect(GUEST1)).auth.me(), 'FORBIDDEN');
72
+ expect((await (await env.connect(ADA)).auth.me()).kind).toBe('account');
73
+ });
74
+ it('applies the rules of every role an account holds, matched ignoring case', async () => {
75
+ const [ada, ben, cai, dee] = await Promise.all([ADA, BEN, CAI, DEE].map((p) => env.connect(p)));
76
+ const fromBen = await notes(ben).create({ body: 'ben' });
77
+ const fromCai = await notes(cai).create({ body: 'cai' });
78
+ expect(fromBen.createdBy).toBe('acct:acc-ben');
79
+ // Teacher can read all; a Student only their own; Ben holds both, so he gets Teacher's `all`.
80
+ expect(ids(await listAll(notes(ada)))).toEqual(ids([fromBen, fromCai]));
81
+ expect(ids(await listAll(notes(ben)))).toEqual(ids([fromBen, fromCai]));
82
+ expect(ids(await listAll(notes(cai)))).toEqual([fromCai.id]);
83
+ expect(await listAll(notes(dee))).toEqual([]);
84
+ await expectError(notes(dee).get(fromCai.id), 'NOT_FOUND');
85
+ await expectError(notes(cai).get(fromBen.id), 'NOT_FOUND');
86
+ // A Student may change and delete only their own.
87
+ await notes(cai).update(fromCai.id, { body: 'cai again' });
88
+ await expectError(notes(cai).update(fromBen.id, { body: 'x' }), 'NOT_FOUND');
89
+ await notes(cai).delete(fromCai.id);
90
+ });
91
+ it('gives a guest only the guest rules, and never another guest’s records', async () => {
92
+ const [ada, guest1, guest2] = await Promise.all([ADA, GUEST1, GUEST2].map((p) => env.connect(p)));
93
+ const mine = await notes(guest1).create({ body: 'hello' });
94
+ expect(mine.createdBy).toBe('guest:guest-1');
95
+ expect(ids(await listAll(notes(guest1)))).toEqual([mine.id]);
96
+ expect(await listAll(notes(guest2))).toEqual([]);
97
+ await expectError(notes(guest2).get(mine.id), 'NOT_FOUND');
98
+ // `guest` has read and create, nothing else.
99
+ await expectError(notes(guest1).update(mine.id, { body: 'x' }), 'NOT_PERMITTED');
100
+ await expectError(notes(guest1).delete(mine.id), 'NOT_PERMITTED');
101
+ // A teacher reads everything, a guest's note included.
102
+ expect(ids(await listAll(notes(ada)))).toEqual([mine.id]);
103
+ });
104
+ it('sorts on createdBy, an implicit index with createdAt, and still refuses an unindexed sort', async () => {
105
+ const ada = await env.connect(ADA);
106
+ await notes(ada).create({ body: 'a' });
107
+ await notes(ada).create({ body: 'b' });
108
+ const sorted = await notes(ada).list({ orderBy: { field: 'createdBy' } });
109
+ expect(sorted.items).toHaveLength(2);
110
+ await expectError(notes(ada).list({ orderBy: { field: 'body' } }), 'VALIDATION');
111
+ });
112
+ it('gives NOT_AVAILABLE for everything under sdk.school, to accounts, guests and school personas alike', async () => {
113
+ const calls = (sdk) => [
114
+ () => sdk.school.info(),
115
+ () => sdk.school.students.list(),
116
+ () => sdk.school.students.get('stu-0001'),
117
+ () => sdk.school.students.parents('stu-0001'),
118
+ () => sdk.school.parents.children('par-0001'),
119
+ () => sdk.school.cohorts.byCode('y07'),
120
+ () => sdk.school.cohorts.members('coh-001'),
121
+ () => sdk.school.calendar.list({ from: '2026-01-01', to: '2026-12-31' }),
122
+ ];
123
+ // The standalone app is previewed by a school persona of the same role name: still no school.
124
+ for (const who of school ? [ADA, CAI, GUEST1, STUDENT] : [ADA, CAI, GUEST1]) {
125
+ const sdk = await env.connect(who);
126
+ for (const call of calls(sdk))
127
+ await expectError(call(), 'NOT_AVAILABLE');
128
+ }
129
+ });
130
+ it('gives NOT_AVAILABLE for relationship recipients, school people and `regarding`', async () => {
131
+ const ada = await env.connect(ADA);
132
+ const send = (to) => ada.notify.send({ type: 'test.message', to, subject: 'S', body: 'B' });
133
+ await expectError(send(parentsOf('stu-0001')), 'NOT_AVAILABLE');
134
+ await expectError(send(staffOf('coh-001')), 'NOT_AVAILABLE');
135
+ await expectError(send(studentsOf('coh-001')), 'NOT_AVAILABLE');
136
+ await expectError(send({ person: 'stu-0001' }), 'NOT_AVAILABLE');
137
+ await expectError(ada.tasks.assign({ type: 'test.review', title: 'T', assignee: parentsOf('stu-0001') }), 'NOT_AVAILABLE');
138
+ await expectError(ada.tasks.assign({
139
+ type: 'test.review',
140
+ title: 'T',
141
+ assignee: { role: 'Student' },
142
+ regarding: { studentId: 'stu-0001' },
143
+ }), 'NOT_AVAILABLE');
144
+ });
145
+ it('notifies accounts by id and by app role, never guests, into the simulated outbox', async () => {
146
+ const ada = await env.connect(ADA);
147
+ await ada.notify.send({
148
+ type: 'test.message',
149
+ to: [{ role: 'Student' }],
150
+ subject: 'Hello',
151
+ body: 'B',
152
+ });
153
+ const outbox = await env.control.outbox();
154
+ expect(outbox.map((e) => e.recipientId).sort()).toEqual([
155
+ 'acct:acc-ben',
156
+ 'acct:acc-cai',
157
+ 'acct:acc-dee',
158
+ ]);
159
+ expect(outbox.every((e) => e.simulated && e.sentBy === 'acct:acc-ada')).toBe(true);
160
+ await env.control.reset();
161
+ await ada.notify.send({
162
+ type: 'test.message',
163
+ to: [{ account: 'acc-cai' }, { role: 'teacher' }],
164
+ subject: 'S',
165
+ body: 'B',
166
+ });
167
+ expect((await env.control.outbox()).map((e) => e.recipientId).sort()).toEqual([
168
+ 'acct:acc-ada',
169
+ 'acct:acc-ben',
170
+ 'acct:acc-cai',
171
+ ]);
172
+ await expectError(ada.notify.send({
173
+ type: 'test.message',
174
+ to: [{ account: 'acc-zed' }],
175
+ subject: 'S',
176
+ body: 'B',
177
+ }), 'VALIDATION');
178
+ await expectError(ada.notify.send({
179
+ type: 'test.message',
180
+ to: [{ role: 'Janitor' }],
181
+ subject: 'S',
182
+ body: 'B',
183
+ }), 'VALIDATION');
184
+ const guest = await env.connect(GUEST1);
185
+ await expectError(guest.notify.send({
186
+ type: 'test.message',
187
+ to: [{ role: 'Teacher' }],
188
+ subject: 'S',
189
+ body: 'B',
190
+ }), 'FORBIDDEN');
191
+ });
192
+ it('assigns tasks to accounts and app roles, completed only by an assignee', async () => {
193
+ const [ada, cai, dee, guest] = await Promise.all([ADA, CAI, DEE, GUEST1].map((p) => env.connect(p)));
194
+ const { tasks } = await ada.tasks.assign({
195
+ type: 'test.review',
196
+ title: 'Review your notes',
197
+ assignee: { role: 'Student' },
198
+ });
199
+ expect(tasks).toHaveLength(3);
200
+ expect((await env.control.inbox('acct:acc-cai')).map((t) => t.type)).toEqual([
201
+ 'test.review',
202
+ ]);
203
+ const mine = (await cai.tasks.list()).items;
204
+ expect(mine).toHaveLength(1);
205
+ expect(mine[0].assignedToMe).toBe(true);
206
+ // Dee isn't involved in Cai's task, so it isn't there for her at all.
207
+ const caisTask = tasks.find((t) => t.id === mine[0].id);
208
+ await expectError(dee.tasks.complete(caisTask.id), 'NOT_FOUND');
209
+ expect((await cai.tasks.complete(caisTask.id)).status).toBe('completed');
210
+ await expectError(guest.tasks.assign({ type: 'test.review', title: 'T', assignee: { account: 'acc-cai' } }), 'FORBIDDEN');
211
+ });
212
+ it('runs a job an account scheduled as that account, and lets no guest schedule one', async () => {
213
+ const ada = await env.connect(ADA);
214
+ await ada.schedule.at({ job: 'remind', when: '2026-03-04T00:00:00Z' });
215
+ const runs = await env.control.runDueJobs();
216
+ expect(runs.map((r) => [r.jobName, r.ok])).toEqual([['remind', true]]);
217
+ const [made] = (await listAll(notes(ada))).filter((n) => n.body.includes('"kind"'));
218
+ expect(JSON.parse(made.body)).toMatchObject({ kind: 'account', account: { id: 'acc-ada' } });
219
+ const guest = await env.connect(GUEST1);
220
+ await expectError(guest.schedule.at({ job: 'remind', when: '2026-03-05T00:00:00Z' }), 'FORBIDDEN');
221
+ });
222
+ });
223
+ defineStandaloneSections(() => env, useApp);
224
+ schoolDescribe('auth', () => {
60
225
  useApp(TEST_APP);
61
226
  it('returns the connected user', async () => {
62
227
  const sdk = await env.connect(STAFF);
@@ -73,14 +238,14 @@ export function defineContractSuite(name, factory) {
73
238
  },
74
239
  });
75
240
  expect(sdk.appId).toBe(TEST_APP.manifest.id);
76
- expect(sdk.version).toBe('0.1.3');
241
+ expect(sdk.version).toBe('0.2.0');
77
242
  });
78
243
  it('knows parents and students', async () => {
79
244
  expect((await (await env.connect(STUDENT)).auth.me()).role).toBe('student');
80
245
  expect((await (await env.connect(SIBLINGS_PARENT)).auth.me()).role).toBe('parent');
81
246
  });
82
247
  });
83
- describe('school: visibility (D4)', () => {
248
+ schoolDescribe('school: visibility (D4)', () => {
84
249
  useApp(TEST_APP);
85
250
  it('staff see every student', async () => {
86
251
  const sdk = await env.connect(STAFF);
@@ -131,7 +296,7 @@ export function defineContractSuite(name, factory) {
131
296
  expect(await listAll((await env.connect(SIBLINGS_PARENT)).school.pastoralNotes)).toEqual([]);
132
297
  });
133
298
  });
134
- describe('school: scopes and tiers (D5, D23)', () => {
299
+ schoolDescribe('school: scopes and tiers (D5, D23)', () => {
135
300
  describe('with only students.basic:read', () => {
136
301
  useApp(BASIC_APP);
137
302
  it('returns basic fields and leaves other tiers absent', async () => {
@@ -149,6 +314,7 @@ export function defineContractSuite(name, factory) {
149
314
  await expectError(sdk.school.parents.list(), 'SCOPE_NOT_GRANTED');
150
315
  await expectError(sdk.school.medicalAlerts.get(ds.medicalAlerts[0].id), 'SCOPE_NOT_GRANTED');
151
316
  await expectError(sdk.school.calendar.list({ from: '2026-01-01', to: '2027-01-01' }), 'SCOPE_NOT_GRANTED');
317
+ await expectError(sdk.school.sessionAttendance.list({ where: { date: '2026-03-03' } }), 'SCOPE_NOT_GRANTED');
152
318
  });
153
319
  it('still answers school.info', async () => {
154
320
  const info = await (await env.connect(STUDENT)).school.info();
@@ -188,7 +354,7 @@ export function defineContractSuite(name, factory) {
188
354
  });
189
355
  });
190
356
  });
191
- describe('app-defined roles are previewed by the persona of the same name (D84)', () => {
357
+ schoolDescribe('app-defined roles are previewed by the persona of the same name (D84)', () => {
192
358
  useApp(ROLES_APP);
193
359
  it('serves the personas whose role matches an app role, ignoring case, and refuses the rest', async () => {
194
360
  const staff = await env.connect(STAFF);
@@ -210,7 +376,7 @@ export function defineContractSuite(name, factory) {
210
376
  await expectError(student.db.entity('entry').delete(note.id), 'NOT_PERMITTED');
211
377
  });
212
378
  });
213
- describe('school: declared fields (D85)', () => {
379
+ schoolDescribe('school: declared fields (D85)', () => {
214
380
  useApp(DATA_APP);
215
381
  it('returns the core fields and the declared ones, and nothing else that varies', async () => {
216
382
  const sdk = await env.connect(STAFF);
@@ -252,7 +418,7 @@ export function defineContractSuite(name, factory) {
252
418
  expect('dateOfBirth' in included).toBe(true);
253
419
  });
254
420
  });
255
- describe('school: no declaration (version 0) still gives every field of the granted tiers', () => {
421
+ schoolDescribe('school: no declaration (version 0) still gives every field of the granted tiers', () => {
256
422
  useApp(BASIC_APP);
257
423
  it('keeps yearLevel and preferredName available', async () => {
258
424
  const student = (await (await env.connect(STAFF)).school.students.list({ limit: 1 }))
@@ -260,7 +426,7 @@ export function defineContractSuite(name, factory) {
260
426
  expect('yearLevel' in student).toBe(true);
261
427
  });
262
428
  });
263
- describe('school: queries and helpers', () => {
429
+ schoolDescribe('school: queries and helpers', () => {
264
430
  useApp(TEST_APP);
265
431
  it('filters with where, orders and pages without gaps or repeats', async () => {
266
432
  const sdk = await env.connect(STAFF);
@@ -331,7 +497,7 @@ export function defineContractSuite(name, factory) {
331
497
  expect(page.items.map((l) => l.id)).toEqual(expected);
332
498
  expect(page.items[0]).toMatchObject({ cohortId: english.id });
333
499
  }
334
- });
500
+ }, 30_000);
335
501
  it('pages through a day of lessons without gaps or repeats, and finds one by id', async () => {
336
502
  const sdk = await env.connect(STUDENT);
337
503
  const day = '2026-03-03';
@@ -352,7 +518,7 @@ export function defineContractSuite(name, factory) {
352
518
  const one = await sdk.school.lessons.get(expected[0]);
353
519
  expect(one.id).toBe(expected[0]);
354
520
  await expectError(sdk.school.lessons.get('les-20260303-nope-p1'), 'NOT_FOUND');
355
- });
521
+ }, 30_000);
356
522
  it('lists the school day’s periods and rooms', async () => {
357
523
  const sdk = await env.connect(STUDENT);
358
524
  const periods = await listAll(sdk.school.periods, {});
@@ -360,6 +526,332 @@ export function defineContractSuite(name, factory) {
360
526
  const rooms = await listAll(sdk.school.rooms, {});
361
527
  expect(ids(rooms)).toEqual(ids(ds.rooms));
362
528
  });
529
+ it('serves the register for the slice asked for, and says what to add otherwise (S4.2)', async () => {
530
+ const staff = await env.connect(STAFF);
531
+ const student = ds.students[10];
532
+ const week = { gte: '2026-03-02', lte: '2026-03-06' };
533
+ const page = await staff.school.sessionAttendance.list({
534
+ where: { studentId: student.id, date: week },
535
+ orderBy: { field: 'date' },
536
+ limit: 50,
537
+ });
538
+ expect(page.items).toHaveLength(10);
539
+ expect(page.items.every((m) => m.studentId === student.id && m.date >= week.gte && m.date <= week.lte)).toBe(true);
540
+ expect(page.items.map((m) => m.date)).toEqual([...page.items.map((m) => m.date)].sort());
541
+ expect(page.items[0]).toMatchObject({
542
+ source: 'simulated',
543
+ session: expect.stringMatching(/^(am|pm)$/),
544
+ code: expect.any(String),
545
+ });
546
+ const noFilter = await expectError(staff.school.sessionAttendance.list({ where: { code: 'late' } }), 'VALIDATION');
547
+ expect(noFilter.message).toMatch(/studentId/);
548
+ await expectError(staff.school.sessionAttendance.list(), 'VALIDATION');
549
+ const wide = await expectError(staff.school.sessionAttendance.list({
550
+ where: { date: { gte: '2026-02-02', lte: '2026-06-30' } },
551
+ }), 'VALIDATION');
552
+ expect(wide.message).toMatch(/narrow by/);
553
+ // A school day is fine, and other filters narrow it further.
554
+ const day = await listAll(staff.school.sessionAttendance, { where: { date: '2026-03-03' } });
555
+ expect(day).toHaveLength(ds.students.length * 2);
556
+ const late = await listAll(staff.school.sessionAttendance, {
557
+ where: { date: '2026-03-03', code: 'late' },
558
+ });
559
+ expect(late.length).toBeGreaterThan(0);
560
+ expect(late.every((m) => m.code === 'late' && typeof m.minutesLate === 'number')).toBe(true);
561
+ }, 30_000);
562
+ it('pages through a register without gaps or repeats, and finds one mark by id', async () => {
563
+ const staff = await env.connect(STAFF);
564
+ const where = {
565
+ studentId: ds.students[20].id,
566
+ date: { gte: '2026-02-02', lte: '2026-04-02' },
567
+ };
568
+ const seen = [];
569
+ let page = await staff.school.sessionAttendance.list({ where, limit: 37 });
570
+ seen.push(...page.items);
571
+ while (page.nextCursor) {
572
+ page = await staff.school.sessionAttendance.list({
573
+ where,
574
+ limit: 37,
575
+ cursor: page.nextCursor,
576
+ });
577
+ seen.push(...page.items);
578
+ }
579
+ expect(new Set(seen.map((m) => m.id)).size).toBe(seen.length);
580
+ expect(seen.length).toBeGreaterThan(80);
581
+ const one = await staff.school.sessionAttendance.get(seen[5].id);
582
+ expect(one).toEqual(seen[5]);
583
+ await expectError(staff.school.sessionAttendance.get('att-stu-nope-20260302-am'), 'NOT_FOUND');
584
+ });
585
+ it('shows a student or parent only their own children, however they ask (D4, D17)', async () => {
586
+ const day = { where: { date: '2026-03-04' } };
587
+ const student = await listAll((await env.connect(STUDENT)).school.sessionAttendance, day);
588
+ expect(new Set(student.map((m) => m.studentId))).toEqual(new Set([STUDENT.personId]));
589
+ expect(student).toHaveLength(2);
590
+ const other = ds.students.find((s) => s.id !== STUDENT.personId);
591
+ const asked = await listAll((await env.connect(STUDENT)).school.sessionAttendance, {
592
+ where: { studentId: other.id, date: '2026-03-04' },
593
+ });
594
+ expect(asked).toEqual([]);
595
+ await expectError((await env.connect(STUDENT)).school.sessionAttendance.get(`att-${other.id}-20260304-am`), 'NOT_FOUND');
596
+ const kids = childrenOf(SIBLINGS_PARENT.personId);
597
+ const parent = await listAll((await env.connect(SIBLINGS_PARENT)).school.sessionAttendance, day);
598
+ expect(new Set(parent.map((m) => m.studentId))).toEqual(new Set(kids));
599
+ expect(await listAll((await env.connect(RESTRICTED_PARENT)).school.sessionAttendance, day)).toEqual([]);
600
+ });
601
+ it('needs the academic scope for marks and the pastoral scope for comments, which are audited', async () => {
602
+ const staff = await env.connect(STAFF);
603
+ const withComments = await listAll(staff.school.sessionAttendance, {
604
+ where: { studentId: ds.students[3].id },
605
+ });
606
+ expect(withComments.some((m) => typeof m.comment === 'string')).toBe(true);
607
+ const log = await env.control.auditLog();
608
+ const reads = log.filter((e) => e.action === 'school.sensitive-read' && e.entity === 'sessionAttendance');
609
+ expect(reads.length).toBeGreaterThan(0);
610
+ expect(reads[0].data.tiers).toEqual(['pastoral']);
611
+ });
612
+ it('serves absences and term summaries, each student’s own', async () => {
613
+ const staff = await env.connect(STAFF);
614
+ const mine = await listAll((await env.connect(STUDENT)).school.attendanceSummaries);
615
+ expect(mine).toHaveLength(4);
616
+ expect(mine.every((s) => s.studentId === STUDENT.personId)).toBe(true);
617
+ expect(mine[0]).toMatchObject({
618
+ possibleMarks: expect.any(Number),
619
+ presentMarks: expect.any(Number),
620
+ });
621
+ const all = await listAll(staff.school.attendanceSummaries, {
622
+ where: { termName: 'Term 1' },
623
+ });
624
+ expect(all).toHaveLength(ds.students.length);
625
+ const absences = await listAll(staff.school.studentAbsences, {
626
+ where: { studentId: ds.students[0].id },
627
+ });
628
+ expect(absences.length).toBeGreaterThan(0);
629
+ // The reason is pastoral, and this app was not granted that tier.
630
+ expect(absences.every((a) => a.endAt > a.startAt && !('reason' in a) && !('comment' in a))).toBe(true);
631
+ const own = await listAll((await env.connect(SIBLINGS_PARENT)).school.studentAbsences);
632
+ expect(new Set(own.map((a) => a.studentId))).toEqual(new Set(childrenOf(SIBLINGS_PARENT.personId)));
633
+ }, 30_000);
634
+ it('serves behaviour incidents and achievements, each student’s own (S4.3)', async () => {
635
+ const staff = await env.connect(STAFF);
636
+ const mine = ds.behaviours.find((b) => b.studentId !== STUDENT.personId);
637
+ const incidents = await listAll(staff.school.behaviours, {
638
+ where: { studentId: mine.studentId },
639
+ });
640
+ expect(incidents.length).toBeGreaterThan(0);
641
+ expect(incidents.every((b) => b.studentId === mine.studentId && b.points < 0)).toBe(true);
642
+ expect(incidents[0]).toMatchObject({
643
+ incident: expect.any(String),
644
+ date: expect.any(String),
645
+ });
646
+ const own = await listAll((await env.connect(STUDENT)).school.behaviours);
647
+ expect(own.every((b) => b.studentId === STUDENT.personId)).toBe(true);
648
+ expect(own).toHaveLength(ds.behaviours.filter((b) => b.studentId === STUDENT.personId).length);
649
+ const kids = new Set(childrenOf(SIBLINGS_PARENT.personId));
650
+ const family = await listAll((await env.connect(SIBLINGS_PARENT)).school.behaviours);
651
+ expect(family.every((b) => kids.has(b.studentId))).toBe(true);
652
+ expect(family).toHaveLength(ds.behaviours.filter((b) => kids.has(b.studentId)).length);
653
+ expect(await listAll((await env.connect(RESTRICTED_PARENT)).school.behaviours)).toEqual([]);
654
+ await expectError((await env.connect(STUDENT)).school.behaviours.get(mine.id), 'NOT_FOUND');
655
+ const awards = await listAll((await env.connect(STUDENT)).school.achievements);
656
+ expect(awards).toHaveLength(ds.achievements.filter((a) => a.studentId === STUDENT.personId).length);
657
+ expect(awards.every((a) => a.points > 0 && typeof a.type === 'string')).toBe(true);
658
+ const all = await listAll(staff.school.achievements, { where: { type: 'Sport' } });
659
+ expect(all).toHaveLength(ds.achievements.filter((a) => a.type === 'Sport').length);
660
+ }, 30_000);
661
+ it('audits behaviour reads, which are pastoral, but not achievements, which are academic (S4.3, D19)', async () => {
662
+ const staff = await env.connect(STAFF);
663
+ await staff.school.behaviours.list({ limit: 4 });
664
+ await staff.school.achievements.list({ limit: 4 });
665
+ const reads = (await env.control.auditLog()).filter((e) => e.action === 'school.sensitive-read' &&
666
+ ['behaviours', 'achievements'].includes(String(e.entity)));
667
+ expect(reads.map((e) => [e.entity, e.data.tiers])).toEqual([['behaviours', ['pastoral']]]);
668
+ });
669
+ describe('an awards app with no pastoral scope', () => {
670
+ useApp(AWARDS_APP);
671
+ it('reads achievements but not behaviour, and leaves no pastoral audit entry', async () => {
672
+ const sdk = await env.connect(STAFF);
673
+ const { items } = await sdk.school.achievements.list({ limit: 5 });
674
+ expect(items).toHaveLength(5);
675
+ await expectError(sdk.school.behaviours.list(), 'SCOPE_NOT_GRANTED');
676
+ const reads = (await env.control.auditLog()).filter((e) => e.action === 'school.sensitive-read');
677
+ expect(reads).toEqual([]);
678
+ });
679
+ });
680
+ it('leaves the diagnosis out of learning support when only the pastoral tier is granted (S4.4)', async () => {
681
+ const staff = await env.connect(STAFF);
682
+ const withNeed = ds.learningSupportNeeds[0];
683
+ const items = await listAll(staff.school.learningSupportNeeds, {
684
+ where: { studentId: withNeed.studentId },
685
+ });
686
+ expect(items.length).toBeGreaterThan(0);
687
+ expect(items[0]).toMatchObject({ category: expect.any(String), level: expect.any(String) });
688
+ expect(items.every((n) => !('need' in n))).toBe(true);
689
+ const reads = (await env.control.auditLog()).filter((e) => e.action === 'school.sensitive-read' && e.entity === 'learningSupportNeeds');
690
+ expect(reads.map((e) => e.data.tiers)).toEqual([['pastoral']]);
691
+ await expectError(staff.school.medicalEvents.list(), 'SCOPE_NOT_GRANTED');
692
+ await expectError(staff.school.medicalNotes.list(), 'SCOPE_NOT_GRANTED');
693
+ });
694
+ describe('a wellbeing app with the medical tier', () => {
695
+ useApp(WELLBEING_APP);
696
+ it('receives the diagnosis, and the audit records both tiers (S4.4)', async () => {
697
+ const staff = await env.connect(STAFF);
698
+ const withNeed = ds.learningSupportNeeds[0];
699
+ const items = await listAll(staff.school.learningSupportNeeds, {
700
+ where: { studentId: withNeed.studentId },
701
+ });
702
+ expect(items.some((n) => n.need === withNeed.need && n.category === withNeed.category)).toBe(true);
703
+ const reads = (await env.control.auditLog()).filter((e) => e.action === 'school.sensitive-read' && e.entity === 'learningSupportNeeds');
704
+ expect([...reads[0].data.tiers].sort()).toEqual(['medical', 'pastoral']);
705
+ });
706
+ it('serves medical events and the notes that link to them, each student’s own', async () => {
707
+ const staff = await env.connect(STAFF);
708
+ const event = ds.medicalEvents.find((e) => e.followUpDate);
709
+ const events = await listAll(staff.school.medicalEvents, {
710
+ where: { studentId: event.studentId },
711
+ });
712
+ expect(events.find((e) => e.id === event.id)).toMatchObject({
713
+ type: event.type,
714
+ followUpDate: event.followUpDate,
715
+ });
716
+ const notes = await listAll(staff.school.medicalNotes, {
717
+ where: { studentId: event.studentId },
718
+ });
719
+ expect(notes.some((n) => n.eventId === event.id)).toBe(true);
720
+ expect(notes.every((n) => (n.conditionId === undefined) !== (n.eventId === undefined))).toBe(true);
721
+ const student = await env.connect(STUDENT);
722
+ for (const [entity, all] of [
723
+ ['learningSupportNeeds', ds.learningSupportNeeds],
724
+ ['medicalEvents', ds.medicalEvents],
725
+ ['medicalNotes', ds.medicalNotes],
726
+ ]) {
727
+ const own = await listAll(student.school[entity]);
728
+ expect(own, entity).toHaveLength(all.filter((r) => r.studentId === STUDENT.personId).length);
729
+ expect(own.every((r) => r.studentId === STUDENT.personId)).toBe(true);
730
+ const kids = new Set(childrenOf(SIBLINGS_PARENT.personId));
731
+ const family = await listAll((await env.connect(SIBLINGS_PARENT)).school[entity]);
732
+ expect(family, entity).toHaveLength(all.filter((r) => kids.has(r.studentId)).length);
733
+ expect(await listAll((await env.connect(RESTRICTED_PARENT)).school[entity])).toEqual([]);
734
+ }
735
+ await expectError(student.school.medicalEvents.get(ds.medicalEvents.find((e) => e.studentId !== STUDENT.personId).id), 'NOT_FOUND');
736
+ });
737
+ });
738
+ describe('demographics: the sensitive tier is staff-only (S4.5, D88)', () => {
739
+ useApp(DEMOGRAPHICS_APP);
740
+ const SENSITIVE = [
741
+ 'firstLanguage',
742
+ 'englishAsAdditionalLanguage',
743
+ 'ethnicity',
744
+ 'nationality',
745
+ 'religion',
746
+ 'birthPlace',
747
+ 'freeSchoolMeals',
748
+ ];
749
+ const leaks = (value) => JSON.stringify(value) !== undefined &&
750
+ SENSITIVE.filter((k) => JSON.stringify(value).includes(`"${k}"`));
751
+ it('gives staff the fields the app asked for, lets them filter on one, and audits the read', async () => {
752
+ const staff = await env.connect(STAFF);
753
+ const some = ds.students.find((s) => s.religion && s.firstLanguage);
754
+ const one = await staff.school.students.get(some.id);
755
+ expect(one).toMatchObject({ religion: some.religion, firstLanguage: some.firstLanguage });
756
+ const catholic = await listAll(staff.school.students, { where: { religion: 'Catholic' } });
757
+ expect(catholic).toHaveLength(ds.students.filter((s) => s.religion === 'Catholic').length);
758
+ expect(catholic.length).toBeGreaterThan(20);
759
+ const eal = await listAll(staff.school.students, {
760
+ where: { englishAsAdditionalLanguage: true },
761
+ });
762
+ expect(eal.every((s) => s.englishAsAdditionalLanguage === true)).toBe(true);
763
+ const reads = (await env.control.auditLog()).filter((e) => e.action === 'school.sensitive-read' && e.entity === 'students');
764
+ expect(reads.length).toBeGreaterThan(0);
765
+ expect(reads.every((e) => e.data.tiers.includes('sensitive'))).toBe(true);
766
+ });
767
+ it('never gives a student or a parent the fields, and refuses a filter that would probe them', async () => {
768
+ for (const who of [STUDENT, SIBLINGS_PARENT, SEPARATED_PARENT]) {
769
+ const sdk = await env.connect(who);
770
+ const mine = await listAll(sdk.school.students);
771
+ expect(mine.length).toBeGreaterThan(0);
772
+ expect(leaks(mine), who.personId).toEqual([]);
773
+ expect(leaks(await sdk.school.students.get(mine[0].id))).toEqual([]);
774
+ await expectError(sdk.school.students.list({ where: { religion: 'Catholic' } }), 'VALIDATION');
775
+ await expectError(sdk.school.students.list({ orderBy: { field: 'ethnicity' } }), 'VALIDATION');
776
+ }
777
+ });
778
+ it('does not leak them through the helpers that return students or parents', async () => {
779
+ const kids = childrenOf(SIBLINGS_PARENT.personId);
780
+ const parent = await env.connect(SIBLINGS_PARENT);
781
+ expect(leaks(await parent.school.parents.children(SIBLINGS_PARENT.personId))).toEqual([]);
782
+ expect(leaks(await parent.school.students.parents(kids[0]))).toEqual([]);
783
+ const student = await env.connect(STUDENT);
784
+ expect(leaks(await student.school.students.parents(STUDENT.personId))).toEqual([]);
785
+ expect(leaks(await student.auth.me())).toEqual([]);
786
+ const staff = await env.connect(STAFF);
787
+ // Staff with the scope get them for a parent's children too: the tier is for staff.
788
+ const children = await staff.school.parents.children(SIBLINGS_PARENT.personId);
789
+ expect(children.some((c) => SENSITIVE.some((k) => k in c))).toBe(true);
790
+ });
791
+ });
792
+ it('never gives the fields to an app that was not granted the tier', async () => {
793
+ const staff = await env.connect(STAFF);
794
+ const students = await listAll(staff.school.students, { where: { yearLevel: 'Y9' } });
795
+ expect(students.length).toBeGreaterThan(0);
796
+ expect(JSON.stringify(students)).not.toMatch(/"(religion|ethnicity|nationality|firstLanguage|birthPlace)"/);
797
+ await expectError(staff.school.students.list({ where: { religion: 'Catholic' } }), 'VALIDATION');
798
+ });
799
+ describe('staff absences are in the hr tier (S4.6)', () => {
800
+ useApp(HR_APP);
801
+ it('are read by any staff member whose app holds the tier, and audited as hr', async () => {
802
+ for (const who of [STAFF, DEPUTY]) {
803
+ const sdk = await env.connect(who);
804
+ const all = await listAll(sdk.school.employeeAbsences);
805
+ expect(all).toHaveLength(ds.employeeAbsences.length);
806
+ expect(all[0]).toMatchObject({
807
+ staffId: expect.any(String),
808
+ absenceType: expect.any(String),
809
+ workingDays: expect.any(Number),
810
+ });
811
+ }
812
+ const sdk = await env.connect(STAFF);
813
+ const sick = await listAll(sdk.school.employeeAbsences, {
814
+ where: { absenceType: 'Sick leave' },
815
+ });
816
+ expect(sick).toHaveLength(ds.employeeAbsences.filter((a) => a.absenceType === 'Sick leave').length);
817
+ expect(sick.every((a) => typeof a.illnessCategory === 'string')).toBe(true);
818
+ const reads = (await env.control.auditLog()).filter((e) => e.action === 'school.sensitive-read' && e.entity === 'employeeAbsences');
819
+ expect(reads.length).toBeGreaterThan(0);
820
+ expect(reads.every((e) => e.data.tiers.includes('hr'))).toBe(true);
821
+ });
822
+ it('are never given to a student or a parent, however they ask', async () => {
823
+ const one = ds.employeeAbsences[0];
824
+ for (const who of [STUDENT, SIBLINGS_PARENT, SEPARATED_PARENT, RESTRICTED_PARENT]) {
825
+ const sdk = await env.connect(who);
826
+ expect(await listAll(sdk.school.employeeAbsences)).toEqual([]);
827
+ await expectError(sdk.school.employeeAbsences.get(one.id), 'NOT_FOUND');
828
+ await expectError(sdk.school.employeeAbsences.list({ where: { absenceType: 'Sick leave' } }), 'VALIDATION');
829
+ }
830
+ });
831
+ });
832
+ it('refuses staff absences to an app that was not granted the tier', async () => {
833
+ const staff = await env.connect(STAFF);
834
+ await expectError(staff.school.employeeAbsences.list(), 'SCOPE_NOT_GRANTED');
835
+ });
836
+ it('serves admissions applicants to staff only, in the contact tier (S4.6)', async () => {
837
+ const staff = await env.connect(STAFF);
838
+ const all = await listAll(staff.school.applicants);
839
+ expect(all).toHaveLength(ds.applicants.length);
840
+ expect(all[0]).toMatchObject({
841
+ givenName: expect.any(String),
842
+ email: expect.any(String),
843
+ status: expect.any(String),
844
+ });
845
+ const offered = await listAll(staff.school.applicants, { where: { status: 'offered' } });
846
+ expect(offered).toHaveLength(ds.applicants.filter((a) => a.status === 'offered').length);
847
+ const sibling = ds.applicants.find((a) => a.siblingId);
848
+ expect((await staff.school.applicants.get(sibling.id)).siblingId).toBe(sibling.siblingId);
849
+ for (const who of [STUDENT, SIBLINGS_PARENT, RESTRICTED_PARENT]) {
850
+ const sdk = await env.connect(who);
851
+ expect(await listAll(sdk.school.applicants)).toEqual([]);
852
+ await expectError(sdk.school.applicants.get(sibling.id), 'NOT_FOUND');
853
+ }
854
+ });
363
855
  it('lists calendar events in a date range', async () => {
364
856
  const sdk = await env.connect(STAFF);
365
857
  const from = '2026-03-01T00:00:00Z';
@@ -373,7 +865,7 @@ export function defineContractSuite(name, factory) {
373
865
  expect(forY7.some((e) => e.title === 'Year 7 camp')).toBe(true);
374
866
  });
375
867
  });
376
- describe('db', () => {
868
+ schoolDescribe('db', () => {
377
869
  useApp(TEST_APP);
378
870
  const studentId = ds.students[0].id;
379
871
  it('creates, reads, updates and deletes records with system fields', async () => {
@@ -557,7 +1049,7 @@ export function defineContractSuite(name, factory) {
557
1049
  expect((await (await env.connect(STAFF)).db.entity('greeting').list()).items).toEqual([]);
558
1050
  });
559
1051
  });
560
- describe('db access control (D25)', () => {
1052
+ schoolDescribe('db access control (D25)', () => {
561
1053
  useApp(ACCESS_APP);
562
1054
  const myChild = () => childrenOf(SIBLINGS_PARENT.personId)[0];
563
1055
  const otherChild = () => ds.students.find((s) => !childrenOf(SIBLINGS_PARENT.personId).includes(s.id) &&
@@ -721,7 +1213,7 @@ export function defineContractSuite(name, factory) {
721
1213
  expect((await system.db.entity('consent').list()).items).toHaveLength(1);
722
1214
  });
723
1215
  });
724
- describe('notify (D10, D17)', () => {
1216
+ schoolDescribe('notify (D10, D17)', () => {
725
1217
  useApp(TEST_APP);
726
1218
  const message = { type: 'test.message', subject: 'Hello', body: 'Body text' };
727
1219
  it('delivers to the simulated outbox only', async () => {
@@ -832,7 +1324,7 @@ export function defineContractSuite(name, factory) {
832
1324
  await expectError(sdk.notify.send({ ...message, to: { role: 'staff' }, subject: '' }), 'VALIDATION');
833
1325
  });
834
1326
  });
835
- describe('notify: roles outside the manifest', () => {
1327
+ schoolDescribe('notify: roles outside the manifest', () => {
836
1328
  useApp({
837
1329
  ...TEST_APP,
838
1330
  manifest: { ...TEST_APP.manifest, id: 'staff-only', roles: ['staff'] },
@@ -867,7 +1359,7 @@ export function defineContractSuite(name, factory) {
867
1359
  };
868
1360
  const SYSTEM_JOBS = { kind: 'system', appId: 'contract-jobs' };
869
1361
  const approval = { type: 'test.approval', title: 'Approve the excursion' };
870
- describe('tasks (D6)', () => {
1362
+ schoolDescribe('tasks (D6)', () => {
871
1363
  useApp(JOBS_APP);
872
1364
  it("mode 'each' gives every assignee their own task and inbox entry", async () => {
873
1365
  const sdk = await env.connect(STAFF);
@@ -1044,7 +1536,7 @@ export function defineContractSuite(name, factory) {
1044
1536
  expect((await (await env.connect(STAFF)).tasks.get(tasks[0].id)).regardingStudentId).toBe(childrenOf(SIBLINGS_PARENT.personId)[0]);
1045
1537
  });
1046
1538
  });
1047
- describe('schedule and cron (D7, D8, D20)', () => {
1539
+ schoolDescribe('schedule and cron (D7, D8, D20)', () => {
1048
1540
  useApp(JOBS_APP);
1049
1541
  const logs = async () => (await (await env.connect(STAFF)).db.entity('jobLog').list({ limit: 200 })).items;
1050
1542
  it('runs a scheduled job at its time, not before, as the user who scheduled it (D7)', async () => {
@@ -1230,7 +1722,7 @@ export function defineContractSuite(name, factory) {
1230
1722
  expect((await env.control.auditLog()).some((e) => e.action === 'job.redelivered')).toBe(true);
1231
1723
  });
1232
1724
  });
1233
- describe('audit (D19)', () => {
1725
+ schoolDescribe('audit (D19)', () => {
1234
1726
  useApp({
1235
1727
  ...JOBS_APP,
1236
1728
  manifest: { ...JOBS_APP.manifest, scopes: [...TEST_APP.manifest.scopes] },
@@ -1371,7 +1863,7 @@ export function defineContractSuite(name, factory) {
1371
1863
  expect(same).toEqual(entry);
1372
1864
  });
1373
1865
  });
1374
- describe('clock controls (D14)', () => {
1866
+ schoolDescribe('clock controls (D14)', () => {
1375
1867
  useApp(TEST_APP);
1376
1868
  it('advances a frozen clock', async () => {
1377
1869
  await env.control.setClock('2026-03-04T00:00:00.000Z');
@@ -1379,7 +1871,7 @@ export function defineContractSuite(name, factory) {
1379
1871
  expect((await env.connect(STAFF)).clock.now()).toBe('2026-03-05T00:00:00.000Z');
1380
1872
  });
1381
1873
  });
1382
- describe('clock (D14, D21)', () => {
1874
+ schoolDescribe('clock (D14, D21)', () => {
1383
1875
  useApp(TEST_APP);
1384
1876
  it('follows the engine clock', async () => {
1385
1877
  await env.control.setClock('2026-03-04T14:30:00.000Z');