@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.
@@ -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
+ }
@@ -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
  }>;
@@ -1464,7 +1472,7 @@ export interface FocusQuery {
1464
1472
  owner?: string;
1465
1473
  search?: string;
1466
1474
  /** `progress` ascending is worst-off first, which is the useful default. */
1467
- orderBy?: 'progress' | '-progress' | 'sortOrder' | 'title';
1475
+ orderBy?: 'progress' | '-progress' | 'sortOrder' | 'title' | 'endDate';
1468
1476
  page?: number;
1469
1477
  pageSize?: number;
1470
1478
  }
@@ -1498,6 +1506,12 @@ export interface PlanningApi extends CommitmentApi {
1498
1506
  /** Move a document to another project, or `null` to unfile. */
1499
1507
  fileDocument?(documentId: string, focusId: string | null): Promise<void>;
1500
1508
  listFocuses(query?: FocusQuery): Promise<CorpusPage<Focus>>;
1509
+ /**
1510
+ * The saves that moved a focus's `current_value`, newest first, server-paginated
1511
+ * (the tenant's revision trail). Absent where the tenant has no trail; the
1512
+ * progress chart then says history is unavailable rather than drawing one.
1513
+ */
1514
+ listFocusRevisions?(focusId: string, query?: { page?: number; pageSize?: number }): Promise<CorpusPage<FocusRevision>>;
1501
1515
  createFocus?(draft: FocusDraft): Promise<Focus>;
1502
1516
  /** Takes the row for the same reason `updateCommitment` does. */
1503
1517
  updateFocus?(focus: Focus, patch: Partial<FocusDraft>): Promise<Focus>;