@startsimpli/integrations 0.2.150 → 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.
@@ -0,0 +1,94 @@
1
+ /**
2
+ * The timeline's server reads. The point of every case: the browser asks the
3
+ * tenant for GROUPED COUNTS and one capped page of rows per series, and never
4
+ * walks the whole list.
5
+ */
6
+ import { describe, expect, it, vi } from 'vitest';
7
+
8
+ import { createTimelineReader } from '../corpus/tracker-timeline-client';
9
+
10
+ const NOW = Date.parse('2026-11-07T15:00:00Z');
11
+ const clock = { now: NOW, timeZone: 'UTC' };
12
+
13
+ type Call = { path: string; params: Record<string, unknown> };
14
+
15
+ function fakeHttp(counts: Record<string, Array<[string | null, number]>> = {}, rows: Array<Record<string, unknown>> = []) {
16
+ const calls: Call[] = [];
17
+ const get = vi.fn(async (path: string, opts?: { params?: Record<string, unknown> }) => {
18
+ const params = opts?.params ?? {};
19
+ calls.push({ path, params });
20
+ if (path.endsWith('/counts')) {
21
+ const all = counts[String(params.group_by)] ?? [];
22
+ const page = Number(params.page ?? 1);
23
+ const slice = all.slice((page - 1) * 2, page * 2);
24
+ return { results: slice.map(([v, c]) => ({ values: [v], count: c })), next: page * 2 < all.length ? 'more' : null, groupBy: [params.group_by] };
25
+ }
26
+ return { count: rows.length, results: rows, next: null };
27
+ });
28
+ return { http: { get } as never, calls };
29
+ }
30
+
31
+ const read = (http: never, filter = {}) =>
32
+ createTimelineReader({ http, type: 'commitment' })(filter, clock);
33
+
34
+ describe('createTimelineReader', () => {
35
+ it('asks for a grouped count per series on the counts endpoint', async () => {
36
+ const { http, calls } = fakeHttp({ 'attr.first_seen_at': [['2026-11-05T10:00:00Z', 3]] });
37
+ const out = await read(http);
38
+ const counted = calls.filter((c) => c.path === 'api/v1/entities/counts').map((c) => c.params.group_by).sort();
39
+ expect(counted).toEqual(['attr.due_at', 'attr.first_seen_at', 'attr.resolved_at']);
40
+ expect(calls.every((c) => c.params.type === 'commitment')).toBe(true);
41
+ expect(out.created).toEqual([{ value: '2026-11-05T10:00:00Z', count: 3 }]);
42
+ expect(out.anchor).toBe('2026-11-07');
43
+ });
44
+
45
+ it('follows the counts pages, not just the first', async () => {
46
+ const many: Array<[string, number]> = ['2026-11-01', '2026-11-02', '2026-11-03', '2026-11-04', '2026-11-05'].map((d) => [d, 1]);
47
+ const { http, calls } = fakeHttp({ 'attr.due_at': many });
48
+ const out = await read(http);
49
+ expect(out.overdue).toHaveLength(5);
50
+ expect(calls.filter((c) => c.params.group_by === 'attr.due_at')).toHaveLength(3);
51
+ });
52
+
53
+ it('reads at most one capped page of rows per series, never everything', async () => {
54
+ const { http, calls } = fakeHttp();
55
+ await read(http);
56
+ const lists = calls.filter((c) => c.path === 'api/v1/entities');
57
+ expect(lists.length).toBe(4); // created, done, estimated done, overdue
58
+ expect(lists.every((c) => Number(c.params.page_size) <= 200 && c.params.page === undefined)).toBe(true);
59
+ });
60
+
61
+ it('looks for already-done rows with no resolved_at, windowed by their last update', async () => {
62
+ const { http, calls } = fakeHttp();
63
+ await read(http);
64
+ const est = calls.find((c) => c.params['attr.resolved_at__isnull'] === 'true')!;
65
+ expect(est.params).toMatchObject({ 'attr.status': 'done' });
66
+ expect(est.params.updated_after).toBeDefined();
67
+ expect(est.params.group_by).toBeUndefined();
68
+ });
69
+
70
+ it('maps rows to timeline items, with updated_at for the estimate', async () => {
71
+ const { http } = fakeHttp({}, [
72
+ { id: 'c1', name: 'Send proposal', updated_at: '2026-11-06T09:00:00Z', data: { title: 'Send proposal', status: 'done', first_seen_at: '2026-11-01', due_at: null } },
73
+ ]);
74
+ const out = await read(http);
75
+ expect(out.items).toEqual([
76
+ { id: 'c1', title: 'Send proposal', status: 'done', dueAt: null, firstSeenAt: '2026-11-01', resolvedAt: null, updatedAt: '2026-11-06T09:00:00Z' },
77
+ ]);
78
+ });
79
+
80
+ it('makes no request for a series the filter empties, and carries the filter to the rest', async () => {
81
+ const { http, calls } = fakeHttp();
82
+ await read(http, { status: 'blocked', search: 'invoice' });
83
+ expect(calls.some((c) => c.params.group_by === 'attr.resolved_at')).toBe(false);
84
+ expect(calls.some((c) => c.params['attr.resolved_at__isnull'] === 'true')).toBe(false);
85
+ expect(calls.every((c) => c.params.search === 'invoice')).toBe(true);
86
+ });
87
+
88
+ it('says when a series had more rows than the page it read', async () => {
89
+ const http = { get: vi.fn(async (path: string) => (path.endsWith('/counts')
90
+ ? { results: [], next: null }
91
+ : { count: 450, results: [], next: 'x' })) } as never;
92
+ expect((await read(http)).truncated).toBe(true);
93
+ });
94
+ });
@@ -0,0 +1,209 @@
1
+ /**
2
+ * The Tracker timeline's arithmetic: which day a thing lands on, what counts as
3
+ * overdue, and what an empty window looks like. Pure, so every case here is a
4
+ * way the strip could draw a wrong number while the data underneath is fine.
5
+ */
6
+ import { describe, expect, it } from 'vitest';
7
+
8
+ import {
9
+ TIMELINE_DAYS,
10
+ bucketCounts,
11
+ buildTimeline,
12
+ completionOf,
13
+ dayOf,
14
+ timelineParams,
15
+ windowDayList,
16
+ type TimelineItem,
17
+ } from '../corpus/tracker-timeline';
18
+
19
+ const NOW = Date.parse('2026-11-07T15:00:00Z');
20
+
21
+ describe('dayOf', () => {
22
+ it('keeps a date-only value as it is', () => {
23
+ expect(dayOf('2026-11-03', 'America/Los_Angeles')).toBe('2026-11-03');
24
+ });
25
+ it('puts an instant on the reader’s local day, not UTC', () => {
26
+ // 02:00Z on the 4th is still the evening of the 3rd in Los Angeles.
27
+ expect(dayOf('2026-11-04T02:00:00Z', 'America/Los_Angeles')).toBe('2026-11-03');
28
+ expect(dayOf('2026-11-04T02:00:00Z', 'UTC')).toBe('2026-11-04');
29
+ });
30
+ it('is null for nothing or nonsense', () => {
31
+ expect(dayOf(null)).toBeNull();
32
+ expect(dayOf('not a date')).toBeNull();
33
+ });
34
+ });
35
+
36
+ describe('windowDayList', () => {
37
+ it('is the anchor day and the days before it, oldest first', () => {
38
+ expect(windowDayList('2026-11-07', 3)).toEqual(['2026-11-05', '2026-11-06', '2026-11-07']);
39
+ });
40
+ it('crosses a month boundary', () => {
41
+ expect(windowDayList('2026-03-01', 2)).toEqual(['2026-02-28', '2026-03-01']);
42
+ });
43
+ });
44
+
45
+ describe('bucketCounts', () => {
46
+ it('merges distinct timestamps that fall on one local day', () => {
47
+ const out = bucketCounts(
48
+ [
49
+ { value: '2026-11-04T02:00:00Z', count: 2 },
50
+ { value: '2026-11-03T20:00:00Z', count: 3 },
51
+ { value: '2026-11-04T09:00:00Z', count: 1 },
52
+ { value: null, count: 9 },
53
+ ],
54
+ 'America/Los_Angeles',
55
+ );
56
+ expect(out.get('2026-11-03')).toBe(5);
57
+ expect(out.get('2026-11-04')).toBe(1);
58
+ expect(out.size).toBe(2);
59
+ });
60
+ });
61
+
62
+ const item = (over: Partial<TimelineItem> & { id: string }): TimelineItem => ({
63
+ title: `Item ${over.id}`,
64
+ status: 'open',
65
+ dueAt: null,
66
+ firstSeenAt: null,
67
+ resolvedAt: null,
68
+ updatedAt: null,
69
+ ...over,
70
+ });
71
+
72
+ describe('completionOf', () => {
73
+ it('uses resolved_at when the item has one', () => {
74
+ expect(completionOf(item({ id: 'a', status: 'done', resolvedAt: '2026-11-05T10:00:00Z', updatedAt: '2026-11-06T10:00:00Z' }), 'UTC'))
75
+ .toEqual({ day: '2026-11-05', estimated: false });
76
+ });
77
+ it('falls back to updated_at and says it is an estimate', () => {
78
+ expect(completionOf(item({ id: 'a', status: 'done', updatedAt: '2026-11-06T10:00:00Z' }), 'UTC'))
79
+ .toEqual({ day: '2026-11-06', estimated: true });
80
+ });
81
+ it('is null for an item that is not done', () => {
82
+ expect(completionOf(item({ id: 'a', status: 'open', resolvedAt: '2026-11-05T10:00:00Z' }), 'UTC')).toBeNull();
83
+ });
84
+ });
85
+
86
+ describe('buildTimeline', () => {
87
+ const empty = { created: [], done: [], overdue: [], items: [] };
88
+
89
+ it('is a zero-filled series for every day of the window when nothing happened', () => {
90
+ const t = buildTimeline({ ...empty, anchor: '2026-11-07' }, NOW, 'UTC');
91
+ expect(t.series.map((s) => s.id)).toEqual(['created', 'done', 'overdue']);
92
+ for (const s of t.series) {
93
+ expect(s.points).toHaveLength(TIMELINE_DAYS);
94
+ expect(s.points.every((p) => p.value === 0)).toBe(true);
95
+ expect(s.points[TIMELINE_DAYS - 1].date).toBe('2026-11-07');
96
+ }
97
+ expect(t.points).toEqual([]);
98
+ expect(t.estimatedDone).toBe(0);
99
+ });
100
+
101
+ it('puts counts on their day', () => {
102
+ const t = buildTimeline(
103
+ {
104
+ ...empty, anchor: '2026-11-07',
105
+ created: [{ value: '2026-11-05T10:00:00Z', count: 4 }],
106
+ done: [{ value: '2026-11-06', count: 2 }],
107
+ overdue: [{ value: '2026-11-01', count: 1 }],
108
+ },
109
+ NOW, 'UTC',
110
+ );
111
+ const at = (id: string, d: string) => t.series.find((s) => s.id === id)!.points.find((p) => p.date === d)!.value;
112
+ expect(at('created', '2026-11-05')).toBe(4);
113
+ expect(at('done', '2026-11-06')).toBe(2);
114
+ expect(at('overdue', '2026-11-01')).toBe(1);
115
+ expect(at('overdue', '2026-11-05')).toBe(0);
116
+ });
117
+
118
+ it('ignores counts older than the longest window', () => {
119
+ const t = buildTimeline({ ...empty, anchor: '2026-11-07', created: [{ value: '2026-01-01', count: 7 }] }, NOW, 'UTC');
120
+ expect(t.series[0].points.reduce((s, p) => s + p.value, 0)).toBe(0);
121
+ });
122
+
123
+ it('adds estimated completions to the done series and reports how many', () => {
124
+ const t = buildTimeline(
125
+ {
126
+ ...empty, anchor: '2026-11-07',
127
+ done: [{ value: '2026-11-06', count: 1 }],
128
+ items: [item({ id: 'old', status: 'done', updatedAt: '2026-11-06T09:00:00Z' })],
129
+ },
130
+ NOW, 'UTC',
131
+ );
132
+ const done = t.series.find((s) => s.id === 'done')!;
133
+ expect(done.points.find((p) => p.date === '2026-11-06')!.value).toBe(2);
134
+ expect(t.estimatedDone).toBe(1);
135
+ });
136
+
137
+ describe('overdue rule', () => {
138
+ const events = (items: TimelineItem[]) =>
139
+ buildTimeline({ ...empty, anchor: '2026-11-07', items }, NOW, 'UTC').points.flatMap((p) => p.events ?? []);
140
+
141
+ it('lists an open item past its date as overdue on its due day', () => {
142
+ const ev = events([item({ id: 'a', dueAt: '2026-11-02' })]);
143
+ expect(ev).toHaveLength(1);
144
+ expect(ev[0]).toMatchObject({ id: 'overdue:a', category: 'overdue', status: 'Overdue', delta: 0, tone: 'down' });
145
+ });
146
+ it('never lists a done or dropped item as overdue', () => {
147
+ expect(events([item({ id: 'a', status: 'done', dueAt: '2026-11-02' })]).filter((e) => e.category === 'overdue')).toEqual([]);
148
+ expect(events([item({ id: 'b', status: 'dropped', dueAt: '2026-11-02' })]).filter((e) => e.category === 'overdue')).toEqual([]);
149
+ });
150
+ it('does not list an item due in the future', () => {
151
+ expect(events([item({ id: 'a', dueAt: '2026-11-20' })]).filter((e) => e.category === 'overdue')).toEqual([]);
152
+ });
153
+ });
154
+
155
+ it('lists the to-dos as events and groups them under their day', () => {
156
+ const t = buildTimeline(
157
+ {
158
+ ...empty, anchor: '2026-11-07',
159
+ items: [
160
+ item({ id: 'a', firstSeenAt: '2026-11-05T10:00:00Z' }),
161
+ item({ id: 'b', firstSeenAt: '2026-11-05T12:00:00Z', status: 'done', resolvedAt: '2026-11-06T08:00:00Z' }),
162
+ ],
163
+ },
164
+ NOW, 'UTC',
165
+ );
166
+ const day5 = t.points.find((p) => p.date === '2026-11-05')!;
167
+ expect(day5.events!.map((e) => e.id).sort()).toEqual(['created:a', 'created:b']);
168
+ expect(day5.value).toBe(2);
169
+ expect(t.points.find((p) => p.date === '2026-11-06')!.events![0]).toMatchObject({ id: 'done:b', status: 'Done', tone: 'up' });
170
+ });
171
+ });
172
+
173
+ describe('timelineParams', () => {
174
+ const base = { now: NOW, timeZone: 'UTC' };
175
+
176
+ it('asks the server for each series, windowed and grouped by the date attribute', () => {
177
+ const p = timelineParams('created', {}, base);
178
+ expect(p).toMatchObject({ group_by: 'attr.first_seen_at' });
179
+ expect(p['attr.first_seen_at__gte']).toBe('2026-08-09');
180
+ });
181
+
182
+ it('counts only done items for the done series', () => {
183
+ expect(timelineParams('done', {}, base)).toMatchObject({ group_by: 'attr.resolved_at', 'attr.status': 'done' });
184
+ });
185
+
186
+ it('counts only owed items past their date for the overdue series', () => {
187
+ const p = timelineParams('overdue', {}, base);
188
+ expect(p).toMatchObject({ group_by: 'attr.due_at', 'attr.status__in': 'open,in_progress,blocked' });
189
+ expect(p['attr.due_at__lt']).toBe('2026-11-07T15:00:00.000Z');
190
+ });
191
+
192
+ it('carries the page’s filters to every series', () => {
193
+ const p = timelineParams('created', { search: 'proposal', owner: 'Rae' }, base);
194
+ expect(p).toMatchObject({ search: 'proposal', 'attr.owner_name__icontains': 'Rae' });
195
+ });
196
+
197
+ it('narrows to the chosen status, and a done-only series has nothing under a blocked chip', () => {
198
+ expect(timelineParams('created', { status: 'blocked' }, base)).toMatchObject({ 'attr.status': 'blocked' });
199
+ expect(timelineParams('done', { status: 'blocked' }, base)).toBeNull();
200
+ expect(timelineParams('overdue', { status: 'blocked' }, base)).toMatchObject({ 'attr.status': 'blocked' });
201
+ });
202
+
203
+ it('the overdue chip narrows every series to owed items past their date', () => {
204
+ const c = timelineParams('created', { overdueOnly: true }, base);
205
+ expect(c).toMatchObject({ 'attr.status__in': 'open,in_progress,blocked' });
206
+ expect(c!['attr.due_at__lt']).toBe('2026-11-07T15:00:00.000Z');
207
+ expect(timelineParams('done', { overdueOnly: true }, base)).toBeNull();
208
+ });
209
+ });
@@ -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
+ }
@@ -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 ?? '';
@@ -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
+ }