@startsimpli/integrations 0.2.216 → 0.2.218

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 (49) hide show
  1. package/package.json +5 -5
  2. package/src/__tests__/briefing-timezone-memory.test.ts +56 -0
  3. package/src/__tests__/corpus-storage.test.ts +6 -0
  4. package/src/__tests__/corpus-tracker.test.tsx +37 -0
  5. package/src/__tests__/engine-near-date.test.ts +136 -0
  6. package/src/__tests__/fleet-page.test.tsx +24 -0
  7. package/src/__tests__/near-date-ui.test.tsx +74 -0
  8. package/src/__tests__/relay-cli.test.ts +1 -1
  9. package/src/__tests__/share-default-row.test.tsx +44 -0
  10. package/src/__tests__/shared-with.test.tsx +87 -0
  11. package/src/__tests__/sync-health.test.ts +70 -0
  12. package/src/__tests__/task-detail.test.tsx +1 -1
  13. package/src/api/_fetch.ts +1 -1
  14. package/src/api/connections.ts +14 -0
  15. package/src/components/DocumentDetail.tsx +3 -0
  16. package/src/components/SharedWith.tsx +140 -0
  17. package/src/components/index.ts +1 -0
  18. package/src/components/pages/FleetPage.tsx +16 -4
  19. package/src/components/pages/SyncHealthCard.tsx +42 -0
  20. package/src/components/pages/TaskDetailPage.tsx +4 -2
  21. package/src/components/pages/TrackerPage.tsx +27 -7
  22. package/src/components/pages/connections/ConnectionCard.tsx +5 -0
  23. package/src/components/pages/connections/ShareDefaultRow.tsx +91 -0
  24. package/src/components/pages/connections/bound-api.ts +4 -1
  25. package/src/components/pages/tracker/PossiblyDone.tsx +28 -2
  26. package/src/components/pages/tracker/Suggestion.tsx +15 -11
  27. package/src/components/pages/types.ts +11 -0
  28. package/src/components/table/todo-model.ts +3 -0
  29. package/src/corpus/briefing/generate-weekly.ts +2 -1
  30. package/src/corpus/briefing/generate.ts +2 -1
  31. package/src/corpus/briefing/zone.ts +24 -0
  32. package/src/corpus/client.ts +6 -0
  33. package/src/corpus/commitments.ts +48 -3
  34. package/src/corpus/converse/fleet-view.ts +1 -1
  35. package/src/corpus/converse/fleet.ts +1 -1
  36. package/src/corpus/converse/index.ts +2 -0
  37. package/src/corpus/converse/respond.ts +2 -1
  38. package/src/corpus/converse/sync-health.ts +96 -0
  39. package/src/corpus/engine/apply.ts +10 -3
  40. package/src/corpus/engine/decide.ts +3 -2
  41. package/src/corpus/engine/near-match.ts +71 -0
  42. package/src/corpus/engine/proposed-due.ts +44 -0
  43. package/src/corpus/engine/suggestion.ts +5 -0
  44. package/src/corpus/engine/types.ts +2 -0
  45. package/src/corpus/entities.ts +13 -0
  46. package/src/corpus/extract.ts +10 -4
  47. package/src/corpus/index.ts +2 -0
  48. package/src/corpus/sharing.ts +135 -0
  49. package/src/corpus/types.ts +21 -1
@@ -158,6 +158,8 @@ export interface Connection {
158
158
  sync?: Record<string, unknown>;
159
159
  /** Why the newest sync run failed or only partly worked, scrubbed; '' when it was clean. */
160
160
  last_error?: string;
161
+ /** Task-tracker connections only: the sync engine's snapshot (pull/push times, rows pending, last error, retry time). */
162
+ sync_status?: Record<string, unknown> | null;
161
163
  last_checked_at?: string | null;
162
164
  /**
163
165
  * WHAT THE SERVER WANTS THE PERSON WHO JUST SAVED TO KNOW. Present on the
@@ -169,8 +171,13 @@ export interface Connection {
169
171
  * connector does, so only the server can say it. Rendered verbatim.
170
172
  */
171
173
  notices?: string[];
174
+ /** Who this account's records are shared with beyond its owner; absent or null means only the owner. */
175
+ share_default?: ShareDefault | null;
172
176
  }
173
177
 
178
+ /** `org` is the owner's own organisation; `group` is one of its teams (by slug). */
179
+ export type ShareDefault = { kind: 'org' } | { kind: 'group'; id: string };
180
+
174
181
  /** What to RENDER, never what to allow. The server refuses on its own. */
175
182
  export interface ConnectionPermissions {
176
183
  view: boolean;
@@ -441,6 +448,10 @@ export interface MemberConnectionsApi {
441
448
  updateConnectionConfig?(
442
449
  id: string, config: Record<string, unknown>,
443
450
  ): Promise<Connection>;
451
+ /** Who this account's records are shared with (Todo ENG-158). `null` makes them private again. Optional for older clients. */
452
+ updateConnectionSharing?(id: string, share: ShareDefault | null): Promise<Connection>;
453
+ /** The teams a default can name (the owner's own organisation). Optional; without it only "my organisation" is offered. */
454
+ shareTeams?(): Promise<Array<{ slug: string; name: string }>>;
444
455
  checkConnection(id: string): Promise<{
445
456
  ok: boolean; account_label: string; detail: string; reason?: string; next_step?: string;
446
457
  }>;
@@ -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
 
@@ -3,7 +3,7 @@
3
3
  * `roles.md` (who leads what), the open-loops ledger (what waits on whom) and `bridge find ""` (who is live and what each
4
4
  * is for). This module is the ONE parser: relay -> role leads -> the sessions each lead owns, then everyone else.
5
5
  */
6
- export interface FleetInputs { roles?: string; loops?: string; sessions?: string; ports?: string }
6
+ export interface FleetInputs { roles?: string; loops?: string; sessions?: string; ports?: string; /** JSON: todo-sync's last-run record. */ todo_sync?: string }
7
7
  export interface FleetSection { title: string; items: string[] }
8
8
  export interface FleetPort { project: string; range: string; base: string; url: string | null; notes: string }
9
9
 
@@ -18,7 +18,7 @@ export interface FleetSnapshot { text: string; updatedAt: string; inputs?: Fleet
18
18
  export function cleanFleetInputs(raw: unknown): FleetInputs | undefined {
19
19
  if (!raw || typeof raw !== 'object') return undefined;
20
20
  const out: FleetInputs = {};
21
- for (const k of ['roles', 'loops', 'sessions', 'ports'] as const) {
21
+ for (const k of ['roles', 'loops', 'sessions', 'ports', 'todo_sync'] as const) {
22
22
  const v = (raw as Record<string, unknown>)[k];
23
23
  if (typeof v === 'string' && v.trim()) out[k] = v.slice(0, MAX_FLEET_INPUT);
24
24
  }
@@ -31,6 +31,8 @@ export { routeUtterance, parseRoute } from './route';
31
31
  export type { ConverseRoute } from './route';
32
32
  export { cleanFleetInputs, saveFleetSnapshot, loadFleetSnapshot, fleetExternalId, FLEET_SOURCE, ageWords, FLEET_FRESH_MS } from './fleet';
33
33
  export type { FleetSnapshot } from './fleet';
34
+ export { buildSyncHealth, parseTodoSyncRecord, todoSyncLeg, TODO_SYNC_STALE_MS } from './sync-health';
35
+ export type { LegState, SyncConnectionInput, SyncLeg, TodoSyncRecord } from './sync-health';
34
36
  export { buildFleetView, parseBridgeFind, parseLoops, parsePorts, parseRoles } from './fleet-view';
35
37
  export type { FleetInputs, FleetLead, FleetPort, FleetSection, FleetSession, FleetView, RoleRow } from './fleet-view';
36
38
  export { PASSED_TO_RELAY, NO_FLEET_STATUS, NO_FILLER } from './brain';
@@ -4,6 +4,7 @@
4
4
  * POST /corpus/converse/end JSON {conversation_id}
5
5
  * GET /corpus/converse/<id>/turn/<n>/audio[?who=user] a turn's recording, to its owner only
6
6
  */
7
+ import { parseTodoSyncRecord } from './sync-health';
7
8
  import { isTimeZone } from '../spoken-time';
8
9
  import { voiceErrorResponse } from '../voice-manage';
9
10
  import { handleConverseEnd, handleConverseTurn } from './handle';
@@ -150,7 +151,7 @@ export async function converseFleetStatusResponse(request: Request, deps: Conver
150
151
  export async function converseFleetViewResponse(deps: ConverseDeps): Promise<Response> {
151
152
  try {
152
153
  const snap = await loadFleetSnapshot(deps);
153
- const body = snap ? { snapshot: { text: snap.text, updatedAt: snap.updatedAt, view: snap.inputs ? buildFleetView(snap.inputs) : null } } : { snapshot: null };
154
+ const body = snap ? { snapshot: { text: snap.text, updatedAt: snap.updatedAt, view: snap.inputs ? buildFleetView(snap.inputs) : null, todoSync: parseTodoSyncRecord(snap.inputs?.todo_sync) } } : { snapshot: null };
154
155
  return Response.json(body, { headers: { 'cache-control': 'no-store' } });
155
156
  } catch (error) {
156
157
  return failure(error);
@@ -0,0 +1,96 @@
1
+ /**
2
+ * One row per sync leg for the Fleet page and the `todo-sync health` CLI (bd startsim-nghko.1). A pure fold over state the
3
+ * server already computes: `sync` (sync_summary) and `sync_status` (task_sync snapshot) on each member connection, plus the
4
+ * last-run record todo-sync writes on the Mac. No new alarm: the relay reads it on /fleet.
5
+ */
6
+ export type LegState = 'ok' | 'behind' | 'stale' | 'failing' | 'reauth' | 'waiting' | 'passive';
7
+
8
+ export interface SyncConnectionInput {
9
+ id: string;
10
+ connector_name?: string;
11
+ last_error?: string;
12
+ sync?: Record<string, unknown> | null;
13
+ sync_status?: Record<string, unknown> | null;
14
+ }
15
+ export interface TodoSyncRecord { at: string; ok: boolean; closed: number; error: string }
16
+ export interface SyncLeg {
17
+ key: string;
18
+ label: string;
19
+ state: LegState;
20
+ lastOkAt: string | null;
21
+ /** Milliseconds since the last success; null when it never succeeded. */
22
+ lagMs: number | null;
23
+ /** Rows still waiting to go out (push legs). */
24
+ behind: number;
25
+ lastError: string;
26
+ retryAt: string | null;
27
+ note: string;
28
+ }
29
+
30
+ /** todo-sync runs every 10 minutes (LaunchAgent); three missed runs is stale. */
31
+ export const TODO_SYNC_STALE_MS = 30 * 60000;
32
+ const ORDER: LegState[] = ['failing', 'reauth', 'stale', 'behind', 'waiting', 'ok', 'passive'];
33
+
34
+ const str = (v: unknown) => (typeof v === 'string' && v ? v : null);
35
+ const num = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) ? v : 0);
36
+ const lag = (at: string | null, now: number) => { const t = at ? Date.parse(at) : NaN; return Number.isFinite(t) ? Math.max(0, now - t) : null; };
37
+ const leg = (p: Partial<SyncLeg> & Pick<SyncLeg, 'key' | 'label' | 'state'>, now: number): SyncLeg => ({
38
+ lastOkAt: null, behind: 0, lastError: '', retryAt: null, note: '', ...p, lagMs: lag(p.lastOkAt ?? null, now),
39
+ });
40
+
41
+ function connectorLeg(c: SyncConnectionInput, now: number): SyncLeg {
42
+ const s = (c.sync ?? {}) as Record<string, unknown>;
43
+ const label = c.connector_name ?? c.id;
44
+ const lastOkAt = str(s.last_success_at);
45
+ const raw = String(s.state ?? 'waiting');
46
+ let state: LegState = raw === 'limited' ? 'behind' : (['ok', 'failing', 'reauth', 'waiting', 'passive'].includes(raw) ? (raw as LegState) : 'waiting');
47
+ const next = str(s.next_sync_at) ? Date.parse(String(s.next_sync_at)) : NaN;
48
+ const interval = num(s.interval_minutes) * 60000;
49
+ if (state === 'ok' && Number.isFinite(next) && interval && now - next > 2 * interval) state = 'stale';
50
+ return leg({
51
+ key: c.id, label, state, lastOkAt, note: String(s.note ?? ''),
52
+ lastError: state === 'failing' || state === 'reauth' ? (c.last_error || String(s.note ?? '')) : '',
53
+ retryAt: state === 'behind' ? str(s.next_sync_at) : null,
54
+ }, now);
55
+ }
56
+
57
+ function trackerLegs(c: SyncConnectionInput, now: number): SyncLeg[] {
58
+ const st = c.sync_status as Record<string, unknown>;
59
+ const label = c.connector_name ?? c.id;
60
+ const status = String(st.status ?? 'ok');
61
+ const error = String(st.last_error ?? '');
62
+ const retryAt = str(st.retry_at);
63
+ const pending = num(st.pending_count);
64
+ const broken = status === 'error' || status === 'needs_reauth';
65
+ const paused = status === 'rate_limited';
66
+ const pullAt = str(st.last_pull_at);
67
+ const pushAt = str(st.last_push_at);
68
+ const pull = leg({ key: `${c.id}:pull`, label: `${label} pull`, state: status === 'needs_reauth' ? 'reauth' : paused ? 'behind' : pullAt ? 'ok' : 'waiting', lastOkAt: pullAt, lastError: broken ? error : '', retryAt }, now);
69
+ const pushState: LegState = status === 'needs_reauth' ? 'reauth' : broken ? 'failing' : paused || (pending > 0 && st.out_of_sync) ? 'behind' : pushAt || !pending ? 'ok' : 'waiting';
70
+ const push = leg({ key: `${c.id}:push`, label: `${label} push`, state: pushState, lastOkAt: pushAt, behind: pending, lastError: broken || paused ? error : '', retryAt }, now);
71
+ return [pull, push];
72
+ }
73
+
74
+ export function todoSyncLeg(rec: TodoSyncRecord | null, now: number): SyncLeg {
75
+ const base = { key: 'todo-sync', label: 'todo-sync (to-dos closed by merged PRs)' };
76
+ if (!rec || !Number.isFinite(Date.parse(rec.at))) return leg({ ...base, state: 'waiting', note: 'Has not reported yet' }, now);
77
+ if (!rec.ok) return leg({ ...base, state: 'failing', lastError: rec.error || 'The last run failed', note: `Last tried ${rec.at}` }, now);
78
+ const old = now - Date.parse(rec.at) > TODO_SYNC_STALE_MS;
79
+ return leg({ ...base, state: old ? 'stale' : 'ok', lastOkAt: rec.at, note: old ? 'No run in over 30 minutes; the LaunchAgent may be off' : `Closed ${rec.closed} last run` }, now);
80
+ }
81
+
82
+ export function buildSyncHealth(connections: SyncConnectionInput[], todoSync: TodoSyncRecord | null, now: number): SyncLeg[] {
83
+ const legs = connections.flatMap((c) => (c.sync_status ? trackerLegs(c, now) : [connectorLeg(c, now)]));
84
+ legs.push(todoSyncLeg(todoSync, now));
85
+ return legs.map((l, i) => ({ l, i })).sort((a, b) => ORDER.indexOf(a.l.state) - ORDER.indexOf(b.l.state) || a.i - b.i).map((x) => x.l);
86
+ }
87
+
88
+ /** Parse the JSON string the relay sync carries in the fleet snapshot; null when absent or unreadable. */
89
+ export function parseTodoSyncRecord(raw: unknown): TodoSyncRecord | null {
90
+ try {
91
+ const o = typeof raw === 'string' ? JSON.parse(raw) : raw;
92
+ if (!o || typeof o !== 'object' || typeof (o as TodoSyncRecord).at !== 'string') return null;
93
+ const r = o as TodoSyncRecord;
94
+ return { at: r.at, ok: r.ok !== false, closed: Number(r.closed) || 0, error: String(r.error ?? '').slice(0, 300) };
95
+ } catch { return null; }
96
+ }
@@ -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));
@@ -17,6 +17,8 @@ export interface Suggestion {
17
17
  reason: string;
18
18
  documentId: string;
19
19
  quote: string;
20
+ /** The existing item a merge or link proposal is about (L-NEAR, L-RELATED). */
21
+ targetId?: string;
20
22
  /** Set when the owner reviews a suggestion. */
21
23
  outcome?: 'accepted' | 'edited' | 'rejected';
22
24
  reviewedAt?: string;
@@ -30,6 +32,7 @@ export function suggestionOf(decision: Decision): Suggestion {
30
32
  reason: decision.reason,
31
33
  documentId: decision.evidence.documentId,
32
34
  quote: decision.evidence.quote.slice(0, 400),
35
+ ...(decision.targetId ? { targetId: decision.targetId } : {}),
33
36
  };
34
37
  }
35
38
 
@@ -50,6 +53,7 @@ export function readSuggestion(raw: unknown): Suggestion | undefined {
50
53
  reason: String(r.reason ?? ''),
51
54
  documentId: String(r.document_id ?? r.documentId ?? ''),
52
55
  quote: String(r.quote ?? ''),
56
+ ...(r.target_id || r.targetId ? { targetId: String(r.target_id ?? r.targetId) } : {}),
53
57
  ...(OUTCOMES.has(outcome) ? { outcome: outcome as Suggestion['outcome'] } : {}),
54
58
  ...(r.reviewed_at || r.reviewedAt ? { reviewedAt: String(r.reviewed_at ?? r.reviewedAt) } : {}),
55
59
  };
@@ -59,6 +63,7 @@ export function writeSuggestion(s: Suggestion): Record<string, unknown> {
59
63
  return {
60
64
  rule: s.rule, mode: s.mode, confidence: s.confidence, reason: s.reason,
61
65
  document_id: s.documentId, quote: s.quote,
66
+ ...(s.targetId ? { target_id: s.targetId } : {}),
62
67
  ...(s.outcome ? { outcome: s.outcome } : {}),
63
68
  ...(s.reviewedAt ? { reviewed_at: s.reviewedAt } : {}),
64
69
  };
@@ -90,6 +90,8 @@ export interface ItemMatch {
90
90
  itemId: string;
91
91
  strength: MatchStrength;
92
92
  itemOwnerSub: string | null;
93
+ /** The item's title, for the plain sentence a proposal shows. */
94
+ title?: string;
93
95
  }
94
96
 
95
97
  /** "That is done" / "we dropped that", said in a later source. */