@startsimpli/integrations 0.2.124 → 0.2.125

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.124",
3
+ "version": "0.2.125",
4
4
  "description": "Provider-agnostic types, API clients, hooks, and UI primitives for email + calendar integrations across StartSimpli apps, plus foundry customer email (subpath ./comms).",
5
5
  "license": "MIT",
6
6
  "homepage": "https://startsimpli.com",
@@ -50,9 +50,9 @@
50
50
  "react-native": ">=0.74.0",
51
51
  "@startsimpli/ui-native": ">=0.1.12",
52
52
  "react-native-safe-area-context": ">=4.0.0",
53
- "@startsimpli/ui": "^0.4.171",
54
53
  "@startsimpli/auth": "^0.4.50",
55
- "@startsimpli/utils": "^0.4.17"
54
+ "@startsimpli/utils": "^0.4.17",
55
+ "@startsimpli/ui": "^0.4.171"
56
56
  },
57
57
  "peerDependenciesMeta": {
58
58
  "react": {
@@ -99,9 +99,9 @@
99
99
  "react-native": "0.85.3",
100
100
  "react-native-safe-area-context": "~5.7.0",
101
101
  "@startsimpli/llm": "0.4.30",
102
+ "@startsimpli/ui": "0.4.171",
102
103
  "@startsimpli/ui-native": "0.1.14",
103
104
  "@startsimpli/auth": "0.4.50",
104
- "@startsimpli/ui": "0.4.171",
105
105
  "@startsimpli/utils": "0.4.17"
106
106
  },
107
107
  "scripts": {
@@ -0,0 +1,121 @@
1
+ /**
2
+ * The utterance table for voice-reply intent parsing (bd startsim-8z2ah). Shared by the
3
+ * deterministic tests and by the one-off real-model accuracy probe, so the number the
4
+ * probe prints is measured on exactly the rows the tests pin.
5
+ *
6
+ * "Today" is Wednesday 2026-11-04 in New York. Item ids are readable on purpose.
7
+ */
8
+ import type { IntentContext, IntentItem, VoiceAction } from '../corpus/briefing';
9
+
10
+ export const TZ = 'America/New_York';
11
+ // 2026-11-04 15:00 UTC = 10:00 in New York (Wednesday).
12
+ export const NOW = Date.parse('2026-11-04T15:00:00Z');
13
+
14
+ export const BRIEFED: IntentItem[] = [
15
+ { id: 'wire', title: 'Send the marketing wireframes', focusName: 'Marketing' },
16
+ { id: 'v2', title: 'Redeploy V2 to production', focusName: 'Platform' },
17
+ { id: 'paper', title: 'Pick up printer paper' },
18
+ { id: 'pr', title: 'Review the billing pull request', focusName: 'Platform' },
19
+ { id: 'bench', title: "Order dad's bench" },
20
+ ];
21
+ export const OTHER_OPEN: IntentItem[] = [
22
+ { id: 'john', title: 'Call John about the lease' },
23
+ { id: 'dentist', title: 'Dentist appointment follow-up' },
24
+ { id: 'denver', title: 'Book flights for the Denver trip', focusName: 'Travel' },
25
+ ];
26
+
27
+ export const baseContext = (over: Partial<IntentContext> = {}): IntentContext => ({
28
+ utterance: '',
29
+ now: NOW,
30
+ timeZone: TZ,
31
+ briefed: BRIEFED,
32
+ open: OTHER_OPEN,
33
+ readingId: null,
34
+ hasUndo: true,
35
+ ...over,
36
+ });
37
+
38
+ export type Category = 'defer' | 'reschedule' | 'pull_today' | 'done' | 'drop' | 'priority' | 'add' | 'undo'
39
+ | 'multi' | 'ambiguous' | 'unknown' | 'none';
40
+
41
+ export interface Row {
42
+ name: string;
43
+ category: Category;
44
+ say: string;
45
+ /** Item being read when the person pressed talk. */
46
+ reading?: string | null;
47
+ /** Expected actions, in order. A `clarify` is matched on type only. */
48
+ expect: VoiceAction[];
49
+ /** Rows the deterministic grammar is not expected to get (it asks to repeat instead). */
50
+ llmOnly?: boolean;
51
+ hasUndo?: boolean;
52
+ /** Open items outside the briefing; defaults to OTHER_OPEN. */
53
+ open?: IntentItem[];
54
+ }
55
+
56
+ const defer = (itemId: string, to: string): VoiceAction => ({ type: 'defer', itemId, to } as VoiceAction);
57
+ const clarify = (): VoiceAction => ({ type: 'clarify', question: '' });
58
+
59
+ export const TABLE: Row[] = [
60
+ // defer to later
61
+ { name: 'later, with the reason', category: 'defer', say: 'move this one to later, I am not doing that today', reading: 'paper', expect: [defer('paper', 'later')] },
62
+ { name: 'push it out', category: 'defer', say: 'push this out', reading: 'pr', expect: [defer('pr', 'later')], llmOnly: true },
63
+ { name: 'not today', category: 'defer', say: 'not today', reading: 'v2', expect: [defer('v2', 'later')] },
64
+ { name: 'bare later', category: 'defer', say: 'later', reading: 'wire', expect: [defer('wire', 'later')] },
65
+ { name: 'snooze', category: 'defer', say: 'snooze that one', reading: 'bench', expect: [defer('bench', 'later')] },
66
+ // reschedule to a date
67
+ { name: 'to Friday', category: 'reschedule', say: 'push this to Friday', reading: 'paper', expect: [defer('paper', '2026-11-06')] },
68
+ { name: 'next week', category: 'reschedule', say: 'next week', reading: 'v2', expect: [defer('v2', '2026-11-09')] },
69
+ { name: 'tomorrow', category: 'reschedule', say: 'move this to tomorrow', reading: 'wire', expect: [defer('wire', '2026-11-05')] },
70
+ { name: 'next Monday', category: 'reschedule', say: 'postpone this until next Monday', reading: 'pr', expect: [defer('pr', '2026-11-09')] },
71
+ { name: 'in three days', category: 'reschedule', say: 'remind me about this in three days', reading: 'bench', expect: [defer('bench', '2026-11-07')], llmOnly: true },
72
+ { name: 'month and day', category: 'reschedule', say: 'push this to November twelfth', reading: 'paper', expect: [defer('paper', '2026-11-12')] },
73
+ { name: 'by name, with a date', category: 'reschedule', say: 'move the bench one to Thursday', expect: [defer('bench', '2026-11-05')] },
74
+ // pull into today
75
+ { name: 'that other thing = the one open item not in the briefing', category: 'pull_today', say: 'what about that other thing, pull it up to today', reading: null, open: [OTHER_OPEN[0]], expect: [{ type: 'pull_today', itemId: 'john' }] },
76
+ { name: 'that other thing is ambiguous with three unbriefed items', category: 'ambiguous', say: 'what about that other thing, pull it up to today', reading: null, expect: [clarify()] },
77
+ { name: 'pull Call John', category: 'pull_today', say: 'pull the call John thing up to today', expect: [{ type: 'pull_today', itemId: 'john' }] },
78
+ { name: 'bring the dentist in', category: 'pull_today', say: 'bring the dentist one into today', expect: [{ type: 'pull_today', itemId: 'dentist' }] },
79
+ { name: 'do it today', category: 'pull_today', say: 'actually, I will do the Denver flights today', expect: [{ type: 'pull_today', itemId: 'denver' }], llmOnly: true },
80
+ { name: 'move to today', category: 'pull_today', say: 'move the denver trip to today', expect: [{ type: 'pull_today', itemId: 'denver' }] },
81
+ // done
82
+ { name: 'the bench one is done', category: 'done', say: 'the bench one is done', expect: [{ type: 'done', itemId: 'bench' }] },
83
+ { name: 'done', category: 'done', say: 'done', reading: 'pr', expect: [{ type: 'done', itemId: 'pr' }] },
84
+ { name: 'mark it complete', category: 'done', say: 'mark this as complete', reading: 'v2', expect: [{ type: 'done', itemId: 'v2' }] },
85
+ { name: 'already did that', category: 'done', say: 'I already did that one', reading: 'paper', expect: [{ type: 'done', itemId: 'paper' }] },
86
+ { name: 'finished the wireframes', category: 'done', say: 'I finished the wireframes', expect: [{ type: 'done', itemId: 'wire' }] },
87
+ // drop
88
+ { name: 'drop the dentist thing', category: 'drop', say: 'drop the dentist thing', expect: [{ type: 'drop', itemId: 'dentist' }] },
89
+ { name: 'forget this one', category: 'drop', say: 'forget about this one', reading: 'bench', expect: [{ type: 'drop', itemId: 'bench' }] },
90
+ { name: 'scrap it', category: 'drop', say: 'scrap this', reading: 'paper', expect: [{ type: 'drop', itemId: 'paper' }] },
91
+ { name: 'not doing it', category: 'drop', say: 'I am never doing the billing review, get rid of it', expect: [{ type: 'drop', itemId: 'pr' }], llmOnly: true },
92
+ // priority
93
+ { name: 'urgent', category: 'priority', say: 'make this urgent', reading: 'v2', expect: [{ type: 'set_priority', itemId: 'v2', priority: 1 }] },
94
+ { name: 'lowest', category: 'priority', say: 'make this lowest priority', reading: 'paper', expect: [{ type: 'set_priority', itemId: 'paper', priority: 4 }] },
95
+ { name: 'critical by name', category: 'priority', say: 'mark the marketing wireframes as critical', expect: [{ type: 'set_priority', itemId: 'wire', priority: 0 }] },
96
+ { name: 'priority number', category: 'priority', say: 'set the billing review to priority two', expect: [{ type: 'set_priority', itemId: 'pr', priority: 2 }] },
97
+ // add
98
+ { name: 'add with a date', category: 'add', say: 'add buy printer ink for tomorrow', expect: [{ type: 'add_item', title: 'Buy printer ink', dueDate: '2026-11-05' }] },
99
+ { name: 'add with no date', category: 'add', say: 'add call the plumber', expect: [{ type: 'add_item', title: 'Call the plumber', dueDate: null }] },
100
+ { name: 'remind me', category: 'add', say: 'remind me to renew the passport on Friday', expect: [{ type: 'add_item', title: 'Renew the passport', dueDate: '2026-11-06' }] },
101
+ { name: 'add and keeps and', category: 'add', say: 'add buy salt and pepper', expect: [{ type: 'add_item', title: 'Buy salt and pepper', dueDate: null }] },
102
+ // undo
103
+ { name: 'undo', category: 'undo', say: 'undo', expect: [{ type: 'undo' }] },
104
+ { name: 'never mind that', category: 'undo', say: 'never mind that', expect: [{ type: 'undo' }] },
105
+ { name: 'put it back', category: 'undo', say: 'no wait, put it back', expect: [{ type: 'undo' }], llmOnly: true },
106
+ { name: 'undo with nothing to undo', category: 'undo', say: 'undo', hasUndo: false, expect: [{ type: 'clarify', question: '' }] },
107
+ // multi
108
+ { name: 'done and move the next one', category: 'multi', say: 'done with this, and move the next one to tomorrow', reading: 'v2', expect: [{ type: 'done', itemId: 'v2' }, defer('paper', '2026-11-05')] },
109
+ { name: 'two by name', category: 'multi', say: 'drop the dentist thing and pull up the call John one to today', expect: [{ type: 'drop', itemId: 'dentist' }, { type: 'pull_today', itemId: 'john' }] },
110
+ // ambiguous
111
+ { name: 'move that one, nothing being read', category: 'ambiguous', say: 'move that one', reading: null, expect: [clarify()] },
112
+ { name: 'later, nothing being read', category: 'ambiguous', say: 'later', reading: null, expect: [clarify()] },
113
+ { name: 'two items match', category: 'ambiguous', say: 'mark the platform one done', expect: [clarify()] },
114
+ { name: 'no date given', category: 'ambiguous', say: 'move this one', reading: 'pr', expect: [clarify()] },
115
+ // unknown
116
+ { name: 'tax thing', category: 'unknown', say: 'pull up the tax thing', expect: [clarify()] },
117
+ { name: 'gardening', category: 'unknown', say: 'mark the gardening one done', expect: [clarify()] },
118
+ // none
119
+ { name: 'chatter', category: 'none', say: 'what a lovely morning', expect: [clarify()] },
120
+ { name: 'empty', category: 'none', say: ' ', expect: [clarify()] },
121
+ ];
@@ -0,0 +1,281 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+
3
+ import {
4
+ parseWithGrammar, resolveVoiceIntent, parseWhen, readingAt,
5
+ type BriefingScriptLlm, type VoiceAction,
6
+ } from '../corpus/briefing';
7
+ import { BRIEFED, NOW, OTHER_OPEN, TABLE, TZ, baseContext, type Row } from './briefing-intent-table';
8
+
9
+ const ctxOf = (row: Row) => baseContext({
10
+ utterance: row.say,
11
+ readingId: row.reading === undefined ? null : row.reading,
12
+ hasUndo: row.hasUndo ?? true,
13
+ ...(row.open ? { open: row.open } : {}),
14
+ });
15
+
16
+ /** Compare actions the way the table states them: clarify matches on type alone. */
17
+ const shape = (actions: VoiceAction[]) => actions.map((a) => (a.type === 'clarify' ? { type: 'clarify' } : a));
18
+ const wanted = (row: Row) => shape(row.expect);
19
+ /** The parser adds a spoken `label` for the confirmation; the table does not state it. */
20
+ const stripLabel = (actions: VoiceAction[]) => actions.map((a) => {
21
+ if (a.type !== 'defer' && a.type !== 'pull_today') return a;
22
+ const { label: _label, ...rest } = a as VoiceAction & { label?: string };
23
+ return rest as VoiceAction;
24
+ });
25
+
26
+ function toWire(a: VoiceAction): Record<string, unknown> {
27
+ switch (a.type) {
28
+ case 'defer': return { type: 'defer', item_id: a.itemId, to: a.to };
29
+ case 'pull_today': return { type: 'pull_today', item_id: a.itemId };
30
+ case 'done': case 'drop': return { type: a.type, item_id: a.itemId };
31
+ case 'set_priority': return { type: 'set_priority', item_id: a.itemId, priority: a.priority };
32
+ case 'add_item': return { type: 'add_item', title: a.title, due: a.dueDate };
33
+ case 'clarify': return { type: 'clarify', question: 'Which one?' };
34
+ default: return { type: a.type };
35
+ }
36
+ }
37
+
38
+ describe('the utterance table', () => {
39
+ it('has 30+ rows across every category', () => {
40
+ expect(TABLE.length).toBeGreaterThanOrEqual(30);
41
+ const categories = new Set(TABLE.map((r) => r.category));
42
+ for (const c of ['defer', 'reschedule', 'pull_today', 'done', 'drop', 'priority', 'add', 'undo', 'multi', 'ambiguous', 'unknown', 'none'])
43
+ expect(categories.has(c as Row['category'])).toBe(true);
44
+ });
45
+
46
+ describe('deterministic grammar (no model at all)', () => {
47
+ const covered = TABLE.filter((r) => !r.llmOnly);
48
+ it('covers at least ten rows without an LLM', () => expect(covered.length).toBeGreaterThanOrEqual(10));
49
+ it.each(covered.map((r) => [`${r.category}: ${r.name}`, r] as const))('%s', (_n, row) => {
50
+ const out = parseWithGrammar(ctxOf(row));
51
+ expect(shape(stripLabel(out.actions))).toEqual(wanted(row));
52
+ });
53
+ });
54
+
55
+ describe('resolveVoiceIntent with a model that answers well', () => {
56
+ it.each(TABLE.filter((r) => r.say.trim()).map((r) => [`${r.category}: ${r.name}`, r] as const))('%s', async (_n, row) => {
57
+ // The fake model "understands" by replaying what the table expects, in the wire shape.
58
+ const llm: BriefingScriptLlm = { write: async () => JSON.stringify({ confidence: 0.95, actions: row.expect.map(toWire) }) };
59
+ const out = await resolveVoiceIntent(ctxOf(row), { llm });
60
+ expect(out.source).toBe('llm');
61
+ expect(shape(stripLabel(out.actions))).toEqual(wanted(row));
62
+ });
63
+ });
64
+ });
65
+
66
+ describe('specific spoken answers', () => {
67
+ it('asks which one, naming up to three briefed items', () => {
68
+ const out = parseWithGrammar(baseContext({ utterance: 'move that one', readingId: null }));
69
+ expect(out.actions[0].type).toBe('clarify');
70
+ const q = (out.actions[0] as { question: string }).question;
71
+ expect(q).toMatch(/^Which one: /);
72
+ expect(q).toContain('marketing wireframes');
73
+ expect(q).toContain('V2');
74
+ });
75
+
76
+ it('never invents an item: an unknown subject asks, and offers to add it', () => {
77
+ const out = parseWithGrammar(baseContext({ utterance: 'pull up the tax thing' }));
78
+ expect(out.actions).toEqual([{ type: 'clarify', question: 'I could not find a tax item. Say add it to create one.' }]);
79
+ });
80
+
81
+ it('asks for the date when it is missing, and for the item when "later" has no reading item', () => {
82
+ const noDate = parseWithGrammar(baseContext({ utterance: 'move this one', readingId: 'pr' }));
83
+ expect((noDate.actions[0] as { question: string }).question).toMatch(/when/i);
84
+ const noItem = parseWithGrammar(baseContext({ utterance: 'later', readingId: null }));
85
+ expect(noItem.actions[0].type).toBe('clarify');
86
+ });
87
+
88
+ it('with nothing to undo, says so instead of undoing', () => {
89
+ const out = parseWithGrammar(baseContext({ utterance: 'undo', hasUndo: false }));
90
+ expect((out.actions[0] as { question: string }).question).toMatch(/nothing to undo/i);
91
+ });
92
+
93
+ it('asks to repeat anything it does not understand', () => {
94
+ const out = parseWithGrammar(baseContext({ utterance: 'what a lovely morning' }));
95
+ expect((out.actions[0] as { question: string }).question).toMatch(/say that again/i);
96
+ });
97
+
98
+ it('"the next one" is the item after the one being read; "the third one" is by position', () => {
99
+ expect(parseWithGrammar(baseContext({ utterance: 'done with the next one', readingId: 'wire' })).actions)
100
+ .toEqual([{ type: 'done', itemId: 'v2' }]);
101
+ expect(parseWithGrammar(baseContext({ utterance: 'drop the third one' })).actions)
102
+ .toEqual([{ type: 'drop', itemId: 'paper' }]);
103
+ });
104
+
105
+ it('keeps the spoken date phrase for the confirmation', () => {
106
+ const out = parseWithGrammar(baseContext({ utterance: 'next week', readingId: 'v2' }));
107
+ expect(out.actions[0]).toMatchObject({ type: 'defer', itemId: 'v2', to: '2026-11-09', label: 'next week' });
108
+ });
109
+ });
110
+
111
+ describe('the model path is checked, never trusted', () => {
112
+ const ctx = baseContext({ utterance: 'move this one to later', readingId: 'paper' });
113
+ const answer = (body: unknown): BriefingScriptLlm => ({ write: async () => (typeof body === 'string' ? body : JSON.stringify(body)) });
114
+
115
+ it('test_item_ids_must_exist_in_open_items_hallucinated_id_rejected', async () => {
116
+ const llm = answer({ confidence: 0.99, actions: [{ type: 'defer', item_id: 'ghost', to: 'later' }] });
117
+ const out = await resolveVoiceIntent(ctx, { llm });
118
+ expect(out.source).toBe('grammar');
119
+ expect(out.actions).toEqual([{ type: 'defer', itemId: 'paper', to: 'later', label: 'later' }]);
120
+ expect(out.notes.join(' ')).toContain('unknown item');
121
+ });
122
+
123
+ it('test_llm_failure_uses_deterministic_grammar_covering_done_later_tomorrow_today_undo_drop_and_otherwise_asks_to_repeat', async () => {
124
+ const down: BriefingScriptLlm = { write: vi.fn(async () => { throw new Error('boom'); }) };
125
+ const run = (say: string, reading: string | null = 'pr') => resolveVoiceIntent(baseContext({ utterance: say, readingId: reading }), { llm: down });
126
+ expect((await run('done')).actions[0]).toMatchObject({ type: 'done', itemId: 'pr' });
127
+ expect((await run('later')).actions[0]).toMatchObject({ type: 'defer', to: 'later' });
128
+ expect((await run('tomorrow')).actions[0]).toMatchObject({ type: 'defer', to: '2026-11-05' });
129
+ expect((await run('do this today')).actions[0]).toMatchObject({ type: 'pull_today', itemId: 'pr' });
130
+ expect((await run('undo')).actions[0]).toEqual({ type: 'undo' });
131
+ expect((await run('drop it')).actions[0]).toMatchObject({ type: 'drop', itemId: 'pr' });
132
+ const odd = await run('hmm the purple elephant sings');
133
+ expect(odd.actions[0]).toMatchObject({ type: 'clarify' });
134
+ expect(odd.source).toBe('grammar');
135
+ });
136
+
137
+ it('test_confidence_below_threshold_asks_clarification_instead_of_acting', async () => {
138
+ const llm = answer({ confidence: 0.3, actions: [{ type: 'done', item_id: 'paper' }] });
139
+ const out = await resolveVoiceIntent(ctx, { llm });
140
+ expect(out.actions).toHaveLength(1);
141
+ expect(out.actions[0].type).toBe('clarify');
142
+ expect((out.actions[0] as { question: string }).question).toMatch(/not sure|say that again/i);
143
+ });
144
+
145
+ it('rejects garbage, bad priorities and bad dates, then falls back', async () => {
146
+ for (const body of ['not json', { confidence: 1, actions: [{ type: 'set_priority', item_id: 'paper', priority: 9 }] },
147
+ { confidence: 1, actions: [{ type: 'defer', item_id: 'paper', to: '2026-13-45' }] }, { confidence: 1, actions: [{ type: 'explode' }] }]) {
148
+ const out = await resolveVoiceIntent(ctx, { llm: answer(body) });
149
+ expect(out.source).toBe('grammar');
150
+ }
151
+ });
152
+
153
+ it('gives the model the spoken list, the item being read and today in the listener zone', async () => {
154
+ const write = vi.fn(async (_: { system: string; prompt: string }) => JSON.stringify({ confidence: 1, actions: [{ type: 'done', item_id: 'paper' }] }));
155
+ await resolveVoiceIntent(ctx, { llm: { write } });
156
+ const { prompt } = write.mock.calls[0][0];
157
+ expect(prompt).toContain('Wednesday 2026-11-04');
158
+ expect(prompt).toContain('[id:paper]');
159
+ expect(prompt).toMatch(/being read.*paper/is);
160
+ expect(prompt).toContain('[id:john]');
161
+ });
162
+
163
+ it('a model "defer to today" becomes pull_today, and a date phrase from the model is understood', async () => {
164
+ const a = await resolveVoiceIntent(ctx, { llm: answer({ confidence: 1, actions: [{ type: 'defer', item_id: 'paper', to: '2026-11-04' }] }) });
165
+ expect(a.actions[0]).toMatchObject({ type: 'pull_today', itemId: 'paper' });
166
+ const b = await resolveVoiceIntent(baseContext({ utterance: 'push this to next friday', readingId: 'paper' }),
167
+ { llm: answer({ confidence: 1, actions: [{ type: 'defer', item_id: 'paper', to: 'next friday' }] }) });
168
+ expect(b.actions[0]).toMatchObject({ type: 'defer', to: '2026-11-13' });
169
+ });
170
+ });
171
+
172
+
173
+ describe('a model guess is not an answer (grounding)', () => {
174
+ const answer = (actions: unknown[]): BriefingScriptLlm => ({ write: async () => JSON.stringify({ confidence: 0.95, actions }) });
175
+ const run = (say: string, reading: string | null, actions: unknown[]) =>
176
+ resolveVoiceIntent(baseContext({ utterance: say, readingId: reading }), { llm: answer(actions) });
177
+
178
+ it('nothing is being read and the words name nothing: the model\'s pick is dropped for a question', async () => {
179
+ const out = await run('mark it done', null, [{ type: 'done', item_id: 'wire' }]);
180
+ expect(out.source).toBe('grammar');
181
+ expect(out.actions[0].type).toBe('clarify');
182
+ expect(out.notes.join(' ')).toContain('ungrounded');
183
+ });
184
+
185
+ it('"pull" in "pull it up" is not "pull request"', async () => {
186
+ const out = await run('what about that other thing, pull it up to today', null, [{ type: 'pull_today', item_id: 'pr' }]);
187
+ expect(out.source).toBe('grammar');
188
+ expect(out.actions[0].type).toBe('clarify');
189
+ });
190
+
191
+ it('a model that moves with no date in the reply is asked again', async () => {
192
+ const out = await run('move this one', 'pr', [{ type: 'defer', item_id: 'pr', to: 'later' }]);
193
+ expect(out.actions[0].type).toBe('clarify');
194
+ expect((out.actions[0] as { question: string }).question).toMatch(/when/i);
195
+ });
196
+
197
+ it('the item being read is not acted on when the words name a different one', async () => {
198
+ const out = await run('the bench one is done', 'pr', [{ type: 'done', item_id: 'pr' }]);
199
+ expect(out.actions).toEqual([{ type: 'done', itemId: 'bench' }]);
200
+ });
201
+
202
+ it('two items that fit the words equally are a question, not a coin flip', async () => {
203
+ const out = await run('mark the platform one done', null, [{ type: 'done', item_id: 'pr' }]);
204
+ expect(out.actions[0].type).toBe('clarify');
205
+ });
206
+
207
+ it('a model date that contradicts the words is not trusted: "to today" is not "later"', async () => {
208
+ const out = await run('move the denver trip to today', null, [{ type: 'defer', item_id: 'denver', to: 'later' }]);
209
+ expect(out.actions).toEqual([{ type: 'pull_today', itemId: 'denver', label: 'today' }]);
210
+ expect(out.source).toBe('grammar');
211
+ });
212
+
213
+ it('when the model only asks but the plain rules find one clear match, the match wins', async () => {
214
+ const out = await run('bring up the lease call', null, [{ type: 'clarify', question: 'Which one?' }]);
215
+ expect(out.actions).toEqual([{ type: 'pull_today', itemId: 'john', label: 'today' }]);
216
+ });
217
+
218
+ it('a well-grounded model answer is kept (source llm)', async () => {
219
+ const out = await run('the bench thing is finished', 'pr', [{ type: 'done', item_id: 'bench' }]);
220
+ expect(out.source).toBe('llm');
221
+ });
222
+ });
223
+
224
+ describe('dates are resolved in the listener zone, relative to today', () => {
225
+ it('test_dates_resolved_in_user_tz_relative_to_today_not_utc', () => {
226
+ // 02:00 UTC on the 5th is still the evening of the 4th in New York: "tomorrow" is the 5th there.
227
+ const lateUtc = Date.parse('2026-11-05T02:00:00Z');
228
+ expect(parseWhen('tomorrow', lateUtc, 'America/New_York')?.date).toBe('2026-11-05');
229
+ expect(parseWhen('tomorrow', lateUtc, 'UTC')?.date).toBe('2026-11-06');
230
+ expect(parseWhen('today', lateUtc, 'America/New_York')?.date).toBe('2026-11-04');
231
+ });
232
+
233
+ it.each([
234
+ ['tomorrow', '2026-11-05'], ['tonight', '2026-11-04'], ['today', '2026-11-04'], ['later today', '2026-11-04'],
235
+ ['the day after tomorrow', '2026-11-06'],
236
+ ['friday', '2026-11-06'], ['this friday', '2026-11-06'], ['next friday', '2026-11-13'], ['wednesday', '2026-11-11'],
237
+ ['monday', '2026-11-09'], ['next monday', '2026-11-09'], ['next week', '2026-11-09'],
238
+ ['this weekend', '2026-11-07'], ['end of the week', '2026-11-06'], ['next month', '2026-12-01'],
239
+ ['in two days', '2026-11-06'], ['in a week', '2026-11-11'], ['in 2 weeks', '2026-11-18'],
240
+ ['november twelfth', '2026-11-12'], ['the 12th', '2026-11-12'], ['december 3', '2026-12-03'], ['the third', '2026-12-03'],
241
+ ['later', 'later'], ['later this week', '2026-11-06'], ['some other time', 'later'], ['sometime', 'later'],
242
+ ])('%s -> %s', (phrase, want) => {
243
+ const w = parseWhen(phrase, NOW, TZ);
244
+ expect(w && (w.later ? 'later' : w.date)).toBe(want);
245
+ });
246
+
247
+ it('does not understand things that are not dates', () => {
248
+ expect(parseWhen('the purple elephant', NOW, TZ)).toBeNull();
249
+ });
250
+ });
251
+
252
+ describe('"this one" by playback position', () => {
253
+ const ctx = {
254
+ itemIds: ['a', 'b', 'c'], localDate: '2026-11-04', timeZone: TZ,
255
+ offsets: [{ id: 'a', start: 20, end: 60 }, { id: 'b', start: 61, end: 120 }, { id: 'c', start: 121, end: 170 }],
256
+ };
257
+ it('is the item whose sentence is being spoken', () => {
258
+ expect(readingAt(ctx, { charPosition: 30 })).toBe('a');
259
+ expect(readingAt(ctx, { charPosition: 100 })).toBe('b');
260
+ });
261
+ it('is the last fully spoken item when playback sits between items (documented rule)', () => {
262
+ expect(readingAt(ctx, { charPosition: 60.5 })).toBe('a');
263
+ expect(readingAt(ctx, { charPosition: 125 })).toBe('c');
264
+ expect(readingAt(ctx, { charPosition: 400 })).toBe('c');
265
+ });
266
+ it('is nothing before the first item', () => expect(readingAt(ctx, { charPosition: 3 })).toBeNull());
267
+ it('estimates the position from seconds when the provider gave no word timings', () => {
268
+ expect(readingAt(ctx, { seconds: 2 })).toBe('a'); // 2 s x 15 chars/s = 30
269
+ expect(readingAt(ctx, { seconds: 7 })).toBe('b'); // 105
270
+ });
271
+ it('uses the fraction of the audio when its length is known', () => {
272
+ expect(readingAt(ctx, { seconds: 10, durationSeconds: 20, textLength: 170 })).toBe('b'); // 85
273
+ });
274
+ });
275
+
276
+ describe('fixture sanity', () => {
277
+ it('has the shape the tests assume', () => {
278
+ expect(BRIEFED.map((i) => i.id)).toEqual(['wire', 'v2', 'paper', 'pr', 'bench']);
279
+ expect(OTHER_OPEN.length).toBe(3);
280
+ });
281
+ });
@@ -11,3 +11,4 @@ export { briefingResponse, briefingAudioResponse } from './respond';
11
11
  export { createEntityBriefingStore, briefingExternalId, BRIEFING_SOURCE } from './store';
12
12
  export type { BriefingContextRecord, BriefingRecord, BriefingStore } from './store';
13
13
  export { briefingContentHash, hashString, SCRIPT_VERSION } from './cache-key';
14
+ export * from './intent';
@@ -0,0 +1,195 @@
1
+ /**
2
+ * Spoken dates for voice replies. PURE: `now` and the listener's `timeZone` come
3
+ * in, a calendar date (`YYYY-MM-DD`) or "later" comes out. "Today" is the
4
+ * listener's day, never UTC's.
5
+ *
6
+ * Conventions (written down because a spoken weekday is ambiguous):
7
+ * - a bare weekday is the NEXT one strictly after today (on a Wednesday, "Wednesday" is in a week);
8
+ * - "this Friday" is the coming one, today included;
9
+ * - "next Friday" is that weekday of NEXT calendar week (Monday to Sunday);
10
+ * - "next week" is Monday of next week;
11
+ * - "later" (and "someday") means no date: the item's due date is cleared.
12
+ */
13
+ import { localDate } from '../compose';
14
+ import { speakDate } from '../speak';
15
+
16
+ export interface SpokenWhen {
17
+ /** `YYYY-MM-DD`; null when `later`. */
18
+ date: string | null;
19
+ later: boolean;
20
+ /** How it is said back: `tomorrow`, `next week`, `Friday`. */
21
+ label: string;
22
+ }
23
+
24
+ const DAY_MS = 86_400_000;
25
+ const WEEKDAYS = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
26
+ const MONTHS = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october',
27
+ 'november', 'december'];
28
+ const WORD_NUMBERS: Record<string, number> = {
29
+ a: 1, an: 1, one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9, ten: 10,
30
+ eleven: 11, twelve: 12, fourteen: 14,
31
+ };
32
+ const ORDINALS: Record<string, number> = {
33
+ first: 1, second: 2, third: 3, fourth: 4, fifth: 5, sixth: 6, seventh: 7, eighth: 8, ninth: 9, tenth: 10,
34
+ eleventh: 11, twelfth: 12, thirteenth: 13, fourteenth: 14, fifteenth: 15, sixteenth: 16, seventeenth: 17,
35
+ eighteenth: 18, nineteenth: 19, twentieth: 20, 'twenty first': 21, 'twenty second': 22, 'twenty third': 23,
36
+ 'twenty fourth': 24, 'twenty fifth': 25, 'twenty sixth': 26, 'twenty seventh': 27, 'twenty eighth': 28,
37
+ 'twenty ninth': 29, thirtieth: 30, 'thirty first': 31,
38
+ 'twenty-first': 21, 'twenty-second': 22, 'twenty-third': 23, 'twenty-fourth': 24, 'twenty-fifth': 25,
39
+ 'twenty-sixth': 26, 'twenty-seventh': 27, 'twenty-eighth': 28, 'twenty-ninth': 29, 'thirty-first': 31,
40
+ };
41
+
42
+ // -- calendar arithmetic on `YYYY-MM-DD` (UTC math: a date string has no zone) ---
43
+
44
+ const toUtc = (iso: string) => { const [y, m, d] = iso.split('-').map(Number); return Date.UTC(y, m - 1, d); };
45
+ const fromUtc = (ms: number) => new Date(ms).toISOString().slice(0, 10);
46
+ export const addDays = (iso: string, n: number) => fromUtc(toUtc(iso) + n * DAY_MS);
47
+ const dow = (iso: string) => new Date(toUtc(iso)).getUTCDay();
48
+ const mondayOf = (iso: string) => addDays(iso, -((dow(iso) + 6) % 7));
49
+ const isRealDate = (y: number, m: number, d: number) => {
50
+ const t = new Date(Date.UTC(y, m - 1, d));
51
+ return t.getUTCFullYear() === y && t.getUTCMonth() === m - 1 && t.getUTCDate() === d;
52
+ };
53
+ const pad = (n: number) => String(n).padStart(2, '0');
54
+
55
+ /** `YYYY-MM-DD` that is a real calendar day. */
56
+ export const isIsoDate = (value: unknown): value is string => {
57
+ if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
58
+ const [y, m, d] = value.split('-').map(Number);
59
+ return isRealDate(y, m, d);
60
+ };
61
+
62
+ export function weekdayName(iso: string): string {
63
+ const name = WEEKDAYS[dow(iso)];
64
+ return name[0].toUpperCase() + name.slice(1);
65
+ }
66
+
67
+ /** How a resolved date is said back: `today`, `tomorrow`, `Friday`, or `Monday the ninth`. */
68
+ export function spokenWhen(date: string, today: string): string {
69
+ if (date === today) return 'today';
70
+ if (date === addDays(today, 1)) return 'tomorrow';
71
+ const gap = (toUtc(date) - toUtc(today)) / DAY_MS;
72
+ if (gap > 1 && gap < 7) return weekdayName(date);
73
+ return speakDate(date, today);
74
+ }
75
+
76
+ // -- the phrases --------------------------------------------------------------
77
+
78
+ const WD = '(sunday|monday|tuesday|wednesday|thursday|friday|saturday)';
79
+ const MON = `(${MONTHS.join('|')})`;
80
+ const NUM = '(\\d{1,2}|a|an|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|fourteen)';
81
+ const ORD_WORDS = Object.keys(ORDINALS).filter((k) => !k.includes('-')).sort((a, b) => b.length - a.length).join('|');
82
+ const DAYNUM = `(\\d{1,2}(?:st|nd|rd|th)?|${ORD_WORDS})`;
83
+
84
+ interface Rule { re: RegExp; resolve(m: RegExpExecArray, today: string): SpokenWhen | null }
85
+ const on = (date: string, label: string): SpokenWhen => ({ date, later: false, label });
86
+ const LATER: SpokenWhen = { date: null, later: true, label: 'later' };
87
+ const dayNumber = (word: string) => ORDINALS[word.replace(/\s+/g, ' ')] ?? (parseInt(word, 10) || 0);
88
+
89
+ const RULES: Rule[] = [
90
+ { re: /\bthe day after tomorrow\b/, resolve: (_m, t) => on(addDays(t, 2), spokenWhen(addDays(t, 2), t)) },
91
+ { re: /\b(?:tomorrow|tmrw)\b/, resolve: (_m, t) => on(addDays(t, 1), 'tomorrow') },
92
+ { re: /\blater (?:today|tonight|this (?:evening|afternoon))\b/, resolve: (_m, t) => on(t, 'today') },
93
+ { re: /\blater (?:this|in the) week\b/, resolve: (_m, t) => fridayOf(t) },
94
+ { re: /\b(?:tonight|today|this (?:evening|afternoon|morning))\b/, resolve: (_m, t) => on(t, 'today') },
95
+ { re: /\b(?:end of (?:the |this )?week)\b/, resolve: (_m, t) => fridayOf(t) },
96
+ { re: /\b(?:this weekend)\b/, resolve: (_m, t) => {
97
+ const delta = dow(t) === 0 ? 0 : (6 - dow(t) + 7) % 7;
98
+ return on(addDays(t, delta), 'this weekend');
99
+ } },
100
+ { re: /\bnext weekend\b/, resolve: (_m, t) => on(addDays(mondayOf(t), 12), 'next weekend') },
101
+ { re: /\b(?:next week|the week after(?: next)?)\b/, resolve: (_m, t) => on(addDays(mondayOf(t), 7), 'next week') },
102
+ { re: /\bnext month\b/, resolve: (_m, t) => {
103
+ const [y, m] = t.split('-').map(Number);
104
+ const ny = m === 12 ? y + 1 : y;
105
+ return on(`${ny}-${pad(m === 12 ? 1 : m + 1)}-01`, 'next month');
106
+ } },
107
+ { re: new RegExp(`\\bin ${NUM} (day|week)s?\\b`), resolve: (m, t) => {
108
+ const n = WORD_NUMBERS[m[1]] ?? parseInt(m[1], 10);
109
+ if (!n) return null;
110
+ const date = addDays(t, m[2] === 'week' ? n * 7 : n);
111
+ return on(date, spokenWhen(date, t));
112
+ } },
113
+ { re: /\ba week from (?:today|now)\b/, resolve: (_m, t) => on(addDays(t, 7), spokenWhen(addDays(t, 7), t)) },
114
+ { re: new RegExp(`\\b(?:(next|this|on) )?${WD}\\b`), resolve: (m, t) => {
115
+ const target = WEEKDAYS.indexOf(m[2]);
116
+ let date: string;
117
+ if (m[1] === 'next') date = addDays(mondayOf(t), 7 + ((target + 6) % 7));
118
+ else {
119
+ const delta = (target - dow(t) + 7) % 7;
120
+ date = addDays(t, delta === 0 && m[1] !== 'this' ? 7 : delta);
121
+ }
122
+ return on(date, m[1] === 'next' ? `next ${weekdayName(date)}` : spokenWhen(date, t));
123
+ } },
124
+ { re: new RegExp(`\\b${MON} (?:the )?${DAYNUM}(?: of ${MON})?\\b`), resolve: (m, t) => monthDay(MONTHS.indexOf(m[1]) + 1, dayNumber(m[2]), t) },
125
+ { re: new RegExp(`\\b(?:the )?${DAYNUM} of ${MON}\\b`), resolve: (m, t) => monthDay(MONTHS.indexOf(m[2]) + 1, dayNumber(m[1]), t) },
126
+ // "the 12th", "the third": a bare day of the month, but never "the third one".
127
+ { re: new RegExp(`\\bthe ${DAYNUM}(?!\\s*(?:one|thing|item|task|to ?do|on)\\b)(?=\\s*$)`), resolve: (m, t) => {
128
+ const day = dayNumber(m[1]);
129
+ const [y, mo, d] = t.split('-').map(Number);
130
+ let year = y; let month = mo;
131
+ if (day <= d) { month += 1; if (month > 12) { month = 1; year += 1; } }
132
+ return isRealDate(year, month, day) ? on(`${year}-${pad(month)}-${pad(day)}`, spokenWhen(`${year}-${pad(month)}-${pad(day)}`, t)) : null;
133
+ } },
134
+ { re: /\b(?:some ?time|some ?day|some other time|another time|next time|not now|not today|whenever|eventually|at some point|later)\b/, resolve: () => LATER },
135
+ ];
136
+
137
+ function fridayOf(today: string): SpokenWhen {
138
+ const d = dow(today);
139
+ const date = d >= 1 && d <= 5 ? addDays(today, 5 - d) : addDays(today, d === 6 ? 6 : 5);
140
+ return on(date, d === 5 ? 'today' : spokenWhen(date, today));
141
+ }
142
+
143
+ function monthDay(month: number, day: number, today: string): SpokenWhen | null {
144
+ const [y, , ] = today.split('-').map(Number);
145
+ if (!month || !day) return null;
146
+ let year = y;
147
+ if (!isRealDate(year, month, day)) return null;
148
+ let date = `${year}-${pad(month)}-${pad(day)}`;
149
+ if (date < today) { year += 1; if (!isRealDate(year, month, day)) return null; date = `${year}-${pad(month)}-${pad(day)}`; }
150
+ return on(date, spokenWhen(date, today));
151
+ }
152
+
153
+ /** Lowercase, hyphens and stray punctuation to spaces: how the rules above expect text. */
154
+ export function normalizeSpeech(text: string): string {
155
+ return text.toLowerCase().replace(/[‘’]/g, "'").replace(/[^a-z0-9'\s-]/g, ' ').replace(/\s+/g, ' ').trim();
156
+ }
157
+
158
+ export interface FoundWhen { when: SpokenWhen; start: number; end: number }
159
+
160
+ /** The leftmost (then longest) date phrase in `text`, with where it sits. */
161
+ export function findWhen(text: string, now: number, timeZone: string): FoundWhen | null {
162
+ const today = localDate(now, timeZone);
163
+ // Callers pass text already through `normalizeSpeech`, so indexes here are indexes into it.
164
+ const lower = text.toLowerCase().replace(/-/g, ' ').replace(/\s+/g, ' ').trim();
165
+ let best: { m: RegExpExecArray; rule: Rule } | null = null;
166
+ for (const rule of RULES) {
167
+ const m = rule.re.exec(lower);
168
+ if (!m) continue;
169
+ if (!best || m.index < best.m.index || (m.index === best.m.index && m[0].length > best.m[0].length)) best = { m, rule };
170
+ }
171
+ if (!best) return null;
172
+ const when = best.rule.resolve(best.m, today);
173
+ return when ? { when, start: best.m.index, end: best.m.index + best.m[0].length } : null;
174
+ }
175
+
176
+ /** Resolve a phrase that should be ONLY a date ("next friday"); null when it is not one. */
177
+ export function parseWhen(phrase: string, now: number, timeZone: string): SpokenWhen | null {
178
+ const text = normalizeSpeech(phrase).replace(/^(?:to|until|till|for|on|by|out to|up to|back to)\s+/, '');
179
+ if (isIsoDate(text as unknown)) return on(text, spokenWhen(text, localDate(now, timeZone)));
180
+ const found = findWhen(text, now, timeZone);
181
+ if (!found) return null;
182
+ const spans = text.replace(/-/g, ' ');
183
+ const rest = (spans.slice(0, found.start) + spans.slice(found.end)).replace(/\b(?:the|a|an|to|on|at|by|in|of|this)\b/g, ' ').trim();
184
+ return rest ? null : found.when;
185
+ }
186
+
187
+ /** `text` with the date phrase cut out, plus the phrase's meaning. */
188
+ export function splitWhen(text: string, now: number, timeZone: string): { rest: string; when: SpokenWhen; after: string } | null {
189
+ const clean = normalizeSpeech(text).replace(/-/g, ' ');
190
+ const found = findWhen(clean, now, timeZone);
191
+ if (!found) return null;
192
+ const before = clean.slice(0, found.start).replace(/\s*(?:to|until|till|for|on|by|due|before|at|out to|up to|back to|into|in|from)\s*$/, '').trim();
193
+ const after = clean.slice(found.end).trim();
194
+ return { rest: `${before} ${after}`.replace(/\s+/g, ' ').trim(), when: found.when, after };
195
+ }