@startsimpli/integrations 0.2.125 → 0.2.126

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.125",
3
+ "version": "0.2.126",
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",
@@ -51,8 +51,8 @@
51
51
  "@startsimpli/ui-native": ">=0.1.12",
52
52
  "react-native-safe-area-context": ">=4.0.0",
53
53
  "@startsimpli/auth": "^0.4.50",
54
- "@startsimpli/utils": "^0.4.17",
55
- "@startsimpli/ui": "^0.4.171"
54
+ "@startsimpli/ui": "^0.4.171",
55
+ "@startsimpli/utils": "^0.4.17"
56
56
  },
57
57
  "peerDependenciesMeta": {
58
58
  "react": {
@@ -0,0 +1,316 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+
3
+ import { createPlanningApi } from '../corpus/client';
4
+ import {
5
+ commitmentEditSeam, createEntityActionLog, createMemoryActionLog, executeVoiceActions, speakConfirmation,
6
+ type ActionLogStore, type EditableItem, type ItemEditSeam, type VoiceAction,
7
+ } from '../corpus/briefing';
8
+
9
+ const ME = 'me';
10
+ const NOW = Date.parse('2026-11-04T15:00:00Z'); // Wednesday 10:00 in New York
11
+ const TZ = 'America/New_York';
12
+
13
+ /** The tenant's entity verbs in memory: shallow-merging upsert keyed by external_id, GET by id. */
14
+ function fakeTenant(rows: Array<{ id: string; title: string; status?: string; due_at?: string; priority?: number }>) {
15
+ const byExternal = new Map<string, any>();
16
+ let seq = 100;
17
+ for (const r of rows) {
18
+ byExternal.set(`item:${r.id}`, {
19
+ id: r.id, entity_type: 'commitment', external_id: `item:${r.id}`, name: r.title,
20
+ data: { title: r.title, status: r.status ?? 'open', owner_sub: ME, subtype: 'action', ...(r.due_at ? { due_at: r.due_at } : {}), ...(r.priority !== undefined ? { priority: r.priority } : {}) },
21
+ });
22
+ }
23
+ const http = {
24
+ get: vi.fn(async (path: string, options?: { params?: Record<string, unknown> }) => {
25
+ const id = decodeURIComponent(path.split('/').pop() ?? '');
26
+ const hit = [...byExternal.values()].find((r) => String(r.id) === id);
27
+ if (hit) return hit;
28
+ if (options?.params?.external_id__in) return { results: [...byExternal.values()].filter((r) => r.external_id === options.params!.external_id__in) };
29
+ throw Object.assign(new Error('not found'), { status: 404 });
30
+ }),
31
+ post: vi.fn(async (_path: string, body: any) => {
32
+ const prev = byExternal.get(body.external_id);
33
+ const row = { id: prev?.id ?? String(++seq), entity_type: body.entity_type, external_id: body.external_id, name: body.name ?? prev?.name, data: { ...(prev?.data ?? {}), ...body.data } };
34
+ byExternal.set(body.external_id, row);
35
+ return row;
36
+ }),
37
+ };
38
+ const get = (id: string) => byExternal.get(`item:${id}`);
39
+ return { http, get, byExternal };
40
+ }
41
+
42
+ function stack(rows: Parameters<typeof fakeTenant>[0], log: ActionLogStore = createMemoryActionLog()) {
43
+ const tenant = fakeTenant(rows);
44
+ const api = createPlanningApi({ http: tenant.http as never, scope: { orgId: 'org', userId: ME } as never });
45
+ const seam = commitmentEditSeam({ api, http: tenant.http as never, scope: { orgId: 'org', userId: ME } as never });
46
+ const run = (actions: VoiceAction[], id = `a${Math.random()}`, extra: object = {}) =>
47
+ executeVoiceActions({ actions, clientActionId: id, seam, log, ownerSub: ME, now: () => NOW, timeZone: TZ, ...extra });
48
+ return { tenant, seam, log, run, api };
49
+ }
50
+
51
+ const BENCH = { id: 'bench', title: "Order dad's bench", due_at: '2026-11-04' };
52
+ const PAPER = { id: 'paper', title: 'Pick up printer paper', due_at: '2026-11-04', priority: 3 };
53
+
54
+ describe('applying voice actions through the item edit path', () => {
55
+ it('test_defer_sets_due_at (a bare date, not an instant)', async () => {
56
+ const t = stack([BENCH]);
57
+ const out = await t.run([{ type: 'defer', itemId: 'bench', to: '2026-11-09', label: 'next week' }]);
58
+ expect(t.tenant.get('bench').data.due_at).toBe('2026-11-09');
59
+ expect(out.results[0]).toMatchObject({ status: 'applied', itemId: 'bench' });
60
+ });
61
+
62
+ it('test_later_clears_due_at', async () => {
63
+ const t = stack([BENCH]);
64
+ await t.run([{ type: 'defer', itemId: 'bench', to: 'later' }]);
65
+ expect(t.tenant.get('bench').data.due_at).toBeNull();
66
+ });
67
+
68
+ it('test_pull_today_sets_due_at_today (the listener\'s today)', async () => {
69
+ const t = stack([{ id: 'x', title: 'X', due_at: '2026-11-20' }]);
70
+ await t.run([{ type: 'pull_today', itemId: 'x' }]);
71
+ expect(t.tenant.get('x').data.due_at).toBe('2026-11-04');
72
+ });
73
+
74
+ it('test_done_sets_status_done_with_resolved_at', async () => {
75
+ const t = stack([BENCH]);
76
+ await t.run([{ type: 'done', itemId: 'bench' }]);
77
+ expect(t.tenant.get('bench').data).toMatchObject({ status: 'done', resolved_at: new Date(NOW).toISOString() });
78
+ });
79
+
80
+ it('test_drop_sets_dropped', async () => {
81
+ const t = stack([BENCH]);
82
+ await t.run([{ type: 'drop', itemId: 'bench' }]);
83
+ expect(t.tenant.get('bench').data.status).toBe('dropped');
84
+ });
85
+
86
+ it('test_priority_set', async () => {
87
+ const t = stack([BENCH]);
88
+ await t.run([{ type: 'set_priority', itemId: 'bench', priority: 1 }]);
89
+ expect(t.tenant.get('bench').data.priority).toBe(1);
90
+ });
91
+
92
+ it('test_add_item_creates_commitment_owned_by_the_caller_with_due_date', async () => {
93
+ const t = stack([]);
94
+ const out = await t.run([{ type: 'add_item', title: 'Buy printer ink', dueDate: '2026-11-05' }]);
95
+ const created = [...t.tenant.byExternal.values()].find((r) => r.data.title === 'Buy printer ink');
96
+ expect(created).toBeTruthy();
97
+ expect(created.entity_type).toBe('commitment');
98
+ expect(created.data).toMatchObject({ due_at: '2026-11-05', owner_sub: ME, status: 'open' });
99
+ expect(out.results[0]).toMatchObject({ status: 'applied', itemId: created.id });
100
+ });
101
+
102
+ it('test_goes_through_existing_entity_mutation_path_not_a_side_door', async () => {
103
+ const t = stack([BENCH]);
104
+ await t.run([{ type: 'defer', itemId: 'bench', to: '2026-11-06' }]);
105
+ // The one write verb of the planning client: the shallow-merging upsert, carrying ONLY the changed keys.
106
+ const writes = t.tenant.http.post.mock.calls.filter(([, body]: any) => body.entity_type === 'commitment');
107
+ expect(writes).toHaveLength(1);
108
+ expect(writes[0][0]).toBe('api/v1/entities/upsert');
109
+ expect(writes[0][1]).toMatchObject({ external_id: 'item:bench', data: { due_at: '2026-11-06' } });
110
+ expect(Object.keys(writes[0][1].data)).toEqual(['due_at']);
111
+ });
112
+
113
+ it('the seam is the one place an edit happens: a wrapper sees every update (where the Linear push hooks in)', async () => {
114
+ const t = stack([BENCH, PAPER]);
115
+ const seen: Array<[string, object]> = [];
116
+ const wrapped: ItemEditSeam = {
117
+ ...t.seam,
118
+ update: async (item, patch) => { seen.push([item.id, patch]); return t.seam.update(item, patch); },
119
+ };
120
+ await executeVoiceActions({
121
+ actions: [{ type: 'done', itemId: 'bench' }, { type: 'defer', itemId: 'paper', to: 'later' }], clientActionId: 'w', seam: wrapped,
122
+ log: t.log, ownerSub: ME, now: () => NOW, timeZone: TZ,
123
+ });
124
+ expect(seen.map(([id]) => id)).toEqual(['bench', 'paper']);
125
+ expect(seen[1][1]).toEqual({ dueAt: null });
126
+ });
127
+ });
128
+
129
+ describe('idempotency', () => {
130
+ it('test_idempotent_replay_of_same_action_id_applies_once', async () => {
131
+ const t = stack([BENCH]);
132
+ const first = await t.run([{ type: 'defer', itemId: 'bench', to: '2026-11-06' }], 'same-id');
133
+ const edits = () => t.tenant.http.post.mock.calls.filter(([, b]: any) => b.entity_type === 'commitment').length;
134
+ expect(edits()).toBe(1);
135
+ const second = await t.run([{ type: 'defer', itemId: 'bench', to: '2026-11-06' }], 'same-id');
136
+ expect(edits()).toBe(1);
137
+ expect(second.replayed).toBe(true);
138
+ expect(second.text).toBe(first.text);
139
+ // And the replay did not push a second entry on the undo stack.
140
+ expect(second.undoDepth).toBe(1);
141
+ });
142
+
143
+ it('a replay survives a new executor over the same log row (the log is the tenant\'s, not the process\'s)', async () => {
144
+ const t = stack([BENCH]);
145
+ const rows = new Map<string, any>();
146
+ const http = {
147
+ get: async (_p: string, o?: { params?: Record<string, unknown> }) => ({ results: [...rows.values()].filter((r) => r.external_id === o?.params?.external_id__in) }),
148
+ post: async (_p: string, body: any) => { const row = { id: '1', owner_sub: ME, ...body, data: { ...(rows.get(body.external_id)?.data ?? {}), ...body.data } }; rows.set(body.external_id, row); return row; },
149
+ };
150
+ const log1 = createEntityActionLog(http as never, ME);
151
+ await executeVoiceActions({ actions: [{ type: 'done', itemId: 'bench' }], clientActionId: 'k', seam: t.seam, log: log1, ownerSub: ME, now: () => NOW, timeZone: TZ });
152
+ const log2 = createEntityActionLog(http as never, ME);
153
+ const again = await executeVoiceActions({ actions: [{ type: 'done', itemId: 'bench' }], clientActionId: 'k', seam: t.seam, log: log2, ownerSub: ME, now: () => NOW, timeZone: TZ });
154
+ expect(again.replayed).toBe(true);
155
+ });
156
+
157
+ it('the action log is a source_document with no body, so the extractor ignores it, and another owner\'s row is not read', async () => {
158
+ const rows = new Map<string, any>();
159
+ const http = {
160
+ get: async (_p: string, o?: { params?: Record<string, unknown> }) => ({ results: [...rows.values()].filter((r) => r.external_id === o?.params?.external_id__in) }),
161
+ post: async (_p: string, body: any) => { const row = { id: '1', owner_sub: 'someone-else', ...body }; rows.set(body.external_id, row); return row; },
162
+ };
163
+ const mine = createEntityActionLog(http as never, ME);
164
+ await mine.save({ applied: { x: { status: 'applied', spoken: 'ok' } }, order: ['x'], stack: [] });
165
+ const row = [...rows.values()][0];
166
+ expect(row.entity_type).toBe('source_document');
167
+ expect(row.data.source).toBe('briefing_actions');
168
+ expect(row.data.body).toBeUndefined();
169
+ expect(row.data.summary).toBeUndefined();
170
+ expect((await mine.load()).applied).toEqual({}); // the stored row's owner_sub is not mine: treated as absent
171
+ });
172
+ });
173
+
174
+ describe('undo', () => {
175
+ it('test_undo_restores_previous_values_for_last_action_and_pushes_the_reversal', async () => {
176
+ const t = stack([BENCH]);
177
+ await t.run([{ type: 'defer', itemId: 'bench', to: '2026-11-09' }]);
178
+ const out = await t.run([{ type: 'undo' }]);
179
+ // Restored exactly as it was read (the reader returns a stored bare date as that day at UTC midnight).
180
+ expect(t.tenant.get('bench').data.due_at).toMatch(/^2026-11-04/);
181
+ expect(out.results[0]).toMatchObject({ status: 'applied', itemId: 'bench' });
182
+ expect(out.text).toMatch(/undid/i);
183
+ expect(out.undoDepth).toBe(0);
184
+ });
185
+
186
+ it('undoes a done: status and resolved_at come back', async () => {
187
+ const t = stack([BENCH]);
188
+ await t.run([{ type: 'done', itemId: 'bench' }]);
189
+ await t.run([{ type: 'undo' }]);
190
+ expect(t.tenant.get('bench').data).toMatchObject({ status: 'open', resolved_at: null });
191
+ });
192
+
193
+ it('undoes an added item by dropping it', async () => {
194
+ const t = stack([]);
195
+ await t.run([{ type: 'add_item', title: 'Buy ink', dueDate: null }]);
196
+ await t.run([{ type: 'undo' }]);
197
+ expect([...t.tenant.byExternal.values()].find((r) => r.data.title === 'Buy ink').data.status).toBe('dropped');
198
+ });
199
+
200
+ it('a second undo undoes the one before, and the stack holds five', async () => {
201
+ const rows = ['a', 'b', 'c', 'd', 'e', 'f', 'g'].map((id) => ({ id, title: `Item ${id}`, due_at: '2026-11-04' }));
202
+ const t = stack(rows);
203
+ for (const r of rows) await t.run([{ type: 'defer', itemId: r.id, to: '2026-11-10' }]);
204
+ let last = await t.run([{ type: 'undo' }]);
205
+ expect(last.undoDepth).toBe(4);
206
+ await t.run([{ type: 'undo' }]); await t.run([{ type: 'undo' }]); await t.run([{ type: 'undo' }]);
207
+ last = await t.run([{ type: 'undo' }]);
208
+ expect(last.undoDepth).toBe(0);
209
+ // g, f, e, d, c were restored; b and a fell off the stack of five and stay moved.
210
+ for (const id of ['g', 'f', 'e', 'd', 'c']) expect(t.tenant.get(id).data.due_at).toMatch(/^2026-11-04/);
211
+ for (const id of ['a', 'b']) expect(t.tenant.get(id).data.due_at).toBe('2026-11-10');
212
+ const none = await t.run([{ type: 'undo' }]);
213
+ expect(none.results[0].status).toBe('asked');
214
+ expect(none.text).toMatch(/nothing to undo/i);
215
+ });
216
+
217
+ it('undo after the item changed elsewhere asks instead of overwriting', async () => {
218
+ const t = stack([BENCH]);
219
+ await t.run([{ type: 'defer', itemId: 'bench', to: '2026-11-09' }]);
220
+ t.tenant.get('bench').data.due_at = '2026-11-12'; // somebody else moved it (Linear, the web app)
221
+ const out = await t.run([{ type: 'undo' }]);
222
+ expect(out.results[0].status).toBe('asked');
223
+ expect(out.text).toMatch(/changed/i);
224
+ expect(t.tenant.get('bench').data.due_at).toBe('2026-11-12');
225
+ });
226
+
227
+ it('priority undo from unset clears it', async () => {
228
+ const t = stack([{ id: 'p', title: 'P' }]);
229
+ await t.run([{ type: 'set_priority', itemId: 'p', priority: 0 }]);
230
+ await t.run([{ type: 'undo' }]);
231
+ expect(t.tenant.get('p').data.priority).toBeNull();
232
+ });
233
+ });
234
+
235
+ describe('what is said back', () => {
236
+ it('test_confirmation_text_uses_item_title_and_spoken_date', async () => {
237
+ const t = stack([BENCH, PAPER]);
238
+ expect((await t.run([{ type: 'defer', itemId: 'bench', to: '2026-11-09', label: 'next week' }])).text).toBe("Moved Order dad's bench to next week.");
239
+ expect((await t.run([{ type: 'defer', itemId: 'paper', to: '2026-11-06' }])).text).toBe('Moved Pick up printer paper to Friday.');
240
+ expect((await t.run([{ type: 'defer', itemId: 'paper', to: 'later' }])).text).toBe('Moved Pick up printer paper to later.');
241
+ expect((await t.run([{ type: 'pull_today', itemId: 'paper' }])).text).toBe('Pulled Pick up printer paper into today.');
242
+ expect((await t.run([{ type: 'done', itemId: 'bench' }])).text).toBe("Marked Order dad's bench done.");
243
+ expect((await t.run([{ type: 'set_priority', itemId: 'paper', priority: 1 }])).text).toBe('Made Pick up printer paper urgent.');
244
+ expect((await t.run([{ type: 'drop', itemId: 'paper' }])).text).toBe('Dropped Pick up printer paper.');
245
+ expect((await t.run([{ type: 'add_item', title: 'Buy printer ink', dueDate: '2026-11-05' }])).text).toBe('Added Buy printer ink for tomorrow.');
246
+ });
247
+
248
+ it('a clarification is spoken as the question, nothing is applied', async () => {
249
+ const t = stack([BENCH]);
250
+ const out = await t.run([{ type: 'clarify', question: 'Move it to when?' }]);
251
+ expect(out.text).toBe('Move it to when?');
252
+ expect(t.tenant.http.post).not.toHaveBeenCalled();
253
+ });
254
+
255
+ it('test_partial_failure_in_multi_action_reports_which_applied', async () => {
256
+ const t = stack([BENCH]);
257
+ const out = await t.run([
258
+ { type: 'done', itemId: 'bench' },
259
+ { type: 'defer', itemId: 'ghost', to: 'later' },
260
+ { type: 'clarify', question: 'Which one?' },
261
+ ]);
262
+ expect(out.results.map((r) => r.status)).toEqual(['applied', 'failed', 'asked']);
263
+ expect(out.text).toContain("Marked Order dad's bench done.");
264
+ expect(out.text).toMatch(/could not find/i);
265
+ expect(out.text).toContain('Which one?');
266
+ expect(out.applied).toBe(1);
267
+ expect(out.failed).toBe(1);
268
+ });
269
+
270
+ it('a write that throws is reported on that action and the rest still run', async () => {
271
+ const t = stack([BENCH, PAPER]);
272
+ const real = t.tenant.http.post.getMockImplementation()!;
273
+ let calls = 0;
274
+ t.tenant.http.post.mockImplementation(async (p: string, b: any) => { calls += 1; if (calls === 1) throw new Error('503'); return real(p, b); });
275
+ const out = await t.run([{ type: 'done', itemId: 'bench' }, { type: 'drop', itemId: 'paper' }]);
276
+ expect(out.results.map((r) => r.status)).toEqual(['failed', 'applied']);
277
+ expect(out.text).toMatch(/could not update/i);
278
+ expect(out.undoDepth).toBe(1); // only what really changed can be undone
279
+ });
280
+ });
281
+
282
+ describe('spoken confirmation audio', () => {
283
+ const synth = (fail = false) => vi.fn(async ({ text }: { text: string }) => {
284
+ if (fail) throw new Error('tts down');
285
+ return { audio: new Uint8Array([1, 2]), mimeType: 'audio/mpeg', model: 'm', provider: 'openai', usage: { characters: text.length } };
286
+ });
287
+ const audio = () => ({
288
+ put: vi.fn(async ({ noteId }: { noteId: string }) => `s3://voice/${noteId}.mp3`),
289
+ url: vi.fn(async (ref: string) => `https://signed/${encodeURIComponent(ref)}`),
290
+ });
291
+
292
+ it('test_confirmation_audio_via_tts_with_text_fallback', async () => {
293
+ const ok = await speakConfirmation({ text: 'Done.', clientActionId: 'k', synthesize: synth(), audio: audio() });
294
+ expect(ok.text).toBe('Done.');
295
+ expect(ok.audioUrl).toMatch(/^https:\/\/signed\//);
296
+ const down = await speakConfirmation({ text: 'Done.', clientActionId: 'k', synthesize: synth(true), audio: audio() });
297
+ expect(down).toMatchObject({ text: 'Done.', audioUrl: null });
298
+ expect(down.reason).toMatch(/tts down/);
299
+ const none = await speakConfirmation({ text: 'Done.', clientActionId: 'k' });
300
+ expect(none).toMatchObject({ text: 'Done.', audioUrl: null });
301
+ });
302
+ });
303
+
304
+ describe('a seam over anything', () => {
305
+ it('works with a hand-written seam (what the Linear-aware path will provide)', async () => {
306
+ const items = new Map<string, EditableItem>([['i', { id: 'i', title: 'Linear thing', status: 'open', dueAt: '2026-11-04' }]]);
307
+ const seam: ItemEditSeam = {
308
+ load: async (id) => items.get(id) ?? null,
309
+ update: async (item, patch) => { const next = { ...item, ...patch } as EditableItem; items.set(item.id, next); return next; },
310
+ create: async (draft) => { const item = { id: 'new', title: draft.title, status: 'open', dueAt: draft.dueAt ?? null } as EditableItem; items.set('new', item); return item; },
311
+ };
312
+ const out = await executeVoiceActions({ actions: [{ type: 'defer', itemId: 'i', to: '2026-11-07' }], clientActionId: 's', seam, log: createMemoryActionLog(), ownerSub: ME, now: () => NOW, timeZone: TZ });
313
+ expect(items.get('i')?.dueAt).toBe('2026-11-07');
314
+ expect(out.text).toBe('Moved Linear thing to Saturday.');
315
+ });
316
+ });
@@ -95,6 +95,12 @@ describe('composeBriefing', () => {
95
95
  expect(b.items[0].kind).toBe('overdue');
96
96
  });
97
97
 
98
+ it('reads a date the tenant stored bare (returned as UTC midnight) as THAT date, not the evening before', () => {
99
+ // A voice reply writes "Friday" as 2026-11-06; the reader hands it back as 2026-11-06T00:00:00.000Z.
100
+ const b = compose([item({ id: 'a', dueAt: '2026-11-05T00:00:00.000Z' }), item({ id: 'b', dueAt: '2026-11-06T00:00:00.000Z' })]);
101
+ expect(b.items.map((e) => [e.id, e.kind, e.dueDate])).toEqual([['a', 'due_today', '2026-11-05']]);
102
+ });
103
+
98
104
  it('keeps an in-progress item even when it has no date, and tolerates unknown status words', () => {
99
105
  const b = compose([item({ id: 'p', status: 'in_progress', dueAt: null }), item({ id: 'weird', status: 'whatever' as never })]);
100
106
  expect(b.items.map((i) => i.id)).toEqual(['p', 'weird']);
@@ -0,0 +1,65 @@
1
+ /** What is said back after an action: plain sentences built from the item's title and a spoken date. */
2
+ import { localDate } from '../compose';
3
+ import { spokenWhen } from '../intent/dates';
4
+ import { PRIORITY_NAMES } from '../intent/describe';
5
+ import { speakable } from '../speak';
6
+ import type { BriefingAudio, BriefingSynthesize } from '../generate';
7
+ import type { ItemPatch, UndoEntry } from './types';
8
+ import type { VoiceAction } from '../intent/types';
9
+
10
+ export const shortTitle = (title: string) => speakable(title, 8) || 'that item';
11
+
12
+ export function confirmText(action: VoiceAction, title: string, now: number, timeZone: string): string {
13
+ const today = localDate(now, timeZone);
14
+ const t = shortTitle(title);
15
+ switch (action.type) {
16
+ case 'defer': return `Moved ${t} to ${action.to === 'later' ? 'later' : action.label ?? spokenWhen(action.to, today)}.`;
17
+ case 'pull_today': return `Pulled ${t} into today.`;
18
+ case 'done': return `Marked ${t} done.`;
19
+ case 'drop': return `Dropped ${t}.`;
20
+ case 'set_priority': return `Made ${t} ${PRIORITY_NAMES[action.priority] ?? `priority ${action.priority}`}.`;
21
+ case 'add_item': return `Added ${shortTitle(action.title)}${action.dueDate ? ` for ${spokenWhen(action.dueDate, today)}` : ''}.`;
22
+ default: return '';
23
+ }
24
+ }
25
+
26
+ /** "Undid it. Order dad's bench is back to Wednesday." */
27
+ export function undoText(entry: UndoEntry, now: number, timeZone: string): string {
28
+ const today = localDate(now, timeZone);
29
+ const t = shortTitle(entry.title);
30
+ if (entry.kind === 'create') return `Undid it. ${t} is removed.`;
31
+ const b: ItemPatch = entry.before;
32
+ const parts: string[] = [];
33
+ if ('dueAt' in b) parts.push(b.dueAt ? `due ${spokenWhen(String(b.dueAt).slice(0, 10), today)}` : 'no date');
34
+ if ('status' in b && b.status) parts.push(b.status === 'open' ? 'open' : String(b.status));
35
+ if ('priority' in b) parts.push(b.priority === null || b.priority === undefined ? 'no priority' : PRIORITY_NAMES[b.priority] ?? `priority ${b.priority}`);
36
+ return `Undid it. ${t} is back to ${parts.join(', ') || 'how it was'}.`;
37
+ }
38
+
39
+ export interface SpokenConfirmation {
40
+ text: string;
41
+ /** Short-lived link to the spoken version, or null when only text is available. */
42
+ audioUrl: string | null;
43
+ mimeType?: string;
44
+ reason?: string;
45
+ }
46
+
47
+ /** Text is always returned; speech is best effort (a synthesis failure never loses the confirmation). */
48
+ export async function speakConfirmation(input: {
49
+ text: string;
50
+ clientActionId: string;
51
+ synthesize?: BriefingSynthesize;
52
+ audio?: Pick<BriefingAudio, 'put' | 'url'>;
53
+ ttlSeconds?: number;
54
+ }): Promise<SpokenConfirmation> {
55
+ if (!input.text.trim()) return { text: input.text, audioUrl: null, reason: 'nothing to say' };
56
+ if (!input.synthesize || !input.audio) return { text: input.text, audioUrl: null, reason: 'speech is not configured' };
57
+ try {
58
+ const out = await input.synthesize({ text: input.text });
59
+ const ref = await input.audio.put({ noteId: `confirm-${input.clientActionId}`, audio: out.audio, mimeType: out.mimeType });
60
+ const audioUrl = await input.audio.url(ref, input.ttlSeconds ?? 300, `confirm-${input.clientActionId}`);
61
+ return { text: input.text, audioUrl, mimeType: out.mimeType };
62
+ } catch (error) {
63
+ return { text: input.text, audioUrl: null, reason: error instanceof Error ? error.message : String(error) };
64
+ }
65
+ }
@@ -0,0 +1,153 @@
1
+ /**
2
+ * THE EXECUTOR: apply parsed voice actions through the item edit seam, safely.
3
+ *
4
+ * - IDEMPOTENT: every action is keyed `<clientActionId>#<n>`; a retry or a double
5
+ * tap replays what was said, writes nothing, pushes nothing on the undo stack.
6
+ * - REVERSIBLE: each real change records before/after; "undo" restores the last
7
+ * five, newest first, through the same seam (so the reversal also reaches
8
+ * wherever edits go). If the item changed since, undo asks instead of overwriting.
9
+ * - HONEST: a failed write is reported on that action and the rest still run.
10
+ * Only what really changed is on the undo stack.
11
+ */
12
+ import { localDate } from '../compose';
13
+ import type { VoiceAction } from '../intent/types';
14
+ import { confirmText, shortTitle, undoText } from './confirm';
15
+ import { REMEMBERED_ACTIONS, UNDO_DEPTH } from './log';
16
+ import type {
17
+ ActionLog, ActionLogStore, ActionResult, EditableItem, ExecuteOutcome, ItemEditSeam, ItemPatch, UndoEntry,
18
+ } from './types';
19
+
20
+ export interface ExecuteInput {
21
+ actions: VoiceAction[];
22
+ /** Generated by the client per reply; sending the same one again is a replay. */
23
+ clientActionId: string;
24
+ seam: ItemEditSeam;
25
+ log: ActionLogStore;
26
+ ownerSub: string;
27
+ now?: () => number;
28
+ /** The listener's zone: "today" is theirs. */
29
+ timeZone: string;
30
+ }
31
+
32
+ const sameDay = (a: unknown, b: unknown) => (a ? String(a).slice(0, 10) : null) === (b ? String(b).slice(0, 10) : null);
33
+
34
+ /** The fields a patch changes, read off an item, so a reversal can put them back. */
35
+ function snapshot(item: EditableItem, patch: ItemPatch): ItemPatch {
36
+ const before: ItemPatch = {};
37
+ for (const key of Object.keys(patch) as Array<keyof ItemPatch>) {
38
+ if (key === 'dueAt') before.dueAt = item.dueAt ?? null;
39
+ else if (key === 'priority') before.priority = item.priority ?? null;
40
+ else if (key === 'resolvedAt') before.resolvedAt = item.resolvedAt ?? null;
41
+ else if (key === 'statusReason') before.statusReason = item.statusReason ?? '';
42
+ else if (key === 'status') before.status = item.status;
43
+ }
44
+ return before;
45
+ }
46
+
47
+ /** Has the item moved on from what we left it as? Only fields people care about are compared. */
48
+ function changedSince(item: EditableItem, after: ItemPatch): boolean {
49
+ if ('dueAt' in after && !sameDay(item.dueAt, after.dueAt)) return true;
50
+ if ('status' in after && item.status !== after.status) return true;
51
+ if ('priority' in after && (item.priority ?? null) !== (after.priority ?? null)) return true;
52
+ return false;
53
+ }
54
+
55
+ function patchFor(action: VoiceAction, today: string, nowIso: string): ItemPatch | null {
56
+ switch (action.type) {
57
+ case 'defer': return { dueAt: action.to === 'later' ? null : action.to };
58
+ case 'pull_today': return { dueAt: today };
59
+ case 'done': return { status: 'done', resolvedAt: nowIso, statusReason: 'Done by voice reply' };
60
+ case 'drop': return { status: 'dropped', statusReason: 'Dropped by voice reply' };
61
+ case 'set_priority': return { priority: action.priority };
62
+ default: return null;
63
+ }
64
+ }
65
+
66
+ function pushUndo(log: ActionLog, entry: UndoEntry) {
67
+ log.stack.push(entry);
68
+ while (log.stack.length > UNDO_DEPTH) log.stack.shift();
69
+ }
70
+
71
+ function remember(log: ActionLog, key: string, result: ActionResult) {
72
+ log.applied[key] = result;
73
+ log.order.push(key);
74
+ while (log.order.length > REMEMBERED_ACTIONS) delete log.applied[log.order.shift() as string];
75
+ }
76
+
77
+ async function undoOne(log: ActionLog, input: ExecuteInput, now: number): Promise<ActionResult> {
78
+ const entry = log.stack[log.stack.length - 1];
79
+ if (!entry) return { status: 'asked', spoken: 'There is nothing to undo.' };
80
+ log.stack.pop(); // popped either way: an entry that cannot be restored must not block the ones under it
81
+ try {
82
+ const item = await input.seam.load(entry.itemId);
83
+ if (!item) return { status: 'asked', spoken: `${shortTitle(entry.title)} is gone, so I could not undo that.`, itemId: entry.itemId };
84
+ if (entry.kind === 'create') {
85
+ if (item.status !== 'open') return { status: 'asked', spoken: `${shortTitle(entry.title)} changed since, so I left it.`, itemId: entry.itemId };
86
+ await input.seam.update(item, { status: 'dropped', statusReason: 'Undone by voice reply' });
87
+ } else {
88
+ if (changedSince(item, entry.after)) {
89
+ return { status: 'asked', spoken: `${shortTitle(entry.title)} changed since, so I did not undo that. Tell me what you want instead.`, itemId: entry.itemId };
90
+ }
91
+ await input.seam.update(item, entry.before);
92
+ }
93
+ return { status: 'applied', spoken: undoText(entry, now, input.timeZone), itemId: entry.itemId };
94
+ } catch (error) {
95
+ log.stack.push(entry); // nothing changed: it can be tried again
96
+ return { status: 'failed', spoken: `I could not undo that: ${error instanceof Error ? error.message : 'the change did not go through'}.`, itemId: entry.itemId };
97
+ }
98
+ }
99
+
100
+ export async function executeVoiceActions(input: ExecuteInput): Promise<ExecuteOutcome> {
101
+ const now = (input.now ?? Date.now)();
102
+ const today = localDate(now, input.timeZone);
103
+ const nowIso = new Date(now).toISOString();
104
+ const log = await input.log.load();
105
+ const results: ActionResult[] = [];
106
+ let replayed = input.actions.length > 0;
107
+
108
+ for (const [n, action] of input.actions.entries()) {
109
+ const key = `${input.clientActionId}#${n}`;
110
+ const seen = log.applied[key];
111
+ if (seen) { results.push(seen); continue; }
112
+ replayed = false;
113
+
114
+ let result: ActionResult;
115
+ if (action.type === 'clarify') result = { status: 'asked', spoken: action.question };
116
+ else if (action.type === 'none') result = { status: 'asked', spoken: 'Sorry, I did not catch that. Can you say that again?' };
117
+ else if (action.type === 'undo') result = await undoOne(log, input, now);
118
+ else if (action.type === 'add_item') {
119
+ try {
120
+ const created = await input.seam.create({ title: action.title, ownerSub: input.ownerSub, dueAt: action.dueDate });
121
+ pushUndo(log, { actionId: key, kind: 'create', itemId: created.id, title: action.title, before: {}, after: {}, at: nowIso });
122
+ result = { status: 'applied', spoken: confirmText(action, action.title, now, input.timeZone), itemId: created.id };
123
+ } catch (error) {
124
+ result = { status: 'failed', spoken: `I could not add ${shortTitle(action.title)}.`, ...(error instanceof Error ? {} : {}) };
125
+ }
126
+ } else {
127
+ const patch = patchFor(action, today, nowIso) as ItemPatch;
128
+ let title = 'that item';
129
+ try {
130
+ const item = await input.seam.load(action.itemId);
131
+ if (!item) result = { status: 'failed', spoken: 'I could not find that item.', itemId: action.itemId };
132
+ else {
133
+ title = item.title;
134
+ const before = snapshot(item, patch);
135
+ await input.seam.update(item, patch);
136
+ pushUndo(log, { actionId: key, kind: 'edit', itemId: item.id, title: item.title, before, after: patch, at: nowIso });
137
+ result = { status: 'applied', spoken: confirmText(action, item.title, now, input.timeZone), itemId: item.id };
138
+ }
139
+ } catch {
140
+ result = { status: 'failed', spoken: `I could not update ${shortTitle(title)}.`, itemId: action.itemId };
141
+ }
142
+ }
143
+
144
+ results.push(result);
145
+ // A failed write is not remembered, so a retry tries it again; everything else is.
146
+ if (result.status !== 'failed') remember(log, key, result);
147
+ await input.log.save(log);
148
+ }
149
+
150
+ const applied = results.filter((r) => r.status === 'applied').length;
151
+ const failed = results.filter((r) => r.status === 'failed').length;
152
+ return { results, text: results.map((r) => r.spoken).join(' '), applied, failed, undoDepth: log.stack.length, replayed };
153
+ }
@@ -0,0 +1,9 @@
1
+ export { executeVoiceActions } from './execute';
2
+ export type { ExecuteInput } from './execute';
3
+ export { commitmentEditSeam } from './seam';
4
+ export { createEntityActionLog, createMemoryActionLog, actionLogExternalId, ACTION_LOG_SOURCE, UNDO_DEPTH } from './log';
5
+ export { speakConfirmation, confirmText, undoText } from './confirm';
6
+ export type { SpokenConfirmation } from './confirm';
7
+ export type {
8
+ ActionLog, ActionLogStore, ActionResult, ActionStatus, EditableItem, ExecuteOutcome, ItemDraft, ItemEditSeam, ItemPatch, UndoEntry,
9
+ } from './types';
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Where the action log lives: ONE tenant row per person (a `source_document` with
3
+ * source `briefing_actions` and NO body/summary, so the to-do extractor reads
4
+ * nothing from it - the same trick as the briefing row, and no new entity type
5
+ * to declare). Owner scope is checked here as well as by the tenant.
6
+ *
7
+ * One row read-modified-written per reply: replies come from one person talking,
8
+ * one at a time. A lost update can only drop an undo entry or an idempotency key,
9
+ * never an item edit.
10
+ */
11
+ import type { CorpusHttp } from '../../client';
12
+ import type { TenantEntity } from '../../entities';
13
+ import type { ActionLog, ActionLogStore } from './types';
14
+
15
+ export const ACTION_LOG_SOURCE = 'briefing_actions';
16
+ /** Undo depth, and how many applied ids are remembered for replay. */
17
+ export const UNDO_DEPTH = 5;
18
+ export const REMEMBERED_ACTIONS = 100;
19
+
20
+ export const emptyLog = (): ActionLog => ({ applied: {}, order: [], stack: [] });
21
+
22
+ export function createMemoryActionLog(initial: ActionLog = emptyLog()): ActionLogStore {
23
+ let log = initial;
24
+ return { async load() { return structuredClone(log); }, async save(next) { log = structuredClone(next); } };
25
+ }
26
+
27
+ export const actionLogExternalId = (ownerSub: string) => `briefing-actions:${ownerSub}`;
28
+
29
+ type LogHttp = Pick<CorpusHttp, 'get'> & { post<T>(path: string, body?: unknown): Promise<T> };
30
+
31
+ export function createEntityActionLog(http: LogHttp, ownerSub: string): ActionLogStore {
32
+ const externalId = actionLogExternalId(ownerSub);
33
+ const mine = (entity: TenantEntity) => {
34
+ const sub = (entity as { owner_sub?: string }).owner_sub ?? (entity as { ownerSub?: string }).ownerSub
35
+ ?? ((entity.data ?? {}) as Record<string, unknown>).owner_sub;
36
+ return sub === ownerSub;
37
+ };
38
+ return {
39
+ async load() {
40
+ const page = await http.get<{ results?: TenantEntity[] }>('api/v1/entities', {
41
+ params: { type: 'source_document', external_id__in: externalId, page_size: 5 },
42
+ });
43
+ const hit = (page.results ?? []).find((r) => (r.external_id ?? (r as { externalId?: string }).externalId) === externalId && mine(r));
44
+ const stored = ((hit?.data ?? {}) as Record<string, unknown>).action_log as Partial<ActionLog> | undefined;
45
+ return stored ? { applied: stored.applied ?? {}, order: stored.order ?? [], stack: stored.stack ?? [] } : emptyLog();
46
+ },
47
+ async save(log) {
48
+ await http.post('api/v1/entities/upsert', {
49
+ entity_type: 'source_document',
50
+ external_id: externalId,
51
+ name: 'Briefing actions',
52
+ data: {
53
+ title: 'Briefing actions',
54
+ source: ACTION_LOG_SOURCE,
55
+ source_label: 'Briefing',
56
+ source_ref: externalId,
57
+ owner_sub: ownerSub,
58
+ action_log: log,
59
+ },
60
+ });
61
+ },
62
+ };
63
+ }
@@ -0,0 +1,50 @@
1
+ /** The default seam: the planning client's own commitment verbs. No new write path. */
2
+ import type { CorpusHttp } from '../../client';
3
+ import { isRecord, notFound } from '../../client';
4
+ import { toCommitment } from '../../entities';
5
+ import type { Commitment, CommitmentApi, CorpusScope } from '../../types';
6
+ import type { EditableItem, ItemEditSeam } from './types';
7
+
8
+ export function commitmentEditSeam(options: {
9
+ api: Pick<CommitmentApi, 'updateCommitment' | 'createCommitment'>;
10
+ http: Pick<CorpusHttp, 'get'>;
11
+ scope: CorpusScope;
12
+ entitiesPath?: string;
13
+ }): ItemEditSeam {
14
+ const { api, http, scope } = options;
15
+ const entities = options.entitiesPath ?? 'api/v1/entities';
16
+ const raw = new WeakMap<EditableItem, Commitment>();
17
+ const wrap = (c: Commitment): EditableItem => {
18
+ const item: EditableItem = {
19
+ id: c.id, externalId: c.externalId, title: c.title, status: c.status, dueAt: c.dueAt ?? null,
20
+ ...(c.priority !== undefined ? { priority: c.priority } : {}),
21
+ resolvedAt: c.resolvedAt ?? null, ...(c.statusReason ? { statusReason: c.statusReason } : {}),
22
+ };
23
+ raw.set(item, c);
24
+ return item;
25
+ };
26
+ return {
27
+ async load(id) {
28
+ try {
29
+ const entity = await http.get<unknown>(`${entities}/${encodeURIComponent(id)}`);
30
+ if (!isRecord(entity, id)) throw notFound(id);
31
+ return wrap(toCommitment(entity, scope));
32
+ } catch (error) {
33
+ if ((error as { status?: number }).status === 404) return null;
34
+ throw error;
35
+ }
36
+ },
37
+ async update(item, patch) {
38
+ if (!api.updateCommitment) throw new Error('This client cannot edit items.');
39
+ const row = raw.get(item) ?? ({ id: item.id, externalId: item.externalId } as Commitment);
40
+ if (!row.externalId) throw new Error('This item has no stable identity to edit.');
41
+ return wrap(await api.updateCommitment(row, patch as never));
42
+ },
43
+ async create(draft) {
44
+ if (!api.createCommitment) throw new Error('This client cannot add items.');
45
+ return wrap(await api.createCommitment({
46
+ title: draft.title, ownerSub: draft.ownerSub, ...(draft.dueAt ? { dueAt: draft.dueAt } : {}),
47
+ }));
48
+ },
49
+ };
50
+ }
@@ -0,0 +1,90 @@
1
+ /**
2
+ * The ITEM EDIT SEAM: the one interface every voice edit goes through.
3
+ *
4
+ * Today it is backed by the tenant's commitment upsert (`commitmentEditSeam`).
5
+ * Epic A's sync engine wraps it so an edit is also stamped for, and pushed to,
6
+ * Linear: it replaces or decorates `update`/`create` and nothing else in the
7
+ * executor changes. Keep this the ONLY way an action touches an item.
8
+ */
9
+ import type { Commitment } from '../../types';
10
+
11
+ /** What an edit needs to know about an item; a `Commitment` satisfies it. */
12
+ export interface EditableItem {
13
+ id: string;
14
+ title: string;
15
+ status: string;
16
+ dueAt?: string | null;
17
+ priority?: number;
18
+ resolvedAt?: string | null;
19
+ statusReason?: string;
20
+ externalId?: string;
21
+ }
22
+
23
+ /** The fields a voice reply changes. `null` clears (due date, priority, resolved time). */
24
+ export interface ItemPatch {
25
+ status?: string;
26
+ statusReason?: string;
27
+ dueAt?: string | null;
28
+ priority?: number | null;
29
+ resolvedAt?: string | null;
30
+ }
31
+
32
+ export interface ItemDraft {
33
+ title: string;
34
+ dueAt?: string | null;
35
+ ownerSub: string;
36
+ }
37
+
38
+ export interface ItemEditSeam {
39
+ load(id: string): Promise<EditableItem | null>;
40
+ update(item: EditableItem, patch: ItemPatch): Promise<EditableItem>;
41
+ create(draft: ItemDraft): Promise<EditableItem>;
42
+ }
43
+
44
+ export type ActionStatus = 'applied' | 'failed' | 'asked';
45
+
46
+ export interface ActionResult {
47
+ status: ActionStatus;
48
+ /** What was said back for this action. */
49
+ spoken: string;
50
+ itemId?: string;
51
+ }
52
+
53
+ /** One undoable change: the fields before and after, to restore and to check nothing moved since. */
54
+ export interface UndoEntry {
55
+ actionId: string;
56
+ kind: 'edit' | 'create';
57
+ itemId: string;
58
+ title: string;
59
+ before: ItemPatch;
60
+ after: ItemPatch;
61
+ at: string;
62
+ }
63
+
64
+ /** Everything remembered per person: what was applied (idempotency) and what can be undone. */
65
+ export interface ActionLog {
66
+ applied: Record<string, ActionResult>;
67
+ /** Insertion order of `applied`, so the oldest ids can be pruned. */
68
+ order: string[];
69
+ /** Newest last. */
70
+ stack: UndoEntry[];
71
+ }
72
+
73
+ export interface ActionLogStore {
74
+ load(): Promise<ActionLog>;
75
+ save(log: ActionLog): Promise<void>;
76
+ }
77
+
78
+ export interface ExecuteOutcome {
79
+ results: ActionResult[];
80
+ /** The sentences to say back, in order. */
81
+ text: string;
82
+ applied: number;
83
+ failed: number;
84
+ /** How many changes can still be undone. */
85
+ undoDepth: number;
86
+ /** True when every action had already been applied under this client action id. */
87
+ replayed: boolean;
88
+ }
89
+
90
+ export type ItemOf = Pick<Commitment, 'id'>;
@@ -28,6 +28,9 @@ export function localDate(instant: number, timeZone = 'UTC'): string {
28
28
  function dueDate(dueAt: string | null | undefined, timeZone: string): string | null {
29
29
  if (!dueAt) return null;
30
30
  if (/^\d{4}-\d{2}-\d{2}$/.test(dueAt)) return dueAt;
31
+ // The tenant reader turns a stored bare date into an instant at UTC midnight. That is still a DATE (a
32
+ // voice reply writes "Friday" as 2026-11-06): localising it would put it on the evening before in New York.
33
+ if (/^\d{4}-\d{2}-\d{2}T00:00:00(?:\.0+)?Z$/.test(dueAt)) return dueAt.slice(0, 10);
31
34
  const t = Date.parse(dueAt);
32
35
  return Number.isNaN(t) ? null : localDate(t, timeZone);
33
36
  }
@@ -12,3 +12,4 @@ export { createEntityBriefingStore, briefingExternalId, BRIEFING_SOURCE } from '
12
12
  export type { BriefingContextRecord, BriefingRecord, BriefingStore } from './store';
13
13
  export { briefingContentHash, hashString, SCRIPT_VERSION } from './cache-key';
14
14
  export * from './intent';
15
+ export * from './actions';
@@ -1401,6 +1401,7 @@ export function createPlanningApi(options: CreateCorpusApiOptions): PlanningApi
1401
1401
  if (patch.dueAt !== undefined) wire.due_at = patch.dueAt;
1402
1402
  if (patch.subtype !== undefined) wire.subtype = patch.subtype;
1403
1403
  if (patch.priority !== undefined) wire.priority = patch.priority;
1404
+ if (patch.resolvedAt !== undefined) wire.resolved_at = patch.resolvedAt;
1404
1405
  const updated = await post<TenantEntity>(`${entities}/upsert`, {
1405
1406
  entity_type: types.commitment,
1406
1407
  external_id: item.externalId,
@@ -858,7 +858,10 @@ export interface CommitmentApi {
858
858
  */
859
859
  updateCommitment?(item: Commitment, patch: Partial<Pick<Commitment,
860
860
  'status' | 'statusReason' | 'ownerName' | 'ownerSub' | 'dueAt' | 'subtype'
861
- | 'priority' | 'title' | 'detail'>>): Promise<Commitment>;
861
+ | 'title' | 'detail' | 'resolvedAt'>> & {
862
+ /** `null` clears it (undoing a voice-set priority). */
863
+ priority?: number | null;
864
+ }): Promise<Commitment>;
862
865
  /**
863
866
  * A person adding an item nobody said in a meeting.
864
867
  *