@startsimpli/integrations 0.2.218 → 0.2.220

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@startsimpli/integrations",
3
- "version": "0.2.218",
3
+ "version": "0.2.220",
4
4
  "description": "Provider-agnostic types, API clients, hooks, and UI primitives for email + calendar integrations across StartSimpli apps, plus foundry customer email (subpath ./comms).",
5
5
  "license": "MIT",
6
6
  "homepage": "https://startsimpli.com",
@@ -50,9 +50,9 @@
50
50
  "react-native": ">=0.74.0",
51
51
  "@startsimpli/ui-native": ">=0.1.12",
52
52
  "react-native-safe-area-context": ">=4.0.0",
53
- "@startsimpli/ui": "^0.4.208",
54
53
  "@startsimpli/utils": "^0.4.21",
55
- "@startsimpli/auth": "^0.4.62"
54
+ "@startsimpli/auth": "^0.4.62",
55
+ "@startsimpli/ui": "^0.4.208"
56
56
  },
57
57
  "peerDependenciesMeta": {
58
58
  "react": {
@@ -0,0 +1,57 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+
3
+ import { generateBriefing, type BriefingDeps, type BriefingItem } from '../corpus/briefing';
4
+
5
+ /**
6
+ * startsim-nghko.40: a cold first briefing (no zone sent, none remembered) spent its
7
+ * time in serial tenant round trips BEFORE any model call: up to 5 sequential
8
+ * remembered-zone lookups, then loadItems, then unsureCount, then the cache find.
9
+ * Every tenant call here costs LATENCY ms; the independent ones must overlap.
10
+ */
11
+ const LATENCY = 100;
12
+ const NOW = Date.parse('2026-11-05T14:00:00Z');
13
+ const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
14
+ const item: BriefingItem = { id: 'a', title: 'Do a', status: 'open', ownerSub: 'me', dueAt: '2026-11-05', priority: 2 };
15
+
16
+ function coldDeps(): { deps: BriefingDeps; gets: ReturnType<typeof vi.fn> } {
17
+ const gets = vi.fn(async () => { await sleep(LATENCY); return { results: [] }; });
18
+ const deps: BriefingDeps = {
19
+ http: { get: gets, post: vi.fn(async (_p: string, body: any) => { await sleep(LATENCY); return { id: 1, ...body }; }) } as never,
20
+ orgId: 'org',
21
+ ownerSub: 'me',
22
+ loadItems: async () => { await sleep(LATENCY); return [item]; },
23
+ unsureCount: async () => { await sleep(LATENCY); return 0; },
24
+ synthesize: async () => ({ audio: new Uint8Array([1]), mimeType: 'audio/mpeg', model: 'm', provider: 'p', usage: {} }),
25
+ scriptLlm: null,
26
+ audio: { put: async () => 's3://x', url: async () => 'https://signed.example/x' },
27
+ now: () => NOW,
28
+ name: 'Quinn',
29
+ };
30
+ return { deps, gets };
31
+ }
32
+
33
+ describe('briefing cold-path latency', () => {
34
+ it('overlaps the independent tenant reads: before the script, a cold call costs ~3 round trips, not ~8', async () => {
35
+ const { deps } = coldDeps();
36
+ const started = Date.now();
37
+ await generateBriefing(deps, {});
38
+ const elapsed = Date.now() - started;
39
+ // reads: (zone x5 | items | unsure) in parallel, then the cache find; then save + nothing else serial.
40
+ // 3 reads-phases + 1 save = 4 round trips = ~400ms. Serial was 8 reads + 1 save = ~900ms.
41
+ expect(elapsed).toBeLessThan(LATENCY * 5.5);
42
+ });
43
+
44
+ it('still falls back to UTC-free behaviour: a remembered zone from the nearest day wins', async () => {
45
+ const { deps, gets } = coldDeps();
46
+ gets.mockImplementation(async (_p: string, o: any) => {
47
+ await sleep(5);
48
+ const ext = String(o?.params?.external_id__in ?? '');
49
+ // only the day before `now` (UTC) has a stored row, in Tokyo
50
+ return ext.includes('2026-11-04')
51
+ ? { results: [{ id: 9, external_id: ext, owner_sub: 'me', data: { briefing_context: { timeZone: 'Asia/Tokyo' } } }] }
52
+ : { results: [] };
53
+ });
54
+ const result = await generateBriefing(deps, {});
55
+ expect(result.context.timeZone).toBe('Asia/Tokyo');
56
+ });
57
+ });
@@ -0,0 +1,120 @@
1
+ /**
2
+ * The Connections page paints as each request lands (bd startsim-nghko.37).
3
+ *
4
+ * It used to wait on `Promise.all([catalog, connections])`: the slowest leg held the whole page on
5
+ * "Loading…", and either leg failing replaced everything with one error. These pin the replacement:
6
+ * the connected accounts show the moment THEY arrive, the catalog fills in on its own clock, and each
7
+ * leg fails and retries by itself.
8
+ */
9
+ import { describe, expect, it, vi } from 'vitest';
10
+ import { render, screen, waitFor, within } from '@testing-library/react';
11
+ import userEvent from '@testing-library/user-event';
12
+
13
+ import { ConnectionsPage } from '../components/pages/ConnectionsPage';
14
+ import type { MemberConnectionsApi } from '../components/pages/types';
15
+
16
+ const GOOGLE = {
17
+ id: 'g1', public_id: 'pub-g1', name: 'Google', connector_key: 'google', connector_name: 'Google',
18
+ external_account_id: '', account_label: '', capabilities_enabled: [], config: {}, status: 'connected',
19
+ health: 'ok', auth_mode: 'oauth',
20
+ sync: { state: 'ok', note: '', records: 72, last_attempt_at: null, last_success_at: null,
21
+ next_sync_at: null, interval_minutes: 10, window_days: 14 },
22
+ };
23
+ const CATALOG_ROW = {
24
+ key: 'granola', name: 'Granola', description: 'Meeting notes', auth_mode: 'api_key', allowed: true,
25
+ availability: { available: true, reason: '' }, capabilities: ['poll'], credential_schema: [{ key: 'api_key', label: 'API key', type: 'secret', required: true }],
26
+ };
27
+ const PERMS = { view: true, manage: true, issue_tokens: false };
28
+
29
+ function deferred<T>() {
30
+ let resolve!: (v: T) => void;
31
+ let reject!: (e: unknown) => void;
32
+ const promise = new Promise<T>((res, rej) => { resolve = res; reject = rej; });
33
+ return { promise, resolve, reject };
34
+ }
35
+
36
+ function api(over: Partial<MemberConnectionsApi>): MemberConnectionsApi {
37
+ return {
38
+ connectorCatalog: vi.fn().mockResolvedValue({ results: [CATALOG_ROW] }),
39
+ connections: vi.fn().mockResolvedValue({ results: [GOOGLE], permissions: PERMS }),
40
+ ...over,
41
+ } as unknown as MemberConnectionsApi;
42
+ }
43
+
44
+ describe('ConnectionsPage — each request paints on its own', () => {
45
+ it('shows the connected accounts while the catalog is still in flight', async () => {
46
+ const catalog = deferred<{ results: unknown[] }>();
47
+ const a = api({ connectorCatalog: vi.fn().mockReturnValue(catalog.promise) as never });
48
+ render(<ConnectionsPage mode="personal" api={a} />);
49
+
50
+ const table = await screen.findByRole('region', { name: 'Source freshness' });
51
+ expect(within(table).getByText('Google')).toBeInTheDocument();
52
+ // The catalog has not answered: its section says so, and does NOT claim nothing is connectable.
53
+ expect(screen.queryByText(/has not opened any connector/i)).toBeNull();
54
+ expect(screen.getByText(/Loading connectors/i)).toBeInTheDocument();
55
+
56
+ catalog.resolve({ results: [CATALOG_ROW] });
57
+ expect(await screen.findByText('Granola')).toBeInTheDocument();
58
+ expect(screen.queryByText(/Loading connectors/i)).toBeNull();
59
+ });
60
+
61
+ it('shows the catalog while the connections are still in flight', async () => {
62
+ const conns = deferred<{ results: unknown[]; permissions: unknown }>();
63
+ const a = api({ connections: vi.fn().mockReturnValue(conns.promise) as never });
64
+ render(<ConnectionsPage mode="personal" api={a} />);
65
+
66
+ expect(await screen.findByText('Granola')).toBeInTheDocument();
67
+ expect(screen.getByText(/Loading your accounts/i)).toBeInTheDocument();
68
+ expect(screen.queryByText(/You have not connected an account yet/i)).toBeNull();
69
+
70
+ conns.resolve({ results: [GOOGLE], permissions: PERMS });
71
+ expect(await screen.findByRole('region', { name: 'Source freshness' })).toBeInTheDocument();
72
+ });
73
+
74
+ it('a failed catalog keeps the accounts and retries only the catalog', async () => {
75
+ const user = userEvent.setup();
76
+ const connectorCatalog = vi.fn()
77
+ .mockRejectedValueOnce(new Error('catalog is down'))
78
+ .mockResolvedValue({ results: [CATALOG_ROW] });
79
+ const connections = vi.fn().mockResolvedValue({ results: [GOOGLE], permissions: PERMS });
80
+ render(<ConnectionsPage mode="personal" api={api({ connectorCatalog, connections } as never)} />);
81
+
82
+ expect(await screen.findByRole('region', { name: 'Source freshness' })).toBeInTheDocument();
83
+ const alert = await screen.findByRole('alert');
84
+ expect(alert).toHaveTextContent(/catalog is down/);
85
+ await user.click(within(alert).getByRole('button', { name: /try again/i }));
86
+
87
+ expect(await screen.findByText('Granola')).toBeInTheDocument();
88
+ expect(connectorCatalog).toHaveBeenCalledTimes(2);
89
+ expect(connections).toHaveBeenCalledTimes(1);
90
+ });
91
+
92
+ it('failed accounts keep the catalog and retry only the accounts', async () => {
93
+ const user = userEvent.setup();
94
+ const connections = vi.fn()
95
+ .mockRejectedValueOnce(new Error('accounts are down'))
96
+ .mockResolvedValue({ results: [GOOGLE], permissions: PERMS });
97
+ const connectorCatalog = vi.fn().mockResolvedValue({ results: [CATALOG_ROW] });
98
+ render(<ConnectionsPage mode="personal" api={api({ connectorCatalog, connections } as never)} />);
99
+
100
+ expect(await screen.findByText('Granola')).toBeInTheDocument();
101
+ const alert = await screen.findByRole('alert');
102
+ expect(alert).toHaveTextContent(/accounts are down/);
103
+ await user.click(within(alert).getByRole('button', { name: /try again/i }));
104
+
105
+ expect(await screen.findByRole('region', { name: 'Source freshness' })).toBeInTheDocument();
106
+ expect(connections).toHaveBeenCalledTimes(2);
107
+ expect(connectorCatalog).toHaveBeenCalledTimes(1);
108
+ });
109
+
110
+ it('LATENCY BUDGET: first content waits on the accounts leg only, never on the slowest request', async () => {
111
+ const slowCatalog = deferred<{ results: unknown[] }>(); // never answers inside this test
112
+ const a = api({ connectorCatalog: vi.fn().mockReturnValue(slowCatalog.promise) as never });
113
+ const t0 = performance.now();
114
+ render(<ConnectionsPage mode="personal" api={a} />);
115
+ await screen.findByRole('region', { name: 'Source freshness' });
116
+ // The accounts mock answers at once; with the catalog hung forever the page must still be useful.
117
+ expect(performance.now() - t0).toBeLessThan(1000);
118
+ await waitFor(() => expect(screen.queryByText(/Loading your accounts/i)).toBeNull());
119
+ });
120
+ });
@@ -39,6 +39,35 @@ const MICROSOFT = connection('m1', 'Microsoft', {
39
39
  last_success_at: null, next_sync_at: null, interval_minutes: null, window_days: 14 },
40
40
  });
41
41
 
42
+ const CONNECTING = connection('m2', 'Outlook', {
43
+ status: 'needs_reauth',
44
+ sync: { state: 'connecting', note: 'Finish signing in with the provider to connect', records: 0, last_attempt_at: null,
45
+ last_success_at: null, next_sync_at: null, interval_minutes: null, window_days: 14 },
46
+ });
47
+ const REFUSED = connection('m3', 'Outlook work', {
48
+ status: 'needs_reauth',
49
+ sync: { state: 'reauth', note: "Microsoft refused this sign-in: StartSimpli's Microsoft app is not set up for accounts outside its own organization yet.",
50
+ records: 0, last_attempt_at: null, last_success_at: null, next_sync_at: null, interval_minutes: null, window_days: 14 },
51
+ });
52
+
53
+ describe('ConnectionsPage — a connect that has not finished', () => {
54
+ it('says Connecting, not Reconnect needed, while the member is still at the provider', async () => {
55
+ render(<ConnectionsPage mode="personal" api={api([CONNECTING])} />);
56
+ const table = await screen.findByRole('region', { name: 'Source freshness' });
57
+ const row = within(table).getByText('Outlook').closest('tr')!;
58
+ expect(within(row).getByText('Connecting…')).toBeInTheDocument();
59
+ expect(within(row).queryByText('Reconnect needed')).toBeNull();
60
+ });
61
+
62
+ it('shows why a refused connect needs reconnecting', async () => {
63
+ render(<ConnectionsPage mode="personal" api={api([REFUSED])} />);
64
+ const table = await screen.findByRole('region', { name: 'Source freshness' });
65
+ const row = within(table).getByText('Outlook work').closest('tr')!;
66
+ expect(within(row).getByText('Reconnect needed')).toBeInTheDocument();
67
+ expect(within(row).getByText(/not set up for accounts outside its own organization/)).toBeInTheDocument();
68
+ });
69
+ });
70
+
42
71
  describe('ConnectionsPage — the sources sync table', () => {
43
72
  it('lists each synced connection as a row: status, records with its window, last and next sync', async () => {
44
73
  render(<ConnectionsPage mode="personal" api={api([GOOGLE, MICROSOFT])} />);
@@ -69,33 +69,57 @@ export function ConnectionsPage(props: ConnectionsPageProps) {
69
69
  const [permissions, setPermissions] = React.useState<ConnectionPermissions>({
70
70
  view: true, manage: false, issue_tokens: false,
71
71
  });
72
- const [loadError, setLoadError] = React.useState<string>('');
73
- const [loading, setLoading] = React.useState(true);
72
+ // TWO LEGS, TWO CLOCKS (bd startsim-nghko.37). The accounts list and the catalog are separate
73
+ // requests with separate failure modes: each paints when it lands, fails on its own, and retries
74
+ // alone. Gating the page on both (`Promise.all`) made the slowest request the page's latency and let
75
+ // either failure blank the other half.
76
+ const [catalogError, setCatalogError] = React.useState<string>('');
77
+ const [connectionsError, setConnectionsError] = React.useState<string>('');
78
+ const [catalogLoading, setCatalogLoading] = React.useState(true);
79
+ const [connectionsLoading, setConnectionsLoading] = React.useState(true);
74
80
  /** The synced connection whose own card is open (the table's one action). */
75
81
  const [openId, setOpenId] = React.useState<string | null>(null);
76
82
 
77
- const reload = React.useCallback(async () => {
78
- setLoading(true);
83
+ const loadCatalog = React.useCallback(async () => {
84
+ setCatalogLoading(true);
79
85
  try {
80
- const [cat, conns] = await Promise.all([
81
- // In personal mode this is the ALLOWED catalog, already narrowed by the
82
- // foundry's policy server-side. Rendered as handed: filtering here would
83
- // put the withheld connectors in the browser to be filtered out of.
84
- api.connectorCatalog(),
85
- api.connections(),
86
- ]);
86
+ // In personal mode this is the ALLOWED catalog, already narrowed by the
87
+ // foundry's policy server-side. Rendered as handed: filtering here would
88
+ // put the withheld connectors in the browser to be filtered out of.
89
+ const cat = await api.connectorCatalog();
87
90
  setCatalog(cat.results ?? []);
91
+ setCatalogError('');
92
+ } catch (err) {
93
+ setCatalogError(readFailureMessage(err, personal));
94
+ } finally {
95
+ setCatalogLoading(false);
96
+ }
97
+ }, [api, personal]);
98
+
99
+ const loadConnections = React.useCallback(async () => {
100
+ setConnectionsLoading(true);
101
+ try {
102
+ const conns = await api.connections();
88
103
  setConnections(conns.results ?? []);
89
104
  setPermissions(conns.permissions ?? { view: true, manage: false, issue_tokens: false });
90
- setLoadError('');
105
+ setConnectionsError('');
91
106
  } catch (err) {
92
- setLoadError(readFailureMessage(err, personal));
107
+ setConnectionsError(readFailureMessage(err, personal));
93
108
  } finally {
94
- setLoading(false);
109
+ setConnectionsLoading(false);
95
110
  }
96
111
  }, [api, personal]);
97
112
 
98
- React.useEffect(() => { void reload(); }, [reload]);
113
+ /** After a change (connect, rotate, disconnect, policy flip): both halves can have moved. */
114
+ const reload = React.useCallback(async () => {
115
+ await Promise.all([loadCatalog(), loadConnections()]);
116
+ }, [loadCatalog, loadConnections]);
117
+
118
+ React.useEffect(() => { void loadConnections(); }, [loadConnections]);
119
+ React.useEffect(() => { void loadCatalog(); }, [loadCatalog]);
120
+ /** Still waiting for the FIRST answer; a refresh after a change keeps what is on screen. */
121
+ const loading = connectionsLoading;
122
+ const catalogPending = catalogLoading && catalog.length === 0;
99
123
 
100
124
  const syncRows: SourceFreshness[] = connections.flatMap((connection) => {
101
125
  const sync = readSync(connection as unknown as Record<string, unknown>);
@@ -112,10 +136,6 @@ export function ConnectionsPage(props: ConnectionsPageProps) {
112
136
  } as SourceFreshness];
113
137
  });
114
138
 
115
- if (loadError) {
116
- return <LoadError what="your connections" message={loadError} onRetry={() => { setLoadError(''); void reload(); }} />;
117
- }
118
-
119
139
  return (
120
140
  <div className={cn.root}>
121
141
  <section className={cn.section}>
@@ -126,8 +146,14 @@ export function ConnectionsPage(props: ConnectionsPageProps) {
126
146
  <h2 className={cn.heading}>
127
147
  {personal ? 'Your connected accounts' : 'Connected accounts'}
128
148
  </h2>
129
- {loading && connections.length === 0 ? <p className={cn.muted}>Loading…</p> : null}
130
- {!loading && connections.length === 0 ? (
149
+ {connectionsError ? (
150
+ <LoadError what="your connections" message={connectionsError}
151
+ onRetry={() => { setConnectionsError(''); void loadConnections(); }} />
152
+ ) : null}
153
+ {loading && connections.length === 0 && !connectionsError ? (
154
+ <p className={cn.muted}>{personal ? 'Loading your accounts…' : 'Loading connected accounts…'}</p>
155
+ ) : null}
156
+ {!loading && !connectionsError && connections.length === 0 ? (
131
157
  <p className={cn.muted}>
132
158
  {personal
133
159
  ? 'You have not connected an account yet.'
@@ -163,12 +189,18 @@ export function ConnectionsPage(props: ConnectionsPageProps) {
163
189
  </section>
164
190
 
165
191
  {/* Nothing to offer is no section: a heading over a blank gap reads as a broken page. */}
166
- {(personal ? connectableEntries(catalog, connections) : catalog).length > 0 || (personal && !loading && catalog.length === 0) ? (
192
+ {(personal ? connectableEntries(catalog, connections) : catalog).length > 0 || catalogPending || catalogError
193
+ || (personal && !catalogLoading && catalog.length === 0) ? (
167
194
  <section className={cn.section}>
168
195
  <h2 className={cn.heading}>
169
196
  {personal ? 'Connect your own account' : 'Available connectors'}
170
197
  </h2>
171
- {personal && !loading && catalog.length === 0 ? (
198
+ {catalogError ? (
199
+ <LoadError what="the connector list" message={catalogError}
200
+ onRetry={() => { setCatalogError(''); void loadCatalog(); }} />
201
+ ) : null}
202
+ {catalogPending && !catalogError ? <p className={cn.muted}>Loading connectors…</p> : null}
203
+ {personal && !catalogLoading && !catalogError && catalog.length === 0 ? (
172
204
  <p className={cn.muted}>
173
205
  Your foundry has not opened any connector to members yet. An admin
174
206
  decides which ones you may connect your own account on.
@@ -17,9 +17,18 @@ const SYNC_WORDS: Record<string, string> = {
17
17
  limited: 'Slowed by the provider',
18
18
  failing: 'Not syncing',
19
19
  reauth: 'Reconnect needed',
20
+ connecting: 'Connecting…',
21
+ syncing: 'Syncing…',
20
22
  waiting: 'Waiting for first sync',
21
23
  };
22
24
 
25
+ /** Why a card needs attention, in the server's own sentence; '' when the status word says it all. */
26
+ export function reasonText(source: SourceFreshness): string {
27
+ const sync = source.sync;
28
+ if (!sync || (sync.state !== 'reauth' && sync.state !== 'connecting')) return '';
29
+ return sync.note === 'Reconnect this account to resume syncing' ? '' : sync.note;
30
+ }
31
+
23
32
  export function statusText(source: SourceFreshness): string {
24
33
  const sync = source.sync;
25
34
  if (sync?.state === 'passive') return sync.note;
@@ -67,6 +76,7 @@ function nextSyncText(source: SourceFreshness, now: number): string {
67
76
  const state = source.sync?.state;
68
77
  if (state === 'passive') return '—';
69
78
  if (state === 'reauth') return 'After you reconnect';
79
+ if (state === 'connecting') return '—';
70
80
  if (source.sync && !source.sync.nextSyncAt) return 'Not scheduled';
71
81
  return ahead(source.sync?.nextSyncAt, now);
72
82
  }
@@ -104,7 +114,13 @@ export function SourcesTable({
104
114
  return (
105
115
  <tr key={source.source}>
106
116
  <th scope="row" className={`${td} text-left font-medium`}>{source.label}</th>
107
- <td className={attention ? `${td} font-medium text-amber-700 dark:text-amber-400` : td}>{statusText(source)}</td>
117
+ <td className={attention ? `${td} font-medium text-amber-700 dark:text-amber-400` : td}>{statusText(source)}
118
+ {reasonText(source) ? (
119
+ <span className="block max-w-xs whitespace-normal text-xs font-normal text-gray-600 dark:text-gray-300" data-sync-reason>
120
+ {reasonText(source)}
121
+ </span>
122
+ ) : null}
123
+ </td>
108
124
  <td className={`${td} text-right tabular-nums`}>{records === null ? '—' : records}
109
125
  {source.sync?.windowDays ? (
110
126
  <span className="block whitespace-nowrap text-xs font-normal text-gray-500 dark:text-gray-400">last {source.sync.windowDays} days</span>
@@ -95,10 +95,17 @@ export async function generateBriefing(deps: BriefingDeps, request: BriefingRequ
95
95
  const now = clock();
96
96
  const ttl = Math.min(deps.audioTtlSeconds ?? DEFAULT_TTL, 600);
97
97
  const store = deps.store ?? createEntityBriefingStore(deps.http, deps.ownerSub);
98
- const timeZone = request.timeZone ?? deps.timeZone ?? (await rememberedTimeZone(store, deps.ownerSub, now)) ?? 'UTC';
98
+ // The zone lookup, the to-do read and the open-question count do not depend on each other:
99
+ // overlap them so a cold call pays one tenant round trip here, not three-plus.
100
+ const givenZone = request.timeZone ?? deps.timeZone;
101
+ const [rememberedZone, items, unsure] = await Promise.all([
102
+ givenZone ? undefined : rememberedTimeZone(store, deps.ownerSub, now),
103
+ deps.loadItems(),
104
+ deps.unsureCount?.().catch(() => 0) ?? 0,
105
+ ]);
106
+ const timeZone = givenZone ?? rememberedZone ?? 'UTC';
99
107
 
100
- const composed = composeBriefing(await deps.loadItems(), { ownerSub: deps.ownerSub, now, timeZone });
101
- const unsure = await deps.unsureCount?.().catch(() => 0) ?? 0;
108
+ const composed = composeBriefing(items, { ownerSub: deps.ownerSub, now, timeZone });
102
109
  const briefing = unsure > 0 ? { ...composed, unsure } : composed;
103
110
  const hash = briefingContentHash(briefing);
104
111
  const externalId = briefingExternalId(deps.ownerSub, briefing.context.localDate);
@@ -13,12 +13,12 @@ const utcDate = (ms: number) => new Date(ms).toISOString().slice(0, 10);
13
13
  export async function rememberedTimeZone(
14
14
  store: Pick<BriefingStore, 'find'>, ownerSub: string, now: number,
15
15
  ): Promise<string | undefined> {
16
- for (const offset of [1, 0, -1, -2, -3]) {
16
+ // Looked up together (one round trip of wall time, not five); the nearest day with a zone still wins.
17
+ const zones = await Promise.all([1, 0, -1, -2, -3].map(async (offset) => {
17
18
  try {
18
19
  const row = await store.find(briefingExternalId(ownerSub, utcDate(now + offset * DAY)));
19
- const zone = row?.context?.timeZone;
20
- if (zone) return zone;
21
- } catch { /* a lookup failure only costs the fallback */ }
22
- }
23
- return undefined;
20
+ return row?.context?.timeZone as string | undefined;
21
+ } catch { return undefined; /* a lookup failure only costs the fallback */ }
22
+ }));
23
+ return zones.find(Boolean);
24
24
  }
@@ -2,9 +2,8 @@
2
2
  * THE CLIENT CORPUS FOR TRANSLATION — glossary and translation memory
3
3
  * (bd startsim-ppfl RED / bd startsim-364c GREEN).
4
4
  *
5
- * CONTRACT AND STUBS ONLY. Every function throws `NotImplementedError`, so the
6
- * tests in `../__tests__/translation-corpus.test.ts` fail on missing BEHAVIOUR
7
- * rather than on a missing module.
5
+ * Pure functions over the generic `TenantEntity` envelope. The behaviour is
6
+ * pinned by `../__tests__/translation-corpus.test.ts`.
8
7
  *
9
8
  * ── WHY THIS LIVES IN THE CORPUS PACKAGE ───────────────────────────────────
10
9
  * `startsim-3o4e` decides the whole mechanism is glossary + translation-memory
@@ -34,6 +33,8 @@
34
33
  * DOCUMENT. So every read here is scope-partitioned and every drop is counted.
35
34
  */
36
35
 
36
+ import { enforceScope, isInScope } from './retrieval';
37
+ import { jaccard, tokenize, words } from './text';
37
38
  import type { CorpusPage, CorpusScope, SourceDocument } from './types';
38
39
 
39
40
  /**
@@ -108,13 +109,6 @@ export interface TenantEntityWrite {
108
109
  data: Record<string, unknown>;
109
110
  }
110
111
 
111
- export class NotImplementedError extends Error {
112
- constructor(what: string) {
113
- super(`${what} is not implemented (bd startsim-ppfl is RED; bd startsim-364c implements it)`);
114
- this.name = 'NotImplementedError';
115
- }
116
- }
117
-
118
112
  // ---------------------------------------------------------------------------
119
113
  // ingestion
120
114
  // ---------------------------------------------------------------------------
@@ -132,10 +126,25 @@ export interface IngestOptions {
132
126
  * mapper in this package.
133
127
  */
134
128
  export function ingestForTranslation(
135
- _document: SourceDocument,
136
- _options: IngestOptions,
129
+ document: SourceDocument,
130
+ options: IngestOptions,
137
131
  ): TenantEntityWrite[] {
138
- throw new NotImplementedError('ingestForTranslation');
132
+ const typeKeys = options.typeKeys ?? TRANSLATION_TYPE_KEYS;
133
+ return [
134
+ {
135
+ entity_type: typeKeys.sourceDocument,
136
+ external_id: `translation:document:${document.id}`,
137
+ name: document.title || document.id,
138
+ data: {
139
+ body: document.body,
140
+ summary: document.summary ?? '',
141
+ source: document.source,
142
+ source_ref: document.sourceRef,
143
+ occurred_at: document.occurredAt,
144
+ org_id: options.scope.orgId,
145
+ },
146
+ },
147
+ ];
139
148
  }
140
149
 
141
150
  // ---------------------------------------------------------------------------
@@ -160,18 +169,74 @@ export interface ExtractTermsOptions {
160
169
  * module that produces an `approved` term without a human verdict.
161
170
  */
162
171
  export function extractTermCandidates(
163
- _documents: readonly SourceDocument[],
164
- _options: ExtractTermsOptions,
172
+ documents: readonly SourceDocument[],
173
+ options: ExtractTermsOptions,
165
174
  ): GlossaryTermRecord[] {
166
- throw new NotImplementedError('extractTermCandidates');
175
+ const minOccurrences = options.minOccurrences ?? 2;
176
+ const maxCandidates = options.maxCandidates ?? 50;
177
+ const ruledOn = new Set(
178
+ (options.known ?? [])
179
+ .filter((t) => t.sourceLocale === options.sourceLocale && t.targetLocale === options.targetLocale)
180
+ .map((t) => t.sourceTerm.toLowerCase()),
181
+ );
182
+
183
+ const counts = new Map<string, { occurrences: number; documentIds: Set<string> }>();
184
+ for (const document of documents) {
185
+ if (!isInScope(document, options.scope)) continue; // the same guard as every other read
186
+ for (const chunk of phraseChunks(document.body)) {
187
+ for (let size = 2; size <= 3; size += 1) {
188
+ for (let at = 0; at + size <= chunk.length; at += 1) {
189
+ const phrase = chunk.slice(at, at + size).join(' ');
190
+ const entry = counts.get(phrase) ?? { occurrences: 0, documentIds: new Set<string>() };
191
+ entry.occurrences += 1;
192
+ entry.documentIds.add(document.id);
193
+ counts.set(phrase, entry);
194
+ }
195
+ }
196
+ }
197
+ }
198
+
199
+ const frequent = [...counts.entries()].filter(
200
+ ([phrase, entry]) => entry.occurrences >= minOccurrences && !ruledOn.has(phrase),
201
+ );
202
+ // "settlement agreement" inside "settlement agreement signed" at the same count is one term, not two.
203
+ const kept = frequent.filter(
204
+ ([phrase, entry]) =>
205
+ !frequent.some(
206
+ ([other, o]) => other !== phrase && o.occurrences === entry.occurrences && ` ${other} `.includes(` ${phrase} `) && other.length > phrase.length,
207
+ ),
208
+ );
209
+
210
+ return kept
211
+ .sort((a, b) => b[1].occurrences - a[1].occurrences || a[0].localeCompare(b[0]))
212
+ .slice(0, maxCandidates)
213
+ .map(([phrase, entry]) => ({
214
+ id: `term:${options.sourceLocale}:${options.targetLocale}:${phrase.replace(/\s+/g, '-')}`,
215
+ sourceLocale: options.sourceLocale,
216
+ targetLocale: options.targetLocale,
217
+ sourceTerm: phrase,
218
+ targetTerm: '',
219
+ status: 'candidate' as const,
220
+ occurrences: entry.occurrences,
221
+ documentIds: [...entry.documentIds],
222
+ scope: options.scope,
223
+ }));
167
224
  }
168
225
 
169
226
  /** Record a human's verdict. The ONLY route from `candidate` to `approved`. */
170
227
  export function applyTermVerdict(
171
- _term: GlossaryTermRecord,
172
- _verdict: { status: 'approved' | 'rejected'; targetTerm?: string; doNotTranslate?: boolean },
228
+ term: GlossaryTermRecord,
229
+ verdict: { status: 'approved' | 'rejected'; targetTerm?: string; doNotTranslate?: boolean },
173
230
  ): GlossaryTermRecord {
174
- throw new NotImplementedError('applyTermVerdict');
231
+ if (verdict.status === 'rejected') {
232
+ return { ...term, status: 'rejected' };
233
+ }
234
+ const doNotTranslate = verdict.doNotTranslate ?? term.doNotTranslate ?? false;
235
+ const targetTerm = doNotTranslate ? term.sourceTerm : (verdict.targetTerm ?? '').trim();
236
+ if (!targetTerm) {
237
+ throw new Error(`Approving "${term.sourceTerm}" needs a target term, or doNotTranslate`);
238
+ }
239
+ return { ...term, status: 'approved', targetTerm, doNotTranslate };
175
240
  }
176
241
 
177
242
  // ---------------------------------------------------------------------------
@@ -185,10 +250,17 @@ export function applyTermVerdict(
185
250
  * page, not the glossary) and status (so a candidate never reaches a model).
186
251
  */
187
252
  export function glossaryForSegment(
188
- _segmentText: string,
189
- _terms: readonly GlossaryTermRecord[],
253
+ segmentText: string,
254
+ terms: readonly GlossaryTermRecord[],
190
255
  ): GlossaryTermRecord[] {
191
- throw new NotImplementedError('glossaryForSegment');
256
+ const haystack = normalizeForMemory(segmentText);
257
+ return terms.filter((t) => {
258
+ if (t.status !== 'approved') return false;
259
+ const needle = normalizeForMemory(t.sourceTerm);
260
+ if (!needle) return false;
261
+ const pattern = new RegExp(`(?<![\\p{L}\\p{N}])${escapeRegExp(needle)}(?![\\p{L}\\p{N}])`, 'u');
262
+ return pattern.test(haystack);
263
+ });
192
264
  }
193
265
 
194
266
  // ---------------------------------------------------------------------------
@@ -200,8 +272,13 @@ export function glossaryForSegment(
200
272
  * bidi isolates stripped. A MATERIAL change — a different word, a different
201
273
  * number — must survive normalisation and defeat the match.
202
274
  */
203
- export function normalizeForMemory(_text: string): string {
204
- throw new NotImplementedError('normalizeForMemory');
275
+ export function normalizeForMemory(text: string): string {
276
+ return (text ?? '')
277
+ .replace(/[\u200e\u200f\u202a-\u202e\u2066-\u2069]/g, '')
278
+ .normalize('NFKC')
279
+ .replace(/\s+/g, ' ')
280
+ .trim()
281
+ .toLowerCase();
205
282
  }
206
283
 
207
284
  export interface MemoryLookupOptions {
@@ -212,11 +289,14 @@ export interface MemoryLookupOptions {
212
289
 
213
290
  /** An exact hit, or null. Costs nothing and makes no provider call. */
214
291
  export function exactMemoryHit(
215
- _segmentText: string,
216
- _units: readonly MemoryUnitRecord[],
217
- _options: MemoryLookupOptions,
292
+ segmentText: string,
293
+ units: readonly MemoryUnitRecord[],
294
+ options: MemoryLookupOptions,
218
295
  ): MemoryUnitRecord | null {
219
- throw new NotImplementedError('exactMemoryHit');
296
+ const wanted = normalizeForMemory(segmentText);
297
+ return (
298
+ servable(units, options).find((u) => u.sourceHash === wanted || normalizeForMemory(u.sourceText) === wanted) ?? null
299
+ );
220
300
  }
221
301
 
222
302
  export interface FuzzyMatch {
@@ -232,11 +312,17 @@ export interface FuzzyOptions extends MemoryLookupOptions {
232
312
 
233
313
  /** Neighbours, best first, capped. Offered to the model as EXAMPLES, never as answers. */
234
314
  export function fuzzyMemoryMatches(
235
- _segmentText: string,
236
- _units: readonly MemoryUnitRecord[],
237
- _options: FuzzyOptions,
315
+ segmentText: string,
316
+ units: readonly MemoryUnitRecord[],
317
+ options: FuzzyOptions,
238
318
  ): FuzzyMatch[] {
239
- throw new NotImplementedError('fuzzyMemoryMatches');
319
+ const query = tokenize(segmentText);
320
+ const minScore = options.minScore ?? 0.3;
321
+ return servable(units, options)
322
+ .map((unit) => ({ unit, score: jaccard(query, tokenize(unit.sourceText)) }))
323
+ .filter((m) => m.score >= minScore)
324
+ .sort((a, b) => b.score - a.score || a.unit.id.localeCompare(b.unit.id))
325
+ .slice(0, options.limit ?? 3);
240
326
  }
241
327
 
242
328
  /**
@@ -246,15 +332,27 @@ export function fuzzyMemoryMatches(
246
332
  * which is exactly the upkeep trap that makes people abandon tools."
247
333
  */
248
334
  export function memoryUnitFromReviewerEdit(
249
- _edit: {
335
+ edit: {
250
336
  sourceText: string;
251
337
  editedTargetText: string;
252
338
  sourceLocale: string;
253
339
  targetLocale: string;
254
340
  },
255
- _scope: CorpusScope,
341
+ scope: CorpusScope,
256
342
  ): MemoryUnitRecord {
257
- throw new NotImplementedError('memoryUnitFromReviewerEdit');
343
+ if (!edit.editedTargetText.trim()) throw new Error('A reviewer edit with no text is not memory');
344
+ const sourceHash = normalizeForMemory(edit.sourceText);
345
+ return {
346
+ id: `memory:${edit.sourceLocale}:${edit.targetLocale}:${sourceHash}`,
347
+ sourceLocale: edit.sourceLocale,
348
+ targetLocale: edit.targetLocale,
349
+ sourceText: edit.sourceText,
350
+ targetText: edit.editedTargetText,
351
+ sourceHash,
352
+ origin: 'reviewer_edit',
353
+ approved: true,
354
+ scope,
355
+ };
258
356
  }
259
357
 
260
358
  // ---------------------------------------------------------------------------
@@ -275,17 +373,19 @@ export interface ScopedRead<T> {
275
373
  * it should not have, the OUTPUT must still not contain it.
276
374
  */
277
375
  export function scopedTerms(
278
- _terms: readonly GlossaryTermRecord[],
279
- _scope: CorpusScope,
376
+ terms: readonly GlossaryTermRecord[],
377
+ scope: CorpusScope,
280
378
  ): ScopedRead<GlossaryTermRecord> {
281
- throw new NotImplementedError('scopedTerms');
379
+ const { kept, dropped } = enforceScope([...terms], scope);
380
+ return { kept, droppedOutOfScope: dropped.length };
282
381
  }
283
382
 
284
383
  export function scopedMemory(
285
- _units: readonly MemoryUnitRecord[],
286
- _scope: CorpusScope,
384
+ units: readonly MemoryUnitRecord[],
385
+ scope: CorpusScope,
287
386
  ): ScopedRead<MemoryUnitRecord> {
288
- throw new NotImplementedError('scopedMemory');
387
+ const { kept, dropped } = enforceScope([...units], scope);
388
+ return { kept, droppedOutOfScope: dropped.length };
289
389
  }
290
390
 
291
391
  // ---------------------------------------------------------------------------
@@ -312,10 +412,60 @@ export interface TranslationCorpusApi {
312
412
  }): Promise<CorpusPage<MemoryUnitRecord>>;
313
413
  }
314
414
 
315
- export function readAllGlossaryTerms(
316
- _api: TranslationCorpusApi,
317
- _scope: CorpusScope,
318
- _options?: { maxPages?: number },
415
+ export async function readAllGlossaryTerms(
416
+ api: TranslationCorpusApi,
417
+ scope: CorpusScope,
418
+ options?: { maxPages?: number },
319
419
  ): Promise<ScopedRead<GlossaryTermRecord>> {
320
- throw new NotImplementedError('readAllGlossaryTerms');
420
+ const maxPages = options?.maxPages ?? 50;
421
+ const all: GlossaryTermRecord[] = [];
422
+ for (let page = 1; ; page += 1) {
423
+ if (page > maxPages) {
424
+ throw new Error(`Glossary has more than ${maxPages} pages; refusing to return a truncated read`);
425
+ }
426
+ const read = await api.listGlossaryTerms({ page });
427
+ all.push(...read.results);
428
+ if (!read.next) break;
429
+ }
430
+ return scopedTerms(all, scope);
431
+ }
432
+
433
+ // ---------------------------------------------------------------------------
434
+ // helpers
435
+ // ---------------------------------------------------------------------------
436
+
437
+ function escapeRegExp(value: string): string {
438
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
439
+ }
440
+
441
+ /**
442
+ * Runs of adjacent content words, broken at punctuation and at stopwords, so a
443
+ * phrase never spans a clause boundary or a "the".
444
+ */
445
+ function phraseChunks(text: string): string[][] {
446
+ const chunks: string[][] = [];
447
+ for (const clause of (text ?? '').toLowerCase().split(/[.!?;:,()\n]+/)) {
448
+ let run: string[] = [];
449
+ for (const token of clause.match(/[a-z0-9][a-z0-9'&\-/]*/g) ?? []) {
450
+ const [content] = words(token);
451
+ if (content) run.push(content);
452
+ else if (run.length) {
453
+ chunks.push(run);
454
+ run = [];
455
+ }
456
+ }
457
+ if (run.length) chunks.push(run);
458
+ }
459
+ return chunks;
460
+ }
461
+
462
+ /** Approved, in scope, and the right language pair: the only units memory may serve. */
463
+ function servable(units: readonly MemoryUnitRecord[], options: MemoryLookupOptions): MemoryUnitRecord[] {
464
+ return units.filter(
465
+ (u) =>
466
+ u.approved &&
467
+ u.sourceLocale === options.sourceLocale &&
468
+ u.targetLocale === options.targetLocale &&
469
+ isInScope(u, options.scope),
470
+ );
321
471
  }
@@ -193,7 +193,7 @@ export interface MoneyEvent {
193
193
  * wrong, so the Library states it per source and the Ask surface repeats it.
194
194
  */
195
195
  export interface SourceSync {
196
- state: 'ok' | 'limited' | 'failing' | 'reauth' | 'waiting' | 'passive';
196
+ state: 'ok' | 'limited' | 'failing' | 'reauth' | 'connecting' | 'syncing' | 'waiting' | 'passive';
197
197
  /** One sentence the server wrote; '' when there is nothing to add. */
198
198
  note: string;
199
199
  records: number;