@startsimpli/integrations 0.2.149 → 0.2.150

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.
@@ -30,6 +30,7 @@ export function ConnectionCard({
30
30
  const [busy, setBusy] = React.useState('');
31
31
  const [error, setError] = React.useState('');
32
32
  const [notice, setNotice] = React.useState('');
33
+ const [checkWhy, setCheckWhy] = React.useState<{ reason: string; next_step: string } | null>(null);
33
34
  /** Sentences the SERVER wrote about the last settings save. Never composed here. */
34
35
  const [notices, setNotices] = React.useState<string[]>([]);
35
36
  const [replacing, setReplacing] = React.useState(false);
@@ -133,8 +134,10 @@ export function ConnectionCard({
133
134
  className={cn.button}
134
135
  disabled={Boolean(busy)}
135
136
  onClick={() => void guard('check', async () => {
137
+ setCheckWhy(null);
136
138
  const res = await api.checkConnection(connection.id);
137
139
  setNotice(res.detail || (res.ok ? 'Connection is healthy.' : ''));
140
+ setCheckWhy(res.reason ? { reason: res.reason, next_step: res.next_step ?? '' } : null);
138
141
  onChanged();
139
142
  })}
140
143
  >
@@ -394,6 +397,15 @@ export function ConnectionCard({
394
397
  </CapabilityPicker>
395
398
 
396
399
  {notice ? <p className={cn.muted}>{notice}</p> : null}
400
+ {/* A key that authenticated but sees nothing: the connector's own words for
401
+ why and what to do (bd startsim-768w.38.16). Generic, so no vendor is named
402
+ here, and `detail` above is never replaced by it. */}
403
+ {checkWhy ? (
404
+ <div className={cn.card} data-check-reason>
405
+ <p className="text-sm text-gray-900">{checkWhy.reason}</p>
406
+ {checkWhy.next_step ? <p className={cn.muted}>{checkWhy.next_step}</p> : null}
407
+ </div>
408
+ ) : null}
397
409
  {/* WHAT THE CHANGE COSTS, in the server's words. Rendered verbatim: this
398
410
  file names no vendor and cannot know which settings restart a walk. */}
399
411
  {notices.map((said) => (
@@ -51,7 +51,7 @@ export interface BoundApi {
51
51
  config?: Record<string, unknown>;
52
52
  capabilities_enabled?: string[];
53
53
  }): Promise<Connection>;
54
- checkConnection(id: string): Promise<{ ok: boolean; account_label: string; detail: string }>;
54
+ checkConnection(id: string): Promise<{ ok: boolean; account_label: string; detail: string; reason?: string; next_step?: string }>;
55
55
  rotateCredential(id: string, credentials: Record<string, unknown>): Promise<Connection>;
56
56
  disconnect(id: string): Promise<void>;
57
57
  updateConnection?(id: string, input: {
@@ -0,0 +1,77 @@
1
+ 'use client';
2
+
3
+ /**
4
+ * A focus's progress over time, drawn by the shared `RangeTimelineChart`
5
+ * (`@startsimpli/ui/insights`) from the tenant's revision trail. See
6
+ * `corpus/focus-history.ts` for what the data is and what it is not.
7
+ *
8
+ * Shown only for a MEASURABLE focus (a target above zero): a qualitative focus has
9
+ * no progress number to chart. `today` is injected and the clock is read once at
10
+ * mount; this never calls `Date.now()` in render.
11
+ */
12
+ import * as React from 'react';
13
+ import { RangeTimelineChart } from '@startsimpli/ui/insights';
14
+
15
+ import { currentValueSeries, loadCurrentValueRevisions, type FocusRevision } from '../../../corpus/focus-history';
16
+ import type { Focus, PlanningApi } from '../../../corpus/types';
17
+
18
+ export interface FocusProgressHistoryProps {
19
+ focus: Focus;
20
+ api: Pick<PlanningApi, 'listFocusRevisions'>;
21
+ /** ISO date the window ends on. Defaults to the day this mounted. */
22
+ today?: string;
23
+ className?: string;
24
+ }
25
+
26
+ type State = { kind: 'loading' } | { kind: 'ready'; revisions: FocusRevision[] } | { kind: 'unavailable' };
27
+
28
+ export function FocusProgressHistory({ focus, api, today, className }: FocusProgressHistoryProps) {
29
+ const [mounted] = React.useState(() => new Date().toISOString().slice(0, 10));
30
+ const anchor = today ?? mounted;
31
+ const [state, setState] = React.useState<State>({ kind: 'loading' });
32
+ const apiRef = React.useRef(api);
33
+ apiRef.current = api;
34
+ const measurable = typeof focus.targetValue === 'number' && focus.targetValue > 0;
35
+ const read = api.listFocusRevisions;
36
+
37
+ React.useEffect(() => {
38
+ if (!read || !measurable) return undefined;
39
+ let live = true;
40
+ setState({ kind: 'loading' });
41
+ loadCurrentValueRevisions((page) => apiRef.current.listFocusRevisions!(focus.id, { page, pageSize: 100 }), anchor)
42
+ .then((revisions) => { if (live) setState({ kind: 'ready', revisions }); })
43
+ .catch(() => { if (live) setState({ kind: 'unavailable' }); });
44
+ return () => { live = false; };
45
+ }, [read, measurable, focus.id, anchor]);
46
+
47
+ const { points, since } = React.useMemo(
48
+ () => (state.kind === 'ready' ? currentValueSeries(state.revisions, anchor) : { points: [] as never[], since: undefined }),
49
+ [state, anchor],
50
+ );
51
+
52
+ if (!read || !measurable) return null;
53
+ return (
54
+ <section className={className ?? 'space-y-2'} aria-label="Progress over time" data-testid="focus-progress-history">
55
+ {state.kind === 'loading' ? <p className="text-sm text-gray-500">Loading progress history…</p> : null}
56
+ {state.kind === 'unavailable' ? (
57
+ <p className="text-sm text-gray-500">Progress history is not available for this workspace yet.</p>
58
+ ) : null}
59
+ {state.kind === 'ready' && points.length === 0 ? (
60
+ <p className="text-sm text-gray-500">No progress changes recorded yet. The chart fills in as the current value is updated.</p>
61
+ ) : null}
62
+ {state.kind === 'ready' && points.length > 0 ? (
63
+ <>
64
+ <RangeTimelineChart
65
+ title="Progress over time"
66
+ points={points}
67
+ anchor={anchor}
68
+ direction="back"
69
+ defaultRange="90d"
70
+ height={240}
71
+ />
72
+ <p className="text-xs text-gray-500">Recorded since {since}. Earlier values were not tracked.</p>
73
+ </>
74
+ ) : null}
75
+ </section>
76
+ );
77
+ }
@@ -0,0 +1,186 @@
1
+ 'use client';
2
+
3
+ /**
4
+ * GOALS - every focus as a goal with its measurable progress
5
+ * (`<GoalsPage api={planningApi} scope={scope} onOpenFocus={...} />`).
6
+ *
7
+ * The table itself is the shared `GoalProgressTable` from
8
+ * `@startsimpli/ui/insights`; this composer only adds what a list over a
9
+ * server needs around it: server-side filter, sort and pagination (CLAUDE.md
10
+ * rule 8), and the row -> focus-detail hand-off. A qualitative focus (no target)
11
+ * reads "No target", never 0%.
12
+ *
13
+ * Nothing here writes. The clock is read once at mount (or injected via `now`),
14
+ * so "overdue" cannot change between renders.
15
+ */
16
+ import * as React from 'react';
17
+ import { GoalProgressTable } from '@startsimpli/ui/insights';
18
+
19
+ import { focusToGoalRow } from '../../../corpus/goal-rows';
20
+ import type { CorpusPage, CorpusScope, Focus, FocusQuery, FocusStatus, PlanningApi } from '../../../corpus/types';
21
+ import { failureMessage } from '../work-items';
22
+
23
+ export interface GoalsPageProps {
24
+ api: Pick<PlanningApi, 'listFocuses'>;
25
+ scope: CorpusScope;
26
+ /** Row click: open this focus's detail (the Planning page's focus view). */
27
+ onOpenFocus?: (focusId: string) => void;
28
+ /** Injectable clock (ms). Defaults to the moment this mounted. */
29
+ now?: number;
30
+ timeZone?: string;
31
+ pageSize?: number;
32
+ classNames?: Partial<Record<'root' | 'toolbar' | 'input' | 'button' | 'muted' | 'error' | 'warning', string>>;
33
+ }
34
+
35
+ const ALL_STATUSES: FocusStatus[] = ['draft', 'active', 'on_track', 'at_risk', 'off_track', 'completed', 'cancelled'];
36
+ /** The default view: everything still in play. Cancelled is one pick away. */
37
+ const IN_PLAY = ALL_STATUSES.filter((s) => s !== 'cancelled');
38
+
39
+ const SORTS: Array<{ value: NonNullable<FocusQuery['orderBy']>; label: string }> = [
40
+ { value: 'progress', label: 'Worst off first' },
41
+ { value: '-progress', label: 'Best off first' },
42
+ { value: 'endDate', label: 'Due date' },
43
+ { value: 'title', label: 'Title' },
44
+ ];
45
+
46
+ const DEFAULTS = {
47
+ root: 'space-y-4',
48
+ toolbar: 'flex flex-wrap items-center gap-2',
49
+ input: 'rounded-md border border-gray-300 px-3 py-1.5 text-sm',
50
+ button: 'rounded-md border border-gray-300 px-3 py-1.5 text-sm font-medium text-gray-800 disabled:opacity-50',
51
+ muted: 'text-sm text-gray-500',
52
+ error: 'text-sm text-red-600',
53
+ warning: 'rounded-md border border-amber-300 bg-amber-50 p-3 text-sm text-amber-900',
54
+ };
55
+
56
+ /** Local calendar day of `ms` in `timeZone` (default UTC). */
57
+ function isoDay(ms: number, timeZone = 'UTC'): string {
58
+ return new Intl.DateTimeFormat('en-CA', { timeZone, year: 'numeric', month: '2-digit', day: '2-digit' }).format(new Date(ms));
59
+ }
60
+
61
+ export function GoalsPage({ api, scope, onOpenFocus, now, timeZone, pageSize = 25, classNames = {} }: GoalsPageProps) {
62
+ const cn = { ...DEFAULTS, ...classNames };
63
+ const [mountedAt] = React.useState(() => Date.now());
64
+ const today = isoDay(now ?? mountedAt, timeZone);
65
+
66
+ const apiRef = React.useRef(api);
67
+ apiRef.current = api;
68
+
69
+ const [statusPick, setStatusPick] = React.useState<'in_play' | 'all' | FocusStatus>('in_play');
70
+ const [orderBy, setOrderBy] = React.useState<NonNullable<FocusQuery['orderBy']>>('progress');
71
+ const [typed, setTyped] = React.useState('');
72
+ const [search, setSearch] = React.useState('');
73
+ const [page, setPage] = React.useState(1);
74
+ const [result, setResult] = React.useState<CorpusPage<Focus> | null>(null);
75
+ const [error, setError] = React.useState('');
76
+ const [loading, setLoading] = React.useState(true);
77
+
78
+ const query = React.useMemo<FocusQuery>(() => ({
79
+ ...(statusPick === 'in_play' ? { status: IN_PLAY } : statusPick === 'all' ? {} : { status: statusPick }),
80
+ ...(search ? { search } : {}),
81
+ orderBy,
82
+ page,
83
+ pageSize,
84
+ }), [statusPick, search, orderBy, page, pageSize]);
85
+
86
+ React.useEffect(() => {
87
+ let live = true;
88
+ setLoading(true);
89
+ setError('');
90
+ apiRef.current.listFocuses(query)
91
+ .then((got) => { if (live) setResult(got); })
92
+ .catch((err) => { if (live) { setResult(null); setError(failureMessage(err)); } })
93
+ .finally(() => { if (live) setLoading(false); });
94
+ return () => { live = false; };
95
+ // `scope.orgId`, not `scope`: a rebuilt scope object must not refetch.
96
+ }, [query, scope.orgId]);
97
+
98
+ const focuses = result?.results ?? [];
99
+ const rows = React.useMemo(() => focuses.map(focusToGoalRow), [focuses]);
100
+ const byId = React.useMemo(() => new Map(focuses.map((f) => [f.id, f])), [focuses]);
101
+ const count = result?.count ?? 0;
102
+ const from = count === 0 ? 0 : (page - 1) * pageSize + 1;
103
+ const to = (page - 1) * pageSize + focuses.length;
104
+
105
+ // [] means the server did not say; only a non-empty report can contradict a filter.
106
+ const applied = result?.appliedFilters ?? [];
107
+ const ignored = applied.length > 0 ? [
108
+ ...(query.status && !applied.some((a) => a.startsWith('attr.status') || a === 'status') ? ['status'] : []),
109
+ ...(query.search && !applied.includes('search') ? ['search'] : []),
110
+ ] : [];
111
+
112
+ const change = <T,>(set: (v: T) => void) => (v: T) => { set(v); setPage(1); };
113
+
114
+ return (
115
+ <div className={cn.root}>
116
+ <form
117
+ className={cn.toolbar}
118
+ role="search"
119
+ onSubmit={(e) => { e.preventDefault(); setSearch(typed.trim()); setPage(1); }}
120
+ >
121
+ <input
122
+ className={cn.input}
123
+ aria-label="Search goals"
124
+ placeholder="Search goals"
125
+ value={typed}
126
+ onChange={(e) => setTyped(e.target.value)}
127
+ />
128
+ <button type="submit" className={cn.button}>Search</button>
129
+ <label className="ml-auto flex items-center gap-2 text-sm">
130
+ Status
131
+ <select
132
+ className={cn.input}
133
+ aria-label="Filter by status"
134
+ value={statusPick}
135
+ onChange={(e) => change(setStatusPick)(e.target.value as typeof statusPick)}
136
+ >
137
+ <option value="in_play">In play</option>
138
+ <option value="all">All statuses</option>
139
+ {ALL_STATUSES.map((s) => <option key={s} value={s}>{s.replace(/_/g, ' ')}</option>)}
140
+ </select>
141
+ </label>
142
+ <label className="flex items-center gap-2 text-sm">
143
+ Sort
144
+ <select
145
+ className={cn.input}
146
+ aria-label="Sort goals"
147
+ value={orderBy}
148
+ onChange={(e) => change(setOrderBy)(e.target.value as typeof orderBy)}
149
+ >
150
+ {SORTS.map((s) => <option key={s.value} value={s.value}>{s.label}</option>)}
151
+ </select>
152
+ </label>
153
+ </form>
154
+
155
+ {ignored.length ? (
156
+ <p className={cn.warning} role="status">
157
+ This workspace’s data API did not filter by {ignored.join(', ')}, so this page may include goals that do not match.
158
+ </p>
159
+ ) : null}
160
+ {error ? <p className={cn.error} role="alert">{error}</p> : null}
161
+
162
+ <GoalProgressTable
163
+ rows={rows}
164
+ // A cancelled goal is not "overdue"; the table only knows done-like
165
+ // statuses, so overdue is not computed while looking at cancelled ones.
166
+ today={statusPick === 'cancelled' ? undefined : today}
167
+ emptyMessage={loading ? 'Loading goals…' : 'No goals match.'}
168
+ onRowClick={onOpenFocus ? (row) => { if (byId.has(row.id)) onOpenFocus(row.id); } : undefined}
169
+ />
170
+
171
+ <div className="flex items-center justify-between">
172
+ <p className={cn.muted} data-testid="goals-range">
173
+ {count === 0 ? '0 goals' : `Showing ${from}–${to} of ${count}`}
174
+ </p>
175
+ <div className="flex gap-2">
176
+ <button type="button" className={cn.button} disabled={loading || page <= 1} onClick={() => setPage((p) => p - 1)}>
177
+ Previous
178
+ </button>
179
+ <button type="button" className={cn.button} disabled={loading || !result?.next} onClick={() => setPage((p) => p + 1)}>
180
+ Next
181
+ </button>
182
+ </div>
183
+ </div>
184
+ </div>
185
+ );
186
+ }
@@ -0,0 +1,4 @@
1
+ export { GoalsPage } from './GoalsPage';
2
+ export type { GoalsPageProps } from './GoalsPage';
3
+ export { FocusProgressHistory } from './FocusProgressHistory';
4
+ export type { FocusProgressHistoryProps } from './FocusProgressHistory';
@@ -266,7 +266,7 @@ export interface ConnectionsApi {
266
266
  config?: Record<string, unknown>;
267
267
  }): Promise<Connection>;
268
268
  checkConnection(slug: string, id: string): Promise<{
269
- ok: boolean; account_label: string; detail: string;
269
+ ok: boolean; account_label: string; detail: string; reason?: string; next_step?: string;
270
270
  }>;
271
271
 
272
272
  /**
@@ -440,7 +440,7 @@ export interface MemberConnectionsApi {
440
440
  id: string, config: Record<string, unknown>,
441
441
  ): Promise<Connection>;
442
442
  checkConnection(id: string): Promise<{
443
- ok: boolean; account_label: string; detail: string;
443
+ ok: boolean; account_label: string; detail: string; reason?: string; next_step?: string;
444
444
  }>;
445
445
  /** Task-tracker connections: push what is pending now (bd startsim-el0zf). Optional for older clients. */
446
446
  syncConnectionNow?(id: string): Promise<{ queued: boolean }>;
@@ -63,6 +63,7 @@ import {
63
63
  focusToEntity,
64
64
  toFocus,
65
65
  } from './planning';
66
+ import { toFocusRevision } from './focus-history';
66
67
  import { commitmentOrder } from './tracker-sort';
67
68
  import type {
68
69
  Commitment,
@@ -1231,6 +1232,7 @@ export function createPlanningApi(options: CreateCorpusApiOptions): PlanningApi
1231
1232
  '-progress': '-attr.progress',
1232
1233
  sortOrder: 'attr.sort_order',
1233
1234
  title: 'attr.title',
1235
+ endDate: 'attr.end_date',
1234
1236
  } as const)[query.orderBy ?? 'progress'],
1235
1237
  };
1236
1238
  if (statuses.length === 1) out['attr.status'] = statuses[0];
@@ -1326,6 +1328,19 @@ export function createPlanningApi(options: CreateCorpusApiOptions): PlanningApi
1326
1328
 
1327
1329
  listFocuses: (query: FocusQuery = {}) => focusPage(focusParams(query)),
1328
1330
 
1331
+ /** Only the saves that touched `current_value` (`?field=` is a key test on the trail). */
1332
+ async listFocusRevisions(focusId: string, query: { page?: number; pageSize?: number } = {}) {
1333
+ const response = await http.get<DrfPage<unknown>>(`${entities}/${encodeURIComponent(focusId)}/revisions/`, {
1334
+ params: { field: 'current_value', page: query.page ?? 1, ...(query.pageSize ? { page_size: Math.min(query.pageSize, 200) } : {}) },
1335
+ });
1336
+ return {
1337
+ count: response.count ?? response.results?.length ?? 0,
1338
+ next: response.next ?? null,
1339
+ previous: response.previous ?? null,
1340
+ results: (response.results ?? []).map(toFocusRevision),
1341
+ };
1342
+ },
1343
+
1329
1344
  /**
1330
1345
  * The children of a focus, one level.
1331
1346
  *
@@ -285,7 +285,9 @@ export function reconcile(
285
285
  // already recorded. A person ticking something off on the screen must
286
286
  // survive the next run, or the screen is a suggestion box.
287
287
  if (!match.ownerName && lead.ownerName) match.ownerName = lead.ownerName;
288
- if (!match.dueAt && lead.dueAt) {
288
+ // A date read from the text goes onto rows the run creates, not onto rows that already
289
+ // exist (bd startsim-768w.38.30): backfilling live rows is a deliberate act of its own.
290
+ if (!match.dueAt && lead.dueAt && !lead.dueOnCreateOnly) {
289
291
  match.dueAt = lead.dueAt;
290
292
  if (lead.dueBasis) match.dueBasis = lead.dueBasis;
291
293
  if (lead.dueConfidence !== undefined) match.dueConfidence = lead.dueConfidence;
@@ -46,6 +46,7 @@ import { applyTeamDecisions, buildTeamRequest } from './classify-team';
46
46
  import { EXTRACTOR_VERSION, applyResolutions, mergeDrafts, reconcile } from './commitments';
47
47
  import { enforceScope } from './retrieval';
48
48
  import { META_LINE, parseItemMeta } from './extraction-fields';
49
+ import { withStatedDue } from './stated-date';
49
50
  import type { ItemMeta } from './extraction-fields';
50
51
  import { documentText, outcomeSections, documentParts, splitSections, words } from './text';
51
52
  import type {
@@ -234,7 +235,7 @@ function toDraft(document: SourceDocument, line: string, detail: string): Commit
234
235
  // document anyway, so nothing is lost by being strict here.
235
236
  if (title.split(/\s+/).length < 3) return null;
236
237
 
237
- return {
238
+ return withStatedDue({
238
239
  documentId: document.id,
239
240
  // Byte-stable: derived from the vendor's own words, never from a model.
240
241
  originKey: `rules:${slug(title)}`,
@@ -247,7 +248,7 @@ function toDraft(document: SourceDocument, line: string, detail: string): Commit
247
248
  // against the record without opening it.
248
249
  quote: line.trim(),
249
250
  extractor: 'rules',
250
- };
251
+ }, document);
251
252
  }
252
253
 
253
254
  const slug = (text: string) =>
@@ -274,9 +275,9 @@ export function extractSystemPrompt(): string {
274
275
  'For every item, copy a short verbatim "quote" from the document it came from, and echo that document\'s exact id. The quote must appear in the document CHARACTER FOR CHARACTER — it is checked, and an item whose quote is not found is discarded.',
275
276
  'Set "subject" to what the item is ABOUT — a matter or case number, a property, a client, a system, a person. Copy an identifier verbatim when the text has one.',
276
277
  'Set "owner" only to a name the document actually names. Leave it out otherwise.',
277
- 'Set "dueAt" only when the document states a date. Never estimate one.',
278
+ 'Never estimate or invent a due date, and do not compute one: the system reads the date itself from your "quote". When the item has a stated date or day ("by 29th July", "tomorrow", "on Monday"), make sure those exact words are inside the quote; when the document states none, say nothing about a date.',
278
279
  'Also report RESOLUTIONS: statements that something previously outstanding is now done or abandoned. Give the subject, what happened, and a verbatim quote.',
279
- 'Respond with JSON only: {"items":[{"documentId":string,"subtype":"action"|"decision"|"need"|"risk"|"question","title":string,"detail":string,"status":"open"|"done"|"blocked","owner":string,"subject":string,"dueAt":string|null,"quote":string}],"resolutions":[{"documentId":string,"subject":string,"statement":string,"quote":string,"outcome":"done"|"dropped"}]}',
280
+ 'Respond with JSON only: {"items":[{"documentId":string,"subtype":"action"|"decision"|"need"|"risk"|"question","title":string,"detail":string,"status":"open"|"done"|"blocked","owner":string,"subject":string,"quote":string}],"resolutions":[{"documentId":string,"subject":string,"statement":string,"quote":string,"outcome":"done"|"dropped"}]}',
280
281
  '"title" must be one short imperative line.',
281
282
  ].join('\n');
282
283
  }
@@ -525,7 +526,9 @@ export async function extractCommitments(
525
526
  promptText,
526
527
  extractor,
527
528
  });
528
- const modelDrafts = checked.kept;
529
+ const documentById = new Map(documents.map((document) => [document.id, document]));
530
+ // The model's own `dueAt` is never read; a stated date is resolved from its quote, in code.
531
+ const modelDrafts = checked.kept.map((item) => withStatedDue(item, documentById.get(item.documentId) ?? { occurredAt: null }));
529
532
 
530
533
  // 5. identity, dedupe within the run, then against what is stored.
531
534
  const groups = mergeDrafts([...ruleDrafts, ...modelDrafts]);
@@ -1008,7 +1011,6 @@ function normaliseItems(
1008
1011
  status: STATUSES.has(status) ? status : 'open',
1009
1012
  ...(owner && owner.length <= 60 ? { ownerName: owner } : {}),
1010
1013
  ...(item.subject ? { subject: String(item.subject).trim() } : {}),
1011
- ...(item.dueAt ? { dueAt: String(item.dueAt) } : {}),
1012
1014
  quote: String(item.quote ?? '').trim(),
1013
1015
  extractor: 'model',
1014
1016
  });
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Progress over time for ONE focus, read from the tenant's append-only revision
3
+ * trail (`GET /entities/<id>/revisions/?field=current_value`, start-simpli-api
4
+ * tenant-starter) - never from a store of our own and never invented.
5
+ *
6
+ * WHAT THE DATA IS: each save that moved `current_value` left a row with
7
+ * `metadata.changed.current_value.{before,after}` and a timestamp. So the series
8
+ * starts at the first RECORDED change; nothing is extrapolated before it, and a
9
+ * focus that never had its value changed has no history to chart.
10
+ */
11
+ import type { TimelinePoint } from '@startsimpli/ui/insights';
12
+ import type { CorpusPage } from './types';
13
+
14
+ export interface FocusRevision {
15
+ version: number;
16
+ createdAt: string;
17
+ actor?: string;
18
+ /** Present only when this save moved `current_value`. */
19
+ currentValue?: { before?: unknown; after?: unknown };
20
+ }
21
+
22
+ type Raw = Record<string, unknown>;
23
+ const asObj = (v: unknown): Raw => (v && typeof v === 'object' && !Array.isArray(v) ? (v as Raw) : {});
24
+
25
+ /** Reads both spellings: the browser client camelCases response keys. */
26
+ export function toFocusRevision(raw: unknown): FocusRevision {
27
+ const r = asObj(raw);
28
+ const changed = asObj(asObj(r.metadata).changed);
29
+ const cv = changed.current_value ?? changed.currentValue;
30
+ const actor = r.actor_label ?? r.actorLabel ?? r.actor_sub ?? r.actorSub;
31
+ return {
32
+ version: Number(r.version) || 0,
33
+ createdAt: String(r.created_at ?? r.createdAt ?? ''),
34
+ ...(typeof actor === 'string' && actor ? { actor } : {}),
35
+ ...(cv && typeof cv === 'object' ? { currentValue: cv as { before?: unknown; after?: unknown } } : {}),
36
+ };
37
+ }
38
+
39
+ function num(v: unknown): number | undefined {
40
+ if (typeof v === 'number') return Number.isFinite(v) ? v : undefined;
41
+ if (typeof v === 'string' && v.trim()) {
42
+ const n = Number(v);
43
+ return Number.isFinite(n) ? n : undefined;
44
+ }
45
+ return undefined;
46
+ }
47
+
48
+ const day = (iso: string) => iso.slice(0, 10);
49
+
50
+ /**
51
+ * Chart points, oldest first. Each day carries its end-of-day value and one
52
+ * event per save (delta = after - before). The last value is held to `anchor` so
53
+ * a short window is not empty; that is the value persisting, not a new fact.
54
+ * No numeric change recorded -> no points (never a flat line).
55
+ */
56
+ export function currentValueSeries(
57
+ revisions: FocusRevision[],
58
+ anchor: string,
59
+ ): { points: TimelinePoint[]; since?: string } {
60
+ const changes = revisions
61
+ .filter((r) => r.currentValue && num(r.currentValue.after) !== undefined && r.createdAt)
62
+ .sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.version - b.version);
63
+ if (!changes.length) return { points: [] };
64
+ const byDay = new Map<string, TimelinePoint>();
65
+ for (const r of changes) {
66
+ const after = num(r.currentValue!.after) as number;
67
+ const before = num(r.currentValue!.before) ?? 0;
68
+ const d = day(r.createdAt);
69
+ const point = byDay.get(d) ?? { date: d, value: after, events: [] };
70
+ point.value = after;
71
+ point.events = [...(point.events ?? []), {
72
+ id: `rev-${r.version}`,
73
+ label: r.actor ? `Updated by ${r.actor}` : 'Updated',
74
+ delta: after - before,
75
+ }];
76
+ byDay.set(d, point);
77
+ }
78
+ const points = [...byDay.values()];
79
+ const last = points[points.length - 1];
80
+ if (last.date < anchor) points.push({ date: anchor, value: last.value, events: [] });
81
+ return { points, since: points[0].date };
82
+ }
83
+
84
+ const WINDOW_DAYS = 90;
85
+ const DAY_MS = 86_400_000;
86
+
87
+ /**
88
+ * Reads revision pages (newest first) until one reaches back past the longest
89
+ * window or the trail ends. Server-paginated; no fixed page cap.
90
+ */
91
+ export async function loadCurrentValueRevisions(
92
+ fetchPage: (page: number) => Promise<CorpusPage<FocusRevision>>,
93
+ anchor: string,
94
+ ): Promise<FocusRevision[]> {
95
+ const cutoff = new Date(Date.parse(`${anchor}T00:00:00Z`) - WINDOW_DAYS * DAY_MS).toISOString().slice(0, 10);
96
+ const out: FocusRevision[] = [];
97
+ for (let page = 1; ; page += 1) {
98
+ const got = await fetchPage(page);
99
+ out.push(...got.results);
100
+ const oldest = got.results.at(-1)?.createdAt;
101
+ if (!got.next || got.results.length === 0 || (oldest && day(oldest) < cutoff)) break;
102
+ }
103
+ return out;
104
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Focus -> the shared goal-table row (`@startsimpli/ui/insights` GoalRow).
3
+ *
4
+ * THE ONE RULE: "no target" stays "no target". A qualitative focus has no
5
+ * `targetValue`; the table shows it as "No target" and never as 0%. So target and
6
+ * current are sent only together and only when the target is a positive number.
7
+ * Item counts (`FocusStanding`) and the stored `progress` field are NOT mapped
8
+ * into them: that would turn a qualitative focus into a measurable one.
9
+ */
10
+ import type { GoalRow } from '@startsimpli/ui/insights';
11
+ import { focusStatusLabel } from './planning';
12
+ import type { Focus } from './types';
13
+
14
+ export function focusToGoalRow(focus: Focus): GoalRow {
15
+ const measurable = typeof focus.targetValue === 'number' && focus.targetValue > 0;
16
+ const subtype = focus.subtype || focus.category;
17
+ return {
18
+ id: focus.id,
19
+ title: focus.title,
20
+ ...(subtype ? { subtype } : {}),
21
+ ...(focus.ownerName ? { owner: focus.ownerName } : {}),
22
+ ...(focus.endDate ? { due: focus.endDate.slice(0, 10) } : {}),
23
+ status: focusStatusLabel(focus.status),
24
+ ...(measurable
25
+ ? { target: focus.targetValue as number, current: focus.currentValue ?? 0 }
26
+ : {}),
27
+ ...(measurable && focus.unit ? { unit: focus.unit } : {}),
28
+ };
29
+ }
@@ -288,6 +288,9 @@ export * from './briefing';
288
288
  // Spoken time -> due dates, and the per-field guesses extraction reports (bd startsim-b7kir).
289
289
  export { isTimeZone, noteWideWhen, resolveSpokenTime } from './spoken-time';
290
290
  export type { SpokenCandidate, SpokenConfidence, SpokenTime } from './spoken-time';
291
+ // Dates a meeting states -> due dates (bd startsim-768w.38.30).
292
+ export { resolveStatedDate, withStatedDue } from './stated-date';
293
+ export type { StatedDate, StatedDateOptions } from './stated-date';
291
294
  export { AMBIGUITY_GAP, openQuestions } from './extraction-fields';
292
295
  export type { FieldCandidate, FieldGuess, FieldSource, ItemFields } from './extraction-fields';
293
296
  export { resolveSectionFields } from './voice-due';
@@ -301,6 +304,9 @@ export type { TrackerEntry, TrackerGroups } from './tracker-groups';
301
304
  export { DEFAULT_TRACKER_SORT, TRACKER_SORTS, commitmentOrder, compareCommitments } from './tracker-sort';
302
305
  export { summarizeFocuses } from './focus-overview';
303
306
  export type { FocusSummary } from './focus-overview';
307
+ export { focusToGoalRow } from './goal-rows';
308
+ export { currentValueSeries, loadCurrentValueRevisions, toFocusRevision } from './focus-history';
309
+ export type { FocusRevision } from './focus-history';
304
310
  export { actionsByNote } from './note-actions';
305
311
  export type { NoteActions } from './note-actions';
306
312
 
@@ -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
  };