@startsimpli/integrations 0.2.148 → 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,238 @@
1
+ /**
2
+ * LIABILITIES — one generic entity for anything owed, and the mapping from it to
3
+ * the payoff engine (bd startsim-a01ps.8, under startsim-a01ps).
4
+ *
5
+ * THE SHAPE. A tenant stores a `liability` entity with a FREE-TEXT `subtype`
6
+ * (credit_card, mortgage, student_loan, auto_loan, ...), so a new kind of debt
7
+ * costs a string and not a table. Everything the payoff engine needs is on the
8
+ * entity itself: balance, apr, min_payment. Kind-specific remainder (escrow,
9
+ * PMI, servicer address) lives in one `details` bag that no shared logic reads.
10
+ *
11
+ * A SCENARIO IS A FOCUS, not a new type: a `focus` with subtype
12
+ * `payoff_scenario` whose `params` are {strategy, monthly_payment, start_date}.
13
+ * Variants of a plan are child focuses (the existing `sub_focus` edge). The
14
+ * schedule itself is never stored; `runPayoffScenario` computes it.
15
+ *
16
+ * PURE and React-free: this file is reachable from the native build through the
17
+ * corpus barrel. The engine call lives in `liability-plan.ts`.
18
+ */
19
+ import type { PayoffDebt, PayoffStrategy } from '@startsimpli/utils';
20
+ import { ORIGIN, ORIGIN_KEY, type TenantEntity } from './entities';
21
+ import type { CorpusScope, Focus, FocusDraft } from './types';
22
+
23
+ /** The entity type key, matching `scripts/schemas/liabilities.json`. */
24
+ export const LIABILITY_TYPE = 'liability';
25
+ /** The focus subtype that makes a focus a payoff scenario. */
26
+ export const PAYOFF_SCENARIO = 'payoff_scenario';
27
+
28
+ export type LiabilityStatus = 'active' | 'deferred' | 'paid_off' | 'closed';
29
+ const STATUSES: readonly LiabilityStatus[] = ['active', 'deferred', 'paid_off', 'closed'];
30
+ const STRATEGIES: readonly PayoffStrategy[] = ['avalanche', 'snowball'];
31
+
32
+ export interface Liability {
33
+ id: string;
34
+ externalId: string;
35
+ title: string;
36
+ /** Free text. Nothing but display branches on it. */
37
+ subtype: string;
38
+ status: LiabilityStatus;
39
+ institution?: string;
40
+ currency?: string;
41
+ /** Absent means unknown, which is not the same as 0 (paid). */
42
+ balance?: number;
43
+ /** Annual percent, e.g. 19.99. */
44
+ apr?: number;
45
+ minPayment?: number;
46
+ nextDueDate?: string;
47
+ lastPaymentAmount?: number;
48
+ lastPaymentDate?: string;
49
+ creditLimit?: number;
50
+ originalPrincipal?: number;
51
+ originationDate?: string;
52
+ maturityDate?: string;
53
+ pastDueAmount?: number;
54
+ details?: Record<string, unknown>;
55
+ scope: CorpusScope;
56
+ }
57
+
58
+ export type LiabilityDraft = Partial<Omit<Liability, 'id' | 'externalId' | 'scope'>> & { title: string };
59
+
60
+ // ---------------------------------------------------------------------------
61
+ // reading
62
+ // ---------------------------------------------------------------------------
63
+
64
+ function bag(entity: TenantEntity): Record<string, unknown> {
65
+ const data = entity.data;
66
+ return data && typeof data === 'object' ? (data as Record<string, unknown>) : {};
67
+ }
68
+
69
+ /** snake_case first, camelCase second: the api client may have converted keys. */
70
+ function pick(data: Record<string, unknown>, snake: string): unknown {
71
+ const camel = snake.replace(/_([a-z])/g, (_m, c: string) => c.toUpperCase());
72
+ for (const key of [snake, camel]) {
73
+ const value = data[key];
74
+ if (value !== undefined && value !== null && value !== '') return value;
75
+ }
76
+ return undefined;
77
+ }
78
+
79
+ function text(value: unknown): string | undefined {
80
+ return typeof value === 'string' && value ? value : undefined;
81
+ }
82
+
83
+ function num(value: unknown): number | undefined {
84
+ if (typeof value === 'number') return Number.isFinite(value) ? value : undefined;
85
+ if (typeof value === 'string' && value.trim()) {
86
+ const parsed = Number(value);
87
+ return Number.isFinite(parsed) ? parsed : undefined;
88
+ }
89
+ return undefined;
90
+ }
91
+
92
+ function defined<T extends object>(obj: T): Partial<T> {
93
+ return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== undefined)) as Partial<T>;
94
+ }
95
+
96
+ export function toLiability(entity: TenantEntity, fallbackScope: CorpusScope): Liability {
97
+ const d = bag(entity);
98
+ const status = text(pick(d, 'status'));
99
+ const details = pick(d, 'details');
100
+ return {
101
+ id: String(entity.id),
102
+ externalId: String(entity.external_id ?? entity.externalId ?? `${LIABILITY_TYPE}:${entity.id}`),
103
+ title: text(pick(d, 'title')) || entity.name || 'Untitled liability',
104
+ subtype: text(pick(d, 'subtype')) || 'other',
105
+ // `active` is the floor: a debt whose status did not survive a round trip is
106
+ // still owed, and hiding it from the plan would understate what is owed.
107
+ status: (STATUSES as readonly string[]).includes(status ?? '') ? (status as LiabilityStatus) : 'active',
108
+ ...defined({
109
+ institution: text(pick(d, 'institution')),
110
+ currency: text(pick(d, 'currency')),
111
+ balance: num(pick(d, 'balance')),
112
+ apr: num(pick(d, 'apr')),
113
+ minPayment: num(pick(d, 'min_payment')),
114
+ nextDueDate: text(pick(d, 'next_due_date')),
115
+ lastPaymentAmount: num(pick(d, 'last_payment_amount')),
116
+ lastPaymentDate: text(pick(d, 'last_payment_date')),
117
+ creditLimit: num(pick(d, 'credit_limit')),
118
+ originalPrincipal: num(pick(d, 'original_principal')),
119
+ originationDate: text(pick(d, 'origination_date')),
120
+ maturityDate: text(pick(d, 'maturity_date')),
121
+ pastDueAmount: num(pick(d, 'past_due_amount')),
122
+ details: details && typeof details === 'object' && !Array.isArray(details)
123
+ ? (details as Record<string, unknown>) : undefined,
124
+ }),
125
+ scope: { orgId: String(entity.org_id ?? entity.orgId ?? fallbackScope.orgId), ...(fallbackScope.ownerSub ? { ownerSub: fallbackScope.ownerSub } : {}) },
126
+ };
127
+ }
128
+
129
+ // ---------------------------------------------------------------------------
130
+ // writing
131
+ // ---------------------------------------------------------------------------
132
+
133
+ /** Draft key -> the declared attribute that carries it. The write AND the patch map. */
134
+ export const LIABILITY_ATTRIBUTES: Record<string, keyof LiabilityDraft> = {
135
+ subtype: 'subtype',
136
+ status: 'status',
137
+ institution: 'institution',
138
+ currency: 'currency',
139
+ balance: 'balance',
140
+ apr: 'apr',
141
+ min_payment: 'minPayment',
142
+ next_due_date: 'nextDueDate',
143
+ last_payment_amount: 'lastPaymentAmount',
144
+ last_payment_date: 'lastPaymentDate',
145
+ credit_limit: 'creditLimit',
146
+ original_principal: 'originalPrincipal',
147
+ origination_date: 'originationDate',
148
+ maturity_date: 'maturityDate',
149
+ past_due_amount: 'pastDueAmount',
150
+ details: 'details',
151
+ };
152
+
153
+ export function liabilityToEntity(draft: LiabilityDraft, externalId: string, options: { create?: boolean } = {}): {
154
+ entity_type: string;
155
+ external_id: string;
156
+ name: string;
157
+ data: Record<string, unknown>;
158
+ } {
159
+ const title = draft.title.trim() || 'Untitled liability';
160
+ const data: Record<string, unknown> = { title };
161
+ for (const [attr, key] of Object.entries(LIABILITY_ATTRIBUTES)) {
162
+ const value = draft[key];
163
+ if (value !== undefined && value !== null) data[attr] = value;
164
+ }
165
+ if (options.create !== false) {
166
+ // Defaults only on create: merging them into a patch would reopen a closed debt.
167
+ data.status ??= 'active';
168
+ data.subtype ??= 'other';
169
+ data[ORIGIN_KEY] = ORIGIN.authored;
170
+ }
171
+ return { entity_type: LIABILITY_TYPE, external_id: externalId, name: title.slice(0, 200), data };
172
+ }
173
+
174
+ // ---------------------------------------------------------------------------
175
+ // -> the payoff engine
176
+ // ---------------------------------------------------------------------------
177
+
178
+ /**
179
+ * One liability as the engine's debt, or `null` when a plan cannot pay it down:
180
+ * not `active`, or nothing owed. A missing apr/minimum is 0 rather than a reason
181
+ * to drop the debt, because dropping it would make the plan finish early.
182
+ */
183
+ export function liabilityToPayoffDebt(l: Liability): PayoffDebt | null {
184
+ if (l.status !== 'active') return null;
185
+ if (l.balance === undefined || !(l.balance > 0)) return null;
186
+ return { id: l.id, name: l.title, balance: l.balance, apr: l.apr ?? 0, minPayment: l.minPayment ?? 0 };
187
+ }
188
+
189
+ export function liabilitiesToPayoffDebts(ls: readonly Liability[]): PayoffDebt[] {
190
+ return ls.map(liabilityToPayoffDebt).filter((d): d is PayoffDebt => d !== null);
191
+ }
192
+
193
+ // ---------------------------------------------------------------------------
194
+ // scenario <-> focus
195
+ // ---------------------------------------------------------------------------
196
+
197
+ export interface PayoffScenarioParams {
198
+ strategy: PayoffStrategy;
199
+ /** Total per month across all debts; absent means "just the minimums". */
200
+ monthlyPayment?: number;
201
+ /** ISO date of the first payment month. */
202
+ startDate?: string;
203
+ }
204
+
205
+ /** A scenario as the focus draft that stores it. `parentId` nests it under the plan it varies. */
206
+ export function scenarioFocusDraft(
207
+ title: string,
208
+ params: PayoffScenarioParams,
209
+ options: { parentId?: string } = {},
210
+ ): FocusDraft {
211
+ return {
212
+ title,
213
+ category: 'financial',
214
+ subtype: PAYOFF_SCENARIO,
215
+ params: {
216
+ strategy: params.strategy,
217
+ ...(params.monthlyPayment !== undefined ? { monthly_payment: params.monthlyPayment } : {}),
218
+ ...(params.startDate ? { start_date: params.startDate } : {}),
219
+ },
220
+ ...(options.parentId ? { parentId: options.parentId } : {}),
221
+ };
222
+ }
223
+
224
+ /** The scenario a focus describes, or `null` when it is not one or its params are unusable. */
225
+ export function scenarioParamsFromFocus(focus: Pick<Focus, 'subtype' | 'params'>): PayoffScenarioParams | null {
226
+ if (focus.subtype !== PAYOFF_SCENARIO || !focus.params) return null;
227
+ const strategy = text(pick(focus.params, 'strategy'));
228
+ if (!strategy || !(STRATEGIES as readonly string[]).includes(strategy)) return null;
229
+ const raw = pick(focus.params, 'monthly_payment');
230
+ const monthlyPayment = num(raw);
231
+ if (raw !== undefined && (monthlyPayment === undefined || monthlyPayment < 0)) return null;
232
+ const startDate = text(pick(focus.params, 'start_date'));
233
+ return {
234
+ strategy: strategy as PayoffStrategy,
235
+ ...(monthlyPayment !== undefined ? { monthlyPayment } : {}),
236
+ ...(startDate ? { startDate } : {}),
237
+ };
238
+ }
@@ -0,0 +1,101 @@
1
+ /**
2
+ * The tenant client for liabilities (bd startsim-a01ps.8).
3
+ *
4
+ * Its own file because `client.ts` is already past the size budget, and a
5
+ * deployment can have planning with no liabilities schema at all. Every write is
6
+ * the shallow-merging upsert keyed on `external_id`, the one tenant verb that
7
+ * preserves keys the caller did not send.
8
+ */
9
+ import { authoredId } from './planning';
10
+ import type { CorpusHttp, CreateCorpusApiOptions } from './client';
11
+ import type { TenantEntity } from './entities';
12
+ import {
13
+ LIABILITY_TYPE,
14
+ liabilityToEntity,
15
+ toLiability,
16
+ type Liability,
17
+ type LiabilityDraft,
18
+ type LiabilityStatus,
19
+ } from './liabilities';
20
+ import type { CorpusPage } from './types';
21
+
22
+ export interface LiabilityQuery {
23
+ status?: LiabilityStatus | LiabilityStatus[];
24
+ subtype?: string;
25
+ search?: string;
26
+ page?: number;
27
+ pageSize?: number;
28
+ }
29
+
30
+ export interface LiabilityApi {
31
+ listLiabilities(query?: LiabilityQuery): Promise<CorpusPage<Liability>>;
32
+ createLiability?(draft: LiabilityDraft): Promise<Liability>;
33
+ /** Takes the row so the external id is the row's own; sends only the keys in `patch`. */
34
+ updateLiability?(liability: Liability, patch: Partial<LiabilityDraft>): Promise<Liability>;
35
+ }
36
+
37
+ interface Page {
38
+ count?: number;
39
+ next?: string | null;
40
+ previous?: string | null;
41
+ results?: TenantEntity[];
42
+ applied_filters?: string[];
43
+ appliedFilters?: string[];
44
+ }
45
+
46
+ export function createLiabilityApi(options: Pick<CreateCorpusApiOptions, 'http' | 'scope' | 'paths'>): LiabilityApi {
47
+ const { http, scope } = options;
48
+ const entities = options.paths?.entities ?? 'api/v1/entities';
49
+ const writer = (): NonNullable<CorpusHttp['post']> => {
50
+ if (!http.post) throw new Error('This liability client is read-only — no write method was supplied.');
51
+ return http.post.bind(http);
52
+ };
53
+
54
+ return {
55
+ async listLiabilities(query: LiabilityQuery = {}) {
56
+ const statuses = Array.isArray(query.status) ? query.status : query.status ? [query.status] : [];
57
+ const params: Record<string, unknown> = {
58
+ type: LIABILITY_TYPE,
59
+ page: query.page ?? 1,
60
+ // Largest balance first: the debts that matter most lead the page.
61
+ order: '-attr.balance',
62
+ ...(query.pageSize ? { page_size: Math.min(query.pageSize, 200) } : {}),
63
+ };
64
+ if (statuses.length === 1) params['attr.status'] = statuses[0];
65
+ else if (statuses.length > 1) params['attr.status__in'] = statuses.join(',');
66
+ if (query.subtype) params['attr.subtype'] = query.subtype;
67
+ if (query.search) params.search = query.search.slice(0, 200);
68
+ const response = await http.get<Page>(entities, { params });
69
+ return {
70
+ count: response.count ?? response.results?.length ?? 0,
71
+ next: response.next ?? null,
72
+ previous: response.previous ?? null,
73
+ results: (response.results ?? []).map((e) => toLiability(e, scope)),
74
+ appliedFilters: response.applied_filters ?? response.appliedFilters ?? [],
75
+ };
76
+ },
77
+
78
+ async createLiability(draft) {
79
+ const created = await writer()<TenantEntity>(
80
+ `${entities}/upsert`,
81
+ liabilityToEntity(draft, `${LIABILITY_TYPE}:${authoredId()}`),
82
+ );
83
+ return toLiability(created, scope);
84
+ },
85
+
86
+ async updateLiability(liability, patch) {
87
+ const body = liabilityToEntity(
88
+ { ...patch, title: patch.title ?? liability.title },
89
+ liability.externalId,
90
+ { create: false },
91
+ );
92
+ const updated = await writer()<TenantEntity>(`${entities}/upsert`, {
93
+ entity_type: LIABILITY_TYPE,
94
+ external_id: liability.externalId,
95
+ ...(patch.title ? { name: body.name } : {}),
96
+ data: body.data,
97
+ });
98
+ return toLiability(updated, scope);
99
+ },
100
+ };
101
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Runs a payoff scenario over liabilities with the SHARED engine
3
+ * (`buildPayoffSchedule`, @startsimpli/utils). Nothing is reimplemented here:
4
+ * this is the join between the tenant's rows and the engine's input.
5
+ */
6
+ import { buildPayoffSchedule } from '@startsimpli/utils';
7
+ import type { PayoffDebt, PayoffSchedule } from '@startsimpli/utils';
8
+ import { liabilitiesToPayoffDebts, type Liability, type PayoffScenarioParams } from './liabilities';
9
+
10
+ export interface PayoffScenarioRun {
11
+ debts: PayoffDebt[];
12
+ /** `{id, name}` pairs in the shape `@startsimpli/ui/payoff` takes. */
13
+ labels: Array<{ id: string; name: string }>;
14
+ schedule: PayoffSchedule;
15
+ /** The budget actually used: the scenario's, or the sum of minimums. */
16
+ monthlyPayment: number;
17
+ startingBalance: number;
18
+ }
19
+
20
+ export function runPayoffScenario(
21
+ liabilities: readonly Liability[],
22
+ params: PayoffScenarioParams,
23
+ ): PayoffScenarioRun {
24
+ const debts = liabilitiesToPayoffDebts(liabilities);
25
+ const minimums = debts.reduce((sum, d) => sum + d.minPayment, 0);
26
+ const monthlyPayment = params.monthlyPayment ?? minimums;
27
+ const schedule = buildPayoffSchedule({
28
+ debts,
29
+ monthlyPayment,
30
+ strategy: params.strategy,
31
+ ...(params.startDate ? { startDate: params.startDate } : {}),
32
+ });
33
+ return {
34
+ debts,
35
+ labels: debts.map((d) => ({ id: d.id, name: d.name ?? d.id })),
36
+ schedule,
37
+ monthlyPayment,
38
+ startingBalance: debts.reduce((sum, d) => sum + d.balance, 0),
39
+ };
40
+ }
@@ -120,6 +120,10 @@ function num(value: unknown): number | undefined {
120
120
  return undefined;
121
121
  }
122
122
 
123
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
124
+ return !!value && typeof value === 'object' && !Array.isArray(value);
125
+ }
126
+
123
127
  function oneOf<T extends string>(value: unknown, allowed: readonly T[]): T | undefined {
124
128
  const raw = text(value);
125
129
  return (allowed as readonly string[]).includes(raw) ? (raw as T) : undefined;
@@ -147,6 +151,8 @@ export function toFocus(entity: TenantEntity, fallbackScope: CorpusScope): Focus
147
151
  status: oneOf(pick(data, 'status'), FOCUS_STATUSES) ?? 'draft',
148
152
  ...(oneOf(pick(data, 'category'), FOCUS_CATEGORIES)
149
153
  ? { category: oneOf(pick(data, 'category'), FOCUS_CATEGORIES) } : {}),
154
+ ...(pick(data, 'subtype') ? { subtype: text(pick(data, 'subtype')) } : {}),
155
+ ...(isPlainObject(data.params) ? { params: data.params } : {}),
150
156
  ...(oneOf(pick(data, 'time_frame', 'timeFrame'), FOCUS_TIME_FRAMES)
151
157
  ? { timeFrame: oneOf(pick(data, 'time_frame', 'timeFrame'), FOCUS_TIME_FRAMES) } : {}),
152
158
  ...(year !== undefined ? { year } : {}),
@@ -186,6 +192,8 @@ export function focusToEntity(draft: FocusDraft, externalId?: string): {
186
192
  ...(draft.detail ? { detail: draft.detail } : {}),
187
193
  status: draft.status ?? 'active',
188
194
  ...(draft.category ? { category: draft.category } : {}),
195
+ ...(draft.subtype ? { subtype: draft.subtype } : {}),
196
+ ...(draft.params ? { params: draft.params } : {}),
189
197
  ...(draft.timeFrame ? { time_frame: draft.timeFrame } : {}),
190
198
  ...(draft.year !== undefined && draft.year !== null ? { year: draft.year } : {}),
191
199
  ...(draft.startDate ? { start_date: draft.startDate } : {}),
@@ -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
+ }