@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,227 @@
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 { speakDatesIn, speakable } from '../briefing/speak';
16
+ import { localDate } from '../today';
17
+ import { answerQuestion, type AnswerDeps } from './answer';
18
+ import { close, listOpenQuestions, storeFor } from './sync';
19
+ import type { OpenQuestion, QuestionAnswer } from './types';
20
+ import { parseSpokenAnswer, type AnswerOption } from './voice-parse';
21
+
22
+ export const CLIENT_ACTION_ID = /^[A-Za-z0-9_-]{8,64}$/;
23
+ const SNOOZE_MS = 12 * 3_600_000;
24
+ const UNDO_WINDOW_MS = 30 * 60_000;
25
+ const PENDING_KEPT = 12;
26
+ export const MAX_ANSWER_AUDIO_BYTES = 10 * 1024 * 1024;
27
+
28
+ export class VoiceAnswerError extends Error {
29
+ constructor(message: string, readonly status: number, readonly code?: string) {
30
+ super(message);
31
+ this.name = 'VoiceAnswerError';
32
+ }
33
+ }
34
+
35
+ export interface VoiceAnswerDeps extends AnswerDeps {
36
+ /** The choices a project / team / owner answer may name. */
37
+ options(q: OpenQuestion): Promise<AnswerOption[]>;
38
+ log: ActionLogStore;
39
+ transcribe?: (input: { audio: Uint8Array; mimeType: string; hints: string[] }) => Promise<string>;
40
+ synthesize?: BriefingSynthesize;
41
+ audio?: Pick<BriefingAudio, 'put'>;
42
+ /** Where the spoken confirmation is fetched from, for this press. */
43
+ audioPath?: (clientActionId: string) => string;
44
+ timeZone?: string;
45
+ }
46
+
47
+ export interface VoiceAnswerRequest {
48
+ clientActionId: string;
49
+ /** The question being answered; omit to answer the best open one. */
50
+ questionId?: string;
51
+ utterance?: string;
52
+ audio?: { audio: Uint8Array; mimeType: string };
53
+ timeZone?: string;
54
+ }
55
+
56
+ export interface VoiceAnswerResult {
57
+ /** `clarify`: it asked back instead of acting. */
58
+ kind: 'answered' | 'accepted' | 'skipped' | 'undone' | 'clarify' | 'nothing';
59
+ clientActionId: string;
60
+ utterance: string;
61
+ /** The question this press answered (absent for `clarify` on nothing, `nothing`). */
62
+ question: OpenQuestion | null;
63
+ /** The next thing to ask, so the app can listen again with this id. */
64
+ next: OpenQuestion | null;
65
+ /** The sentence said back, including the next question. */
66
+ spoken: string;
67
+ audioUrl: string | null;
68
+ mimeType?: string;
69
+ /** Open questions still waiting. */
70
+ remaining: number;
71
+ replayed: boolean;
72
+ }
73
+
74
+ export function validateAnswerRequest(req: VoiceAnswerRequest): void {
75
+ if (!CLIENT_ACTION_ID.test(req.clientActionId ?? '')) {
76
+ throw new VoiceAnswerError('Send a clientActionId (8-64 letters, digits, - or _), fresh for each press.', 400);
77
+ }
78
+ if (req.utterance === undefined && !req.audio) throw new VoiceAnswerError('Send what was said: audio or an utterance.', 400);
79
+ if (req.audio && req.audio.audio.byteLength > MAX_ANSWER_AUDIO_BYTES) throw new VoiceAnswerError('That recording is too long for an answer.', 413);
80
+ }
81
+
82
+ const asks = (q: OpenQuestion, title: string, today: string) => {
83
+ const t = speakable(title, 10);
84
+ const question = speakDatesIn(q.question, today);
85
+ return t ? `About ${t}: ${question}` : question;
86
+ };
87
+
88
+ async function titleOf(deps: VoiceAnswerDeps, q: OpenQuestion): Promise<string> {
89
+ return (await deps.seam.load(q.itemId).catch(() => null))?.title ?? '';
90
+ }
91
+
92
+ function saidBack(q: OpenQuestion, title: string, a: { value: string; label?: string; spoken: string }): string {
93
+ const t = speakable(title, 8) || 'that one';
94
+ switch (q.kind) {
95
+ case 'due_date': return a.value ? `Got it, ${t} is due ${a.spoken}.` : `Got it, ${t} has no due date.`;
96
+ case 'project': return `Got it, ${t} goes under ${a.spoken}.`;
97
+ case 'team': return `Got it, ${t} goes to ${a.spoken}.`;
98
+ case 'ownership': return `Got it, ${t} is ${a.spoken}'s.`;
99
+ case 'private_space': return `Got it, ${a.spoken} is your private space.`;
100
+ }
101
+ }
102
+
103
+ async function recordPress(deps: VoiceAnswerDeps, entry: PendingReply) {
104
+ const log: ActionLog = await deps.log.load();
105
+ log.pending = [...(log.pending ?? []).filter((p) => p.id !== entry.id), entry].slice(-PENDING_KEPT);
106
+ await deps.log.save(log);
107
+ }
108
+
109
+ async function undoLast(deps: VoiceAnswerDeps, now: number): Promise<{ text: string; question: OpenQuestion | null }> {
110
+ const all = await storeFor(deps).all();
111
+ const last = all
112
+ .filter((q) => q.resolution === 'answered' && q.answer?.via && q.resolvedAt && now - Date.parse(q.resolvedAt) <= UNDO_WINDOW_MS)
113
+ .sort((a, b) => (b.resolvedAt ?? '').localeCompare(a.resolvedAt ?? ''))[0];
114
+ if (!last) return { text: 'There is nothing to undo.', question: null };
115
+ if (last.kind !== 'due_date' || !last.answer?.prior) {
116
+ return { text: 'I cannot undo that one by voice. You can change it on the item.', question: last };
117
+ }
118
+ const item = await deps.seam.load(last.itemId);
119
+ if (!item) return { text: 'That item is gone, so there is nothing to put back.', question: last };
120
+ await deps.seam.update(item, { dueAt: last.answer.prior.dueAt ?? null });
121
+ const at = new Date(now).toISOString();
122
+ const reopened = await storeFor(deps).put(last.itemId, last.kind, last.question, {
123
+ status: 'open', resolution: '', resolved_at: '', answer: '', updated_at: at,
124
+ });
125
+ return { text: `Undone. ${speakable(item.title, 8)} is back how it was.`, question: reopened };
126
+ }
127
+
128
+ export async function answerQuestionByVoice(deps: VoiceAnswerDeps, req: VoiceAnswerRequest): Promise<VoiceAnswerResult> {
129
+ validateAnswerRequest(req);
130
+ const now = (deps.now ?? Date.now)();
131
+ const id = req.clientActionId;
132
+ const timeZone = req.timeZone || deps.timeZone || 'UTC';
133
+ const store = storeFor(deps);
134
+
135
+ // Already handled: answer from the log.
136
+ const log = await deps.log.load();
137
+ const mine = (log.pending ?? []).find((p) => p.id === id);
138
+ const result = (over: Partial<VoiceAnswerResult> & Pick<VoiceAnswerResult, 'kind' | 'spoken'>, audio?: { audioUrl: string | null; mimeType?: string }): VoiceAnswerResult => ({
139
+ clientActionId: id, utterance: req.utterance ?? '', question: null, next: null, audioUrl: audio?.audioUrl ?? null,
140
+ ...(audio?.mimeType ? { mimeType: audio.mimeType } : {}), remaining: 0, replayed: false, ...over,
141
+ });
142
+ if (mine?.understood) {
143
+ const remaining = (await listOpenQuestions(deps)).length;
144
+ return result({
145
+ kind: mine.actions.some((a) => a.type === 'clarify') ? 'clarify' : 'answered', spoken: mine.understood, utterance: mine.utterance,
146
+ remaining, replayed: true,
147
+ }, { audioUrl: mine.confirmAudio && deps.audioPath ? deps.audioPath(id) : null, ...(mine.confirmAudio ? { mimeType: mine.confirmAudio.mimeType } : {}) });
148
+ }
149
+
150
+ const open = await listOpenQuestions(deps);
151
+ const target = req.questionId ? await store.get(req.questionId) : open[0] ?? null;
152
+ if (req.questionId && !target) throw new VoiceAnswerError('Not found.', 404);
153
+
154
+ let utterance = req.utterance ?? '';
155
+ if (req.audio) {
156
+ if (!deps.transcribe) throw new VoiceAnswerError('Speech to text is not set up.', 503, 'transcription_unavailable');
157
+ try {
158
+ const options = target ? await deps.options(target).catch(() => []) : [];
159
+ utterance = await deps.transcribe({ audio: req.audio.audio, mimeType: req.audio.mimeType, hints: options.map((o) => o.label) });
160
+ } catch (error) {
161
+ throw new VoiceAnswerError(`I could not make out the recording: ${error instanceof Error ? error.message : 'transcription failed'}`, 502, 'transcription_failed');
162
+ }
163
+ }
164
+ utterance = utterance.trim();
165
+
166
+ const finish = async (
167
+ kind: VoiceAnswerResult['kind'], lead: string, answered: OpenQuestion | null, asked: OpenQuestion | null = null,
168
+ ): Promise<VoiceAnswerResult> => {
169
+ const remainingQs = (await listOpenQuestions(deps)).filter((q) => q.id !== answered?.id || kind === 'undone');
170
+ const next = asked ?? (kind === 'clarify' ? null : remainingQs.find((q) => q.id !== answered?.id) ?? null);
171
+ const tail = kind === 'clarify' ? '' : next ? ` ${asks(next, await titleOf(deps, next), localDate(now, timeZone))}` : ' That is everything for now.';
172
+ const spoken = `${lead}${tail}`.trim();
173
+ const said = await speakConfirmation({
174
+ text: spoken, clientActionId: id, synthesize: deps.synthesize,
175
+ audio: deps.audio && deps.audioPath ? { put: deps.audio.put, url: async (ref) => { audioRef = ref; return (deps.audioPath as (i: string) => string)(id); } } : undefined,
176
+ });
177
+ await recordPress(deps, {
178
+ id, utterance, understood: spoken, source: 'grammar', confidence: 1, at: new Date(now).toISOString(),
179
+ actions: kind === 'clarify' ? [{ type: 'clarify', question: spoken }] : [{ type: 'none' }],
180
+ ...(said.audioUrl && audioRef ? { confirmAudio: { ref: audioRef, mimeType: said.mimeType ?? 'audio/mpeg' } } : {}),
181
+ });
182
+ return result({ kind, spoken, question: answered, next, remaining: remainingQs.length, utterance }, said);
183
+ };
184
+ let audioRef = '';
185
+
186
+ if (!utterance) return finish('clarify', 'Sorry, I did not catch that. Can you say that again?', null);
187
+
188
+ const parsed = target
189
+ ? parseSpokenAnswer(target, utterance, { now, timeZone, options: await deps.options(target).catch(() => []) })
190
+ : parseSpokenAnswer({ id: '', itemId: '', kind: 'due_date', question: '', status: 'open', candidates: [], score: 0, ownerSub: deps.ownerSub, createdAt: '', updatedAt: '' }, utterance, { now, timeZone, options: [] });
191
+
192
+ if (parsed.kind === 'undo') {
193
+ const undone = await undoLast(deps, now);
194
+ return finish(undone.question && undone.text.startsWith('Undone') ? 'undone' : 'clarify', undone.text, undone.question, undone.question && undone.text.startsWith('Undone') ? undone.question : null);
195
+ }
196
+ if (!target) return finish('nothing', 'Nothing is waiting on you right now.', null);
197
+ const at = new Date(now).toISOString();
198
+ const title = await titleOf(deps, target);
199
+
200
+ switch (parsed.kind) {
201
+ case 'unclear': return finish('clarify', parsed.question, target);
202
+ case 'skip': {
203
+ const closed = await close(store, target, 'expired', 'skipped', at);
204
+ await store.put(target.itemId, target.kind, target.question, { snoozed_until: new Date(now + SNOOZE_MS).toISOString() });
205
+ return finish('skipped', 'Okay, I will ask again later.', closed);
206
+ }
207
+ case 'accept': {
208
+ const value = target.assumed?.value ?? '';
209
+ if (!value) return finish('clarify', `I do not have a guess to keep. ${target.question}`, target);
210
+ const named = target.assumed?.display ?? (await deps.options(target).catch(() => [])).find((o) => o.value === value)?.label;
211
+ const answered = await applyAnswer(deps, target, { value, ...(named ? { label: named } : {}), via: id });
212
+ // An id is not worth saying aloud: without a name, just confirm.
213
+ const said = target.kind === 'due_date' && named === undefined ? '' : named ? ` ${speakable(title, 8) || 'That one'} stays ${named}.` : '';
214
+ return finish('accepted', `Okay, keeping it.${said}`, answered);
215
+ }
216
+ case 'answer': {
217
+ const answered = await applyAnswer(deps, target, { value: parsed.value, ...(parsed.label ? { label: parsed.label } : {}), via: id });
218
+ return finish('answered', saidBack(target, title, parsed), answered);
219
+ }
220
+ }
221
+ }
222
+
223
+ /** Apply the answer, remembering what a due date was so "undo" can put it back. */
224
+ async function applyAnswer(deps: VoiceAnswerDeps, q: OpenQuestion, answer: QuestionAnswer): Promise<OpenQuestion> {
225
+ const prior = q.kind === 'due_date' ? await deps.seam.load(q.itemId).catch(() => null) : null;
226
+ return answerQuestion(deps, q.id, prior ? { ...answer, prior: { dueAt: prior.dueAt ?? null } } : answer);
227
+ }
@@ -0,0 +1,117 @@
1
+ /**
2
+ * THE TRACKER TIMELINE'S SERVER READS.
3
+ *
4
+ * Per series, ONE grouped count over the tenant's `entities/counts` (one row per
5
+ * stored date value, followed through its pages) plus ONE capped page of the
6
+ * rows themselves, for the table under the chart. Nothing here walks the list:
7
+ * the browser never holds more than 200 rows per series, and says so when a
8
+ * series had more (`truncated`).
9
+ *
10
+ * The counts are exact; the rows are the newest page. That asymmetry is
11
+ * deliberate and surfaced, not hidden: a chart that is right and a table that
12
+ * says "showing 200 of 450" beats a table that silently stops.
13
+ */
14
+ import type { CorpusHttp } from './client';
15
+ import {
16
+ anchorOf,
17
+ estimatedDoneParams,
18
+ timelineParams,
19
+ type TimelineFilter,
20
+ type TimelineInput,
21
+ type TimelineKind,
22
+ type ValueCount,
23
+ } from './tracker-timeline';
24
+ import type { CommitmentStatus } from './types';
25
+
26
+ const PAGE = 200;
27
+ /** Distinct stored values in a 90-day window stay far under this; it is a stop, not a target. */
28
+ const MAX_COUNT_PAGES = 10;
29
+ const STATUSES = ['open', 'in_progress', 'done', 'blocked', 'dropped'];
30
+
31
+ export interface TimelineReaderOptions {
32
+ http: Pick<CorpusHttp, 'get'>;
33
+ /** The commitment type key. */
34
+ type: string;
35
+ entitiesPath?: string;
36
+ }
37
+
38
+ export interface TimelineRead extends TimelineInput {
39
+ /** A series had more rows than the one page read for it. */
40
+ truncated: boolean;
41
+ }
42
+
43
+ interface Wire { id?: unknown; name?: unknown; updated_at?: unknown; updatedAt?: unknown; data?: unknown }
44
+
45
+ const text = (data: Record<string, unknown>, ...keys: string[]): string | null => {
46
+ for (const k of keys) {
47
+ const v = data[k];
48
+ if (typeof v === 'string' && v) return v;
49
+ }
50
+ return null;
51
+ };
52
+
53
+ function toItem(row: Wire) {
54
+ const data = row.data && typeof row.data === 'object' ? (row.data as Record<string, unknown>) : {};
55
+ const status = String(data.status ?? 'open');
56
+ return {
57
+ id: String(row.id),
58
+ title: text(data, 'title') ?? (typeof row.name === 'string' && row.name ? row.name : 'Untitled item'),
59
+ status: (STATUSES.includes(status) ? status : 'open') as CommitmentStatus,
60
+ dueAt: text(data, 'due_at', 'dueAt'),
61
+ firstSeenAt: text(data, 'first_seen_at', 'firstSeenAt'),
62
+ resolvedAt: text(data, 'resolved_at', 'resolvedAt'),
63
+ updatedAt: text(row as Record<string, unknown>, 'updated_at', 'updatedAt'),
64
+ };
65
+ }
66
+
67
+ export function createTimelineReader(options: TimelineReaderOptions) {
68
+ const entities = options.entitiesPath ?? 'api/v1/entities';
69
+ const { http, type } = options;
70
+
71
+ async function counts(params: Record<string, unknown> | null): Promise<ValueCount[]> {
72
+ if (!params) return [];
73
+ const out: ValueCount[] = [];
74
+ for (let page = 1; page <= MAX_COUNT_PAGES; page += 1) {
75
+ const body = await http.get<{ results?: Array<{ values?: unknown[]; count?: number }>; next?: string | null }>(
76
+ `${entities}/counts`, { params: { ...params, type, page, page_size: PAGE } });
77
+ for (const row of body.results ?? []) {
78
+ const v = row.values?.[0];
79
+ out.push({ value: typeof v === 'string' ? v : null, count: Number(row.count ?? 0) });
80
+ }
81
+ if (!body.next) break;
82
+ }
83
+ return out;
84
+ }
85
+
86
+ async function rows(params: Record<string, unknown> | null, order?: string) {
87
+ if (!params) return { items: [], truncated: false };
88
+ const { group_by: _g, ...rest } = params;
89
+ void _g;
90
+ const body = await http.get<{ count?: number; results?: Wire[] }>(
91
+ entities, { params: { ...rest, type, page_size: PAGE, ...(order ? { order } : {}) } });
92
+ const results = body.results ?? [];
93
+ return { items: results.map(toItem), truncated: Number(body.count ?? results.length) > results.length };
94
+ }
95
+
96
+ return async function read(
97
+ filter: TimelineFilter,
98
+ clock: { now: number; timeZone?: string },
99
+ ): Promise<TimelineRead> {
100
+ const p = (kind: TimelineKind) => timelineParams(kind, filter, clock);
101
+ const [created, done, overdue, rc, rd, re, ro] = await Promise.all([
102
+ counts(p('created')), counts(p('done')), counts(p('overdue')),
103
+ rows(p('created'), '-attr.first_seen_at'),
104
+ rows(p('done'), '-attr.resolved_at'),
105
+ rows(estimatedDoneParams(filter, clock)),
106
+ rows(p('overdue'), 'attr.due_at'),
107
+ ]);
108
+ const seen = new Map<string, ReturnType<typeof toItem>>();
109
+ for (const item of [...rc.items, ...rd.items, ...re.items, ...ro.items]) if (!seen.has(item.id)) seen.set(item.id, item);
110
+ return {
111
+ anchor: anchorOf(clock.now, clock.timeZone),
112
+ created, done, overdue,
113
+ items: [...seen.values()],
114
+ truncated: rc.truncated || rd.truncated || re.truncated || ro.truncated,
115
+ };
116
+ };
117
+ }
@@ -0,0 +1,228 @@
1
+ /**
2
+ * THE TRACKER TIMELINE'S ARITHMETIC: three per-day series (created / done /
3
+ * overdue) and the to-dos behind them, as the generic `TimelinePoint` shape that
4
+ * `@startsimpli/ui/insights` draws. No React, no clock reads (the caller passes
5
+ * `now`), no HTTP: the reader in `tracker-timeline-client` fetches, this decides
6
+ * what the fetched numbers mean.
7
+ *
8
+ * WHAT EACH SERIES MEANS
9
+ * created items first seen that day (`first_seen_at`).
10
+ * done items marked done that day (`resolved_at`). Rows that were already
11
+ * done before completion was stamped have no `resolved_at`; they are
12
+ * placed on their last-updated day and COUNTED AS ESTIMATED so the
13
+ * screen can say so instead of pretending the date is exact.
14
+ * overdue items still owed whose date has passed, on the day they fell due.
15
+ * Same rule as the list (`isOverdue`): done and dropped are never
16
+ * overdue however old their date is.
17
+ */
18
+ import type { TimelineEvent, TimelinePoint } from '@startsimpli/ui/insights';
19
+
20
+ import type { CommitmentQuery, CommitmentStatus } from './types';
21
+ import { isOverdue } from './work-item-logic';
22
+
23
+ /** The longest window the strip offers; one read serves every shorter window. */
24
+ export const TIMELINE_DAYS = 90;
25
+
26
+ export type TimelineKind = 'created' | 'done' | 'overdue';
27
+
28
+ const OWED: CommitmentStatus[] = ['open', 'in_progress', 'blocked'];
29
+ const DAY_MS = 86_400_000;
30
+
31
+ /** One value of a grouped count (the raw attribute text) and how many rows hold it. */
32
+ export interface ValueCount { value: string | null; count: number }
33
+
34
+ /** The slice of a to-do the timeline needs; dates are as stored. */
35
+ export interface TimelineItem {
36
+ id: string;
37
+ title: string;
38
+ status: CommitmentStatus;
39
+ dueAt: string | null;
40
+ firstSeenAt: string | null;
41
+ resolvedAt: string | null;
42
+ /** The row's own last-write time, the fallback for a done item with no `resolved_at`. */
43
+ updatedAt: string | null;
44
+ }
45
+
46
+ export interface TimelineInput {
47
+ /** The reader's local day, YYYY-MM-DD. */
48
+ anchor: string;
49
+ created: ValueCount[];
50
+ done: ValueCount[];
51
+ overdue: ValueCount[];
52
+ items: TimelineItem[];
53
+ }
54
+
55
+ /** The page's filters, as the timeline understands them. */
56
+ export interface TimelineFilter {
57
+ /** Narrow to one status (the quick chips). */
58
+ status?: CommitmentStatus;
59
+ /** Only owed items past their date (the Overdue chip). */
60
+ overdueOnly?: boolean;
61
+ search?: string;
62
+ owner?: string;
63
+ }
64
+
65
+ const addDays = (day: string, days: number): string =>
66
+ new Date(Date.parse(`${day}T00:00:00Z`) + days * DAY_MS).toISOString().slice(0, 10);
67
+
68
+ /** The local calendar day of an instant; a date-only value is already a day. `null` if unreadable. */
69
+ export function dayOf(value: string | null | undefined, timeZone = 'UTC'): string | null {
70
+ if (!value) return null;
71
+ if (/^\d{4}-\d{2}-\d{2}$/.test(value)) return value;
72
+ const ms = Date.parse(value);
73
+ if (!Number.isFinite(ms)) return null;
74
+ try {
75
+ return new Intl.DateTimeFormat('en-CA', { timeZone, year: 'numeric', month: '2-digit', day: '2-digit' }).format(ms);
76
+ } catch {
77
+ return new Date(ms).toISOString().slice(0, 10);
78
+ }
79
+ }
80
+
81
+ /** The anchor day for a clock reading. */
82
+ export const anchorOf = (now: number, timeZone = 'UTC'): string => dayOf(new Date(now).toISOString(), timeZone) as string;
83
+
84
+ /** `days` calendar days ending on `anchorDay`, oldest first. */
85
+ export function windowDayList(anchorDay: string, days: number): string[] {
86
+ return Array.from({ length: days }, (_, i) => addDays(anchorDay, i - (days - 1)));
87
+ }
88
+
89
+ /** Grouped counts (one row per stored value) folded into one count per local day. */
90
+ export function bucketCounts(rows: ValueCount[], timeZone = 'UTC'): Map<string, number> {
91
+ const out = new Map<string, number>();
92
+ for (const row of rows) {
93
+ const day = dayOf(row.value, timeZone);
94
+ if (day) out.set(day, (out.get(day) ?? 0) + row.count);
95
+ }
96
+ return out;
97
+ }
98
+
99
+ /** The day an item was completed, and whether that day is a guess (no `resolved_at`). */
100
+ export function completionOf(item: TimelineItem, timeZone = 'UTC'): { day: string; estimated: boolean } | null {
101
+ if (item.status !== 'done') return null;
102
+ const exact = dayOf(item.resolvedAt, timeZone);
103
+ if (exact) return { day: exact, estimated: false };
104
+ const guess = dayOf(item.updatedAt, timeZone);
105
+ return guess ? { day: guess, estimated: true } : null;
106
+ }
107
+
108
+ const TONE: Record<TimelineKind, TimelineEvent['tone']> = { created: 'neutral', done: 'up', overdue: 'down' };
109
+
110
+ function eventFor(kind: TimelineKind, item: TimelineItem, label: string): TimelineEvent {
111
+ return { id: `${kind}:${item.id}`, label: item.title, delta: 0, tone: TONE[kind], category: kind, status: label };
112
+ }
113
+
114
+ export interface BuiltTimeline {
115
+ /** created / done / overdue, one point per day of the longest window, zero-filled. */
116
+ series: Array<{ id: TimelineKind; name: string; points: TimelinePoint[] }>;
117
+ /** Days that have at least one to-do, for the table under the chart. */
118
+ points: TimelinePoint[];
119
+ /** How many done items sit on an estimated day. */
120
+ estimatedDone: number;
121
+ }
122
+
123
+ export function buildTimeline(input: TimelineInput, now: number, timeZone = 'UTC'): BuiltTimeline {
124
+ const days = windowDayList(input.anchor, TIMELINE_DAYS);
125
+ const inWindow = new Set(days);
126
+ const counts: Record<TimelineKind, Map<string, number>> = {
127
+ created: bucketCounts(input.created, timeZone),
128
+ done: bucketCounts(input.done, timeZone),
129
+ overdue: bucketCounts(input.overdue, timeZone),
130
+ };
131
+
132
+ const byDay = new Map<string, TimelineEvent[]>();
133
+ const put = (day: string | null, event: TimelineEvent) => {
134
+ if (!day || !inWindow.has(day)) return;
135
+ byDay.set(day, [...(byDay.get(day) ?? []), event]);
136
+ };
137
+ let estimatedDone = 0;
138
+ for (const item of input.items) {
139
+ put(dayOf(item.firstSeenAt, timeZone), eventFor('created', item, 'Created'));
140
+ const completed = completionOf(item, timeZone);
141
+ if (completed) {
142
+ put(completed.day, eventFor('done', item, completed.estimated ? 'Done (date estimated)' : 'Done'));
143
+ if (completed.estimated && inWindow.has(completed.day)) {
144
+ estimatedDone += 1;
145
+ counts.done.set(completed.day, (counts.done.get(completed.day) ?? 0) + 1);
146
+ }
147
+ }
148
+ if (isOverdue(item, now)) put(dayOf(item.dueAt, timeZone), eventFor('overdue', item, 'Overdue'));
149
+ }
150
+
151
+ const names: Record<TimelineKind, string> = { created: 'Created', done: 'Done', overdue: 'Overdue' };
152
+ const series = (['created', 'done', 'overdue'] as TimelineKind[]).map((id) => ({
153
+ id,
154
+ name: names[id],
155
+ points: days.map((date) => ({ date, value: counts[id].get(date) ?? 0 })),
156
+ }));
157
+ const points = days
158
+ .filter((date) => byDay.has(date))
159
+ .map((date) => ({ date, value: byDay.get(date)!.length, events: byDay.get(date)! }));
160
+ return { series, points, estimatedDone };
161
+ }
162
+
163
+ /**
164
+ * The server parameters for one series' grouped count (`entities/counts`), or
165
+ * `null` when the filters make the series empty by definition (a Blocked chip
166
+ * has no done items) — no request is the honest answer there.
167
+ */
168
+ export function timelineParams(
169
+ kind: TimelineKind,
170
+ filter: TimelineFilter,
171
+ clock: { now: number; timeZone?: string },
172
+ ): Record<string, unknown> | null {
173
+ const anchor = anchorOf(clock.now, clock.timeZone);
174
+ // One day wider than the window: the day a stored instant falls on depends on
175
+ // the reader's zone, which only the client knows how to apply.
176
+ const since = addDays(anchor, -TIMELINE_DAYS);
177
+ const nowIso = new Date(clock.now).toISOString();
178
+ const params: Record<string, unknown> = {};
179
+
180
+ if (kind === 'done') {
181
+ if (filter.overdueOnly || (filter.status && filter.status !== 'done')) return null;
182
+ params['attr.status'] = 'done';
183
+ params['attr.resolved_at__gte'] = since;
184
+ } else if (kind === 'overdue') {
185
+ if (filter.status === 'done') return null;
186
+ if (filter.status) params['attr.status'] = filter.status;
187
+ else params['attr.status__in'] = OWED.join(',');
188
+ params['attr.due_at__gte'] = since;
189
+ params['attr.due_at__lt'] = nowIso;
190
+ } else {
191
+ params['attr.first_seen_at__gte'] = since;
192
+ if (filter.status) params['attr.status'] = filter.status;
193
+ if (filter.overdueOnly) {
194
+ if (!filter.status) params['attr.status__in'] = OWED.join(',');
195
+ params['attr.due_at__lt'] = nowIso;
196
+ }
197
+ }
198
+ params.group_by = { created: 'attr.first_seen_at', done: 'attr.resolved_at', overdue: 'attr.due_at' }[kind];
199
+ if (filter.search?.trim()) params.search = filter.search.trim();
200
+ if (filter.owner?.trim()) params['attr.owner_name__icontains'] = filter.owner.trim();
201
+ return params;
202
+ }
203
+
204
+ /**
205
+ * Rows for the done items that have no `resolved_at` (finished before
206
+ * completion was stamped): the same filters as the done series, windowed by the
207
+ * row's own last update instead. `null` when the filters rule done items out.
208
+ */
209
+ export function estimatedDoneParams(
210
+ filter: TimelineFilter,
211
+ clock: { now: number; timeZone?: string },
212
+ ): Record<string, unknown> | null {
213
+ const base = timelineParams('done', filter, clock);
214
+ if (!base) return null;
215
+ const { group_by: _g, 'attr.resolved_at__gte': _r, ...rest } = base;
216
+ void _g; void _r;
217
+ const since = addDays(anchorOf(clock.now, clock.timeZone), -TIMELINE_DAYS);
218
+ return { ...rest, 'attr.resolved_at__isnull': 'true', updated_after: `${since}T00:00:00.000Z` };
219
+ }
220
+
221
+ /** Map the Tracker's quick chip onto the timeline's filter. */
222
+ export function filterFromChip(chip: 'all' | 'overdue' | 'blocked' | 'in_progress', rest: Pick<CommitmentQuery, 'search' | 'owner'> = {}): TimelineFilter {
223
+ return {
224
+ ...(chip === 'blocked' || chip === 'in_progress' ? { status: chip } : {}),
225
+ ...(chip === 'overdue' ? { overdueOnly: true } : {}),
226
+ ...rest,
227
+ };
228
+ }
@@ -1105,6 +1105,16 @@ export interface ExtractionDraft {
1105
1105
  * handler; the handler runs the extraction server-side, where the key lives.
1106
1106
  */
1107
1107
  export interface CommitmentTrackerApi extends CommitmentApi {
1108
+ /**
1109
+ * The Tracker timeline's data: grouped per-day counts for created / done /
1110
+ * overdue plus one capped page of the to-dos behind them, read server-side.
1111
+ * Absent on a deployment without the tenant's `entities/counts`; the page then
1112
+ * simply has no timeline.
1113
+ */
1114
+ timeline?(
1115
+ filter: import('./tracker-timeline').TimelineFilter,
1116
+ clock: { now: number; timeZone?: string },
1117
+ ): Promise<import('./tracker-timeline-client').TimelineRead>;
1108
1118
  /**
1109
1119
  * Run ONE slice of extraction and wait for it.
1110
1120
  *
@@ -124,6 +124,20 @@ function fmtCandidate(c: { date: string; time?: string }): string {
124
124
  return c.time ? `${c.date} ${c.time}` : c.date;
125
125
  }
126
126
 
127
+ /** Words that carry no task of their own (as `stem` cuts them). */
128
+ const FILLER = new Set(['the', 'and', 'but', 'for', 'you', 'all', 'oh', 'ok', 'okay', 'also', 'need', 'have', 'has', 'got', 'must', 'should', 'will', 'then', 'now', 'just', 'some', 'one', 'out', 'get', 'its', 'are', 'was', 'that', 'this', 'with', 'from', 'to', 'by', 'of', 'on', 'in', 'my', 'me', 'it', 'is', 'an', 'at', 'as', 'be', 'do', 'so', 'we', 'quick', 'thing', 'items', 'stuff', 'todos', 'tasks', 'these', 'those', 'every', 'anyth', 'today', 'tomor', 'soon', 'later', 'week', 'weeke', 'next', 'this', 'after', 'befor', 'somebo', 'somet', 'brain', 'dump', 'list']);
129
+
130
+ /** True when the sentence that holds `said` is about some other to-do (two or more words of its own, none of this item's). */
131
+ function saidAboutAnother(said: string, title: string, transcript: string): boolean {
132
+ const needle = said.toLowerCase();
133
+ const sentence = transcript.split(/(?<=[.!?])\s+/).find((t) => t.toLowerCase().includes(needle));
134
+ if (!sentence) return false;
135
+ const own = new Set(title.split(/\s+/).map(stem));
136
+ const words = [...new Set(sentence.replace(new RegExp(said.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'i'), ' ').split(/\s+/).map(stem))]
137
+ .filter((w) => w.length >= 3 && !STOP.has(w) && !FILLER.has(w));
138
+ return words.length >= 2 && !words.some((w) => own.has(w));
139
+ }
140
+
127
141
  function dueGuess(item: VoiceItem, section: VoiceSection, ctx: DueContext): { due: FieldGuess<string>; priority?: number } {
128
142
  const resolve = (text: string | undefined) => (text ? resolveSpokenTime(text, ctx) : null);
129
143
  const sentence = evidenceSentence(item.title, ctx.transcript);
@@ -136,12 +150,12 @@ function dueGuess(item: VoiceItem, section: VoiceSection, ctx: DueContext): { du
136
150
  const itemLevel = modelWhen?.kind === 'unscheduled' && !heardOpen ? null : modelWhen;
137
151
 
138
152
  // Most specific first. Each level is [text, how it counts, source].
139
- const levels: Array<{ res: SpokenTime | null; source: 'stated' | 'assumed'; cap: number; where: string }> = [
153
+ const levels: Array<{ res: SpokenTime | null; source: 'stated' | 'assumed'; cap: number; where: string; said?: string }> = [
140
154
  { res: itemLevel, source: 'stated', cap: 1, where: 'the speaker' },
141
155
  { res: resolve(item.title), source: 'stated', cap: 1, where: 'the item' },
142
156
  { res: sentence ? resolve(sentence) : null, source: 'stated', cap: 0.9, where: 'the sentence it came from' },
143
- { res: resolve(section.when), source: 'assumed', cap: 0.75, where: 'the section' },
144
- { res: resolve(ctx.noteWhen), source: 'assumed', cap: 0.75, where: 'the note' },
157
+ { res: resolve(section.when), source: 'assumed', cap: 0.75, where: 'the section', said: section.when },
158
+ { res: resolve(ctx.noteWhen), source: 'assumed', cap: 0.75, where: 'the note', said: ctx.noteWhen },
145
159
  { res: noteWideWhen(ctx.transcript, ctx), source: 'assumed', cap: 0.6, where: 'the plan for the day' },
146
160
  ];
147
161
 
@@ -159,9 +173,20 @@ function dueGuess(item: VoiceItem, section: VoiceSection, ctx: DueContext): { du
159
173
  const reason = level.source === 'assumed' ? `${level.where === 'the plan for the day' ? 'the plan for the day' : `${res.phrase} (${level.where})`}` : res.reason;
160
174
  const candidates = res.candidates.map((c) => ({ value: c.dueAt, confidence: c.score, reason: c.reason }));
161
175
  const gap = res.candidates.length > 1 ? res.candidates[0].score - res.candidates[1].score : 1;
162
- const question = gap < AMBIGUITY_GAP
176
+ let question = gap < AMBIGUITY_GAP
163
177
  ? `Due ${fmtCandidate(res.candidates[0])} or ${fmtCandidate(res.candidates[1])}?`
164
178
  : undefined;
179
+ // A date the speaker tied to ANOTHER item, carried here by the note-level "when": a doubtful guess, so ask.
180
+ if (level.source === 'assumed' && level.said && saidAboutAnother(level.said, item.title, ctx.transcript)) {
181
+ const shown = res.time ? `${res.date} ${res.time}` : res.date;
182
+ return {
183
+ due: guessOf(res.dueAt as string, Math.min(confidence, 0.5), 'assumed', `${res.phrase} was said about another item`, {
184
+ candidates: [{ value: res.dueAt as string, confidence: 0.5, reason }, { value: '', confidence: 0.45, reason: 'nothing was said about when for this one' }],
185
+ question: `Is "${item.title}" due ${shown} too, or does it have no date?`, display,
186
+ }),
187
+ priority: res.priority,
188
+ };
189
+ }
165
190
  return {
166
191
  due: guessOf(res.dueAt as string, confidence, level.source, reason, { candidates, question, display }),
167
192
  priority: res.priority,
@@ -24,7 +24,7 @@ export function priorityLabel(priority?: number): string | null {
24
24
  * A `done` or `dropped` item is never overdue however old its date is, because
25
25
  * an overdue count is a list of things to do and a finished item is not one.
26
26
  */
27
- export function isOverdue(item: Commitment, now: number): boolean {
27
+ export function isOverdue(item: Pick<Commitment, 'dueAt' | 'status'>, now: number): boolean {
28
28
  if (!item.dueAt) return false;
29
29
  if (item.status === 'done' || item.status === 'dropped') return false;
30
30
  return Date.parse(item.dueAt) < now;