@startsimpli/integrations 0.2.53 → 0.2.55

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.
@@ -0,0 +1,563 @@
1
+ /**
2
+ * NOTES UNDER THEIR PROJECT (bd startsim-vkymg: RED startsim-hh8c9).
3
+ *
4
+ * A note — or any other `source_document`, a Fathom meeting included — is filed
5
+ * under a project (a `focus`) by an `about_focus` edge, source_document -> focus.
6
+ * Three screens have to show that edge, and one rule has to survive them:
7
+ *
8
+ * - Planning: a focus lists its documents, SERVER-paginated (CLAUDE.md rule 8);
9
+ * - Library: any document shows 'Filed under' and can be moved;
10
+ * - Ask: a question can be scoped to one project;
11
+ * - and `about_focus` never enters 'N of M done', which walks `in_focus`
12
+ * commitments only.
13
+ *
14
+ * ACCESS, stated as it is today (bd startsim-9084j.12): `source_document` is
15
+ * row_scope=personal with no exemption, so a note is private to its owner. These
16
+ * tests do not widen that — they only assume the list endpoint answers with what
17
+ * the principal may read, and render exactly that.
18
+ */
19
+ import * as React from 'react';
20
+ import { render, screen, waitFor, within } from '@testing-library/react';
21
+ import userEvent from '@testing-library/user-event';
22
+ import { describe, expect, it, vi } from 'vitest';
23
+
24
+ import { AskPage } from '../components/pages/AskPage';
25
+ import { LibraryPage } from '../components/pages/LibraryPage';
26
+ import { PlanningPage } from '../components/pages/PlanningPage';
27
+ import { askCorpus, sanitizeAskFilters } from '../corpus/ask';
28
+ import { createCorpusApi, createPlanningApi } from '../corpus/client';
29
+ import {
30
+ FIXTURE_DOCUMENTS,
31
+ FIXTURE_ORG,
32
+ createFixtureCorpusApi,
33
+ createFixtureLlm,
34
+ } from '../corpus/fixtures';
35
+ import { createVoiceApi } from '../corpus/voice';
36
+ import type {
37
+ CorpusApi,
38
+ CorpusAskApi,
39
+ CorpusPage,
40
+ DocumentQuery,
41
+ Focus,
42
+ PlanningApi,
43
+ SourceDocument,
44
+ } from '../corpus/types';
45
+
46
+ const SCOPE = { orgId: FIXTURE_ORG };
47
+
48
+ const FOCUS_A: Focus = {
49
+ id: 'f1', externalId: 'focus:crochets', title: 'Crochets', detail: '',
50
+ status: 'active', scope: SCOPE,
51
+ };
52
+ const FOCUS_B: Focus = {
53
+ id: 'f2', externalId: 'focus:raise', title: 'Raise', detail: '',
54
+ status: 'active', scope: SCOPE,
55
+ };
56
+
57
+ // ---------------------------------------------------------------------------
58
+ // a tiny stateful tenant: entities + the relationships endpoint
59
+ // ---------------------------------------------------------------------------
60
+
61
+ interface Edge { id: string; rel_type: string; source: string; target: string }
62
+
63
+ function fakeTenant(initial: Edge[] = []) {
64
+ const edges = [...initial];
65
+ const gets: Array<{ path: string; params: Record<string, unknown> }> = [];
66
+ let next = 1;
67
+ const http = {
68
+ get: vi.fn(async (path: string, options?: { params?: Record<string, unknown> }) => {
69
+ const params = options?.params ?? {};
70
+ gets.push({ path, params });
71
+ if (path.includes('relationships')) {
72
+ const rows = edges.filter(
73
+ (e) =>
74
+ (!params.rel_type || e.rel_type === params.rel_type) &&
75
+ (!params.source || e.source === params.source),
76
+ );
77
+ return { count: rows.length, next: null, previous: null, results: rows };
78
+ }
79
+ return { count: 0, next: null, previous: null, results: [], applied_filters: [] };
80
+ }),
81
+ post: vi.fn(async (_path: string, body: any) => {
82
+ edges.push({ id: `e${next++}`, rel_type: body.rel_type, source: body.source, target: body.target });
83
+ return {};
84
+ }),
85
+ delete: vi.fn(async (path: string) => {
86
+ const id = path.split('/').pop();
87
+ const at = edges.findIndex((e) => e.id === id);
88
+ if (at >= 0) edges.splice(at, 1);
89
+ return {};
90
+ }),
91
+ };
92
+ return { edges, gets, http };
93
+ }
94
+
95
+ const edgesOf = (edges: Edge[], doc: string) =>
96
+ edges.filter((e) => e.rel_type === 'about_focus' && e.source === doc);
97
+
98
+ // ---------------------------------------------------------------------------
99
+ // the corpus client
100
+ // ---------------------------------------------------------------------------
101
+
102
+ describe('listing a focus’s documents is an edge walk, paginated by the server', () => {
103
+ it('sends related_to / about_focus / out with page and page_size', async () => {
104
+ const { gets, http } = fakeTenant();
105
+ const api = createCorpusApi({ http: http as never, scope: SCOPE });
106
+ await api.listDocuments({ focus: 'f1', page: 2, pageSize: 10 });
107
+ const params = gets.at(-1)!.params;
108
+ expect(params).toMatchObject({
109
+ type: 'source_document',
110
+ related_to: 'f1',
111
+ related_via: 'about_focus',
112
+ // A document is the SOURCE of its own about_focus edge, so `out` returns
113
+ // documents; `in` returns an empty page rather than an error.
114
+ related_direction: 'out',
115
+ page: 2,
116
+ page_size: 10,
117
+ });
118
+ });
119
+
120
+ it('sends no edge walk when no focus is asked for', async () => {
121
+ const { gets, http } = fakeTenant();
122
+ await createCorpusApi({ http: http as never, scope: SCOPE }).listDocuments({});
123
+ expect(gets.at(-1)!.params.related_via).toBeUndefined();
124
+ });
125
+
126
+ it('counts a server-reported related_to as the focus filter being honoured', async () => {
127
+ const http = {
128
+ get: vi.fn(async () => ({
129
+ count: 0, next: null, previous: null, results: [], applied_filters: ['type', 'related_to'],
130
+ })),
131
+ };
132
+ const page = await createCorpusApi({ http: http as never, scope: SCOPE }).listDocuments({ focus: 'f1' });
133
+ expect(page.appliedFilters).toContain('focus');
134
+ });
135
+ });
136
+
137
+ describe('fileDocument — a document lives under exactly one project', () => {
138
+ it('files an unfiled document with one edge', async () => {
139
+ const { edges, http } = fakeTenant();
140
+ const api = createCorpusApi({ http: http as never, scope: SCOPE });
141
+ await api.fileDocument!('d1', 'f1');
142
+ expect(edgesOf(edges, 'd1')).toMatchObject([{ target: 'f1' }]);
143
+ });
144
+
145
+ it('replaces the edge when moved, so exactly one exists', async () => {
146
+ const { edges, http } = fakeTenant([{ id: 'e0', rel_type: 'about_focus', source: 'd1', target: 'f1' }]);
147
+ const api = createCorpusApi({ http: http as never, scope: SCOPE });
148
+ await api.fileDocument!('d1', 'f2');
149
+ expect(edgesOf(edges, 'd1')).toMatchObject([{ target: 'f2' }]);
150
+ });
151
+
152
+ it('unfiles with null', async () => {
153
+ const { edges, http } = fakeTenant([{ id: 'e0', rel_type: 'about_focus', source: 'd1', target: 'f1' }]);
154
+ await createCorpusApi({ http: http as never, scope: SCOPE }).fileDocument!('d1', null);
155
+ expect(edgesOf(edges, 'd1')).toHaveLength(0);
156
+ });
157
+
158
+ it('leaves another document’s edge alone', async () => {
159
+ const { edges, http } = fakeTenant([{ id: 'e9', rel_type: 'about_focus', source: 'other', target: 'f1' }]);
160
+ await createCorpusApi({ http: http as never, scope: SCOPE }).fileDocument!('d1', 'f2');
161
+ expect(edgesOf(edges, 'other')).toHaveLength(1);
162
+ });
163
+
164
+ it('is the same code the voice page uses (one replace-the-edge implementation)', async () => {
165
+ const { edges, http } = fakeTenant([{ id: 'e0', rel_type: 'about_focus', source: 'n1', target: 'f1' }]);
166
+ await createVoiceApi({ http: http as never, scope: SCOPE, upload: vi.fn() }).file('n1', 'f2');
167
+ expect(edgesOf(edges, 'n1')).toMatchObject([{ target: 'f2' }]);
168
+ });
169
+ });
170
+
171
+ describe('a read-only client (no post) shows the chip and no way to move it', () => {
172
+ it('createCorpusApi omits fileDocument without http.post', () => {
173
+ const api = createCorpusApi({ http: { get: vi.fn() } as never, scope: SCOPE });
174
+ expect(api.fileDocument).toBeUndefined();
175
+ expect(api.getDocumentFiling).toBeDefined();
176
+ });
177
+
178
+ it('the Library renders the chip without a combobox', async () => {
179
+ const user = userEvent.setup();
180
+ const fathom = doc('fathom-1', 'Weekly call with Acme', 'fathom');
181
+ const read = createCorpusApi({
182
+ http: {
183
+ get: vi.fn(async (path: string) => {
184
+ if (path.includes('relationships')) return { results: [{ id: 'e0', source: 'fathom-1', target: 'f1' }] };
185
+ return { id: 'f1', name: 'Crochets', data: { title: 'Crochets' } };
186
+ }),
187
+ } as never,
188
+ scope: SCOPE,
189
+ });
190
+ const api: CorpusApi = {
191
+ ...createFixtureCorpusApi({ scope: SCOPE, documents: [fathom], moneyEvents: [] }),
192
+ getDocumentFiling: read.getDocumentFiling,
193
+ fileDocument: read.fileDocument,
194
+ listFocusChoices: read.listFocusChoices,
195
+ };
196
+ render(<LibraryPage api={api} scope={SCOPE} />);
197
+ await user.click(await screen.findByText('Weekly call with Acme'));
198
+ const detail = await screen.findByRole('region', { name: 'Record detail' });
199
+ expect(await within(detail).findByText('Crochets', { selector: 'span' })).toBeInTheDocument();
200
+ expect(within(detail).queryByRole('combobox', { name: /change project/i })).toBeNull();
201
+ });
202
+ });
203
+
204
+ describe('getDocumentFiling — "filed under"', () => {
205
+ it('names the project a document is filed under', async () => {
206
+ const http = {
207
+ get: vi.fn(async (path: string) => {
208
+ if (path.includes('relationships')) {
209
+ return { results: [{ id: 'e0', rel_type: 'about_focus', source: 'd1', target: 'f1' }] };
210
+ }
211
+ return { id: 'f1', external_id: 'focus:crochets', name: 'Crochets', entity_type: 'focus', data: { title: 'Crochets' } };
212
+ }),
213
+ };
214
+ const filing = await createCorpusApi({ http: http as never, scope: SCOPE }).getDocumentFiling!('d1');
215
+ expect(filing).toEqual({ id: 'f1', title: 'Crochets' });
216
+ });
217
+
218
+ it('is null for an unfiled document', async () => {
219
+ const { http } = fakeTenant();
220
+ expect(await createCorpusApi({ http: http as never, scope: SCOPE }).getDocumentFiling!('d1')).toBeNull();
221
+ });
222
+ });
223
+
224
+ // ---------------------------------------------------------------------------
225
+ // REGRESSION: documents never enter 'N of M done'
226
+ // ---------------------------------------------------------------------------
227
+
228
+ describe('about_focus never changes a focus’s standing', () => {
229
+ it('counts only commitments over in_focus, before and after a document is filed', async () => {
230
+ const { edges, gets, http } = fakeTenant();
231
+ const api = createPlanningApi({ http: http as never, scope: SCOPE });
232
+ await api.focusStanding!('f1', Date.parse('2026-11-02T00:00:00Z'));
233
+ await api.fileDocument!('d1', 'f1');
234
+ await api.listDocuments!({ focus: 'f1', page: 1, pageSize: 10 });
235
+ await api.focusStanding!('f1', Date.parse('2026-11-02T00:00:00Z'));
236
+
237
+ expect(edgesOf(edges, 'd1')).toHaveLength(1);
238
+ const counts = gets.filter((g) => g.params.page_size === 1);
239
+ expect(counts.length).toBe(6); // 3 counts x 2 reads
240
+ for (const call of counts) {
241
+ expect(call.params.type).toBe('commitment');
242
+ expect(call.params.related_via).toBe('in_focus');
243
+ }
244
+ });
245
+
246
+ it('keeps "12 of 40 done" and the item list unchanged when documents are listed', async () => {
247
+ const user = userEvent.setup();
248
+ const api = planningWithDocs({
249
+ standings: { f1: { focusId: 'f1', total: 40, done: 12, overdue: 3 } },
250
+ documents: [doc('d1', 'Standup note'), doc('d2', 'Planning call')],
251
+ });
252
+ render(<PlanningPage api={api} scope={SCOPE} now={Date.parse('2026-08-26T12:00:00Z')} />);
253
+ await user.click(await screen.findByText('Crochets'));
254
+ await screen.findByText('Standup note');
255
+ expect(screen.getByText(/12 of 40 done/)).toBeInTheDocument();
256
+ // Documents are not items: the item heading counts commitments only.
257
+ expect(screen.getByText(/0 items in Crochets/)).toBeInTheDocument();
258
+ });
259
+ });
260
+
261
+ // ---------------------------------------------------------------------------
262
+ // Planning: a focus lists its documents
263
+ // ---------------------------------------------------------------------------
264
+
265
+ function doc(id: string, title: string, source = 'voice'): SourceDocument {
266
+ return { ...FIXTURE_DOCUMENTS[0], id, title, source, sourceLabel: source, scope: SCOPE };
267
+ }
268
+
269
+ function planningWithDocs(options: {
270
+ documents?: SourceDocument[];
271
+ total?: number;
272
+ standings?: Record<string, { focusId: string; total: number; done: number; overdue: number }>;
273
+ onDocuments?: (query: DocumentQuery) => void;
274
+ } = {}): PlanningApi {
275
+ const page = <T,>(results: T[], count = results.length): CorpusPage<T> =>
276
+ ({ count, next: null, previous: null, results, appliedFilters: ['focus', 'status'] });
277
+ return {
278
+ listCommitments: async () => page([]),
279
+ listFocuses: async () => page([FOCUS_A, FOCUS_B]),
280
+ focusStanding: async (focusId) =>
281
+ options.standings?.[focusId] ?? { focusId, total: 0, done: 0, overdue: 0 },
282
+ listDocuments: async (query: DocumentQuery) => {
283
+ options.onDocuments?.(query);
284
+ // The server pages: a second page returns the second slice.
285
+ const all = options.documents ?? [];
286
+ const size = query.pageSize ?? all.length;
287
+ const from = ((query.page ?? 1) - 1) * size;
288
+ return page(all.slice(from, from + size), options.total ?? all.length);
289
+ },
290
+ } as PlanningApi;
291
+ }
292
+
293
+ describe('PlanningPage — a focus lists its documents', () => {
294
+ it('asks the server for the selected focus’s documents, page one', async () => {
295
+ const user = userEvent.setup();
296
+ const queries: DocumentQuery[] = [];
297
+ render(
298
+ <PlanningPage
299
+ api={planningWithDocs({ documents: [doc('d1', 'Standup note')], onDocuments: (q) => queries.push(q) })}
300
+ scope={SCOPE}
301
+ />,
302
+ );
303
+ await user.click(await screen.findByText('Crochets'));
304
+ expect(await screen.findByText('Standup note')).toBeInTheDocument();
305
+ expect(queries.at(-1)).toMatchObject({ focus: 'f1', page: 1 });
306
+ expect(queries.at(-1)!.pageSize).toBeGreaterThan(0);
307
+ });
308
+
309
+ it('asks nothing about documents until a focus is selected', async () => {
310
+ const queries: DocumentQuery[] = [];
311
+ render(<PlanningPage api={planningWithDocs({ onDocuments: (q) => queries.push(q) })} scope={SCOPE} />);
312
+ await screen.findByText('Crochets');
313
+ expect(queries).toHaveLength(0);
314
+ });
315
+
316
+ it('turns the page with a SERVER round trip, never by slicing in the browser', async () => {
317
+ const user = userEvent.setup();
318
+ const queries: DocumentQuery[] = [];
319
+ const documents = Array.from({ length: 25 }, (_, i) => doc(`d${i}`, `Note ${i}`));
320
+ render(
321
+ <PlanningPage
322
+ api={planningWithDocs({ documents, onDocuments: (q) => queries.push(q) })}
323
+ scope={SCOPE}
324
+ />,
325
+ );
326
+ await user.click(await screen.findByText('Crochets'));
327
+ const size = (await waitFor(() => {
328
+ expect(queries.length).toBeGreaterThan(0);
329
+ return queries.at(-1)!.pageSize!;
330
+ }));
331
+ await screen.findByText('Note 0');
332
+ expect(screen.queryByText(`Note ${size}`)).toBeNull();
333
+
334
+ await user.click(screen.getByRole('button', { name: /next/i }));
335
+ expect(await screen.findByText(`Note ${size}`)).toBeInTheDocument();
336
+ expect(queries.at(-1)).toMatchObject({ focus: 'f1', page: 2 });
337
+ });
338
+
339
+ it('shows every row the server returned (no client-side filtering)', async () => {
340
+ const user = userEvent.setup();
341
+ render(
342
+ <PlanningPage
343
+ api={planningWithDocs({ documents: [doc('d1', 'A voice note'), doc('d2', 'A Fathom call', 'fathom')] })}
344
+ scope={SCOPE}
345
+ />,
346
+ );
347
+ await user.click(await screen.findByText('Crochets'));
348
+ expect(await screen.findByText('A voice note')).toBeInTheDocument();
349
+ expect(screen.getByText('A Fathom call')).toBeInTheDocument();
350
+ });
351
+
352
+ it('says so when nothing is filed under the focus, and names the source on each row', async () => {
353
+ const user = userEvent.setup();
354
+ render(<PlanningPage api={planningWithDocs({ documents: [] })} scope={SCOPE} />);
355
+ await user.click(await screen.findByText('Crochets'));
356
+ expect(await screen.findByText(/No notes or documents filed under this yet/i)).toBeInTheDocument();
357
+ });
358
+
359
+ it('opens a document through onOpenDocument', async () => {
360
+ const user = userEvent.setup();
361
+ const open = vi.fn();
362
+ render(
363
+ <PlanningPage
364
+ api={planningWithDocs({ documents: [doc('d1', 'Standup note')] })}
365
+ scope={SCOPE}
366
+ onOpenDocument={open}
367
+ />,
368
+ );
369
+ await user.click(await screen.findByText('Crochets'));
370
+ await user.click(await screen.findByText('Standup note'));
371
+ expect(open).toHaveBeenCalledWith('d1');
372
+ });
373
+
374
+ it('renders no documents section for a client that cannot list documents', async () => {
375
+ const user = userEvent.setup();
376
+ const api = planningWithDocs();
377
+ delete (api as { listDocuments?: unknown }).listDocuments;
378
+ render(<PlanningPage api={api} scope={SCOPE} />);
379
+ await user.click(await screen.findByText('Crochets'));
380
+ expect(screen.queryByRole('region', { name: /documents/i })).toBeNull();
381
+ });
382
+ });
383
+
384
+ // ---------------------------------------------------------------------------
385
+ // Library: 'Filed under' + change control, for ANY source_document
386
+ // ---------------------------------------------------------------------------
387
+
388
+ function libraryWith(over: Partial<CorpusApi> = {}) {
389
+ const fathom = doc('fathom-1', 'Weekly call with Acme', 'fathom');
390
+ const base = createFixtureCorpusApi({ scope: SCOPE, documents: [fathom], moneyEvents: [] });
391
+ const fileDocument = vi.fn(async () => undefined);
392
+ const api: CorpusApi = {
393
+ ...base,
394
+ getDocumentFiling: vi.fn(async () => ({ id: 'f1', title: 'Crochets' })),
395
+ listFocusChoices: vi.fn(async () => [
396
+ { id: 'f1', title: 'Crochets' },
397
+ { id: 'f2', title: 'Raise' },
398
+ ]),
399
+ fileDocument,
400
+ ...over,
401
+ };
402
+ return { api, fileDocument };
403
+ }
404
+
405
+ describe('LibraryPage — Filed under', () => {
406
+ it('shows the project chip on a NON-voice document', async () => {
407
+ const user = userEvent.setup();
408
+ const { api } = libraryWith();
409
+ render(<LibraryPage api={api} scope={SCOPE} />);
410
+ await user.click(await screen.findByText('Weekly call with Acme'));
411
+ const detail = await screen.findByRole('region', { name: 'Record detail' });
412
+ expect(await within(detail).findByText(/Filed under/i)).toBeInTheDocument();
413
+ expect(within(detail).getByText('Crochets', { selector: 'span' })).toBeInTheDocument();
414
+ });
415
+
416
+ it('says "Not filed" when there is no edge', async () => {
417
+ const user = userEvent.setup();
418
+ const { api } = libraryWith({ getDocumentFiling: vi.fn(async () => null) });
419
+ render(<LibraryPage api={api} scope={SCOPE} />);
420
+ await user.click(await screen.findByText('Weekly call with Acme'));
421
+ const detail = await screen.findByRole('region', { name: 'Record detail' });
422
+ expect(await within(detail).findByText(/Not filed under a project/i)).toBeInTheDocument();
423
+ });
424
+
425
+ it('moves the document through fileDocument and shows the new project', async () => {
426
+ const user = userEvent.setup();
427
+ const { api, fileDocument } = libraryWith();
428
+ render(<LibraryPage api={api} scope={SCOPE} />);
429
+ await user.click(await screen.findByText('Weekly call with Acme'));
430
+ const detail = await screen.findByRole('region', { name: 'Record detail' });
431
+ const control = await within(detail).findByRole('combobox', { name: /change project/i });
432
+ await user.selectOptions(control, 'f2');
433
+ await waitFor(() => expect(fileDocument).toHaveBeenCalledWith('fathom-1', 'f2'));
434
+ expect(await within(detail).findByText('Raise', { selector: 'span' })).toBeInTheDocument();
435
+ });
436
+
437
+ it('can unfile', async () => {
438
+ const user = userEvent.setup();
439
+ const { api, fileDocument } = libraryWith();
440
+ render(<LibraryPage api={api} scope={SCOPE} />);
441
+ await user.click(await screen.findByText('Weekly call with Acme'));
442
+ const detail = await screen.findByRole('region', { name: 'Record detail' });
443
+ await user.selectOptions(await within(detail).findByRole('combobox', { name: /change project/i }), '');
444
+ await waitFor(() => expect(fileDocument).toHaveBeenCalledWith('fathom-1', null));
445
+ });
446
+
447
+ it('shows no change control when the client cannot file (read-only fork)', async () => {
448
+ const user = userEvent.setup();
449
+ const { api } = libraryWith({ fileDocument: undefined });
450
+ render(<LibraryPage api={api} scope={SCOPE} />);
451
+ await user.click(await screen.findByText('Weekly call with Acme'));
452
+ const detail = await screen.findByRole('region', { name: 'Record detail' });
453
+ await within(detail).findByText(/Filed under/i);
454
+ expect(within(detail).queryByRole('combobox', { name: /change project/i })).toBeNull();
455
+ });
456
+
457
+ it('shows nothing about filing when the client has no filing reads at all', async () => {
458
+ const user = userEvent.setup();
459
+ const { api } = libraryWith({
460
+ getDocumentFiling: undefined, fileDocument: undefined, listFocusChoices: undefined,
461
+ });
462
+ render(<LibraryPage api={api} scope={SCOPE} />);
463
+ await user.click(await screen.findByText('Weekly call with Acme'));
464
+ const detail = await screen.findByRole('region', { name: 'Record detail' });
465
+ expect(within(detail).queryByText(/Filed under/i)).toBeNull();
466
+ });
467
+ });
468
+
469
+ // ---------------------------------------------------------------------------
470
+ // Ask: scoped to a project
471
+ // ---------------------------------------------------------------------------
472
+
473
+ describe('Ask — scope to a project', () => {
474
+ const answered = {
475
+ status: 'answered' as const, answer: 'ok', citations: [], considered: [],
476
+ unresolvedCitations: [], droppedOutOfScope: 0,
477
+ provider: { provider: 'fixture', model: 'm', live: false },
478
+ };
479
+
480
+ it('sends the chosen project as filters.focus', async () => {
481
+ const user = userEvent.setup();
482
+ const ask = vi.fn(async () => answered);
483
+ const api: CorpusAskApi = { ask };
484
+ render(
485
+ <AskPage
486
+ api={api}
487
+ scope={SCOPE}
488
+ listProjects={async () => [{ id: 'f1', title: 'Crochets' }, { id: 'f2', title: 'Raise' }]}
489
+ />,
490
+ );
491
+ await user.selectOptions(await screen.findByRole('combobox', { name: /project/i }), 'f1');
492
+ await user.type(screen.getByRole('textbox'), 'what did I decide');
493
+ await user.click(screen.getByRole('button', { name: 'Ask' }));
494
+ await waitFor(() => expect(ask).toHaveBeenCalled());
495
+ expect((ask.mock.calls[0] as unknown as [{ filters?: unknown }])[0].filters).toEqual({ focus: 'f1' });
496
+ });
497
+
498
+ it('sends no filters when "All projects" is left selected', async () => {
499
+ const user = userEvent.setup();
500
+ const ask = vi.fn(async () => answered);
501
+ render(
502
+ <AskPage api={{ ask }} scope={SCOPE} listProjects={async () => [{ id: 'f1', title: 'Crochets' }]} />,
503
+ );
504
+ await screen.findByRole('combobox', { name: /project/i });
505
+ await user.type(screen.getByRole('textbox'), 'anything');
506
+ await user.click(screen.getByRole('button', { name: 'Ask' }));
507
+ await waitFor(() => expect(ask).toHaveBeenCalled());
508
+ expect((ask.mock.calls[0] as unknown as [{ filters?: unknown }])[0].filters).toBeUndefined();
509
+ });
510
+
511
+ it('renders no project picker without listProjects', () => {
512
+ render(<AskPage api={{ ask: vi.fn() }} scope={SCOPE} />);
513
+ expect(screen.queryByRole('combobox', { name: /project/i })).toBeNull();
514
+ });
515
+
516
+ it('retrieves only the project’s documents: the focus goes to the server query', async () => {
517
+ const queries: DocumentQuery[] = [];
518
+ const corpus = createFixtureCorpusApi({ scope: SCOPE });
519
+ const spy: CorpusApi = {
520
+ ...corpus,
521
+ listDocuments: (q) => { queries.push(q); return corpus.listDocuments(q); },
522
+ };
523
+ await askCorpus(
524
+ { question: 'renewal terms', mode: 'ask', scope: SCOPE, filters: { focus: 'f1' } },
525
+ { corpus: spy, llm: createFixtureLlm() },
526
+ );
527
+ expect(queries.length).toBeGreaterThan(0);
528
+ expect(queries.every((q) => q.focus === 'f1')).toBe(true);
529
+ });
530
+
531
+ it('does not ask for money events when scoped to a project', async () => {
532
+ // A payment cannot be filed under a project, so a project-scoped answer has none.
533
+ const corpus = createFixtureCorpusApi({ scope: SCOPE });
534
+ const listMoneyEvents = vi.fn(corpus.listMoneyEvents!);
535
+ const queries: DocumentQuery[] = [];
536
+ const spy: CorpusApi = {
537
+ ...corpus,
538
+ listMoneyEvents,
539
+ listDocuments: (q) => { queries.push(q); return corpus.listDocuments(q); },
540
+ };
541
+ await askCorpus(
542
+ { question: 'what did we agree', mode: 'ask', scope: SCOPE, filters: { focus: 'f1' } },
543
+ { corpus: spy, llm: createFixtureLlm() },
544
+ );
545
+ expect(listMoneyEvents).not.toHaveBeenCalled();
546
+ // ...and the unscoped question still does.
547
+ await askCorpus(
548
+ { question: 'what did we agree', mode: 'ask', scope: SCOPE },
549
+ { corpus: spy, llm: createFixtureLlm() },
550
+ );
551
+ expect(listMoneyEvents).toHaveBeenCalled();
552
+ });
553
+
554
+ it('a route can accept only the filters Ask understands', () => {
555
+ expect(sanitizeAskFilters({ focus: 'f1', partyId: 'p1', evil: 'x' } as never)).toEqual({
556
+ focus: 'f1', partyId: 'p1',
557
+ });
558
+ expect(sanitizeAskFilters(undefined)).toBeUndefined();
559
+ expect(sanitizeAskFilters({ focus: '' } as never)).toBeUndefined();
560
+ });
561
+ });
562
+
563
+ void React;
@@ -0,0 +1,54 @@
1
+ // @vitest-environment node
2
+ /**
3
+ * REAL-MODEL golden eval (bd startsim-5njrt). Paid, so gated: `VOICE_EVAL=1`.
4
+ * Speech: VOICE_EVAL_SPEECH=elevenlabs|openai (default elevenlabs). Audio is
5
+ * generated here with macOS `say` and never committed. Provider keys come from
6
+ * the environment of this one command.
7
+ */
8
+ import { spawnSync } from 'node:child_process';
9
+ import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
10
+ import { tmpdir } from 'node:os';
11
+ import { join } from 'node:path';
12
+ import { describe, expect, it } from 'vitest';
13
+
14
+ import { createVoiceAnalyzer, createVoiceTranscriber } from '../corpus/llm';
15
+ import { GOLDEN_CLIPS, GOLDEN_FOCUSES } from './fixtures/voice-golden';
16
+ import { aggregate, commitmentsFromSummary, scoreClip, PRECISION_FLOOR, RECALL_FLOOR } from './helpers/voice-eval';
17
+
18
+ const enabled = process.env.VOICE_EVAL === '1';
19
+ const hasSay = spawnSync('say', ['-v', '?']).status === 0;
20
+ if (enabled && !hasSay) console.warn('VOICE_EVAL skipped: macOS `say` is not available, so no audio can be generated.');
21
+
22
+ describe.skipIf(!enabled || !hasSay)('golden clips with real models', () => {
23
+ it('holds the recall and precision floors and the right project', async () => {
24
+ const dir = mkdtempSync(join(tmpdir(), 'voice-golden-'));
25
+ const provider = process.env.VOICE_EVAL_SPEECH ?? 'elevenlabs';
26
+ const transcriber = createVoiceTranscriber({ speech: { preferredProvider: provider, fallback: false } });
27
+ const analyzer = createVoiceAnalyzer();
28
+ const scores = []; const rows: Array<Record<string, unknown>> = [];
29
+ let tokensIn = 0, tokensOut = 0, seconds = 0, focusRight = 0;
30
+ try {
31
+ for (const clip of GOLDEN_CLIPS) {
32
+ const file = join(dir, `${clip.id}.wav`);
33
+ expect(spawnSync('say', ['-o', file, '--data-format=LEI16@22050', clip.text]).status).toBe(0);
34
+ const audio = new Uint8Array(readFileSync(file));
35
+ const t = await transcriber.transcribe({ audio, mimeType: 'audio/wav', focusTitles: GOLDEN_FOCUSES.map((f) => f.title) });
36
+ const text = typeof t === 'string' ? t : t.text;
37
+ if (typeof t !== 'string') seconds += t.audioSeconds ?? 0;
38
+ const a = await analyzer.analyze({ transcript: text, focuses: GOLDEN_FOCUSES });
39
+ const produced = commitmentsFromSummary(a.summary);
40
+ const s = scoreClip(clip, produced);
41
+ scores.push(s);
42
+ tokensIn += a.usage?.tokensIn ?? 0; tokensOut += a.usage?.tokensOut ?? 0;
43
+ if (a.focusId === clip.focusId) focusRight++;
44
+ rows.push({ clip: clip.id, focus: a.focusId, wantFocus: clip.focusId, recall: `${s.matchedExpected}/${s.expected}`, produced: s.produced, calls: a.usage?.calls, llm: `${a.usage?.provider}/${a.usage?.model}` });
45
+ }
46
+ } finally { rmSync(dir, { recursive: true, force: true }); }
47
+ const agg = aggregate(scores);
48
+ console.table(rows);
49
+ console.log(JSON.stringify({ speech: provider, ...agg, focusRight, clips: GOLDEN_CLIPS.length, audioSeconds: seconds, tokensIn, tokensOut }));
50
+ expect(agg.recall).toBeGreaterThanOrEqual(RECALL_FLOOR);
51
+ expect(agg.precision).toBeGreaterThanOrEqual(PRECISION_FLOOR);
52
+ expect(focusRight).toBe(GOLDEN_CLIPS.length);
53
+ }, 600_000);
54
+ });