@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,37 @@
1
+ /**
2
+ * A date said about ONE item must not quietly become the due date of the others (bd startsim-tmrvi, found in the
3
+ * live run of tmrvi.8). The model put "by Friday" (said about the vet) on the whole note.
4
+ */
5
+ import { describe, expect, it } from 'vitest';
6
+
7
+ import { resolveItemFields } from '../corpus/voice-due';
8
+ import type { VoiceItem, VoiceSection } from '../corpus/voice-sections';
9
+
10
+ const TRANSCRIPT = 'Okay, quick brain dump. I need to call the vet by Friday. Also send the invoice to Sam for the website thing. And somebody has to fix the login bug soon. Oh, and buy a birthday present for my sister.';
11
+ const ctx = { now: Date.parse('2026-11-07T19:00:00Z'), timeZone: 'America/New_York', transcript: TRANSCRIPT, noteWhen: 'by Friday' };
12
+ const section: VoiceSection = { label: 'Personal', kind: 'personal', focusId: null, items: [] } as never;
13
+ const item = (title: string, when?: string): VoiceItem => ({ title, ...(when ? { when } : {}) });
14
+
15
+ describe('a date said about one item', () => {
16
+ it('stays the vet\'s, stated and sure', () => {
17
+ const f = resolveItemFields(item('Call the vet', 'by Friday'), section, ctx);
18
+ expect(f.due.source).toBe('stated');
19
+ expect(f.due.question).toBeUndefined();
20
+ });
21
+
22
+ it('is only a doubtful guess for the others, and Tandem asks', () => {
23
+ for (const title of ['Buy a birthday present for my sister', 'Send the invoice to Sam for the website thing', 'Fix the login bug']) {
24
+ const f = resolveItemFields(item(title), section, ctx);
25
+ expect(f.due.confidence, title).toBeLessThanOrEqual(0.5);
26
+ expect(f.due.question, title).toMatch(/no date/i);
27
+ expect(f.due.candidates.map((c) => c.value)).toContain('');
28
+ }
29
+ });
30
+
31
+ it('a note-wide "these are all for Friday" is still a plain assumption, not a question', () => {
32
+ const wide = { ...ctx, transcript: 'Okay, these are all the things I need by Friday. Call the vet. Fix the login bug.', noteWhen: 'by Friday' };
33
+ const f = resolveItemFields(item('Fix the login bug'), section, wide);
34
+ expect(f.due.question).toBeUndefined();
35
+ expect(f.due.value).not.toBeNull();
36
+ });
37
+ });
@@ -34,6 +34,8 @@ import type { MemberConnectionsApi } from './types';
34
34
  import { failureMessage, unfilteredMessage } from './work-items';
35
35
  import { CompactItemRow } from './home/CompactItemRow';
36
36
  import { TrackerBoard } from './tracker/TrackerBoard';
37
+ import { TrackerTimeline } from './tracker/TrackerTimeline';
38
+ import { filterFromChip } from '../../corpus/tracker-timeline';
37
39
  import { TrackerToolbar, type TrackerView } from './tracker/TrackerToolbar';
38
40
  import { DEFAULT_TRACKER_SORT } from '../../corpus/tracker-sort';
39
41
  import { STALE_DAYS, groupTracker } from '../../corpus/tracker-groups';
@@ -463,6 +465,12 @@ export function TrackerPage({
463
465
  ))}
464
466
  </div>
465
467
  ) : null}
468
+ {api.timeline ? (
469
+ <TrackerTimeline
470
+ api={api} orgId={scope.orgId} now={clock} timeZone={timeZone}
471
+ filter={filterFromChip(quick, { search: filterText })}
472
+ />
473
+ ) : null}
466
474
  {filtering && owed === 0 && rows.length > 0 ? <p className={cn.muted}>No to-dos match{filterText.trim() ? ` “${filterText.trim()}”` : ' this filter'}.</p> : null}
467
475
  {rows.length > 0 ? (
468
476
  <TrackerToolbar sort={sort} onSort={setSort} view={view} onView={setView} inputClassName={cn.input} />
@@ -0,0 +1,123 @@
1
+ /**
2
+ * THE TRACKER'S TIMELINE STRIP: created / done / overdue per day over a 7/30/60/90
3
+ * day window, and the to-dos behind those numbers in a table. Drawn by the
4
+ * shared `@startsimpli/ui/insights` components; this file only supplies data and
5
+ * keeps ONE range state that drives both.
6
+ *
7
+ * Reads are server-side and bounded (see `tracker-timeline-client`). The effect
8
+ * is keyed on the workspace, the reader's day and a SERIALISED filter, with the
9
+ * api held in a ref and the free-text filter debounced: this page has already
10
+ * shipped one request runaway, and a timeline that re-read on every keystroke
11
+ * or render would be a second.
12
+ */
13
+ import * as React from 'react';
14
+ import { DEFAULT_RANGES, RangeEventTable, RangeSelector, RangeTimelineChart } from '@startsimpli/ui/insights';
15
+
16
+ import { buildTimeline, anchorOf, type TimelineFilter } from '../../../corpus/tracker-timeline';
17
+ import type { TimelineRead } from '../../../corpus/tracker-timeline-client';
18
+ import type { CommitmentTrackerApi } from '../../../corpus/types';
19
+ import { failureMessage } from '../work-items';
20
+
21
+ export interface TrackerTimelineProps {
22
+ api: Pick<CommitmentTrackerApi, 'timeline'>;
23
+ /** The workspace; a change re-reads. */
24
+ orgId: string;
25
+ filter: TimelineFilter;
26
+ /** Frozen by the page; the anchor day comes from this, never from a clock read here. */
27
+ now: number;
28
+ timeZone?: string;
29
+ /** Free-text filters wait this long before they become a server query. */
30
+ debounceMs?: number;
31
+ className?: string;
32
+ }
33
+
34
+ const FILTER_DEBOUNCE_MS = 400;
35
+
36
+ function useDebounced<T>(value: T, ms: number): T {
37
+ const [held, setHeld] = React.useState(value);
38
+ React.useEffect(() => {
39
+ if (ms <= 0) { setHeld(value); return undefined; }
40
+ const timer = setTimeout(() => setHeld(value), ms);
41
+ return () => clearTimeout(timer);
42
+ }, [value, ms]);
43
+ return held;
44
+ }
45
+
46
+ export function TrackerTimeline({
47
+ api, orgId, filter, now, timeZone = 'UTC', debounceMs = FILTER_DEBOUNCE_MS, className,
48
+ }: TrackerTimelineProps) {
49
+ const apiRef = React.useRef(api);
50
+ apiRef.current = api;
51
+ const [range, setRange] = React.useState('30d');
52
+ const [read, setRead] = React.useState<TimelineRead | null>(null);
53
+ const [error, setError] = React.useState('');
54
+ const [loading, setLoading] = React.useState(true);
55
+
56
+ const debouncedSearch = useDebounced(filter.search ?? '', debounceMs);
57
+ const filterKey = JSON.stringify({
58
+ status: filter.status ?? null, overdueOnly: Boolean(filter.overdueOnly),
59
+ owner: filter.owner ?? '', search: debouncedSearch,
60
+ });
61
+ const anchor = anchorOf(now, timeZone);
62
+
63
+ React.useEffect(() => {
64
+ let live = true;
65
+ setLoading(true);
66
+ setError('');
67
+ const f = JSON.parse(filterKey) as { status: TimelineFilter['status'] | null; overdueOnly: boolean; owner: string; search: string };
68
+ apiRef.current.timeline!(
69
+ { ...(f.status ? { status: f.status } : {}), ...(f.overdueOnly ? { overdueOnly: true } : {}), owner: f.owner, search: f.search },
70
+ { now, timeZone },
71
+ )
72
+ .then((data) => { if (live) setRead(data); })
73
+ .catch((err) => { if (live) { setRead(null); setError(failureMessage(err)); } })
74
+ .finally(() => { if (live) setLoading(false); });
75
+ return () => { live = false; };
76
+ // `now` is the page's frozen clock; the anchor day stands in for it.
77
+ // eslint-disable-next-line react-hooks/exhaustive-deps
78
+ }, [orgId, filterKey, anchor, timeZone]);
79
+
80
+ const built = React.useMemo(() => (read ? buildTimeline(read, now, timeZone) : null), [read, now, timeZone]);
81
+
82
+ return (
83
+ <section className={className ?? 'space-y-4'} aria-label="Tracker timeline" data-testid="tracker-timeline">
84
+ <h2 className="text-lg font-semibold text-gray-900">Timeline</h2>
85
+ {error ? <p className="text-sm text-red-600" role="alert">{error}</p> : null}
86
+ {loading && !built ? <p className="text-sm text-gray-500">Loading the timeline…</p> : null}
87
+ {built ? (
88
+ <>
89
+ <RangeSelector value={range} ranges={DEFAULT_RANGES} onChange={setRange} />
90
+ <RangeTimelineChart
91
+ series={built.series}
92
+ anchor={anchor}
93
+ direction="back"
94
+ unit="number"
95
+ title="Created, done and overdue"
96
+ range={range}
97
+ hideRangeSelector
98
+ height={260}
99
+ />
100
+ {built.estimatedDone > 0 ? (
101
+ <p className="text-xs text-gray-500" data-testid="timeline-estimated">
102
+ {built.estimatedDone} done {built.estimatedDone === 1 ? 'to-do has' : 'to-dos have'} no completion date and {built.estimatedDone === 1 ? 'is' : 'are'} counted on the day {built.estimatedDone === 1 ? 'it was' : 'they were'} last updated.
103
+ </p>
104
+ ) : null}
105
+ <RangeEventTable
106
+ points={built.points}
107
+ anchor={anchor}
108
+ direction="back"
109
+ range={range}
110
+ hideRangeSelector
111
+ showCategory
112
+ pageSize={10}
113
+ title="To-dos in this window"
114
+ emptyMessage="No to-dos in this window."
115
+ />
116
+ {read?.truncated ? (
117
+ <p className="text-xs text-gray-500">The table lists the newest 200 per kind; the chart counts all of them.</p>
118
+ ) : null}
119
+ </>
120
+ ) : null}
121
+ </section>
122
+ );
123
+ }
@@ -1,7 +1,7 @@
1
1
  import type { Briefing } from './types';
2
2
 
3
3
  /** Bump when the script wording or contract changes, so yesterday's cached script is not reused. */
4
- export const SCRIPT_VERSION = 1;
4
+ export const SCRIPT_VERSION = 2;
5
5
 
6
6
  /** 53-bit string hash (cyrb53). A cache key, not a security boundary, and it needs no `crypto`. */
7
7
  export function hashString(text: string): string {
@@ -24,5 +24,5 @@ export function hashString(text: string): string {
24
24
  */
25
25
  export function briefingContentHash(briefing: Briefing): string {
26
26
  const parts = briefing.items.map((e) => [e.id, e.title, e.kind, e.group, e.dueDate ?? '', e.priority ?? ''].join('␟'));
27
- return hashString([`v${SCRIPT_VERSION}`, briefing.context.localDate, briefing.remaining, ...parts].join('␞'));
27
+ return hashString([`v${SCRIPT_VERSION}`, briefing.context.localDate, briefing.remaining, briefing.unsure ?? 0, ...parts].join('␞'));
28
28
  }
@@ -45,6 +45,8 @@ export interface BriefingDeps {
45
45
  ownerSub: string;
46
46
  /** The caller's open to-dos (any owner may be returned; the composer scopes to `ownerSub`). */
47
47
  loadItems(): Promise<BriefingItem[]>;
48
+ /** How many clarifying questions are open; said as a pointer at the end. Omit for none. */
49
+ unsureCount?(): Promise<number>;
48
50
  synthesize: BriefingSynthesize;
49
51
  scriptLlm: BriefingScriptLlm | null;
50
52
  audio: BriefingAudio;
@@ -91,7 +93,9 @@ export async function generateBriefing(deps: BriefingDeps, request: BriefingRequ
91
93
  const ttl = Math.min(deps.audioTtlSeconds ?? DEFAULT_TTL, 600);
92
94
  const store = deps.store ?? createEntityBriefingStore(deps.http, deps.ownerSub);
93
95
 
94
- const briefing = composeBriefing(await deps.loadItems(), { ownerSub: deps.ownerSub, now, timeZone });
96
+ const composed = composeBriefing(await deps.loadItems(), { ownerSub: deps.ownerSub, now, timeZone });
97
+ const unsure = await deps.unsureCount?.().catch(() => 0) ?? 0;
98
+ const briefing = unsure > 0 ? { ...composed, unsure } : composed;
95
99
  const hash = briefingContentHash(briefing);
96
100
  const externalId = briefingExternalId(deps.ownerSub, briefing.context.localDate);
97
101
  const stored = request.force ? null : await store.find(externalId);
@@ -105,6 +105,12 @@ function summaryLine(briefing: Briefing): string {
105
105
  return `You have ${speakCount(n)} ${noun} on your plate today${tail}.`;
106
106
  }
107
107
 
108
+ /** "I am also unsure about two things. Say check in to go through them." Empty when nothing is open. */
109
+ export function unsurePointer(unsure: number | undefined): string {
110
+ if (!unsure || unsure < 1) return '';
111
+ return `I am also unsure about ${speakCount(unsure)} ${unsure === 1 ? 'thing' : 'things'}. Say check in to go through ${unsure === 1 ? 'it' : 'them'}.`;
112
+ }
113
+
108
114
  function signOff(briefing: Briefing): string {
109
115
  const n = briefing.remaining;
110
116
  return n > 0 ? `And ${speakCount(n)} more after that.` : 'That is everything.';
@@ -127,6 +133,8 @@ function assemble(briefing: Briefing, options: BriefingScriptOptions, parts: Par
127
133
  if (parts.lead) add(parts.lead, null);
128
134
  for (const say of parts.says) add(say.text, say.id);
129
135
  add(signOff(briefing), null);
136
+ const pointer = unsurePointer(briefing.unsure);
137
+ if (pointer) add(pointer, null);
130
138
  return { text, segments, source, words: wordCount(text) };
131
139
  }
132
140
 
@@ -145,8 +153,9 @@ export function templateScript(briefing: Briefing, options: BriefingScriptOption
145
153
 
146
154
  // -- the model path -----------------------------------------------------------
147
155
 
148
- function emptyScript(options: BriefingScriptOptions): BriefingScript {
149
- const text = `${greeting(options)} Nothing is due today, and nothing is overdue. Enjoy the clear day.`;
156
+ function emptyScript(briefing: Briefing, options: BriefingScriptOptions): BriefingScript {
157
+ const pointer = unsurePointer(briefing.unsure);
158
+ const text = `${greeting(options)} Nothing is due today, and nothing is overdue. ${pointer || 'Enjoy the clear day.'}`;
150
159
  return { text, segments: [], source: 'template', words: wordCount(text) };
151
160
  }
152
161
 
@@ -202,7 +211,7 @@ export async function writeBriefingScript(
202
211
  llm: BriefingScriptLlm | null,
203
212
  options: BriefingScriptOptions,
204
213
  ): Promise<BriefingScript> {
205
- if (briefing.empty) return emptyScript(options);
214
+ if (briefing.empty) return emptyScript(briefing, options);
206
215
  if (llm) {
207
216
  const ms = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
208
217
  try {
@@ -71,3 +71,11 @@ export function partOfDay(instant: number, timeZone: string): 'morning' | 'after
71
71
  if (hour < 12) return 'morning';
72
72
  return hour < 17 ? 'afternoon' : 'evening';
73
73
  }
74
+
75
+ /** Numeric dates inside a sentence said the way a person would (`due 2026-11-13 too` -> `due Friday the thirteenth too`). */
76
+ export function speakDatesIn(text: string, today: string): string {
77
+ return text.replace(/\b(\d{4})-(\d{2})-(\d{2})\b/g, (m, y, mo, d) => {
78
+ const month = Number(mo);
79
+ return month >= 1 && month <= 12 && Number(d) >= 1 && Number(d) <= 31 ? speakDate(m, today) : m;
80
+ });
81
+ }
@@ -59,4 +59,6 @@ export interface Briefing {
59
59
  counts: Record<BriefingKind, number>;
60
60
  empty: boolean;
61
61
  context: BriefingContext;
62
+ /** Open clarifying questions: said as a pointer at the end ("I am also unsure about two things"). Default 0. */
63
+ unsure?: number;
62
64
  }
@@ -32,6 +32,7 @@
32
32
  */
33
33
  import { patchEditedItem } from './commitment-edit';
34
34
  import { readStandings } from './standings';
35
+ import { createTimelineReader } from './tracker-timeline-client';
35
36
  import {
36
37
  DEFAULT_PARTICIPANT_EDGES,
37
38
  FOLDER_ROOT,
@@ -70,6 +71,7 @@ import type {
70
71
  SaveCommitmentsOptions,
71
72
  CommitmentApi,
72
73
  CommitmentQuery,
74
+ CommitmentTrackerApi,
73
75
  CorpusApi,
74
76
  CorpusFolder,
75
77
  CorpusPage,
@@ -124,6 +126,8 @@ export interface CorpusHttp {
124
126
 
125
127
  export interface CreateCorpusApiOptions {
126
128
  http: CorpusHttp;
129
+ /** Injectable clock (ms), for the completion stamp. Default `Date.now`. */
130
+ now?: () => number;
127
131
  /** The asking principal's scope, used as the fallback when a row omits its own. */
128
132
  scope: CorpusScope;
129
133
  /** Override when a tenant modelled its types under different keys. */
@@ -508,7 +512,7 @@ function undetermined(what: string): Error & { status: number } {
508
512
 
509
513
  export function createCorpusApi(
510
514
  options: CreateCorpusApiOptions,
511
- ): CorpusApi & CommitmentApi & ExtractionRunStore {
515
+ ): CorpusApi & CommitmentApi & ExtractionRunStore & Pick<CommitmentTrackerApi, 'timeline'> {
512
516
  const {
513
517
  http,
514
518
  scope,
@@ -723,6 +727,9 @@ export function createCorpusApi(
723
727
  return {
724
728
  ...createFilingApi(http, { entities, relationships }),
725
729
 
730
+ // The Tracker timeline's server reads (grouped counts + one capped page per series).
731
+ timeline: createTimelineReader({ http, type: types.commitment, entitiesPath: entities }),
732
+
726
733
  async listDocuments(query) {
727
734
  const documents = await page<TenantEntity>(types.document, query, (entity) => entity);
728
735
  // Skip the edge read entirely for an empty page: an empty corpus should
@@ -1440,6 +1447,10 @@ export function createPlanningApi(options: CreateCorpusApiOptions): PlanningApi
1440
1447
  if (patch.subtype !== undefined) wire.subtype = patch.subtype;
1441
1448
  if (patch.priority !== undefined) wire.priority = patch.priority;
1442
1449
  if (patch.resolvedAt !== undefined) wire.resolved_at = patch.resolvedAt;
1450
+ // WHEN it was finished, stamped on the transition to done only (never on
1451
+ // an edit to an already-done item, never over a value the caller sent):
1452
+ // the Tracker timeline's "done per day" reads this.
1453
+ else if (patch.status === 'done' && item.status !== 'done') wire.resolved_at = new Date((options.now ?? Date.now)()).toISOString();
1443
1454
  // `null` clears the mark: the tenant reads anything but 'private' as shared.
1444
1455
  if (patch.visibility !== undefined) {
1445
1456
  wire.visibility = patch.visibility ?? '';
@@ -5,6 +5,7 @@
5
5
  * release of a held item go through the tenant PATCH (`patchItem`).
6
6
  */
7
7
  import type { ItemEditSeam } from '../briefing/actions/types';
8
+ import { learnFromAnswer } from './learn';
8
9
  import { close, listOpenQuestions, storeFor, type QuestionDeps } from './sync';
9
10
  import type { OpenQuestion, QuestionAnswer } from './types';
10
11
 
@@ -16,6 +17,9 @@ export interface AnswerDeps extends QuestionDeps {
16
17
  fileItem?(itemId: string, focusId: string | null): Promise<void>;
17
18
  /** Save the tracker's personal container on the member's connection (central). */
18
19
  setPersonalContainer?(containerId: string): Promise<void>;
20
+ /** Remember the answer as a habit (default on). */
21
+ learn?: boolean;
22
+ timeZone?: string;
19
23
  }
20
24
 
21
25
  /** The fields that send a held item on its way. */
@@ -64,5 +68,11 @@ export async function answerQuestion(
64
68
  await deps.patchItem(q.itemId, { owner_sub: value, owner_name: answer.label ?? '' });
65
69
  break;
66
70
  }
67
- return close(store, q, 'resolved', 'answered', at, answer);
71
+ const closed = await close(store, q, 'resolved', 'answered', at, answer);
72
+ if (deps.learn !== false && (q.kind === 'project' || q.kind === 'due_date')) {
73
+ // Learning is a bonus: a failure here never undoes an answer that has already been applied.
74
+ const title = (await deps.seam.load(q.itemId).catch(() => null))?.title ?? '';
75
+ await learnFromAnswer(deps, { kind: q.kind, title, answer }).catch(() => undefined);
76
+ }
77
+ return closed;
68
78
  }
@@ -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,14 @@ 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';
24
+ export { createPreferenceStore, learnFromAnswer, nextEvidence, decideFromHabits, PREFERENCE_ATTRIBUTES, PREFERENCE_LABEL, PREFERENCE_TYPE } from './learn';
25
+ export type { Preference, PreferenceKind } from './learn';