@startsimpli/integrations 0.2.145 → 0.2.147

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 (76) hide show
  1. package/package.json +3 -3
  2. package/src/__tests__/briefing-actions.test.ts +2 -0
  3. package/src/__tests__/briefing-reply.test.ts +334 -0
  4. package/src/__tests__/corpus-tracker.test.tsx +79 -0
  5. package/src/__tests__/extract-classify.test.ts +9 -4
  6. package/src/__tests__/owner-backfill.test.ts +114 -0
  7. package/src/__tests__/owner-link.test.ts +115 -0
  8. package/src/__tests__/owner-picker.test.tsx +70 -0
  9. package/src/__tests__/private-items.test.ts +63 -0
  10. package/src/__tests__/roster.test.ts +27 -0
  11. package/src/__tests__/task-detail-private.test.tsx +44 -0
  12. package/src/__tests__/tracker-sort.test.ts +28 -0
  13. package/src/components/index.ts +1 -0
  14. package/src/components/pages/TaskDetailPage.tsx +51 -2
  15. package/src/components/pages/TrackerPage.tsx +28 -6
  16. package/src/components/pages/task-tracker/OwnerPicker.tsx +82 -0
  17. package/src/components/pages/tracker/TrackerBoard.tsx +45 -0
  18. package/src/components/pages/tracker/TrackerToolbar.tsx +44 -0
  19. package/src/corpus/briefing/actions/execute.ts +5 -4
  20. package/src/corpus/briefing/actions/log.ts +1 -1
  21. package/src/corpus/briefing/actions/types.ts +21 -0
  22. package/src/corpus/briefing/index.ts +1 -0
  23. package/src/corpus/briefing/intent/model.ts +3 -0
  24. package/src/corpus/briefing/intent/resolve.ts +14 -6
  25. package/src/corpus/briefing/intent/types.ts +7 -0
  26. package/src/corpus/briefing/reply/handle.ts +174 -0
  27. package/src/corpus/briefing/reply/index.ts +6 -0
  28. package/src/corpus/briefing/reply/respond.ts +95 -0
  29. package/src/corpus/briefing/reply/types.ts +112 -0
  30. package/src/corpus/briefing/store.ts +14 -0
  31. package/src/corpus/client.ts +24 -18
  32. package/src/corpus/entities.ts +7 -0
  33. package/src/corpus/extract.ts +21 -0
  34. package/src/corpus/index.ts +4 -0
  35. package/src/corpus/owner-backfill.ts +200 -0
  36. package/src/corpus/owner-link.ts +160 -0
  37. package/src/corpus/roster.ts +53 -0
  38. package/src/corpus/tracker-groups.ts +8 -4
  39. package/src/corpus/tracker-sort.ts +51 -0
  40. package/src/corpus/types.ts +24 -1
  41. package/src/native/app/FoundryApp.tsx +25 -7
  42. package/src/native/app/__tests__/briefingLink.test.tsx +57 -0
  43. package/src/native/app/__tests__/briefingServices.test.ts +92 -0
  44. package/src/native/app/__tests__/launch.test.ts +2 -1
  45. package/src/native/app/briefingServices.ts +101 -0
  46. package/src/native/app/config/__tests__/briefingConfig.test.ts +49 -0
  47. package/src/native/app/config/links.ts +4 -1
  48. package/src/native/app/config/types.ts +13 -1
  49. package/src/native/app/config/validate.ts +20 -2
  50. package/src/native/app/data.ts +3 -3
  51. package/src/native/app/device.ts +3 -0
  52. package/src/native/app/launch.ts +4 -0
  53. package/src/native/app/registry.tsx +3 -1
  54. package/src/native/app/screens/RecordScreen.tsx +3 -2
  55. package/src/native/app/services.ts +11 -30
  56. package/src/native/app/strings.ts +28 -0
  57. package/src/native/briefing/BriefingCard.tsx +14 -2
  58. package/src/native/briefing/BriefingReply.tsx +68 -0
  59. package/src/native/briefing/__tests__/BriefingReply.test.tsx +144 -0
  60. package/src/native/briefing/__tests__/fakeReply.test.ts +46 -0
  61. package/src/native/briefing/__tests__/notify.test.ts +42 -1
  62. package/src/native/briefing/__tests__/replyApi.test.ts +43 -0
  63. package/src/native/briefing/__tests__/replyController.test.ts +230 -0
  64. package/src/native/briefing/__tests__/replyPosition.test.ts +116 -0
  65. package/src/native/briefing/audioPlayer.ts +9 -2
  66. package/src/native/briefing/controller.ts +50 -5
  67. package/src/native/briefing/fake.ts +25 -18
  68. package/src/native/briefing/fakeReply.ts +65 -0
  69. package/src/native/briefing/index.ts +8 -3
  70. package/src/native/briefing/notify.ts +42 -0
  71. package/src/native/briefing/reply.ts +261 -0
  72. package/src/native/briefing/replyApi.ts +82 -0
  73. package/src/native/recording/__tests__/deeplink.test.ts +20 -0
  74. package/src/native/recording/deeplink.ts +7 -0
  75. package/src/native/tracker/__tests__/itemsChanged.test.ts +13 -0
  76. package/src/native/tracker/tab.tsx +4 -1
@@ -0,0 +1,112 @@
1
+ /**
2
+ * THE REPLY ENDPOINT'S SHAPES (bd startsim-t1hsu.1).
3
+ *
4
+ * One request/response pair for "the person said something back": a briefing reply
5
+ * today, and the answer to a clarifying question (epic startsim-tmrvi) tomorrow
6
+ * (`subject.kind: 'question'`). The response is one union the app can render without
7
+ * knowing which: what was understood, what changed, what to say back, and the
8
+ * question to ask when it could not tell.
9
+ */
10
+ import type { CorpusHttp } from '../../client';
11
+ import type { ActionLogStore, ActionResult, ItemEditSeam } from '../actions/types';
12
+ import type { BriefingAudio, BriefingSynthesize } from '../generate';
13
+ import type { PlaybackPosition } from '../intent/position';
14
+ import type { VoiceAction } from '../intent/types';
15
+ import type { BriefingScriptLlm } from '../script';
16
+ import type { BriefingStore } from '../store';
17
+ import type { BriefingItem } from '../types';
18
+
19
+ export type ReplySubject =
20
+ | { kind: 'briefing'; id: string }
21
+ /** Reserved for the clarifying-question loop: answers an `open_question` row. */
22
+ | { kind: 'question'; id: string };
23
+
24
+ export interface ReplyRequest {
25
+ subject: ReplySubject;
26
+ /** Fresh per press. Sending it again is a replay: nothing is transcribed, parsed or written twice. */
27
+ clientActionId: string;
28
+ /** What was said, when the app already has the words. */
29
+ utterance?: string;
30
+ /** What was said, as a recording. */
31
+ audio?: { audio: Uint8Array; mimeType: string };
32
+ /** Where the briefing was when the person pressed talk ("this one"). */
33
+ position?: PlaybackPosition;
34
+ /** The listener's IANA zone. Default: the briefing's. */
35
+ timeZone?: string;
36
+ /** `auto` applies a sure reply at once; `preview` only says what was understood. Default `auto`. */
37
+ mode?: 'auto' | 'preview';
38
+ /** Apply the preview stored under `clientActionId`. */
39
+ apply?: boolean;
40
+ /** Undo the last change (what the Undo button sends). */
41
+ undo?: boolean;
42
+ /** The client action id of the earlier reply that ended in a question; this reply answers it. */
43
+ inReplyTo?: string;
44
+ }
45
+
46
+ export interface ReplyConfirmation {
47
+ /** What is said back. */
48
+ text: string;
49
+ /** Owner-checked link to the spoken version, or null when only text is available. */
50
+ audioUrl: string | null;
51
+ mimeType?: string;
52
+ reason?: string;
53
+ }
54
+
55
+ export interface ReplyResult {
56
+ /** `preview`: understood, waiting for `apply`. `applied`: the edits ran. `clarify`: it asked instead of acting. */
57
+ kind: 'preview' | 'applied' | 'clarify';
58
+ clientActionId: string;
59
+ /** The words (transcribed if it was audio). */
60
+ utterance: string;
61
+ /** One line: "Move Order dad's bench to Friday". */
62
+ understood: string;
63
+ actions: VoiceAction[];
64
+ source: 'llm' | 'grammar';
65
+ confidence: number;
66
+ /** True while a preview waits for `apply`. */
67
+ needsConfirm: boolean;
68
+ /** What each action did (empty for a preview). */
69
+ results: ActionResult[];
70
+ /** The question, when `kind` is `clarify`. */
71
+ question: string | null;
72
+ /** The sentence to say back (confirmation, undo, or the question) and its audio; null for a preview. */
73
+ confirmation: ReplyConfirmation | null;
74
+ /** How many changes can still be undone. */
75
+ undoDepth: number;
76
+ /** True when the briefing's items changed and the list should be reloaded. */
77
+ refresh: boolean;
78
+ /** True when this press had already been handled and nothing ran again. */
79
+ replayed: boolean;
80
+ }
81
+
82
+ export interface BriefingReplyDeps {
83
+ http: Pick<CorpusHttp, 'get'> & { post<T>(path: string, body?: unknown): Promise<T> };
84
+ /** The caller, from the verified session. */
85
+ ownerSub: string;
86
+ /** The caller's open to-dos: what "that other thing" may name. */
87
+ loadItems(): Promise<BriefingItem[]>;
88
+ /** The one way an action touches an item (see `ItemEditSeam`). */
89
+ seam: ItemEditSeam;
90
+ log: ActionLogStore;
91
+ /** The intent model (temperature 0). Omit to use the plain rules alone. */
92
+ intentLlm?: BriefingScriptLlm | null;
93
+ synthesize?: BriefingSynthesize;
94
+ audio?: Pick<BriefingAudio, 'put'> & { get(audioRef: string): Promise<{ audio: Uint8Array; mimeType: string }> };
95
+ /** Speech to text for a recording; `hints` are the item titles just read. */
96
+ transcribe?: (input: { audio: Uint8Array; mimeType: string; hints: string[] }) => Promise<string>;
97
+ store?: BriefingStore;
98
+ now?: () => number;
99
+ /** Used when neither the request nor the briefing has a zone. */
100
+ timeZone?: string;
101
+ /** A model answer below this asks first even in `auto`. Default 0.85. */
102
+ minAutoConfidence?: number;
103
+ intentTimeoutMs?: number;
104
+ }
105
+
106
+ /** An error the route turns into a status; `code` lets the app choose its message. */
107
+ export class ReplyError extends Error {
108
+ constructor(message: string, readonly status: number, readonly code?: string) {
109
+ super(message);
110
+ this.name = 'ReplyError';
111
+ }
112
+ }
@@ -42,6 +42,8 @@ export type BriefingDraft = Omit<BriefingRecord, 'id'>;
42
42
 
43
43
  export interface BriefingStore {
44
44
  find(externalId: string): Promise<BriefingRecord | null>;
45
+ /** One of the caller's own briefings by row id; null for another person's row, a row of another kind or no row. */
46
+ get(id: string): Promise<BriefingRecord | null>;
45
47
  /** Shallow-merging upsert; returns the row with its id. */
46
48
  save(draft: BriefingDraft): Promise<BriefingRecord>;
47
49
  }
@@ -103,6 +105,18 @@ export function createEntityBriefingStore(http: StoreHttp, ownerSub: string): Br
103
105
  const hit = (page.results ?? []).find((r) => (r.external_id ?? r.externalId) === externalId && mine(r));
104
106
  return hit ? toRecord(hit) : null;
105
107
  },
108
+ async get(id) {
109
+ let entity: TenantEntity;
110
+ try {
111
+ entity = await http.get<TenantEntity>(`api/v1/entities/${encodeURIComponent(id)}`);
112
+ } catch (error) {
113
+ const status = (error as { status?: number }).status;
114
+ if (status === 404 || status === 403) return null;
115
+ throw error;
116
+ }
117
+ const data = (entity?.data ?? {}) as Record<string, unknown>;
118
+ return data.source === BRIEFING_SOURCE && mine(entity) ? toRecord(entity) : null;
119
+ },
106
120
  async save(draft) {
107
121
  const row = await http.post<TenantEntity>('api/v1/entities/upsert', {
108
122
  entity_type: 'source_document',
@@ -52,6 +52,8 @@ import type {
52
52
  CorpusTypeKeys, TenantEntity, TenantFacetRow, TenantRelationship,
53
53
  } from './entities';
54
54
  import { entityParams } from './entity-query';
55
+ import { encodeOwnerSubs } from './owner-link';
56
+ import { readRoster } from './roster';
55
57
  import { ABOUT_FOCUS, createFilingApi, setCommitmentFocus } from './filing';
56
58
  import {
57
59
  FOCUS_TYPE,
@@ -61,6 +63,7 @@ import {
61
63
  focusToEntity,
62
64
  toFocus,
63
65
  } from './planning';
66
+ import { commitmentOrder } from './tracker-sort';
64
67
  import type {
65
68
  Commitment,
66
69
  SaveCommitmentsOptions,
@@ -146,6 +149,8 @@ export interface CreateCorpusApiOptions {
146
149
  * picker exists to close, reappearing as an empty dropdown with no error.
147
150
  */
148
151
  members?: string;
152
+ /** The member-readable roster that supplies display names (`{sub, label}`). */
153
+ roster?: string;
149
154
  };
150
155
  /** How old a source's last sync may be before the Library calls it stale. */
151
156
  staleAfterHours?: number;
@@ -249,9 +254,9 @@ function commitmentParams(query: CommitmentQuery, type: string): Record<string,
249
254
  type,
250
255
  page: query.page ?? 1,
251
256
  ...(query.pageSize ? { page_size: Math.min(query.pageSize, 200) } : {}),
252
- // Oldest debt first, which is what the screen sorts by anyway — asking the
253
- // server for it means page one is the right page one.
254
- order: 'attr.due_at',
257
+ // Oldest debt first unless the screen asks otherwise — asking the server
258
+ // means page one is the right page one.
259
+ order: commitmentOrder(query.sort),
255
260
  };
256
261
  if (statuses.length === 1) out['attr.status'] = statuses[0];
257
262
  else if (statuses.length > 1) out['attr.status__in'] = statuses.join(',');
@@ -1201,6 +1206,7 @@ export function createPlanningApi(options: CreateCorpusApiOptions): PlanningApi
1201
1206
  const relationships = options.paths?.relationships ?? 'api/v1/relationships';
1202
1207
  // tenant-starter/config/urls.py: path("api/v1/org/members/", OrgMembersView…)
1203
1208
  const membersPath = options.paths?.members ?? 'api/v1/org/members';
1209
+ const rosterPath = options.paths?.roster ?? 'api/v1/org/roster';
1204
1210
 
1205
1211
  function writer(): NonNullable<CorpusHttp['post']> {
1206
1212
  if (!http.post) {
@@ -1406,10 +1412,24 @@ export function createPlanningApi(options: CreateCorpusApiOptions): PlanningApi
1406
1412
  if (patch.statusReason !== undefined) wire.status_reason = patch.statusReason;
1407
1413
  if (patch.ownerName !== undefined) wire.owner_name = patch.ownerName;
1408
1414
  if (patch.ownerSub !== undefined) wire.owner_sub = patch.ownerSub;
1415
+ // Joint owners: the list and its first member move together, so a reader of
1416
+ // only `owner_sub` never sees a different person than `owner_subs` does.
1417
+ if (patch.ownerSubs !== undefined) {
1418
+ wire.owner_subs = encodeOwnerSubs(patch.ownerSubs);
1419
+ wire.owner_sub = patch.ownerSubs[0] ?? '';
1420
+ }
1409
1421
  if (patch.dueAt !== undefined) wire.due_at = patch.dueAt;
1410
1422
  if (patch.subtype !== undefined) wire.subtype = patch.subtype;
1411
1423
  if (patch.priority !== undefined) wire.priority = patch.priority;
1412
1424
  if (patch.resolvedAt !== undefined) wire.resolved_at = patch.resolvedAt;
1425
+ // `null` clears the mark: the tenant reads anything but 'private' as shared.
1426
+ if (patch.visibility !== undefined) {
1427
+ wire.visibility = patch.visibility ?? '';
1428
+ // Private items also route as personal so the tracker push never sends
1429
+ // them to a shared team; an already-linked issue is left as it is.
1430
+ if (patch.visibility === 'private' && !item.sync) wire.destination = 'personal';
1431
+ if (patch.visibility === null && item.visibility === 'private' && item.destination === 'personal') wire.destination = '';
1432
+ }
1413
1433
  const name = patch.title !== undefined ? patch.title.slice(0, 200) : undefined;
1414
1434
  if (http.patch && item.id) {
1415
1435
  const claimed = await patchEditedItem(
@@ -1456,21 +1476,7 @@ export function createPlanningApi(options: CreateCorpusApiOptions): PlanningApi
1456
1476
  * alongside `ownerSub` instead of being replaced by it.
1457
1477
  */
1458
1478
  async listMembers(): Promise<Array<{ sub: string; email: string; name?: string }>> {
1459
- try {
1460
- const page = await http.get<DrfPage<Record<string, unknown>>>(membersPath, {});
1461
- return (page.results ?? [])
1462
- .map((row) => {
1463
- const user = (row.user ?? {}) as Record<string, unknown>;
1464
- return {
1465
- sub: String(user.sub ?? row.sub ?? ''),
1466
- email: String(user.email ?? row.email ?? ''),
1467
- ...(user.name ? { name: String(user.name) } : {}),
1468
- };
1469
- })
1470
- .filter((member) => member.sub);
1471
- } catch {
1472
- return [];
1473
- }
1479
+ return readRoster(http, { members: membersPath, roster: rosterPath });
1474
1480
  },
1475
1481
  };
1476
1482
  }
@@ -23,6 +23,7 @@
23
23
  * row with a missing subtitle.
24
24
  */
25
25
  import { withSourceEntity } from './source-entity';
26
+ import { decodeOwnerSubs, encodeOwnerSubs } from './owner-link';
26
27
  import { readItemSync, type ItemSync } from '../task-tracker/item-sync';
27
28
  import { filingsFromRow } from './voice-sections';
28
29
  import type {
@@ -736,6 +737,10 @@ export function toCommitment(
736
737
  ? { dueConfidence: asNumber(pick(data, 'due_confidence', 'dueConfidence')) } : {}),
737
738
  ...(pick(data, 'owner_sub', 'ownerSub')
738
739
  ? { ownerSub: asText(pick(data, 'owner_sub', 'ownerSub')) } : {}),
740
+ ...(pick(data, 'visibility') === 'private' ? { visibility: 'private' as const } : {}),
741
+ ...(pick(data, 'destination') === 'personal' ? { destination: 'personal' as const } : {}),
742
+ ...(decodeOwnerSubs(pick(data, 'owner_subs', 'ownerSubs')).length
743
+ ? { ownerSubs: decodeOwnerSubs(pick(data, 'owner_subs', 'ownerSubs')) } : {}),
739
744
  // Both spellings, for the reason spelled out on ORIGIN_KEY above: the
740
745
  // browser client camelCases `_origin` into `Origin` on the way in, and a
741
746
  // server-side fetch does not.
@@ -812,7 +817,9 @@ export function commitmentToEntity(commitment: Commitment): {
812
817
  ...(commitment.dueBasis ? { due_basis: commitment.dueBasis } : {}),
813
818
  ...(commitment.dueConfidence !== undefined ? { due_confidence: commitment.dueConfidence } : {}),
814
819
  ...(commitment.ownerSub ? { owner_sub: commitment.ownerSub } : {}),
820
+ ...(commitment.ownerSubs?.length ? { owner_subs: encodeOwnerSubs(commitment.ownerSubs) } : {}),
815
821
  ...(commitment.destination ? { destination: commitment.destination } : {}),
822
+ ...(commitment.visibility === 'private' ? { visibility: 'private' } : {}),
816
823
  ...(commitment.externalFocusId ? { external_focus_id: commitment.externalFocusId } : {}),
817
824
  ...(commitment.externalContainerId ? { external_container_id: commitment.externalContainerId } : {}),
818
825
  first_seen_at: commitment.firstSeenAt,
@@ -562,6 +562,15 @@ export async function extractCommitments(
562
562
  } else if (placed?.destination) {
563
563
  item.destination = placed.destination;
564
564
  }
565
+ if (isPersonalItem(item)) {
566
+ // Private also means "never leaves Tandem for a shared tracker": the push
567
+ // engine routes `destination: personal` to the member's private space, or
568
+ // holds it. A project filing would send it to a team's Linear project.
569
+ item.visibility = 'private';
570
+ item.destination = 'personal';
571
+ delete item.focusId;
572
+ delete item.externalFocusId;
573
+ }
565
574
  }
566
575
  const teams = await classifyTeams(fresh, { corpus, extractor, documents, promptText });
567
576
  for (const item of fresh) {
@@ -672,6 +681,18 @@ async function classifyTeams(
672
681
  }
673
682
  }
674
683
 
684
+ /**
685
+ * An item that came from the speaker's own Personal section, or that the
686
+ * classifier called a personal errand. Both are private to the owner (bd
687
+ * startsim-768w.38.48). The heading rule is deterministic on purpose: the
688
+ * classifier is a model and did not mark a single Personal-section item on the
689
+ * live tenant, so privacy cannot depend on it.
690
+ */
691
+ export function isPersonalItem(item: Pick<Commitment, 'destination' | 'mentions'>): boolean {
692
+ if (item.destination === 'personal') return true;
693
+ return item.mentions.some((mention) => /^\s*personal\b/i.test(mention.section ?? ''));
694
+ }
695
+
675
696
  async function readAllFocuses(list: NonNullable<PlanningApi['listFocuses']>) {
676
697
  const out = [];
677
698
  for (let page = 1; page <= 10; page++) {
@@ -15,6 +15,7 @@ export type {
15
15
  CommitmentDraft,
16
16
  CommitmentMention,
17
17
  CommitmentQuery,
18
+ CommitmentSort,
18
19
  CommitmentStatus,
19
20
  CommitmentSubtype,
20
21
  CommitmentTrackerApi,
@@ -297,6 +298,7 @@ export { DUE_LABELS, WEEK_DAYS, bucketOf, daysBetween, groupDue } from './due-gr
297
298
  export type { DueBucket, DueEntry, DueGroup, DueGroups } from './due-groups';
298
299
  export { STALE_DAYS, groupTracker, isTask } from './tracker-groups';
299
300
  export type { TrackerEntry, TrackerGroups } from './tracker-groups';
301
+ export { DEFAULT_TRACKER_SORT, TRACKER_SORTS, commitmentOrder, compareCommitments } from './tracker-sort';
300
302
  export { summarizeFocuses } from './focus-overview';
301
303
  export type { FocusSummary } from './focus-overview';
302
304
  export { actionsByNote } from './note-actions';
@@ -309,3 +311,5 @@ export type { TrackerTeamsApi } from './tracker-teams';
309
311
  export * from './questions';
310
312
  // A person's field edit written the way the tenant protects it (human-edited, stamped, queued for the tracker).
311
313
  export { patchEditedItem } from './commitment-edit';
314
+ export * from './owner-link';
315
+ export * from './owner-backfill';
@@ -0,0 +1,200 @@
1
+ /**
2
+ * REVERSIBLE OWNER BACKFILL (bd startsim-768w.38.29).
3
+ *
4
+ * Walks the commitments, runs the owner matcher over each `owner_name`, and
5
+ * either REPORTS (dry run, the default, read-only) or WRITES the links.
6
+ *
7
+ * What a write touches, and nothing else: `owner_sub` (first owner),
8
+ * `owner_subs` (all owners), and `owner_link` (a JSON string: run id, the
9
+ * original text, the PRIOR values, and the per-name verdicts). `owner_name` is
10
+ * never modified, so the original text is always there and undo is exact.
11
+ *
12
+ * Rows a person already assigned (an owner_sub with no owner_link) are skipped.
13
+ * Rows with no unambiguous match are never written: they stay text.
14
+ *
15
+ * Undo removes links by run id, and only where nobody has re-picked the owner
16
+ * since (the stored link still matches the row).
17
+ */
18
+ import { decodeOwnerSubs, encodeOwnerSubs, planOwnerLinks } from './owner-link';
19
+ import type { OwnerPart, OwnerOutcome, RosterMember } from './owner-link';
20
+
21
+ interface Row { id: string | number; version?: number; data?: Record<string, unknown> }
22
+ interface Page { results?: Row[]; next?: string | null }
23
+
24
+ export interface BackfillHttp {
25
+ get<T>(path: string, options?: { params?: Record<string, unknown> }): Promise<T>;
26
+ patch?<T>(path: string, body?: unknown): Promise<T>;
27
+ }
28
+
29
+ export type RowVerdict = OwnerOutcome | 'already_linked' | 'auto_linked';
30
+
31
+ export interface RowReport {
32
+ id: string;
33
+ ownerName: string;
34
+ verdict: RowVerdict;
35
+ parts?: OwnerPart[];
36
+ }
37
+
38
+ export interface BackfillReport {
39
+ mode: 'dry-run' | 'apply';
40
+ runId: string;
41
+ rows: number;
42
+ rowCounts: Record<RowVerdict, number>;
43
+ tokenCounts: { linked: number; ambiguous: number; unmatched: number };
44
+ /** Distinct owner strings per verdict with how many rows carry each. */
45
+ distinct: Record<string, Array<{ text: string; rows: number; detail: string }>>;
46
+ written: number;
47
+ failed: Array<{ id: string; error: string }>;
48
+ }
49
+
50
+ export interface BackfillOptions {
51
+ http: BackfillHttp;
52
+ roster: RosterMember[];
53
+ entitiesPath?: string;
54
+ commitmentType?: string;
55
+ apply?: boolean;
56
+ runId?: string;
57
+ now?: () => number;
58
+ maxPages?: number;
59
+ pageSize?: number;
60
+ }
61
+
62
+ const str = (value: unknown) => (typeof value === 'string' ? value : value == null ? '' : String(value));
63
+
64
+ function emptyCounts(): Record<RowVerdict, number> {
65
+ return { none: 0, linked: 0, partial: 0, ambiguous: 0, unmatched: 0, already_linked: 0, auto_linked: 0 };
66
+ }
67
+
68
+ async function* rowsOf(opts: BackfillOptions): AsyncGenerator<Row> {
69
+ const path = opts.entitiesPath ?? 'api/v1/entities';
70
+ const type = opts.commitmentType ?? 'commitment';
71
+ for (let page = 1; page <= (opts.maxPages ?? 200); page += 1) {
72
+ const response = await opts.http.get<Page>(path, {
73
+ params: { type, page, page_size: opts.pageSize ?? 100 },
74
+ });
75
+ for (const row of response?.results ?? []) yield row;
76
+ if (!response?.next || !(response.results ?? []).length) return;
77
+ }
78
+ }
79
+
80
+ function label(parts: OwnerPart[], roster: RosterMember[]): string {
81
+ const nameOf = (sub: string) => (() => { const m = roster.find((x) => x.sub === sub); return m?.name ?? m?.aliases?.[0] ?? m?.email ?? sub; })();
82
+ return parts.map((p) => (p.status === 'linked' ? `${p.text} -> ${nameOf(p.sub)}`
83
+ : p.status === 'ambiguous' ? `${p.text} -> ambiguous (${p.candidates.map(nameOf).join(' / ')})`
84
+ : `${p.text} -> no member`)).join('; ');
85
+ }
86
+
87
+ export async function backfillOwners(opts: BackfillOptions): Promise<BackfillReport> {
88
+ const now = opts.now ?? Date.now;
89
+ const runId = opts.runId ?? `own-${new Date(now()).toISOString().replace(/[-:.TZ]/g, '').slice(0, 14)}`;
90
+ const path = opts.entitiesPath ?? 'api/v1/entities';
91
+ const report: BackfillReport = {
92
+ mode: opts.apply ? 'apply' : 'dry-run', runId, rows: 0, rowCounts: emptyCounts(),
93
+ tokenCounts: { linked: 0, ambiguous: 0, unmatched: 0 }, distinct: {}, written: 0, failed: [],
94
+ };
95
+ const distinct = new Map<string, { text: string; rows: number; detail: string; verdict: string }>();
96
+ if (opts.apply && !opts.http.patch) throw new Error('This client has no patch method, so it cannot write links.');
97
+
98
+ for await (const row of rowsOf(opts)) {
99
+ report.rows += 1;
100
+ const data = row.data ?? {};
101
+ const ownerName = str(data.owner_name).trim();
102
+ let verdict: RowVerdict;
103
+ let parts: OwnerPart[] | undefined;
104
+ if (!ownerName) verdict = 'none';
105
+ else if (!str(data.owner_link) && (str(data.owner_sub) || decodeOwnerSubs(data.owner_subs).length)) {
106
+ verdict = 'already_linked';
107
+ } else if (str(data.owner_link)) {
108
+ verdict = 'auto_linked';
109
+ } else {
110
+ const plan = planOwnerLinks(ownerName, opts.roster);
111
+ verdict = plan.outcome;
112
+ parts = plan.parts;
113
+ for (const part of plan.parts) report.tokenCounts[part.status] += 1;
114
+ if (opts.apply && plan.subs.length) {
115
+ const link = {
116
+ run: runId, at: new Date(now()).toISOString(), method: 'name-match', text: ownerName,
117
+ prior: { owner_sub: str(data.owner_sub), owner_subs: str(data.owner_subs) },
118
+ owner_sub: plan.subs[0], owner_subs: encodeOwnerSubs(plan.subs), parts: plan.parts,
119
+ };
120
+ try {
121
+ await opts.http.patch!(`${path}/${encodeURIComponent(String(row.id))}`, {
122
+ data: { ...data, owner_sub: plan.subs[0], owner_subs: link.owner_subs, owner_link: JSON.stringify(link) },
123
+ ...(typeof row.version === 'number' ? { expected_version: row.version } : {}),
124
+ });
125
+ report.written += 1;
126
+ } catch (error) {
127
+ report.failed.push({ id: String(row.id), error: error instanceof Error ? error.message : String(error) });
128
+ }
129
+ }
130
+ }
131
+ report.rowCounts[verdict] += 1;
132
+ if (ownerName && parts) {
133
+ const key = `${verdict}\u0000${ownerName}`;
134
+ const hit = distinct.get(key);
135
+ if (hit) hit.rows += 1;
136
+ else distinct.set(key, { text: ownerName, rows: 1, detail: label(parts, opts.roster), verdict });
137
+ }
138
+ }
139
+ for (const entry of distinct.values()) {
140
+ (report.distinct[entry.verdict] ??= []).push({ text: entry.text, rows: entry.rows, detail: entry.detail });
141
+ }
142
+ for (const list of Object.values(report.distinct)) list.sort((a, b) => b.rows - a.rows);
143
+ return report;
144
+ }
145
+
146
+ export interface UndoReport { runId: string; restored: number; skippedChanged: number; failed: Array<{ id: string; error: string }> }
147
+
148
+ /** Restore the prior owner fields on every row linked by `runId` (or any run, when omitted). */
149
+ export async function undoOwnerBackfill(
150
+ opts: Pick<BackfillOptions, 'http' | 'entitiesPath' | 'commitmentType' | 'maxPages' | 'pageSize'> & { runId?: string; dryRun?: boolean },
151
+ ): Promise<UndoReport> {
152
+ const path = opts.entitiesPath ?? 'api/v1/entities';
153
+ const out: UndoReport = { runId: opts.runId ?? '*', restored: 0, skippedChanged: 0, failed: [] };
154
+ if (!opts.dryRun && !opts.http.patch) throw new Error('This client has no patch method, so it cannot undo.');
155
+ for await (const row of rowsOf({ ...opts, roster: [] })) {
156
+ const data = row.data ?? {};
157
+ const raw = str(data.owner_link);
158
+ if (!raw) continue;
159
+ let link: { run?: string; prior?: Record<string, string>; owner_sub?: string; owner_subs?: string };
160
+ try { link = JSON.parse(raw); } catch { continue; }
161
+ if (opts.runId && link.run !== opts.runId) continue;
162
+ if (str(data.owner_sub) !== str(link.owner_sub) || str(data.owner_subs) !== str(link.owner_subs)) {
163
+ out.skippedChanged += 1;
164
+ continue;
165
+ }
166
+ if (opts.dryRun) { out.restored += 1; continue; }
167
+ try {
168
+ await opts.http.patch!(`${path}/${encodeURIComponent(String(row.id))}`, {
169
+ data: {
170
+ ...data,
171
+ owner_sub: link.prior?.owner_sub ?? '', owner_subs: link.prior?.owner_subs ?? '', owner_link: '',
172
+ },
173
+ ...(typeof row.version === 'number' ? { expected_version: row.version } : {}),
174
+ });
175
+ out.restored += 1;
176
+ } catch (error) {
177
+ out.failed.push({ id: String(row.id), error: error instanceof Error ? error.message : String(error) });
178
+ }
179
+ }
180
+ return out;
181
+ }
182
+
183
+ export function formatBackfillReport(report: BackfillReport, examples = 6): string {
184
+ const c = report.rowCounts;
185
+ const lines = [
186
+ `Owner link ${report.mode} ${report.runId}: ${report.rows} commitments`,
187
+ `rows: fully linked ${c.linked}, partly linked ${c.partial}, ambiguous ${c.ambiguous}, no member match ${c.unmatched}, ` +
188
+ `already assigned by a person ${c.already_linked}, linked by an earlier run ${c.auto_linked}, no owner text ${c.none}`,
189
+ `names (joint owners counted one by one): linked ${report.tokenCounts.linked}, ambiguous ${report.tokenCounts.ambiguous}, ` +
190
+ `no member ${report.tokenCounts.unmatched}`,
191
+ ];
192
+ for (const verdict of ['linked', 'partial', 'ambiguous', 'unmatched']) {
193
+ const list = report.distinct[verdict] ?? [];
194
+ if (!list.length) continue;
195
+ lines.push(`${verdict} examples:`);
196
+ for (const e of list.slice(0, examples)) lines.push(` ${e.rows}x ${e.detail}`);
197
+ }
198
+ if (report.mode === 'apply') lines.push(`written ${report.written}, failed ${report.failed.length}`);
199
+ return lines.join('\n');
200
+ }