@startsimpli/integrations 0.2.127 → 0.2.129

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/package.json +5 -5
  2. package/src/__tests__/commitment-edit.test.ts +67 -0
  3. package/src/__tests__/connections-me-client.test.ts +8 -0
  4. package/src/__tests__/corpus-tracker.test.tsx +1 -1
  5. package/src/__tests__/today-selector.test.ts +60 -0
  6. package/src/api/connections.ts +9 -0
  7. package/src/components/pages/PlanningPage.tsx +1 -1
  8. package/src/components/pages/TrackerPage.tsx +2 -2
  9. package/src/components/pages/types.ts +2 -0
  10. package/src/corpus/briefing/actions/confirm.ts +1 -1
  11. package/src/corpus/briefing/actions/execute.ts +1 -1
  12. package/src/corpus/briefing/compose.ts +8 -23
  13. package/src/corpus/briefing/intent/dates.ts +1 -1
  14. package/src/corpus/briefing/intent/describe.ts +1 -1
  15. package/src/corpus/briefing/intent/grammar.ts +1 -1
  16. package/src/corpus/briefing/intent/ground.ts +1 -1
  17. package/src/corpus/briefing/intent/model.ts +1 -1
  18. package/src/corpus/client.ts +16 -1
  19. package/src/corpus/commitment-edit.ts +65 -0
  20. package/src/corpus/commitments.ts +1 -1
  21. package/src/corpus/entities.ts +1 -1
  22. package/src/corpus/index.ts +3 -0
  23. package/src/corpus/today.ts +73 -0
  24. package/src/corpus/types.ts +2 -1
  25. package/src/native/corpus/display.ts +1 -1
  26. package/src/native/corpus/fake-tenant.ts +12 -0
  27. package/src/native/screens/planning/controller.ts +1 -1
  28. package/src/native/tracker/TrackerListScreen.tsx +2 -2
  29. package/src/native/tracker/__tests__/controller.test.ts +4 -4
  30. package/src/native/tracker/__tests__/detail.test.ts +5 -2
  31. package/src/native/tracker/__tests__/format.test.ts +3 -3
  32. package/src/native/tracker/format.ts +2 -2
  33. package/src/native/voice/http.ts +7 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@startsimpli/integrations",
3
- "version": "0.2.127",
3
+ "version": "0.2.129",
4
4
  "description": "Provider-agnostic types, API clients, hooks, and UI primitives for email + calendar integrations across StartSimpli apps, plus foundry customer email (subpath ./comms).",
5
5
  "license": "MIT",
6
6
  "homepage": "https://startsimpli.com",
@@ -50,9 +50,9 @@
50
50
  "react-native": ">=0.74.0",
51
51
  "@startsimpli/ui-native": ">=0.1.12",
52
52
  "react-native-safe-area-context": ">=4.0.0",
53
- "@startsimpli/ui": "^0.4.171",
53
+ "@startsimpli/utils": "^0.4.17",
54
54
  "@startsimpli/auth": "^0.4.50",
55
- "@startsimpli/utils": "^0.4.17"
55
+ "@startsimpli/ui": "^0.4.171"
56
56
  },
57
57
  "peerDependenciesMeta": {
58
58
  "react": {
@@ -98,11 +98,11 @@
98
98
  "vitest": "^3.0.0",
99
99
  "react-native": "0.85.3",
100
100
  "react-native-safe-area-context": "~5.7.0",
101
- "@startsimpli/llm": "0.4.30",
102
101
  "@startsimpli/ui": "0.4.171",
103
102
  "@startsimpli/ui-native": "0.1.14",
104
103
  "@startsimpli/auth": "0.4.50",
105
- "@startsimpli/utils": "0.4.17"
104
+ "@startsimpli/utils": "0.4.17",
105
+ "@startsimpli/llm": "0.4.30"
106
106
  },
107
107
  "scripts": {
108
108
  "type-check": "tsc --noEmit && tsc --noEmit -p tsconfig.native.json",
@@ -0,0 +1,67 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { createPlanningApi } from '../corpus/client';
3
+ import { editedData } from '../corpus/commitment-edit';
4
+ import type { Commitment } from '../corpus/types';
5
+
6
+ const NOW = Date.parse('2026-11-05T10:00:00.000Z');
7
+ const stored = (data: Record<string, unknown>) => ({
8
+ id: 'c1', entity_type: 'commitment', external_id: 'item:c1', name: 'Call John', version: 4,
9
+ data: { title: 'Call John', status: 'open', ...data },
10
+ });
11
+
12
+ describe('editedData', () => {
13
+ it('lays the edit over the stored blob and stamps only the tracker-owned fields', () => {
14
+ const out = editedData(stored({ owner_name: 'Quinn' }), { due_at: '2026-11-06', owner_name: 'Q' }, NOW);
15
+ expect(out).toMatchObject({ title: 'Call John', owner_name: 'Q', due_at: '2026-11-06' });
16
+ expect(out.field_edited_at).toEqual({ due_at: '2026-11-05T10:00:00.000Z' });
17
+ });
18
+
19
+ it('keeps earlier stamps and moves a linked item to pending', () => {
20
+ const out = editedData(stored({ external_id: 'r1', sync_state: 'synced', field_edited_at: { status: 'old' } }), { due_at: null }, NOW);
21
+ expect(out.sync_state).toBe('pending');
22
+ expect(out.field_edited_at).toEqual({ status: 'old', due_at: '2026-11-05T10:00:00.000Z' });
23
+ });
24
+
25
+ it('a new edit clears the failure backoff so the drain pushes it now', () => {
26
+ const out = editedData(stored({ external_id: 'r1', sync_state: 'error', sync_error: 'boom', sync_attempts: 5, sync_next_at: 'later' }), { priority: 0 }, NOW);
27
+ expect(out).toMatchObject({ sync_state: 'pending' });
28
+ expect(out).not.toHaveProperty('sync_error');
29
+ expect(out).not.toHaveProperty('sync_attempts');
30
+ expect(out).not.toHaveProperty('sync_next_at');
31
+ });
32
+
33
+ it('leaves an unlinked item unsynced', () => {
34
+ expect(editedData(stored({}), { status: 'done' }, NOW).sync_state).toBeUndefined();
35
+ });
36
+
37
+ it('does not resurrect a remotely deleted item', () => {
38
+ expect(editedData(stored({ external_id: 'r1', sync_state: 'remote_deleted' }), { status: 'done' }, NOW).sync_state).toBe('remote_deleted');
39
+ });
40
+ });
41
+
42
+ describe('updateCommitment over a client that can PATCH', () => {
43
+ const scope = { orgId: 'o' } as never;
44
+ const row = { id: 'c1', externalId: 'item:c1' } as Commitment;
45
+
46
+ it('GETs then PATCHes the whole blob under the row version, never the upsert door', async () => {
47
+ const get = vi.fn().mockResolvedValue(stored({}));
48
+ const patch = vi.fn().mockImplementation(async (_p: string, body: { data: object }) => ({ ...stored({}), data: body.data }));
49
+ const post = vi.fn();
50
+ const api = createPlanningApi({ http: { get, post, patch } as never, scope });
51
+ await api.updateCommitment!(row, { dueAt: '2026-11-06' });
52
+ expect(post).not.toHaveBeenCalled();
53
+ expect(patch).toHaveBeenCalledTimes(1);
54
+ const [path, body] = patch.mock.calls[0];
55
+ expect(path).toBe('api/v1/entities/c1');
56
+ expect(body.expected_version).toBe(4);
57
+ expect(body.data).toMatchObject({ title: 'Call John', due_at: '2026-11-06' });
58
+ expect(Object.keys(body.data.field_edited_at)).toEqual(['due_at']);
59
+ });
60
+
61
+ it('falls back to the upsert for a host that has no patch', async () => {
62
+ const post = vi.fn().mockResolvedValue(stored({}));
63
+ const api = createPlanningApi({ http: { get: vi.fn(), post } as never, scope });
64
+ await api.updateCommitment!(row, { status: 'done' });
65
+ expect(post).toHaveBeenCalledTimes(1);
66
+ });
67
+ });
@@ -77,6 +77,13 @@ describe('connectionsMe — every route is /connections/me/', () => {
77
77
  expect(calls[0].body).toEqual({});
78
78
  });
79
79
 
80
+ it('syncs now through its own narrow route, with no body', async () => {
81
+ await connectionsMe.syncConnectionNow('abc');
82
+ expect(calls[0].url).toBe('/api/v1/connections/me/abc/sync/');
83
+ expect(calls[0].method).toBe('POST');
84
+ expect(calls[0].body).toEqual({});
85
+ });
86
+
80
87
  it('rotates through the credential route, wrapping the map the way the API expects', async () => {
81
88
  await connectionsMe.rotateCredential('abc', { api_key: 'grn_new' });
82
89
  expect(calls[0].url).toBe('/api/v1/connections/me/abc/credential/');
@@ -99,6 +106,7 @@ describe('connectionsMe — every route is /connections/me/', () => {
99
106
  await connectionsMe.connections();
100
107
  await connectionsMe.connect({ connector_key: 'granola' });
101
108
  await connectionsMe.checkConnection('abc');
109
+ await connectionsMe.syncConnectionNow('abc');
102
110
  await connectionsMe.rotateCredential('abc', { api_key: 'x' });
103
111
  await connectionsMe.disconnect('abc');
104
112
  await connectionsMe.connectionRuns('abc');
@@ -168,7 +168,7 @@ describe('TrackerPage — what is outstanding', () => {
168
168
  render(<TrackerPage api={makeApi({ onQuery: (query) => queries.push(query) })} scope={SCOPE} now={NOW} />);
169
169
  await screen.findByText('Chase the inventor for comments on 2148');
170
170
 
171
- expect(queries[0].status).toEqual(['open', 'blocked']);
171
+ expect(queries[0].status).toEqual(['open', 'in_progress', 'blocked']);
172
172
  expect(queries[0].pageSize).toBe(200);
173
173
  });
174
174
 
@@ -0,0 +1,60 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { dueDay, localDate, selectToday, todayKind } from '../corpus/today';
3
+
4
+ const at = (iso: string) => Date.parse(iso);
5
+ const LA = 'America/Los_Angeles';
6
+
7
+ describe('today selector (startsim-cqeho)', () => {
8
+ const items = [
9
+ { id: 'a', status: 'open', dueAt: '2026-11-05' },
10
+ { id: 'b', status: 'in_progress', dueAt: '2026-11-05' },
11
+ { id: 'c', status: 'open', dueAt: '2026-11-01' },
12
+ { id: 'd', status: 'open', dueAt: '2026-11-09' },
13
+ { id: 'e', status: 'open' },
14
+ { id: 'f', status: 'done', dueAt: '2026-11-05' },
15
+ { id: 'g', status: 'dropped', dueAt: '2026-11-01' },
16
+ { id: 'h', status: 'blocked', dueAt: '2026-11-05' },
17
+ ];
18
+ const now = at('2026-11-05T12:00:00Z');
19
+
20
+ it('returns open and in_progress with due_at <= today in the user tz', () => {
21
+ expect(selectToday(items, { now, timeZone: LA }).map((e) => e.item.id)).toEqual(['c', 'a', 'b']);
22
+ });
23
+
24
+ it('flags overdue for a due date before today', () => {
25
+ const kinds = Object.fromEntries(selectToday(items, { now, timeZone: LA }).map((e) => [e.item.id, e.kind]));
26
+ expect(kinds).toEqual({ a: 'due_today', b: 'due_today', c: 'overdue' });
27
+ });
28
+
29
+ it('excludes dropped, done and blocked', () => {
30
+ const ids = selectToday(items, { now, timeZone: 'UTC' }).map((e) => e.item.id);
31
+ for (const gone of ['f', 'g', 'h']) expect(ids).not.toContain(gone);
32
+ });
33
+
34
+ it('uses the timezone, not UTC, at the midnight boundary', () => {
35
+ const late = at('2026-11-06T03:00:00Z');
36
+ expect(localDate(late, LA)).toBe('2026-11-05');
37
+ expect(localDate(late, 'UTC')).toBe('2026-11-06');
38
+ expect(localDate(late, 'Asia/Tokyo')).toBe('2026-11-06');
39
+ const sixth = [{ id: 'x', status: 'open', dueAt: '2026-11-06' }];
40
+ expect(selectToday(sixth, { now: late, timeZone: LA })).toEqual([]);
41
+ expect(selectToday(sixth, { now: late, timeZone: 'UTC' }).map((e) => e.item.id)).toEqual(['x']);
42
+ });
43
+
44
+ it('keeps undated items out of today', () => {
45
+ expect(selectToday(items, { now, timeZone: 'UTC' }).map((e) => e.item.id)).not.toContain('e');
46
+ });
47
+
48
+ it('reads a bare date, a UTC-midnight instant and a real instant', () => {
49
+ expect(dueDay('2026-11-06', LA)).toBe('2026-11-06');
50
+ expect(dueDay('2026-11-06T00:00:00.000Z', LA)).toBe('2026-11-06');
51
+ expect(dueDay('2026-11-06T03:00:00Z', LA)).toBe('2026-11-05');
52
+ expect(dueDay(null, LA)).toBeNull();
53
+ expect(dueDay('nonsense', LA)).toBeNull();
54
+ });
55
+
56
+ it('can count an undated in_progress item (the briefing rule)', () => {
57
+ expect(todayKind({ status: 'in_progress' }, null, '2026-11-05', { includeUndatedInProgress: true })).toBe('in_progress');
58
+ expect(todayKind({ status: 'in_progress' }, null, '2026-11-05')).toBeNull();
59
+ });
60
+ });
@@ -152,6 +152,15 @@ function build(request: Requester): MemberConnectionsApi {
152
152
  );
153
153
  },
154
154
 
155
+ /**
156
+ * Sync NOW (a task-tracker connection): push what is pending for this card.
157
+ * A narrow route with no body; the sync itself runs on the server and the
158
+ * result shows up as each item's `sync_state` (bd startsim-el0zf).
159
+ */
160
+ syncConnectionNow(id: string): Promise<{ queued: boolean }> {
161
+ return request<{ queued: boolean }>(`${BASE}/${id}/sync/`, { method: 'POST', body: {} });
162
+ },
163
+
155
164
  /**
156
165
  * Rotate MY key. The old one stays live until the new one passes `check()`,
157
166
  * so a bad paste changes nothing. A PARTIAL map is legal and normal: send the
@@ -191,7 +191,7 @@ export function PlanningPage({
191
191
  // -- items ---------------------------------------------------------------
192
192
 
193
193
  const itemQuery = React.useMemo<CommitmentQuery>(() => ({
194
- status: showDone ? 'done' : (['open', 'blocked'] as CommitmentStatus[]),
194
+ status: showDone ? 'done' : (['open', 'in_progress', 'blocked'] as CommitmentStatus[]),
195
195
  ...(owner.trim() ? { owner: owner.trim() } : {}),
196
196
  ...(selected ? { focus: selected } : {}),
197
197
  // Each row names its project, and filing is an edge the entity row lacks.
@@ -182,7 +182,7 @@ export function TrackerPage({
182
182
  // narrowed again below — see `visible` — because a deployment whose API
183
183
  // ignores `status` would otherwise render closed items under "Outstanding"
184
184
  // and the banner alone would be doing all the work.
185
- status: tab === 'done' ? 'done' : (['open', 'blocked'] as CommitmentStatus[]),
185
+ status: tab === 'done' ? 'done' : (['open', 'in_progress', 'blocked'] as CommitmentStatus[]),
186
186
  ...(owner.trim() ? { owner: owner.trim() } : {}),
187
187
  ...(tab === 'recent' ? { changedAfter: new Date(clock - WEEK_MS).toISOString() } : {}),
188
188
  ...(tab === 'overdue' ? { dueBefore: new Date(clock).toISOString() } : {}),
@@ -324,7 +324,7 @@ export function TrackerPage({
324
324
  const visible = React.useMemo(() => {
325
325
  const byTab = rows.filter((item) => {
326
326
  if (tab === 'done') return item.status === 'done' || item.status === 'dropped';
327
- if (item.status !== 'open' && item.status !== 'blocked') return false;
327
+ if (item.status !== 'open' && item.status !== 'in_progress' && item.status !== 'blocked') return false;
328
328
  if (tab === 'overdue') return isOverdue(item, clock);
329
329
  if (tab === 'recent') return changedSince(item, clock - WEEK_MS);
330
330
  return true;
@@ -438,6 +438,8 @@ export interface MemberConnectionsApi {
438
438
  checkConnection(id: string): Promise<{
439
439
  ok: boolean; account_label: string; detail: string;
440
440
  }>;
441
+ /** Task-tracker connections: push what is pending now (bd startsim-el0zf). Optional for older clients. */
442
+ syncConnectionNow?(id: string): Promise<{ queued: boolean }>;
441
443
  rotateCredential(id: string, credentials: Record<string, unknown>): Promise<Connection>;
442
444
  disconnect(id: string): Promise<void>;
443
445
  connectionRuns(id: string): Promise<{ results: ConnectionRun[] }>;
@@ -1,5 +1,5 @@
1
1
  /** What is said back after an action: plain sentences built from the item's title and a spoken date. */
2
- import { localDate } from '../compose';
2
+ import { localDate } from '../../today';
3
3
  import { spokenWhen } from '../intent/dates';
4
4
  import { PRIORITY_NAMES } from '../intent/describe';
5
5
  import { speakable } from '../speak';
@@ -9,7 +9,7 @@
9
9
  * - HONEST: a failed write is reported on that action and the rest still run.
10
10
  * Only what really changed is on the undo stack.
11
11
  */
12
- import { localDate } from '../compose';
12
+ import { localDate } from '../../today';
13
13
  import type { VoiceAction } from '../intent/types';
14
14
  import { confirmText, shortTitle, undoText } from './confirm';
15
15
  import { REMEMBERED_ACTIONS, UNDO_DEPTH } from './log';
@@ -7,6 +7,7 @@
7
7
  * not done / dropped, not completed or canceled in Linear, and either overdue,
8
8
  * in progress, or due today in the CALLER'S zone.
9
9
  */
10
+ import { dueDay, localDate, todayKind } from '../today';
10
11
  import type {
11
12
  Briefing, BriefingEntry, BriefingItem, BriefingKind, BriefingOptions,
12
13
  } from './types';
@@ -16,32 +17,16 @@ const LINEAR_FINISHED = new Set(['completed', 'canceled', 'cancelled']);
16
17
  const DEFAULT_MAX_ITEMS = 8;
17
18
  const KIND_RANK: Record<BriefingKind, number> = { overdue: 0, in_progress: 1, due_today: 2 };
18
19
 
19
- /** `YYYY-MM-DD` of an instant in a zone. */
20
- export function localDate(instant: number, timeZone = 'UTC'): string {
21
- const parts = new Intl.DateTimeFormat('en-US', { timeZone, year: 'numeric', month: '2-digit', day: '2-digit' })
22
- .formatToParts(new Date(instant));
23
- const get = (type: string) => parts.find((p) => p.type === type)?.value ?? '';
24
- return `${get('year')}-${get('month')}-${get('day')}`;
25
- }
26
-
27
- /** The calendar day a due value means: a bare date as written, an instant in the zone. */
28
- function dueDate(dueAt: string | null | undefined, timeZone: string): string | null {
29
- if (!dueAt) return null;
30
- if (/^\d{4}-\d{2}-\d{2}$/.test(dueAt)) return dueAt;
31
- // The tenant reader turns a stored bare date into an instant at UTC midnight. That is still a DATE (a
32
- // voice reply writes "Friday" as 2026-11-06): localising it would put it on the evening before in New York.
33
- if (/^\d{4}-\d{2}-\d{2}T00:00:00(?:\.0+)?Z$/.test(dueAt)) return dueAt.slice(0, 10);
34
- const t = Date.parse(dueAt);
35
- return Number.isNaN(t) ? null : localDate(t, timeZone);
36
- }
37
-
20
+ /** The shared Today rule (../today), plus the briefing's own: an in_progress item is spoken even undated or future. */
38
21
  function kindOf(item: BriefingItem, due: string | null, today: string): BriefingKind | null {
39
- if (due && due < today) return 'overdue';
22
+ const kind = todayKind(item, due, today, { includeBlocked: true });
23
+ if (kind === 'overdue') return kind;
40
24
  if (item.status === 'in_progress') return 'in_progress';
41
- if (due === today) return 'due_today';
42
- return null;
25
+ return kind;
43
26
  }
44
27
 
28
+ export { localDate };
29
+
45
30
  export function composeBriefing(items: BriefingItem[], options: BriefingOptions): Briefing {
46
31
  const timeZone = options.timeZone ?? 'UTC';
47
32
  const today = localDate(options.now, timeZone);
@@ -52,7 +37,7 @@ export function composeBriefing(items: BriefingItem[], options: BriefingOptions)
52
37
  if (!item.ownerSub || item.ownerSub !== options.ownerSub) continue;
53
38
  if (FINISHED.has(item.status)) continue;
54
39
  if (item.linearState && LINEAR_FINISHED.has(item.linearState.toLowerCase())) continue;
55
- const due = dueDate(item.dueAt, timeZone);
40
+ const due = dueDay(item.dueAt, timeZone);
56
41
  const kind = kindOf(item, due, today);
57
42
  if (!kind) continue;
58
43
  eligible.push({
@@ -10,7 +10,7 @@
10
10
  * - "next week" is Monday of next week;
11
11
  * - "later" (and "someday") means no date: the item's due date is cleared.
12
12
  */
13
- import { localDate } from '../compose';
13
+ import { localDate } from '../../today';
14
14
  import { speakDate } from '../speak';
15
15
 
16
16
  export interface SpokenWhen {
@@ -1,5 +1,5 @@
1
1
  /** One line saying what was understood, shown BEFORE anything is applied. */
2
- import { localDate } from '../compose';
2
+ import { localDate } from '../../today';
3
3
  import { speakable } from '../speak';
4
4
  import { spokenWhen } from './dates';
5
5
  import type { IntentContext, VoiceAction } from './types';
@@ -12,7 +12,7 @@
12
12
  * read. Several actions in one reply ("done with this, and move the next one to
13
13
  * tomorrow") split at "and" ONLY where both halves are actions in their own right.
14
14
  */
15
- import { localDate } from '../compose';
15
+ import { localDate } from '../../today';
16
16
  import { normalizeSpeech, splitWhen, type SpokenWhen } from './dates';
17
17
  import { describeActions } from './describe';
18
18
  import { contentWords } from './match';
@@ -9,7 +9,7 @@
9
9
  * - what "the next / previous / third / other one" structurally means.
10
10
  * Anything else is a guess, and a guess becomes the grammar's spoken question.
11
11
  */
12
- import { localDate } from '../compose';
12
+ import { localDate } from '../../today';
13
13
  import { splitWhen } from './dates';
14
14
  import { contentWords, words } from './match';
15
15
  import type { IntentContext, IntentItem, VoiceAction } from './types';
@@ -5,7 +5,7 @@
5
5
  * have meant (the spoken list or an open item), dates must be real, priorities
6
6
  * 0-4; one bad action rejects the whole answer and the grammar answers instead.
7
7
  */
8
- import { localDate } from '../compose';
8
+ import { localDate } from '../../today';
9
9
  import { speakable } from '../speak';
10
10
  import { isIsoDate, parseWhen, spokenWhen, weekdayName } from './dates';
11
11
  import { PRIORITY_NAMES } from './describe';
@@ -30,6 +30,7 @@
30
30
  * second copy of the graph that will drift; the edge is the declared contract,
31
31
  * so the edge is what is read. The join is cached, bounded and fails soft.
32
32
  */
33
+ import { patchEditedItem } from './commitment-edit';
33
34
  import { readStandings } from './standings';
34
35
  import {
35
36
  DEFAULT_PARTICIPANT_EDGES,
@@ -108,6 +109,13 @@ export interface CorpusHttp {
108
109
  * appearing to succeed.
109
110
  */
110
111
  delete?<T>(path: string, options?: { params?: Record<string, unknown> }): Promise<T>;
112
+ /**
113
+ * OPTIONAL: the tenant's GET-then-write verb. An item EDIT goes through it so
114
+ * the server marks the field human-edited and holds it against a later
115
+ * extraction upsert (bd startsim-kgkp1.2). A host without it falls back to the
116
+ * upsert, which writes the value but does not claim it.
117
+ */
118
+ patch?<T>(path: string, body?: unknown, options?: { params?: Record<string, unknown> }): Promise<T>;
111
119
  }
112
120
 
113
121
  export interface CreateCorpusApiOptions {
@@ -1402,10 +1410,17 @@ export function createPlanningApi(options: CreateCorpusApiOptions): PlanningApi
1402
1410
  if (patch.subtype !== undefined) wire.subtype = patch.subtype;
1403
1411
  if (patch.priority !== undefined) wire.priority = patch.priority;
1404
1412
  if (patch.resolvedAt !== undefined) wire.resolved_at = patch.resolvedAt;
1413
+ const name = patch.title !== undefined ? patch.title.slice(0, 200) : undefined;
1414
+ if (http.patch && item.id) {
1415
+ const claimed = await patchEditedItem(
1416
+ { get: (path) => http.get(path), patch: (path, body) => http.patch!(path, body) },
1417
+ entities, String(item.id), wire, name !== undefined ? { name } : {});
1418
+ return toCommitment(claimed, scope, sourceLabels);
1419
+ }
1405
1420
  const updated = await post<TenantEntity>(`${entities}/upsert`, {
1406
1421
  entity_type: types.commitment,
1407
1422
  external_id: item.externalId,
1408
- ...(patch.title !== undefined ? { name: patch.title.slice(0, 200) } : {}),
1423
+ ...(name !== undefined ? { name } : {}),
1409
1424
  data: wire,
1410
1425
  });
1411
1426
  return toCommitment(updated, scope, sourceLabels);
@@ -0,0 +1,65 @@
1
+ /**
2
+ * A PERSON'S (OR A VOICE REPLY'S) EDIT TO AN ITEM, written the way the tenant
3
+ * protects (bd startsim-kgkp1.2, ADR startsim-hwkty D5).
4
+ *
5
+ * Two things the old upsert-only edit could not do:
6
+ *
7
+ * 1. MARK THE FIELD AS HUMAN-EDITED. The tenant records a field as edited only on
8
+ * `PATCH /entities/<id>` (apps/api/human_edits.py): upsert is the machine door.
9
+ * So the edit is a GET-then-PATCH under the row's version, and a later
10
+ * extraction upsert can no longer replace a due date or status a person set.
11
+ * 2. STAMP THE FIELD. The tracker keeps one `updatedAt` per issue, so the per-field
12
+ * time of the local edit lives in `field_edited_at`, which the sync engine
13
+ * compares against the remote's update time. A linked item also goes
14
+ * `sync_state: pending`, which is what the push drain reads.
15
+ */
16
+ import type { TenantEntity } from './entities';
17
+
18
+ /** The item fields a tracker also owns: the ones that need a stamp. */
19
+ export const STAMPED_FIELDS = ['status', 'due_at', 'priority', 'title', 'detail'] as const;
20
+ const LIFECYCLE = new Set(['pending', 'synced', 'conflict', 'error']);
21
+
22
+ const isRecord = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);
23
+
24
+ /** The `data` body a PATCH should carry: the stored blob with `wire` laid over it, stamped. */
25
+ export function editedData(current: TenantEntity, wire: Record<string, unknown>, now: number): Record<string, unknown> {
26
+ const data: Record<string, unknown> = { ...(isRecord(current.data) ? current.data : {}) };
27
+ const stamps: Record<string, unknown> = isRecord(data.field_edited_at) ? { ...data.field_edited_at } : {};
28
+ const at = new Date(now).toISOString();
29
+ for (const key of Object.keys(wire)) {
30
+ data[key] = wire[key];
31
+ if ((STAMPED_FIELDS as readonly string[]).includes(key)) stamps[key] = at;
32
+ }
33
+ if (Object.keys(stamps).length) data.field_edited_at = stamps;
34
+ const linked = Boolean(data.external_id) || LIFECYCLE.has(String(data.sync_state ?? ''));
35
+ const touchedTracker = Object.keys(wire).some((k) => (STAMPED_FIELDS as readonly string[]).includes(k));
36
+ if (linked && touchedTracker && data.sync_state !== 'remote_deleted') {
37
+ data.sync_state = 'pending';
38
+ // A new edit is a fresh reason to push now: drop the backoff the last failure set.
39
+ delete data.sync_error;
40
+ delete data.sync_attempts;
41
+ delete data.sync_next_at;
42
+ }
43
+ return data;
44
+ }
45
+
46
+ export interface PatchHttp {
47
+ get<T>(path: string): Promise<T>;
48
+ patch<T>(path: string, body?: unknown): Promise<T>;
49
+ }
50
+
51
+ export async function patchEditedItem(
52
+ http: PatchHttp,
53
+ entitiesPath: string,
54
+ id: string,
55
+ wire: Record<string, unknown>,
56
+ extra: { name?: string; now?: number } = {},
57
+ ): Promise<TenantEntity> {
58
+ const path = `${entitiesPath}/${encodeURIComponent(id)}`;
59
+ const current = await http.get<TenantEntity & { version?: number }>(path);
60
+ return http.patch<TenantEntity>(path, {
61
+ ...(extra.name !== undefined ? { name: extra.name } : {}),
62
+ data: editedData(current, wire, extra.now ?? Date.now()),
63
+ ...(typeof current.version === 'number' ? { expected_version: current.version } : {}),
64
+ });
65
+ }
@@ -441,7 +441,7 @@ export function applyResolutions(
441
441
 
442
442
  let best: { commitment: Commitment; score: number; bar: number } | null = null;
443
443
  for (const commitment of out) {
444
- if (commitment.status !== 'open' && commitment.status !== 'blocked') continue;
444
+ if (commitment.status !== 'open' && commitment.status !== 'in_progress' && commitment.status !== 'blocked') continue;
445
445
  if (at && commitment.firstSeenAt && commitment.firstSeenAt > at) continue;
446
446
  const other = identityOf(commitment);
447
447
  // Two IDENTIFIERS that disagree are different things, and no amount of
@@ -715,7 +715,7 @@ export function toCommitment(
715
715
  subtype: asText(pick(data, 'subtype')) || 'action',
716
716
  title: asText(pick(data, 'title')) || entity.name || 'Untitled item',
717
717
  detail: asText(pick(data, 'detail', 'description')),
718
- status: ['open', 'done', 'blocked', 'dropped'].includes(status) ? status : 'open',
718
+ status: ['open', 'in_progress', 'done', 'blocked', 'dropped'].includes(status) ? status : 'open',
719
719
  ...(pick(data, 'status_reason', 'statusReason')
720
720
  ? { statusReason: asText(pick(data, 'status_reason', 'statusReason')) } : {}),
721
721
  ...(pick(data, 'resolved_by', 'resolvedBy')
@@ -273,5 +273,8 @@ export type {
273
273
  FilterVerdict, RelationshipListQuery,
274
274
  } from './entity-query';
275
275
 
276
+ // Today, defined once (bd startsim-cqeho): the date helpers and the selector the briefing composes on.
277
+ export { dueDay, localDate, selectToday, todayKind } from './today';
278
+ export type { TodayEntry, TodayItem, TodayKind, TodayRule } from './today';
276
279
  // Daily briefing: what is on one person's plate today (bd startsim-kgkp1).
277
280
  export * from './briefing';
@@ -0,0 +1,73 @@
1
+ /**
2
+ * TODAY, defined once (bd startsim-cqeho, ADR startsim-hwkty D6). Provider
3
+ * independent and PURE: `now` and the person's IANA `timeZone` come in.
4
+ *
5
+ * Today = an `open` or `in_progress` item whose due date is on or before today's
6
+ * calendar date IN THE PERSON'S ZONE. Before today it is `overdue`. Undated,
7
+ * done, dropped and blocked items are not in it. The tenant answers the same
8
+ * question server-side at `GET /api/v1/entities/today/?tz=`; the two agree.
9
+ */
10
+
11
+ /** `YYYY-MM-DD` of an instant in a zone. */
12
+ export function localDate(instant: number, timeZone = 'UTC'): string {
13
+ const parts = new Intl.DateTimeFormat('en-US', { timeZone, year: 'numeric', month: '2-digit', day: '2-digit' })
14
+ .formatToParts(new Date(instant));
15
+ const get = (type: string) => parts.find((p) => p.type === type)?.value ?? '';
16
+ return `${get('year')}-${get('month')}-${get('day')}`;
17
+ }
18
+
19
+ /** The calendar day a due value means: a bare date as written, an instant in the zone. */
20
+ export function dueDay(dueAt: string | null | undefined, timeZone = 'UTC'): string | null {
21
+ if (!dueAt) return null;
22
+ if (/^\d{4}-\d{2}-\d{2}$/.test(dueAt)) return dueAt;
23
+ // The tenant reader turns a stored bare date into an instant at UTC midnight. That is still a DATE (a
24
+ // voice reply writes "Friday" as 2026-11-06): localising it would put it on the evening before in New York.
25
+ if (/^\d{4}-\d{2}-\d{2}T00:00:00(?:\.0+)?Z$/.test(dueAt)) return dueAt.slice(0, 10);
26
+ const t = Date.parse(dueAt);
27
+ return Number.isNaN(t) ? null : localDate(t, timeZone);
28
+ }
29
+
30
+ export type TodayKind = 'overdue' | 'in_progress' | 'due_today';
31
+
32
+ export interface TodayItem {
33
+ status: string;
34
+ dueAt?: string | null;
35
+ }
36
+
37
+ export interface TodayRule {
38
+ /** The briefing also speaks an in_progress item that has no date. The Today LIST does not. */
39
+ includeUndatedInProgress?: boolean;
40
+ /** The briefing still raises a blocked item that is overdue or due; the Today list does not. */
41
+ includeBlocked?: boolean;
42
+ }
43
+
44
+ const FINISHED = new Set(['done', 'dropped']);
45
+
46
+ /** Why an item is in Today, or null when it is not. `due` is the already-resolved calendar day. */
47
+ export function todayKind(item: TodayItem, due: string | null, today: string, rule: TodayRule = {}): TodayKind | null {
48
+ if (FINISHED.has(item.status) || (item.status === 'blocked' && !rule.includeBlocked)) return null;
49
+ if (due && due < today) return 'overdue';
50
+ if (due === today) return 'due_today';
51
+ if (!due && rule.includeUndatedInProgress && item.status === 'in_progress') return 'in_progress';
52
+ return null;
53
+ }
54
+
55
+ export interface TodayEntry<T> { item: T; kind: TodayKind; due: string | null }
56
+
57
+ const RANK: Record<TodayKind, number> = { overdue: 0, in_progress: 1, due_today: 2 };
58
+
59
+ /** The Today list: overdue first (oldest first), then what is due today. Stable for ties. */
60
+ export function selectToday<T extends TodayItem>(
61
+ items: T[],
62
+ options: { now: number; timeZone?: string } & TodayRule,
63
+ ): TodayEntry<T>[] {
64
+ const timeZone = options.timeZone ?? 'UTC';
65
+ const today = localDate(options.now, timeZone);
66
+ const out: TodayEntry<T>[] = [];
67
+ for (const item of items) {
68
+ const due = dueDay(item.dueAt, timeZone);
69
+ const kind = todayKind(item, due, today, options);
70
+ if (kind) out.push({ item, kind, due });
71
+ }
72
+ return out.sort((a, b) => RANK[a.kind] - RANK[b.kind] || (a.due ?? '9999').localeCompare(b.due ?? '9999'));
73
+ }
@@ -613,10 +613,11 @@ export type CommitmentSubtype = string;
613
613
  * `done` — satisfied. Set by a human, or by RESOLUTION DETECTION against a
614
614
  * later meeting, and in the second case `statusReason` carries the
615
615
  * sentence that closed it and `resolvedBy` the record it came from.
616
+ * `in_progress` — being worked on (set by a tracker pulling a started state, or by hand).
616
617
  * `blocked` — owed, but waiting on something named in `statusReason`.
617
618
  * `dropped` — explicitly abandoned. Not the same as done and must not read as it.
618
619
  */
619
- export type CommitmentStatus = 'open' | 'done' | 'blocked' | 'dropped';
620
+ export type CommitmentStatus = 'open' | 'in_progress' | 'done' | 'blocked' | 'dropped';
620
621
 
621
622
  /**
622
623
  * One time a commitment was talked about.
@@ -79,7 +79,7 @@ export function typesFrom(rows: SchemaTypeRow[]): SchemaTypeInfo[] {
79
79
  }));
80
80
  }
81
81
 
82
- const OPEN_TONES: Record<string, DisplayTone> = { open: 'info', done: 'good', blocked: 'warn', dropped: 'neutral' };
82
+ const OPEN_TONES: Record<string, DisplayTone> = { open: 'info', in_progress: 'info', done: 'good', blocked: 'warn', dropped: 'neutral' };
83
83
 
84
84
  /**
85
85
  * What a row of a well-known type reads as when the tenant has not declared a display yet. Data, not a switch:
@@ -325,6 +325,18 @@ export function createFakeTenantHttp(options: FakeTenantOptions = {}): FakeTenan
325
325
  }
326
326
  throw status(404, `${path} responded 404`);
327
327
  },
328
+ /** The tenant's GET-then-write verb: the body's `data` REPLACES the stored blob (the real tenant's PATCH). */
329
+ async patch<T>(path: string, body?: unknown): Promise<T> {
330
+ const b = (body ?? {}) as Record<string, unknown>;
331
+ requests.push({ method: 'PATCH', path, params: b });
332
+ options.onRequest?.('PATCH', path, b);
333
+ const id = /^api\/v1\/entities\/(.+?)\/?$/.exec(path.replace(/^\/+/, ''))?.[1];
334
+ const at = entities.findIndex((e) => String(e.id) === decodeURIComponent(id ?? ''));
335
+ if (at < 0) throw status(404, `No record ${id}`);
336
+ const merged = { ...entities[at], ...(b.name ? { name: String(b.name) } : {}), ...(b.data ? { data: b.data as Record<string, unknown> } : {}) };
337
+ entities[at] = merged;
338
+ return merged as T;
339
+ },
328
340
  async delete<T>(path: string): Promise<T> {
329
341
  requests.push({ method: 'DELETE', path, params: {} });
330
342
  const id = /relationships\/(.+?)\/?$/.exec(path)?.[1];
@@ -119,7 +119,7 @@ export interface FocusDetailController {
119
119
  stop(): void;
120
120
  }
121
121
 
122
- const OPEN = ['open', 'blocked'];
122
+ const OPEN = ['open', 'in_progress', 'blocked'];
123
123
  const CLOSED = ['done', 'dropped'];
124
124
 
125
125
  export function createFocusDetailController(
@@ -63,8 +63,8 @@ export function TrackerListScreen({ controller, onOpen, displays, now = Date.now
63
63
  subtitle={parts.who || undefined}
64
64
  meta={parts.due ?? undefined}
65
65
  metaTone={parts.overdue ? 'danger' : undefined}
66
- // Open is the default and needs no badge; blocked and dropped do.
67
- trailing={status === 'blocked' || status === 'dropped' ? <StatusChip status={status} /> : undefined}
66
+ // Open is the default and needs no badge; in progress, blocked and dropped do.
67
+ trailing={status === 'blocked' || status === 'dropped' || status === 'in_progress' ? <StatusChip status={status} /> : undefined}
68
68
  onPress={() => onOpen(row.item)}
69
69
  />
70
70
  </SwipeRow>
@@ -21,7 +21,7 @@ describe('tracker controller: every list change is a server request', () => {
21
21
  expect(titles(c).slice(0, 3)).toEqual(['Call Megan about the filing receipt', 'Finish exhibit list', 'Book the dentist']);
22
22
  expect(titles(c)).toHaveLength(5);
23
23
  const q = api.tenant.requests.find((r) => r.params?.type === 'commitment');
24
- expect(q?.params).toMatchObject({ order: 'attr.due_at', 'attr.status__in': 'open,blocked', page_size: 25 });
24
+ expect(q?.params).toMatchObject({ order: 'attr.due_at', 'attr.status__in': 'open,in_progress,blocked', page_size: 25 });
25
25
  });
26
26
 
27
27
  it('switching view sends the due window / status to the server and swaps the rows', async () => {
@@ -116,8 +116,8 @@ describe('tracker controller: mark done', () => {
116
116
  expect(titles(c)).not.toContain('Finish exhibit list'); // optimistic
117
117
  expect(c.getState().pendingIds).toContain('c1');
118
118
  await p;
119
- const post = api.tenant.requests.find((r) => r.method === 'POST');
120
- expect(post?.params).toMatchObject({ external_id: 'commit:c1', data: { status: 'done' } });
119
+ const patch = api.tenant.requests.find((r) => r.method === 'PATCH');
120
+ expect(patch?.params).toMatchObject({ data: { status: 'done' } });
121
121
  expect(c.getState().pendingIds).toEqual([]);
122
122
  expect(titles(c)).not.toContain('Finish exhibit list');
123
123
  await c.setView('closed');
@@ -127,7 +127,7 @@ describe('tracker controller: mark done', () => {
127
127
 
128
128
  it('puts the row back and says why when the write fails', async () => {
129
129
  let fail = false;
130
- const { c } = await setup({ onRequest: (m) => { if (fail && m === 'POST') throw Object.assign(new Error('Server said no'), { status: 500 }); } });
130
+ const { c } = await setup({ onRequest: (m) => { if (fail && m === 'PATCH') throw Object.assign(new Error('Server said no'), { status: 500 }); } });
131
131
  const row = c.getState().rows.find((r) => r.item.id === 'c1')!;
132
132
  fail = true;
133
133
  await c.setStatus(row.item, 'done');
@@ -63,7 +63,10 @@ describe('tracker detail controller', () => {
63
63
  const p = c.setStatus('done');
64
64
  expect(c.getState().item?.status).toBe('done');
65
65
  await p;
66
- expect(api.tenant.requests.find((r) => r.method === 'POST')?.params).toMatchObject({ external_id: 'commit:c1', data: { status: 'done' } });
66
+ // An edit is a GET-then-PATCH of the whole blob, stamped (bd startsim-kgkp1.2), not the machine upsert.
67
+ const patch = api.tenant.requests.find((r) => r.method === 'PATCH');
68
+ expect(patch?.params).toMatchObject({ data: { status: 'done' } });
69
+ expect(Object.keys((patch?.params as { data: { field_edited_at: object } }).data.field_edited_at)).toEqual(['status']);
67
70
  expect(changed()).toBe(1);
68
71
  await c.setStatus('open');
69
72
  expect(c.getState().item?.status).toBe('open');
@@ -71,7 +74,7 @@ describe('tracker detail controller', () => {
71
74
 
72
75
  it('rolls the status back and explains when the write fails', async () => {
73
76
  let fail = false;
74
- const { c } = await open('c1', { onRequest: (m) => { if (fail && m === 'POST') throw new Error('Server said no'); } });
77
+ const { c } = await open('c1', { onRequest: (m) => { if (fail && m === 'PATCH') throw new Error('Server said no'); } });
75
78
  fail = true;
76
79
  await c.setStatus('done');
77
80
  expect(c.getState().item?.status).toBe('open');
@@ -6,11 +6,11 @@ const NOW = Date.parse('2026-11-05T00:00:00Z');
6
6
 
7
7
  describe('trackerQuery', () => {
8
8
  it('the Unfiled project choice is a server filter, not a project id', () => {
9
- expect(trackerQuery({ ...DEFAULT_TRACKER_FILTERS, focusId: UNFILED_PROJECT }, NOW)).toEqual({ status: ['open', 'blocked'], unfiled: true });
9
+ expect(trackerQuery({ ...DEFAULT_TRACKER_FILTERS, focusId: UNFILED_PROJECT }, NOW)).toEqual({ status: ['open', 'in_progress', 'blocked'], unfiled: true });
10
10
  });
11
11
  it('maps each view to server filters', () => {
12
- expect(trackerQuery(DEFAULT_TRACKER_FILTERS, NOW)).toEqual({ status: ['open', 'blocked'] });
13
- expect(trackerQuery({ ...DEFAULT_TRACKER_FILTERS, view: 'overdue' }, NOW)).toEqual({ status: ['open', 'blocked'], dueBefore: '2026-11-05T00:00:00.000Z' });
12
+ expect(trackerQuery(DEFAULT_TRACKER_FILTERS, NOW)).toEqual({ status: ['open', 'in_progress', 'blocked'] });
13
+ expect(trackerQuery({ ...DEFAULT_TRACKER_FILTERS, view: 'overdue' }, NOW)).toEqual({ status: ['open', 'in_progress', 'blocked'], dueBefore: '2026-11-05T00:00:00.000Z' });
14
14
  expect(trackerQuery({ ...DEFAULT_TRACKER_FILTERS, view: 'recent' }, NOW).changedAfter).toBe('2026-10-29T00:00:00.000Z');
15
15
  expect(trackerQuery({ ...DEFAULT_TRACKER_FILTERS, view: 'closed' }, NOW).status).toEqual(['done', 'dropped']);
16
16
  });
@@ -23,7 +23,7 @@ export const DEFAULT_TRACKER_FILTERS: TrackerFilters = { view: 'open', focusId:
23
23
 
24
24
  export const WEEK_MS = 7 * 24 * 3600 * 1000;
25
25
 
26
- const OPEN: CommitmentStatus[] = ['open', 'blocked'];
26
+ const OPEN: CommitmentStatus[] = ['open', 'in_progress', 'blocked'];
27
27
  const CLOSED: CommitmentStatus[] = ['done', 'dropped'];
28
28
 
29
29
  /**
@@ -67,7 +67,7 @@ const PRIORITY = ['Critical', 'High', 'Medium', 'Low', 'Backlog'];
67
67
  export const priorityText = (p?: number): string | null => (p === undefined || p === null ? null : PRIORITY[p] ?? null);
68
68
 
69
69
  export function statusText(status: CommitmentStatus): string {
70
- return { open: 'Open', blocked: 'Blocked', done: 'Done', dropped: 'Dropped' }[status] ?? status;
70
+ return { open: 'Open', in_progress: 'In progress', blocked: 'Blocked', done: 'Done', dropped: 'Dropped' }[status] ?? status;
71
71
  }
72
72
 
73
73
  /**
@@ -15,6 +15,7 @@ export type AuthorizedFetch = (url: string, init?: RequestInit) => Promise<Respo
15
15
  export interface AuthorizedHttp extends CorpusHttp {
16
16
  post<T>(path: string, body?: unknown): Promise<T>;
17
17
  delete<T>(path: string): Promise<T>;
18
+ patch<T>(path: string, body?: unknown): Promise<T>;
18
19
  }
19
20
 
20
21
  const trimBase = (u: string) => u.replace(/\/+$/, '');
@@ -50,6 +51,12 @@ export function createAuthorizedCorpusHttp(deps: { baseUrl: string; authorizedFe
50
51
  delete<T>(path: string) {
51
52
  return call<T>('DELETE', path);
52
53
  },
54
+ patch<T>(path: string, body?: unknown) {
55
+ return call<T>('PATCH', path, {
56
+ headers: { 'Content-Type': 'application/json' },
57
+ body: body === undefined ? undefined : JSON.stringify(body),
58
+ });
59
+ },
53
60
  };
54
61
  }
55
62