@startsimpli/integrations 0.2.216 → 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.
@@ -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
+ }
@@ -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
 
@@ -15,7 +15,7 @@ import { decide } from './decide';
15
15
  import { suggestionOf } from './suggestion';
16
16
  import { SUGGESTED_STATUS } from '../item-status';
17
17
  import type { Commitment, SourceDocument } from '../types';
18
- import type { DecisionLabel, OwnerRelation, RuleId } from './types';
18
+ import type { DecisionLabel, ItemMatch, OwnerRelation, RuleId } from './types';
19
19
 
20
20
  export interface EngineScope {
21
21
  /** The person the pass runs for; every source must be theirs. */
@@ -63,7 +63,10 @@ export function ownerNamesFrom(items: Array<Pick<Commitment, 'ownerName' | 'owne
63
63
  return [...counts].filter(([, n]) => n >= 2).sort((a, b) => b[1] - a[1]).map(([name]) => name);
64
64
  }
65
65
 
66
- export function applyPolicy(fresh: Commitment[], context: { scope: EngineScope; documents: SourceDocument[] }): PolicyOutcome {
66
+ export function applyPolicy(
67
+ fresh: Commitment[],
68
+ context: { scope: EngineScope; documents: SourceDocument[]; matches?: Record<string, ItemMatch> },
69
+ ): PolicyOutcome {
67
70
  const { scope } = context;
68
71
  const byId = new Map(context.documents.map((doc) => [doc.id, doc]));
69
72
  const out: PolicyOutcome = { kept: [], acted: 0, proposed: 0, skipped: {} };
@@ -90,13 +93,17 @@ export function applyPolicy(fresh: Commitment[], context: { scope: EngineScope;
90
93
  const people = doc ? (doc.participants.length || doc.participantCount || 0) : 0;
91
94
  return people > 0 ? people - 1 : 2;
92
95
  })(),
93
- match: null,
96
+ match: context.matches?.[item.externalId] ?? null,
94
97
  }, { ownerSub: scope.ownerSub }, scope.labels ?? []);
95
98
 
96
99
  if (decision.mode === 'skip') {
97
100
  out.skipped[decision.rule] = (out.skipped[decision.rule] ?? 0) + 1;
98
101
  continue;
99
102
  }
103
+ // A merge or a link is never done silently: accepting one has to move mentions
104
+ // onto another row, which only the owner's "yes" (and the next pass) does.
105
+ const proposedOnly = decision.verb === 'merge' || decision.verb === 'link' ? decision.rule !== 'L-EXACT' : false;
106
+ if (proposedOnly) decision.mode = 'propose';
100
107
  const kept: Commitment = { ...item, suggestion: suggestionOf(decision) };
101
108
  if (owner === 'self' && !kept.ownerSub) kept.ownerSub = scope.ownerSub;
102
109
  if (decision.mode === 'propose') {
@@ -74,8 +74,9 @@ function decideItem(candidate: ItemCandidate, context: DecisionContext, fire: Fi
74
74
  // owner's own, or nothing (bd startsim-vrmx5; isolation audit, 2026-11-24).
75
75
  const match = sameOwner(candidate.match, context) ? candidate.match! : null;
76
76
  if (match?.strength === 'exact') return fire('L-EXACT', match.itemId);
77
- if (match?.strength === 'anchored') return fire('L-NEAR', match.itemId);
78
- if (match?.strength === 'unanchored') return fire('L-RELATED', match.itemId);
77
+ const about = match?.title ? ` “${match.title}”` : ' an item you have';
78
+ if (match?.strength === 'anchored') return fire('L-NEAR', match.itemId, `Looks like${about}: same subject, nearly the same wording.`);
79
+ if (match?.strength === 'unanchored') return fire('L-RELATED', match.itemId, `Close to${about}, but a different subject.`);
79
80
 
80
81
  if (candidate.owner === 'other') return fire('C-WAITING');
81
82
  if (candidate.owner === 'none') return fire('C-UNOWNED');
@@ -0,0 +1,71 @@
1
+ /**
2
+ * NEAR MATCHES AND STATED DATES, as the policy sees them (bd startsim-81mzy,
3
+ * Todo: ENG-151). `reconcile` reports what it found; `decide` judges it. This
4
+ * module is the plumbing between the two, shared by the write path and the dry run.
5
+ */
6
+ import { decide } from './decide';
7
+ import { SUGGESTED_STATUS } from '../item-status';
8
+ import { matchStrength, identityOf } from '../commitments';
9
+ import type { CommitmentIdentity } from '../commitments';
10
+ import { pendingProposals, withProposal } from './proposed-due';
11
+ import type { Commitment, SourceDocument } from '../types';
12
+ import type { DecisionLabel, ItemMatch } from './types';
13
+
14
+ const RANK = { anchored: 2, unanchored: 1 } as const;
15
+
16
+ /**
17
+ * The best OPEN item of this owner's that a statement is near, but not identical
18
+ * to. Never another owner's item, and never a suggestion or a closed row: a
19
+ * merge onto something the owner has not accepted (or has dismissed) means nothing.
20
+ */
21
+ export function nearMatchOf(items: Commitment[], identity: CommitmentIdentity, ownerSub: string): ItemMatch | null {
22
+ let best: ItemMatch | null = null;
23
+ for (const item of items) {
24
+ if (item.scope?.ownerSub !== ownerSub) continue;
25
+ if (item.status === SUGGESTED_STATUS || item.status === 'done' || item.status === 'dropped') continue;
26
+ const strength = matchStrength(identityOf(item), identity);
27
+ if (strength !== 'anchored' && strength !== 'unanchored') continue;
28
+ if (!best || RANK[strength] > RANK[best.strength as 'anchored' | 'unanchored']) {
29
+ best = { itemId: item.externalId, strength, itemOwnerSub: item.scope?.ownerSub ?? null, title: item.title };
30
+ }
31
+ }
32
+ return best;
33
+ }
34
+
35
+ const day = (iso: string | null | undefined) => (iso ?? '').slice(0, 10);
36
+
37
+ /**
38
+ * A source states a date for an item that already exists. The policy answers:
39
+ * leave it (a person set it, or it is the same date), set it (a graduated rule),
40
+ * or keep it on the item as a proposal. Returns whether the item changed.
41
+ */
42
+ export function judgeStatedDate(
43
+ item: Commitment,
44
+ stated: { dueAt: string; documentId: string; quote: string },
45
+ document: SourceDocument,
46
+ engine: { ownerSub: string; labels?: readonly DecisionLabel[] },
47
+ extras: { basis?: string; confidence?: number } = {},
48
+ ): boolean {
49
+ if (day(item.dueAt) === day(stated.dueAt)) return false;
50
+ const decision = decide({
51
+ kind: 'date',
52
+ documentId: stated.documentId,
53
+ documentOwnerSub: document.scope?.ownerSub ?? null,
54
+ documentSource: String(document.source ?? ''),
55
+ quote: stated.quote,
56
+ itemId: item.externalId,
57
+ dueAt: stated.dueAt,
58
+ humanEdited: item.dueSetByPerson ? ['due_at'] : [],
59
+ }, { ownerSub: engine.ownerSub }, engine.labels ?? []);
60
+ if (decision.mode === 'skip') return false;
61
+ if (decision.mode === 'act') {
62
+ item.dueAt = stated.dueAt;
63
+ if (extras.basis) item.dueBasis = extras.basis;
64
+ if (extras.confidence !== undefined) item.dueConfidence = extras.confidence;
65
+ return true;
66
+ }
67
+ const next = withProposal(item.proposedDue, { dueAt: stated.dueAt, documentId: stated.documentId, quote: stated.quote, state: 'pending' });
68
+ if (!next) return false;
69
+ item.proposedDue = next;
70
+ return pendingProposals(next).length > 0;
71
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * A DATE A LATER SOURCE STATES, kept ON the item it is about (bd startsim-81mzy,
3
+ * Todo: ENG-151) until the owner decides. Same shape of idea as "possibly done":
4
+ * one proposal per (item, source document), and a decided one is remembered so a
5
+ * re-sweep of the same document does not raise it again. Nothing here changes `dueAt`.
6
+ */
7
+ export interface ProposedDue {
8
+ dueAt: string;
9
+ documentId: string;
10
+ quote: string;
11
+ state: 'pending' | 'dismissed';
12
+ }
13
+
14
+ const text = (v: unknown): string => (typeof v === 'string' ? v : v == null ? '' : String(v));
15
+
16
+ export function readProposedDue(raw: unknown): ProposedDue[] {
17
+ if (!Array.isArray(raw)) return [];
18
+ const out: ProposedDue[] = [];
19
+ for (const entry of raw) {
20
+ if (!entry || typeof entry !== 'object') continue;
21
+ const e = entry as Record<string, unknown>;
22
+ const dueAt = text(e.due_at ?? e.dueAt);
23
+ const documentId = text(e.document_id ?? e.documentId);
24
+ if (!documentId || !dueAt || Number.isNaN(Date.parse(dueAt))) continue;
25
+ out.push({ dueAt, documentId, quote: text(e.quote), state: e.state === 'dismissed' ? 'dismissed' : 'pending' });
26
+ }
27
+ return out;
28
+ }
29
+
30
+ export const writeProposedDue = (list: ProposedDue[]): Array<Record<string, unknown>> =>
31
+ list.map((p) => ({ due_at: p.dueAt, document_id: p.documentId, quote: p.quote.slice(0, 400), state: p.state }));
32
+
33
+ /** The list with `proposal` added, unless this document already has one (pending or decided). */
34
+ export function withProposal(existing: ProposedDue[] | undefined, proposal: ProposedDue): ProposedDue[] | null {
35
+ const list = existing ?? [];
36
+ if (list.some((p) => p.documentId === proposal.documentId)) return null;
37
+ return [...list, proposal];
38
+ }
39
+
40
+ export const pendingProposals = (list: ProposedDue[] | undefined): ProposedDue[] =>
41
+ (list ?? []).filter((p) => p.state === 'pending');
42
+
43
+ export const dismissProposal = (list: ProposedDue[] | undefined, documentId: string): ProposedDue[] =>
44
+ (list ?? []).map((p) => (p.documentId === documentId ? { ...p, state: 'dismissed' as const } : p));