@startsimpli/integrations 0.2.138 → 0.2.140

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.138",
3
+ "version": "0.2.140",
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.171",
53
+ "@startsimpli/auth": "^0.4.50",
54
54
  "@startsimpli/utils": "^0.4.17",
55
- "@startsimpli/auth": "^0.4.50"
55
+ "@startsimpli/ui": "^0.4.171"
56
56
  },
57
57
  "peerDependenciesMeta": {
58
58
  "react": {
@@ -627,3 +627,22 @@ describe('TrackerPage — opening a to-do', () => {
627
627
  expect(onOpenDocument).not.toHaveBeenCalled();
628
628
  });
629
629
  });
630
+
631
+ describe('TrackerPage — adding a to-do', () => {
632
+ it('adds a to-do from a quick-add box and re-reads the list', async () => {
633
+ const createCommitment = vi.fn(async () => ROWS[0]);
634
+ let calls = 0;
635
+ const api = { ...makeApi({ onQuery: () => { calls += 1; } }), createCommitment } as CommitmentTrackerApi;
636
+ render(<TrackerPage api={api} scope={SCOPE} />);
637
+ await screen.findByText('Chase the inventor for comments on 2148');
638
+ await userEvent.type(screen.getByRole('textbox', { name: /add a to-do/i }), 'Call the notary{Enter}');
639
+ expect(createCommitment).toHaveBeenCalledWith(expect.objectContaining({ title: 'Call the notary' }));
640
+ await vi.waitFor(() => expect(calls).toBeGreaterThan(1));
641
+ });
642
+
643
+ it('offers no quick-add when the api cannot create', async () => {
644
+ render(<TrackerPage api={makeApi()} scope={SCOPE} />);
645
+ await screen.findByText('Chase the inventor for comments on 2148');
646
+ expect(screen.queryByRole('textbox', { name: /add a to-do/i })).toBeNull();
647
+ });
648
+ });
@@ -0,0 +1,268 @@
1
+ /**
2
+ * The open-questions queue (bd startsim-tmrvi.3, tmrvi.9): per-user, ranked,
3
+ * deduped by (item, kind), resolved or expired when the item moves on, answered
4
+ * through the item edit path so the answer syncs to the tracker.
5
+ */
6
+ import { describe, expect, it, vi } from 'vitest';
7
+
8
+ import { answerQuestion, listOpenQuestions, syncOpenQuestions } from '../corpus/questions';
9
+ import { commitmentEditSeam } from '../corpus/briefing/actions/seam';
10
+ import { createPlanningApi } from '../corpus/client';
11
+ import { guessOf, unknownGuess } from '../corpus/extraction-fields';
12
+ import type { ItemFields } from '../corpus/extraction-fields';
13
+ import type { CorpusHttp } from '../corpus/client';
14
+
15
+ const SCOPE = { orgId: 'o' } as never;
16
+ const ME = 'user-me';
17
+
18
+ interface Row { id: string; entity_type: string; external_id: string; name: string; data: Record<string, unknown>; version: number }
19
+
20
+ /** A tenant in memory: list/get, shallow-merging upsert, and the PATCH door. */
21
+ function tenant(seed: Array<Omit<Row, 'version'>> = []) {
22
+ const rows = new Map<string, Row>(seed.map((r) => [r.id, { ...r, version: 1 }]));
23
+ let next = 1000;
24
+ const http: CorpusHttp & { post: NonNullable<CorpusHttp['post']>; patch: NonNullable<CorpusHttp['patch']> } = {
25
+ async get(path, options) {
26
+ const clean = path.replace(/\/+$/, '');
27
+ if (clean === 'api/v1/entities') {
28
+ const type = String(options?.params?.type ?? '');
29
+ const all = [...rows.values()].filter((r) => r.entity_type === type);
30
+ return { results: all, next: null } as never;
31
+ }
32
+ const row = rows.get(decodeURIComponent(clean.split('/').pop() as string));
33
+ if (!row) throw Object.assign(new Error('nf'), { status: 404 });
34
+ return structuredClone(row) as never;
35
+ },
36
+ async post(path, body) {
37
+ const b = body as { entity_type: string; external_id: string; name?: string; data: Record<string, unknown> };
38
+ expect(path).toContain('upsert');
39
+ const hit = [...rows.values()].find((r) => r.entity_type === b.entity_type && r.external_id === b.external_id);
40
+ if (hit) {
41
+ hit.data = { ...hit.data, ...b.data };
42
+ if (b.name) hit.name = b.name;
43
+ hit.version += 1;
44
+ return structuredClone(hit) as never;
45
+ }
46
+ const row: Row = { id: `e${next++}`, entity_type: b.entity_type, external_id: b.external_id, name: b.name ?? '', data: { ...b.data }, version: 1 };
47
+ rows.set(row.id, row);
48
+ return structuredClone(row) as never;
49
+ },
50
+ async patch(path, body) {
51
+ const row = rows.get(decodeURIComponent(path.replace(/\/+$/, '').split('/').pop() as string)) as Row;
52
+ row.data = (body as { data: Record<string, unknown> }).data;
53
+ row.version += 1;
54
+ return structuredClone(row) as never;
55
+ },
56
+ };
57
+ return { rows, http };
58
+ }
59
+
60
+ const item = (id: string, data: Record<string, unknown> = {}) => ({
61
+ id, entity_type: 'commitment', external_id: `commit:${id}`, name: String(data.title ?? id),
62
+ data: { title: `Item ${id}`, status: 'open', mentions: [{ document_id: 'note1', quote: 'q' }], ...data },
63
+ });
64
+
65
+ const held = (id: string, kind: 'team' | 'personal_space', extra: Record<string, unknown> = {}) =>
66
+ item(id, {
67
+ sync_state: kind === 'team' ? 'needs_team' : 'needs_private_space',
68
+ open_question_kind: kind,
69
+ open_question: kind === 'team' ? 'Which team is this for?' : 'Which private Linear team should hold your personal to-dos?',
70
+ ...extra,
71
+ });
72
+
73
+ const fields = (over: Partial<ItemFields>): ItemFields => ({
74
+ due: unknownGuess('x'), project: unknownGuess('x'), owner: unknownGuess('x'),
75
+ priority: unknownGuess('x'), estimate: unknownGuess('x'), ...over,
76
+ });
77
+
78
+ const voiceNote = (records: unknown[]) => ({
79
+ id: 'note1', entity_type: 'source_document', external_id: 'voice:n1', name: 'Voice note',
80
+ data: { source: 'voice', title: 'Voice note', voice_items: JSON.stringify(records) },
81
+ });
82
+
83
+ const deps = (t: ReturnType<typeof tenant>, now = Date.parse('2026-11-06T12:00:00Z')) =>
84
+ ({ http: t.http, scope: SCOPE, ownerSub: ME, now: () => now });
85
+
86
+ describe('syncOpenQuestions: ingest', () => {
87
+ it('turns held items into team and private-space questions', async () => {
88
+ const t = tenant([held('a', 'team'), held('b', 'personal_space'), item('c')]);
89
+ await syncOpenQuestions(deps(t));
90
+ const open = await listOpenQuestions(deps(t));
91
+ expect(open.map((q) => [q.itemId, q.kind, q.status])).toEqual([
92
+ ['a', 'team', 'open'], ['b', 'private_space', 'open'],
93
+ ]);
94
+ expect(open[0].question).toBe('Which team is this for?');
95
+ });
96
+
97
+ it('is deduped by (item, kind): syncing twice leaves one question and keeps its age', async () => {
98
+ const t = tenant([held('a', 'team')]);
99
+ await syncOpenQuestions(deps(t, Date.parse('2026-11-06T10:00:00Z')));
100
+ await syncOpenQuestions(deps(t, Date.parse('2026-11-06T12:00:00Z')));
101
+ const open = await listOpenQuestions(deps(t));
102
+ expect(open).toHaveLength(1);
103
+ expect(open[0].createdAt).toBe('2026-11-06T10:00:00.000Z');
104
+ });
105
+
106
+ it('reads the voice note questions: due, project and owner, with the assumed value', async () => {
107
+ const t = tenant([
108
+ item('d', { title: 'Call the vet', due_at: '2026-11-06', external_focus_id: 'p1', owner_name: 'Sam' }),
109
+ voiceNote([{
110
+ section: 's', title: 'Call the vet', fields: fields({
111
+ due: guessOf('2026-11-06', 0.5, 'assumed', 'said Friday on a Friday', {
112
+ question: 'Did you mean today or next Friday?',
113
+ candidates: [{ value: '2026-11-06', confidence: 0.5, reason: 'today' }, { value: '2026-11-13', confidence: 0.45, reason: 'next week' }],
114
+ }),
115
+ project: guessOf('p1', 0.4, 'assumed', 'maybe home', { question: 'Which project?' }),
116
+ owner: guessOf('Sam', 0.4, 'assumed', 'a Sam', { question: 'Who owns this?' }),
117
+ }),
118
+ }]),
119
+ ]);
120
+ await syncOpenQuestions(deps(t));
121
+ const open = await listOpenQuestions(deps(t));
122
+ expect(new Set(open.map((q) => q.kind))).toEqual(new Set(['due_date', 'project', 'ownership']));
123
+ const due = open.find((q) => q.kind === 'due_date')!;
124
+ expect(due.assumed).toMatchObject({ value: '2026-11-06', confidence: 0.5 });
125
+ expect(due.candidates.map((c) => c.value)).toEqual(['2026-11-06', '2026-11-13']);
126
+ });
127
+
128
+ it('ranks what blocks the sync first, then low-confidence guesses', async () => {
129
+ const t = tenant([
130
+ held('team', 'team'),
131
+ item('due', { title: 'Pay rent', due_at: '2026-11-06' }),
132
+ voiceNote([{ section: 's', title: 'Pay rent', fields: fields({ due: guessOf('2026-11-06', 0.5, 'assumed', 'r', { question: 'When?' }) }) }]),
133
+ ]);
134
+ await syncOpenQuestions(deps(t));
135
+ const open = await listOpenQuestions(deps(t));
136
+ expect(open.map((q) => q.kind)).toEqual(['team', 'due_date']);
137
+ expect(open[0].score).toBeGreaterThan(open[1].score);
138
+ });
139
+
140
+ it('resolves a question when the item moves on, and expires it when the item is gone or closed', async () => {
141
+ const t = tenant([held('a', 'team'), held('b', 'team'), held('c', 'team')]);
142
+ await syncOpenQuestions(deps(t));
143
+ // a: the engine placed it (question cleared). b: closed. c: deleted.
144
+ t.rows.get('a')!.data = { ...t.rows.get('a')!.data, open_question_kind: '', open_question: '', sync_state: 'synced' };
145
+ t.rows.get('b')!.data.status = 'done';
146
+ t.rows.delete('c');
147
+ await syncOpenQuestions(deps(t));
148
+ expect(await listOpenQuestions(deps(t))).toEqual([]);
149
+ const all = await listOpenQuestions(deps(t), { status: 'all' });
150
+ expect(Object.fromEntries(all.map((q) => [q.itemId, q.status]))).toEqual({ a: 'resolved', b: 'expired', c: 'expired' });
151
+ });
152
+
153
+ it('resolves a voice-note question once someone changed the field it was about', async () => {
154
+ const t = tenant([
155
+ item('d', { title: 'Call the vet', due_at: '2026-11-06' }),
156
+ voiceNote([{ section: 's', title: 'Call the vet', fields: fields({ due: guessOf('2026-11-06', 0.5, 'assumed', 'r', { question: 'When?' }) }) }]),
157
+ ]);
158
+ await syncOpenQuestions(deps(t));
159
+ t.rows.get('d')!.data.due_at = '2026-11-13';
160
+ await syncOpenQuestions(deps(t));
161
+ expect(await listOpenQuestions(deps(t))).toEqual([]);
162
+ // and it is not asked again on the next pass
163
+ await syncOpenQuestions(deps(t));
164
+ expect(await listOpenQuestions(deps(t))).toEqual([]);
165
+ });
166
+
167
+ it('keeps one queue per person', async () => {
168
+ const t = tenant([held('a', 'team')]);
169
+ await syncOpenQuestions(deps(t));
170
+ await syncOpenQuestions({ ...deps(t), ownerSub: 'someone-else' });
171
+ expect(await listOpenQuestions(deps(t))).toHaveLength(1);
172
+ expect(await listOpenQuestions({ ...deps(t), ownerSub: 'someone-else' })).toHaveLength(1);
173
+ expect([...t.rows.values()].filter((r) => r.entity_type === 'open_question')).toHaveLength(2);
174
+ });
175
+ });
176
+
177
+ describe('answerQuestion', () => {
178
+ function setup(rowsIn: Parameters<typeof tenant>[0]) {
179
+ const t = tenant(rowsIn);
180
+ const api = createPlanningApi({ http: t.http, scope: SCOPE, supportedFilters: [], resolveParticipants: false } as never);
181
+ const seam = commitmentEditSeam({ api, http: t.http, scope: SCOPE });
182
+ const d = {
183
+ ...deps(t), seam,
184
+ patchItem: vi.fn(async (id: string, wire: Record<string, unknown>) => {
185
+ const row = t.rows.get(id)!;
186
+ row.data = { ...row.data, ...wire };
187
+ }),
188
+ setPersonalContainer: vi.fn(async () => undefined),
189
+ fileItem: vi.fn(async () => undefined),
190
+ };
191
+ return { t, d };
192
+ }
193
+
194
+ it('team: sets the container, queues the push, clears the question, resolves it', async () => {
195
+ const { t, d } = setup([held('a', 'team')]);
196
+ await syncOpenQuestions(d);
197
+ const [q] = await listOpenQuestions(d);
198
+ const result = await answerQuestion(d, q.id, { value: 'team-eng' });
199
+ expect(result.status).toBe('resolved');
200
+ expect(d.patchItem).toHaveBeenCalledWith('a', expect.objectContaining({
201
+ external_container_id: 'team-eng', open_question_kind: '', open_question: '', sync_state: 'pending',
202
+ }));
203
+ expect(t.rows.get('a')!.data.external_container_id).toBe('team-eng');
204
+ expect(await listOpenQuestions(d)).toEqual([]);
205
+ });
206
+
207
+ it('private space: saves the personal container once and releases every held personal item', async () => {
208
+ const { d } = setup([held('a', 'personal_space'), held('b', 'personal_space')]);
209
+ await syncOpenQuestions(d);
210
+ const [q] = await listOpenQuestions(d);
211
+ await answerQuestion(d, q.id, { value: 'team-mine' });
212
+ expect(d.setPersonalContainer).toHaveBeenCalledTimes(1);
213
+ expect(d.setPersonalContainer).toHaveBeenCalledWith('team-mine');
214
+ expect(d.patchItem).toHaveBeenCalledTimes(2);
215
+ expect(await listOpenQuestions(d)).toEqual([]);
216
+ });
217
+
218
+ it('due date: goes through the item edit seam (stamped, so it syncs)', async () => {
219
+ const { t, d } = setup([
220
+ item('d', { title: 'Call the vet', due_at: '2026-11-06' }),
221
+ voiceNote([{ section: 's', title: 'Call the vet', fields: fields({ due: guessOf('2026-11-06', 0.5, 'assumed', 'r', { question: 'When?' }) }) }]),
222
+ ]);
223
+ await syncOpenQuestions(d);
224
+ const [q] = await listOpenQuestions(d);
225
+ await answerQuestion(d, q.id, { value: '2026-11-13' });
226
+ const data = t.rows.get('d')!.data;
227
+ expect(String(data.due_at)).toContain('2026-11-13');
228
+ expect((data.field_edited_at as Record<string, string>).due_at).toBeTruthy();
229
+ expect(d.patchItem).not.toHaveBeenCalled();
230
+ expect(await listOpenQuestions(d)).toEqual([]);
231
+ });
232
+
233
+ it('project: files the item; ownership: patches the owner', async () => {
234
+ const { d } = setup([
235
+ item('d', { title: 'Call the vet', external_focus_id: 'p1', owner_name: 'Sam' }),
236
+ voiceNote([{ section: 's', title: 'Call the vet', fields: fields({
237
+ project: guessOf('p1', 0.4, 'assumed', 'r', { question: 'Which project?' }),
238
+ owner: guessOf('Sam', 0.4, 'assumed', 'r', { question: 'Who?' }),
239
+ }) }]),
240
+ ]);
241
+ await syncOpenQuestions(d);
242
+ const open = await listOpenQuestions(d);
243
+ await answerQuestion(d, open.find((q) => q.kind === 'project')!.id, { value: 'focus-9' });
244
+ await answerQuestion(d, open.find((q) => q.kind === 'ownership')!.id, { value: 'sub-7', label: 'Sam Lee' });
245
+ expect(d.fileItem).toHaveBeenCalledWith('d', 'focus-9');
246
+ expect(d.patchItem).toHaveBeenCalledWith('d', expect.objectContaining({ owner_sub: 'sub-7', owner_name: 'Sam Lee' }));
247
+ });
248
+
249
+ it('refuses an empty answer, an unknown question and someone else\'s question', async () => {
250
+ const { d } = setup([held('a', 'team')]);
251
+ await syncOpenQuestions(d);
252
+ const [q] = await listOpenQuestions(d);
253
+ await expect(answerQuestion(d, q.id, { value: ' ' })).rejects.toThrow(/answer/i);
254
+ await expect(answerQuestion(d, 'nope', { value: 'x' })).rejects.toThrow(/not found/i);
255
+ await expect(answerQuestion({ ...d, ownerSub: 'other' }, q.id, { value: 'x' })).rejects.toThrow(/not found/i);
256
+ expect(d.patchItem).not.toHaveBeenCalled();
257
+ });
258
+
259
+ it('answering twice does not edit twice', async () => {
260
+ const { d } = setup([held('a', 'team')]);
261
+ await syncOpenQuestions(d);
262
+ const [q] = await listOpenQuestions(d);
263
+ await answerQuestion(d, q.id, { value: 'team-eng' });
264
+ const again = await answerQuestion(d, q.id, { value: 'team-other' });
265
+ expect(again.status).toBe('resolved');
266
+ expect(d.patchItem).toHaveBeenCalledTimes(1);
267
+ });
268
+ });
@@ -0,0 +1,96 @@
1
+ /**
2
+ * The tracker's real teams, read from the member's connected task tracker, as the
3
+ * classes of the team classifier (bd startsim-6z7vi.7).
4
+ */
5
+ import { describe, expect, it, vi } from 'vitest';
6
+
7
+ import { createPersonalSpaceSetter, createTrackerTeamLister } from '../corpus/tracker-teams';
8
+
9
+ const choice = (id: string, label: string, detail: Record<string, unknown> = {}) =>
10
+ ({ id, label, kind: 'team', selectable: true, reason: '', remediation: '', hidden_by_default: false, detail });
11
+
12
+ function api(opts: { connections?: unknown[]; teams?: unknown[][]; kinds?: Record<string, string> } = {}) {
13
+ const pages = opts.teams ?? [[choice('t1', 'Engineering', { key: 'ENG', description: 'Builds the product' }), choice('t2', 'Design', { key: 'DSN' })]];
14
+ const connections = vi.fn(async () => ({
15
+ results: (opts.connections ?? [
16
+ { id: 'c-drive', connector_key: 'dropbox', status: 'connected', config: {} },
17
+ { id: 'c-lin', connector_key: 'linear', status: 'connected', config: {} },
18
+ ]) as never[],
19
+ permissions: {} as never,
20
+ }));
21
+ const connectorCatalog = vi.fn(async () => ({
22
+ results: [
23
+ { key: 'dropbox', kind: '' },
24
+ { key: 'linear', kind: opts.kinds?.linear ?? 'task_tracker' },
25
+ ] as never[],
26
+ }));
27
+ const connectionChoices = vi.fn(async (_id: string, params?: { kind?: string; cursor?: string }) => {
28
+ const index = params?.cursor ? Number(params.cursor) : 0;
29
+ return { results: pages[index] as never[], kind: 'team', cursor: index + 1 < pages.length ? String(index + 1) : null, has_more: index + 1 < pages.length };
30
+ });
31
+ return { connections, connectorCatalog, connectionChoices };
32
+ }
33
+
34
+ describe('createTrackerTeamLister', () => {
35
+ it('lists the teams of the connected task tracker, with key and description', async () => {
36
+ const a = api();
37
+ const teams = await createTrackerTeamLister(a)();
38
+ expect(teams).toEqual([
39
+ { id: 't1', title: 'Engineering', key: 'ENG', detail: 'Builds the product' },
40
+ { id: 't2', title: 'Design', key: 'DSN', detail: '' },
41
+ ]);
42
+ expect(a.connectionChoices).toHaveBeenCalledWith('c-lin', { kind: 'team' });
43
+ });
44
+
45
+ it('reads every page of teams', async () => {
46
+ const a = api({ teams: [[choice('t1', 'A')], [choice('t2', 'B')]] });
47
+ expect((await createTrackerTeamLister(a)()).map((t) => t.id)).toEqual(['t1', 't2']);
48
+ });
49
+
50
+ it('is empty when no task tracker is connected', async () => {
51
+ const a = api({ connections: [{ id: 'c-lin', connector_key: 'linear', status: 'needs_reauth', config: {} }] });
52
+ expect(await createTrackerTeamLister(a)()).toEqual([]);
53
+ expect(a.connectionChoices).not.toHaveBeenCalled();
54
+ });
55
+
56
+ it('never offers a private team or the personal space as a team for business work', async () => {
57
+ const a = api({
58
+ connections: [{ id: 'c-lin', connector_key: 'linear', status: 'connected', config: { task_sync: { personal_container_id: 't2' } } }],
59
+ teams: [[choice('t1', 'Eng'), choice('t2', 'Mine'), choice('t3', 'Secret', { private: true })]],
60
+ });
61
+ expect((await createTrackerTeamLister(a)()).map((t) => t.id)).toEqual(['t1']);
62
+ });
63
+
64
+ it('answers once for repeated asks within the same run', async () => {
65
+ const a = api();
66
+ const list = createTrackerTeamLister(a);
67
+ await list();
68
+ await list();
69
+ expect(a.connectionChoices).toHaveBeenCalledTimes(1);
70
+ });
71
+
72
+ it('lets the failure out so the caller can decide (extraction swallows it)', async () => {
73
+ const a = api();
74
+ a.connectionChoices.mockRejectedValueOnce(new Error('central down'));
75
+ await expect(createTrackerTeamLister(a)()).rejects.toThrow('central down');
76
+ });
77
+ });
78
+
79
+ describe('createPersonalSpaceSetter', () => {
80
+ it('saves the private team on the tracker connection, keeping the rest of the task_sync block', async () => {
81
+ const a = {
82
+ ...api({ connections: [{ id: 'c-lin', connector_key: 'linear', status: 'connected', config: { task_sync: { default_container_id: 't1', assignee_id: 'u1' } } }] }),
83
+ updateConnectionConfig: vi.fn(async () => ({}) as never),
84
+ };
85
+ await createPersonalSpaceSetter(a)('t9');
86
+ expect(a.updateConnectionConfig).toHaveBeenCalledWith('c-lin', {
87
+ task_sync: { default_container_id: 't1', assignee_id: 'u1', personal_container_id: 't9' },
88
+ });
89
+ });
90
+
91
+ it('says so when no tracker is connected', async () => {
92
+ const a = { ...api({ connections: [] }), updateConnectionConfig: vi.fn() };
93
+ await expect(createPersonalSpaceSetter(a as never)('t9')).rejects.toThrow(/no task tracker/i);
94
+ expect(a.updateConnectionConfig).not.toHaveBeenCalled();
95
+ });
96
+ });
@@ -335,6 +335,25 @@ export function TrackerPage({
335
335
  }
336
336
  }, [doneOpen, loadDone]);
337
337
  const canWrite = Boolean(api.updateCommitment);
338
+ const canAdd = Boolean(api.createCommitment);
339
+ const [draftTitle, setDraftTitle] = React.useState('');
340
+ const [adding, setAdding] = React.useState(false);
341
+ /** Quick-add: a title is enough; everything else is edited on the detail page. */
342
+ const addTodo = async () => {
343
+ const title = draftTitle.trim();
344
+ if (!title || adding) return;
345
+ setAdding(true);
346
+ setError('');
347
+ try {
348
+ await apiRef.current.createCommitment!({ title });
349
+ setDraftTitle('');
350
+ await loadRef.current();
351
+ } catch (err) {
352
+ setError(failureMessage(err));
353
+ } finally {
354
+ setAdding(false);
355
+ }
356
+ };
338
357
  const open = (item: Commitment) => {
339
358
  if (onOpenItem) { onOpenItem(item); return; }
340
359
  const doc = item.mentions[0]?.documentId;
@@ -372,6 +391,16 @@ export function TrackerPage({
372
391
 
373
392
  return (
374
393
  <div className={cn.root}>
394
+ {canAdd ? (
395
+ <form className="flex gap-2" onSubmit={(e) => { e.preventDefault(); void addTodo(); }}>
396
+ <input
397
+ className={`${cn.input} flex-1`} value={draftTitle} disabled={adding}
398
+ onChange={(e) => setDraftTitle(e.target.value)}
399
+ placeholder="Add a to-do…" aria-label="Add a to-do"
400
+ />
401
+ <button type="submit" className={cn.secondaryButton} disabled={adding || !draftTitle.trim()}>Add</button>
402
+ </form>
403
+ ) : null}
375
404
  <div className="flex flex-wrap items-center gap-3">
376
405
  <p className={cn.muted} data-testid="tracker-summary">
377
406
  {loading ? 'Loading…' : `${owed} owed · ${c.today} today · ${c.inProgress} in progress`}
@@ -301,3 +301,11 @@ export { summarizeFocuses } from './focus-overview';
301
301
  export type { FocusSummary } from './focus-overview';
302
302
  export { actionsByNote } from './note-actions';
303
303
  export type { NoteActions } from './note-actions';
304
+
305
+ // The tracker's real teams for the team classifier (bd startsim-6z7vi.7).
306
+ export { createPersonalSpaceSetter, createTrackerTeamLister } from './tracker-teams';
307
+ export type { TrackerTeamsApi } from './tracker-teams';
308
+ // Open questions: ranked, deduped, expiring queue per person (bd startsim-tmrvi.3).
309
+ export * from './questions';
310
+ // A person's field edit written the way the tenant protects it (human-edited, stamped, queued for the tracker).
311
+ export { patchEditedItem } from './commitment-edit';
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Answering a question applies the answer to the ITEM through the paths a person's
3
+ * own edit takes, so it is stamped human-edited and the sync engine pushes it to
4
+ * the tracker: a due date goes through the item edit seam; a team, an owner or the
5
+ * release of a held item go through the tenant PATCH (`patchItem`).
6
+ */
7
+ import type { ItemEditSeam } from '../briefing/actions/types';
8
+ import { close, listOpenQuestions, storeFor, type QuestionDeps } from './sync';
9
+ import type { OpenQuestion, QuestionAnswer } from './types';
10
+
11
+ export interface AnswerDeps extends QuestionDeps {
12
+ seam: ItemEditSeam;
13
+ /** GET-then-PATCH one item's fields (human-edit stamped). */
14
+ patchItem(itemId: string, wire: Record<string, unknown>): Promise<void>;
15
+ /** File an item under a focus (an edge). */
16
+ fileItem?(itemId: string, focusId: string | null): Promise<void>;
17
+ /** Save the tracker's personal container on the member's connection (central). */
18
+ setPersonalContainer?(containerId: string): Promise<void>;
19
+ }
20
+
21
+ /** The fields that send a held item on its way. */
22
+ const RELEASE = { open_question_kind: '', open_question: '', sync_state: 'pending', sync_error: '' };
23
+
24
+ export async function answerQuestion(
25
+ deps: AnswerDeps,
26
+ questionId: string,
27
+ answer: QuestionAnswer,
28
+ ): Promise<OpenQuestion> {
29
+ const store = storeFor(deps);
30
+ const q = await store.get(questionId);
31
+ if (!q) throw Object.assign(new Error('Question not found.'), { status: 404 });
32
+ if (q.status !== 'open') return q;
33
+
34
+ const value = (answer.value ?? '').trim();
35
+ if (!value && q.kind !== 'due_date') throw Object.assign(new Error('An answer is needed.'), { status: 400 });
36
+ const at = new Date((deps.now ?? Date.now)()).toISOString();
37
+
38
+ switch (q.kind) {
39
+ case 'team':
40
+ await deps.patchItem(q.itemId, { external_container_id: value, ...RELEASE });
41
+ break;
42
+ case 'private_space': {
43
+ if (!deps.setPersonalContainer) throw new Error('This client cannot save a private space.');
44
+ await deps.setPersonalContainer(value);
45
+ const siblings = (await listOpenQuestions(deps)).filter((o) => o.kind === 'private_space');
46
+ for (const s of siblings) {
47
+ await deps.patchItem(s.itemId, RELEASE);
48
+ if (s.id !== q.id) await close(store, s, 'resolved', 'answered', at, { value });
49
+ }
50
+ break;
51
+ }
52
+ case 'due_date': {
53
+ const item = await deps.seam.load(q.itemId);
54
+ if (!item) throw Object.assign(new Error('Item not found.'), { status: 404 });
55
+ await deps.seam.update(item, { dueAt: value || null });
56
+ break;
57
+ }
58
+ case 'project':
59
+ if (!deps.fileItem) throw new Error('This client cannot file items.');
60
+ await deps.fileItem(q.itemId, value);
61
+ await deps.patchItem(q.itemId, { external_focus_id: value });
62
+ break;
63
+ case 'ownership':
64
+ await deps.patchItem(q.itemId, { owner_sub: value, owner_name: answer.label ?? '' });
65
+ break;
66
+ }
67
+ return close(store, q, 'resolved', 'answered', at, answer);
68
+ }
@@ -0,0 +1,75 @@
1
+ /**
2
+ * What the queue SHOULD contain, from the current state of the items and the
3
+ * voice notes they came from. Pure: no storage, no clock.
4
+ */
5
+ import { openQuestions } from '../extraction-fields';
6
+ import type { FieldGuess, ItemFields } from '../extraction-fields';
7
+ import type { VoiceItemRecord } from '../voice-due';
8
+ import type { DerivedQuestion, ItemView, QuestionKind } from './types';
9
+
10
+ export const CLOSED_STATUSES: ReadonlySet<string> = new Set(['done', 'dropped']);
11
+
12
+ /** Held by the sync engine: what blocks an item reaching the tracker is asked first. */
13
+ const KIND_WEIGHT: Record<QuestionKind, number> = {
14
+ team: 100, private_space: 90, due_date: 70, project: 60, ownership: 40,
15
+ };
16
+
17
+ const FIELD_KIND: Partial<Record<keyof ItemFields, QuestionKind>> = {
18
+ due: 'due_date', project: 'project', owner: 'ownership',
19
+ };
20
+
21
+ const norm = (s: string) => s.toLowerCase().replace(/\s+/g, ' ').trim();
22
+ const day = (v: string | null | undefined) => (v ? String(v).slice(0, 10) : '');
23
+
24
+ /** Higher asks first: blocking kinds, then the guesses we are least sure of. */
25
+ export function scoreOf(kind: QuestionKind, confidence?: number): number {
26
+ const doubt = confidence === undefined ? 1 : 1 - Math.min(1, Math.max(0, confidence));
27
+ return KIND_WEIGHT[kind] + Math.round(doubt * 20);
28
+ }
29
+
30
+ /** The item still holds the value extraction assumed; once someone changes it, the question is moot. */
31
+ function stillAssumed(kind: QuestionKind, guess: FieldGuess<unknown>, item: ItemView): boolean {
32
+ const assumed = guess.value === null || guess.value === undefined ? '' : String(guess.value);
33
+ if (kind === 'due_date') return day(assumed) === day(item.dueAt);
34
+ if (kind === 'project') return assumed === item.focusId;
35
+ return norm(assumed) === norm(item.ownerName);
36
+ }
37
+
38
+ export function deriveQuestions(
39
+ items: ItemView[],
40
+ notes: ReadonlyMap<string, VoiceItemRecord[]>,
41
+ ): DerivedQuestion[] {
42
+ const out: DerivedQuestion[] = [];
43
+ for (const item of items) {
44
+ if (CLOSED_STATUSES.has(item.status)) continue;
45
+ const base = item.noteId ? { noteId: item.noteId } : {};
46
+
47
+ if (item.openKind === 'team' || item.openKind === 'personal_space') {
48
+ const kind: QuestionKind = item.openKind === 'team' ? 'team' : 'private_space';
49
+ out.push({
50
+ itemId: item.id, kind, candidates: [], reopens: true, ...base,
51
+ question: item.openText || (kind === 'team' ? 'Which team is this for?' : 'Which private space should hold your personal to-dos?'),
52
+ });
53
+ }
54
+
55
+ const records = item.noteId ? notes.get(item.noteId) : undefined;
56
+ const record = records?.find((r) => norm(r.title) === norm(item.title));
57
+ if (!record) continue;
58
+ for (const { field, question } of openQuestions(record.fields)) {
59
+ const kind = FIELD_KIND[field];
60
+ if (!kind) continue;
61
+ const guess = record.fields[field] as FieldGuess<unknown>;
62
+ if (!stillAssumed(kind, guess, item)) continue;
63
+ out.push({
64
+ itemId: item.id, kind, question, reopens: false, ...base,
65
+ assumed: {
66
+ value: guess.value === null || guess.value === undefined ? null : String(guess.value),
67
+ ...(guess.display ? { display: guess.display } : {}),
68
+ confidence: guess.confidence, reason: guess.reason,
69
+ },
70
+ candidates: guess.candidates.map((c) => ({ value: String(c.value), confidence: c.confidence, reason: c.reason })),
71
+ });
72
+ }
73
+ }
74
+ return out;
75
+ }
@@ -0,0 +1,14 @@
1
+ export { answerQuestion } from './answer';
2
+ export type { AnswerDeps } from './answer';
3
+ export { deriveQuestions, scoreOf } from './derive';
4
+ export { createQuestionStore, questionExternalId } from './store';
5
+ export type { QuestionStore } from './store';
6
+ export { listOpenQuestions, syncOpenQuestions } from './sync';
7
+ export type { QuestionDeps } from './sync';
8
+ export {
9
+ OPEN_QUESTION_ATTRIBUTES, OPEN_QUESTION_LABEL, OPEN_QUESTION_TYPE, QUESTION_KINDS,
10
+ } from './types';
11
+ export type {
12
+ AssumedValue, DerivedQuestion, ItemView, OpenQuestion, QuestionAnswer, QuestionCandidate,
13
+ QuestionKind, QuestionResolution, QuestionStatus,
14
+ } from './types';
@@ -0,0 +1,53 @@
1
+ /** Reading the items and notes the queue is derived from. */
2
+ import type { CorpusHttp } from '../client';
3
+ import { toCommitment, type TenantEntity } from '../entities';
4
+ import type { CorpusScope } from '../types';
5
+ import type { VoiceItemRecord } from '../voice-due';
6
+ import type { ItemView } from './types';
7
+
8
+ const PAGE_SIZE = 200;
9
+ const MAX_PAGES = 100;
10
+ const str = (v: unknown): string => (typeof v === 'string' ? v : '');
11
+
12
+ export async function readItemViews(http: CorpusHttp, scope: CorpusScope, entitiesPath: string): Promise<ItemView[]> {
13
+ const out: ItemView[] = [];
14
+ for (let page = 1; page <= MAX_PAGES; page += 1) {
15
+ const res = await http.get<{ results?: TenantEntity[]; next?: string | null }>(entitiesPath, {
16
+ params: { type: 'commitment', page, page_size: PAGE_SIZE },
17
+ });
18
+ const rows = res.results ?? [];
19
+ for (const row of rows) {
20
+ const c = toCommitment(row, scope);
21
+ const d = (row.data ?? {}) as Record<string, unknown>;
22
+ const noteId = c.mentions[0]?.documentId;
23
+ out.push({
24
+ id: c.id, title: c.title, status: c.status, dueAt: c.dueAt ?? null,
25
+ focusId: str(d.external_focus_id ?? d.externalFocusId), ownerName: c.ownerName ?? '', ownerSub: c.ownerSub ?? '',
26
+ ...(noteId ? { noteId } : {}),
27
+ openKind: str(d.open_question_kind ?? d.openQuestionKind),
28
+ openText: str(d.open_question ?? d.openQuestion),
29
+ });
30
+ }
31
+ if (!res.next || rows.length === 0) break;
32
+ }
33
+ return out;
34
+ }
35
+
36
+ /** The per-item records of each voice note the open items came from. */
37
+ export async function readVoiceRecords(
38
+ http: CorpusHttp, noteIds: string[], entitiesPath: string,
39
+ ): Promise<Map<string, VoiceItemRecord[]>> {
40
+ const out = new Map<string, VoiceItemRecord[]>();
41
+ await Promise.all([...new Set(noteIds)].map(async (id) => {
42
+ try {
43
+ const note = await http.get<TenantEntity>(`${entitiesPath}/${encodeURIComponent(id)}`);
44
+ const raw = (note.data ?? {}) as Record<string, unknown>;
45
+ const items = raw.voice_items ?? raw.voiceItems;
46
+ const parsed = typeof items === 'string' ? (JSON.parse(items) as unknown) : items;
47
+ if (Array.isArray(parsed)) out.set(id, parsed as VoiceItemRecord[]);
48
+ } catch {
49
+ // A note that is gone or unreadable has no questions to add; the held-item ones still stand.
50
+ }
51
+ }));
52
+ return out;
53
+ }
@@ -0,0 +1,100 @@
1
+ /** Where open questions are kept: tenant entities of type `open_question`, one queue per person. */
2
+ import type { CorpusHttp } from '../client';
3
+ import type { TenantEntity } from '../entities';
4
+ import {
5
+ OPEN_QUESTION_TYPE,
6
+ type AssumedValue, type OpenQuestion, type QuestionCandidate, type QuestionKind,
7
+ type QuestionResolution, type QuestionStatus,
8
+ } from './types';
9
+
10
+ export interface QuestionStoreDeps {
11
+ http: CorpusHttp;
12
+ ownerSub: string;
13
+ entitiesPath?: string;
14
+ }
15
+
16
+ const ENTITIES = 'api/v1/entities';
17
+ const PAGE_SIZE = 200;
18
+ const MAX_PAGES = 50;
19
+
20
+ const str = (v: unknown): string => (typeof v === 'string' ? v : v === undefined || v === null ? '' : String(v));
21
+ const pick = (d: Record<string, unknown>, a: string, b: string): unknown => d[a] ?? d[b];
22
+ const json = <T,>(v: unknown, fallback: T): T => {
23
+ if (v && typeof v === 'object') return v as T;
24
+ if (typeof v !== 'string' || !v) return fallback;
25
+ try { return JSON.parse(v) as T; } catch { return fallback; }
26
+ };
27
+
28
+ export const questionExternalId = (ownerSub: string, itemId: string, kind: QuestionKind) =>
29
+ `q:${ownerSub}:${itemId}:${kind}`;
30
+
31
+ export function toQuestion(entity: TenantEntity): OpenQuestion {
32
+ const d = (entity.data ?? {}) as Record<string, unknown>;
33
+ const assumed = json<AssumedValue | null>(d.assumed, null);
34
+ const resolvedAt = str(pick(d, 'resolved_at', 'resolvedAt'));
35
+ const resolution = str(d.resolution);
36
+ const noteId = str(pick(d, 'note_id', 'noteId'));
37
+ return {
38
+ id: String(entity.id),
39
+ itemId: str(pick(d, 'item_id', 'itemId')),
40
+ kind: str(d.kind) as QuestionKind,
41
+ question: str(d.question),
42
+ status: (str(d.status) || 'open') as QuestionStatus,
43
+ ...(assumed ? { assumed } : {}),
44
+ candidates: json<QuestionCandidate[]>(d.candidates, []),
45
+ score: Number(d.score) || 0,
46
+ ownerSub: str(pick(d, 'owner_sub', 'ownerSub')),
47
+ ...(noteId ? { noteId } : {}),
48
+ ...(resolution ? { resolution: resolution as QuestionResolution } : {}),
49
+ createdAt: str(pick(d, 'created_at', 'createdAt')),
50
+ updatedAt: str(pick(d, 'updated_at', 'updatedAt')),
51
+ ...(resolvedAt ? { resolvedAt } : {}),
52
+ };
53
+ }
54
+
55
+ export interface QuestionStore {
56
+ /** Every question of this person, any status. */
57
+ all(): Promise<OpenQuestion[]>;
58
+ get(id: string): Promise<OpenQuestion | null>;
59
+ /** Create or merge-update by (item, kind). `data` keys are the stored attribute names. */
60
+ put(itemId: string, kind: QuestionKind, question: string, data: Record<string, unknown>): Promise<OpenQuestion>;
61
+ }
62
+
63
+ export function createQuestionStore({ http, ownerSub, entitiesPath = ENTITIES }: QuestionStoreDeps): QuestionStore {
64
+ return {
65
+ async all() {
66
+ const out: OpenQuestion[] = [];
67
+ for (let page = 1; page <= MAX_PAGES; page += 1) {
68
+ const res = await http.get<{ results?: TenantEntity[]; next?: string | null }>(entitiesPath, {
69
+ params: { type: OPEN_QUESTION_TYPE, page, page_size: PAGE_SIZE },
70
+ });
71
+ const rows = res.results ?? [];
72
+ out.push(...rows.map(toQuestion).filter((q) => q.ownerSub === ownerSub));
73
+ if (!res.next || rows.length === 0) break;
74
+ }
75
+ return out;
76
+ },
77
+ async get(id) {
78
+ try {
79
+ const entity = await http.get<TenantEntity>(`${entitiesPath}/${encodeURIComponent(id)}`);
80
+ const type = entity.entity_type ?? entity.entityType;
81
+ if (type !== OPEN_QUESTION_TYPE) return null;
82
+ const q = toQuestion(entity);
83
+ return q.ownerSub === ownerSub ? q : null;
84
+ } catch (error) {
85
+ if ((error as { status?: number }).status === 404) return null;
86
+ throw error;
87
+ }
88
+ },
89
+ async put(itemId, kind, question, data) {
90
+ if (!http.post) throw new Error('This client cannot write questions.');
91
+ const entity = await http.post<TenantEntity>(`${entitiesPath}/upsert`, {
92
+ entity_type: OPEN_QUESTION_TYPE,
93
+ external_id: questionExternalId(ownerSub, itemId, kind),
94
+ name: question.slice(0, 200),
95
+ data: { item_id: itemId, kind, question, owner_sub: ownerSub, ...data },
96
+ });
97
+ return toQuestion(entity);
98
+ },
99
+ };
100
+ }
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Bring the queue in line with the items: ingest what is unsure, resolve what
3
+ * moved on, expire what is gone. Idempotent; run it as often as is convenient.
4
+ */
5
+ import type { CorpusHttp } from '../client';
6
+ import type { CorpusScope } from '../types';
7
+ import { CLOSED_STATUSES, deriveQuestions, scoreOf } from './derive';
8
+ import { readItemViews, readVoiceRecords } from './items';
9
+ import { createQuestionStore } from './store';
10
+ import type { ItemView, OpenQuestion, QuestionResolution } from './types';
11
+
12
+ export interface QuestionDeps {
13
+ http: CorpusHttp;
14
+ scope: CorpusScope;
15
+ /** The person whose queue this is. */
16
+ ownerSub: string;
17
+ entitiesPath?: string;
18
+ now?: () => number;
19
+ }
20
+
21
+ const ENTITIES = 'api/v1/entities';
22
+ const key = (itemId: string, kind: string) => `${itemId}:${kind}`;
23
+
24
+ export const storeFor = (deps: QuestionDeps) =>
25
+ createQuestionStore({ http: deps.http, ownerSub: deps.ownerSub, entitiesPath: deps.entitiesPath ?? ENTITIES });
26
+
27
+ export async function syncOpenQuestions(deps: QuestionDeps): Promise<{ opened: number; resolved: number; expired: number }> {
28
+ const path = deps.entitiesPath ?? ENTITIES;
29
+ const iso = () => new Date((deps.now ?? Date.now)()).toISOString();
30
+ const store = storeFor(deps);
31
+
32
+ const items = await readItemViews(deps.http, deps.scope, path);
33
+ const byId = new Map<string, ItemView>(items.map((i) => [i.id, i]));
34
+ const noteIds = items.filter((i) => !CLOSED_STATUSES.has(i.status) && i.noteId).map((i) => i.noteId as string);
35
+ const notes = await readVoiceRecords(deps.http, noteIds, path);
36
+ const derived = deriveQuestions(items, notes);
37
+ const existing = new Map((await store.all()).map((q) => [key(q.itemId, q.kind), q]));
38
+
39
+ let opened = 0, resolved = 0, expired = 0;
40
+ const wanted = new Set<string>();
41
+
42
+ for (const d of derived) {
43
+ const k = key(d.itemId, d.kind);
44
+ wanted.add(k);
45
+ const have = existing.get(k);
46
+ const score = scoreOf(d.kind, d.assumed?.confidence);
47
+ const body = {
48
+ question: d.question, score,
49
+ assumed: d.assumed ? JSON.stringify(d.assumed) : '',
50
+ candidates: JSON.stringify(d.candidates),
51
+ ...(d.noteId ? { note_id: d.noteId } : {}),
52
+ };
53
+ if (!have) {
54
+ await store.put(d.itemId, d.kind, d.question, { ...body, status: 'open', created_at: iso(), updated_at: iso() });
55
+ opened += 1;
56
+ } else if (have.status !== 'open') {
57
+ if (!d.reopens) continue;
58
+ await store.put(d.itemId, d.kind, d.question, { ...body, status: 'open', resolution: '', resolved_at: '', created_at: iso(), updated_at: iso() });
59
+ opened += 1;
60
+ } else if (have.question !== d.question || have.score !== score) {
61
+ await store.put(d.itemId, d.kind, d.question, { ...body, updated_at: iso() });
62
+ }
63
+ }
64
+
65
+ for (const [k, q] of existing) {
66
+ if (q.status !== 'open' || wanted.has(k)) continue;
67
+ const item = byId.get(q.itemId);
68
+ const resolution: QuestionResolution = !item ? 'item_gone' : CLOSED_STATUSES.has(item.status) ? 'item_closed' : 'item_changed';
69
+ await close(store, q, item ? (resolution === 'item_closed' ? 'expired' : 'resolved') : 'expired', resolution, iso());
70
+ if (resolution === 'item_changed') resolved += 1; else expired += 1;
71
+ }
72
+ return { opened, resolved, expired };
73
+ }
74
+
75
+ export async function close(
76
+ store: ReturnType<typeof createQuestionStore>,
77
+ q: OpenQuestion,
78
+ status: 'resolved' | 'expired',
79
+ resolution: QuestionResolution,
80
+ at: string,
81
+ answer?: unknown,
82
+ ): Promise<OpenQuestion> {
83
+ return store.put(q.itemId, q.kind, q.question, {
84
+ status, resolution, resolved_at: at, updated_at: at,
85
+ ...(answer !== undefined ? { answer: JSON.stringify(answer) } : {}),
86
+ });
87
+ }
88
+
89
+ /** The queue, best first. `status: 'all'` includes what has been resolved or expired. */
90
+ export async function listOpenQuestions(
91
+ deps: QuestionDeps,
92
+ options: { status?: 'open' | 'all' } = {},
93
+ ): Promise<OpenQuestion[]> {
94
+ const all = await storeFor(deps).all();
95
+ return all
96
+ .filter((q) => options.status === 'all' || q.status === 'open')
97
+ .sort((a, b) => b.score - a.score || a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id));
98
+ }
@@ -0,0 +1,92 @@
1
+ /**
2
+ * THE OPEN-QUESTIONS QUEUE (bd startsim-tmrvi.3 / tmrvi.9).
3
+ *
4
+ * One row per (person, item, kind): a thing Tandem is unsure about and has
5
+ * either held back (a team, a private space) or ASSUMED an answer to (a due date,
6
+ * a project, an owner). Rows are tenant-side entities of type `open_question`:
7
+ * the person's own to-dos and the model's doubts about them are tenant-originated
8
+ * data, not something ingested from a remote API.
9
+ */
10
+ export const QUESTION_KINDS = ['team', 'private_space', 'due_date', 'project', 'ownership'] as const;
11
+ export type QuestionKind = (typeof QUESTION_KINDS)[number];
12
+
13
+ export type QuestionStatus = 'open' | 'resolved' | 'expired';
14
+
15
+ /** Why a question left the queue. */
16
+ export type QuestionResolution = 'answered' | 'item_changed' | 'item_closed' | 'item_gone';
17
+
18
+ export interface AssumedValue {
19
+ value: string | null;
20
+ display?: string;
21
+ confidence: number;
22
+ reason: string;
23
+ }
24
+
25
+ export interface QuestionCandidate {
26
+ value: string;
27
+ confidence: number;
28
+ reason: string;
29
+ }
30
+
31
+ export interface OpenQuestion {
32
+ /** The question row's own id. */
33
+ id: string;
34
+ itemId: string;
35
+ kind: QuestionKind;
36
+ question: string;
37
+ status: QuestionStatus;
38
+ /** What Tandem is acting on until it is confirmed; absent for held items. */
39
+ assumed?: AssumedValue;
40
+ candidates: QuestionCandidate[];
41
+ /** Higher is asked first. */
42
+ score: number;
43
+ ownerSub: string;
44
+ noteId?: string;
45
+ resolution?: QuestionResolution;
46
+ createdAt: string;
47
+ updatedAt: string;
48
+ resolvedAt?: string;
49
+ }
50
+
51
+ export interface QuestionAnswer {
52
+ /** A team id, an ISO date (or empty to clear), a focus id, or a member sub. */
53
+ value: string;
54
+ /** Human label for the value (an owner's name). */
55
+ label?: string;
56
+ }
57
+
58
+ /** What the queue needs to know about an item (from its commitment row). */
59
+ export interface ItemView {
60
+ id: string;
61
+ title: string;
62
+ status: string;
63
+ dueAt: string | null;
64
+ focusId: string;
65
+ ownerName: string;
66
+ ownerSub: string;
67
+ noteId?: string;
68
+ openKind: string;
69
+ openText: string;
70
+ }
71
+
72
+ /** A question as derived from the current state of items and notes, before storage. */
73
+ export interface DerivedQuestion {
74
+ itemId: string;
75
+ kind: QuestionKind;
76
+ question: string;
77
+ assumed?: AssumedValue;
78
+ candidates: QuestionCandidate[];
79
+ noteId?: string;
80
+ /** Held items re-ask when the engine holds them again; assumptions are asked once. */
81
+ reopens: boolean;
82
+ }
83
+
84
+ /** The entity type key and attributes the tenant must declare. */
85
+ export const OPEN_QUESTION_TYPE = 'open_question';
86
+ export const OPEN_QUESTION_LABEL = 'Open question';
87
+ export const OPEN_QUESTION_ATTRIBUTES: Array<[string, string]> = [
88
+ ['item_id', 'text'], ['kind', 'text'], ['question', 'text'], ['status', 'text'],
89
+ ['assumed', 'text'], ['candidates', 'text'], ['answer', 'text'], ['score', 'integer'],
90
+ ['owner_sub', 'text'], ['note_id', 'text'], ['resolution', 'text'],
91
+ ['created_at', 'date'], ['updated_at', 'date'], ['resolved_at', 'date'],
92
+ ];
@@ -0,0 +1,89 @@
1
+ /**
2
+ * THE TRACKER'S REAL TEAMS, for the team classifier (bd startsim-6z7vi.7).
3
+ *
4
+ * Extraction needs `listTeams` to place an engineering-sounding item. The teams
5
+ * are what the member's connected task tracker reaches (`choices?kind=team` on
6
+ * their own connection), so this reads them through the member connections api
7
+ * and names no vendor: the first CONNECTED connection whose catalog row says
8
+ * `kind: task_tracker` is the tracker.
9
+ *
10
+ * - a private team, and the member's `personal_container_id`, are never offered:
11
+ * personal work goes there by the engine, business work must not;
12
+ * - the answer is read once per lister, so a run that classifies several slices
13
+ * does not re-walk the tracker;
14
+ * - a failure is thrown, not hidden: extraction already treats a failed team read
15
+ * as "no teams" and holds the items as `needs_team`.
16
+ */
17
+ import type { Connection, MemberConnectionsApi } from '../components/pages/types';
18
+ import { isTaskTracker, readTaskSync, withTaskSync } from '../task-tracker/sync-config';
19
+ import type { TeamCandidate } from './types';
20
+
21
+ const MAX_PAGES = 20;
22
+
23
+ export type TrackerTeamsApi = Pick<MemberConnectionsApi, 'connections' | 'connectorCatalog'> & {
24
+ connectionChoices: NonNullable<MemberConnectionsApi['connectionChoices']>;
25
+ };
26
+
27
+ async function findTracker(api: Pick<MemberConnectionsApi, 'connections' | 'connectorCatalog'>): Promise<Connection | undefined> {
28
+ const [mine, catalog] = await Promise.all([api.connections(), api.connectorCatalog()]);
29
+ const kinds = new Map(catalog.results.map((entry) => [entry.key, entry]));
30
+ return mine.results.find((c) => c.status === 'connected' && isTaskTracker(kinds.get(c.connector_key)));
31
+ }
32
+
33
+ const text = (v: unknown): string => (typeof v === 'string' ? v.trim() : '');
34
+
35
+ export function createTrackerTeamLister(api: TrackerTeamsApi): () => Promise<TeamCandidate[]> {
36
+ let pending: Promise<TeamCandidate[]> | null = null;
37
+
38
+ async function read(): Promise<TeamCandidate[]> {
39
+ const tracker = await findTracker(api);
40
+ if (!tracker) return [];
41
+ const personal = readTaskSync(tracker).personal_container_id;
42
+
43
+ const teams: TeamCandidate[] = [];
44
+ let cursor: string | undefined;
45
+ for (let page = 0; page < MAX_PAGES; page += 1) {
46
+ const res = await api.connectionChoices(tracker.id, { kind: 'team', ...(cursor ? { cursor } : {}) });
47
+ for (const row of res.results) {
48
+ const detail = (row.detail ?? {}) as Record<string, unknown>;
49
+ if (detail.private === true || row.id === personal) continue;
50
+ teams.push({
51
+ id: row.id,
52
+ title: row.label,
53
+ key: text(detail.key) || row.label,
54
+ detail: text(detail.description),
55
+ });
56
+ }
57
+ if (!res.has_more || !res.cursor) break;
58
+ cursor = res.cursor;
59
+ }
60
+ return teams;
61
+ }
62
+
63
+ return () => {
64
+ if (!pending) {
65
+ pending = read().catch((error: unknown) => {
66
+ pending = null;
67
+ throw error;
68
+ });
69
+ }
70
+ return pending;
71
+ };
72
+ }
73
+
74
+ /**
75
+ * Save the member's private space (`personal_container_id`) on their tracker
76
+ * connection: the stored `task_sync` block with the one field laid over it, since
77
+ * the server replaces the block whole.
78
+ */
79
+ export function createPersonalSpaceSetter(
80
+ api: Pick<MemberConnectionsApi, 'connections' | 'connectorCatalog'> & {
81
+ updateConnectionConfig: NonNullable<MemberConnectionsApi['updateConnectionConfig']>;
82
+ },
83
+ ): (containerId: string) => Promise<void> {
84
+ return async (containerId) => {
85
+ const tracker = await findTracker(api);
86
+ if (!tracker) throw new Error('No task tracker is connected.');
87
+ await api.updateConnectionConfig(tracker.id, { task_sync: withTaskSync(tracker, { personal_container_id: containerId }) });
88
+ };
89
+ }