@startsimpli/integrations 0.2.150 → 0.2.152

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.
Files changed (36) hide show
  1. package/package.json +7 -7
  2. package/src/__tests__/briefing-script.test.ts +26 -0
  3. package/src/__tests__/helpers/question-tenant.ts +45 -0
  4. package/src/__tests__/question-checkin.test.ts +139 -0
  5. package/src/__tests__/question-learn.test.ts +124 -0
  6. package/src/__tests__/question-voice-parse.test.ts +110 -0
  7. package/src/__tests__/question-voice.test.ts +225 -0
  8. package/src/__tests__/tracker-done-stamp.test.ts +42 -0
  9. package/src/__tests__/tracker-timeline-component.test.tsx +81 -0
  10. package/src/__tests__/tracker-timeline-reader.test.ts +94 -0
  11. package/src/__tests__/tracker-timeline.test.ts +209 -0
  12. package/src/__tests__/voice-due-inherited.test.ts +37 -0
  13. package/src/components/pages/TrackerPage.tsx +8 -0
  14. package/src/components/pages/tracker/TrackerTimeline.tsx +123 -0
  15. package/src/corpus/briefing/cache-key.ts +2 -2
  16. package/src/corpus/briefing/generate.ts +5 -1
  17. package/src/corpus/briefing/script.ts +12 -3
  18. package/src/corpus/briefing/speak.ts +8 -0
  19. package/src/corpus/briefing/types.ts +2 -0
  20. package/src/corpus/client.ts +12 -1
  21. package/src/corpus/questions/answer.ts +11 -1
  22. package/src/corpus/questions/checkin-handle.ts +67 -0
  23. package/src/corpus/questions/checkin.ts +103 -0
  24. package/src/corpus/questions/index.ts +11 -0
  25. package/src/corpus/questions/learn.ts +135 -0
  26. package/src/corpus/questions/respond.ts +76 -0
  27. package/src/corpus/questions/store.ts +5 -1
  28. package/src/corpus/questions/sync.ts +20 -3
  29. package/src/corpus/questions/types.ts +10 -2
  30. package/src/corpus/questions/voice-parse.ts +98 -0
  31. package/src/corpus/questions/voice.ts +227 -0
  32. package/src/corpus/tracker-timeline-client.ts +117 -0
  33. package/src/corpus/tracker-timeline.ts +228 -0
  34. package/src/corpus/types.ts +10 -0
  35. package/src/corpus/voice-due.ts +29 -4
  36. package/src/corpus/work-item-logic.ts +1 -1
@@ -0,0 +1,135 @@
1
+ /**
2
+ * LEARN FROM ANSWERS, AND USE WHAT WAS LEARNED BEFORE ASKING (bd startsim-tmrvi.6, tmrvi.2).
3
+ *
4
+ * Every answer is evidence. Words in a to-do's title that keep going to one project become a habit
5
+ * ("newsletter" -> Marketing after two alike); so does the usual due date (today, tomorrow, none) after
6
+ * three alike. A habit that AGREES with the guess Tandem is already acting on settles the question without
7
+ * asking, and the row says what decided it. A habit that disagrees, or none at all, still asks: nothing
8
+ * learned ever changes an item by itself.
9
+ */
10
+ import type { CorpusHttp } from '../client';
11
+ import type { TenantEntity } from '../entities';
12
+ import { addDays, isIsoDate } from '../briefing/intent/dates';
13
+ import { contentWords } from '../briefing/intent/match';
14
+ import { localDate } from '../today';
15
+ import type { CorpusScope } from '../types';
16
+ import type { QuestionAnswer, QuestionKind } from './types';
17
+
18
+ export const PREFERENCE_TYPE = 'assistant_preference';
19
+ export const PREFERENCE_LABEL = 'Assistant preference';
20
+ export const PREFERENCE_ATTRIBUTES: Array<[string, string]> = [
21
+ ['kind', 'text'], ['key', 'text'], ['value', 'text'], ['count', 'integer'], ['conflicts', 'integer'],
22
+ ['owner_sub', 'text'], ['updated_at', 'date'],
23
+ ];
24
+
25
+ export type PreferenceKind = 'project_word' | 'due_offset';
26
+ /** Alike answers needed before a habit is trusted. */
27
+ const NEEDED: Record<PreferenceKind, number> = { project_word: 2, due_offset: 3 };
28
+ const MAX_WORDS = 6;
29
+ const ENTITIES = 'api/v1/entities';
30
+
31
+ export interface Evidence { value: string; count: number; conflicts: number }
32
+ export interface Preference extends Evidence { kind: PreferenceKind; key: string }
33
+
34
+ /** One more answer: agreement builds a habit, disagreement erodes it, a winning newcomer replaces it. */
35
+ export function nextEvidence(prev: Evidence | undefined, value: string): Evidence {
36
+ if (!prev) return { value, count: 1, conflicts: 0 };
37
+ if (prev.value === value) return { ...prev, count: prev.count + 1 };
38
+ const conflicts = prev.conflicts + 1;
39
+ return conflicts > prev.count ? { value, count: conflicts, conflicts: prev.count } : { ...prev, conflicts };
40
+ }
41
+
42
+ export interface LearnDeps {
43
+ http: CorpusHttp;
44
+ scope: CorpusScope;
45
+ ownerSub: string;
46
+ entitiesPath?: string;
47
+ now?: () => number;
48
+ timeZone?: string;
49
+ }
50
+
51
+ const text = (v: unknown) => (typeof v === 'string' ? v : v == null ? '' : String(v));
52
+ const externalId = (owner: string, kind: string, key: string) => `pref:${owner}:${kind}:${key}`;
53
+
54
+ export function createPreferenceStore(deps: LearnDeps) {
55
+ const path = deps.entitiesPath ?? ENTITIES;
56
+ async function all(): Promise<Preference[]> {
57
+ const out: Preference[] = [];
58
+ for (let page = 1; page <= 20; page += 1) {
59
+ const res = await deps.http.get<{ results?: TenantEntity[]; next?: string | null }>(path, { params: { type: PREFERENCE_TYPE, page, page_size: 200 } });
60
+ for (const row of res.results ?? []) {
61
+ const d = (row.data ?? {}) as Record<string, unknown>;
62
+ if (text(d.owner_sub) !== deps.ownerSub) continue;
63
+ out.push({ kind: text(d.kind) as PreferenceKind, key: text(d.key), value: text(d.value), count: Number(d.count) || 0, conflicts: Number(d.conflicts) || 0 });
64
+ }
65
+ if (!res.next || !(res.results ?? []).length) break;
66
+ }
67
+ return out;
68
+ }
69
+ return {
70
+ all,
71
+ async confident(kind: PreferenceKind, key: string): Promise<Preference | null> {
72
+ return confidentIn(await all(), kind, key);
73
+ },
74
+ async record(kind: PreferenceKind, key: string, value: string, existing?: Preference): Promise<void> {
75
+ if (!deps.http.post) return;
76
+ const e = nextEvidence(existing, value);
77
+ await deps.http.post(`${path}/upsert`, {
78
+ entity_type: PREFERENCE_TYPE, external_id: externalId(deps.ownerSub, kind, key), name: `${kind}: ${key}`,
79
+ data: { kind, key, value: e.value, count: e.count, conflicts: e.conflicts, owner_sub: deps.ownerSub, updated_at: new Date((deps.now ?? Date.now)()).toISOString() },
80
+ });
81
+ },
82
+ };
83
+ }
84
+
85
+ export function confidentIn(prefs: Preference[], kind: PreferenceKind, key: string): Preference | null {
86
+ const p = prefs.find((x) => x.kind === kind && x.key === key);
87
+ return p && p.conflicts === 0 && p.count >= NEEDED[kind] ? p : null;
88
+ }
89
+
90
+ export const titleWords = (title: string): string[] => [...new Set(contentWords(title).filter((w) => w.length >= 4))].slice(0, MAX_WORDS);
91
+
92
+ /** A due date as the habit it shows: days from today (`0`, `1`, ...), or `later` for none. */
93
+ export function dueOffset(value: string | null | undefined, now: number, timeZone: string): string | null {
94
+ if (value === '' || value === null || value === undefined) return value === '' ? 'later' : null;
95
+ const day = value.slice(0, 10);
96
+ if (!isIsoDate(day)) return null;
97
+ const today = localDate(now, timeZone);
98
+ let n = 0;
99
+ for (let cursor = today; cursor < day && n < 400; n += 1) cursor = addDays(cursor, 1);
100
+ return day < today ? null : String(n);
101
+ }
102
+
103
+ export async function learnFromAnswer(
104
+ deps: LearnDeps,
105
+ input: { kind: QuestionKind; title: string; answer: QuestionAnswer },
106
+ ): Promise<void> {
107
+ const store = createPreferenceStore(deps);
108
+ const prefs = await store.all();
109
+ const find = (kind: PreferenceKind, key: string) => prefs.find((p) => p.kind === kind && p.key === key);
110
+ if (input.kind === 'project' && input.answer.value) {
111
+ for (const word of titleWords(input.title)) await store.record('project_word', word, input.answer.value, find('project_word', word));
112
+ } else if (input.kind === 'due_date') {
113
+ const offset = dueOffset(input.answer.value, (deps.now ?? Date.now)(), deps.timeZone ?? 'UTC');
114
+ if (offset) await store.record('due_offset', 'default', offset, find('due_offset', 'default'));
115
+ }
116
+ }
117
+
118
+ /** What a learned habit says about a guess: `agrees` settles the question; otherwise it is asked as before. */
119
+ export function decideFromHabits(
120
+ input: { kind: QuestionKind; title: string; assumed?: { value: string | null } },
121
+ prefs: Preference[], now: number, timeZone: string,
122
+ ): { agrees: true; evidence: string } | null {
123
+ const assumed = input.assumed?.value;
124
+ if (!assumed) return null;
125
+ if (input.kind === 'project') {
126
+ for (const word of titleWords(input.title)) {
127
+ const p = confidentIn(prefs, 'project_word', word);
128
+ if (p?.value === assumed) return { agrees: true, evidence: `${word} -> ${assumed} (${p.count} alike)` };
129
+ }
130
+ } else if (input.kind === 'due_date') {
131
+ const p = confidentIn(prefs, 'due_offset', 'default');
132
+ if (p && dueOffset(assumed, now, timeZone) === p.value) return { agrees: true, evidence: `usual due date ${p.value} (${p.count} alike)` };
133
+ }
134
+ return null;
135
+ }
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Fetch-`Response` wrappers for the tenant frontend's route files (bd startsim-tmrvi.5):
3
+ * POST /corpus/questions/answer JSON {clientActionId, utterance?, questionId?} or multipart with `audio`
4
+ * GET /corpus/questions/audio/<id> the spoken reply to one press, to its owner only
5
+ */
6
+ import { voiceErrorResponse } from '../voice-manage';
7
+ import { isTimeZone } from '../spoken-time';
8
+ import { emptyLog } from '../briefing/actions/log';
9
+ import type { ActionLogStore } from '../briefing/actions/types';
10
+ import {
11
+ CLIENT_ACTION_ID, MAX_ANSWER_AUDIO_BYTES, VoiceAnswerError, answerQuestionByVoice,
12
+ type VoiceAnswerDeps, type VoiceAnswerRequest,
13
+ } from './voice';
14
+
15
+ const str = (v: unknown): string | undefined => (typeof v === 'string' && v ? v : undefined);
16
+
17
+ async function parse(request: Request): Promise<VoiceAnswerRequest> {
18
+ const type = request.headers.get('content-type') ?? '';
19
+ let fields: Record<string, unknown>;
20
+ let audio: VoiceAnswerRequest['audio'];
21
+ if (type.includes('multipart/form-data')) {
22
+ // Typed by what is used: the native build has no DOM lib, so `FormData`'s methods are not declared there.
23
+ const form = (await request.formData().catch(() => { throw new VoiceAnswerError('Send the answer as multipart form data or JSON.', 400); })) as unknown as {
24
+ entries(): Iterable<[string, unknown]>;
25
+ get(name: string): unknown;
26
+ };
27
+ fields = Object.fromEntries([...form.entries()].filter(([, v]) => typeof v === 'string'));
28
+ const file = form.get('audio');
29
+ if (file instanceof Blob && file.size > 0) {
30
+ if (file.size > MAX_ANSWER_AUDIO_BYTES) throw new VoiceAnswerError('That recording is too long for an answer.', 413);
31
+ audio = { audio: new Uint8Array(await file.arrayBuffer()), mimeType: file.type || 'audio/mp4' };
32
+ }
33
+ } else {
34
+ try { fields = JSON.parse((await request.text()) || '{}'); } catch { throw new VoiceAnswerError('Send JSON, or multipart with the recording.', 400); }
35
+ if (!fields || typeof fields !== 'object') throw new VoiceAnswerError('Send JSON, or multipart with the recording.', 400);
36
+ }
37
+ const zone = str(fields.timeZone);
38
+ return {
39
+ clientActionId: str(fields.clientActionId) ?? '',
40
+ ...(str(fields.questionId) ? { questionId: str(fields.questionId) } : {}),
41
+ ...(typeof fields.utterance === 'string' ? { utterance: fields.utterance } : {}),
42
+ ...(audio ? { audio } : {}),
43
+ ...(zone && isTimeZone(zone) ? { timeZone: zone } : {}),
44
+ };
45
+ }
46
+
47
+ const failure = (error: unknown) => {
48
+ if (error instanceof VoiceAnswerError) return Response.json({ detail: error.message, ...(error.code ? { code: error.code } : {}) }, { status: error.status });
49
+ return voiceErrorResponse(error);
50
+ };
51
+
52
+ export async function questionAnswerResponse(request: Request, deps: VoiceAnswerDeps): Promise<Response> {
53
+ try {
54
+ return Response.json(await answerQuestionByVoice(deps, await parse(request)));
55
+ } catch (error) {
56
+ return failure(error);
57
+ }
58
+ }
59
+
60
+ /** The spoken reply to one press. The log is the caller's own, so anyone else's id is a 404. */
61
+ export async function questionAnswerAudioResponse(
62
+ clientActionId: string,
63
+ deps: { log: ActionLogStore; audio: { get(ref: string): Promise<{ audio: Uint8Array; mimeType: string }> } },
64
+ ): Promise<Response> {
65
+ const notFound = () => Response.json({ detail: 'Not found.' }, { status: 404 });
66
+ if (!CLIENT_ACTION_ID.test(clientActionId)) return notFound();
67
+ try {
68
+ const log = await deps.log.load().catch(() => emptyLog());
69
+ const ref = (log.pending ?? []).find((p) => p.id === clientActionId)?.confirmAudio;
70
+ if (!ref) return notFound();
71
+ const { audio, mimeType } = await deps.audio.get(ref.ref);
72
+ return new Response(audio as BodyInit, { headers: { 'content-type': mimeType, 'cache-control': 'private, max-age=300', 'content-length': String(audio.byteLength) } });
73
+ } catch (error) {
74
+ return failure(error);
75
+ }
76
+ }
@@ -3,7 +3,7 @@ import type { CorpusHttp } from '../client';
3
3
  import type { TenantEntity } from '../entities';
4
4
  import {
5
5
  OPEN_QUESTION_TYPE,
6
- type AssumedValue, type OpenQuestion, type QuestionCandidate, type QuestionKind,
6
+ type AssumedValue, type OpenQuestion, type QuestionAnswer, type QuestionCandidate, type QuestionKind,
7
7
  type QuestionResolution, type QuestionStatus,
8
8
  } from './types';
9
9
 
@@ -34,6 +34,8 @@ export function toQuestion(entity: TenantEntity): OpenQuestion {
34
34
  const resolvedAt = str(pick(d, 'resolved_at', 'resolvedAt'));
35
35
  const resolution = str(d.resolution);
36
36
  const noteId = str(pick(d, 'note_id', 'noteId'));
37
+ const answer = json<QuestionAnswer | null>(d.answer, null);
38
+ const snoozedUntil = str(pick(d, 'snoozed_until', 'snoozedUntil'));
37
39
  return {
38
40
  id: String(entity.id),
39
41
  itemId: str(pick(d, 'item_id', 'itemId')),
@@ -46,6 +48,8 @@ export function toQuestion(entity: TenantEntity): OpenQuestion {
46
48
  ownerSub: str(pick(d, 'owner_sub', 'ownerSub')),
47
49
  ...(noteId ? { noteId } : {}),
48
50
  ...(resolution ? { resolution: resolution as QuestionResolution } : {}),
51
+ ...(answer && typeof answer === 'object' ? { answer } : {}),
52
+ ...(snoozedUntil ? { snoozedUntil } : {}),
49
53
  createdAt: str(pick(d, 'created_at', 'createdAt')),
50
54
  updatedAt: str(pick(d, 'updated_at', 'updatedAt')),
51
55
  ...(resolvedAt ? { resolvedAt } : {}),
@@ -6,6 +6,7 @@ import type { CorpusHttp } from '../client';
6
6
  import type { CorpusScope } from '../types';
7
7
  import { CLOSED_STATUSES, deriveQuestions, scoreOf } from './derive';
8
8
  import { readItemViews, readVoiceRecords } from './items';
9
+ import { createPreferenceStore, decideFromHabits } from './learn';
9
10
  import { createQuestionStore } from './store';
10
11
  import type { ItemView, OpenQuestion, QuestionResolution } from './types';
11
12
 
@@ -16,6 +17,8 @@ export interface QuestionDeps {
16
17
  ownerSub: string;
17
18
  entitiesPath?: string;
18
19
  now?: () => number;
20
+ /** The listener's zone: "today" in a habit is theirs. */
21
+ timeZone?: string;
19
22
  }
20
23
 
21
24
  const ENTITIES = 'api/v1/entities';
@@ -24,7 +27,7 @@ const key = (itemId: string, kind: string) => `${itemId}:${kind}`;
24
27
  export const storeFor = (deps: QuestionDeps) =>
25
28
  createQuestionStore({ http: deps.http, ownerSub: deps.ownerSub, entitiesPath: deps.entitiesPath ?? ENTITIES });
26
29
 
27
- export async function syncOpenQuestions(deps: QuestionDeps): Promise<{ opened: number; resolved: number; expired: number }> {
30
+ export async function syncOpenQuestions(deps: QuestionDeps): Promise<{ opened: number; resolved: number; expired: number; decidedByContext: number }> {
28
31
  const path = deps.entitiesPath ?? ENTITIES;
29
32
  const iso = () => new Date((deps.now ?? Date.now)()).toISOString();
30
33
  const store = storeFor(deps);
@@ -36,7 +39,8 @@ export async function syncOpenQuestions(deps: QuestionDeps): Promise<{ opened: n
36
39
  const derived = deriveQuestions(items, notes);
37
40
  const existing = new Map((await store.all()).map((q) => [key(q.itemId, q.kind), q]));
38
41
 
39
- let opened = 0, resolved = 0, expired = 0;
42
+ const prefs = await createPreferenceStore(deps).all().catch(() => []);
43
+ let opened = 0, resolved = 0, expired = 0, decidedByContext = 0;
40
44
  const wanted = new Set<string>();
41
45
 
42
46
  for (const d of derived) {
@@ -50,11 +54,24 @@ export async function syncOpenQuestions(deps: QuestionDeps): Promise<{ opened: n
50
54
  candidates: JSON.stringify(d.candidates),
51
55
  ...(d.noteId ? { note_id: d.noteId } : {}),
52
56
  };
57
+ if (!have && d.assumed) {
58
+ // Context first: a learned habit that agrees with the guess settles it, and the row says why.
59
+ const hit = decideFromHabits({ kind: d.kind, title: byId.get(d.itemId)?.title ?? '', assumed: d.assumed }, prefs, (deps.now ?? Date.now)(), deps.timeZone ?? 'UTC');
60
+ if (hit) {
61
+ await store.put(d.itemId, d.kind, d.question, {
62
+ ...body, status: 'resolved', resolution: 'context', resolved_at: iso(), created_at: iso(), updated_at: iso(),
63
+ answer: JSON.stringify({ value: d.assumed.value ?? '', label: `learned: ${hit.evidence}` }),
64
+ });
65
+ decidedByContext += 1;
66
+ continue;
67
+ }
68
+ }
53
69
  if (!have) {
54
70
  await store.put(d.itemId, d.kind, d.question, { ...body, status: 'open', created_at: iso(), updated_at: iso() });
55
71
  opened += 1;
56
72
  } else if (have.status !== 'open') {
57
73
  if (!d.reopens) continue;
74
+ if (have.snoozedUntil && have.snoozedUntil > iso()) continue; // skipped for now
58
75
  await store.put(d.itemId, d.kind, d.question, { ...body, status: 'open', resolution: '', resolved_at: '', created_at: iso(), updated_at: iso() });
59
76
  opened += 1;
60
77
  } else if (have.question !== d.question || have.score !== score) {
@@ -69,7 +86,7 @@ export async function syncOpenQuestions(deps: QuestionDeps): Promise<{ opened: n
69
86
  await close(store, q, item ? (resolution === 'item_closed' ? 'expired' : 'resolved') : 'expired', resolution, iso());
70
87
  if (resolution === 'item_changed') resolved += 1; else expired += 1;
71
88
  }
72
- return { opened, resolved, expired };
89
+ return { opened, resolved, expired, decidedByContext };
73
90
  }
74
91
 
75
92
  export async function close(
@@ -13,7 +13,7 @@ export type QuestionKind = (typeof QUESTION_KINDS)[number];
13
13
  export type QuestionStatus = 'open' | 'resolved' | 'expired';
14
14
 
15
15
  /** Why a question left the queue. */
16
- export type QuestionResolution = 'answered' | 'item_changed' | 'item_closed' | 'item_gone';
16
+ export type QuestionResolution = 'answered' | 'skipped' | 'context' | 'item_changed' | 'item_closed' | 'item_gone';
17
17
 
18
18
  export interface AssumedValue {
19
19
  value: string | null;
@@ -43,6 +43,10 @@ export interface OpenQuestion {
43
43
  ownerSub: string;
44
44
  noteId?: string;
45
45
  resolution?: QuestionResolution;
46
+ /** What it was answered with, once resolved by an answer. */
47
+ answer?: QuestionAnswer;
48
+ /** A skipped question is not asked again before this instant (ISO). */
49
+ snoozedUntil?: string;
46
50
  createdAt: string;
47
51
  updatedAt: string;
48
52
  resolvedAt?: string;
@@ -53,6 +57,10 @@ export interface QuestionAnswer {
53
57
  value: string;
54
58
  /** Human label for the value (an owner's name). */
55
59
  label?: string;
60
+ /** Set when the answer was spoken: the press that gave it, so a repeat press does nothing twice. */
61
+ via?: string;
62
+ /** What the item held before, so a spoken "undo" can put it back. */
63
+ prior?: { dueAt?: string | null };
56
64
  }
57
65
 
58
66
  /** What the queue needs to know about an item (from its commitment row). */
@@ -88,5 +96,5 @@ export const OPEN_QUESTION_ATTRIBUTES: Array<[string, string]> = [
88
96
  ['item_id', 'text'], ['kind', 'text'], ['question', 'text'], ['status', 'text'],
89
97
  ['assumed', 'text'], ['candidates', 'text'], ['answer', 'text'], ['score', 'integer'],
90
98
  ['owner_sub', 'text'], ['note_id', 'text'], ['resolution', 'text'],
91
- ['created_at', 'date'], ['updated_at', 'date'], ['resolved_at', 'date'],
99
+ ['created_at', 'date'], ['updated_at', 'date'], ['resolved_at', 'date'], ['snoozed_until', 'date'],
92
100
  ];
@@ -0,0 +1,98 @@
1
+ /**
2
+ * WHAT A SPOKEN ANSWER TO A CLARIFYING QUESTION MEANS (bd startsim-tmrvi.5).
3
+ *
4
+ * Its own small grammar, NOT the briefing reply grammar: there "skip" drops a
5
+ * to-do and "today" pulls one in, here "skip" leaves the question for later and
6
+ * "today" is the answer. A reply this cannot place becomes a short question back,
7
+ * never a guess and never an edit. Pure: no model, no storage.
8
+ */
9
+ import { normalizeSpeech, parseWhen, splitWhen } from '../briefing/intent/dates';
10
+ import { contentWords, matchItems } from '../briefing/intent/match';
11
+ import { speakable } from '../briefing/speak';
12
+ import type { OpenQuestion } from './types';
13
+
14
+ export interface AnswerOption { value: string; label: string }
15
+
16
+ export interface AnswerContext {
17
+ now: number;
18
+ timeZone: string;
19
+ /** The choices a project / team / owner answer may name, by label. */
20
+ options: AnswerOption[];
21
+ }
22
+
23
+ export type SpokenAnswer =
24
+ /** `value` is a date (or '' to clear it), or an option's value. `spoken` is how it is said back. */
25
+ | { kind: 'answer'; value: string; label?: string; spoken: string }
26
+ /** "Yes, keep it": take the guess as the answer. */
27
+ | { kind: 'accept' }
28
+ /** "Not now": leave it for later. */
29
+ | { kind: 'skip' }
30
+ | { kind: 'undo' }
31
+ | { kind: 'unclear'; question: string };
32
+
33
+ const UNDO = /^(?:undo|undo (?:that|it|the last(?: one| answer)?)|never ?mind|take (?:that|it) back|go back|scratch that|oops)$/;
34
+ const SKIP = /^(?:skip(?: it| this| that| this one| that one)?|not now|ask me (?:later|again|tomorrow)|pass|leave it|come back (?:to (?:it|this|that) )?later|maybe later|i (?:don't|do not) know(?: yet)?|no idea)$/;
35
+ const YES = /^(?:(?:yes|yeah|yep|yup|sure|ok|okay)[,\s]+)?(?:yes|yeah|yep|yup|sure|correct|right|exactly|ok|okay|alright|that(?:'s| is) (?:right|correct|fine|good|it)|sounds (?:good|right)|looks (?:good|right)|keep (?:it|that|them)|go with (?:that|it)|that works|fine|good|do that)(?: please| thanks| thank you)?$/;
36
+ const LEAD = /^(?:(?:hey|um|uh|so|well|actually|please|oh|hmm|just|and|then)\b[,\s]*)+/;
37
+
38
+ const ORDINALS: Array<[RegExp, number]> = [
39
+ [/\b(?:first|1st|number one|option one)\b/, 0], [/\b(?:second|2nd|number two|option two)\b/, 1],
40
+ [/\b(?:third|3rd|number three|option three)\b/, 2], [/\b(?:fourth|4th|number four)\b/, 3],
41
+ ];
42
+
43
+ /** Words that frame a choice without naming it: "that's the marketing project". */
44
+ const CHOICE_FILLER = /\b(?:thats|that's|that is|its|it's|it is|project|team|space|folder|owner|goes|belongs|go|put|file|filed|under|in|into|for|to|with|assign|assigned|give|make)\b/g;
45
+
46
+ const unclear = (question: string): SpokenAnswer => ({ kind: 'unclear', question });
47
+ const orList = (labels: string[]) => (labels.length < 2 ? labels.join('') : `${labels.slice(0, -1).join(', ')} or ${labels[labels.length - 1]}`);
48
+
49
+ /** The options this question offered, best first, as the labels the person heard. */
50
+ export function offeredOptions(q: OpenQuestion, options: AnswerOption[]): AnswerOption[] {
51
+ const byValue = new Map(options.map((o) => [o.value, o]));
52
+ const offered = q.candidates.map((c) => byValue.get(c.value)).filter((o): o is AnswerOption => Boolean(o));
53
+ return offered.length ? offered : options.slice(0, 4);
54
+ }
55
+
56
+ function parseDate(q: OpenQuestion, text: string, ctx: AnswerContext): SpokenAnswer {
57
+ const whole = parseWhen(text, ctx.now, ctx.timeZone);
58
+ const part = whole ? null : splitWhen(text, ctx.now, ctx.timeZone);
59
+ // "make it Friday please": the date plus only filler around it.
60
+ const spare = part ? contentWords(part.rest).filter((w) => !['make', 'set', 'put', 'move', 'due', 'say', 'lets', "let's", 'let', 'be', 'it', 'is', 'would', 'will', 'can'].includes(w)) : [];
61
+ const when = whole ?? (part && spare.length === 0 ? part.when : null);
62
+ if (!when) return unclear(`${q.question} You can say a day, like tomorrow or next Friday, or skip it.`);
63
+ return { kind: 'answer', value: when.date ?? '', spoken: when.later ? 'no date' : when.label };
64
+ }
65
+
66
+ function parseChoice(q: OpenQuestion, text: string, ctx: AnswerContext): SpokenAnswer {
67
+ const offered = offeredOptions(q, ctx.options);
68
+ const pool = ctx.options.length ? ctx.options : offered;
69
+ const asItems = (os: AnswerOption[]) => os.map((o) => ({ id: o.value, title: o.label }));
70
+
71
+ const hit = (o: AnswerOption): SpokenAnswer => ({ kind: 'answer', value: o.value, label: o.label, spoken: o.label });
72
+ const byValue = new Map(pool.map((o) => [o.value, o]));
73
+
74
+ // By name first: "that's the marketing project", "operations".
75
+ const named = matchItems(text.replace(CHOICE_FILLER, ' '), asItems(pool));
76
+ if (named.kind === 'one') return hit(byValue.get(named.item.id) as AnswerOption);
77
+ if (named.kind === 'many') {
78
+ const labels = named.items.map((i) => i.title);
79
+ return unclear(`Which one: ${orList(labels)}?`);
80
+ }
81
+ // Then by position among what was just offered: "the second one".
82
+ const position = ORDINALS.find(([re]) => re.test(text));
83
+ if (position && offered[position[1]]) return hit(offered[position[1]]);
84
+
85
+ const shown = offered.slice(0, 3).map((o) => speakable(o.label, 6));
86
+ return unclear(shown.length ? `I did not catch which. Is it ${orList(shown)}?` : 'I did not catch that. Can you say it again?');
87
+ }
88
+
89
+ export function parseSpokenAnswer(q: OpenQuestion, utterance: string, ctx: AnswerContext): SpokenAnswer {
90
+ const text = normalizeSpeech(utterance).replace(LEAD, '').trim();
91
+ if (!text) return unclear('Sorry, I did not catch that. Can you say that again?');
92
+ if (UNDO.test(text)) return { kind: 'undo' };
93
+ if (SKIP.test(text)) return { kind: 'skip' };
94
+ if (YES.test(text)) {
95
+ return q.assumed?.value || q.assumed?.display ? { kind: 'accept' } : unclear(`I do not have a guess for that one. ${q.question}`);
96
+ }
97
+ return q.kind === 'due_date' ? parseDate(q, text, ctx) : parseChoice(q, text, ctx);
98
+ }