@startsimpli/integrations 0.2.67 → 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/README.md CHANGED
@@ -189,6 +189,31 @@ the screens need the OPTIONAL peers `react-native`, `react-native-safe-area-cont
189
189
  5. Check without a login: launch with `-tgFakeNotes list` (or a note id such as `n1`) to see the screens over `createFakeVoiceApi`.
190
190
  6. `npx expo prebuild --platform ios`, then `npx expo run:ios --configuration Release` (Hermes). Signing and device install are per-Apple-team, see the template README.
191
191
 
192
+ ### Tabs: `FoundryTabsShell` and the shared corpus data layer (bd startsim-23np6.1)
193
+
194
+ Every Tandem web tab becomes an iOS tab from config. `NotesShell` is just the first preset.
195
+
196
+ | Export | What |
197
+ |---|---|
198
+ | `FoundryTabsShell({ tabs, initialTab?, initialDetail?, navigator? })` | Bottom tabs driven by `[{ key, label, icon?, render(ctx), safeArea?, resetOnLeave? }]`. A tab is mounted when first shown and then kept (hidden) so its state survives switching. `ctx` = `{ route, push(id, params?), back(), openTab(key, id?), active }`: `route` null = your list, set = your detail with Back. |
199
+ | `createTabsNavigator`, `parseTabLink`, `readTabLaunchTarget` | The framework-free state behind the shell. Deep links: `navigator.open('tracker', { id })`; launch args: `-tgTab tracker -tgDetail <id>`. |
200
+ | `createNativeCorpusApi({ baseUrl, authorizedFetch })` | One object: `entities` (`list`/`get`/`facets`), `relationships.list`, `corpus` (the web composers' own Library / Tracker / Planning api), `commitments.setStatus`, `ask` (POST `corpus/ask`), and `lists.*` paged controllers. |
201
+ | `createPagedList({ fetchPage })` | Server paging as a controller: `refresh`, `loadMore`, `setQuery`; state has `items`, `count`, `hasMore`, `error` and `ignoredFilters`. |
202
+ | `entityParams` / `reconcileFilters` / `toEntityPage` (also exported from the package root) | The ONE spelling of the tenant query (`page`, `page_size` max 200, `search`, `order=recent\|oldest\|relevance\|[-]attr.x`, `filters`, `attr`) and the check of the server's `applied_filters`. The web adapter uses the same function. |
203
+ | `createFakeNativeCorpusApi()`, `createFakeTenantHttp()` | The real adapters over an in-memory tenant that honours the same query contract (paging, order, attr operators, edge walks, applied/ignored report). `unsupported: ['attr.status']` plays a fork that ignores a filter. |
204
+
205
+ Rules every list tab follows: one server request per page (never load a list and filter/sort/page it on the phone); show `ignoredFilters` instead of presenting an unapplied filter as applied; sort by an attribute with `order: 'attr.due_at'` (undated rows sort last).
206
+
207
+ **Adding a tab** (a screen agent's whole job):
208
+
209
+ 1. **Controller** (pure, vitest): wrap `api.lists.<x>(query)` or `createPagedList` with your actions (for example `api.commitments.setStatus` optimistic with rollback). Put it in `src/native/<tab>/controller.ts` with tests that use `createFakeNativeCorpusApi()`.
210
+ 2. **Screen** (`src/native/<tab>/ListScreen.tsx`, `DetailScreen.tsx`): `@startsimpli/ui-native` primitives only; subscribe with `useSyncExternalStore`; `onEndReached={() => list.loadMore()}`.
211
+ 3. **Config entry**: `{ key: 'tracker', label: 'To-dos', render: ({ route, push, back }) => route ? <Detail id={route.id} onBack={back} /> : <List onOpen={(c) => push(c.id)} /> }`, added to the `tabs` array the app passes to `FoundryTabsShell` (or a new preset beside `NotesShell`).
212
+ 4. **Fake**: extend `sampleTenantEntities()` / `sampleTenantRelationships()` in `native/corpus/fake-data.ts` with rows for your tab. The fake tenant already serves them through the contract, so the simulator (`-tgTab <key>`) and the tests show real mapped data with no sign-in and no tenant.
213
+ 5. Export from `native/index.ts`, run `pnpm type-check && pnpm test` in this package.
214
+
215
+ Not wired yet: `mcpTokens` and `connectionsMe` (`src/api/*`) call a module-global `request()` that does not use `authorizedFetch`; the Connections / Connect Claude tabs need a `create*Api(fetch)` factory first.
216
+
192
217
  ## Verification
193
218
 
194
219
  ```bash
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@startsimpli/integrations",
3
- "version": "0.2.67",
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,122 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import {
3
+ entityParams, facetParams, reconcileFilters, relationshipParams, toEntityPage,
4
+ } from '../corpus/entity-query';
5
+
6
+ describe('entityParams serialization', () => {
7
+ it('defaults to page 1 and always carries the type', () => {
8
+ expect(entityParams({ type: 'commitment' })).toEqual({ type: 'commitment', page: 1 });
9
+ });
10
+ it('caps page_size at the server max and floors it at 1', () => {
11
+ expect(entityParams({ type: 't', pageSize: 999 }).page_size).toBe(200);
12
+ expect(entityParams({ type: 't', pageSize: 0 }).page_size).toBeUndefined();
13
+ expect(entityParams({ type: 't', pageSize: 25, page: 3 })).toMatchObject({ page: 3, page_size: 25 });
14
+ });
15
+ it('sends a trimmed search, never a blank one', () => {
16
+ expect(entityParams({ type: 't', search: ' lease ' }).search).toBe('lease');
17
+ expect(entityParams({ type: 't', search: ' ' }).search).toBeUndefined();
18
+ });
19
+ it('sends relevance only alongside a search', () => {
20
+ expect(entityParams({ type: 't', order: 'relevance' }).order).toBeUndefined();
21
+ expect(entityParams({ type: 't', order: 'relevance', search: 'x' }).order).toBe('relevance');
22
+ expect(entityParams({ type: 't', order: 'oldest' }).order).toBe('oldest');
23
+ expect(entityParams({ type: 't', order: 'recent' }).order).toBe('recent');
24
+ });
25
+ it('orders by an attribute, either direction', () => {
26
+ expect(entityParams({ type: 't', order: 'attr.due_at' }).order).toBe('attr.due_at');
27
+ expect(entityParams({ type: 't', order: '-attr.progress' }).order).toBe('-attr.progress');
28
+ });
29
+ it('serializes every first-class filter', () => {
30
+ expect(entityParams({
31
+ type: 't',
32
+ filters: {
33
+ id: 'i', idIn: ['a', 'b'], externalId: 'e', externalIdIn: ['x,1', 'y'], source: 's', party: 'p', scope: '/ogmc',
34
+ occurredAfter: 'oa', occurredBefore: 'ob', createdAfter: 'ca', createdBefore: 'cb',
35
+ },
36
+ })).toMatchObject({
37
+ id: 'i', id__in: 'a,b', external_id: 'e', source: 's', party: 'p', scope: '/ogmc',
38
+ occurred_after: 'oa', occurred_before: 'ob', created_after: 'ca', created_before: 'cb',
39
+ });
40
+ });
41
+ it('sends external_id__in as a repeated parameter, not a comma list', () => {
42
+ expect(entityParams({ type: 't', filters: { externalIdIn: ['x,1', 'y'] } }).external_id__in).toEqual(['x,1', 'y']);
43
+ });
44
+ it('refuses more than 200 ids in a list rather than letting the server 400', () => {
45
+ const ids = Array.from({ length: 201 }, (_, i) => String(i));
46
+ expect(() => entityParams({ type: 't', filters: { idIn: ids } })).toThrow(/at most 200/);
47
+ expect(() => entityParams({ type: 't', filters: { externalIdIn: ids } })).toThrow(/at most 200/);
48
+ });
49
+ it('serializes an edge walk, and drops companions that have no target', () => {
50
+ expect(entityParams({
51
+ type: 't', filters: { relatedTo: 'f1', relatedVia: ['in_focus', 'about_focus'], relatedDirection: 'out', relatedDepth: 2 },
52
+ })).toMatchObject({ related_to: 'f1', related_via: 'in_focus,about_focus', related_direction: 'out', related_depth: 2 });
53
+ const orphan = entityParams({ type: 't', filters: { relatedDirection: 'out', relatedVia: 'in_focus' } });
54
+ expect(orphan.related_direction).toBeUndefined();
55
+ expect(orphan.related_via).toBeUndefined();
56
+ });
57
+ it('serializes attribute filters with operators and comma-joined __in lists', () => {
58
+ expect(entityParams({
59
+ type: 't',
60
+ attr: { status: 'open', status__in: ['open', 'blocked'], due_at__lte: '2026-11-01', done: false, n__gte: 0, skip: undefined, none: null, empty: [] },
61
+ })).toMatchObject({
62
+ 'attr.status': 'open', 'attr.status__in': 'open,blocked', 'attr.due_at__lte': '2026-11-01', 'attr.done': false, 'attr.n__gte': 0,
63
+ });
64
+ const p = entityParams({ type: 't', attr: { skip: undefined, none: null, empty: [] } });
65
+ expect(Object.keys(p)).toEqual(['type', 'page']);
66
+ });
67
+ });
68
+
69
+ describe('facetParams and relationshipParams', () => {
70
+ it('facets carry attr + under + the entity vocabulary, and never search/order', () => {
71
+ const p = facetParams({ type: 'source_document', facetAttr: 'path', under: '/Contracts', filters: { source: 'dropbox' }, attr: { status: 'open' } });
72
+ expect(p).toEqual({ type: 'source_document', attr: 'path', page: 1, under: '/Contracts', source: 'dropbox', 'attr.status': 'open' });
73
+ });
74
+ it('relationships serialize every filter', () => {
75
+ expect(relationshipParams({
76
+ source: 's', target: 't', entity: 'e', sourceIn: ['a'], targetIn: ['b', 'c'], entityIn: ['d'],
77
+ relType: ['in_focus', 'involves'], sourceType: 'commitment', targetType: 'focus', page: 2, pageSize: 50,
78
+ })).toEqual({
79
+ page: 2, page_size: 50, source: 's', target: 't', entity: 'e', source__in: 'a', target__in: 'b,c', entity__in: 'd',
80
+ rel_type: 'in_focus,involves', source_type: 'commitment', target_type: 'focus',
81
+ });
82
+ });
83
+ });
84
+
85
+ describe('reconcileFilters: an ignored filter is never shown as applied', () => {
86
+ const sent = entityParams({ type: 'commitment', search: 'x', order: 'attr.due_at', attr: { status: 'open' }, filters: { relatedTo: 'f', relatedDirection: 'out' } });
87
+ it('confirms what the server names in applied_filters', () => {
88
+ const v = reconcileFilters(sent, { applied_filters: ['type', 'search', 'order', 'attr.status', 'related_to', 'related_direction'] });
89
+ expect(v.ignored).toEqual([]);
90
+ expect(v.reported).toBe(true);
91
+ expect(v.applied).toContain('attr.status');
92
+ });
93
+ it('flags a filter the server left out or listed under ignored_filters', () => {
94
+ const v = reconcileFilters(sent, {
95
+ applied_filters: ['type', 'search', 'related_to', 'related_direction'],
96
+ ignored_filters: ['attr.status'],
97
+ });
98
+ expect(v.ignored.sort()).toEqual(['attr.status', 'order']);
99
+ });
100
+ it('reads the camelCased spelling too', () => {
101
+ expect(reconcileFilters({ type: 't', page: 1, search: 'x' }, { appliedFilters: ['type', 'search'] }).ignored).toEqual([]);
102
+ });
103
+ it('treats a server that reports nothing as unconfirmed, not applied', () => {
104
+ const v = reconcileFilters({ type: 't', page: 1, 'attr.status': 'open' }, {});
105
+ expect(v.reported).toBe(false);
106
+ expect(v.ignored).toEqual(['type', 'attr.status']);
107
+ });
108
+ it('accepts related_to as confirmation of a party filter', () => {
109
+ expect(reconcileFilters({ type: 't', page: 1, party: 'p' }, { applied_filters: ['type', 'related_to'] }).ignored).toEqual([]);
110
+ });
111
+ it('does not count paging as a filter', () => {
112
+ expect(reconcileFilters({ type: 't', page: 2, page_size: 10 }, { applied_filters: ['type'] }).ignored).toEqual([]);
113
+ });
114
+ });
115
+
116
+ describe('toEntityPage', () => {
117
+ it('maps rows and derives the next page from the server next link', () => {
118
+ const page = toEntityPage({ type: 't', page: 2 }, { count: 7, next: '?page=3', results: [1, 2], applied_filters: ['type'] }, (n: number) => n * 2);
119
+ expect(page).toMatchObject({ items: [2, 4], count: 7, next: '?page=3', nextPage: 3, ignoredFilters: [], filtersReported: true });
120
+ expect(toEntityPage({ type: 't', page: 3 }, { results: [], applied_filters: ['type'] }, (n: number) => n).nextPage).toBeNull();
121
+ });
122
+ });
@@ -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
+ });
@@ -49,7 +49,8 @@ import {
49
49
  import type {
50
50
  CorpusTypeKeys, TenantEntity, TenantFacetRow, TenantRelationship,
51
51
  } from './entities';
52
- import { ABOUT_FOCUS, createFilingApi } from './filing';
52
+ import { entityParams } from './entity-query';
53
+ import { ABOUT_FOCUS, createFilingApi, setCommitmentFocus } from './filing';
53
54
  import {
54
55
  FOCUS_TYPE,
55
56
  IN_FOCUS,
@@ -363,32 +364,32 @@ function isALiveSource(connection: Record<string, unknown>): boolean {
363
364
  const WRITE_CONCURRENCY = 6;
364
365
 
365
366
  function params(query: DocumentQuery, type: string) {
366
- const out: Record<string, unknown> = { type, page: query.page ?? 1 };
367
- if (query.pageSize) out.page_size = query.pageSize;
368
- if (query.search) out.search = query.search;
369
- // Only alongside a term: `order=relevance` with nothing to be relevant TO is a
370
- // parameter the server has to reject or ignore, and neither is worth asking.
371
- if (query.order && (query.order !== 'relevance' || query.search)) out.order = query.order;
372
- if (query.source) out.source = query.source;
373
- if (query.partyId) out.party = query.partyId;
374
- if (query.focus) {
375
- // Filing is an edge, so "the documents in this project" is an edge walk. A
376
- // document is the SOURCE of its own `about_focus` edge: `out` returns
377
- // documents, `in` returns an empty page (see `commitmentParams`).
378
- out.related_to = query.focus;
379
- out.related_via = ABOUT_FOCUS;
380
- out.related_direction = 'out';
381
- }
382
- if (query.occurredAfter) out.occurred_after = query.occurredAfter;
383
- if (query.occurredBefore) out.occurred_before = query.occurredBefore;
384
- // THE FOLDER BOUNDS, and only ever one of them. `attr.path` is the shelf and
385
- // `attr.path__under` is the subtree; sending both would AND an exact match
386
- // with its own subtree and answer with the shelf, which is the exact-match
387
- // query wearing a second parameter. The composer chooses; this just refuses to
388
- // send a contradiction.
389
- if (query.underFolder) out['attr.path__under'] = query.underFolder;
390
- else if (query.folder) out['attr.path'] = query.folder;
391
- return out;
367
+ // Spelled once, in `entity-query.ts`, so the native adapter cannot drift from
368
+ // this one. Filing is an edge, so "the documents in this project" is an edge
369
+ // walk: a document is the SOURCE of its own `about_focus` edge, `out` returns
370
+ // documents and `in` returns an empty page rather than an error.
371
+ return entityParams({
372
+ type,
373
+ page: query.page,
374
+ pageSize: query.pageSize,
375
+ search: query.search,
376
+ order: query.order,
377
+ filters: {
378
+ source: query.source,
379
+ party: query.partyId,
380
+ occurredAfter: query.occurredAfter,
381
+ occurredBefore: query.occurredBefore,
382
+ ...(query.focus
383
+ ? { relatedTo: query.focus, relatedVia: ABOUT_FOCUS, relatedDirection: 'out' as const }
384
+ : {}),
385
+ },
386
+ // THE FOLDER BOUNDS, and only ever one of them: `attr.path` is the shelf and
387
+ // `attr.path__under` the subtree; sending both would AND an exact match with
388
+ // its own subtree. The composer chooses; this refuses to send a contradiction.
389
+ attr: query.underFolder
390
+ ? { path__under: query.underFolder }
391
+ : query.folder ? { path: query.folder } : undefined,
392
+ });
392
393
  }
393
394
 
394
395
  /**
@@ -436,7 +437,7 @@ function appliedFilters(
436
437
  * verified on the live tenant, 200 with count 180), a body with no id at all,
437
438
  * and a row whose id is somebody else's.
438
439
  */
439
- function isRecord(value: unknown, id: string): value is TenantEntity {
440
+ export function isRecord(value: unknown, id: string): value is TenantEntity {
440
441
  if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
441
442
  // A page is the shape a LIST answers with. It is never one record, whatever
442
443
  // its count happens to be.
@@ -456,7 +457,7 @@ function isRecord(value: unknown, id: string): value is TenantEntity {
456
457
  * principal may not see ABSENT rather than refused — so callers get one status
457
458
  * to branch on, and "not found" is already the honest word for both.
458
459
  */
459
- function notFound(id: string): Error & { status: number } {
460
+ export function notFound(id: string): Error & { status: number } {
460
461
  return Object.assign(new Error(`No record ${id} in this workspace.`), { status: 404 });
461
462
  }
462
463
 
@@ -1356,24 +1357,15 @@ export function createPlanningApi(options: CreateCorpusApiOptions): PlanningApi
1356
1357
  return toCommitment(updated, scope, sourceLabels);
1357
1358
  },
1358
1359
 
1360
+ // Replace, never add (bd startsim-23np6.1.1): one writer, in ./filing.
1359
1361
  async fileCommitment(item: Commitment, focusId: string | null): Promise<void> {
1360
- const post = writer();
1361
- if (focusId !== null) {
1362
- await post(relationships, { rel_type: IN_FOCUS, source: item.id, target: focusId });
1363
- return;
1364
- }
1365
- if (!http.delete) {
1362
+ writer();
1363
+ if (focusId === null && !http.delete) {
1366
1364
  // Said out loud rather than resolving. A control that appears to unfile
1367
1365
  // and does not is worse than one that is disabled.
1368
1366
  throw new Error('This planning client cannot unfile — no delete method was supplied.');
1369
1367
  }
1370
- const del = http.delete.bind(http);
1371
- const page = await http.get<DrfPage<TenantRelationship>>(relationships, {
1372
- params: { rel_type: IN_FOCUS, source: item.id },
1373
- });
1374
- for (const edge of page.results ?? []) {
1375
- await del(`${relationships}/${edge.id}`);
1376
- }
1368
+ await setCommitmentFocus(http, item.id, focusId, { relationships });
1377
1369
  },
1378
1370
 
1379
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,