@startsimpli/integrations 0.2.149 → 0.2.150

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.149",
3
+ "version": "0.2.150",
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/auth": "^0.4.50",
53
+ "@startsimpli/ui": "^0.4.172",
54
54
  "@startsimpli/utils": "^0.4.18",
55
- "@startsimpli/ui": "^0.4.172"
55
+ "@startsimpli/auth": "^0.4.50"
56
56
  },
57
57
  "peerDependenciesMeta": {
58
58
  "react": {
@@ -0,0 +1,85 @@
1
+ /**
2
+ * A KEY THAT WORKS BUT SEES NOTHING SAYS WHY (bd startsim-768w.38.16).
3
+ *
4
+ * "0 note(s) visible on the first page" is accurate and useless: the admin reads
5
+ * it as a broken integration. A connector that authenticates but whose grant is
6
+ * empty returns `reason` and `next_step` beside `detail`. This page renders them
7
+ * for ANY connector, naming no vendor, and never hides `detail`.
8
+ */
9
+ import { describe, expect, it, vi } from 'vitest';
10
+ import { render, screen } from '@testing-library/react';
11
+ import userEvent from '@testing-library/user-event';
12
+
13
+ import { ConnectionsPage } from '../components/pages/ConnectionsPage';
14
+ import type { ConnectionsApi } from '../components/pages/types';
15
+
16
+ const CATALOG = {
17
+ results: [
18
+ {
19
+ key: 'granola', name: 'Granola', description: 'Meeting notes',
20
+ logo_url: '', docs_url: '', capabilities: ['poll'], auth_mode: 'api_key',
21
+ credential_schema: { version: 1, fields: [] },
22
+ config_schema: { version: 1, fields: [] },
23
+ record_types: [], supports_webhooks: false,
24
+ availability: { available: true, reason: '' },
25
+ },
26
+ ],
27
+ };
28
+
29
+ const CONNECTED = {
30
+ results: [
31
+ {
32
+ id: 'c1', public_id: 'pub1', name: 'Tandem Granola',
33
+ connector_key: 'granola', connector_name: 'Granola',
34
+ external_account_id: '', account_label: 'tandem',
35
+ capabilities_enabled: ['poll'], config: {}, status: 'connected',
36
+ health: 'ok', auth_mode: 'api_key',
37
+ },
38
+ ],
39
+ permissions: { view: true, manage: true, issue_tokens: true },
40
+ };
41
+
42
+ function stubApi(check: Record<string, unknown>): ConnectionsApi {
43
+ return {
44
+ connectorCatalog: vi.fn().mockResolvedValue(CATALOG),
45
+ connections: vi.fn().mockResolvedValue(CONNECTED),
46
+ connect: vi.fn(),
47
+ checkConnection: vi.fn().mockResolvedValue(check),
48
+ disconnect: vi.fn(),
49
+ connectionChoices: vi.fn(),
50
+ wireTarget: vi.fn(),
51
+ confirmTarget: vi.fn(),
52
+ connectionActions: vi.fn(),
53
+ invokeConnectionAction: vi.fn(),
54
+ updateConnection: vi.fn(),
55
+ rotateCredential: vi.fn(),
56
+ } as unknown as ConnectionsApi;
57
+ }
58
+
59
+ async function runTest(check: Record<string, unknown>) {
60
+ render(<ConnectionsPage api={stubApi(check)} foundrySlug="tandem" />);
61
+ await userEvent.click(await screen.findByRole('button', { name: /^Test$/i }));
62
+ }
63
+
64
+ describe('the Test result on a connection card', () => {
65
+ it('shows the reason and the next step when the grant is empty, and keeps the raw detail', async () => {
66
+ await runTest({
67
+ ok: true, account_label: 'tandem',
68
+ detail: 'scope workspace: 0 note(s) visible on the first page',
69
+ reason: 'No notes are visible to this key.',
70
+ next_step: 'Enable API access for a space, then check again.',
71
+ });
72
+
73
+ const reason = await screen.findByText('No notes are visible to this key.');
74
+ expect(reason.closest('[data-check-reason]')).not.toBeNull();
75
+ expect(screen.getByText('Enable API access for a space, then check again.')).toBeInTheDocument();
76
+ expect(screen.getByText(/0 note\(s\) visible on the first page/)).toBeInTheDocument();
77
+ });
78
+
79
+ it('renders no reason block when the connector gave none', async () => {
80
+ await runTest({ ok: true, account_label: 'tandem', detail: 'all good', reason: '', next_step: '' });
81
+
82
+ expect(await screen.findByText('all good')).toBeInTheDocument();
83
+ expect(document.querySelector('[data-check-reason]')).toBeNull();
84
+ });
85
+ });
@@ -0,0 +1,90 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { currentValueSeries, toFocusRevision, loadCurrentValueRevisions } from '../corpus/focus-history';
3
+
4
+ const rev = (version: number, at: string, before: unknown, after: unknown, key = 'current_value') =>
5
+ toFocusRevision({
6
+ version, created_at: at, actor_label: 'ana@x.test', action: 'updated',
7
+ metadata: { changed: { [key]: { ...(before === undefined ? {} : { before }), after } } },
8
+ });
9
+
10
+ describe('toFocusRevision', () => {
11
+ it('reads snake and camel spellings of the wire', () => {
12
+ const r = toFocusRevision({ version: 2, createdAt: '2026-11-01T10:00:00Z', actorLabel: 'a', metadata: { changed: { currentValue: { before: 1, after: 2 } } } });
13
+ expect(r).toMatchObject({ version: 2, createdAt: '2026-11-01T10:00:00Z', actor: 'a' });
14
+ expect(r.currentValue).toEqual({ before: 1, after: 2 });
15
+ });
16
+ it('a revision that did not move current_value has none', () => {
17
+ expect(toFocusRevision({ version: 1, created_at: '2026-11-01T00:00:00Z', metadata: { changed: { title: { after: 'x' } } } }).currentValue).toBeUndefined();
18
+ });
19
+ });
20
+
21
+ describe('currentValueSeries', () => {
22
+ it('builds dated points oldest first with the delta as the event', () => {
23
+ const { points } = currentValueSeries([rev(3, '2026-11-05T09:00:00Z', 5, 8), rev(2, '2026-11-01T09:00:00Z', 2, 5)], '2026-11-05');
24
+ expect(points.map((p) => [p.date, p.value])).toEqual([['2026-11-01', 5], ['2026-11-05', 8]]);
25
+ expect(points[1].events?.[0].delta).toBe(3);
26
+ });
27
+ it('two edits in one day: the end-of-day value wins and both events stay', () => {
28
+ const { points } = currentValueSeries([rev(3, '2026-11-01T18:00:00Z', 5, 7), rev(2, '2026-11-01T09:00:00Z', 2, 5)], '2026-11-02');
29
+ expect(points[0]).toMatchObject({ date: '2026-11-01', value: 7 });
30
+ expect(points[0].events).toHaveLength(2);
31
+ });
32
+ it('holds the last value to the anchor day without inventing an event', () => {
33
+ const { points } = currentValueSeries([rev(2, '2026-11-01T09:00:00Z', 2, 5)], '2026-11-05');
34
+ expect(points.at(-1)).toMatchObject({ date: '2026-11-05', value: 5 });
35
+ expect(points.at(-1)?.events ?? []).toEqual([]);
36
+ });
37
+ it('no revisions that moved current_value: no points at all, never a flat line', () => {
38
+ expect(currentValueSeries([], '2026-11-05').points).toEqual([]);
39
+ const other = toFocusRevision({ version: 1, created_at: '2026-11-01T00:00:00Z', metadata: { changed: { title: { after: 'x' } } } });
40
+ expect(currentValueSeries([other], '2026-11-05').points).toEqual([]);
41
+ });
42
+ it('ignores a non-numeric or removed value', () => {
43
+ const gone = toFocusRevision({ version: 2, created_at: '2026-11-02T00:00:00Z', metadata: { changed: { current_value: { before: 5 } } } });
44
+ const text = rev(3, '2026-11-03T00:00:00Z', 5, 'n/a');
45
+ expect(currentValueSeries([text, gone], '2026-11-05').points).toEqual([]);
46
+ });
47
+ it('reports the oldest recorded change, so the chart can say what it covers', () => {
48
+ expect(currentValueSeries([rev(2, '2026-11-01T09:00:00Z', 2, 5)], '2026-11-05').since).toBe('2026-11-01');
49
+ });
50
+ });
51
+
52
+ describe('loadCurrentValueRevisions', () => {
53
+ const page = (rows: ReturnType<typeof rev>[], next: boolean) => ({ count: 9, next: next ? 'n' : null, previous: null, results: rows });
54
+ it('pages newest-first until it is past the 90 day window, then stops', async () => {
55
+ const calls: number[] = [];
56
+ const pages = [
57
+ page([rev(9, '2026-11-01T00:00:00Z', 1, 2)], true),
58
+ page([rev(8, '2026-06-01T00:00:00Z', 0, 1)], true),
59
+ page([rev(7, '2026-05-01T00:00:00Z', 0, 0)], false),
60
+ ];
61
+ const out = await loadCurrentValueRevisions(async (n) => { calls.push(n); return pages[n - 1]; }, '2026-11-05');
62
+ expect(calls).toEqual([1, 2]);
63
+ expect(out).toHaveLength(2);
64
+ });
65
+ it('stops when there is no next page', async () => {
66
+ const calls: number[] = [];
67
+ await loadCurrentValueRevisions(async (n) => { calls.push(n); return page([rev(1, '2026-11-01T00:00:00Z', 0, 1)], false); }, '2026-11-05');
68
+ expect(calls).toEqual([1]);
69
+ });
70
+ });
71
+
72
+ import { createPlanningApi } from '../corpus/client';
73
+
74
+ describe('planning client: listFocusRevisions / endDate order', () => {
75
+ it('reads only current_value saves, server-paginated, and maps them', async () => {
76
+ const gets: Array<{ path: string; params?: Record<string, unknown> }> = [];
77
+ const http = {
78
+ async get(path: string, init?: { params?: Record<string, unknown> }) {
79
+ gets.push({ path, params: init?.params });
80
+ return { count: 1, next: null, previous: null, results: [{ version: 4, created_at: '2026-11-01T00:00:00Z', metadata: { changed: { current_value: { before: 1, after: 2 } } } }] };
81
+ },
82
+ };
83
+ const api = createPlanningApi({ http: http as never, scope: { orgId: 'o' } });
84
+ const out = await api.listFocusRevisions!('f1', { page: 2, pageSize: 100 });
85
+ expect(gets[0]).toEqual({ path: 'api/v1/entities/f1/revisions/', params: { field: 'current_value', page: 2, page_size: 100 } });
86
+ expect(out.results[0].currentValue).toEqual({ before: 1, after: 2 });
87
+ await api.listFocuses({ orderBy: 'endDate' });
88
+ expect(gets[1].params).toMatchObject({ order: 'attr.end_date' });
89
+ });
90
+ });
@@ -0,0 +1,51 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { focusToGoalRow } from '../corpus/goal-rows';
3
+ import type { Focus } from '../corpus/types';
4
+
5
+ const base: Focus = {
6
+ id: 'f1', externalId: 'focus:f1', title: 'Ship v2', detail: '', status: 'active',
7
+ scope: { orgId: 'tandem' },
8
+ };
9
+
10
+ describe('focusToGoalRow', () => {
11
+ it('maps a measurable focus to target / current / unit', () => {
12
+ const row = focusToGoalRow({ ...base, targetValue: 10, currentValue: 4, unit: 'deals' });
13
+ expect(row).toMatchObject({ id: 'f1', title: 'Ship v2', target: 10, current: 4, unit: 'deals' });
14
+ });
15
+
16
+ it('a focus with no target is qualitative: no target and no current are sent', () => {
17
+ const row = focusToGoalRow({ ...base, currentValue: 3 });
18
+ expect(row.target).toBeUndefined();
19
+ expect(row.current).toBeUndefined();
20
+ });
21
+
22
+ it('a target of 0 or less is qualitative, never a fully-achieved goal', () => {
23
+ expect(focusToGoalRow({ ...base, targetValue: 0, currentValue: 0 }).target).toBeUndefined();
24
+ expect(focusToGoalRow({ ...base, targetValue: -5, currentValue: 1 }).target).toBeUndefined();
25
+ });
26
+
27
+ it('a target with nothing recorded yet is 0 of the target, not "no target"', () => {
28
+ expect(focusToGoalRow({ ...base, targetValue: 10 })).toMatchObject({ target: 10, current: 0 });
29
+ });
30
+
31
+ it('never invents progress from item counts or the stored progress field', () => {
32
+ const row = focusToGoalRow({ ...base, progress: 0.8 });
33
+ expect(row.target).toBeUndefined();
34
+ expect(row.current).toBeUndefined();
35
+ });
36
+
37
+ it('owner is the display name, else absent; never the raw sub', () => {
38
+ expect(focusToGoalRow({ ...base, ownerName: 'Ana', ownerSub: 'user:1' }).owner).toBe('Ana');
39
+ expect(focusToGoalRow({ ...base, ownerSub: 'user:1' }).owner).toBeUndefined();
40
+ });
41
+
42
+ it('due is the end date cut to a day; subtype falls back to category', () => {
43
+ expect(focusToGoalRow({ ...base, endDate: '2026-12-31T10:00:00Z' }).due).toBe('2026-12-31');
44
+ expect(focusToGoalRow({ ...base, subtype: 'payoff', category: 'financial' }).subtype).toBe('payoff');
45
+ expect(focusToGoalRow({ ...base, category: 'financial' }).subtype).toBe('financial');
46
+ });
47
+
48
+ it('status is the readable label', () => {
49
+ expect(focusToGoalRow({ ...base, status: 'on_track' }).status).toBe('on track');
50
+ });
51
+ });
@@ -0,0 +1,124 @@
1
+ import { fireEvent, render, screen, waitFor } from '@testing-library/react';
2
+ import { describe, expect, it, vi } from 'vitest';
3
+ import { GoalsPage } from '../components/pages/goals';
4
+ import { FocusProgressHistory } from '../components/pages/goals/FocusProgressHistory';
5
+ import type { CorpusPage, Focus, FocusQuery } from '../corpus/types';
6
+
7
+ const SCOPE = { orgId: 'tandem' };
8
+ const NOW = Date.parse('2026-11-05T12:00:00Z');
9
+
10
+ const mk = (id: string, over: Partial<Focus> = {}): Focus => ({
11
+ id, externalId: `focus:${id}`, title: `Goal ${id}`, detail: '', status: 'active', scope: SCOPE, ...over,
12
+ });
13
+
14
+ function page(results: Focus[], count = results.length, next: string | null = null, previous: string | null = null): CorpusPage<Focus> {
15
+ return { count, next, previous, results, appliedFilters: [] };
16
+ }
17
+
18
+ describe('GoalsPage', () => {
19
+ it('shows a measurable goal with its numbers and a qualitative one as No target, never 0%', async () => {
20
+ const listFocuses = vi.fn(async () => page([
21
+ mk('a', { targetValue: 10, currentValue: 4, unit: 'deals' }),
22
+ mk('b'),
23
+ mk('c', { targetValue: 0, currentValue: 0 }),
24
+ ]));
25
+ render(<GoalsPage api={{ listFocuses }} scope={SCOPE} now={NOW} />);
26
+ expect(await screen.findByText('Goal a')).toBeTruthy();
27
+ expect(screen.getByText(/4 \/ 10 deals/)).toBeTruthy();
28
+ expect(screen.getAllByText('No target')).toHaveLength(2);
29
+ expect(screen.getByTestId('goal-progress-table').textContent).not.toMatch(/\b0%/);
30
+ });
31
+
32
+ it('asks the server for page 1 in play, worst-off first, and states the range', async () => {
33
+ const listFocuses = vi.fn(async (_q?: FocusQuery) => page([mk('a')], 60, 'next'));
34
+ render(<GoalsPage api={{ listFocuses }} scope={SCOPE} now={NOW} pageSize={25} />);
35
+ await screen.findByText('Goal a');
36
+ const q = listFocuses.mock.calls[0][0]!;
37
+ expect(q).toMatchObject({ page: 1, pageSize: 25, orderBy: 'progress' });
38
+ expect(q.status).toEqual(['draft', 'active', 'on_track', 'at_risk', 'off_track', 'completed']);
39
+ expect(screen.getByTestId('goals-range').textContent).toBe('Showing 1–1 of 60');
40
+ });
41
+
42
+ it('Next asks the server for page 2; changing a filter returns to page 1', async () => {
43
+ const listFocuses = vi.fn(async (q?: FocusQuery) => page([mk(`p${q?.page}`)], 60, q?.page === 1 ? 'n' : null));
44
+ render(<GoalsPage api={{ listFocuses }} scope={SCOPE} now={NOW} />);
45
+ await screen.findByText('Goal p1');
46
+ fireEvent.click(screen.getByRole('button', { name: 'Next' }));
47
+ await screen.findByText('Goal p2');
48
+ expect(listFocuses.mock.calls.at(-1)![0]).toMatchObject({ page: 2 });
49
+ fireEvent.change(screen.getByLabelText('Sort goals'), { target: { value: 'endDate' } });
50
+ await waitFor(() => expect(listFocuses.mock.calls.at(-1)![0]).toMatchObject({ page: 1, orderBy: 'endDate' }));
51
+ });
52
+
53
+ it('filters by status and searches on the server', async () => {
54
+ const listFocuses = vi.fn(async (_q?: FocusQuery) => page([mk('a')]));
55
+ render(<GoalsPage api={{ listFocuses }} scope={SCOPE} now={NOW} />);
56
+ await screen.findByText('Goal a');
57
+ fireEvent.change(screen.getByLabelText('Filter by status'), { target: { value: 'at_risk' } });
58
+ await waitFor(() => expect(listFocuses.mock.calls.at(-1)![0]).toMatchObject({ status: 'at_risk' }));
59
+ fireEvent.change(screen.getByLabelText('Search goals'), { target: { value: 'launch' } });
60
+ fireEvent.click(screen.getByRole('button', { name: 'Search' }));
61
+ await waitFor(() => expect(listFocuses.mock.calls.at(-1)![0]).toMatchObject({ search: 'launch', page: 1 }));
62
+ });
63
+
64
+ it('row click hands the focus id to the host', async () => {
65
+ const onOpenFocus = vi.fn();
66
+ render(<GoalsPage api={{ listFocuses: async () => page([mk('a')]) }} scope={SCOPE} now={NOW} onOpenFocus={onOpenFocus} />);
67
+ fireEvent.click(await screen.findByText('Goal a'));
68
+ expect(onOpenFocus).toHaveBeenCalledWith('a');
69
+ });
70
+
71
+ it('marks a past-due goal overdue against the injected clock, not a done one', async () => {
72
+ render(<GoalsPage
73
+ api={{ listFocuses: async () => page([mk('a', { endDate: '2026-10-01' }), mk('b', { endDate: '2026-10-01', status: 'completed' })]) }}
74
+ scope={SCOPE} now={NOW}
75
+ />);
76
+ await screen.findByText('Goal a');
77
+ expect(screen.getAllByText('Overdue')).toHaveLength(1);
78
+ });
79
+
80
+ it('says when a filter was requested but the server did not apply it', async () => {
81
+ const listFocuses = async () => ({ ...page([mk('a')]), appliedFilters: ['type', 'order'] });
82
+ render(<GoalsPage api={{ listFocuses }} scope={SCOPE} now={NOW} />);
83
+ expect((await screen.findByRole('status')).textContent).toMatch(/did not filter by status/);
84
+ });
85
+
86
+ it('surfaces a failed read', async () => {
87
+ render(<GoalsPage api={{ listFocuses: async () => { throw new Error('boom'); } }} scope={SCOPE} now={NOW} />);
88
+ expect(await screen.findByRole('alert')).toBeTruthy();
89
+ });
90
+ });
91
+
92
+ describe('FocusProgressHistory', () => {
93
+ const rev = (version: number, at: string, before: number, after: number) => ({
94
+ version, createdAt: at, currentValue: { before, after },
95
+ });
96
+ const goal = mk('a', { targetValue: 10, currentValue: 8 });
97
+
98
+ it('draws the chart from recorded changes', async () => {
99
+ const listFocusRevisions = vi.fn(async () => ({ count: 2, next: null, previous: null, results: [rev(3, '2026-11-04T10:00:00Z', 5, 8), rev(2, '2026-10-20T10:00:00Z', 0, 5)] }));
100
+ render(<FocusProgressHistory focus={goal} api={{ listFocusRevisions }} today="2026-11-05" />);
101
+ expect(await screen.findByTestId('range-timeline')).toBeTruthy();
102
+ expect(screen.getByText(/Recorded since 2026-10-20/)).toBeTruthy();
103
+ });
104
+
105
+ it('with no recorded change it says so instead of drawing a flat line', async () => {
106
+ const listFocusRevisions = async () => ({ count: 0, next: null, previous: null, results: [] });
107
+ render(<FocusProgressHistory focus={goal} api={{ listFocusRevisions }} today="2026-11-05" />);
108
+ expect(await screen.findByText(/No progress changes recorded yet/)).toBeTruthy();
109
+ expect(screen.queryByTestId('range-timeline')).toBeNull();
110
+ });
111
+
112
+ it('a workspace without the trail says history is unavailable', async () => {
113
+ const listFocusRevisions = async () => { throw new Error('404'); };
114
+ render(<FocusProgressHistory focus={goal} api={{ listFocusRevisions }} today="2026-11-05" />);
115
+ expect(await screen.findByText(/not available/)).toBeTruthy();
116
+ });
117
+
118
+ it('renders nothing for a qualitative goal or an api without history', () => {
119
+ const { container, rerender } = render(<FocusProgressHistory focus={mk('q')} api={{ listFocusRevisions: async () => ({ count: 0, next: null, previous: null, results: [] }) }} today="2026-11-05" />);
120
+ expect(container.firstChild).toBeNull();
121
+ rerender(<FocusProgressHistory focus={goal} api={{}} today="2026-11-05" />);
122
+ expect(container.firstChild).toBeNull();
123
+ });
124
+ });
@@ -0,0 +1,119 @@
1
+ /**
2
+ * The extractor carries the dates a meeting states onto the rows it creates
3
+ * (bd startsim-768w.38.30) - and invents none.
4
+ */
5
+ import { describe, expect, it } from 'vitest';
6
+
7
+ import { mergeDrafts, reconcile } from '../corpus/commitments';
8
+ import { extractCommitments, extractSystemPrompt, rulesExtract } from '../corpus/extract';
9
+ import { createFixtureCorpusApi, createFixtureExtractor, FIXTURE_ORG } from '../corpus/fixtures';
10
+ import type { Commitment, CorpusExtractorLlm, SourceDocument } from '../corpus/types';
11
+
12
+ const TANDEM = { orgId: FIXTURE_ORG };
13
+ const MEETING = '2026-08-05T15:00:00Z';
14
+
15
+ const BODY = [
16
+ '## Discussion',
17
+ '',
18
+ '- Kevin said the vendor contract will be signed by 29th July, nothing else changes there.',
19
+ '- Peggy will circulate the revised budget tomorrow after the board call.',
20
+ '- Julia thinks someone should probably revisit the onboarding emails at some point.',
21
+ '',
22
+ '## Next Steps',
23
+ '',
24
+ '- **Complete the equity item today** (Jonathan)',
25
+ '- **Pay the Rexford invoice by 11th August** (Kate)',
26
+ '- **Schedule call with Peggy for next week**',
27
+ '- **Review the data room permissions urgently** (Brian)',
28
+ '- **Send the revised term sheet on Wednesday** (Kevin)',
29
+ ].join('\n');
30
+
31
+ function meeting(occurredAt: string | null = MEETING): SourceDocument {
32
+ return {
33
+ id: 'm1', title: 'Weekly sync', body: BODY, sections: [], occurredAt,
34
+ source: 'granola', sourceLabel: 'Granola', sourceRef: 'granola:m1', participants: [], scope: TANDEM,
35
+ };
36
+ }
37
+
38
+ const modelItems = (): CorpusExtractorLlm => ({
39
+ ...createFixtureExtractor(),
40
+ async extract() {
41
+ return {
42
+ items: [
43
+ // the date is in the quote: code resolves it, whatever the model wrote
44
+ { documentId: 'm1', title: 'Circulate the revised budget', quote: 'Peggy will circulate the revised budget tomorrow after the board call.', dueAt: '2031-01-01' },
45
+ { documentId: 'm1', title: 'Get the vendor contract signed', quote: 'the vendor contract will be signed by 29th July', dueAt: null },
46
+ // the model estimated a date nobody stated
47
+ { documentId: 'm1', title: 'Revisit the onboarding emails', quote: 'someone should probably revisit the onboarding emails at some point', dueAt: '2026-08-12' },
48
+ ],
49
+ resolutions: [],
50
+ };
51
+ },
52
+ });
53
+
54
+ describe('rules extraction carries stated dates', () => {
55
+ const byTitle = (occurredAt?: string | null) => Object.fromEntries(rulesExtract(meeting(occurredAt)).map((d) => [d.title, d]));
56
+
57
+ it('resolves absolute and relative dates against the meeting date', () => {
58
+ const d = byTitle();
59
+ expect(d['Complete the equity item today'].dueAt).toBe('2026-08-05T23:59:59Z');
60
+ expect(d['Pay the Rexford invoice by 11th August'].dueAt).toBe('2026-08-11T23:59:59Z');
61
+ expect(d['Send the revised term sheet on Wednesday']?.dueAt).toBeUndefined(); // said on a Wednesday: ambiguous
62
+ });
63
+
64
+ it('records what it read, as the row\'s due basis', () => {
65
+ const d = byTitle()['Complete the equity item today'];
66
+ expect(d.dueBasis).toContain('today');
67
+ expect(d.dueConfidence).toBeGreaterThan(0.8);
68
+ });
69
+
70
+ it('leaves spans, urgency and undated items without a date', () => {
71
+ const d = byTitle();
72
+ expect(d['Schedule call with Peggy for next week'].dueAt).toBeUndefined();
73
+ expect(d['Review the data room permissions urgently'].dueAt).toBeUndefined();
74
+ });
75
+
76
+ it('cannot resolve "today" without a meeting date, but still reads an absolute one', () => {
77
+ const d = byTitle(null);
78
+ expect(d['Complete the equity item today'].dueAt).toBeUndefined();
79
+ expect(d['Pay the Rexford invoice by 11th August'].dueAt).toBeUndefined(); // no year, no anchor: a guess
80
+ });
81
+ });
82
+
83
+ describe('model extraction never supplies a date of its own', () => {
84
+ it('resolves the date from the quote, ignores the model\'s own dueAt, and leaves undated items unset', async () => {
85
+ const corpus = createFixtureCorpusApi({ scope: TANDEM, documents: [meeting()] });
86
+ const rows: Commitment[] = [];
87
+ (corpus as { listCommitments?: unknown }).listCommitments = async () => ({ count: 0, next: null, previous: null, results: [] });
88
+ (corpus as { saveCommitments?: unknown }).saveCommitments = async (items: Commitment[]) => { rows.push(...items); };
89
+ await extractCommitments({ scope: TANDEM }, { corpus, extractor: modelItems() });
90
+ const row = (needle: string) => rows.find((r) => r.title.includes(needle));
91
+
92
+ expect(row('Circulate the revised budget')?.dueAt).toBe('2026-08-06T23:59:59Z');
93
+ expect(row('vendor contract signed')?.dueAt).toBe('2026-07-29T23:59:59Z');
94
+ expect(row('Revisit the onboarding emails')).toBeDefined();
95
+ expect(row('Revisit the onboarding emails')?.dueAt).toBeUndefined();
96
+ expect(row('Complete the equity item today')?.dueAt).toBe('2026-08-05T23:59:59Z');
97
+ expect(row('Schedule call with Peggy')?.dueAt).toBeUndefined();
98
+ });
99
+
100
+ it('still tells the model never to estimate a date', () => {
101
+ expect(extractSystemPrompt()).toMatch(/never estimate/i);
102
+ });
103
+ });
104
+
105
+ describe('rows that already exist are not touched', () => {
106
+ it('does not fill a due date onto an existing row, only onto a row it creates', () => {
107
+ const doc = meeting();
108
+ const drafts = rulesExtract(doc);
109
+ const first = reconcile([], mergeDrafts(drafts), { scope: TANDEM, documents: [doc] });
110
+ // The live rows were written before dates were read: none has one.
111
+ const live = first.commitments.map((c) => { const { dueAt, dueBasis, dueConfidence, ...rest } = c; void dueAt; void dueBasis; void dueConfidence; return rest; });
112
+ const second = reconcile(live, mergeDrafts(drafts), { scope: TANDEM, documents: [doc] });
113
+ expect(second.created).toBe(0);
114
+ expect(second.commitments.every((c) => c.dueAt === undefined)).toBe(true);
115
+ expect(second.touched).toEqual([]);
116
+ // ...while a fresh row does carry it.
117
+ expect(first.commitments.find((c) => c.title.includes('equity'))?.dueAt).toBe('2026-08-05T23:59:59Z');
118
+ });
119
+ });
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Dates a meeting STATES -> due dates (bd startsim-768w.38.30). Pure and model-free:
3
+ * the date is computed from the meeting's own date; nothing is ever estimated.
4
+ */
5
+ import { describe, expect, it } from 'vitest';
6
+
7
+ import { resolveStatedDate } from '../corpus/stated-date';
8
+
9
+ // Wed 2026-08-05, the meeting the bead was measured on.
10
+ const MEETING = '2026-08-05T15:00:00Z';
11
+ const due = (text: string, anchor = MEETING, timeZone?: string) => resolveStatedDate(text, anchor, timeZone ? { timeZone } : {})?.dueAt ?? null;
12
+
13
+ describe('resolveStatedDate', () => {
14
+ it.each([
15
+ // relative, anchored to the meeting date
16
+ ['Complete the equity item today', '2026-08-05T23:59:59Z'],
17
+ ['**Complete the equity item** (Jonathan) - today', '2026-08-05T23:59:59Z'],
18
+ ['Send the deck this afternoon', '2026-08-05T23:59:59Z'],
19
+ ['Send the deck tonight', '2026-08-05T23:59:59Z'],
20
+ ['Send the deck by end of day', '2026-08-05T23:59:59Z'],
21
+ ['Send the deck tomorrow', '2026-08-06T23:59:59Z'],
22
+ ['Send the deck the day after tomorrow', '2026-08-07T23:59:59Z'],
23
+ ['Send the deck by Friday', '2026-08-07T23:59:59Z'],
24
+ ['Send the deck on Monday', '2026-08-10T23:59:59Z'],
25
+ ['Send the deck this Thursday', '2026-08-06T23:59:59Z'],
26
+ ['Send the deck in 2 days', '2026-08-07T23:59:59Z'],
27
+ ['Send the deck in two weeks', '2026-08-19T23:59:59Z'],
28
+ ['Send the deck in a week', '2026-08-12T23:59:59Z'],
29
+ // absolute
30
+ ['Pay the invoice by 29th July', '2026-07-29T23:59:59Z'],
31
+ ['Pay the invoice by July 29', '2026-07-29T23:59:59Z'],
32
+ ['Pay the invoice by 11th August', '2026-08-11T23:59:59Z'],
33
+ ['Pay the invoice by 11 of August', '2026-08-11T23:59:59Z'],
34
+ ['Pay the invoice by Oct 29', '2026-10-29T23:59:59Z'],
35
+ ['Pay the invoice by October 29th, 2027', '2027-10-29T23:59:59Z'],
36
+ ['Pay the invoice by 2026-09-01', '2026-09-01T23:59:59Z'],
37
+ // the same date said twice is still one date
38
+ ['Send the deck tomorrow, yes tomorrow', '2026-08-06T23:59:59Z'],
39
+ ])('%s -> %s', (text, expected) => {
40
+ expect(due(text)).toBe(expected);
41
+ });
42
+
43
+ it.each([
44
+ // no date at all
45
+ ['Follow up with the vendor'],
46
+ ['Look into the pricing page'],
47
+ // urgency is not a date
48
+ ['Fix the login bug urgently'],
49
+ ['Send the deck asap'],
50
+ ['Send the deck soon'],
51
+ // a span, not a day: choosing a day would be estimating
52
+ ['Send the deck next week'],
53
+ ['Send the deck this week'],
54
+ ['Send the deck by end of week'],
55
+ ['Send the deck next month'],
56
+ ['Send the deck in a few days'],
57
+ ['Send the deck in a couple of weeks'],
58
+ // "next Friday" has two readings
59
+ ['Send the deck next Friday'],
60
+ // said on a Wednesday: today or a week from now
61
+ ['Send the deck on Wednesday'],
62
+ // two different dates in one item
63
+ ['Send the deck tomorrow and the contract by 29th July'],
64
+ ['Send the deck on Monday, review it by Friday'],
65
+ // past tense references and a bare month
66
+ ['Revisit what we agreed last Friday'],
67
+ ['Revisit what we agreed 3 days ago'],
68
+ ['Send the deck in May'],
69
+ // not a calendar day
70
+ ['Fix bug 29 in July build'],
71
+ ['Pay the invoice by February 30'],
72
+ // a date so far from the meeting that the year is a guess
73
+ ['Pay the invoice by March 3'],
74
+ // not a date
75
+ ['Review the Monday.com integration'],
76
+ [''],
77
+ ])('stays unset: %s', (text) => {
78
+ expect(due(text)).toBeNull();
79
+ });
80
+
81
+ it('is computed in the stated time zone, so a late-evening meeting keeps its own day', () => {
82
+ // 2026-08-06 03:30Z is still Wed 5 Aug 20:30 in Los Angeles.
83
+ const late = '2026-08-06T03:30:00Z';
84
+ expect(due('Send the deck today', late)).toBe('2026-08-06T23:59:59Z');
85
+ expect(resolveStatedDate('Send the deck today', late, { timeZone: 'America/Los_Angeles' })?.date).toBe('2026-08-05');
86
+ expect(due('Send the deck today', late, 'America/Los_Angeles')).toBe('2026-08-06T06:59:59.000Z'.replace('.000Z', 'Z'));
87
+ });
88
+
89
+ it('says what it read and how sure it is', () => {
90
+ const r = resolveStatedDate('Pay it by 29th July', MEETING);
91
+ expect(r).toMatchObject({ date: '2026-07-29', kind: 'absolute', phrase: expect.stringMatching(/29th July/i) });
92
+ expect(r?.basis).toContain('29th July');
93
+ const t = resolveStatedDate('Send it tomorrow', MEETING);
94
+ expect(t).toMatchObject({ date: '2026-08-06', kind: 'relative' });
95
+ expect(t?.basis).toContain('2026-08-05');
96
+ expect(t!.confidence).toBeGreaterThan(0.8);
97
+ });
98
+
99
+ it('needs a usable meeting date for relative phrases, but not for absolute ones', () => {
100
+ expect(due('Send it tomorrow', '')).toBeNull();
101
+ expect(due('Send it tomorrow', 'not a date')).toBeNull();
102
+ expect(due('Send it by 2026-09-01', '')).toBe('2026-09-01T23:59:59Z');
103
+ expect(due('Send it by 29th July 2026', 'not a date')).toBe('2026-07-29T23:59:59Z');
104
+ // no year and no meeting date: the year would be a guess
105
+ expect(due('Send it by 29th July', '')).toBeNull();
106
+ });
107
+ });
@@ -53,6 +53,7 @@ export { ExternalLinkChip } from './pages/task-tracker/ExternalLinkChip';
53
53
  // row, the honesty banner, the overdue/changed predicates — so two views over
54
54
  // one list cannot drift into disagreeing about what they mean.
55
55
  export * from './pages/PlanningPage';
56
+ export * from './pages/goals';
56
57
  export * from './pages/LiabilityPlanPage';
57
58
  export {
58
59
  PRIORITY_LABELS,
@@ -33,6 +33,7 @@ import * as React from 'react';
33
33
 
34
34
  import { displayProgress, focusStatusLabel, standingLabel } from '../../corpus/planning';
35
35
  import { FocusDocuments } from '../FocusDocuments';
36
+ import { FocusProgressHistory } from './goals/FocusProgressHistory';
36
37
  import {
37
38
  WorkItemRow,
38
39
  compareForScreen,
@@ -121,11 +122,18 @@ export interface PlanningPageProps {
121
122
  now?: number;
122
123
  /** The reader's IANA zone, for "overdue" and "next due". Default UTC. */
123
124
  timeZone?: string;
125
+ /**
126
+ * Optional CONTROLLED selection: the id of the focus whose detail is open.
127
+ * Lets a host route straight to one (`/planning?focus=<id>`), e.g. from the
128
+ * Goals table. Omit both and the page keeps its own selection.
129
+ */
130
+ focusId?: string | null;
131
+ onFocusChange?: (focusId: string | null) => void;
124
132
  classNames?: Partial<Record<PlanningSlot, string>>;
125
133
  }
126
134
 
127
135
  export function PlanningPage({
128
- api, scope, onOpenDocument, now, timeZone, classNames = {},
136
+ api, scope, onOpenDocument, now, timeZone, focusId, onFocusChange, classNames = {},
129
137
  }: PlanningPageProps) {
130
138
  const cn = { ...DEFAULTS, ...classNames };
131
139
 
@@ -140,7 +148,12 @@ export function PlanningPage({
140
148
 
141
149
  const [focuses, setFocuses] = React.useState<Focus[]>([]);
142
150
  const [standings, setStandings] = React.useState<Record<string, FocusStanding>>({});
143
- const [selected, setSelected] = React.useState<string | null>(null);
151
+ const [innerSelected, setInnerSelected] = React.useState<string | null>(null);
152
+ const selected = focusId !== undefined ? focusId : innerSelected;
153
+ const setSelected = React.useCallback((id: string | null) => {
154
+ setInnerSelected(id);
155
+ onFocusChange?.(id);
156
+ }, [onFocusChange]);
144
157
  const [items, setItems] = React.useState<Commitment[]>([]);
145
158
  const [applied, setApplied] = React.useState<string[]>([]);
146
159
  const [members, setMembers] = React.useState<Array<{ sub: string; email: string; name?: string }>>([]);
@@ -372,6 +385,7 @@ export function PlanningPage({
372
385
  classNames={cn}
373
386
  onSelect={() => setSelected(null)}
374
387
  />
388
+ <FocusProgressHistory focus={selectedFocus} api={api} />
375
389
  {error ? <p className={cn.error} role="alert">{error}</p> : null}
376
390
  </section>
377
391