@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
@@ -55,9 +55,9 @@ export interface SpokenContext { now: number; timeZone?: string }
55
55
 
56
56
  const pad = (n: number) => String(n).padStart(2, '0');
57
57
 
58
- interface Local { date: string; hour: number; minute: number; weekday: number }
58
+ export interface Local { date: string; hour: number; minute: number; weekday: number }
59
59
 
60
- function localParts(instant: number, timeZone: string): Local {
60
+ export function localParts(instant: number, timeZone: string): Local {
61
61
  const parts = new Intl.DateTimeFormat('en-US', {
62
62
  timeZone, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hourCycle: 'h23', weekday: 'short',
63
63
  }).formatToParts(new Date(instant));
@@ -66,13 +66,13 @@ function localParts(instant: number, timeZone: string): Local {
66
66
  return { date: `${get('year')}-${get('month')}-${get('day')}`, hour: Number(get('hour')), minute: Number(get('minute')), weekday };
67
67
  }
68
68
 
69
- function addDays(date: string, days: number): string {
69
+ export function addDays(date: string, days: number): string {
70
70
  const [y, m, d] = date.split('-').map(Number);
71
71
  const t = new Date(Date.UTC(y, m - 1, d + days));
72
72
  return `${t.getUTCFullYear()}-${pad(t.getUTCMonth() + 1)}-${pad(t.getUTCDate())}`;
73
73
  }
74
74
 
75
- const weekdayOf = (date: string): number => {
75
+ export const weekdayOf = (date: string): number => {
76
76
  const [y, m, d] = date.split('-').map(Number);
77
77
  return new Date(Date.UTC(y, m - 1, d)).getUTCDay();
78
78
  };
@@ -0,0 +1,187 @@
1
+ /**
2
+ * DATES A MEETING STATES -> DUE DATES (bd startsim-768w.38.30). Pure, model-free.
3
+ *
4
+ * "Complete the equity item today", "pay it by 29th July", "send it on Monday"
5
+ * carry a date; the extractor used to drop all of them (0 of 19 on the live
6
+ * tenant). Resolution belongs in code, anchored to the MEETING's own date: a
7
+ * small model gets "next Friday" wrong about one time in four, and `today` is
8
+ * only a date because the meeting happened on a particular day.
9
+ *
10
+ * THE RULE THIS FILE EXISTS TO KEEP: it reads what was SAID and never estimates.
11
+ * - Resolved: a calendar date, today, tomorrow, the day after tomorrow, a
12
+ * weekday name, "in N days/weeks".
13
+ * - Left unset (returns null): spans ("next week", "end of the month"),
14
+ * urgency ("asap", "urgently"), vague counts ("in a few days"), a weekday
15
+ * said on that same weekday (today or a week on?), "next <weekday>" (two
16
+ * readings), past references ("last Friday", "3 days ago"), a bare month,
17
+ * an impossible date, a yearless date that is far from the meeting (the year
18
+ * would be a guess), and any text that states two DIFFERENT dates.
19
+ *
20
+ * Distinct from `spoken-time.ts`, which resolves a voice note's phrases for the
21
+ * speaker and is deliberately willing to approximate ("next week" -> Friday).
22
+ * A meeting record is evidence about somebody else's work; it only gets a
23
+ * deadline when one was stated.
24
+ */
25
+ import type { CommitmentDraft, SourceDocument } from './types';
26
+ import { addDays, localParts, weekdayOf, zonedInstant } from './spoken-time';
27
+
28
+ export interface StatedDate {
29
+ /** ISO-8601 UTC, zero-padded, so range filters and sorts compare lexicographically. End of the stated day. */
30
+ dueAt: string;
31
+ /** Local `YYYY-MM-DD` of the stated day. */
32
+ date: string;
33
+ /** The words matched. */
34
+ phrase: string;
35
+ kind: 'absolute' | 'relative';
36
+ /** Why this date, for the row's `dueBasis`. */
37
+ basis: string;
38
+ /** 0..1. */
39
+ confidence: number;
40
+ }
41
+
42
+ export interface StatedDateOptions { timeZone?: string }
43
+
44
+ const pad = (n: number) => String(n).padStart(2, '0');
45
+ const WEEKDAYS = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
46
+ const MONTHS = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'];
47
+ const MONTH_RE = MONTHS.map((m) => (m.length > 3 ? `${m.slice(0, 3)}(?:${m.slice(3)})?` : m)).join('|');
48
+ const WD_RE = WEEKDAYS.join('|');
49
+ const NUMBER_WORDS: Record<string, number> = { a: 1, an: 1, one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9, ten: 10 };
50
+ /** A year-less date further than this from the meeting is not reliably this year or next. */
51
+ const MAX_YEARLESS_DISTANCE_DAYS = 120;
52
+
53
+ interface Hit { date: string; phrase: string; kind: 'absolute' | 'relative'; confidence: number; reason: string }
54
+
55
+ const dayNumber = (date: string): number => {
56
+ const [y, m, d] = date.split('-').map(Number);
57
+ return Math.round(Date.UTC(y, m - 1, d) / 86_400_000);
58
+ };
59
+
60
+ function validDate(y: number, m: number, d: number): string | null {
61
+ if (m < 1 || m > 12 || d < 1 || d > 31 || y < 1970 || y > 2200) return null;
62
+ const t = new Date(Date.UTC(y, m - 1, d));
63
+ if (t.getUTCMonth() !== m - 1 || t.getUTCDate() !== d) return null;
64
+ return `${y}-${pad(m)}-${pad(d)}`;
65
+ }
66
+
67
+ const monthIndex = (word: string): number => MONTHS.findIndex((m) => m.startsWith(word.toLowerCase().slice(0, 3))) + 1;
68
+
69
+ /** The year for a date said without one: the occurrence closest to the meeting, or null when even that is far. */
70
+ function yearlessDate(month: number, day: number, today: string | null): string | null {
71
+ if (!today) return null;
72
+ const ty = Number(today.slice(0, 4));
73
+ let best: { date: string; gap: number } | null = null;
74
+ for (const year of [ty - 1, ty, ty + 1]) {
75
+ const date = validDate(year, month, day);
76
+ if (!date) continue;
77
+ const gap = Math.abs(dayNumber(date) - dayNumber(today));
78
+ if (!best || gap < best.gap) best = { date, gap };
79
+ }
80
+ return best && best.gap <= MAX_YEARLESS_DISTANCE_DAYS ? best.date : null;
81
+ }
82
+
83
+ function absoluteHits(text: string, today: string | null): { hits: Hit[]; blocked: boolean } {
84
+ const hits: Hit[] = [];
85
+ let blocked = false;
86
+ const push = (date: string | null, phrase: string) => {
87
+ if (date) hits.push({ date, phrase, kind: 'absolute', confidence: 0.95, reason: `said "${phrase}"` });
88
+ else blocked = true; // a date was written but cannot be a real day: say nothing rather than guess
89
+ };
90
+ let m: RegExpExecArray | null;
91
+
92
+ const iso = /\b(\d{4})-(\d{2})-(\d{2})\b/g;
93
+ while ((m = iso.exec(text))) push(validDate(Number(m[1]), Number(m[2]), Number(m[3])), m[0]);
94
+
95
+ // "29th July", "29 of July 2026"
96
+ const dayFirst = new RegExp(`\\b(\\d{1,2})(?:st|nd|rd|th)?(?: of)? (${MONTH_RE})\\b\\.?(?:,? (\\d{4})\\b)?`, 'gi');
97
+ while ((m = dayFirst.exec(text))) {
98
+ const month = monthIndex(m[2]);
99
+ const day = Number(m[1]);
100
+ push(m[3] ? validDate(Number(m[3]), month, day) : yearlessDate(month, day, today), m[0].replace(/\.$/, ''));
101
+ }
102
+ // "July 29", "Oct 29th, 2027"
103
+ const monthFirst = new RegExp(`\\b(${MONTH_RE})\\.? (\\d{1,2})(?:st|nd|rd|th)?\\b(?!:)(?:,? (\\d{4})\\b)?`, 'gi');
104
+ while ((m = monthFirst.exec(text))) {
105
+ const month = monthIndex(m[1]);
106
+ const day = Number(m[2]);
107
+ push(m[3] ? validDate(Number(m[3]), month, day) : yearlessDate(month, day, today), m[0]);
108
+ }
109
+ return { hits, blocked };
110
+ }
111
+
112
+ function relativeHits(text: string, today: string): Hit[] {
113
+ const hits: Hit[] = [];
114
+ const wd = weekdayOf(today);
115
+ const rel = (date: string, phrase: string, confidence: number) =>
116
+ hits.push({ date, phrase, kind: 'relative', confidence, reason: `said "${phrase.toLowerCase()}" in a meeting held ${today}` });
117
+ let m: RegExpExecArray | null;
118
+
119
+ if ((m = /\bday after tomorrow\b/.exec(text))) rel(addDays(today, 2), m[0], 0.95);
120
+ else if ((m = /\btomorrow\b/.exec(text))) rel(addDays(today, 1), m[0], 0.95);
121
+ if ((m = /\b(?:today|tonight|this (?:morning|afternoon|evening)|end of (?:the )?day|eod)\b/.exec(text))) rel(today, m[0], 0.9);
122
+
123
+ // A weekday NAME. "next <weekday>" has two readings and "last <weekday>" is the past: neither resolves.
124
+ const named = new RegExp(`(?:\\b(next|last|previous) )?\\b(${WD_RE})\\b(?!\\.\\w|\\s+(?:night\\b|'s))`, 'g');
125
+ while ((m = named.exec(text))) {
126
+ if (m[1]) { hits.push({ date: '', phrase: m[0], kind: 'relative', confidence: 0, reason: 'ambiguous' }); continue; }
127
+ const before = text.slice(0, m.index).trimEnd();
128
+ // Only where it is a deadline-style use: "by/on/before/until/this/for Monday".
129
+ if (!/(?:\b(?:by|on|before|until|till|this|for|due)|^)$/.test(before)) continue;
130
+ const ahead = (WEEKDAYS.indexOf(m[2]) - wd + 7) % 7;
131
+ if (ahead === 0) { hits.push({ date: '', phrase: m[0], kind: 'relative', confidence: 0, reason: 'ambiguous' }); continue; }
132
+ rel(addDays(today, ahead), m[0], 0.85);
133
+ }
134
+
135
+ const inN = /\bin (\d+|an?|one|two|three|four|five|six|seven|eight|nine|ten) (day|week)s?\b/g;
136
+ while ((m = inN.exec(text))) {
137
+ const n = /^\d+$/.test(m[1]) ? Number(m[1]) : NUMBER_WORDS[m[1]];
138
+ rel(addDays(today, m[2] === 'day' ? n : n * 7), m[0], 0.9);
139
+ }
140
+ return hits;
141
+ }
142
+
143
+ /** Past references anywhere in the text make a relative phrase's tense uncertain. */
144
+ const PAST_REFERENCE = /\b(?:last|previous|yesterday|ago)\b/;
145
+
146
+ export function resolveStatedDate(text: string, anchor: string | number | Date | null | undefined, options: StatedDateOptions = {}): StatedDate | null {
147
+ const flat = (text ?? '').replace(/\*\*/g, '').replace(/\s+/g, ' ').trim();
148
+ if (!flat) return null;
149
+ const lower = flat.toLowerCase();
150
+ const timeZone = options.timeZone || 'UTC';
151
+
152
+ const at = anchor === null || anchor === undefined || anchor === '' ? NaN : new Date(anchor as string).getTime();
153
+ const today = Number.isFinite(at) ? localParts(at, timeZone).date : null;
154
+
155
+ const abs = absoluteHits(flat, today);
156
+ const rels = today ? relativeHits(lower, today) : [];
157
+ if (abs.blocked || rels.some((h) => h.reason === 'ambiguous')) return null;
158
+ if (rels.length && PAST_REFERENCE.test(lower)) return null;
159
+ const hits = [...abs.hits, ...rels];
160
+ if (!hits.length) return null;
161
+
162
+ const dates = new Set(hits.map((h) => h.date));
163
+ if (dates.size > 1) return null;
164
+
165
+ const top = hits.sort((a, b) => b.confidence - a.confidence)[0];
166
+ const instant = new Date(zonedInstant(top.date, '23:59', timeZone) + 59_000).toISOString().replace('.000Z', 'Z');
167
+ return {
168
+ dueAt: instant,
169
+ date: top.date,
170
+ phrase: top.phrase,
171
+ kind: top.kind,
172
+ basis: top.reason,
173
+ confidence: top.confidence,
174
+ };
175
+ }
176
+
177
+ /**
178
+ * Carry onto the draft the due date its own words state (bd startsim-768w.38.30), resolved in code
179
+ * against the meeting's date. Never the model's say-so, never an estimate: no stated date, no `dueAt`.
180
+ * A date already on the draft (a voice note's resolved field) is left alone.
181
+ */
182
+ export function withStatedDue(draft: CommitmentDraft, document: Pick<SourceDocument, 'occurredAt'>): CommitmentDraft {
183
+ if (draft.dueAt) return draft;
184
+ const stated = resolveStatedDate([draft.title, draft.quote, draft.detail].filter(Boolean).join(' \n '), document.occurredAt);
185
+ if (!stated) return draft;
186
+ return { ...draft, dueAt: stated.dueAt, dueBasis: stated.basis, dueConfidence: stated.confidence, dueOnCreateOnly: true };
187
+ }
@@ -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
+ }
@@ -25,6 +25,7 @@
25
25
  * attribute names shift, `./entities.ts` is the one file that changes.
26
26
  */
27
27
  import type { ItemSync } from '../task-tracker/item-sync';
28
+ import type { FocusRevision } from './focus-history';
28
29
 
29
30
  /**
30
31
  * Which connector filled a record. FREE-FORM on purpose — `granola`, `dropbox`,
@@ -792,6 +793,12 @@ export interface CommitmentDraft {
792
793
  ownerName?: string;
793
794
  subject?: string;
794
795
  dueAt?: string | null;
796
+ /**
797
+ * True when `dueAt` was READ FROM THE SOURCE TEXT by `stated-date.ts` (bd startsim-768w.38.30).
798
+ * Such a date goes onto a row the run CREATES and is never filled onto a row that already
799
+ * exists: backfilling live rows is a separate, deliberate act.
800
+ */
801
+ dueOnCreateOnly?: boolean;
795
802
  /** 0 critical .. 4 lowest; only when the source signalled it. */
796
803
  priority?: number;
797
804
  /** Minutes, in total, when a length of time was spoken. */
@@ -1080,6 +1087,7 @@ export interface ExtractionDraft {
1080
1087
  status?: string;
1081
1088
  owner?: string;
1082
1089
  subject?: string;
1090
+ /** IGNORED: the model never supplies a date. It is read from the quote by `stated-date.ts`. Kept so older adapters still type-check. */
1083
1091
  dueAt?: string | null;
1084
1092
  quote?: string;
1085
1093
  }>;
@@ -1097,6 +1105,16 @@ export interface ExtractionDraft {
1097
1105
  * handler; the handler runs the extraction server-side, where the key lives.
1098
1106
  */
1099
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>;
1100
1118
  /**
1101
1119
  * Run ONE slice of extraction and wait for it.
1102
1120
  *
@@ -1464,7 +1482,7 @@ export interface FocusQuery {
1464
1482
  owner?: string;
1465
1483
  search?: string;
1466
1484
  /** `progress` ascending is worst-off first, which is the useful default. */
1467
- orderBy?: 'progress' | '-progress' | 'sortOrder' | 'title';
1485
+ orderBy?: 'progress' | '-progress' | 'sortOrder' | 'title' | 'endDate';
1468
1486
  page?: number;
1469
1487
  pageSize?: number;
1470
1488
  }
@@ -1498,6 +1516,12 @@ export interface PlanningApi extends CommitmentApi {
1498
1516
  /** Move a document to another project, or `null` to unfile. */
1499
1517
  fileDocument?(documentId: string, focusId: string | null): Promise<void>;
1500
1518
  listFocuses(query?: FocusQuery): Promise<CorpusPage<Focus>>;
1519
+ /**
1520
+ * The saves that moved a focus's `current_value`, newest first, server-paginated
1521
+ * (the tenant's revision trail). Absent where the tenant has no trail; the
1522
+ * progress chart then says history is unavailable rather than drawing one.
1523
+ */
1524
+ listFocusRevisions?(focusId: string, query?: { page?: number; pageSize?: number }): Promise<CorpusPage<FocusRevision>>;
1501
1525
  createFocus?(draft: FocusDraft): Promise<Focus>;
1502
1526
  /** Takes the row for the same reason `updateCommitment` does. */
1503
1527
  updateFocus?(focus: Focus, patch: Partial<FocusDraft>): Promise<Focus>;
@@ -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;