@startsimpli/integrations 0.2.117 → 0.2.119

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.117",
3
+ "version": "0.2.119",
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,7 +50,7 @@
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.170",
53
+ "@startsimpli/ui": "^0.4.171",
54
54
  "@startsimpli/auth": "^0.4.50",
55
55
  "@startsimpli/utils": "^0.4.17"
56
56
  },
@@ -98,11 +98,11 @@
98
98
  "vitest": "^3.0.0",
99
99
  "react-native": "0.85.3",
100
100
  "react-native-safe-area-context": "~5.7.0",
101
- "@startsimpli/llm": "0.4.28",
102
- "@startsimpli/auth": "0.4.50",
101
+ "@startsimpli/llm": "0.4.30",
102
+ "@startsimpli/ui": "0.4.171",
103
103
  "@startsimpli/ui-native": "0.1.14",
104
- "@startsimpli/utils": "0.4.17",
105
- "@startsimpli/ui": "0.4.170"
104
+ "@startsimpli/auth": "0.4.50",
105
+ "@startsimpli/utils": "0.4.17"
106
106
  },
107
107
  "scripts": {
108
108
  "type-check": "tsc --noEmit && tsc --noEmit -p tsconfig.native.json",
@@ -0,0 +1,102 @@
1
+ import { describe, expect, it } from 'vitest';
2
+
3
+ import { composeBriefing, localDate, type BriefingItem } from '../corpus/briefing';
4
+
5
+ const ME = 'user-me';
6
+ // 2026-11-05 09:00 in New York (14:00Z).
7
+ const NOW = Date.parse('2026-11-05T14:00:00Z');
8
+ const TZ = 'America/New_York';
9
+
10
+ const item = (over: Partial<BriefingItem> & { id: string }): BriefingItem => ({
11
+ title: `Item ${over.id}`,
12
+ status: 'open',
13
+ ownerSub: ME,
14
+ dueAt: '2026-11-05',
15
+ ...over,
16
+ });
17
+ const compose = (items: BriefingItem[], over = {}) =>
18
+ composeBriefing(items, { ownerSub: ME, now: NOW, timeZone: TZ, ...over });
19
+
20
+ describe('composeBriefing', () => {
21
+ it('lists overdue, then in progress, then due today, each ordered by priority then date', () => {
22
+ const b = compose([
23
+ item({ id: 'today-hi', priority: 0 }),
24
+ item({ id: 'today-lo', priority: 3 }),
25
+ item({ id: 'prog', status: 'in_progress', dueAt: null, priority: 2 }),
26
+ item({ id: 'over-lo', dueAt: '2026-11-01', priority: 3 }),
27
+ item({ id: 'over-hi', dueAt: '2026-11-03', priority: 1 }),
28
+ ]);
29
+ expect(b.items.map((i) => i.id)).toEqual(['over-hi', 'over-lo', 'prog', 'today-hi', 'today-lo']);
30
+ expect(b.items.map((i) => i.kind)).toEqual(['overdue', 'overdue', 'in_progress', 'due_today', 'due_today']);
31
+ });
32
+
33
+ it('never includes done, dropped, or Linear completed/canceled items', () => {
34
+ const b = compose([
35
+ item({ id: 'done', status: 'done' }),
36
+ item({ id: 'dropped', status: 'dropped' }),
37
+ item({ id: 'lin-done', linearState: 'completed' }),
38
+ item({ id: 'lin-cancel', linearState: 'canceled' }),
39
+ item({ id: 'ok', linearState: 'started' }),
40
+ ]);
41
+ expect(b.items.map((i) => i.id)).toEqual(['ok']);
42
+ });
43
+
44
+ it('is owner scoped: other users (and unowned rows) are never included', () => {
45
+ const b = compose([item({ id: 'mine' }), item({ id: 'theirs', ownerSub: 'someone-else' }), item({ id: 'nobody', ownerSub: undefined })]);
46
+ expect(b.items.map((i) => i.id)).toEqual(['mine']);
47
+ });
48
+
49
+ it('groups by project focus name, else Personal', () => {
50
+ const b = compose([item({ id: 'a', focusName: 'Tandem' }), item({ id: 'b' })]);
51
+ expect(b.items.map((i) => i.group)).toEqual(['Tandem', 'Personal']);
52
+ });
53
+
54
+ it('caps at 8 spoken items and reports how many more', () => {
55
+ const items = Array.from({ length: 11 }, (_, n) => item({ id: `i${n}`, priority: n % 5 }));
56
+ const b = compose(items);
57
+ expect(b.items).toHaveLength(8);
58
+ expect(b.remaining).toBe(3);
59
+ expect(b.total).toBe(11);
60
+ });
61
+
62
+ it('returns an explicit empty state', () => {
63
+ const b = compose([item({ id: 'later', dueAt: '2026-11-20' }), item({ id: 'undated', dueAt: null })]);
64
+ expect(b.empty).toBe(true);
65
+ expect(b.items).toEqual([]);
66
+ expect(b.counts).toEqual({ overdue: 0, in_progress: 0, due_today: 0 });
67
+ });
68
+
69
+ it('returns the ordered item ids as the briefing context', () => {
70
+ const b = compose([item({ id: 'x', priority: 2 }), item({ id: 'y', priority: 1 })]);
71
+ expect(b.context.itemIds).toEqual(['y', 'x']);
72
+ expect(b.context.localDate).toBe('2026-11-05');
73
+ });
74
+
75
+ it('carries the Linear identifier when linked', () => {
76
+ const b = compose([item({ id: 'l', linearIdentifier: 'LIN-123' }), item({ id: 'n' })]);
77
+ expect(b.items[0].linearIdentifier).toBe('LIN-123');
78
+ expect(b.items[1].linearIdentifier).toBeUndefined();
79
+ });
80
+
81
+ it('uses the time zone, not UTC, for today (midnight boundary)', () => {
82
+ // 2026-11-06T02:00Z is still Nov 5 evening in New York, already Nov 6 in UTC.
83
+ const late = Date.parse('2026-11-06T02:00:00Z');
84
+ expect(localDate(late, TZ)).toBe('2026-11-05');
85
+ expect(localDate(late, 'UTC')).toBe('2026-11-06');
86
+ const ny = composeBriefing([item({ id: 't', dueAt: '2026-11-05' })], { ownerSub: ME, now: late, timeZone: TZ });
87
+ expect(ny.items[0].kind).toBe('due_today');
88
+ const utc = composeBriefing([item({ id: 't', dueAt: '2026-11-05' })], { ownerSub: ME, now: late, timeZone: 'UTC' });
89
+ expect(utc.items[0].kind).toBe('overdue');
90
+ });
91
+
92
+ it('reads a full ISO due date in the user zone', () => {
93
+ // 2026-11-05T03:00Z is Nov 4 at 10pm in New York: overdue, not today.
94
+ const b = compose([item({ id: 'iso', dueAt: '2026-11-05T03:00:00Z' })]);
95
+ expect(b.items[0].kind).toBe('overdue');
96
+ });
97
+
98
+ it('keeps an in-progress item even when it has no date, and tolerates unknown status words', () => {
99
+ const b = compose([item({ id: 'p', status: 'in_progress', dueAt: null }), item({ id: 'weird', status: 'whatever' as never })]);
100
+ expect(b.items.map((i) => i.id)).toEqual(['p', 'weird']);
101
+ });
102
+ });
@@ -0,0 +1,144 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+
3
+ import {
4
+ composeBriefing, speakCount, speakDate, writeBriefingScript,
5
+ type BriefingItem, type BriefingScriptLlm,
6
+ } from '../corpus/briefing';
7
+
8
+ const ME = 'me';
9
+ const NOW = Date.parse('2026-11-05T14:00:00Z'); // Thursday 9:00 in New York
10
+ const TZ = 'America/New_York';
11
+ const item = (over: Partial<BriefingItem> & { id: string }): BriefingItem => ({
12
+ title: `Do ${over.id}`, status: 'open', ownerSub: ME, dueAt: '2026-11-05', ...over,
13
+ });
14
+ const brief = (items: BriefingItem[], max?: number) =>
15
+ composeBriefing(items, { ownerSub: ME, now: NOW, timeZone: TZ, maxItems: max });
16
+ const opts = { now: NOW, timeZone: TZ, name: 'Quinn' };
17
+
18
+ const day = [
19
+ item({ id: 'a', title: 'Review the **invoice** [LIN-123](https://linear.app/x/issue/LIN-123)', dueAt: '2026-11-02', linearIdentifier: 'LIN-123', priority: 1, focusName: 'Tandem' }),
20
+ item({ id: 'b', title: 'Finish briefing slice', status: 'in_progress', dueAt: null }),
21
+ item({ id: 'c', title: 'Ship the speech package' }),
22
+ ];
23
+ const briefing = () => brief(day);
24
+
25
+ /** A fake model that returns the JSON contract for whatever items it was shown. */
26
+ const goodLlm = (extra: object = {}): BriefingScriptLlm => ({
27
+ write: vi.fn(async ({ prompt }) => {
28
+ const ids = [...prompt.matchAll(/\[id:([^\]]+)\]/g)].map((m) => m[1]);
29
+ return JSON.stringify({ lead: 'A steady one today.', items: ids.map((id) => ({ id, say: `Item ${id} needs you.` })), ...extra });
30
+ }),
31
+ });
32
+
33
+ describe('speakDate / speakCount', () => {
34
+ it.each([
35
+ // The bead's example (2026-11-07 = Friday) was wrong: that day is a Saturday.
36
+ ['2026-11-07', 'Saturday the seventh'],
37
+ ['2026-11-06', 'Friday the sixth'],
38
+ ['2026-11-05', 'Thursday the fifth'],
39
+ ['2026-11-02', 'Monday the second'],
40
+ ['2026-11-21', 'Saturday the twenty-first'],
41
+ ['2026-11-30', 'Monday the thirtieth'],
42
+ ['2026-10-30', 'Friday the thirtieth of October'],
43
+ ])('%s -> %s', (iso, spoken) => expect(speakDate(iso, '2026-11-05')).toBe(spoken));
44
+ it.each([[1, 'one'], [2, 'two'], [8, 'eight'], [12, 'twelve'], [21, 'twenty-one'], [100, '100']])('%i -> %s', (n, w) =>
45
+ expect(speakCount(n)).toBe(w));
46
+ });
47
+
48
+ describe('writeBriefingScript', () => {
49
+ it('has no markdown, bullets, urls or identifiers read as codes (LIN-123 is not spoken)', async () => {
50
+ for (const llm of [goodLlm(), { write: async () => { throw new Error('down'); } }]) {
51
+ const s = await writeBriefingScript(briefing(), llm, opts);
52
+ expect(s.text).not.toMatch(/[*_#`\[\]]|https?:|www\.|^\s*[-•]|LIN-\d+|\b[A-Z]{2,}-\d+\b/m);
53
+ }
54
+ });
55
+
56
+ it('speaks dates and counts in words', async () => {
57
+ const s = await writeBriefingScript(briefing(), null, opts);
58
+ expect(s.text).toContain('Monday the second');
59
+ expect(s.text).toMatch(/\bthree items\b/);
60
+ expect(s.text).not.toMatch(/\d/);
61
+ });
62
+
63
+ it('stays under 220 words even for a long model reply', async () => {
64
+ const wordy: BriefingScriptLlm = { write: async () => JSON.stringify({ lead: 'x', items: [{ id: 'a', say: 'word '.repeat(400) }, { id: 'b', say: 'ok' }, { id: 'c', say: 'ok' }] }) };
65
+ const s = await writeBriefingScript(briefing(), wordy, opts);
66
+ expect(s.words).toBeLessThanOrEqual(220);
67
+ expect(s.source).toBe('template'); // an over-budget reply is not trusted
68
+ const full = await writeBriefingScript(brief(Array.from({ length: 12 }, (_, n) => item({ id: `i${n}`, title: 'Review the quarterly vendor contract renewal terms with legal' }))), null, opts);
69
+ expect(full.words).toBeLessThanOrEqual(220);
70
+ });
71
+
72
+ it('greets in the second person with the part of day in the listener zone', async () => {
73
+ expect((await writeBriefingScript(briefing(), goodLlm(), opts)).text).toMatch(/^Good morning, Quinn\./);
74
+ const noon = { ...opts, now: Date.parse('2026-11-05T19:30:00Z') }; // 2:30pm NY
75
+ expect((await writeBriefingScript(composeBriefing(day, { ownerSub: ME, now: noon.now, timeZone: TZ }), null, noon)).text).toMatch(/^Good afternoon, Quinn\./);
76
+ const eve = { ...opts, now: Date.parse('2026-11-06T00:30:00Z') }; // 7:30pm NY, still the 5th
77
+ expect((await writeBriefingScript(composeBriefing(day, { ownerSub: ME, now: eve.now, timeZone: TZ }), null, eve)).text).toMatch(/^Good evening, Quinn\./);
78
+ expect((await writeBriefingScript(briefing(), null, { ...opts, name: undefined })).text).toMatch(/^Good morning\./);
79
+ expect((await writeBriefingScript(briefing(), null, opts)).text).toMatch(/\byou\b/i);
80
+ });
81
+
82
+ it.each([
83
+ ['throws', { write: async () => { throw new Error('boom'); } }],
84
+ ['times out', { write: () => new Promise<string>(() => {}) }],
85
+ ['returns garbage', { write: async () => 'Sure! Here is your briefing: ...' }],
86
+ ['returns markdown', { write: async () => JSON.stringify({ items: [{ id: 'a', say: '**bold**' }, { id: 'b', say: 'ok' }, { id: 'c', say: 'ok' }] }) }],
87
+ ])('falls back to the template with the same items when the model %s', async (_n, llm) => {
88
+ const s = await writeBriefingScript(briefing(), llm as BriefingScriptLlm, { ...opts, timeoutMs: 20 });
89
+ expect(s.source).toBe('template');
90
+ expect(s.segments.filter((x) => x.id).map((x) => x.id)).toEqual(['a', 'b', 'c']);
91
+ });
92
+
93
+ it('cannot add, drop, duplicate or reorder items', async () => {
94
+ const extra = goodLlm({ items: [{ id: 'a', say: 'x' }, { id: 'ghost', say: 'a made up task' }, { id: 'b', say: 'x' }, { id: 'c', say: 'x' }] });
95
+ const s1 = await writeBriefingScript(briefing(), extra, opts);
96
+ expect(s1.source).toBe('template');
97
+ expect(s1.text).not.toContain('made up');
98
+ const dropped = goodLlm({ items: [{ id: 'a', say: 'x' }] });
99
+ expect((await writeBriefingScript(briefing(), dropped, opts)).source).toBe('template');
100
+ const dup = goodLlm({ items: [{ id: 'a', say: 'x' }, { id: 'a', say: 'x' }, { id: 'c', say: 'x' }] });
101
+ expect((await writeBriefingScript(briefing(), dup, opts)).source).toBe('template');
102
+ // A reordered reply is kept but laid out in the composer's order: overdue still first.
103
+ const swapped = goodLlm({ items: [{ id: 'c', say: 'x' }, { id: 'b', say: 'x' }, { id: 'a', say: 'x' }] });
104
+ const reordered = await writeBriefingScript(briefing(), swapped, opts);
105
+ expect(reordered.source).toBe('llm');
106
+ expect(reordered.segments.filter((x) => x.id).map((x) => x.id)).toEqual(['a', 'b', 'c']);
107
+ const ok = await writeBriefingScript(briefing(), goodLlm(), opts);
108
+ expect(ok.source).toBe('llm');
109
+ expect(ok.segments.filter((x) => x.id).map((x) => x.id)).toEqual(['a', 'b', 'c']);
110
+ });
111
+
112
+ it('calls out overdue items first', async () => {
113
+ for (const llm of [null, goodLlm()]) {
114
+ const s = await writeBriefingScript(briefing(), llm, opts);
115
+ expect(s.segments.find((x) => x.id)!.id).toBe('a');
116
+ }
117
+ const t = await writeBriefingScript(briefing(), null, opts);
118
+ expect(t.text.indexOf('overdue')).toBeGreaterThan(-1);
119
+ expect(t.text.indexOf('overdue')).toBeLessThan(t.text.indexOf('Finish briefing slice'));
120
+ });
121
+
122
+ it('records where each item starts and ends in the text (for voice replies)', async () => {
123
+ const s = await writeBriefingScript(briefing(), goodLlm(), opts);
124
+ for (const seg of s.segments.filter((x) => x.id)) {
125
+ expect(seg.start).toBeLessThan(seg.end);
126
+ expect(s.text.slice(seg.start, seg.end)).toContain(`Item ${seg.id} needs you.`);
127
+ }
128
+ });
129
+
130
+ it('says "and N more" when the composer capped the list', async () => {
131
+ const many = brief(Array.from({ length: 5 }, (_, n) => item({ id: `i${n}`, priority: n })), 3);
132
+ const s = await writeBriefingScript(many, null, opts);
133
+ expect(s.text).toMatch(/and two more/i);
134
+ expect((await writeBriefingScript(many, goodLlm(), opts)).text).toMatch(/and two more/i);
135
+ });
136
+
137
+ it('has a plain script for an empty day, and never calls the model', async () => {
138
+ const llm = goodLlm();
139
+ const s = await writeBriefingScript(brief([]), llm, opts);
140
+ expect(s.text).toMatch(/^Good morning, Quinn\. Nothing is due today/);
141
+ expect(s.segments).toEqual([]);
142
+ expect(llm.write).not.toHaveBeenCalled();
143
+ });
144
+ });
@@ -0,0 +1,83 @@
1
+ /**
2
+ * THE BRIEFING CONTENT (bd startsim-nwc7t): what is on this person's plate today.
3
+ *
4
+ * PURE. No clock, no network, no zone database beyond `Intl`: the caller passes
5
+ * `now` and `timeZone`, so the same function runs on the server route, in the
6
+ * native app and in a test. Eligibility is one rule set: owned by the caller,
7
+ * not done / dropped, not completed or canceled in Linear, and either overdue,
8
+ * in progress, or due today in the CALLER'S zone.
9
+ */
10
+ import type {
11
+ Briefing, BriefingEntry, BriefingItem, BriefingKind, BriefingOptions,
12
+ } from './types';
13
+
14
+ const FINISHED = new Set(['done', 'dropped']);
15
+ const LINEAR_FINISHED = new Set(['completed', 'canceled', 'cancelled']);
16
+ const DEFAULT_MAX_ITEMS = 8;
17
+ const KIND_RANK: Record<BriefingKind, number> = { overdue: 0, in_progress: 1, due_today: 2 };
18
+
19
+ /** `YYYY-MM-DD` of an instant in a zone. */
20
+ export function localDate(instant: number, timeZone = 'UTC'): string {
21
+ const parts = new Intl.DateTimeFormat('en-US', { timeZone, year: 'numeric', month: '2-digit', day: '2-digit' })
22
+ .formatToParts(new Date(instant));
23
+ const get = (type: string) => parts.find((p) => p.type === type)?.value ?? '';
24
+ return `${get('year')}-${get('month')}-${get('day')}`;
25
+ }
26
+
27
+ /** The calendar day a due value means: a bare date as written, an instant in the zone. */
28
+ function dueDate(dueAt: string | null | undefined, timeZone: string): string | null {
29
+ if (!dueAt) return null;
30
+ if (/^\d{4}-\d{2}-\d{2}$/.test(dueAt)) return dueAt;
31
+ const t = Date.parse(dueAt);
32
+ return Number.isNaN(t) ? null : localDate(t, timeZone);
33
+ }
34
+
35
+ function kindOf(item: BriefingItem, due: string | null, today: string): BriefingKind | null {
36
+ if (due && due < today) return 'overdue';
37
+ if (item.status === 'in_progress') return 'in_progress';
38
+ if (due === today) return 'due_today';
39
+ return null;
40
+ }
41
+
42
+ export function composeBriefing(items: BriefingItem[], options: BriefingOptions): Briefing {
43
+ const timeZone = options.timeZone ?? 'UTC';
44
+ const today = localDate(options.now, timeZone);
45
+ const max = options.maxItems ?? DEFAULT_MAX_ITEMS;
46
+
47
+ const eligible: BriefingEntry[] = [];
48
+ for (const item of items) {
49
+ if (!item.ownerSub || item.ownerSub !== options.ownerSub) continue;
50
+ if (FINISHED.has(item.status)) continue;
51
+ if (item.linearState && LINEAR_FINISHED.has(item.linearState.toLowerCase())) continue;
52
+ const due = dueDate(item.dueAt, timeZone);
53
+ const kind = kindOf(item, due, today);
54
+ if (!kind) continue;
55
+ eligible.push({
56
+ id: item.id,
57
+ title: item.title,
58
+ kind,
59
+ group: item.focusName?.trim() || 'Personal',
60
+ dueDate: due,
61
+ ...(item.priority !== undefined ? { priority: item.priority } : {}),
62
+ ...(item.linearIdentifier ? { linearIdentifier: item.linearIdentifier } : {}),
63
+ });
64
+ }
65
+
66
+ // Array.sort is stable: equal rows keep the order they arrived in.
67
+ eligible.sort((a, b) =>
68
+ KIND_RANK[a.kind] - KIND_RANK[b.kind]
69
+ || (a.priority ?? 99) - (b.priority ?? 99)
70
+ || (a.dueDate ?? '9999').localeCompare(b.dueDate ?? '9999'));
71
+
72
+ const counts: Briefing['counts'] = { overdue: 0, in_progress: 0, due_today: 0 };
73
+ for (const entry of eligible) counts[entry.kind] += 1;
74
+ const spoken = eligible.slice(0, max);
75
+ return {
76
+ items: spoken,
77
+ remaining: eligible.length - spoken.length,
78
+ total: eligible.length,
79
+ counts,
80
+ empty: eligible.length === 0,
81
+ context: { itemIds: spoken.map((e) => e.id), localDate: today, timeZone },
82
+ };
83
+ }
@@ -0,0 +1,7 @@
1
+ export { composeBriefing, localDate } from './compose';
2
+ export type {
3
+ Briefing, BriefingContext, BriefingEntry, BriefingItem, BriefingKind, BriefingOptions,
4
+ } from './types';
5
+ export { writeBriefingScript, templateScript, scriptPrompt, scriptSystemPrompt } from './script';
6
+ export type { BriefingScript, BriefingScriptLlm, BriefingScriptOptions, ScriptSegment } from './script';
7
+ export { speakCount, speakDate, speakable, isUnspeakable, partOfDay, wordCount } from './speak';
@@ -0,0 +1,29 @@
1
+ /**
2
+ * SERVER-ONLY: the real model behind `BriefingScriptLlm`. Re-exported from
3
+ * `@startsimpli/integrations/corpus-llm` and never from the package index, for
4
+ * the reason `corpus/llm.ts` gives (no provider client in a browser bundle).
5
+ */
6
+ import { LLMService } from '@startsimpli/llm';
7
+
8
+ import { voiceAnalyzerDefaults, type CorpusLlmOptions } from '../llm';
9
+ import type { BriefingScriptLlm } from './script';
10
+
11
+ export function createBriefingScriptLlm(options: CorpusLlmOptions = {}): BriefingScriptLlm {
12
+ const defaults = voiceAnalyzerDefaults(options.env, options);
13
+ const service =
14
+ options.service ??
15
+ new LLMService<unknown>({
16
+ preferredProvider: defaults.preferredProvider,
17
+ defaultModel: defaults.model,
18
+ // A little warmth: this is wording, not extraction. The validator holds the facts.
19
+ defaultTemperature: options.temperature ?? 0.5,
20
+ defaultMaxTokens: options.maxTokens ?? 900,
21
+ });
22
+ return {
23
+ async write({ system, prompt, timeoutMs }) {
24
+ if (!service.isAvailable()) throw new Error('No LLM provider is reachable for the briefing script.');
25
+ const response = await service.chat(prompt, system, { timeout: timeoutMs ?? options.timeoutMs });
26
+ return response.content;
27
+ },
28
+ };
29
+ }
@@ -0,0 +1,223 @@
1
+ /**
2
+ * THE SPOKEN SCRIPT (bd startsim-e8upb): turn a composed briefing into a short
3
+ * thing a person can listen to, and NEVER fail to produce one.
4
+ *
5
+ * THE MODEL ONLY WORDS THE ITEMS. The greeting, the counts, the "and N more" and
6
+ * the sign-off are ours, and the model's reply is a JSON list keyed by the item
7
+ * ids it was shown. So it cannot add a task (an unknown id fails), drop one,
8
+ * reorder them (we lay the text out in our order), or push the script over budget, and every sentence maps to an id
9
+ * - which is what lets a voice reply resolve "this one" by character offset.
10
+ * Anything off the contract (timeout, error, garbage, markup, a code like
11
+ * LIN-123, a numeric date, too long) is discarded for the deterministic template
12
+ * over the SAME items.
13
+ */
14
+ import { partOfDay, isUnspeakable, speakCount, speakDate, speakable, wordCount } from './speak';
15
+ import type { Briefing, BriefingEntry } from './types';
16
+
17
+ /** One text completion. Server adapters wrap `@startsimpli/llm`; tests pass a fake. */
18
+ export interface BriefingScriptLlm {
19
+ write(input: { system: string; prompt: string; timeoutMs?: number }): Promise<string>;
20
+ }
21
+
22
+ export interface BriefingScriptOptions {
23
+ now: number;
24
+ timeZone?: string;
25
+ /** How to address the listener. */
26
+ name?: string;
27
+ /** Model deadline; past it the template is used. Default 12 s. */
28
+ timeoutMs?: number;
29
+ /** Word budget (about 90 seconds spoken). Default 220. */
30
+ maxWords?: number;
31
+ }
32
+
33
+ export interface ScriptSegment {
34
+ /** The item this stretch of text is about; null for greeting, lead and sign-off. */
35
+ id: string | null;
36
+ /** Offsets into `text`, end exclusive. */
37
+ start: number;
38
+ end: number;
39
+ }
40
+
41
+ export interface BriefingScript {
42
+ text: string;
43
+ segments: ScriptSegment[];
44
+ source: 'llm' | 'template';
45
+ words: number;
46
+ }
47
+
48
+ const DEFAULT_TIMEOUT_MS = 12_000;
49
+ const DEFAULT_MAX_WORDS = 220;
50
+ const MAX_LEAD_WORDS = 25;
51
+ const MAX_SAY_WORDS = 30;
52
+
53
+ export function scriptSystemPrompt(): string {
54
+ return [
55
+ 'You write short spoken to-do briefings that a text-to-speech voice will read aloud.',
56
+ 'Reply with ONLY a JSON object: {"lead": string, "items": [{"id": string, "say": string}]}.',
57
+ '"items" must contain EVERY item shown, exactly once, using the id given in [id:...]; do not add items.',
58
+ '"say" is one short, natural sentence about that item (at most 25 words), in the second person where it fits.',
59
+ '"lead" is one optional sentence (at most 20 words) setting the tone; use an empty string if nothing to add.',
60
+ 'Plain spoken English only: no markdown, bullets, quotes, links, ticket codes like ABC-123, or digits for dates.',
61
+ 'Say dates the way a person would (Friday the seventh). Never invent items, dates or details.',
62
+ ].join('\n');
63
+ }
64
+
65
+ function itemLine(entry: BriefingEntry, today: string): string {
66
+ const title = speakable(entry.title) || 'an untitled item';
67
+ const when = entry.kind === 'overdue' && entry.dueDate ? `overdue, was due ${speakDate(entry.dueDate, today)}`
68
+ : entry.kind === 'in_progress' ? 'in progress'
69
+ : 'due today';
70
+ const project = entry.group === 'Personal' ? '' : `; project: ${speakable(entry.group, 6)}`;
71
+ return `[id:${entry.id}] ${title} (${when}${project})`;
72
+ }
73
+
74
+ export function scriptPrompt(briefing: Briefing): string {
75
+ const today = briefing.context.localDate;
76
+ return ['Items, most urgent first:', ...briefing.items.map((e) => itemLine(e, today))].join('\n');
77
+ }
78
+
79
+ // -- the deterministic template ----------------------------------------------
80
+
81
+ const projectOf = (e: BriefingEntry) => (e.group === 'Personal' ? '' : ` for ${speakable(e.group, 6)}`);
82
+
83
+ function templateSay(entry: BriefingEntry, today: string): string {
84
+ const title = speakable(entry.title) || 'An untitled item';
85
+ const lowered = title.charAt(0).toUpperCase() + title.slice(1);
86
+ if (entry.kind === 'overdue') {
87
+ return entry.dueDate
88
+ ? `${lowered}${projectOf(entry)} is overdue, it was due ${speakDate(entry.dueDate, today)}.`
89
+ : `${lowered}${projectOf(entry)} is overdue.`;
90
+ }
91
+ if (entry.kind === 'in_progress') return `You are working on ${title}${projectOf(entry)}.`;
92
+ return `${lowered}${projectOf(entry)} is due today.`;
93
+ }
94
+
95
+ function greeting(options: BriefingScriptOptions): string {
96
+ const part = partOfDay(options.now, options.timeZone ?? 'UTC');
97
+ return options.name ? `Good ${part}, ${options.name}.` : `Good ${part}.`;
98
+ }
99
+
100
+ function summaryLine(briefing: Briefing): string {
101
+ const n = briefing.total;
102
+ const noun = n === 1 ? 'item' : 'items';
103
+ const overdue = briefing.counts.overdue;
104
+ const tail = overdue > 0 ? `, ${speakCount(overdue)} of them overdue` : '';
105
+ return `You have ${speakCount(n)} ${noun} on your plate today${tail}.`;
106
+ }
107
+
108
+ function signOff(briefing: Briefing): string {
109
+ const n = briefing.remaining;
110
+ return n > 0 ? `And ${speakCount(n)} more after that.` : 'That is everything.';
111
+ }
112
+
113
+ interface Parts { lead?: string; says: Array<{ id: string; text: string }> }
114
+
115
+ /** Join the parts into one text, recording each item's offsets. */
116
+ function assemble(briefing: Briefing, options: BriefingScriptOptions, parts: Parts, source: 'llm' | 'template'): BriefingScript {
117
+ let text = '';
118
+ const segments: ScriptSegment[] = [];
119
+ const add = (piece: string, id: string | null) => {
120
+ if (text) text += ' ';
121
+ const start = text.length;
122
+ text += piece;
123
+ segments.push({ id, start, end: text.length });
124
+ };
125
+ add(greeting(options), null);
126
+ add(summaryLine(briefing), null);
127
+ if (parts.lead) add(parts.lead, null);
128
+ for (const say of parts.says) add(say.text, say.id);
129
+ add(signOff(briefing), null);
130
+ return { text, segments, source, words: wordCount(text) };
131
+ }
132
+
133
+ /** The template, shrunk (trailing items fold into "and N more") until it fits the budget. */
134
+ export function templateScript(briefing: Briefing, options: BriefingScriptOptions): BriefingScript {
135
+ const budget = options.maxWords ?? DEFAULT_MAX_WORDS;
136
+ const today = briefing.context.localDate;
137
+ let shown = briefing.items;
138
+ for (;;) {
139
+ const trimmed: Briefing = { ...briefing, items: shown, remaining: briefing.remaining + (briefing.items.length - shown.length) };
140
+ const built = assemble(trimmed, options, { says: shown.map((e) => ({ id: e.id, text: templateSay(e, today) })) }, 'template');
141
+ if (built.words <= budget || shown.length <= 1) return built;
142
+ shown = shown.slice(0, -1);
143
+ }
144
+ }
145
+
146
+ // -- the model path -----------------------------------------------------------
147
+
148
+ function emptyScript(options: BriefingScriptOptions): BriefingScript {
149
+ const text = `${greeting(options)} Nothing is due today, and nothing is overdue. Enjoy the clear day.`;
150
+ return { text, segments: [], source: 'template', words: wordCount(text) };
151
+ }
152
+
153
+ /** The model's reply as parts, or null when it is not exactly what was asked for. */
154
+ function parseReply(raw: string, briefing: Briefing): Parts | null {
155
+ let json: unknown;
156
+ try {
157
+ json = JSON.parse(raw.trim().replace(/^```(?:json)?\s*|\s*```$/g, ''));
158
+ } catch {
159
+ return null;
160
+ }
161
+ if (!json || typeof json !== 'object') return null;
162
+ const { lead, items } = json as { lead?: unknown; items?: unknown };
163
+ if (!Array.isArray(items) || items.length !== briefing.items.length) return null;
164
+ // Any order is fine (the model often groups by urgency): the ids must be EXACTLY the
165
+ // ones shown, each once, and the text is laid out in OUR order, so a reordered reply
166
+ // cannot change what is read first.
167
+ const byId = new Map<string, string>();
168
+ for (const raw of items) {
169
+ const row = raw as { id?: unknown; say?: unknown };
170
+ if (!row || typeof row.id !== 'string' || typeof row.say !== 'string' || byId.has(row.id)) return null;
171
+ const text = row.say.trim();
172
+ if (!text || wordCount(text) > MAX_SAY_WORDS || isUnspeakable(text)) return null;
173
+ byId.set(row.id, text);
174
+ }
175
+ const says: Parts['says'] = [];
176
+ for (const entry of briefing.items) {
177
+ const text = byId.get(entry.id);
178
+ if (text === undefined) return null;
179
+ says.push({ id: entry.id, text });
180
+ }
181
+ let leadText = '';
182
+ if (lead !== undefined && lead !== null && lead !== '') {
183
+ if (typeof lead !== 'string') return null;
184
+ leadText = lead.trim();
185
+ if (wordCount(leadText) > MAX_LEAD_WORDS || isUnspeakable(leadText)) return null;
186
+ }
187
+ return { lead: leadText || undefined, says };
188
+ }
189
+
190
+ function withDeadline<T>(work: Promise<T>, ms: number): Promise<T> {
191
+ let timer: ReturnType<typeof setTimeout>;
192
+ const timeout = new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error('briefing script timed out')), ms); });
193
+ return Promise.race([work, timeout]).finally(() => clearTimeout(timer));
194
+ }
195
+
196
+ /**
197
+ * The script for a briefing. `llm` may be null (template only). Never throws:
198
+ * every failure of the model path ends in the template over the same items.
199
+ */
200
+ export async function writeBriefingScript(
201
+ briefing: Briefing,
202
+ llm: BriefingScriptLlm | null,
203
+ options: BriefingScriptOptions,
204
+ ): Promise<BriefingScript> {
205
+ if (briefing.empty) return emptyScript(options);
206
+ if (llm) {
207
+ const ms = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
208
+ try {
209
+ const raw = await withDeadline(
210
+ Promise.resolve(llm.write({ system: scriptSystemPrompt(), prompt: scriptPrompt(briefing), timeoutMs: ms })),
211
+ ms,
212
+ );
213
+ const parts = parseReply(raw, briefing);
214
+ if (parts) {
215
+ const built = assemble(briefing, options, parts, 'llm');
216
+ if (built.words <= (options.maxWords ?? DEFAULT_MAX_WORDS)) return built;
217
+ }
218
+ } catch {
219
+ // fall through to the template
220
+ }
221
+ }
222
+ return templateScript(briefing, options);
223
+ }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Spoken forms: numbers, dates, and text made safe to read aloud. Pure.
3
+ */
4
+ const ONES = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve',
5
+ 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];
6
+ const TENS = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
7
+ const ORD_ONES = ['', 'first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth',
8
+ 'eleventh', 'twelfth', 'thirteenth', 'fourteenth', 'fifteenth', 'sixteenth', 'seventeenth', 'eighteenth', 'nineteenth'];
9
+ const WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
10
+ const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October',
11
+ 'November', 'December'];
12
+
13
+ /** 0..99 in words; anything larger stays digits (a count that big is not read out). */
14
+ export function speakCount(n: number): string {
15
+ if (n < 20) return ONES[n] ?? String(n);
16
+ if (n < 100) return TENS[Math.floor(n / 10)] + (n % 10 ? `-${ONES[n % 10]}` : '');
17
+ return String(n);
18
+ }
19
+
20
+ function ordinal(n: number): string {
21
+ if (n < 20) return ORD_ONES[n];
22
+ if (n % 10 === 0) return TENS[n / 10].replace(/y$/, 'ieth');
23
+ return `${TENS[Math.floor(n / 10)]}-${ORD_ONES[n % 10]}`;
24
+ }
25
+
26
+ /**
27
+ * `2026-11-07` -> `Friday the seventh`; the month is added only when it is not
28
+ * the month of `today` (`Friday the thirtieth of October`).
29
+ */
30
+ export function speakDate(isoDate: string, today: string): string {
31
+ const [y, m, d] = isoDate.split('-').map(Number);
32
+ const weekday = WEEKDAYS[new Date(Date.UTC(y, m - 1, d)).getUTCDay()];
33
+ const sameMonth = isoDate.slice(0, 7) === today.slice(0, 7);
34
+ return `${weekday} the ${ordinal(d)}${sameMonth ? '' : ` of ${MONTHS[m - 1]}`}`;
35
+ }
36
+
37
+ /** Ticket-style codes (`LIN-123`) are never read out: spelled aloud they are noise. */
38
+ export const IDENTIFIER = /\b[A-Za-z]{2,10}-\d+\b/g;
39
+ const MARKDOWN = /[*_#`~<>|\\]|\[|\]|^\s*[-•>]\s/m;
40
+ const URL = /https?:\/\/|www\./i;
41
+ const NUMERIC_DATE = /\b\d{4}-\d{2}-\d{2}\b|\b\d{1,2}\/\d{1,2}(\/\d{2,4})?\b/;
42
+
43
+ /** True when `text` would sound wrong read aloud: markup, links, codes, numeric dates. */
44
+ export function isUnspeakable(text: string): boolean {
45
+ return MARKDOWN.test(text) || URL.test(text) || new RegExp(IDENTIFIER.source).test(text) || NUMERIC_DATE.test(text);
46
+ }
47
+
48
+ /** A title made speakable: markdown links keep their label, markup and codes go, whitespace collapses. */
49
+ export function speakable(text: string, maxWords = 14): string {
50
+ const words = text
51
+ .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
52
+ .replace(/https?:\/\/\S+|www\.\S+/gi, 'a link')
53
+ .replace(IDENTIFIER, '')
54
+ .replace(/[*_#`~<>|\\[\]]/g, '')
55
+ .replace(/^\s*[-•>]\s+/gm, '')
56
+ .replace(/\s+/g, ' ')
57
+ .trim()
58
+ .replace(/\s+([,.;:!?])/g, '$1')
59
+ .split(' ')
60
+ .filter(Boolean);
61
+ const cut = words.slice(0, maxWords).join(' ').replace(/[,.;:]+$/, '');
62
+ return cut;
63
+ }
64
+
65
+ export function wordCount(text: string): number {
66
+ return text.trim() ? text.trim().split(/\s+/).length : 0;
67
+ }
68
+
69
+ export function partOfDay(instant: number, timeZone: string): 'morning' | 'afternoon' | 'evening' {
70
+ const hour = Number(new Intl.DateTimeFormat('en-US', { timeZone, hour: 'numeric', hourCycle: 'h23' }).format(new Date(instant)));
71
+ if (hour < 12) return 'morning';
72
+ return hour < 17 ? 'afternoon' : 'evening';
73
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * The briefing's input and output. The input is STRUCTURAL: a to-do from the
3
+ * tenant (a `Commitment`) or a Linear-synced item both fit, so the composer needs
4
+ * no mapping layer and no import of either type.
5
+ */
6
+ export interface BriefingItem {
7
+ id: string;
8
+ title: string;
9
+ /** `open` | `in_progress` | `blocked` | `done` | `dropped`; other words are treated as open. */
10
+ status: string;
11
+ /** A date (`2026-11-05`) or a full ISO instant; the reader's zone decides which day an instant is. */
12
+ dueAt?: string | null;
13
+ /** 0 critical .. 4 backlog. Unset sorts last. */
14
+ priority?: number;
15
+ /** The member who owns it. Items without one are not anybody's briefing. */
16
+ ownerSub?: string;
17
+ /** The project (focus) it is filed under, by name. */
18
+ focusName?: string;
19
+ /** Linear's own state type when the item is synced (`started`, `completed`, `canceled`, ...). */
20
+ linearState?: string;
21
+ linearIdentifier?: string;
22
+ }
23
+
24
+ export type BriefingKind = 'overdue' | 'in_progress' | 'due_today';
25
+
26
+ export interface BriefingEntry {
27
+ id: string;
28
+ title: string;
29
+ kind: BriefingKind;
30
+ /** Project name, or `Personal`. */
31
+ group: string;
32
+ dueDate: string | null;
33
+ priority?: number;
34
+ linearIdentifier?: string;
35
+ }
36
+
37
+ export interface BriefingOptions {
38
+ ownerSub: string;
39
+ now: number;
40
+ /** IANA zone of the person hearing it. Default UTC. */
41
+ timeZone?: string;
42
+ /** Items spoken before "and N more". Default 8. */
43
+ maxItems?: number;
44
+ }
45
+
46
+ /** What a voice reply is resolved against: the spoken order, and the day it was composed for. */
47
+ export interface BriefingContext {
48
+ itemIds: string[];
49
+ localDate: string;
50
+ timeZone: string;
51
+ }
52
+
53
+ export interface Briefing {
54
+ items: BriefingEntry[];
55
+ /** Eligible items beyond the spoken ones. */
56
+ remaining: number;
57
+ /** All eligible items. */
58
+ total: number;
59
+ counts: Record<BriefingKind, number>;
60
+ empty: boolean;
61
+ context: BriefingContext;
62
+ }
@@ -272,3 +272,6 @@ export type {
272
272
  AttrValue, CountGroup, CountQuery, CountRow, EntityFilters, EntityOrder, EntityPage, EntityQuery, FacetQuery, FilterReport,
273
273
  FilterVerdict, RelationshipListQuery,
274
274
  } from './entity-query';
275
+
276
+ // Daily briefing: what is on one person's plate today (bd startsim-kgkp1).
277
+ export * from './briefing';
package/src/corpus/llm.ts CHANGED
@@ -648,3 +648,5 @@ export function createVoiceTranscriber(
648
648
  },
649
649
  };
650
650
  }
651
+
652
+ export { createBriefingScriptLlm } from './briefing/llm';