@startsimpli/integrations 0.2.149 → 0.2.151

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 (46) hide show
  1. package/package.json +3 -3
  2. package/src/__tests__/connection-check-reason.test.tsx +85 -0
  3. package/src/__tests__/focus-history.test.ts +90 -0
  4. package/src/__tests__/goal-rows.test.ts +51 -0
  5. package/src/__tests__/goals-page.test.tsx +124 -0
  6. package/src/__tests__/helpers/question-tenant.ts +45 -0
  7. package/src/__tests__/question-checkin.test.ts +139 -0
  8. package/src/__tests__/question-voice-parse.test.ts +110 -0
  9. package/src/__tests__/question-voice.test.ts +208 -0
  10. package/src/__tests__/stated-date-extract.test.ts +119 -0
  11. package/src/__tests__/stated-date.test.ts +107 -0
  12. package/src/__tests__/tracker-done-stamp.test.ts +42 -0
  13. package/src/__tests__/tracker-timeline-component.test.tsx +81 -0
  14. package/src/__tests__/tracker-timeline-reader.test.ts +94 -0
  15. package/src/__tests__/tracker-timeline.test.ts +209 -0
  16. package/src/components/index.ts +1 -0
  17. package/src/components/pages/PlanningPage.tsx +16 -2
  18. package/src/components/pages/TrackerPage.tsx +8 -0
  19. package/src/components/pages/connections/ConnectionCard.tsx +12 -0
  20. package/src/components/pages/connections/bound-api.ts +1 -1
  21. package/src/components/pages/goals/FocusProgressHistory.tsx +77 -0
  22. package/src/components/pages/goals/GoalsPage.tsx +186 -0
  23. package/src/components/pages/goals/index.ts +4 -0
  24. package/src/components/pages/tracker/TrackerTimeline.tsx +123 -0
  25. package/src/components/pages/types.ts +2 -2
  26. package/src/corpus/client.ts +27 -1
  27. package/src/corpus/commitments.ts +3 -1
  28. package/src/corpus/extract.ts +8 -6
  29. package/src/corpus/focus-history.ts +104 -0
  30. package/src/corpus/goal-rows.ts +29 -0
  31. package/src/corpus/index.ts +6 -0
  32. package/src/corpus/questions/checkin-handle.ts +67 -0
  33. package/src/corpus/questions/checkin.ts +103 -0
  34. package/src/corpus/questions/index.ts +9 -0
  35. package/src/corpus/questions/respond.ts +76 -0
  36. package/src/corpus/questions/store.ts +5 -1
  37. package/src/corpus/questions/sync.ts +1 -0
  38. package/src/corpus/questions/types.ts +10 -2
  39. package/src/corpus/questions/voice-parse.ts +98 -0
  40. package/src/corpus/questions/voice.ts +225 -0
  41. package/src/corpus/spoken-time.ts +4 -4
  42. package/src/corpus/stated-date.ts +187 -0
  43. package/src/corpus/tracker-timeline-client.ts +117 -0
  44. package/src/corpus/tracker-timeline.ts +228 -0
  45. package/src/corpus/types.ts +25 -1
  46. package/src/corpus/work-item-logic.ts +1 -1
@@ -0,0 +1,67 @@
1
+ /**
2
+ * GET /corpus/questions/checkin (bd startsim-tmrvi.4): the open questions as a spoken check-in plus the card data.
3
+ * The same text is only synthesized once: the press id is a hash of it, and its audio is served by the
4
+ * spoken-answer audio route from the person's own log.
5
+ */
6
+ import { speakConfirmation } from '../briefing/actions/confirm';
7
+ import { composeCheckIn, type CheckIn } from './checkin';
8
+ import { listOpenQuestions, syncOpenQuestions } from './sync';
9
+ import type { VoiceAnswerDeps } from './voice';
10
+
11
+ /** Two 32-bit FNV-style passes: stable, dependency-free (the native bundle has no node:crypto). */
12
+ function hashOf(text: string): string {
13
+ let a = 0x811c9dc5, b = 0x01000193;
14
+ for (let i = 0; i < text.length; i += 1) {
15
+ a = Math.imul(a ^ text.charCodeAt(i), 0x01000193) >>> 0;
16
+ b = Math.imul(b + text.charCodeAt(i), 0x85ebca6b) >>> 0;
17
+ }
18
+ return a.toString(16).padStart(8, '0') + b.toString(16).padStart(8, '0') + text.length.toString(16);
19
+ }
20
+
21
+ export interface CheckInResult extends CheckIn {
22
+ audioUrl: string | null;
23
+ mimeType?: string;
24
+ /** The first question's id: what the app sends back as `questionId`, so the answer lands on what was just read. */
25
+ firstQuestionId: string | null;
26
+ }
27
+
28
+ export async function buildCheckIn(deps: VoiceAnswerDeps, options: { sync?: boolean; timeZone?: string } = {}): Promise<CheckInResult> {
29
+ if (options.sync !== false) await syncOpenQuestions(deps);
30
+ const open = await listOpenQuestions(deps);
31
+ const titles = new Map<string, string>();
32
+ await Promise.all(open.slice(0, 12).map(async (q) => {
33
+ const item = await deps.seam.load(q.itemId).catch(() => null);
34
+ if (item) titles.set(q.itemId, item.title);
35
+ }));
36
+ // A guess is stored as an id (a project, a team): say its name, not the id.
37
+ const named = await Promise.all(open.slice(0, 12).map(async (q) => {
38
+ const value = q.assumed?.value;
39
+ if (!q.assumed || !value || q.assumed.display || q.kind === 'due_date') return q;
40
+ const label = (await deps.options(q).catch(() => [])).find((o) => o.value === value)?.label;
41
+ return label ? { ...q, assumed: { ...q.assumed, display: label } } : q;
42
+ }));
43
+ const now = (deps.now ?? Date.now)();
44
+ const checkIn = composeCheckIn([...named, ...open.slice(12)], { titles, now, timeZone: options.timeZone ?? deps.timeZone });
45
+ const base = { ...checkIn, audioUrl: null as string | null, firstQuestionId: checkIn.entries[0]?.questionId ?? null };
46
+ if (checkIn.empty || !deps.synthesize || !deps.audio || !deps.audioPath) return base;
47
+
48
+ const id = `checkin-${hashOf(checkIn.text)}`;
49
+ const log = await deps.log.load();
50
+ const seen = (log.pending ?? []).find((p) => p.id === id && p.confirmAudio);
51
+ if (seen?.confirmAudio) return { ...base, audioUrl: deps.audioPath(id), mimeType: seen.confirmAudio.mimeType };
52
+
53
+ let audioRef = '';
54
+ const said = await speakConfirmation({
55
+ text: checkIn.text, clientActionId: id, synthesize: deps.synthesize,
56
+ audio: { put: deps.audio.put, url: async (ref) => { audioRef = ref; return (deps.audioPath as (i: string) => string)(id); } },
57
+ });
58
+ if (said.audioUrl && audioRef) {
59
+ const fresh = await deps.log.load();
60
+ fresh.pending = [...(fresh.pending ?? []).filter((p) => p.id !== id), {
61
+ id, utterance: '', understood: checkIn.text, actions: [{ type: 'none' as const }], source: 'grammar' as const, confidence: 1,
62
+ at: new Date(now).toISOString(), confirmAudio: { ref: audioRef, mimeType: said.mimeType ?? 'audio/mpeg' },
63
+ }].slice(-12);
64
+ await deps.log.save(fresh);
65
+ }
66
+ return { ...base, audioUrl: said.audioUrl, ...(said.mimeType ? { mimeType: said.mimeType } : {}) };
67
+ }
@@ -0,0 +1,103 @@
1
+ /**
2
+ * THE CHECK-IN (bd startsim-tmrvi.4): "there are N things I am unsure about", composed like the morning
3
+ * briefing: PURE, our words around the person's own (speakable) titles, offsets recorded per question so a
4
+ * reply made while one is being read resolves to it. Most important first, each with the guess Tandem is
5
+ * acting on, so a plain "yes" is a complete answer.
6
+ */
7
+ import { dueDay } from '../today';
8
+ import { speakCount, speakDate, speakable, wordCount } from '../briefing/speak';
9
+ import type { ScriptSegment } from '../briefing/script';
10
+ import type { OpenQuestion } from './types';
11
+
12
+ const DEFAULT_MAX = 5;
13
+ const ORDINALS = ['First', 'Second', 'Third', 'Fourth', 'Fifth'];
14
+
15
+ export interface CheckInEntry {
16
+ questionId: string;
17
+ itemId: string;
18
+ kind: OpenQuestion['kind'];
19
+ title: string;
20
+ /** The question as asked. */
21
+ question: string;
22
+ /** The guess Tandem is acting on, as it is said; null when there is none. */
23
+ guess: string | null;
24
+ }
25
+
26
+ export interface CheckIn {
27
+ entries: CheckInEntry[];
28
+ total: number;
29
+ remaining: number;
30
+ empty: boolean;
31
+ text: string;
32
+ segments: ScriptSegment[];
33
+ words: number;
34
+ }
35
+
36
+ export interface CheckInOptions {
37
+ /** item id -> its title. */
38
+ titles: ReadonlyMap<string, string>;
39
+ now: number;
40
+ timeZone?: string;
41
+ maxItems?: number;
42
+ }
43
+
44
+ function guessOf(q: OpenQuestion, today: string, timeZone: string): string | null {
45
+ const a = q.assumed;
46
+ if (!a || (!a.value && !a.display)) return null;
47
+ if (q.kind === 'due_date') {
48
+ const day = dueDay(a.value, timeZone);
49
+ return day ? speakDate(day, today) : null;
50
+ }
51
+ // An id with no name is not worth saying aloud: ask without a guess.
52
+ const said = speakable(a.display ?? '', 6);
53
+ return said || null;
54
+ }
55
+
56
+ function lineFor(q: OpenQuestion, title: string, guess: string | null): string {
57
+ const name = speakable(title, 8) || 'This one';
58
+ switch (q.kind) {
59
+ case 'due_date':
60
+ return guess ? `${name}: I put it down for ${guess}. Is that right?` : `${name}: when is it due?`;
61
+ case 'project':
62
+ return guess ? `${name}: I filed it under ${guess}. Is that right?` : `${name}: which project is it for?`;
63
+ case 'ownership':
64
+ return guess ? `${name}: I assumed ${guess} owns it. Is that right?` : `${name}: who owns it?`;
65
+ case 'team':
66
+ return `${name}: which team is it for?`;
67
+ case 'private_space':
68
+ return 'Where should your personal to-dos go? I need a private team for them.';
69
+ }
70
+ }
71
+
72
+ export function composeCheckIn(questions: OpenQuestion[], options: CheckInOptions): CheckIn {
73
+ const timeZone = options.timeZone ?? 'UTC';
74
+ const today = new Date(options.now).toLocaleDateString('en-CA', { timeZone });
75
+ const max = options.maxItems ?? DEFAULT_MAX;
76
+ const open = questions.filter((q) => q.status === 'open').sort((a, b) => b.score - a.score || a.id.localeCompare(b.id));
77
+ if (!open.length) return { entries: [], total: 0, remaining: 0, empty: true, text: '', segments: [], words: 0 };
78
+
79
+ const shown = open.slice(0, max);
80
+ const entries: CheckInEntry[] = shown.map((q) => ({
81
+ questionId: q.id, itemId: q.itemId, kind: q.kind, title: options.titles.get(q.itemId) ?? '', question: q.question,
82
+ guess: guessOf(q, today, timeZone),
83
+ }));
84
+
85
+ let text = '';
86
+ const segments: ScriptSegment[] = [];
87
+ const add = (piece: string, id: string | null) => {
88
+ if (text) text += ' ';
89
+ const start = text.length;
90
+ text += piece;
91
+ segments.push({ id, start, end: text.length });
92
+ };
93
+ const n = open.length;
94
+ add(`I am not sure about ${speakCount(n)} ${n === 1 ? 'thing' : 'things'}.`, null);
95
+ shown.forEach((q, i) => {
96
+ const lead = n === 1 ? '' : `${ORDINALS[i]}, `;
97
+ const line = lineFor(q, entries[i].title, entries[i].guess);
98
+ add(`${lead}${line}`, q.id);
99
+ });
100
+ if (open.length > shown.length) add(`And ${speakCount(open.length - shown.length)} more after that.`, null);
101
+ add('Say yes to keep my guess, tell me the answer, or say skip.', null);
102
+ return { entries, total: n, remaining: open.length - shown.length, empty: false, text, segments, words: wordCount(text) };
103
+ }
@@ -12,3 +12,12 @@ export type {
12
12
  AssumedValue, DerivedQuestion, ItemView, OpenQuestion, QuestionAnswer, QuestionCandidate,
13
13
  QuestionKind, QuestionResolution, QuestionStatus,
14
14
  } from './types';
15
+ export { answerQuestionByVoice, validateAnswerRequest, VoiceAnswerError } from './voice';
16
+ export type { VoiceAnswerDeps, VoiceAnswerRequest, VoiceAnswerResult } from './voice';
17
+ export { parseSpokenAnswer, offeredOptions } from './voice-parse';
18
+ export type { AnswerContext, AnswerOption, SpokenAnswer } from './voice-parse';
19
+ export { questionAnswerResponse, questionAnswerAudioResponse } from './respond';
20
+ export { composeCheckIn } from './checkin';
21
+ export type { CheckIn, CheckInEntry, CheckInOptions } from './checkin';
22
+ export { buildCheckIn } from './checkin-handle';
23
+ export type { CheckInResult } from './checkin-handle';
@@ -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 } : {}),
@@ -55,6 +55,7 @@ export async function syncOpenQuestions(deps: QuestionDeps): Promise<{ opened: n
55
55
  opened += 1;
56
56
  } else if (have.status !== 'open') {
57
57
  if (!d.reopens) continue;
58
+ if (have.snoozedUntil && have.snoozedUntil > iso()) continue; // skipped for now
58
59
  await store.put(d.itemId, d.kind, d.question, { ...body, status: 'open', resolution: '', resolved_at: '', created_at: iso(), updated_at: iso() });
59
60
  opened += 1;
60
61
  } else if (have.question !== d.question || have.score !== score) {
@@ -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' | '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
+ }
@@ -0,0 +1,225 @@
1
+ /**
2
+ * ANSWER A CLARIFYING QUESTION BY VOICE, AND KEEP THE CONVERSATION GOING
3
+ * (bd startsim-tmrvi.5).
4
+ *
5
+ * words (transcribed if audio) -> which question (the one named, else the best open one)
6
+ * -> parse (its own grammar, `voice-parse`) -> apply through `answerQuestion`
7
+ * -> say it back AND ask the next question, so one press can lead to the next.
8
+ *
9
+ * Request-free like the briefing reply: a route, a worker and a test call the same thing.
10
+ * A repeat press (same `clientActionId`) is answered from the log; nothing runs twice.
11
+ */
12
+ import { speakConfirmation } from '../briefing/actions/confirm';
13
+ import type { ActionLog, ActionLogStore, PendingReply } from '../briefing/actions/types';
14
+ import type { BriefingAudio, BriefingSynthesize } from '../briefing/generate';
15
+ import { speakable } from '../briefing/speak';
16
+ import { answerQuestion, type AnswerDeps } from './answer';
17
+ import { close, listOpenQuestions, storeFor } from './sync';
18
+ import type { OpenQuestion, QuestionAnswer } from './types';
19
+ import { parseSpokenAnswer, type AnswerOption } from './voice-parse';
20
+
21
+ export const CLIENT_ACTION_ID = /^[A-Za-z0-9_-]{8,64}$/;
22
+ const SNOOZE_MS = 12 * 3_600_000;
23
+ const UNDO_WINDOW_MS = 30 * 60_000;
24
+ const PENDING_KEPT = 12;
25
+ export const MAX_ANSWER_AUDIO_BYTES = 10 * 1024 * 1024;
26
+
27
+ export class VoiceAnswerError extends Error {
28
+ constructor(message: string, readonly status: number, readonly code?: string) {
29
+ super(message);
30
+ this.name = 'VoiceAnswerError';
31
+ }
32
+ }
33
+
34
+ export interface VoiceAnswerDeps extends AnswerDeps {
35
+ /** The choices a project / team / owner answer may name. */
36
+ options(q: OpenQuestion): Promise<AnswerOption[]>;
37
+ log: ActionLogStore;
38
+ transcribe?: (input: { audio: Uint8Array; mimeType: string; hints: string[] }) => Promise<string>;
39
+ synthesize?: BriefingSynthesize;
40
+ audio?: Pick<BriefingAudio, 'put'>;
41
+ /** Where the spoken confirmation is fetched from, for this press. */
42
+ audioPath?: (clientActionId: string) => string;
43
+ timeZone?: string;
44
+ }
45
+
46
+ export interface VoiceAnswerRequest {
47
+ clientActionId: string;
48
+ /** The question being answered; omit to answer the best open one. */
49
+ questionId?: string;
50
+ utterance?: string;
51
+ audio?: { audio: Uint8Array; mimeType: string };
52
+ timeZone?: string;
53
+ }
54
+
55
+ export interface VoiceAnswerResult {
56
+ /** `clarify`: it asked back instead of acting. */
57
+ kind: 'answered' | 'accepted' | 'skipped' | 'undone' | 'clarify' | 'nothing';
58
+ clientActionId: string;
59
+ utterance: string;
60
+ /** The question this press answered (absent for `clarify` on nothing, `nothing`). */
61
+ question: OpenQuestion | null;
62
+ /** The next thing to ask, so the app can listen again with this id. */
63
+ next: OpenQuestion | null;
64
+ /** The sentence said back, including the next question. */
65
+ spoken: string;
66
+ audioUrl: string | null;
67
+ mimeType?: string;
68
+ /** Open questions still waiting. */
69
+ remaining: number;
70
+ replayed: boolean;
71
+ }
72
+
73
+ export function validateAnswerRequest(req: VoiceAnswerRequest): void {
74
+ if (!CLIENT_ACTION_ID.test(req.clientActionId ?? '')) {
75
+ throw new VoiceAnswerError('Send a clientActionId (8-64 letters, digits, - or _), fresh for each press.', 400);
76
+ }
77
+ if (req.utterance === undefined && !req.audio) throw new VoiceAnswerError('Send what was said: audio or an utterance.', 400);
78
+ if (req.audio && req.audio.audio.byteLength > MAX_ANSWER_AUDIO_BYTES) throw new VoiceAnswerError('That recording is too long for an answer.', 413);
79
+ }
80
+
81
+ const asks = (q: OpenQuestion, title: string) => {
82
+ const t = speakable(title, 10);
83
+ return t ? `About ${t}: ${q.question}` : q.question;
84
+ };
85
+
86
+ async function titleOf(deps: VoiceAnswerDeps, q: OpenQuestion): Promise<string> {
87
+ return (await deps.seam.load(q.itemId).catch(() => null))?.title ?? '';
88
+ }
89
+
90
+ function saidBack(q: OpenQuestion, title: string, a: { value: string; label?: string; spoken: string }): string {
91
+ const t = speakable(title, 8) || 'that one';
92
+ switch (q.kind) {
93
+ case 'due_date': return a.value ? `Got it, ${t} is due ${a.spoken}.` : `Got it, ${t} has no due date.`;
94
+ case 'project': return `Got it, ${t} goes under ${a.spoken}.`;
95
+ case 'team': return `Got it, ${t} goes to ${a.spoken}.`;
96
+ case 'ownership': return `Got it, ${t} is ${a.spoken}'s.`;
97
+ case 'private_space': return `Got it, ${a.spoken} is your private space.`;
98
+ }
99
+ }
100
+
101
+ async function recordPress(deps: VoiceAnswerDeps, entry: PendingReply) {
102
+ const log: ActionLog = await deps.log.load();
103
+ log.pending = [...(log.pending ?? []).filter((p) => p.id !== entry.id), entry].slice(-PENDING_KEPT);
104
+ await deps.log.save(log);
105
+ }
106
+
107
+ async function undoLast(deps: VoiceAnswerDeps, now: number): Promise<{ text: string; question: OpenQuestion | null }> {
108
+ const all = await storeFor(deps).all();
109
+ const last = all
110
+ .filter((q) => q.resolution === 'answered' && q.answer?.via && q.resolvedAt && now - Date.parse(q.resolvedAt) <= UNDO_WINDOW_MS)
111
+ .sort((a, b) => (b.resolvedAt ?? '').localeCompare(a.resolvedAt ?? ''))[0];
112
+ if (!last) return { text: 'There is nothing to undo.', question: null };
113
+ if (last.kind !== 'due_date' || !last.answer?.prior) {
114
+ return { text: 'I cannot undo that one by voice. You can change it on the item.', question: last };
115
+ }
116
+ const item = await deps.seam.load(last.itemId);
117
+ if (!item) return { text: 'That item is gone, so there is nothing to put back.', question: last };
118
+ await deps.seam.update(item, { dueAt: last.answer.prior.dueAt ?? null });
119
+ const at = new Date(now).toISOString();
120
+ const reopened = await storeFor(deps).put(last.itemId, last.kind, last.question, {
121
+ status: 'open', resolution: '', resolved_at: '', answer: '', updated_at: at,
122
+ });
123
+ return { text: `Undone. ${speakable(item.title, 8)} is back how it was.`, question: reopened };
124
+ }
125
+
126
+ export async function answerQuestionByVoice(deps: VoiceAnswerDeps, req: VoiceAnswerRequest): Promise<VoiceAnswerResult> {
127
+ validateAnswerRequest(req);
128
+ const now = (deps.now ?? Date.now)();
129
+ const id = req.clientActionId;
130
+ const timeZone = req.timeZone || deps.timeZone || 'UTC';
131
+ const store = storeFor(deps);
132
+
133
+ // Already handled: answer from the log.
134
+ const log = await deps.log.load();
135
+ const mine = (log.pending ?? []).find((p) => p.id === id);
136
+ const result = (over: Partial<VoiceAnswerResult> & Pick<VoiceAnswerResult, 'kind' | 'spoken'>, audio?: { audioUrl: string | null; mimeType?: string }): VoiceAnswerResult => ({
137
+ clientActionId: id, utterance: req.utterance ?? '', question: null, next: null, audioUrl: audio?.audioUrl ?? null,
138
+ ...(audio?.mimeType ? { mimeType: audio.mimeType } : {}), remaining: 0, replayed: false, ...over,
139
+ });
140
+ if (mine?.understood) {
141
+ const remaining = (await listOpenQuestions(deps)).length;
142
+ return result({
143
+ kind: mine.actions.some((a) => a.type === 'clarify') ? 'clarify' : 'answered', spoken: mine.understood, utterance: mine.utterance,
144
+ remaining, replayed: true,
145
+ }, { audioUrl: mine.confirmAudio && deps.audioPath ? deps.audioPath(id) : null, ...(mine.confirmAudio ? { mimeType: mine.confirmAudio.mimeType } : {}) });
146
+ }
147
+
148
+ const open = await listOpenQuestions(deps);
149
+ const target = req.questionId ? await store.get(req.questionId) : open[0] ?? null;
150
+ if (req.questionId && !target) throw new VoiceAnswerError('Not found.', 404);
151
+
152
+ let utterance = req.utterance ?? '';
153
+ if (req.audio) {
154
+ if (!deps.transcribe) throw new VoiceAnswerError('Speech to text is not set up.', 503, 'transcription_unavailable');
155
+ try {
156
+ const options = target ? await deps.options(target).catch(() => []) : [];
157
+ utterance = await deps.transcribe({ audio: req.audio.audio, mimeType: req.audio.mimeType, hints: options.map((o) => o.label) });
158
+ } catch (error) {
159
+ throw new VoiceAnswerError(`I could not make out the recording: ${error instanceof Error ? error.message : 'transcription failed'}`, 502, 'transcription_failed');
160
+ }
161
+ }
162
+ utterance = utterance.trim();
163
+
164
+ const finish = async (
165
+ kind: VoiceAnswerResult['kind'], lead: string, answered: OpenQuestion | null, asked: OpenQuestion | null = null,
166
+ ): Promise<VoiceAnswerResult> => {
167
+ const remainingQs = (await listOpenQuestions(deps)).filter((q) => q.id !== answered?.id || kind === 'undone');
168
+ const next = asked ?? (kind === 'clarify' ? null : remainingQs.find((q) => q.id !== answered?.id) ?? null);
169
+ const tail = kind === 'clarify' ? '' : next ? ` ${asks(next, await titleOf(deps, next))}` : ' That is everything for now.';
170
+ const spoken = `${lead}${tail}`.trim();
171
+ const said = await speakConfirmation({
172
+ text: spoken, clientActionId: id, synthesize: deps.synthesize,
173
+ audio: deps.audio && deps.audioPath ? { put: deps.audio.put, url: async (ref) => { audioRef = ref; return (deps.audioPath as (i: string) => string)(id); } } : undefined,
174
+ });
175
+ await recordPress(deps, {
176
+ id, utterance, understood: spoken, source: 'grammar', confidence: 1, at: new Date(now).toISOString(),
177
+ actions: kind === 'clarify' ? [{ type: 'clarify', question: spoken }] : [{ type: 'none' }],
178
+ ...(said.audioUrl && audioRef ? { confirmAudio: { ref: audioRef, mimeType: said.mimeType ?? 'audio/mpeg' } } : {}),
179
+ });
180
+ return result({ kind, spoken, question: answered, next, remaining: remainingQs.length, utterance }, said);
181
+ };
182
+ let audioRef = '';
183
+
184
+ if (!utterance) return finish('clarify', 'Sorry, I did not catch that. Can you say that again?', null);
185
+
186
+ const parsed = target
187
+ ? parseSpokenAnswer(target, utterance, { now, timeZone, options: await deps.options(target).catch(() => []) })
188
+ : parseSpokenAnswer({ id: '', itemId: '', kind: 'due_date', question: '', status: 'open', candidates: [], score: 0, ownerSub: deps.ownerSub, createdAt: '', updatedAt: '' }, utterance, { now, timeZone, options: [] });
189
+
190
+ if (parsed.kind === 'undo') {
191
+ const undone = await undoLast(deps, now);
192
+ return finish(undone.question && undone.text.startsWith('Undone') ? 'undone' : 'clarify', undone.text, undone.question, undone.question && undone.text.startsWith('Undone') ? undone.question : null);
193
+ }
194
+ if (!target) return finish('nothing', 'Nothing is waiting on you right now.', null);
195
+ const at = new Date(now).toISOString();
196
+ const title = await titleOf(deps, target);
197
+
198
+ switch (parsed.kind) {
199
+ case 'unclear': return finish('clarify', parsed.question, target);
200
+ case 'skip': {
201
+ const closed = await close(store, target, 'expired', 'skipped', at);
202
+ await store.put(target.itemId, target.kind, target.question, { snoozed_until: new Date(now + SNOOZE_MS).toISOString() });
203
+ return finish('skipped', 'Okay, I will ask again later.', closed);
204
+ }
205
+ case 'accept': {
206
+ const value = target.assumed?.value ?? '';
207
+ if (!value) return finish('clarify', `I do not have a guess to keep. ${target.question}`, target);
208
+ const named = target.assumed?.display ?? (await deps.options(target).catch(() => [])).find((o) => o.value === value)?.label;
209
+ const answered = await applyAnswer(deps, target, { value, ...(named ? { label: named } : {}), via: id });
210
+ // An id is not worth saying aloud: without a name, just confirm.
211
+ const said = target.kind === 'due_date' && named === undefined ? '' : named ? ` ${speakable(title, 8) || 'That one'} stays ${named}.` : '';
212
+ return finish('accepted', `Okay, keeping it.${said}`, answered);
213
+ }
214
+ case 'answer': {
215
+ const answered = await applyAnswer(deps, target, { value: parsed.value, ...(parsed.label ? { label: parsed.label } : {}), via: id });
216
+ return finish('answered', saidBack(target, title, parsed), answered);
217
+ }
218
+ }
219
+ }
220
+
221
+ /** Apply the answer, remembering what a due date was so "undo" can put it back. */
222
+ async function applyAnswer(deps: VoiceAnswerDeps, q: OpenQuestion, answer: QuestionAnswer): Promise<OpenQuestion> {
223
+ const prior = q.kind === 'due_date' ? await deps.seam.load(q.itemId).catch(() => null) : null;
224
+ return answerQuestion(deps, q.id, prior ? { ...answer, prior: { dueAt: prior.dueAt ?? null } } : answer);
225
+ }