@startsimpli/integrations 0.2.215 → 0.2.217

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 (36) hide show
  1. package/package.json +5 -5
  2. package/src/__tests__/briefing-record-library.test.ts +47 -0
  3. package/src/__tests__/briefing-timezone-memory.test.ts +56 -0
  4. package/src/__tests__/corpus-storage.test.ts +6 -0
  5. package/src/__tests__/corpus-tracker.test.tsx +37 -0
  6. package/src/__tests__/engine-near-date.test.ts +136 -0
  7. package/src/__tests__/engine-scheduled-run.test.ts +8 -0
  8. package/src/__tests__/near-date-ui.test.tsx +74 -0
  9. package/src/__tests__/shared-with.test.tsx +78 -0
  10. package/src/__tests__/task-detail.test.tsx +1 -1
  11. package/src/components/DocumentDetail.tsx +3 -0
  12. package/src/components/SharedWith.tsx +140 -0
  13. package/src/components/pages/TaskDetailPage.tsx +4 -2
  14. package/src/components/pages/TrackerPage.tsx +27 -7
  15. package/src/components/pages/tracker/PossiblyDone.tsx +28 -2
  16. package/src/components/pages/tracker/Suggestion.tsx +15 -11
  17. package/src/components/table/todo-model.ts +3 -0
  18. package/src/corpus/briefing/generate-weekly.ts +2 -1
  19. package/src/corpus/briefing/generate.ts +2 -1
  20. package/src/corpus/briefing/zone.ts +24 -0
  21. package/src/corpus/briefing-text.ts +11 -0
  22. package/src/corpus/client.ts +6 -0
  23. package/src/corpus/commitments.ts +48 -3
  24. package/src/corpus/engine/apply.ts +10 -3
  25. package/src/corpus/engine/decide.ts +3 -2
  26. package/src/corpus/engine/near-match.ts +71 -0
  27. package/src/corpus/engine/proposed-due.ts +44 -0
  28. package/src/corpus/engine/suggestion.ts +5 -0
  29. package/src/corpus/engine/types.ts +2 -0
  30. package/src/corpus/entities.ts +15 -1
  31. package/src/corpus/extract.ts +10 -4
  32. package/src/corpus/index.ts +2 -0
  33. package/src/corpus/retrieval.ts +3 -0
  34. package/src/corpus/runs.ts +10 -1
  35. package/src/corpus/sharing.ts +132 -0
  36. package/src/corpus/types.ts +22 -2
@@ -0,0 +1,140 @@
1
+ /**
2
+ * WHO CAN SEE THIS RECORD, on the open record in the Library (Todo ENG-158).
3
+ *
4
+ * A record is private to whoever it belongs to until they share it. This is the
5
+ * one place that says so and changes it: a line of who it is shared with, and one
6
+ * menu to add a person, a team, or the whole organisation. It hides itself when
7
+ * the host's client cannot read shares, and shows the line without the menu when
8
+ * the caller may read the record but not change who else can.
9
+ */
10
+ import * as React from 'react';
11
+
12
+ import type { CorpusApi } from '../corpus/types';
13
+ import type { RecordShare, RecordShares, ShareChoices, ShareKind, ShareLevel } from '../corpus/sharing';
14
+
15
+ type Slots = Record<'badge' | 'input' | 'muted' | 'error', string>;
16
+
17
+ type SharingApi = Pick<CorpusApi, 'listRecordShares' | 'listShareChoices' | 'addRecordShare' | 'removeRecordShare'>;
18
+
19
+ const ORG_OPTION = 'org:';
20
+
21
+ export function labelFor(share: RecordShare, choices: ShareChoices): string {
22
+ if (share.kind === 'org') return choices.org?.label ?? 'Everyone in my organisation';
23
+ const pool = share.kind === 'group' ? choices.teams : choices.people;
24
+ return pool.find((c) => c.id === share.subjectId)?.label ?? (share.kind === 'group' ? 'A team' : 'A colleague');
25
+ }
26
+
27
+ export function SharedWith({
28
+ api, documentId, classNames: cn,
29
+ }: {
30
+ api: SharingApi;
31
+ documentId: string;
32
+ classNames: Slots;
33
+ }) {
34
+ const apiRef = React.useRef(api);
35
+ apiRef.current = api;
36
+ const [state, setState] = React.useState<RecordShares | undefined>(undefined);
37
+ const [choices, setChoices] = React.useState<ShareChoices>({ people: [], teams: [] });
38
+ const [level, setLevel] = React.useState<ShareLevel>('viewer');
39
+ const [busy, setBusy] = React.useState(false);
40
+ const [error, setError] = React.useState('');
41
+ const canRead = Boolean(api.listRecordShares);
42
+
43
+ const load = React.useCallback(async () => {
44
+ try {
45
+ setState(await apiRef.current.listRecordShares!(documentId));
46
+ } catch {
47
+ setState(undefined);
48
+ setError('Who this is shared with could not be read.');
49
+ }
50
+ }, [documentId]);
51
+
52
+ React.useEffect(() => {
53
+ if (!canRead) return;
54
+ setState(undefined);
55
+ setError('');
56
+ void load();
57
+ }, [canRead, load]);
58
+
59
+ const canEdit = Boolean(state?.canShare && api.addRecordShare && api.removeRecordShare && api.listShareChoices);
60
+ React.useEffect(() => {
61
+ if (!canEdit) return undefined;
62
+ let live = true;
63
+ apiRef.current.listShareChoices!()
64
+ .then((result) => { if (live) setChoices(result); })
65
+ .catch(() => { /* the line still shows; only the menu is lost */ });
66
+ return () => { live = false; };
67
+ }, [canEdit]);
68
+
69
+ if (!canRead) return null;
70
+
71
+ async function act(work: () => Promise<void>) {
72
+ setBusy(true);
73
+ setError('');
74
+ try {
75
+ await work();
76
+ await load();
77
+ } catch (err) {
78
+ setError((err as { message?: string })?.message || 'Sharing could not be changed.');
79
+ } finally {
80
+ setBusy(false);
81
+ }
82
+ }
83
+
84
+ function add(value: string) {
85
+ if (!value) return;
86
+ const [kind, ...rest] = value.split(':');
87
+ const subjectId = rest.join(':');
88
+ void act(() => apiRef.current.addRecordShare!(documentId, { kind: kind as ShareKind, subjectId, level }));
89
+ }
90
+
91
+ const taken = new Set((state?.shares ?? []).map((s) => `${s.kind}:${s.subjectId}`));
92
+ const orgTaken = (state?.shares ?? []).some((s) => s.kind === 'org');
93
+
94
+ return (
95
+ <div className="mt-3 flex flex-wrap items-center gap-2" data-testid="shared-with">
96
+ <p className="text-sm font-medium text-gray-900">Shared with</p>
97
+ {state === undefined && !error ? <span className={cn.muted}>…</span> : null}
98
+ {state && state.shares.length === 0 ? <span className={cn.muted}>Only you</span> : null}
99
+ {state?.shares.map((share) => (
100
+ <span key={share.id} className={cn.badge}>
101
+ {labelFor(share, choices)}{share.level === 'editor' ? ' · can edit' : ''}
102
+ {canEdit ? (
103
+ <button
104
+ type="button"
105
+ className="ml-1"
106
+ aria-label={`Stop sharing with ${labelFor(share, choices)}`}
107
+ disabled={busy}
108
+ onClick={() => { void act(() => apiRef.current.removeRecordShare!(share.id)); }}
109
+ >×</button>
110
+ ) : null}
111
+ </span>
112
+ ))}
113
+ {canEdit ? (
114
+ <>
115
+ <label>
116
+ <span className="sr-only">Share with</span>
117
+ <select className={cn.input} disabled={busy} value="" onChange={(e) => add(e.target.value)}>
118
+ <option value="">Share with…</option>
119
+ {choices.org && !orgTaken ? <option value={`${ORG_OPTION}${choices.org.id}`}>{choices.org.label}</option> : null}
120
+ {choices.teams.filter((t) => !taken.has(`group:${t.id}`)).map((t) => (
121
+ <option key={`g${t.id}`} value={`group:${t.id}`}>{t.label} (team)</option>
122
+ ))}
123
+ {choices.people.filter((p) => !taken.has(`user:${p.id}`)).map((p) => (
124
+ <option key={`u${p.id}`} value={`user:${p.id}`}>{p.label}</option>
125
+ ))}
126
+ </select>
127
+ </label>
128
+ <label>
129
+ <span className="sr-only">Access</span>
130
+ <select className={cn.input} disabled={busy} value={level} onChange={(e) => setLevel(e.target.value as ShareLevel)}>
131
+ <option value="viewer">Can view</option>
132
+ <option value="editor">Can edit</option>
133
+ </select>
134
+ </label>
135
+ </>
136
+ ) : null}
137
+ {error ? <p className={cn.error} role="alert">{error}</p> : null}
138
+ </div>
139
+ );
140
+ }
@@ -23,7 +23,7 @@ import type { RosterMember } from '../../corpus/owner-link';
23
23
  import { ExternalLinkChip } from './task-tracker/ExternalLinkChip';
24
24
  import { failureMessage } from './work-items';
25
25
  import { ProjectGuess } from './task-tracker/ProjectGuess';
26
- import { PossiblyDoneNote, markDonePatch, notDonePatch } from './tracker/PossiblyDone';
26
+ import { PossiblyDoneNote, keepDuePatch, markDonePatch, notDonePatch, setDuePatch } from './tracker/PossiblyDone';
27
27
  import { EngineReason, SuggestionNote, acceptPatch, rejectPatch } from './tracker/Suggestion';
28
28
  import { SUGGESTED_STATUS } from '../../corpus/item-status';
29
29
  import type { MemberConnectionsApi } from './types';
@@ -219,7 +219,7 @@ export function TaskDetailPage({
219
219
  };
220
220
 
221
221
  const back = onBack ? (
222
- <button type="button" className="text-sm text-blue-700 underline" onClick={onBack}>← Back to Tracker</button>
222
+ <button type="button" className="text-sm text-blue-700 underline" onClick={onBack}>← Back to to-dos</button>
223
223
  ) : null;
224
224
 
225
225
  if (loading) return <div className={cn.root}>{back}<p className={cn.muted}>Loading…</p></div>;
@@ -311,6 +311,8 @@ export function TaskDetailPage({
311
311
  item={item} disabled={busy}
312
312
  onMarkDone={(it, c) => void patchItem(markDonePatch(c))}
313
313
  onNotDone={(it, c) => void patchItem(notDonePatch(it, c))}
314
+ onSetDue={(it, p) => void patchItem(setDuePatch(it, p))}
315
+ onKeepDue={(it, p) => void patchItem(keepDuePatch(it, p))}
314
316
  />
315
317
  ) : null}
316
318
  {item.statusReason ? (
@@ -5,7 +5,7 @@
5
5
  * `LibraryPage` and `AskPage`. The app owns className slots and a wrapper; extraction happens behind
6
6
  * `api.extract`, server-side, where the provider key is. Nothing in this file imports a provider.
7
7
  *
8
- * ONE TOOLBAR, ONE TABLE (Quinn, 2026-11-20): a search box, Status and Project dropdowns and a single
8
+ * ONE TOOLBAR, ONE TABLE (Quinn, 2026-11-20): a search box, Status, Project and Owner dropdowns and a single
9
9
  * filled "+ Add to-do"; then `TodoTable` with sortable headers and the shared pagination footer. No
10
10
  * pill rows, no second status, no groups or boards or folds: Status "Done" is how finished work is read.
11
11
  *
@@ -25,7 +25,7 @@ import { isStalled } from '../../corpus/runs';
25
25
  import { useTrackerName } from '../../task-tracker/useTrackerName';
26
26
  import type { MemberConnectionsApi } from './types';
27
27
  import { failureMessage, unfilteredMessage } from './work-items';
28
- import { PossiblyDoneNote, markDonePatch, notDonePatch } from './tracker/PossiblyDone';
28
+ import { PossiblyDoneNote, keepDuePatch, markDonePatch, notDonePatch, setDuePatch } from './tracker/PossiblyDone';
29
29
  import { SuggestionNote, acceptPatch, rejectPatch } from './tracker/Suggestion';
30
30
  import { SUGGESTED_STATUS } from '../../corpus/item-status';
31
31
  import { SweepPanel } from './tracker/SweepPanel';
@@ -42,7 +42,8 @@ import type {
42
42
  } from '../../corpus/types';
43
43
 
44
44
  export interface TrackerPageProps {
45
- api: CommitmentTrackerApi;
45
+ /** `listMembers` (the viewer's own workspace roster) turns on the Owner dropdown. */
46
+ api: CommitmentTrackerApi & { listMembers?: () => Promise<Array<{ sub: string; email: string; name?: string }>> };
46
47
  scope: CorpusScope;
47
48
  /** Click-through from a mention to the record, normally the Library route. */
48
49
  onOpenDocument?: (documentId: string) => void;
@@ -190,10 +191,20 @@ export function TrackerPage({
190
191
  const [search, setSearch] = React.useState(initialSearch ?? '');
191
192
  const [status, setStatus] = React.useState('open');
192
193
  const [project, setProject] = React.useState('');
194
+ const [owner, setOwner] = React.useState('');
195
+ /** The viewer's own workspace roster (the server only returns the viewer's company); absent = no Owner filter. */
196
+ const [members, setMembers] = React.useState<Array<{ sub: string; email: string; name?: string }>>([]);
193
197
  const [sort, setSort] = React.useState<TableSort | null>(null);
194
198
  const [page, setPage] = React.useState(1);
195
199
  const [pageSize, setPageSizeState] = React.useState<PageSize>(() => readPageSize('todos'));
196
200
 
201
+ React.useEffect(() => {
202
+ let live = true;
203
+ if (!api.listMembers) return undefined;
204
+ void apiRef.current.listMembers?.().then((roster) => { if (live) setMembers(roster); }).catch(() => undefined);
205
+ return () => { live = false; };
206
+ }, [api.listMembers, scope.orgId]);
207
+
197
208
  // The typed text becomes a server query only after a pause, and starts again from page one.
198
209
  React.useEffect(() => {
199
210
  if (searchText === search) return undefined;
@@ -202,8 +213,8 @@ export function TrackerPage({
202
213
  }, [searchText, search]);
203
214
 
204
215
  const query = React.useMemo(
205
- () => todoQuery({ search, status, project, sort, page, pageSize }, focusId),
206
- [search, status, project, sort, page, pageSize, focusId],
216
+ () => todoQuery({ search, status, project, owner, sort, page, pageSize }, focusId),
217
+ [search, status, project, owner, sort, page, pageSize, focusId],
207
218
  );
208
219
 
209
220
  const load = React.useCallback(async () => {
@@ -347,9 +358,11 @@ export function TrackerPage({
347
358
  setSaving(true);
348
359
  setError('');
349
360
  try {
350
- await apiRef.current.createCommitment!({ title, ...(focusId ? { focusId } : {}) });
361
+ const created = await apiRef.current.createCommitment!({ title, ...(focusId ? { focusId } : {}) });
351
362
  setDraftTitle('');
352
363
  setAdding(false);
364
+ // A new to-do opens on its detail page at once; the list re-reads only where there is no detail to open.
365
+ if (onOpenItem && created) { onOpenItem(created); return; }
353
366
  await loadRef.current();
354
367
  } catch (err) {
355
368
  setError(failureMessage(err));
@@ -368,12 +381,16 @@ export function TrackerPage({
368
381
  const sweepBusy = Boolean(sweep && (sweep.status === 'queued' || sweep.status === 'running'));
369
382
  // A run whose lease has lapsed is not running, whatever its status field says.
370
383
  const sweepStalled = Boolean(sweep && isStalled(sweep, clock));
371
- const filtering = search.trim().length > 0 || status !== 'open' || Boolean(project);
384
+ const filtering = search.trim().length > 0 || status !== 'open' || Boolean(project) || Boolean(owner);
372
385
 
373
386
  const projectOptions = [
374
387
  { value: '', label: 'All projects' },
375
388
  ...Object.entries(projectNames).map(([value, label]) => ({ value, label })),
376
389
  ];
390
+ const ownerOptions = [
391
+ { value: '', label: 'All owners' },
392
+ ...members.map((m) => ({ value: m.sub, label: m.name || m.email })),
393
+ ];
377
394
  const resetPage = <T,>(set: (v: T) => void) => (v: T) => { set(v); setPage(1); };
378
395
 
379
396
  const pullButton = !manualPull ? null : canQueue ? (
@@ -436,6 +453,7 @@ export function TrackerPage({
436
453
  >
437
454
  <FilterSelect label="Status" value={status} options={[...TODO_STATUS_FILTERS]} onChange={resetPage(setStatus)} />
438
455
  {focusId ? null : <FilterSelect label="Project" value={project} options={projectOptions} onChange={resetPage(setProject)} />}
456
+ {members.length ? <FilterSelect label="Owner" value={owner} options={ownerOptions} onChange={resetPage(setOwner)} /> : null}
439
457
  {pullButton}
440
458
  </TableToolbar>
441
459
 
@@ -460,6 +478,8 @@ export function TrackerPage({
460
478
  item={item}
461
479
  onMarkDone={(it, c) => void act(it, markDonePatch(c))}
462
480
  onNotDone={(it, c) => void act(it, notDonePatch(it, c))}
481
+ onSetDue={(it, p) => void act(it, setDuePatch(it, p))}
482
+ onKeepDue={(it, p) => void act(it, keepDuePatch(it, p))}
463
483
  />
464
484
  </>
465
485
  ) : undefined}
@@ -7,6 +7,8 @@ import * as React from 'react';
7
7
 
8
8
  import { stripMarkdown } from '../../Markdown';
9
9
  import { dismissCandidate, pendingCandidates } from '../../../corpus/possibly-done';
10
+ import { dismissProposal, pendingProposals } from '../../../corpus/engine/proposed-due';
11
+ import type { ProposedDue } from '../../../corpus/engine/proposed-due';
10
12
  import type { Commitment, PossiblyDone } from '../../../corpus/types';
11
13
 
12
14
  const BTN = 'rounded border border-gray-300 px-2 py-0.5 text-xs text-gray-700 hover:border-gray-400';
@@ -23,17 +25,41 @@ export const notDonePatch = (item: Commitment, candidate: PossiblyDone) => ({
23
25
  possiblyDone: dismissCandidate(item.possiblyDone, candidate.documentId),
24
26
  });
25
27
 
26
- export function PossiblyDoneNote({ item, onMarkDone, onNotDone, disabled }: {
28
+ /** A later source's date, taken. */
29
+ export const setDuePatch = (item: Commitment, proposal: ProposedDue) => ({
30
+ dueAt: proposal.dueAt,
31
+ proposedDue: dismissProposal(item.proposedDue, proposal.documentId),
32
+ });
33
+
34
+ /** A later source's date, declined; it is remembered so the same source does not ask again. */
35
+ export const keepDuePatch = (item: Commitment, proposal: ProposedDue) => ({
36
+ proposedDue: dismissProposal(item.proposedDue, proposal.documentId),
37
+ });
38
+
39
+ export function PossiblyDoneNote({ item, onMarkDone, onNotDone, onSetDue, onKeepDue, disabled }: {
27
40
  item: Commitment;
28
41
  onMarkDone: (item: Commitment, candidate: PossiblyDone) => void;
29
42
  onNotDone: (item: Commitment, candidate: PossiblyDone) => void;
43
+ onSetDue?: (item: Commitment, proposal: ProposedDue) => void;
44
+ onKeepDue?: (item: Commitment, proposal: ProposedDue) => void;
30
45
  disabled?: boolean;
31
46
  }) {
32
47
  if (item.status === 'done' || item.status === 'dropped') return null;
33
48
  const pending = pendingCandidates(item.possiblyDone);
34
- if (!pending.length) return null;
49
+ const dates = onSetDue && onKeepDue ? pendingProposals(item.proposedDue) : [];
50
+ if (!pending.length && !dates.length) return null;
35
51
  return (
36
52
  <div className="mt-1 space-y-1" data-testid="possibly-done">
53
+ {dates.map((p) => (
54
+ <div key={`due:${p.documentId}`} className="flex flex-wrap items-center gap-2 text-xs text-amber-900" data-testid="proposed-due">
55
+ <span className="min-w-0">
56
+ <span className="font-medium">New date:</span> a later note says {new Date(p.dueAt).toLocaleDateString()}
57
+ {p.quote ? <> “{stripMarkdown(p.quote)}”</> : null}
58
+ </span>
59
+ <button type="button" className={BTN} disabled={disabled} onClick={() => onSetDue!(item, p)}>Use it</button>
60
+ <button type="button" className={BTN} disabled={disabled} onClick={() => onKeepDue!(item, p)}>Keep mine</button>
61
+ </div>
62
+ ))}
37
63
  {pending.map((c) => (
38
64
  <div key={c.documentId} className="flex flex-wrap items-center gap-2 text-xs text-amber-900">
39
65
  <span className="min-w-0">
@@ -18,17 +18,20 @@ const reviewed = (item: Commitment, outcome: NonNullable<Suggestion['outcome']>)
18
18
  ({ ...item.suggestion!, outcome, reviewedAt: new Date().toISOString() });
19
19
 
20
20
  /** Accepting puts it on the list. If the owner changed it first, the review says so. */
21
- export const acceptPatch = (item: Commitment, edited = false) => ({
22
- status: 'open' as const,
23
- suggestion: reviewed(item, edited ? 'edited' : 'accepted'),
24
- });
21
+ export const acceptPatch = (item: Commitment, edited = false) => item.suggestion?.rule === 'L-NEAR' && !edited
22
+ // "Same as that one": this row is the duplicate. Its quotes join the other item on the next pass.
23
+ ? { status: 'dropped' as const, statusReason: 'Merged into the item it was the same as', suggestion: reviewed(item, 'accepted') }
24
+ : { status: 'open' as const, suggestion: reviewed(item, edited ? 'edited' : 'accepted') };
25
25
 
26
26
  /** Rejecting drops it, and the rejection is what teaches the rule. */
27
- export const rejectPatch = (item: Commitment) => ({
28
- status: 'dropped' as const,
29
- statusReason: 'Suggestion rejected',
30
- suggestion: reviewed(item, 'rejected'),
31
- });
27
+ export const rejectPatch = (item: Commitment) => item.suggestion?.rule === 'L-NEAR'
28
+ // "Not the same": the owner wants it as an item of its own.
29
+ ? { status: 'open' as const, suggestion: reviewed(item, 'rejected') }
30
+ : {
31
+ status: 'dropped' as const,
32
+ statusReason: 'Suggestion rejected',
33
+ suggestion: reviewed(item, 'rejected'),
34
+ };
32
35
 
33
36
  export function SuggestionNote({ item, onAccept, onReject, disabled }: {
34
37
  item: Commitment;
@@ -38,14 +41,15 @@ export function SuggestionNote({ item, onAccept, onReject, disabled }: {
38
41
  }) {
39
42
  if (item.status !== SUGGESTED_STATUS || !item.suggestion) return null;
40
43
  const { reason, quote } = item.suggestion;
44
+ const same = item.suggestion.rule === 'L-NEAR';
41
45
  return (
42
46
  <div className="mt-1 flex flex-wrap items-center gap-2 text-xs text-sky-900 dark:text-sky-200" data-testid="suggestion">
43
47
  <span className="min-w-0">
44
48
  <span className="font-medium">Suggested:</span> {reason}
45
49
  {quote ? <> “{stripMarkdown(quote)}”</> : null}
46
50
  </span>
47
- <button type="button" className={BTN} disabled={disabled} onClick={() => onAccept(item)}>Accept</button>
48
- <button type="button" className={BTN} disabled={disabled} onClick={() => onReject(item)}>Reject</button>
51
+ <button type="button" className={BTN} disabled={disabled} onClick={() => onAccept(item)}>{same ? 'Same item' : 'Accept'}</button>
52
+ <button type="button" className={BTN} disabled={disabled} onClick={() => onReject(item)}>{same ? 'Keep separate' : 'Reject'}</button>
49
53
  </div>
50
54
  );
51
55
  }
@@ -69,6 +69,8 @@ export interface TodoTableState {
69
69
  search: string;
70
70
  status: string;
71
71
  project: string;
72
+ /** A member's central user id; empty = everyone. */
73
+ owner?: string;
72
74
  sort: TableSort | null;
73
75
  page: number;
74
76
  pageSize: PageSize;
@@ -85,6 +87,7 @@ export function todoQuery(state: TodoTableState, fixedFocus?: string): Commitmen
85
87
  subtype: ['action', 'requirement'],
86
88
  withFocus: true,
87
89
  ...(focus ? { focus } : {}),
90
+ ...(state.owner ? { ownerSub: state.owner } : {}),
88
91
  ...(search ? { search } : {}),
89
92
  sort: sort ?? 'due',
90
93
  ...(sort && state.sort ? { sortDir: state.sort.dir } : {}),
@@ -8,6 +8,7 @@
8
8
  import { weeklyMarkdown } from './markdown';
9
9
  import { hashString } from './cache-key';
10
10
  import { composeWeekly, weeklyScript } from './weekly';
11
+ import { rememberedTimeZone } from './zone';
11
12
  import { createEntityBriefingStore, type BriefingRecord } from './store';
12
13
  import type { BriefingDeps, BriefingRequest } from './generate';
13
14
  import type { WeeklySummary } from './weekly';
@@ -31,9 +32,9 @@ const reasonOf = (error: unknown) => (error instanceof Error ? error.message : S
31
32
 
32
33
  export async function generateWeekly(deps: BriefingDeps, request: BriefingRequest = {}): Promise<WeeklyResult> {
33
34
  const now = (deps.now ?? Date.now)();
34
- const timeZone = request.timeZone ?? deps.timeZone ?? 'UTC';
35
35
  const ttl = Math.min(deps.audioTtlSeconds ?? 300, 600);
36
36
  const store = deps.store ?? createEntityBriefingStore(deps.http, deps.ownerSub);
37
+ const timeZone = request.timeZone ?? deps.timeZone ?? (await rememberedTimeZone(store, deps.ownerSub, now)) ?? 'UTC';
37
38
 
38
39
  const summary = composeWeekly(await deps.loadItems(), { ownerSub: deps.ownerSub, now, timeZone });
39
40
  const script = weeklyScript(summary, { now, timeZone, name: deps.name });
@@ -16,6 +16,7 @@ import type { CorpusHttp } from '../client';
16
16
  import { briefingContentHash } from './cache-key';
17
17
  import { composeBriefing } from './compose';
18
18
  import { briefingMarkdown } from './markdown';
19
+ import { rememberedTimeZone } from './zone';
19
20
  import { writeBriefingScript, type BriefingScriptLlm } from './script';
20
21
  import {
21
22
  briefingExternalId, createEntityBriefingStore, offsetsOf,
@@ -91,10 +92,10 @@ const reasonOf = (error: unknown) => (error instanceof Error ? error.message : S
91
92
  export async function generateBriefing(deps: BriefingDeps, request: BriefingRequest): Promise<BriefingResult> {
92
93
  const clock = deps.now ?? Date.now;
93
94
  const started = Date.now();
94
- const timeZone = request.timeZone ?? deps.timeZone ?? 'UTC';
95
95
  const now = clock();
96
96
  const ttl = Math.min(deps.audioTtlSeconds ?? DEFAULT_TTL, 600);
97
97
  const store = deps.store ?? createEntityBriefingStore(deps.http, deps.ownerSub);
98
+ const timeZone = request.timeZone ?? deps.timeZone ?? (await rememberedTimeZone(store, deps.ownerSub, now)) ?? 'UTC';
98
99
 
99
100
  const composed = composeBriefing(await deps.loadItems(), { ownerSub: deps.ownerSub, now, timeZone });
100
101
  const unsure = await deps.unsureCount?.().catch(() => 0) ?? 0;
@@ -0,0 +1,24 @@
1
+ /**
2
+ * The zone to day-bucket a briefing in when the caller sent none. UTC is the last
3
+ * resort, not the default: a client without a zone would otherwise move a user's
4
+ * evening to the next day. The owner's most recent stored briefing remembers the
5
+ * zone it was made in; the local date is within one day of the UTC date, so the
6
+ * few UTC days around `now` are enough to look at.
7
+ */
8
+ import { briefingExternalId, type BriefingStore } from './store';
9
+
10
+ const DAY = 86_400_000;
11
+ const utcDate = (ms: number) => new Date(ms).toISOString().slice(0, 10);
12
+
13
+ export async function rememberedTimeZone(
14
+ store: Pick<BriefingStore, 'find'>, ownerSub: string, now: number,
15
+ ): Promise<string | undefined> {
16
+ for (const offset of [1, 0, -1, -2, -3]) {
17
+ try {
18
+ const row = await store.find(briefingExternalId(ownerSub, utcDate(now + offset * DAY)));
19
+ const zone = row?.context?.timeZone;
20
+ if (zone) return zone;
21
+ } catch { /* a lookup failure only costs the fallback */ }
22
+ }
23
+ return undefined;
24
+ }
@@ -0,0 +1,11 @@
1
+ /** A briefing row keeps its spoken script in `briefing_text`; the Library shows it as one section. */
2
+ import type { DocumentSection } from './types';
3
+
4
+ export const BRIEFING_SOURCE_KEY = 'briefing';
5
+
6
+ export function briefingSections(data: Record<string, unknown>): DocumentSection[] {
7
+ if (data.source !== BRIEFING_SOURCE_KEY) return [];
8
+ const raw = data.briefing_text ?? data.briefingText;
9
+ const text = typeof raw === 'string' ? raw.trim() : '';
10
+ return text ? [{ key: 'briefing_text', label: 'What was said', text }] : [];
11
+ }
@@ -32,6 +32,7 @@
32
32
  */
33
33
  import { writePossiblyDone } from './possibly-done';
34
34
  import { writeSuggestion } from './engine/suggestion';
35
+ import { writeProposedDue } from './engine/proposed-due';
35
36
  import { patchEditedItem } from './commitment-edit';
36
37
  import { readStandings } from './standings';
37
38
  import { createParticipantReader } from './participants';
@@ -59,6 +60,7 @@ import { entityParams } from './entity-query';
59
60
  import { encodeOwnerSubs } from './owner-link';
60
61
  import { readRoster } from './roster';
61
62
  import { ABOUT_FOCUS, createFilingApi, setCommitmentFocus } from './filing';
63
+ import { createSharingApi } from './sharing';
62
64
  import {
63
65
  FOCUS_TYPE,
64
66
  IN_FOCUS,
@@ -274,6 +276,7 @@ function commitmentParams(query: CommitmentQuery, type: string): Record<string,
274
276
  if (subtypes.length === 1) out['attr.subtype'] = subtypes[0];
275
277
  else if (subtypes.length > 1) out['attr.subtype__in'] = subtypes.join(',');
276
278
  if (query.owner) out['attr.owner_name__icontains'] = query.owner.slice(0, TEXT_FILTER_MAX);
279
+ if (query.ownerSub) out['attr.owner_sub'] = query.ownerSub;
277
280
  if (query.dueBefore) out['attr.due_at__lte'] = query.dueBefore;
278
281
  if (query.changedAfter) out['attr.last_seen_at__gte'] = query.changedAfter;
279
282
  if (query.origin) out['attr._origin'] = query.origin;
@@ -301,6 +304,7 @@ const FILTER_PARAMS: Array<[keyof CommitmentQuery, string[]]> = [
301
304
  ['status', ['attr.status', 'attr.status__in']],
302
305
  ['subtype', ['attr.subtype', 'attr.subtype__in']],
303
306
  ['owner', ['attr.owner_name__icontains']],
307
+ ['ownerSub', ['attr.owner_sub']],
304
308
  ['dueBefore', ['attr.due_at__lte']],
305
309
  ['changedAfter', ['attr.last_seen_at__gte']],
306
310
  ['origin', ['attr._origin']],
@@ -603,6 +607,7 @@ export function createCorpusApi(
603
607
 
604
608
  return {
605
609
  ...createFilingApi(http, { entities, relationships }),
610
+ ...createSharingApi(http),
606
611
 
607
612
  // The Tracker timeline's server reads (grouped counts + one capped page per series).
608
613
  timeline: createTimelineReader({ http, type: types.commitment, entitiesPath: entities }),
@@ -1374,6 +1379,7 @@ export function createPlanningApi(options: CreateCorpusApiOptions): PlanningApi
1374
1379
  else if (patch.status === 'done' && item.status !== 'done') wire.resolved_at = new Date((options.now ?? Date.now)()).toISOString();
1375
1380
  if (patch.possiblyDone !== undefined) wire.possibly_done = writePossiblyDone(patch.possiblyDone);
1376
1381
  if (patch.suggestion !== undefined) wire.suggestion = writeSuggestion(patch.suggestion);
1382
+ if (patch.proposedDue !== undefined) wire.proposed_due = writeProposedDue(patch.proposedDue);
1377
1383
  // `null` clears the mark: the tenant reads anything but 'private' as shared.
1378
1384
  if (patch.visibility !== undefined) {
1379
1385
  wire.visibility = patch.visibility ?? '';
@@ -38,6 +38,8 @@
38
38
  * enough to sort by.
39
39
  */
40
40
  import { withCandidate } from './possibly-done';
41
+ import { judgeStatedDate, nearMatchOf } from './engine/near-match';
42
+ import type { DecisionLabel, ItemMatch } from './engine/types';
41
43
  import { jaccard, tokenize } from './text';
42
44
  import type {
43
45
  Commitment,
@@ -264,12 +266,21 @@ export interface ReconcileContext {
264
266
  */
265
267
  documents: SourceDocument[];
266
268
  now?: number;
269
+ /**
270
+ * The decision policy is in charge (bd startsim-81mzy). Only an IDENTICAL
271
+ * statement merges by itself; a near one is reported in `matches` and judged by
272
+ * `decide`, and a stated date goes through `decide` too instead of being
273
+ * backfilled or dropped.
274
+ */
275
+ engine?: { ownerSub: string; labels?: readonly DecisionLabel[] };
267
276
  }
268
277
 
269
278
  export interface ReconcileResult {
270
279
  commitments: Commitment[];
271
280
  created: number;
272
281
  merged: number;
282
+ /** Engine mode: the existing item each NEW row is near, by the new row's externalId. */
283
+ matches: Record<string, ItemMatch>;
273
284
  /**
274
285
  * The `externalId`s this pass actually changed.
275
286
  *
@@ -291,6 +302,8 @@ export function reconcile(
291
302
  const touched = new Set<string>();
292
303
  let created = 0;
293
304
  let merged = 0;
305
+ const matches: Record<string, ItemMatch> = {};
306
+ if (context.engine) foldAcceptedMerges(out, touched);
294
307
 
295
308
  for (const group of groups) {
296
309
  const mentions = group.drafts
@@ -299,7 +312,12 @@ export function reconcile(
299
312
  if (mentions.length === 0) continue;
300
313
 
301
314
  const lead = group.drafts.find((draft) => byId.has(draft.documentId))!;
302
- const match = out.find((commitment) => isSameCommitment(identityOf(commitment), group.identity));
315
+ // Under the engine only an identical key merges silently; the nearest open item is
316
+ // reported instead, so `decide` can propose the merge rather than do it.
317
+ const match = context.engine
318
+ ? out.find((commitment) => commitment.dedupeKey === group.identity.dedupeKey)
319
+ : out.find((commitment) => isSameCommitment(identityOf(commitment), group.identity));
320
+ const near = !match && context.engine ? nearMatchOf(out, group.identity, context.engine.ownerSub) : null;
303
321
 
304
322
  if (match) {
305
323
  merged += 1;
@@ -311,7 +329,13 @@ export function reconcile(
311
329
  if (!match.ownerName && lead.ownerName) match.ownerName = lead.ownerName;
312
330
  // A date read from the text goes onto rows the run creates, not onto rows that already
313
331
  // exist (bd startsim-768w.38.30): backfilling live rows is a deliberate act of its own.
314
- if (!match.dueAt && lead.dueAt && !lead.dueOnCreateOnly) {
332
+ if (context.engine) {
333
+ if (lead.dueAt && !lead.dueOnCreateOnly && match.scope?.ownerSub === context.engine.ownerSub) {
334
+ judgeStatedDate(match, { dueAt: lead.dueAt, documentId: lead.documentId, quote: lead.quote ?? '' },
335
+ byId.get(lead.documentId)!, context.engine,
336
+ { ...(lead.dueBasis ? { basis: lead.dueBasis } : {}), ...(lead.dueConfidence !== undefined ? { confidence: lead.dueConfidence } : {}) });
337
+ }
338
+ } else if (!match.dueAt && lead.dueAt && !lead.dueOnCreateOnly) {
315
339
  match.dueAt = lead.dueAt;
316
340
  if (lead.dueBasis) match.dueBasis = lead.dueBasis;
317
341
  if (lead.dueConfidence !== undefined) match.dueConfidence = lead.dueConfidence;
@@ -361,9 +385,28 @@ export function reconcile(
361
385
  applyMentions(fresh, mentions);
362
386
  out.push(fresh);
363
387
  touched.add(fresh.externalId);
388
+ if (near) matches[fresh.externalId] = near;
364
389
  }
365
390
 
366
- return { commitments: out, created, merged, touched: [...touched] };
391
+ return { commitments: out, created, merged, matches, touched: [...touched] };
392
+ }
393
+
394
+ /**
395
+ * "Same as ..." accepted: the new wording's mentions join the item it was the
396
+ * same as. `updateCommitment` cannot carry mentions, so the next pass does it.
397
+ * Folding is idempotent (mentions replace by key), so a repeat changes nothing.
398
+ */
399
+ function foldAcceptedMerges(items: Commitment[], touched: Set<string>) {
400
+ const byExternalId = new Map(items.map((item) => [item.externalId, item]));
401
+ for (const row of items) {
402
+ const s = row.suggestion;
403
+ if (!s || s.rule !== 'L-NEAR' || s.outcome !== 'accepted' || !s.targetId || row.status !== 'dropped') continue;
404
+ const target = byExternalId.get(s.targetId);
405
+ if (!target || target === row) continue;
406
+ const before = signature(target);
407
+ applyMentions(target, row.mentions);
408
+ if (signature(target) !== before) touched.add(target.externalId);
409
+ }
367
410
  }
368
411
 
369
412
  /**
@@ -397,6 +440,7 @@ function signature(commitment: Commitment): string {
397
440
  commitment.statusReason ?? '',
398
441
  commitment.ownerName ?? '',
399
442
  commitment.dueAt ?? '',
443
+ (commitment.proposedDue ?? []).map((p) => `${p.documentId}|${p.dueAt}|${p.state}`).join('~'),
400
444
  commitment.priority ?? '',
401
445
  commitment.estimateMinutes ?? '',
402
446
  commitment.resolvedBy ?? '',
@@ -531,6 +575,7 @@ function cloneCommitment(commitment: Commitment): Commitment {
531
575
  ...commitment,
532
576
  mentions: commitment.mentions.map((mention) => ({ ...mention })),
533
577
  ...(commitment.possiblyDone ? { possiblyDone: commitment.possiblyDone.map((c) => ({ ...c })) } : {}),
578
+ ...(commitment.proposedDue ? { proposedDue: commitment.proposedDue.map((p) => ({ ...p })) } : {}),
534
579
  };
535
580
  }
536
581