@startsimpli/integrations 0.2.68 → 0.2.69

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.68",
3
+ "version": "0.2.69",
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",
@@ -90,8 +90,8 @@
90
90
  "vitest": "^3.0.0",
91
91
  "react-native": "0.85.3",
92
92
  "react-native-safe-area-context": "~5.7.0",
93
- "@startsimpli/llm": "0.4.28",
94
93
  "@startsimpli/ui": "0.4.167",
94
+ "@startsimpli/llm": "0.4.28",
95
95
  "@startsimpli/ui-native": "0.1.0"
96
96
  },
97
97
  "scripts": {
@@ -0,0 +1,67 @@
1
+ /**
2
+ * An in-memory tenant data API: entities, relationships, the filters the voice
3
+ * re-filing reads with. Enough to watch edges move, which a call-recording mock
4
+ * cannot show.
5
+ */
6
+ type Row = { id: string; entity_type: string; external_id?: string; name?: string; data: Record<string, unknown> };
7
+ type Edge = { id: string; rel_type: string; source: string; target: string };
8
+
9
+ export function fakeTenant(seed: { entities?: Row[]; edges?: Array<Omit<Edge, 'id'>> } = {}) {
10
+ const entities: Row[] = [...(seed.entities ?? [])];
11
+ let n = 0;
12
+ const edges: Edge[] = (seed.edges ?? []).map((e) => ({ ...e, id: `e${++n}` }));
13
+ const log: string[] = [];
14
+ const page = <T,>(rows: T[]) => ({ count: rows.length, next: null, previous: null, results: rows });
15
+
16
+ const http = {
17
+ async get(path: string, options?: { params?: Record<string, unknown> }) {
18
+ const p = options?.params ?? {};
19
+ if (path === 'api/v1/relationships') {
20
+ const ids = typeof p.entity__in === 'string' ? new Set(p.entity__in.split(',')) : null;
21
+ return page(edges.filter((e) =>
22
+ (!p.rel_type || e.rel_type === p.rel_type)
23
+ && (!p.source || e.source === p.source)
24
+ && (!ids || ids.has(e.source) || ids.has(e.target))));
25
+ }
26
+ if (path === 'api/v1/entities') {
27
+ let rows = entities.filter((r) => (!p.type || r.entity_type === p.type));
28
+ if (p['attr.source']) rows = rows.filter((r) => r.data.source === p['attr.source']);
29
+ if (p.related_to) {
30
+ const inFocus = new Set(edges.filter((e) => e.rel_type === p.related_via && e.target === p.related_to).map((e) => e.source));
31
+ rows = rows.filter((r) => inFocus.has(r.id));
32
+ }
33
+ return page(rows);
34
+ }
35
+ const id = decodeURIComponent(path.replace('api/v1/entities/', ''));
36
+ const row = entities.find((r) => r.id === id);
37
+ if (!row) throw Object.assign(new Error('not found'), { status: 404 });
38
+ return row;
39
+ },
40
+ async post(path: string, body: any) {
41
+ if (path === 'api/v1/relationships') {
42
+ log.push(`edge+ ${body.rel_type} ${body.source}->${body.target}`);
43
+ edges.push({ id: `e${++n}`, rel_type: body.rel_type, source: body.source, target: body.target });
44
+ return {};
45
+ }
46
+ if (path === 'api/v1/entities/upsert') {
47
+ let row = entities.find((r) => r.external_id === body.external_id);
48
+ if (!row) { row = { id: `x${++n}`, entity_type: body.entity_type, external_id: body.external_id, name: body.name, data: {} }; entities.push(row); }
49
+ row.data = { ...row.data, ...body.data };
50
+ return row;
51
+ }
52
+ throw new Error(`unexpected POST ${path}`);
53
+ },
54
+ async delete(path: string) {
55
+ const id = path.replace('api/v1/relationships/', '');
56
+ const at = edges.findIndex((e) => e.id === id);
57
+ if (at < 0) throw Object.assign(new Error('gone'), { status: 404 });
58
+ log.push(`edge- ${edges[at].rel_type} ${edges[at].source}->${edges[at].target}`);
59
+ edges.splice(at, 1);
60
+ return {};
61
+ },
62
+ };
63
+ /** Targets of one source's edges of a type, sorted. */
64
+ const targets = (type: string, source: string) =>
65
+ edges.filter((e) => e.rel_type === type && e.source === source).map((e) => e.target).sort();
66
+ return { http, entities, edges, log, targets };
67
+ }
@@ -0,0 +1,218 @@
1
+ /**
2
+ * RED for bd startsim-23np6.1.1: moving a voice section's project must move the
3
+ * to-dos that section produced, and filing a commitment REPLACES its project.
4
+ */
5
+ import { describe, expect, it } from 'vitest';
6
+
7
+ import { createPlanningApi } from '../corpus/client';
8
+ import { commitmentToEntity, toCommitment } from '../corpus/entities';
9
+ import { rulesExtract } from '../corpus/extract';
10
+ import { toSourceDocument } from '../corpus/entities';
11
+ import { createVoiceApi } from '../corpus/voice';
12
+ import { createVoiceNotesController } from '../native/voice/controller';
13
+ import { fakeTenant } from './helpers/fake-tenant';
14
+
15
+ const SUMMARY = [
16
+ 'Three topics.',
17
+ '## 287A',
18
+ '- **Review the schema mapping** (Malin)',
19
+ '- **Send the lease draft today**',
20
+ '## Debug',
21
+ '- **Fix the tunnel timeout bug**',
22
+ '## Personal',
23
+ '- **Renew the passport this month**',
24
+ ].join('\n');
25
+
26
+ const note = (sections: unknown[] | undefined, summary = SUMMARY) => ({
27
+ id: 'n1', entity_type: 'source_document', external_id: 'voice:n1', name: 'Note',
28
+ data: { source: 'voice', title: 'Note', summary, ...(sections ? { voice_sections: sections } : {}) },
29
+ });
30
+ const SECTIONS = [
31
+ { label: '287A', kind: 'project', focus_id: 'f-a' },
32
+ { label: 'Debug', kind: 'project', focus_id: 'f-debug' },
33
+ { label: 'Personal', kind: 'personal', focus_id: null },
34
+ ];
35
+
36
+ function commitment(id: string, doc: string, quote: string, section?: string) {
37
+ return {
38
+ id, entity_type: 'commitment', external_id: `commit:${id}`, name: id,
39
+ data: {
40
+ source: 'voice', title: id, status: 'open',
41
+ mentions: [{ document_id: doc, origin_key: `rules:${id}`, quote, extractor: 'rules', ...(section ? { section } : {}) }],
42
+ },
43
+ };
44
+ }
45
+ const ROWS = () => [
46
+ note(SECTIONS),
47
+ commitment('c1', 'n1', '- **Review the schema mapping** (Malin)', '287A'),
48
+ commitment('c2', 'n1', '- **Send the lease draft today**', '287A'),
49
+ commitment('c3', 'n1', '- **Fix the tunnel timeout bug**', 'Debug'),
50
+ commitment('c4', 'n1', '- **Renew the passport this month**', 'Personal'),
51
+ commitment('c5', 'n2', '- **Review the schema mapping** (Malin)'), // another note, same words
52
+ ];
53
+ const EDGES = () => [
54
+ { rel_type: 'about_focus', source: 'n1', target: 'f-a' },
55
+ { rel_type: 'about_focus', source: 'n1', target: 'f-debug' },
56
+ { rel_type: 'in_focus', source: 'c1', target: 'f-a' },
57
+ { rel_type: 'in_focus', source: 'c2', target: 'f-a' },
58
+ { rel_type: 'in_focus', source: 'c3', target: 'f-debug' },
59
+ { rel_type: 'in_focus', source: 'c5', target: 'f-a' },
60
+ ];
61
+
62
+ function world(rows = ROWS(), edges = EDGES()) {
63
+ const t = fakeTenant({ entities: rows as never, edges });
64
+ const api = createVoiceApi({ http: t.http as never, scope: { orgId: 'o' } as never, upload: async () => ({ id: 'x' }) });
65
+ return { ...t, api };
66
+ }
67
+
68
+ describe('moving a section moves its to-dos', () => {
69
+ it('re-files that section\'s commitments, removes the old in_focus edge, leaves other sections alone', async () => {
70
+ const w = world();
71
+ await w.api.fileSection!('n1', 0, 'f-b');
72
+ expect(w.targets('in_focus', 'c1')).toEqual(['f-b']);
73
+ expect(w.targets('in_focus', 'c2')).toEqual(['f-b']);
74
+ expect(w.targets('in_focus', 'c3')).toEqual(['f-debug']);
75
+ expect(w.targets('in_focus', 'c4')).toEqual([]);
76
+ expect(w.targets('in_focus', 'c5')).toEqual(['f-a']); // another note's row, same words
77
+ expect(w.targets('about_focus', 'n1')).toEqual(['f-b', 'f-debug']);
78
+ expect(w.entities.find((r) => r.id === 'n1')!.data.voice_sections).toEqual([
79
+ { label: '287A', kind: 'project', focus_id: 'f-b' }, SECTIONS[1], SECTIONS[2],
80
+ ]);
81
+ });
82
+
83
+ it('unfiling a section (null) removes its commitments\' edge and adds none', async () => {
84
+ const w = world();
85
+ await w.api.fileSection!('n1', 1, null);
86
+ expect(w.targets('in_focus', 'c3')).toEqual([]);
87
+ expect(w.targets('in_focus', 'c1')).toEqual(['f-a']);
88
+ });
89
+
90
+ it('filing a previously unfiled section files its (unfiled) commitments', async () => {
91
+ const w = world();
92
+ await w.api.fileSection!('n1', 2, 'f-debug');
93
+ expect(w.targets('in_focus', 'c4')).toEqual(['f-debug']);
94
+ });
95
+
96
+ it('moving the whole note (sectioned) moves every section\'s commitments', async () => {
97
+ const w = world();
98
+ await w.api.file('n1', 'f-z');
99
+ for (const id of ['c1', 'c2', 'c3', 'c4']) expect(w.targets('in_focus', id)).toEqual(['f-z']);
100
+ expect(w.targets('in_focus', 'c5')).toEqual(['f-a']);
101
+ expect(w.targets('about_focus', 'n1')).toEqual(['f-z']);
102
+ });
103
+
104
+ it('moving a legacy single-section note (no voice_sections) moves its commitments', async () => {
105
+ const rows = ROWS(); rows[0] = note(undefined) as never;
106
+ const edges = EDGES().filter((e) => !(e.rel_type === 'about_focus' && e.target === 'f-debug'));
107
+ const w = world(rows, edges);
108
+ await w.api.file('n1', 'f-z');
109
+ // Whole-note move: every to-do that sat in the note's old project follows it.
110
+ expect(w.targets('in_focus', 'c1')).toEqual(['f-z']);
111
+ expect(w.targets('in_focus', 'c2')).toEqual(['f-z']);
112
+ expect(w.targets('in_focus', 'c3')).toEqual(['f-debug']); // filed elsewhere than the note's project
113
+ expect(w.targets('about_focus', 'n1')).toEqual(['f-z']);
114
+ });
115
+
116
+ it('unfiling a legacy note (null) clears its commitments from the old project', async () => {
117
+ const rows = ROWS(); rows[0] = note(undefined) as never;
118
+ const w = world(rows, EDGES().filter((e) => !(e.rel_type === 'about_focus' && e.target === 'f-debug')));
119
+ await w.api.file('n1', null);
120
+ expect(w.targets('in_focus', 'c1')).toEqual([]);
121
+ expect(w.targets('about_focus', 'n1')).toEqual([]);
122
+ });
123
+
124
+ it('a commitment written before sections were stored on mentions is found by its quote', async () => {
125
+ const rows = ROWS();
126
+ for (const r of rows) for (const m of ((r.data as any).mentions ?? [])) delete m.section;
127
+ const w = world(rows);
128
+ await w.api.fileSection!('n1', 0, 'f-b');
129
+ expect(w.targets('in_focus', 'c1')).toEqual(['f-b']);
130
+ expect(w.targets('in_focus', 'c2')).toEqual(['f-b']);
131
+ expect(w.targets('in_focus', 'c3')).toEqual(['f-debug']);
132
+ });
133
+
134
+ it('keeps a project a person picked by hand: only rows still under the section\'s old project move', async () => {
135
+ const edges = EDGES().filter((e) => !(e.source === 'c2'));
136
+ edges.push({ rel_type: 'in_focus', source: 'c2', target: 'f-hand' });
137
+ const w = world(ROWS(), edges);
138
+ await w.api.fileSection!('n1', 0, 'f-b');
139
+ expect(w.targets('in_focus', 'c1')).toEqual(['f-b']);
140
+ expect(w.targets('in_focus', 'c2')).toEqual(['f-hand']);
141
+ });
142
+
143
+ it('is idempotent: filing the same project again writes nothing', async () => {
144
+ const w = world();
145
+ await w.api.fileSection!('n1', 0, 'f-b');
146
+ w.log.length = 0;
147
+ await w.api.fileSection!('n1', 0, 'f-b');
148
+ expect(w.log.filter((l) => l.includes('in_focus'))).toEqual([]);
149
+ expect(w.targets('in_focus', 'c1')).toEqual(['f-b']);
150
+ });
151
+
152
+ it('a retry after a half-finished move converges (no duplicate edge)', async () => {
153
+ const w = world();
154
+ // c1 already moved, c2 not — as after a crash mid-way.
155
+ await w.http.delete(`api/v1/relationships/${w.edges.find((e) => e.source === 'c1')!.id}`);
156
+ await w.http.post('api/v1/relationships', { rel_type: 'in_focus', source: 'c1', target: 'f-b' });
157
+ await w.api.fileSection!('n1', 0, 'f-b');
158
+ expect(w.targets('in_focus', 'c1')).toEqual(['f-b']);
159
+ expect(w.targets('in_focus', 'c2')).toEqual(['f-b']);
160
+ });
161
+
162
+ it('the native controller moves commitments through the same path', async () => {
163
+ const w = world();
164
+ const controller = createVoiceNotesController({ api: w.api });
165
+ await controller.refresh();
166
+ await controller.file('n1', 'f-z');
167
+ expect(w.targets('in_focus', 'c1')).toEqual(['f-z']);
168
+ expect(w.targets('in_focus', 'c3')).toEqual(['f-z']);
169
+ expect(controller.getState().error).toBeNull();
170
+ });
171
+ });
172
+
173
+ describe('fileCommitment replaces, never adds', () => {
174
+ const api = (t: ReturnType<typeof fakeTenant>) => createPlanningApi({ http: t.http as never, scope: { orgId: 'o' } as never });
175
+ const item = (id: string) => ({ id } as never);
176
+
177
+ it('removes the old in_focus edge when filing under a new project', async () => {
178
+ const t = fakeTenant({ edges: [{ rel_type: 'in_focus', source: 'c1', target: 'f-a' }] });
179
+ await api(t).fileCommitment!(item('c1'), 'f-b');
180
+ expect(t.targets('in_focus', 'c1')).toEqual(['f-b']);
181
+ });
182
+
183
+ it('collapses an already doubled-up item to the one project', async () => {
184
+ const t = fakeTenant({ edges: [
185
+ { rel_type: 'in_focus', source: 'c1', target: 'f-a' }, { rel_type: 'in_focus', source: 'c1', target: 'f-b' },
186
+ ] });
187
+ await api(t).fileCommitment!(item('c1'), 'f-b');
188
+ expect(t.targets('in_focus', 'c1')).toEqual(['f-b']);
189
+ });
190
+
191
+ it('is idempotent and unfiles with null', async () => {
192
+ const t = fakeTenant({ edges: [{ rel_type: 'in_focus', source: 'c1', target: 'f-a' }] });
193
+ await api(t).fileCommitment!(item('c1'), 'f-a');
194
+ expect(t.log).toEqual([]);
195
+ await api(t).fileCommitment!(item('c1'), null);
196
+ expect(t.targets('in_focus', 'c1')).toEqual([]);
197
+ });
198
+ });
199
+
200
+ describe('the section a to-do came from is stored at creation', () => {
201
+ it('extraction puts the section heading on the mention and it survives the row round-trip', () => {
202
+ const doc = toSourceDocument(
203
+ { id: 'n1', name: 'n', data: { source: 'voice', title: 't', summary: SUMMARY, body: '', voice_sections: SECTIONS } } as never,
204
+ { orgId: 'o' } as never,
205
+ );
206
+ const drafts = rulesExtract(doc);
207
+ expect(drafts.map((d) => d.section)).toEqual(['287A', '287A', 'Debug', 'Personal']);
208
+ const c = {
209
+ ...toCommitment({ id: 'c1', external_id: 'commit:x', data: commitmentToEntity({
210
+ id: 'c1', externalId: 'commit:x', dedupeKey: 'x', subtype: 'action', title: 'T', detail: '', status: 'open',
211
+ subjectKey: '', actionKey: '', firstSeenAt: null, lastSeenAt: null, extractorVersion: 'v', source: 'voice', sourceLabel: 'Voice note',
212
+ scope: { orgId: 'o' } as never,
213
+ mentions: [{ documentId: 'n1', originKey: 'k', occurredAt: null, quote: 'q', extractor: 'rules', section: 'Debug' }],
214
+ } as never).data } as never, { orgId: 'o' } as never),
215
+ };
216
+ expect(c.mentions[0].section).toBe('Debug');
217
+ });
218
+ });
@@ -50,7 +50,7 @@ import type {
50
50
  CorpusTypeKeys, TenantEntity, TenantFacetRow, TenantRelationship,
51
51
  } from './entities';
52
52
  import { entityParams } from './entity-query';
53
- import { ABOUT_FOCUS, createFilingApi } from './filing';
53
+ import { ABOUT_FOCUS, createFilingApi, setCommitmentFocus } from './filing';
54
54
  import {
55
55
  FOCUS_TYPE,
56
56
  IN_FOCUS,
@@ -1357,24 +1357,15 @@ export function createPlanningApi(options: CreateCorpusApiOptions): PlanningApi
1357
1357
  return toCommitment(updated, scope, sourceLabels);
1358
1358
  },
1359
1359
 
1360
+ // Replace, never add (bd startsim-23np6.1.1): one writer, in ./filing.
1360
1361
  async fileCommitment(item: Commitment, focusId: string | null): Promise<void> {
1361
- const post = writer();
1362
- if (focusId !== null) {
1363
- await post(relationships, { rel_type: IN_FOCUS, source: item.id, target: focusId });
1364
- return;
1365
- }
1366
- if (!http.delete) {
1362
+ writer();
1363
+ if (focusId === null && !http.delete) {
1367
1364
  // Said out loud rather than resolving. A control that appears to unfile
1368
1365
  // and does not is worse than one that is disabled.
1369
1366
  throw new Error('This planning client cannot unfile — no delete method was supplied.');
1370
1367
  }
1371
- const del = http.delete.bind(http);
1372
- const page = await http.get<DrfPage<TenantRelationship>>(relationships, {
1373
- params: { rel_type: IN_FOCUS, source: item.id },
1374
- });
1375
- for (const edge of page.results ?? []) {
1376
- await del(`${relationships}/${edge.id}`);
1377
- }
1368
+ await setCommitmentFocus(http, item.id, focusId, { relationships });
1378
1369
  },
1379
1370
 
1380
1371
  /**
@@ -369,7 +369,7 @@ function signature(commitment: Commitment): string {
369
369
  commitment.resolvedBy ?? '',
370
370
  commitment.firstSeenAt ?? '',
371
371
  commitment.lastSeenAt ?? '',
372
- commitment.mentions.map((mention) => `${mentionKey(mention)}|${mention.quote}`).join('~'),
372
+ commitment.mentions.map((mention) => `${mentionKey(mention)}|${mention.quote}|${mention.section ?? ''}`).join('~'),
373
373
  ].join('\u0000');
374
374
  }
375
375
 
@@ -380,6 +380,7 @@ function toMention(draft: CommitmentDraft, document: SourceDocument): Commitment
380
380
  occurredAt: iso(document.occurredAt),
381
381
  quote: draft.quote ?? '',
382
382
  extractor: draft.extractor,
383
+ ...(draft.section ? { section: draft.section } : {}),
383
384
  };
384
385
  }
385
386
 
@@ -756,6 +756,7 @@ function toMention(value: unknown): CommitmentMention | null {
756
756
  occurredAt: asIso(pick(data, 'occurred_at', 'occurredAt')),
757
757
  quote: asText(pick(data, 'quote')),
758
758
  extractor: extractor === 'model' ? 'model' : 'rules',
759
+ ...(asText(pick(data, 'section')) ? { section: asText(pick(data, 'section')) } : {}),
759
760
  };
760
761
  }
761
762
 
@@ -795,6 +796,7 @@ export function commitmentToEntity(commitment: Commitment): {
795
796
  occurred_at: mention.occurredAt,
796
797
  quote: mention.quote.slice(0, 400),
797
798
  extractor: mention.extractor,
799
+ ...(mention.section ? { section: mention.section } : {}),
798
800
  })),
799
801
  extractor_version: commitment.extractorVersion,
800
802
  source: commitment.source,
@@ -170,7 +170,9 @@ export function rulesExtract(document: SourceDocument): CommitmentDraft[] {
170
170
  const flush = () => {
171
171
  if (!current) return;
172
172
  const draft = toDraft(document, current.line, current.detail.join('\n'));
173
- if (draft) drafts.push(focusId ? { ...draft, focusId } : draft);
173
+ if (draft) {
174
+ drafts.push({ ...draft, ...(focusId ? { focusId } : {}), ...(voice ? { section: section.heading } : {}) });
175
+ }
174
176
  current = null;
175
177
  };
176
178
  for (const line of section.body.split('\n')) {
@@ -13,7 +13,7 @@
13
13
  */
14
14
  import type { CorpusHttp } from './client';
15
15
  import type { TenantEntity, TenantRelationship } from './entities';
16
- import { FOCUS_TYPE } from './planning';
16
+ import { FOCUS_TYPE, IN_FOCUS } from './planning';
17
17
 
18
18
  /** A document is ABOUT a focus — its own edge, never `in_focus`. */
19
19
  export const ABOUT_FOCUS = 'about_focus';
@@ -66,6 +66,34 @@ export async function fileDocument(
66
66
  }
67
67
  }
68
68
 
69
+ /**
70
+ * Replace, never add: a commitment lives in one project (bd startsim-23np6.1.1).
71
+ * Edges to other projects are deleted, an edge to `focusId` is kept or written
72
+ * (none for `null`, which unfiles). Idempotent: nothing is written when the item
73
+ * is already filed exactly there.
74
+ */
75
+ export async function setCommitmentFocus(
76
+ http: CorpusHttp,
77
+ commitmentId: string,
78
+ focusId: string | null,
79
+ paths: FilingPaths = {},
80
+ ): Promise<void> {
81
+ const relationships = paths.relationships ?? 'api/v1/relationships';
82
+ if (!http.post) throw new Error('This client is read-only.');
83
+ const existing = await http.get<Page<TenantRelationship>>(relationships, {
84
+ params: { rel_type: IN_FOCUS, source: commitmentId },
85
+ });
86
+ let kept = false;
87
+ for (const edge of existing.results ?? []) {
88
+ if (focusId !== null && String(edge.target) === focusId && !kept) { kept = true; continue; }
89
+ if (!http.delete) throw new Error('This planning client cannot unfile — no delete method was supplied.');
90
+ await http.delete(`${relationships}/${edge.id}`);
91
+ }
92
+ if (focusId !== null && !kept) {
93
+ await http.post(relationships, { rel_type: IN_FOCUS, source: commitmentId, target: focusId });
94
+ }
95
+ }
96
+
69
97
  /**
70
98
  * Make a document's `about_focus` edges exactly this set of projects — adding
71
99
  * the missing, deleting the ones nobody wants, leaving the rest untouched. The
@@ -634,6 +634,12 @@ export interface CommitmentMention {
634
634
  quote: string;
635
635
  /** `rules` when the vendor's own structure produced it, `model` otherwise. */
636
636
  extractor: 'rules' | 'model';
637
+ /**
638
+ * The voice-note section heading the bullet was spoken under — the stored link
639
+ * from a to-do back to its section, so moving the section can move the to-do
640
+ * (bd startsim-23np6.1.1). Absent on rows written before this, and on other sources.
641
+ */
642
+ section?: string;
637
643
  }
638
644
 
639
645
  /** A trackable thing that came out of a conversation. */
@@ -742,6 +748,8 @@ export interface CommitmentDraft {
742
748
  extractor: 'rules' | 'model';
743
749
  /** The project of the voice-note section this bullet sits in, when that section is filed. */
744
750
  focusId?: string;
751
+ /** That section's heading (voice notes only), kept on the mention. */
752
+ section?: string;
745
753
  }
746
754
 
747
755
  /**
@@ -0,0 +1,142 @@
1
+ /**
2
+ * RE-FILING A VOICE NOTE'S TO-DOS WHEN ITS PROJECT MOVES (bd startsim-23np6.1.1).
3
+ *
4
+ * Extraction files each commitment under the project of the section it was
5
+ * spoken in (`in_focus`, commitment -> focus). Moving a section (or the whole
6
+ * note) changes `about_focus` and `voice_sections`; without this, the section's
7
+ * existing to-dos stayed under the old project.
8
+ *
9
+ * WHICH TO-DOS BELONG TO WHICH SECTION. The mention a commitment keeps of this
10
+ * note carries the section heading it was spoken under (`mention.section`, set
11
+ * at extraction). Rows written before that field existed are placed by their
12
+ * mention's `quote` — the verbatim bullet — found under its `## heading` in the
13
+ * note's own summary. A to-do that neither says nor can be found is left alone.
14
+ *
15
+ * WHAT MOVES. A to-do follows its section only while it still sits where the
16
+ * section used to be filed (an edge to the old project, or no edge when the
17
+ * section was unfiled). One a person has since filed somewhere else is theirs:
18
+ * the extractor never overwrites a person's edit (see `reconcile`), and neither
19
+ * does this. Only the old edge is removed, so a second project a person added
20
+ * is not lost. Idempotent: a retry after a half-finished move converges.
21
+ */
22
+ import type { CorpusHttp } from './client';
23
+ import { DEFAULT_TYPE_KEYS, toCommitment } from './entities';
24
+ import type { TenantEntity, TenantRelationship } from './entities';
25
+ import type { FilingPaths } from './filing';
26
+ import { ABOUT_FOCUS } from './filing';
27
+ import { IN_FOCUS } from './planning';
28
+ import type { CorpusScope } from './types';
29
+ import { sectionKey } from './voice-sections';
30
+
31
+ /** One section changing project. `label` null = the whole of a note that has no sections. */
32
+ export interface FilingMove {
33
+ label: string | null;
34
+ from: string | null;
35
+ to: string | null;
36
+ }
37
+
38
+ type Page<T> = { results?: T[]; next?: string | null };
39
+
40
+ const MAX_PAGES = 50;
41
+ const EDGE_CHUNK = 25;
42
+
43
+ const HEADING = /^\s*#{1,6}\s+(.+?)\s*$/;
44
+
45
+ /** The `## heading` a verbatim bullet sits under in the note's summary, or null. */
46
+ export function sectionOfQuote(summary: string, quote: string): string | null {
47
+ const wanted = quote.trim();
48
+ if (!wanted) return null;
49
+ let heading: string | null = null;
50
+ for (const line of (summary ?? '').split('\n')) {
51
+ const h = HEADING.exec(line);
52
+ if (h) { heading = h[1]; continue; }
53
+ const flat = line.trim();
54
+ if (heading !== null && flat && (flat === wanted || flat.slice(0, wanted.length) === wanted)) return heading;
55
+ }
56
+ return null;
57
+ }
58
+
59
+ /** The project a note without sections is filed under now (its first `about_focus` edge). */
60
+ export async function currentNoteFocus(
61
+ http: CorpusHttp,
62
+ noteId: string,
63
+ paths: FilingPaths = {},
64
+ ): Promise<string | null> {
65
+ const edges = await http.get<Page<TenantRelationship>>(paths.relationships ?? 'api/v1/relationships', {
66
+ params: { rel_type: ABOUT_FOCUS, source: noteId },
67
+ });
68
+ const first = edges.results?.[0];
69
+ return first ? String(first.target) : null;
70
+ }
71
+
72
+ /** Every voice-sourced commitment row (paged). The tenant cannot filter inside `mentions`, so the note is picked out here. */
73
+ async function voiceCommitments(http: CorpusHttp, entities: string): Promise<TenantEntity[]> {
74
+ const out: TenantEntity[] = [];
75
+ for (let page = 1; page <= MAX_PAGES; page += 1) {
76
+ const response = await http.get<Page<TenantEntity>>(entities, {
77
+ params: { type: DEFAULT_TYPE_KEYS.commitment, 'attr.source': 'voice', page, page_size: 200 },
78
+ });
79
+ out.push(...(response.results ?? []));
80
+ if (!response.next) break;
81
+ }
82
+ return out;
83
+ }
84
+
85
+ export async function refileVoiceCommitments(
86
+ http: CorpusHttp,
87
+ note: { id: string; summary: string },
88
+ scope: CorpusScope,
89
+ moves: FilingMove[],
90
+ paths: FilingPaths = {},
91
+ ): Promise<void> {
92
+ const real = moves.filter((m) => m.from !== m.to);
93
+ if (!real.length) return;
94
+ if (!http.post) throw new Error('This client is read-only.');
95
+ const entities = paths.entities ?? 'api/v1/entities';
96
+ const relationships = paths.relationships ?? 'api/v1/relationships';
97
+
98
+ // 1. this note's commitments, each with the move that applies to it.
99
+ const matched: Array<{ id: string; move: FilingMove }> = [];
100
+ for (const entity of await voiceCommitments(http, entities)) {
101
+ const item = toCommitment(entity, scope);
102
+ const mention = item.mentions.find((m) => m.documentId === note.id);
103
+ if (!mention) continue;
104
+ const move = real.find((m) => m.label === null)
105
+ ?? real.find((m) => {
106
+ const label = mention.section ?? sectionOfQuote(note.summary, mention.quote);
107
+ return label !== null && sectionKey(label) === sectionKey(m.label as string);
108
+ });
109
+ if (move) matched.push({ id: item.id, move });
110
+ }
111
+ if (!matched.length) return;
112
+
113
+ // 2. where each one is filed now.
114
+ const edgesOf = new Map<string, TenantRelationship[]>();
115
+ for (let i = 0; i < matched.length; i += EDGE_CHUNK) {
116
+ const ids = matched.slice(i, i + EDGE_CHUNK).map((m) => m.id);
117
+ const page = await http.get<Page<TenantRelationship>>(relationships, {
118
+ params: { rel_type: IN_FOCUS, entity__in: ids.join(','), page_size: 200 },
119
+ });
120
+ for (const edge of page.results ?? []) {
121
+ const source = String(edge.source);
122
+ if (!ids.includes(source)) continue;
123
+ edgesOf.set(source, [...(edgesOf.get(source) ?? []), edge]);
124
+ }
125
+ }
126
+
127
+ // 3. move the ones still where the section used to be. New edge first, so a
128
+ // crash between the two writes leaves it in both places (a retry fixes that),
129
+ // never in neither.
130
+ for (const { id, move } of matched) {
131
+ const edges = edgesOf.get(id) ?? [];
132
+ const follows = move.from === null ? edges.length === 0 : edges.some((e) => String(e.target) === move.from);
133
+ if (!follows) continue;
134
+ if (move.to !== null && !edges.some((e) => String(e.target) === move.to)) {
135
+ await http.post(relationships, { rel_type: IN_FOCUS, source: id, target: move.to });
136
+ }
137
+ if (move.from !== null) {
138
+ if (!http.delete) throw new Error('This client cannot move a note — no delete method was supplied.');
139
+ for (const edge of edges) if (String(edge.target) === move.from) await http.delete(`${relationships}/${edge.id}`);
140
+ }
141
+ }
142
+ }
@@ -30,6 +30,8 @@ import type { TenantEntity, TenantRelationship } from './entities';
30
30
  import type { CorpusScope } from './types';
31
31
  import { ABOUT_FOCUS, fileDocument, listFocusChoices, setDocumentFocuses } from './filing';
32
32
  import { filingsFromRow, filingsToRow, uniqueFocusIds } from './voice-sections';
33
+ import { currentNoteFocus, refileVoiceCommitments } from './voice-refile';
34
+ import type { FilingMove } from './voice-refile';
33
35
  import type { SectionFiling, VoiceSection } from './voice-sections';
34
36
  import type { FocusChoice } from './filing';
35
37
 
@@ -416,21 +418,29 @@ export function createVoiceApi(options: CreateVoiceApiOptions): VoiceNotesApi {
416
418
  const submit = options.server?.upload ?? options.upload;
417
419
  if (!submit) throw new Error('createVoiceApi needs an upload function or a server client.');
418
420
 
419
- async function readFilings(noteId: string): Promise<{ row: TenantEntity; filings: SectionFiling[] }> {
421
+ async function readFilings(noteId: string): Promise<{ row: TenantEntity; filings: SectionFiling[]; summary: string }> {
420
422
  const row = await http.get<TenantEntity>(`api/v1/entities/${encodeURIComponent(noteId)}`);
421
423
  const data = (row?.data ?? {}) as Record<string, unknown>;
422
- return { row, filings: filingsFromRow(data.voice_sections ?? data.voiceSections) };
424
+ return { row, filings: filingsFromRow(data.voice_sections ?? data.voiceSections), summary: text(data.summary) };
423
425
  }
424
- /** The ONE writer of section filing: the sections on the row, then the edges as their union. */
425
- async function writeFilings(noteId: string, row: TenantEntity, filings: SectionFiling[]): Promise<void> {
426
+ /**
427
+ * The ONE writer of section filing: the to-dos those sections produced, then
428
+ * the sections on the row, then the edges as their union. To-dos go first so a
429
+ * failure part-way leaves the row as it was and a retry finishes the job.
430
+ */
431
+ async function writeFilings(
432
+ noteId: string, row: TenantEntity, summary: string, before: SectionFiling[], after: SectionFiling[],
433
+ ): Promise<void> {
426
434
  if (!http.post) throw new Error('This client is read-only.');
435
+ const moves: FilingMove[] = after.map((f, i) => ({ label: f.label, from: before[i]?.focusId ?? null, to: f.focusId }));
436
+ await refileVoiceCommitments(http, { id: noteId, summary }, options.scope, moves);
427
437
  await http.post('api/v1/entities/upsert', {
428
438
  entity_type: 'source_document',
429
439
  external_id: row.external_id ?? row.externalId,
430
440
  name: row.name,
431
- data: { voice_sections: filingsToRow(filings) },
441
+ data: { voice_sections: filingsToRow(after) },
432
442
  });
433
- await setDocumentFocuses(http, noteId, uniqueFocusIds(filings));
443
+ await setDocumentFocuses(http, noteId, uniqueFocusIds(after));
434
444
  }
435
445
 
436
446
  return {
@@ -465,17 +475,21 @@ export function createVoiceApi(options: CreateVoiceApiOptions): VoiceNotesApi {
465
475
 
466
476
  // Replace, never add. A note with sections moves every section to the one
467
477
  // project (the sections are what say where it lives); one without keeps the
468
- // plain single-edge move.
478
+ // plain single-edge move. Either way the note's existing to-dos follow.
469
479
  async file(noteId, focusId) {
470
- const { row, filings } = await readFilings(noteId);
471
- if (!filings.length) return fileDocument(http, noteId, focusId);
472
- await writeFilings(noteId, row, filings.map((f) => ({ ...f, focusId })));
480
+ const { row, filings, summary } = await readFilings(noteId);
481
+ if (!filings.length) {
482
+ const from = await currentNoteFocus(http, noteId);
483
+ await refileVoiceCommitments(http, { id: noteId, summary }, options.scope, [{ label: null, from, to: focusId }]);
484
+ return fileDocument(http, noteId, focusId);
485
+ }
486
+ await writeFilings(noteId, row, summary, filings, filings.map((f) => ({ ...f, focusId })));
473
487
  },
474
488
 
475
489
  async fileSection(noteId, sectionIndex, focusId) {
476
- const { row, filings } = await readFilings(noteId);
490
+ const { row, filings, summary } = await readFilings(noteId);
477
491
  if (!filings[sectionIndex]) throw new Error('That section no longer exists.');
478
- await writeFilings(noteId, row, filings.map((f, i) => (i === sectionIndex ? { ...f, focusId } : f)));
492
+ await writeFilings(noteId, row, summary, filings, filings.map((f, i) => (i === sectionIndex ? { ...f, focusId } : f)));
479
493
  },
480
494
  };
481
495
  }
@@ -51,14 +51,18 @@ describe('createNativeVoiceApi', () => {
51
51
  });
52
52
 
53
53
  it('file replaces the about_focus edge using post + delete', async () => {
54
- const f = vi.fn()
55
- .mockResolvedValueOnce(res({ id: '7', data: {} }))
56
- .mockResolvedValueOnce(res({ results: [{ id: 5 }] }))
57
- .mockResolvedValue(res({}));
58
- const api = createNativeVoiceApi({ baseUrl: 'http://t', authorizedFetch: f });
54
+ const f = vi.fn(async (url: string, init: { method: string }) => {
55
+ const path = url.replace('http://t/', '').split('?')[0];
56
+ if (init.method === 'GET' && path === 'api/v1/entities/7') return res({ id: '7', data: {} });
57
+ if (init.method === 'GET' && path === 'api/v1/relationships') return res({ results: [{ id: 5, target: 'f1' }] });
58
+ if (init.method === 'GET') return res({ results: [] }); // no to-dos from this note
59
+ return res({});
60
+ });
61
+ const api = createNativeVoiceApi({ baseUrl: 'http://t', authorizedFetch: f as never });
59
62
  await api.file('7', 'f9');
60
63
  const calls = f.mock.calls.map((c) => `${c[1].method} ${c[0].replace('http://t/', '').split('?')[0]}`);
61
- expect(calls).toEqual(['GET api/v1/entities/7', 'GET api/v1/relationships', 'DELETE api/v1/relationships/5', 'POST api/v1/relationships']);
64
+ expect(calls.filter((c) => c.endsWith('relationships/5') || c === 'POST api/v1/relationships')).toEqual(['DELETE api/v1/relationships/5', 'POST api/v1/relationships']);
65
+ expect(calls[0]).toBe('GET api/v1/entities/7');
62
66
  });
63
67
 
64
68
  it('submit is not offered (recording uploads go through the upload queue)', async () => {