@startsimpli/integrations 0.2.217 → 0.2.219

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.217",
3
+ "version": "0.2.219",
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",
53
+ "@startsimpli/utils": "^0.4.21",
54
54
  "@startsimpli/auth": "^0.4.62",
55
- "@startsimpli/utils": "^0.4.21"
55
+ "@startsimpli/ui": "^0.4.208"
56
56
  },
57
57
  "peerDependenciesMeta": {
58
58
  "react": {
@@ -55,3 +55,27 @@ describe('FleetPage', () => {
55
55
  await waitFor(() => expect(screen.getByTestId('load-error')).toBeTruthy());
56
56
  });
57
57
  });
58
+
59
+ describe('FleetPage sync health', () => {
60
+ it('shows one row per leg from the connections, with todo-sync from the snapshot', async () => {
61
+ const now = new Date().toISOString();
62
+ const load = async () => payload({ snapshot: { text: 'n', updatedAt: now, view, todoSync: { at: now, ok: false, closed: 0, error: 'relay login expired' } } });
63
+ const loadConnections = async () => ({ results: [{ id: 'lin', connector_name: 'Linear', sync: { state: 'ok' }, sync_status: { status: 'ok', last_pull_at: now, last_push_at: now, pending_count: 3, out_of_sync: true } }] });
64
+ render(<FleetPage load={load} loadConnections={loadConnections} />);
65
+ await waitFor(() => expect(screen.getByTestId('sync-leg-lin:push')).toBeTruthy());
66
+ expect(screen.getByTestId('sync-leg-lin:push').textContent).toContain('3 waiting to send');
67
+ expect(screen.getByTestId('sync-leg-lin:push').getAttribute('data-state')).toBe('behind');
68
+ expect(screen.getByTestId('sync-leg-todo-sync').textContent).toContain('relay login expired');
69
+ });
70
+
71
+ it('says so when the connections cannot be read', async () => {
72
+ render(<FleetPage load={async () => payload()} loadConnections={async () => { throw new Error('401'); }} />);
73
+ await waitFor(() => expect(screen.getByTestId('sync-health-error').textContent).toContain('401'));
74
+ });
75
+
76
+ it('shows no sync card when the mount does not pass connections', async () => {
77
+ render(<FleetPage load={async () => payload()} />);
78
+ await waitFor(() => expect(screen.getByTestId('fleet-relay')).toBeTruthy());
79
+ expect(screen.queryByTestId('fleet-sync-health')).toBeNull();
80
+ });
81
+ });
@@ -32,7 +32,7 @@ describe('fleet inputs for the /fleet page', () => {
32
32
  it('reads roles.md, the loops ledger and the raw bridge listing; leaves out what is missing', async () => {
33
33
  const dir = mkdtempSync(join(tmpdir(), 'rc-'));
34
34
  writeFileSync(join(dir, 'roles.md'), '| Role | s | n |');
35
- const env = { RELAY_ROLES_FILE: join(dir, 'roles.md'), RELAY_LOOPS_FILE: join(dir, 'nope.md'), RELAY_PORTS_FILE: join(dir, 'nope2.md') };
35
+ const env = { RELAY_ROLES_FILE: join(dir, 'roles.md'), RELAY_LOOPS_FILE: join(dir, 'nope.md'), RELAY_PORTS_FILE: join(dir, 'nope2.md'), TODO_SYNC_LAST_RUN: join(dir, 'nope3.json') };
36
36
  expect(await readFleetInputs(env, '[live] `a · b · 12345678` g')).toEqual({ roles: '| Role | s | n |', sessions: '[live] `a · b · 12345678` g' });
37
37
  });
38
38
  });
@@ -0,0 +1,44 @@
1
+ // @vitest-environment jsdom
2
+ import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
3
+ import * as React from 'react';
4
+ import { afterEach, describe, expect, it, vi } from 'vitest';
5
+
6
+ import { ShareDefaultRow, parse, valueOf } from '../components/pages/connections/ShareDefaultRow';
7
+
8
+ afterEach(cleanup);
9
+ const cn = { muted: 'm', error: 'e' };
10
+ const connection = { id: 'c1', share_default: null } as never;
11
+
12
+ describe('ShareDefaultRow', () => {
13
+ it('says only me by default and offers the organisation and its teams', async () => {
14
+ const api = {
15
+ updateConnectionSharing: vi.fn(async () => ({}) as never),
16
+ shareTeams: vi.fn(async () => [{ slug: 'editorial', name: 'Editorial' }]),
17
+ };
18
+ const changed = vi.fn();
19
+ render(<ShareDefaultRow api={api} connection={connection} classNames={cn} onChanged={changed} />);
20
+ expect((screen.getByLabelText('Records are shared with') as HTMLSelectElement).value).toBe('none');
21
+ await waitFor(() => expect(screen.getByText('Editorial (team)')).toBeTruthy());
22
+ fireEvent.change(screen.getByLabelText('Records are shared with'), { target: { value: 'org' } });
23
+ await waitFor(() => expect(api.updateConnectionSharing).toHaveBeenCalledWith('c1', { kind: 'org' }));
24
+ await waitFor(() => expect(changed).toHaveBeenCalled());
25
+ });
26
+
27
+ it('turns it off with null and shows a failure', async () => {
28
+ const api = { updateConnectionSharing: vi.fn(async () => { throw new Error('tenant down'); }) };
29
+ render(<ShareDefaultRow api={api as never} connection={{ id: 'c1', share_default: { kind: 'org' } } as never} classNames={cn} onChanged={vi.fn()} />);
30
+ fireEvent.change(screen.getByLabelText('Records are shared with'), { target: { value: 'none' } });
31
+ await waitFor(() => expect(api.updateConnectionSharing).toHaveBeenCalledWith('c1', null));
32
+ expect(await screen.findByRole('alert')).toBeTruthy();
33
+ });
34
+
35
+ it('renders nothing for a client without the verb', () => {
36
+ const { container } = render(<ShareDefaultRow api={{}} connection={connection} classNames={cn} onChanged={vi.fn()} />);
37
+ expect(container.textContent).toBe('');
38
+ });
39
+
40
+ it('maps values both ways', () => {
41
+ expect(parse(valueOf({ kind: 'group', id: 'a:b' }))).toEqual({ kind: 'group', id: 'a:b' });
42
+ expect(parse(valueOf(null))).toBeNull();
43
+ });
44
+ });
@@ -76,3 +76,12 @@ describe('sharing client', () => {
76
76
  expect(c.teams).toEqual([]);
77
77
  });
78
78
  });
79
+
80
+ describe('sharing client with a camelizing http client', () => {
81
+ it('reads mayShare and subjectType', async () => {
82
+ const http = { get: vi.fn(async () => ({ mayShare: true, results: [{ id: '1', subjectType: 'group', subjectId: 'editorial', level: 'viewer' }] })) };
83
+ const r = await listRecordShares(http as never, 'd');
84
+ expect(r.canShare).toBe(true);
85
+ expect(r.shares[0]).toMatchObject({ kind: 'group', subjectId: 'editorial' });
86
+ });
87
+ });
@@ -0,0 +1,70 @@
1
+ import { describe, expect, it } from 'vitest';
2
+
3
+ import { buildSyncHealth, type SyncConnectionInput } from '../corpus/converse/sync-health';
4
+
5
+ const NOW = Date.parse('2026-11-26T12:00:00Z');
6
+ const ago = (min: number) => new Date(NOW - min * 60000).toISOString();
7
+ const conn = (over: Partial<SyncConnectionInput>): SyncConnectionInput => ({ id: 'c1', connector_name: 'Gmail', ...over });
8
+ const sync = (over: Record<string, unknown>) => ({ state: 'ok', note: '', records: 10, last_attempt_at: ago(5), last_success_at: ago(5), next_sync_at: new Date(NOW + 600000).toISOString(), interval_minutes: 15, ...over });
9
+ const rows = (c: SyncConnectionInput[], todo: Parameters<typeof buildSyncHealth>[1] = { at: ago(3), ok: true, closed: 0, error: '' }) => buildSyncHealth(c, todo, NOW);
10
+
11
+ describe('buildSyncHealth', () => {
12
+ it('a clean connector is one ok leg with last-success and lag', () => {
13
+ const [leg] = rows([conn({ sync: sync({}) })]).filter((l) => l.key === 'c1');
14
+ expect(leg).toMatchObject({ label: 'Gmail', state: 'ok', lastOkAt: ago(5), lagMs: 5 * 60000, lastError: '' });
15
+ });
16
+
17
+ it('a failing connector carries the scrubbed last error', () => {
18
+ const [leg] = rows([conn({ sync: sync({ state: 'failing', note: 'The last sync did not finish; it will try again' }), last_error: 'Quota exhausted' })]).filter((l) => l.key === 'c1');
19
+ expect(leg).toMatchObject({ state: 'failing', lastError: 'Quota exhausted' });
20
+ });
21
+
22
+ it('limited reads as behind with the retry time; reauth and waiting keep their own state', () => {
23
+ const out = rows([
24
+ conn({ id: 'a', sync: sync({ state: 'limited', note: 'The provider is limiting requests' }) }),
25
+ conn({ id: 'b', sync: sync({ state: 'reauth', note: 'Reconnect this account' }) }),
26
+ conn({ id: 'c', sync: sync({ state: 'waiting', last_success_at: null, last_attempt_at: null }) }),
27
+ ]);
28
+ const by = Object.fromEntries(out.map((l) => [l.key, l]));
29
+ expect(by.a.state).toBe('behind');
30
+ expect(by.b.state).toBe('reauth');
31
+ expect(by.c).toMatchObject({ state: 'waiting', lastOkAt: null, lagMs: null });
32
+ });
33
+
34
+ it('an ok connector whose next sync is long overdue is stale, not ok', () => {
35
+ const [leg] = rows([conn({ sync: sync({ next_sync_at: ago(60), interval_minutes: 15 }) })]).filter((l) => l.key === 'c1');
36
+ expect(leg.state).toBe('stale');
37
+ });
38
+
39
+ it('passive connectors are shown but never alarm', () => {
40
+ const [leg] = rows([conn({ sync: sync({ state: 'passive', note: 'Receives data only when sent' }) })]).filter((l) => l.key === 'c1');
41
+ expect(leg.state).toBe('passive');
42
+ });
43
+
44
+ it('a task tracker splits into a pull leg and a push leg with rows behind', () => {
45
+ const out = rows([conn({ id: 'lin', connector_name: 'Linear', sync: sync({}), sync_status: { status: 'ok', last_pull_at: ago(2), last_push_at: ago(40), pending_count: 4, out_of_sync: true, last_error: '', retry_at: null } })]);
46
+ const pull = out.find((l) => l.key === 'lin:pull')!;
47
+ const push = out.find((l) => l.key === 'lin:push')!;
48
+ expect(pull).toMatchObject({ label: 'Linear pull', state: 'ok', lastOkAt: ago(2) });
49
+ expect(push).toMatchObject({ label: 'Linear push', state: 'behind', behind: 4, lastOkAt: ago(40) });
50
+ });
51
+
52
+ it('a failing task-tracker push shows the error and retry time', () => {
53
+ const out = rows([conn({ id: 'lin', connector_name: 'Linear', sync: sync({}), sync_status: { status: 'error', last_pull_at: ago(1), last_push_at: ago(90), pending_count: 2, out_of_sync: true, last_error: 'HTTP 500', retry_at: ago(-5) } })]);
54
+ expect(out.find((l) => l.key === 'lin:push')).toMatchObject({ state: 'failing', lastError: 'HTTP 500', retryAt: ago(-5), behind: 2 });
55
+ });
56
+
57
+ it('todo-sync: never reported is waiting, recent is ok, old is stale, failed is failing', () => {
58
+ const t = (todo: Parameters<typeof rows>[1]) => rows([], todo).find((l) => l.key === 'todo-sync')!;
59
+ expect(t(null)).toMatchObject({ state: 'waiting', lastOkAt: null });
60
+ expect(t({ at: ago(4), ok: true, closed: 2, error: '' })).toMatchObject({ state: 'ok', lastOkAt: ago(4), lagMs: 4 * 60000 });
61
+ expect(t({ at: ago(45), ok: true, closed: 0, error: '' }).state).toBe('stale');
62
+ expect(t({ at: ago(2), ok: false, closed: 0, error: 'relay login expired' })).toMatchObject({ state: 'failing', lastError: 'relay login expired' });
63
+ });
64
+
65
+ it('puts the worst legs first', () => {
66
+ const out = rows([conn({ id: 'ok', sync: sync({}) }), conn({ id: 'bad', sync: sync({ state: 'failing' }) })], null);
67
+ expect(out[0].key).toBe('bad');
68
+ expect(out.at(-1)!.state).not.toBe('failing');
69
+ });
70
+ });
package/src/api/_fetch.ts CHANGED
@@ -43,7 +43,7 @@ export function setAuthTokenProvider(
43
43
  }
44
44
 
45
45
  export interface RequestOptions {
46
- method?: 'GET' | 'POST' | 'PATCH' | 'DELETE';
46
+ method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
47
47
  body?: unknown;
48
48
  query?: Record<string, string | number | boolean | undefined | null>;
49
49
  headers?: Record<string, string>;
@@ -45,6 +45,7 @@ import type {
45
45
  ConnectorCatalogEntry,
46
46
  MemberConnectionsApi,
47
47
  OAuthStart,
48
+ ShareDefault,
48
49
  } from '../components/pages/types';
49
50
  import { createRequester, request, type ClientDeps, type Requester } from './_fetch';
50
51
 
@@ -217,6 +218,19 @@ function build(request: Requester): MemberConnectionsApi {
217
218
  });
218
219
  },
219
220
 
221
+ /** Who this account's records are shared with; `null` is private again (Todo ENG-158). */
222
+ updateConnectionSharing(id: string, share: ShareDefault | null): Promise<Connection> {
223
+ return request<Connection>(`${BASE}/${id}/sharing/`, {
224
+ method: 'PUT', body: { share_default: share },
225
+ });
226
+ },
227
+
228
+ /** The teams a default can name: those of the caller's own organisation. */
229
+ async shareTeams(): Promise<Array<{ slug: string; name: string }>> {
230
+ const body = await request<{ results?: Array<{ slug: string; name: string }> }>(`${BASE}/share-teams/`);
231
+ return body.results ?? [];
232
+ },
233
+
220
234
  /**
221
235
  * DISCONNECT, not delete. One transaction stops the scheduled fetches, revokes
222
236
  * every token issued for the account and deletes the stored credential; the
@@ -79,6 +79,7 @@ export { DecisionsPage } from './pages/DecisionsPage';
79
79
  export type { DecisionsPageProps, DecisionsClassNames } from './pages/DecisionsPage';
80
80
  export { FleetPage } from './pages/FleetPage';
81
81
  export type { FleetPageProps, FleetPayload } from './pages/FleetPage';
82
+ export { SyncHealthCard } from './pages/SyncHealthCard';
82
83
  export type { VoiceRecordButtonProps, VoiceRecordClassNames } from './pages/VoiceRecordButton';
83
84
  export * from './pages/home';
84
85
  export * from './pages/questions';
@@ -9,10 +9,17 @@ import * as React from 'react';
9
9
 
10
10
  import { ageWords, FLEET_FRESH_MS } from '../../corpus/converse/fleet';
11
11
  import type { FleetSession, FleetView } from '../../corpus/converse/fleet-view';
12
+ import { buildSyncHealth, type SyncConnectionInput, type TodoSyncRecord } from '../../corpus/converse/sync-health';
13
+ import { SyncHealthCard } from './SyncHealthCard';
12
14
  import { LoadError } from '../LoadError';
13
15
 
14
- export interface FleetPayload { snapshot: { text: string; updatedAt: string; view: FleetView | null } | null }
15
- export interface FleetPageProps { load: () => Promise<FleetPayload>; refreshMs?: number }
16
+ export interface FleetPayload { snapshot: { text: string; updatedAt: string; view: FleetView | null; todoSync?: TodoSyncRecord | null } | null }
17
+ export interface FleetPageProps {
18
+ load: () => Promise<FleetPayload>;
19
+ /** The member's own connections (`connectionsMe.connections`); when given, the page shows one Sync health row per leg. */
20
+ loadConnections?: () => Promise<{ results: SyncConnectionInput[] }>;
21
+ refreshMs?: number;
22
+ }
16
23
 
17
24
  function SessionRow({ s, testId }: { s: FleetSession; testId?: string }) {
18
25
  return (
@@ -91,16 +98,21 @@ function FleetBody({ view }: { view: FleetView }) {
91
98
  );
92
99
  }
93
100
 
94
- export function FleetPage({ load, refreshMs = 30000 }: FleetPageProps) {
101
+ export function FleetPage({ load, loadConnections, refreshMs = 30000 }: FleetPageProps) {
95
102
  const [data, setData] = React.useState<FleetPayload | undefined>();
103
+ const [conns, setConns] = React.useState<SyncConnectionInput[] | undefined>();
104
+ const [connsError, setConnsError] = React.useState<string | null>(null);
96
105
  const [error, setError] = React.useState<string | null>(null);
97
106
  const [, tick] = React.useState(0);
98
- const run = React.useCallback(() => { load().then((d) => { setData(d); setError(null); }).catch((e) => setError(e instanceof Error ? e.message : 'Could not load.')); }, [load]);
107
+ const run = React.useCallback(() => { load().then((d) => { setData(d); setError(null); }).catch((e) => setError(e instanceof Error ? e.message : 'Could not load.'));
108
+ loadConnections?.().then((c) => { setConns(c.results); setConnsError(null); }).catch((e) => setConnsError(e instanceof Error ? e.message : 'Could not load.')); }, [load, loadConnections]);
99
109
  React.useEffect(() => { run(); const t = setInterval(() => { run(); tick((n) => n + 1); }, refreshMs); return () => clearInterval(t); }, [run, refreshMs]);
100
110
  const snap = data?.snapshot;
101
111
  const stale = snap ? Date.now() - Date.parse(snap.updatedAt) > FLEET_FRESH_MS : false;
112
+ const legs = React.useMemo(() => (conns ? buildSyncHealth(conns, snap?.todoSync ?? null, Date.now()) : null), [conns, snap, data]);
102
113
  return (
103
114
  <div className="space-y-4">
115
+ {loadConnections ? <SyncHealthCard legs={legs} error={connsError} /> : null}
104
116
  {error ? <LoadError what="the fleet" message={error} onRetry={run} /> : null}
105
117
  {data && !snap ? <div className="rounded-xl border border-gray-200 bg-white p-6 text-center" data-testid="fleet-empty"><p className="font-medium text-gray-900">The relay has not posted a fleet snapshot yet.</p></div> : null}
106
118
  {snap ? (
@@ -0,0 +1,42 @@
1
+ 'use client';
2
+
3
+ /** Sync health (Fleet page): one row per sync leg, worst first. Draws `buildSyncHealth`; owns no logic. */
4
+ import * as React from 'react';
5
+
6
+ import type { LegState, SyncLeg } from '../../corpus/converse/sync-health';
7
+
8
+ const DOT: Record<LegState, string> = { ok: 'bg-green-500', behind: 'bg-amber-500', stale: 'bg-amber-500', failing: 'bg-red-500', reauth: 'bg-red-500', waiting: 'bg-gray-300', passive: 'bg-gray-300' };
9
+ const WORD: Record<LegState, string> = { ok: 'OK', behind: 'Behind', stale: 'Overdue', failing: 'Failing', reauth: 'Reconnect', waiting: 'Not run yet', passive: 'Receive-only' };
10
+
11
+ export function lagWords(ms: number | null): string {
12
+ if (ms === null) return 'never';
13
+ const m = Math.round(ms / 60000);
14
+ if (m < 1) return 'just now';
15
+ if (m < 60) return `${m} min ago`;
16
+ const h = Math.round(m / 60);
17
+ return h < 36 ? `${h} h ago` : `${Math.round(h / 24)} d ago`;
18
+ }
19
+
20
+ export function SyncHealthCard({ legs, error }: { legs: SyncLeg[] | null; error?: string | null }) {
21
+ const bad = legs?.filter((l) => l.state === 'failing' || l.state === 'reauth' || l.state === 'stale' || l.state === 'behind').length ?? 0;
22
+ return (
23
+ <section className={`rounded-xl border p-4 ${bad ? 'border-amber-300 bg-amber-50' : 'border-gray-200 bg-white'}`} data-testid="fleet-sync-health">
24
+ <h2 className="mb-1 text-sm font-semibold uppercase tracking-wide text-gray-500">Sync health{legs ? ` (${bad ? `${bad} need a look` : 'all fine'})` : ''}</h2>
25
+ {error ? <p className="text-sm text-red-700" data-testid="sync-health-error">Could not read the connections: {error}</p> : null}
26
+ {!legs && !error ? <p className="text-sm text-gray-500">Loading…</p> : null}
27
+ {legs ? (
28
+ <ul className="divide-y divide-gray-100 text-sm">
29
+ {legs.map((l) => (
30
+ <li key={l.key} className="flex flex-wrap items-baseline gap-x-2 py-1.5" data-testid={`sync-leg-${l.key}`} data-state={l.state}>
31
+ <span className={`h-2 w-2 shrink-0 self-center rounded-full ${DOT[l.state]}`} />
32
+ <span className="font-medium text-gray-900">{l.label}</span>
33
+ <span className="text-gray-700">{WORD[l.state]}</span>
34
+ <span className="text-xs text-gray-500">last ok {lagWords(l.lagMs)}{l.behind ? ` · ${l.behind} waiting to send` : ''}{l.retryAt ? ` · retries ${new Date(l.retryAt).toLocaleTimeString()}` : ''}</span>
35
+ {l.lastError ? <span className="w-full pl-4 text-xs text-red-700">{l.lastError}</span> : l.note && l.state !== 'ok' ? <span className="w-full pl-4 text-xs text-gray-500">{l.note}</span> : null}
36
+ </li>
37
+ ))}
38
+ </ul>
39
+ ) : null}
40
+ </section>
41
+ );
42
+ }
@@ -9,6 +9,7 @@ import { TaskTrackerSettings } from '../task-tracker/TaskTrackerSettings';
9
9
  import type { Connection, ConnectionChoice, ConnectionRun, ConnectionTarget, ConnectorAction, ConnectorCatalogEntry } from '../types';
10
10
  import { CapabilityPicker, orderCapabilities } from './CapabilityPicker';
11
11
  import { ConnectionSettingsForm, ReplaceKeyForm } from './ConnectionForms';
12
+ import { ShareDefaultRow } from './ShareDefaultRow';
12
13
  import type { BoundApi } from './bound-api';
13
14
  import { DEFAULTS, RUN_KIND_COPY } from './copy';
14
15
 
@@ -251,6 +252,10 @@ export function ConnectionCard({
251
252
  </div>
252
253
  </div>
253
254
 
255
+ {personal && api.updateConnectionSharing ? (
256
+ <ShareDefaultRow api={api} connection={connection} classNames={cn} onChanged={onChanged} />
257
+ ) : null}
258
+
254
259
  {activityOpen ? (
255
260
  <div className="mt-3 space-y-2 border-t pt-3" role="group"
256
261
  aria-label="Recent activity">
@@ -0,0 +1,91 @@
1
+ /**
2
+ * WHO THE RECORDS FROM THIS ACCOUNT ARE SHARED WITH (Todo ENG-158).
3
+ *
4
+ * One row on a person's own connection card, not a panel: "Only me", "Everyone in
5
+ * my organisation", or one of the organisation's teams. Changing it applies to
6
+ * what the account already brought in and to everything it brings later; turning
7
+ * it off takes back exactly what it shared, and never a share made by hand.
8
+ */
9
+ import * as React from 'react';
10
+
11
+ import type { Connection, MemberConnectionsApi, ShareDefault } from '../types';
12
+
13
+ type Slots = Record<'muted' | 'error', string>;
14
+ const SELECT = 'rounded-md border border-gray-300 bg-white px-2 py-1 text-sm text-gray-900';
15
+
16
+ const ONLY_ME = 'none';
17
+ const ORG = 'org';
18
+
19
+ export function valueOf(share: ShareDefault | null | undefined): string {
20
+ if (!share) return ONLY_ME;
21
+ return share.kind === 'org' ? ORG : `group:${share.id}`;
22
+ }
23
+
24
+ export function parse(value: string): ShareDefault | null {
25
+ if (value === ONLY_ME) return null;
26
+ if (value === ORG) return { kind: 'org' };
27
+ return { kind: 'group', id: value.slice('group:'.length) };
28
+ }
29
+
30
+ export function ShareDefaultRow({
31
+ api, connection, classNames: cn, onChanged,
32
+ }: {
33
+ api: Pick<MemberConnectionsApi, 'updateConnectionSharing' | 'shareTeams'>;
34
+ connection: Connection;
35
+ classNames: Slots;
36
+ onChanged: () => void;
37
+ }) {
38
+ const [teams, setTeams] = React.useState<Array<{ slug: string; name: string }>>([]);
39
+ const [busy, setBusy] = React.useState(false);
40
+ const [error, setError] = React.useState('');
41
+ const apiRef = React.useRef(api);
42
+ apiRef.current = api;
43
+
44
+ React.useEffect(() => {
45
+ let live = true;
46
+ apiRef.current.shareTeams?.()
47
+ .then((rows) => { if (live) setTeams(rows); })
48
+ .catch(() => { /* only the team options are lost */ });
49
+ return () => { live = false; };
50
+ }, []);
51
+
52
+ if (!api.updateConnectionSharing) return null;
53
+ const current = valueOf(connection.share_default);
54
+ const known = connection.share_default?.kind === 'group'
55
+ && !teams.some((t) => t.slug === (connection.share_default as { id: string }).id);
56
+
57
+ async function change(value: string) {
58
+ setBusy(true);
59
+ setError('');
60
+ try {
61
+ await api.updateConnectionSharing!(connection.id, parse(value));
62
+ onChanged();
63
+ } catch (err) {
64
+ setError((err as { message?: string })?.message || 'Sharing could not be changed.');
65
+ } finally {
66
+ setBusy(false);
67
+ }
68
+ }
69
+
70
+ return (
71
+ <div className="mt-2 flex flex-wrap items-center gap-2" data-testid="share-default">
72
+ <label className="text-sm font-medium text-gray-900" htmlFor={`share-${connection.id}`}>
73
+ Records are shared with
74
+ </label>
75
+ <select
76
+ id={`share-${connection.id}`}
77
+ className={SELECT}
78
+ disabled={busy}
79
+ value={current}
80
+ onChange={(e) => { void change(e.target.value); }}
81
+ >
82
+ <option value={ONLY_ME}>Only me</option>
83
+ <option value={ORG}>Everyone in my organisation</option>
84
+ {teams.map((t) => <option key={t.slug} value={`group:${t.slug}`}>{t.name} (team)</option>)}
85
+ {known ? <option value={current}>A team</option> : null}
86
+ </select>
87
+ {busy ? <span className={cn.muted}>Updating what it already brought in…</span> : null}
88
+ {error ? <p className={cn.error} role="alert">{error}</p> : null}
89
+ </div>
90
+ );
91
+ }
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * The injected api as the connection components use it (slugless), and the page props. Split out of ConnectionsPage (bd startsim-ovq7f) with no behaviour change.
3
3
  */
4
- import type { Connection, ConnectionChoicePage, ConnectionInvokeResult, ConnectionPermissions, ConnectionRun, ConnectionTarget, ConnectionsApi, ConnectorAction, ConnectorCatalogEntry, MemberConnectionRow, MemberConnectionsApi } from '../types';
4
+ import type { Connection, ConnectionChoicePage, ConnectionInvokeResult, ConnectionPermissions, ConnectionRun, ConnectionTarget, ConnectionsApi, ConnectorAction, ConnectorCatalogEntry, MemberConnectionRow, MemberConnectionsApi, ShareDefault } from '../types';
5
5
 
6
6
  export type ClassNames = Partial<Record<
7
7
  'root' | 'section' | 'heading' | 'card' | 'button' | 'muted' | 'error', string
@@ -71,6 +71,9 @@ export interface BoundApi {
71
71
  updateConnectionConfig?(
72
72
  id: string, config: Record<string, unknown>,
73
73
  ): Promise<Connection>;
74
+ /** Personal mode only: who this account's records are shared with (Todo ENG-158). */
75
+ updateConnectionSharing?(id: string, share: ShareDefault | null): Promise<Connection>;
76
+ shareTeams?(): Promise<Array<{ slug: string; name: string }>>;
74
77
  connectionChoices?(id: string, params?: { kind?: string; cursor?: string }):
75
78
  Promise<ConnectionChoicePage>;
76
79
  /** Task-tracker connections: sync now (bd startsim-el0zf). */
@@ -158,6 +158,8 @@ export interface Connection {
158
158
  sync?: Record<string, unknown>;
159
159
  /** Why the newest sync run failed or only partly worked, scrubbed; '' when it was clean. */
160
160
  last_error?: string;
161
+ /** Task-tracker connections only: the sync engine's snapshot (pull/push times, rows pending, last error, retry time). */
162
+ sync_status?: Record<string, unknown> | null;
161
163
  last_checked_at?: string | null;
162
164
  /**
163
165
  * WHAT THE SERVER WANTS THE PERSON WHO JUST SAVED TO KNOW. Present on the
@@ -169,8 +171,13 @@ export interface Connection {
169
171
  * connector does, so only the server can say it. Rendered verbatim.
170
172
  */
171
173
  notices?: string[];
174
+ /** Who this account's records are shared with beyond its owner; absent or null means only the owner. */
175
+ share_default?: ShareDefault | null;
172
176
  }
173
177
 
178
+ /** `org` is the owner's own organisation; `group` is one of its teams (by slug). */
179
+ export type ShareDefault = { kind: 'org' } | { kind: 'group'; id: string };
180
+
174
181
  /** What to RENDER, never what to allow. The server refuses on its own. */
175
182
  export interface ConnectionPermissions {
176
183
  view: boolean;
@@ -441,6 +448,10 @@ export interface MemberConnectionsApi {
441
448
  updateConnectionConfig?(
442
449
  id: string, config: Record<string, unknown>,
443
450
  ): Promise<Connection>;
451
+ /** Who this account's records are shared with (Todo ENG-158). `null` makes them private again. Optional for older clients. */
452
+ updateConnectionSharing?(id: string, share: ShareDefault | null): Promise<Connection>;
453
+ /** The teams a default can name (the owner's own organisation). Optional; without it only "my organisation" is offered. */
454
+ shareTeams?(): Promise<Array<{ slug: string; name: string }>>;
444
455
  checkConnection(id: string): Promise<{
445
456
  ok: boolean; account_label: string; detail: string; reason?: string; next_step?: string;
446
457
  }>;
@@ -3,7 +3,7 @@
3
3
  * `roles.md` (who leads what), the open-loops ledger (what waits on whom) and `bridge find ""` (who is live and what each
4
4
  * is for). This module is the ONE parser: relay -> role leads -> the sessions each lead owns, then everyone else.
5
5
  */
6
- export interface FleetInputs { roles?: string; loops?: string; sessions?: string; ports?: string }
6
+ export interface FleetInputs { roles?: string; loops?: string; sessions?: string; ports?: string; /** JSON: todo-sync's last-run record. */ todo_sync?: string }
7
7
  export interface FleetSection { title: string; items: string[] }
8
8
  export interface FleetPort { project: string; range: string; base: string; url: string | null; notes: string }
9
9
 
@@ -18,7 +18,7 @@ export interface FleetSnapshot { text: string; updatedAt: string; inputs?: Fleet
18
18
  export function cleanFleetInputs(raw: unknown): FleetInputs | undefined {
19
19
  if (!raw || typeof raw !== 'object') return undefined;
20
20
  const out: FleetInputs = {};
21
- for (const k of ['roles', 'loops', 'sessions', 'ports'] as const) {
21
+ for (const k of ['roles', 'loops', 'sessions', 'ports', 'todo_sync'] as const) {
22
22
  const v = (raw as Record<string, unknown>)[k];
23
23
  if (typeof v === 'string' && v.trim()) out[k] = v.slice(0, MAX_FLEET_INPUT);
24
24
  }
@@ -31,6 +31,8 @@ export { routeUtterance, parseRoute } from './route';
31
31
  export type { ConverseRoute } from './route';
32
32
  export { cleanFleetInputs, saveFleetSnapshot, loadFleetSnapshot, fleetExternalId, FLEET_SOURCE, ageWords, FLEET_FRESH_MS } from './fleet';
33
33
  export type { FleetSnapshot } from './fleet';
34
+ export { buildSyncHealth, parseTodoSyncRecord, todoSyncLeg, TODO_SYNC_STALE_MS } from './sync-health';
35
+ export type { LegState, SyncConnectionInput, SyncLeg, TodoSyncRecord } from './sync-health';
34
36
  export { buildFleetView, parseBridgeFind, parseLoops, parsePorts, parseRoles } from './fleet-view';
35
37
  export type { FleetInputs, FleetLead, FleetPort, FleetSection, FleetSession, FleetView, RoleRow } from './fleet-view';
36
38
  export { PASSED_TO_RELAY, NO_FLEET_STATUS, NO_FILLER } from './brain';
@@ -4,6 +4,7 @@
4
4
  * POST /corpus/converse/end JSON {conversation_id}
5
5
  * GET /corpus/converse/<id>/turn/<n>/audio[?who=user] a turn's recording, to its owner only
6
6
  */
7
+ import { parseTodoSyncRecord } from './sync-health';
7
8
  import { isTimeZone } from '../spoken-time';
8
9
  import { voiceErrorResponse } from '../voice-manage';
9
10
  import { handleConverseEnd, handleConverseTurn } from './handle';
@@ -150,7 +151,7 @@ export async function converseFleetStatusResponse(request: Request, deps: Conver
150
151
  export async function converseFleetViewResponse(deps: ConverseDeps): Promise<Response> {
151
152
  try {
152
153
  const snap = await loadFleetSnapshot(deps);
153
- const body = snap ? { snapshot: { text: snap.text, updatedAt: snap.updatedAt, view: snap.inputs ? buildFleetView(snap.inputs) : null } } : { snapshot: null };
154
+ const body = snap ? { snapshot: { text: snap.text, updatedAt: snap.updatedAt, view: snap.inputs ? buildFleetView(snap.inputs) : null, todoSync: parseTodoSyncRecord(snap.inputs?.todo_sync) } } : { snapshot: null };
154
155
  return Response.json(body, { headers: { 'cache-control': 'no-store' } });
155
156
  } catch (error) {
156
157
  return failure(error);
@@ -0,0 +1,96 @@
1
+ /**
2
+ * One row per sync leg for the Fleet page and the `todo-sync health` CLI (bd startsim-nghko.1). A pure fold over state the
3
+ * server already computes: `sync` (sync_summary) and `sync_status` (task_sync snapshot) on each member connection, plus the
4
+ * last-run record todo-sync writes on the Mac. No new alarm: the relay reads it on /fleet.
5
+ */
6
+ export type LegState = 'ok' | 'behind' | 'stale' | 'failing' | 'reauth' | 'waiting' | 'passive';
7
+
8
+ export interface SyncConnectionInput {
9
+ id: string;
10
+ connector_name?: string;
11
+ last_error?: string;
12
+ sync?: Record<string, unknown> | null;
13
+ sync_status?: Record<string, unknown> | null;
14
+ }
15
+ export interface TodoSyncRecord { at: string; ok: boolean; closed: number; error: string }
16
+ export interface SyncLeg {
17
+ key: string;
18
+ label: string;
19
+ state: LegState;
20
+ lastOkAt: string | null;
21
+ /** Milliseconds since the last success; null when it never succeeded. */
22
+ lagMs: number | null;
23
+ /** Rows still waiting to go out (push legs). */
24
+ behind: number;
25
+ lastError: string;
26
+ retryAt: string | null;
27
+ note: string;
28
+ }
29
+
30
+ /** todo-sync runs every 10 minutes (LaunchAgent); three missed runs is stale. */
31
+ export const TODO_SYNC_STALE_MS = 30 * 60000;
32
+ const ORDER: LegState[] = ['failing', 'reauth', 'stale', 'behind', 'waiting', 'ok', 'passive'];
33
+
34
+ const str = (v: unknown) => (typeof v === 'string' && v ? v : null);
35
+ const num = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) ? v : 0);
36
+ const lag = (at: string | null, now: number) => { const t = at ? Date.parse(at) : NaN; return Number.isFinite(t) ? Math.max(0, now - t) : null; };
37
+ const leg = (p: Partial<SyncLeg> & Pick<SyncLeg, 'key' | 'label' | 'state'>, now: number): SyncLeg => ({
38
+ lastOkAt: null, behind: 0, lastError: '', retryAt: null, note: '', ...p, lagMs: lag(p.lastOkAt ?? null, now),
39
+ });
40
+
41
+ function connectorLeg(c: SyncConnectionInput, now: number): SyncLeg {
42
+ const s = (c.sync ?? {}) as Record<string, unknown>;
43
+ const label = c.connector_name ?? c.id;
44
+ const lastOkAt = str(s.last_success_at);
45
+ const raw = String(s.state ?? 'waiting');
46
+ let state: LegState = raw === 'limited' ? 'behind' : (['ok', 'failing', 'reauth', 'waiting', 'passive'].includes(raw) ? (raw as LegState) : 'waiting');
47
+ const next = str(s.next_sync_at) ? Date.parse(String(s.next_sync_at)) : NaN;
48
+ const interval = num(s.interval_minutes) * 60000;
49
+ if (state === 'ok' && Number.isFinite(next) && interval && now - next > 2 * interval) state = 'stale';
50
+ return leg({
51
+ key: c.id, label, state, lastOkAt, note: String(s.note ?? ''),
52
+ lastError: state === 'failing' || state === 'reauth' ? (c.last_error || String(s.note ?? '')) : '',
53
+ retryAt: state === 'behind' ? str(s.next_sync_at) : null,
54
+ }, now);
55
+ }
56
+
57
+ function trackerLegs(c: SyncConnectionInput, now: number): SyncLeg[] {
58
+ const st = c.sync_status as Record<string, unknown>;
59
+ const label = c.connector_name ?? c.id;
60
+ const status = String(st.status ?? 'ok');
61
+ const error = String(st.last_error ?? '');
62
+ const retryAt = str(st.retry_at);
63
+ const pending = num(st.pending_count);
64
+ const broken = status === 'error' || status === 'needs_reauth';
65
+ const paused = status === 'rate_limited';
66
+ const pullAt = str(st.last_pull_at);
67
+ const pushAt = str(st.last_push_at);
68
+ const pull = leg({ key: `${c.id}:pull`, label: `${label} pull`, state: status === 'needs_reauth' ? 'reauth' : paused ? 'behind' : pullAt ? 'ok' : 'waiting', lastOkAt: pullAt, lastError: broken ? error : '', retryAt }, now);
69
+ const pushState: LegState = status === 'needs_reauth' ? 'reauth' : broken ? 'failing' : paused || (pending > 0 && st.out_of_sync) ? 'behind' : pushAt || !pending ? 'ok' : 'waiting';
70
+ const push = leg({ key: `${c.id}:push`, label: `${label} push`, state: pushState, lastOkAt: pushAt, behind: pending, lastError: broken || paused ? error : '', retryAt }, now);
71
+ return [pull, push];
72
+ }
73
+
74
+ export function todoSyncLeg(rec: TodoSyncRecord | null, now: number): SyncLeg {
75
+ const base = { key: 'todo-sync', label: 'todo-sync (to-dos closed by merged PRs)' };
76
+ if (!rec || !Number.isFinite(Date.parse(rec.at))) return leg({ ...base, state: 'waiting', note: 'Has not reported yet' }, now);
77
+ if (!rec.ok) return leg({ ...base, state: 'failing', lastError: rec.error || 'The last run failed', note: `Last tried ${rec.at}` }, now);
78
+ const old = now - Date.parse(rec.at) > TODO_SYNC_STALE_MS;
79
+ return leg({ ...base, state: old ? 'stale' : 'ok', lastOkAt: rec.at, note: old ? 'No run in over 30 minutes; the LaunchAgent may be off' : `Closed ${rec.closed} last run` }, now);
80
+ }
81
+
82
+ export function buildSyncHealth(connections: SyncConnectionInput[], todoSync: TodoSyncRecord | null, now: number): SyncLeg[] {
83
+ const legs = connections.flatMap((c) => (c.sync_status ? trackerLegs(c, now) : [connectorLeg(c, now)]));
84
+ legs.push(todoSyncLeg(todoSync, now));
85
+ return legs.map((l, i) => ({ l, i })).sort((a, b) => ORDER.indexOf(a.l.state) - ORDER.indexOf(b.l.state) || a.i - b.i).map((x) => x.l);
86
+ }
87
+
88
+ /** Parse the JSON string the relay sync carries in the fleet snapshot; null when absent or unreadable. */
89
+ export function parseTodoSyncRecord(raw: unknown): TodoSyncRecord | null {
90
+ try {
91
+ const o = typeof raw === 'string' ? JSON.parse(raw) : raw;
92
+ if (!o || typeof o !== 'object' || typeof (o as TodoSyncRecord).at !== 'string') return null;
93
+ const r = o as TodoSyncRecord;
94
+ return { at: r.at, ok: r.ok !== false, closed: Number(r.closed) || 0, error: String(r.error ?? '').slice(0, 300) };
95
+ } catch { return null; }
96
+ }
@@ -55,6 +55,9 @@ const DEFAULTS: Required<SharingPaths> = {
55
55
 
56
56
  type Obj = Record<string, unknown>;
57
57
  const str = (v: unknown) => (typeof v === 'string' ? v : '');
58
+ /** A key as the tenant spells it, or as a camelizing client hands it back. */
59
+ const pick = (row: Obj, snake: string) =>
60
+ row[snake] ?? row[snake.replace(/_([a-z])/g, (_, c: string) => c.toUpperCase())];
58
61
  const rows = (body: unknown): Obj[] => {
59
62
  const list = Array.isArray(body) ? body : (body as { results?: unknown })?.results;
60
63
  return Array.isArray(list) ? (list.filter((r) => r && typeof r === 'object') as Obj[]) : [];
@@ -67,17 +70,17 @@ export async function listRecordShares(
67
70
  ): Promise<RecordShares> {
68
71
  const p = { ...DEFAULTS, ...paths };
69
72
  const body = await http.get<unknown>(p.grants, { params: { entity: documentId, page_size: 100 } });
70
- const envelope = (body ?? {}) as { may_share?: boolean; may_share_reason?: string };
73
+ const envelope = (body ?? {}) as Obj;
71
74
  const shares: RecordShare[] = [];
72
75
  for (const row of rows(body)) {
73
- const kind = str(row.subject_type) as ShareKind;
76
+ const kind = str(pick(row, 'subject_type')) as ShareKind;
74
77
  if (!KINDS.includes(kind)) continue; // a public link is publishing, not sharing
75
78
  shares.push({
76
- id: str(row.id), kind, subjectId: str(row.subject_id),
79
+ id: str(row.id), kind, subjectId: str(pick(row, 'subject_id')),
77
80
  level: str(row.level) === 'editor' ? 'editor' : 'viewer',
78
81
  });
79
82
  }
80
- return { shares, canShare: envelope.may_share === true, reason: envelope.may_share_reason || undefined };
83
+ return { shares, canShare: pick(envelope, 'may_share') === true, reason: str(pick(envelope, 'may_share_reason')) || undefined };
81
84
  }
82
85
 
83
86
  export async function addRecordShare(
@@ -111,9 +114,9 @@ export async function listShareChoices(
111
114
  http.get<unknown>(p.teams).catch(() => null),
112
115
  ]);
113
116
  const w = (who ?? {}) as Obj;
114
- const orgId = str(w.org_id) || str((w.org as Obj | undefined)?.id) || str(w.org);
117
+ const orgId = str(pick(w, 'org_id')) || str((w.org as Obj | undefined)?.id) || str(w.org);
115
118
  return {
116
- org: orgId ? { id: orgId, label: str(w.org_name) || 'Everyone in my organisation' } : undefined,
119
+ org: orgId ? { id: orgId, label: str(pick(w, 'org_name')) || 'Everyone in my organisation' } : undefined,
117
120
  people: rows(roster).map((r) => ({ id: str(r.sub), label: str(r.label) || str(r.sub) })).filter((r) => r.id),
118
121
  teams: rows(teams).map((r) => ({ id: str(r.slug), label: str(r.name) || str(r.slug) })).filter((r) => r.id),
119
122
  };
@@ -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
  }