@startsimpli/integrations 0.2.144 → 0.2.146

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 (72) hide show
  1. package/package.json +4 -4
  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 +102 -0
  5. package/src/__tests__/owner-backfill.test.ts +114 -0
  6. package/src/__tests__/owner-link.test.ts +115 -0
  7. package/src/__tests__/owner-picker.test.tsx +70 -0
  8. package/src/__tests__/roster.test.ts +27 -0
  9. package/src/__tests__/tracker-sort.test.ts +28 -0
  10. package/src/components/index.ts +1 -0
  11. package/src/components/pages/TaskDetailPage.tsx +33 -2
  12. package/src/components/pages/TrackerPage.tsx +47 -9
  13. package/src/components/pages/task-tracker/OwnerPicker.tsx +82 -0
  14. package/src/components/pages/tracker/TrackerBoard.tsx +45 -0
  15. package/src/components/pages/tracker/TrackerToolbar.tsx +44 -0
  16. package/src/corpus/briefing/actions/execute.ts +5 -4
  17. package/src/corpus/briefing/actions/log.ts +1 -1
  18. package/src/corpus/briefing/actions/types.ts +21 -0
  19. package/src/corpus/briefing/index.ts +1 -0
  20. package/src/corpus/briefing/intent/model.ts +3 -0
  21. package/src/corpus/briefing/intent/resolve.ts +14 -6
  22. package/src/corpus/briefing/intent/types.ts +7 -0
  23. package/src/corpus/briefing/reply/handle.ts +174 -0
  24. package/src/corpus/briefing/reply/index.ts +6 -0
  25. package/src/corpus/briefing/reply/respond.ts +95 -0
  26. package/src/corpus/briefing/reply/types.ts +112 -0
  27. package/src/corpus/briefing/store.ts +14 -0
  28. package/src/corpus/client.ts +16 -18
  29. package/src/corpus/entities.ts +4 -0
  30. package/src/corpus/index.ts +4 -0
  31. package/src/corpus/owner-backfill.ts +200 -0
  32. package/src/corpus/owner-link.ts +160 -0
  33. package/src/corpus/roster.ts +53 -0
  34. package/src/corpus/tracker-groups.ts +8 -4
  35. package/src/corpus/tracker-sort.ts +51 -0
  36. package/src/corpus/types.ts +13 -1
  37. package/src/native/app/FoundryApp.tsx +25 -7
  38. package/src/native/app/__tests__/briefingLink.test.tsx +57 -0
  39. package/src/native/app/__tests__/briefingServices.test.ts +92 -0
  40. package/src/native/app/__tests__/launch.test.ts +2 -1
  41. package/src/native/app/briefingServices.ts +101 -0
  42. package/src/native/app/config/__tests__/briefingConfig.test.ts +49 -0
  43. package/src/native/app/config/links.ts +4 -1
  44. package/src/native/app/config/types.ts +13 -1
  45. package/src/native/app/config/validate.ts +20 -2
  46. package/src/native/app/data.ts +3 -3
  47. package/src/native/app/device.ts +3 -0
  48. package/src/native/app/launch.ts +4 -0
  49. package/src/native/app/registry.tsx +3 -1
  50. package/src/native/app/screens/RecordScreen.tsx +3 -2
  51. package/src/native/app/services.ts +11 -30
  52. package/src/native/app/strings.ts +28 -0
  53. package/src/native/briefing/BriefingCard.tsx +14 -2
  54. package/src/native/briefing/BriefingReply.tsx +68 -0
  55. package/src/native/briefing/__tests__/BriefingReply.test.tsx +144 -0
  56. package/src/native/briefing/__tests__/fakeReply.test.ts +46 -0
  57. package/src/native/briefing/__tests__/notify.test.ts +42 -1
  58. package/src/native/briefing/__tests__/replyApi.test.ts +43 -0
  59. package/src/native/briefing/__tests__/replyController.test.ts +230 -0
  60. package/src/native/briefing/__tests__/replyPosition.test.ts +116 -0
  61. package/src/native/briefing/audioPlayer.ts +9 -2
  62. package/src/native/briefing/controller.ts +50 -5
  63. package/src/native/briefing/fake.ts +25 -18
  64. package/src/native/briefing/fakeReply.ts +65 -0
  65. package/src/native/briefing/index.ts +8 -3
  66. package/src/native/briefing/notify.ts +42 -0
  67. package/src/native/briefing/reply.ts +261 -0
  68. package/src/native/briefing/replyApi.ts +82 -0
  69. package/src/native/recording/__tests__/deeplink.test.ts +20 -0
  70. package/src/native/recording/deeplink.ts +7 -0
  71. package/src/native/tracker/__tests__/itemsChanged.test.ts +13 -0
  72. package/src/native/tracker/tab.tsx +4 -1
@@ -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,8 @@ 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
+ ...(decodeOwnerSubs(pick(data, 'owner_subs', 'ownerSubs')).length
741
+ ? { ownerSubs: decodeOwnerSubs(pick(data, 'owner_subs', 'ownerSubs')) } : {}),
739
742
  // Both spellings, for the reason spelled out on ORIGIN_KEY above: the
740
743
  // browser client camelCases `_origin` into `Origin` on the way in, and a
741
744
  // server-side fetch does not.
@@ -812,6 +815,7 @@ export function commitmentToEntity(commitment: Commitment): {
812
815
  ...(commitment.dueBasis ? { due_basis: commitment.dueBasis } : {}),
813
816
  ...(commitment.dueConfidence !== undefined ? { due_confidence: commitment.dueConfidence } : {}),
814
817
  ...(commitment.ownerSub ? { owner_sub: commitment.ownerSub } : {}),
818
+ ...(commitment.ownerSubs?.length ? { owner_subs: encodeOwnerSubs(commitment.ownerSubs) } : {}),
815
819
  ...(commitment.destination ? { destination: commitment.destination } : {}),
816
820
  ...(commitment.externalFocusId ? { external_focus_id: commitment.externalFocusId } : {}),
817
821
  ...(commitment.externalContainerId ? { external_container_id: commitment.externalContainerId } : {}),
@@ -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
+ }
@@ -0,0 +1,160 @@
1
+ /**
2
+ * OWNER TEXT -> PEOPLE (bd startsim-768w.38.29).
3
+ *
4
+ * A commitment's `owner_name` is whatever the meeting said. This module decides,
5
+ * conservatively, which workspace member (if any) that text means. The rule is
6
+ * Quinn's: link only when the text UNAMBIGUOUSLY matches exactly one member by
7
+ * first name or full-name variant. Several possible people, or none, are never
8
+ * merged: the row keeps its text and the UI offers a manual pick.
9
+ *
10
+ * Deliberately NOT matched: a surname alone, an email local part, a member with
11
+ * no display name, and service/QA accounts. Guessing merges two humans, which is
12
+ * worse than leaving one fragmented.
13
+ *
14
+ * Pure and generic: no I/O, no tenant knowledge, so the backfill, the write path
15
+ * and the picker all share one decision.
16
+ */
17
+
18
+ export interface RosterMember {
19
+ sub: string;
20
+ email: string;
21
+ name?: string;
22
+ /**
23
+ * Names someone DECLARED for this member (e.g. from an alias file), for rosters
24
+ * that carry only sub + email. Declared, never derived from the email.
25
+ */
26
+ aliases?: string[];
27
+ }
28
+
29
+ export type OwnerPart =
30
+ | { text: string; status: 'linked'; sub: string; via: 'first-name' | 'full-name' }
31
+ | { text: string; status: 'ambiguous'; candidates: string[] }
32
+ | { text: string; status: 'unmatched' };
33
+
34
+ export type OwnerOutcome = 'none' | 'linked' | 'partial' | 'ambiguous' | 'unmatched';
35
+
36
+ export interface OwnerPlan {
37
+ parts: OwnerPart[];
38
+ /** Subs of the parts that linked, in the order written, de-duplicated. */
39
+ subs: string[];
40
+ outcome: OwnerOutcome;
41
+ }
42
+
43
+ const SERVICE_LOCAL = /^(qa|idf|verify|test|bot|system|noreply|no-reply|admin)([+\-_.]|$)/i;
44
+ const SERVICE_DOMAIN = /@(local\.test|foundry\.local)$/i;
45
+
46
+ /** Accounts that are not people: never a candidate for a name in a meeting. */
47
+ export function isServiceAccount(member: RosterMember): boolean {
48
+ const email = member.email ?? '';
49
+ return SERVICE_LOCAL.test(email) || SERVICE_DOMAIN.test(email) || SERVICE_LOCAL.test(member.name ?? '');
50
+ }
51
+
52
+ function normalize(text: string): string[] {
53
+ return text
54
+ .normalize('NFKD')
55
+ .replace(/[̀-ͯ]/g, '')
56
+ .toLowerCase()
57
+ .replace(/\([^)]*\)/g, ' ')
58
+ .replace(/[^a-z0-9\s]/g, ' ')
59
+ .split(/\s+/)
60
+ .filter(Boolean);
61
+ }
62
+
63
+ /** "Jude, Jenny" / "A & B" / "A and B" / "A; B" / "A / B" -> separate names. */
64
+ export function splitOwnerNames(text: string): string[] {
65
+ const seen = new Set<string>();
66
+ const out: string[] = [];
67
+ for (const raw of (text ?? '').split(/\s*(?:,|;|&|\/|\+|\band\b)\s*/i)) {
68
+ const name = raw.trim();
69
+ const key = normalize(name).join(' ');
70
+ if (!key || seen.has(key)) continue;
71
+ seen.add(key);
72
+ out.push(name);
73
+ }
74
+ return out;
75
+ }
76
+
77
+ interface Candidate { sub: string; tokens: string[] }
78
+
79
+ function candidates(roster: RosterMember[]): Candidate[] {
80
+ const bySub = new Map<string, Candidate>();
81
+ const out: Candidate[] = [];
82
+ for (const member of roster) {
83
+ if (!member.sub || isServiceAccount(member)) continue;
84
+ for (const raw of [member.name, ...(member.aliases ?? [])]) {
85
+ const tokens = raw ? normalize(raw) : [];
86
+ const key = `${member.sub}\u0000${tokens.join(' ')}`;
87
+ if (!tokens.length || bySub.has(key)) continue;
88
+ bySub.set(key, { sub: member.sub, tokens });
89
+ out.push({ sub: member.sub, tokens });
90
+ }
91
+ }
92
+ return out;
93
+ }
94
+
95
+ function verdict(text: string, found: Candidate[], via: 'first-name' | 'full-name'): OwnerPart | null {
96
+ const subs = [...new Set(found.map((hit) => hit.sub))];
97
+ if (subs.length === 1) return { text, status: 'linked', sub: subs[0], via };
98
+ if (subs.length > 1) return { text, status: 'ambiguous', candidates: subs };
99
+ return null;
100
+ }
101
+
102
+ export function matchOwnerName(text: string, roster: RosterMember[]): OwnerPart {
103
+ const query = normalize(text);
104
+ const pool = candidates(roster);
105
+ if (!query.length) return { text, status: 'unmatched' };
106
+ if (query.length === 1) {
107
+ const hit = verdict(text, pool.filter((c) => c.tokens[0] === query[0]), 'first-name');
108
+ return hit ?? { text, status: 'unmatched' };
109
+ }
110
+ const joined = query.join(' ');
111
+ const exact = verdict(text, pool.filter((c) => c.tokens.join(' ') === joined), 'full-name');
112
+ if (exact) return exact;
113
+ const last = query[query.length - 1];
114
+ const variant = verdict(
115
+ text,
116
+ pool.filter((c) => c.tokens.length > 1 && c.tokens[0] === query[0] && c.tokens[c.tokens.length - 1] === last),
117
+ 'full-name',
118
+ );
119
+ return variant ?? { text, status: 'unmatched' };
120
+ }
121
+
122
+ export function planOwnerLinks(ownerText: string, roster: RosterMember[]): OwnerPlan {
123
+ const parts = splitOwnerNames(ownerText).map((name) => matchOwnerName(name, roster));
124
+ const subs: string[] = [];
125
+ for (const part of parts) if (part.status === 'linked' && !subs.includes(part.sub)) subs.push(part.sub);
126
+ let outcome: OwnerOutcome;
127
+ if (!parts.length) outcome = 'none';
128
+ else if (parts.every((p) => p.status === 'linked')) outcome = 'linked';
129
+ else if (subs.length) outcome = 'partial';
130
+ else outcome = parts.some((p) => p.status === 'ambiguous') ? 'ambiguous' : 'unmatched';
131
+ return { parts, subs, outcome };
132
+ }
133
+
134
+ // ---- joint-owner storage --------------------------------------------------
135
+ //
136
+ // `owner_subs` is a DELIMITED TEXT attribute (`|a|b|`), not a JSON list. The
137
+ // tenant filters only declared attributes, and `attr.owner_subs__icontains=|a|`
138
+ // works identically on Postgres and the SQLite local stack, where a JSON
139
+ // `__contains` does not. `owner_sub` stays as the first owner so every existing
140
+ // reader (isTask, the single-owner picker) keeps working.
141
+
142
+ export const OWNER_SUBS_ATTRIBUTES: Array<[string, string]> = [
143
+ ['owner_sub', 'text'], ['owner_subs', 'text'], ['owner_link', 'text'],
144
+ ];
145
+
146
+ export function encodeOwnerSubs(subs: string[]): string {
147
+ const clean = [...new Set(subs.filter(Boolean))];
148
+ return clean.length ? `|${clean.join('|')}|` : '';
149
+ }
150
+
151
+ export function decodeOwnerSubs(value: unknown): string[] {
152
+ if (Array.isArray(value)) return value.map(String).filter(Boolean);
153
+ if (typeof value !== 'string') return [];
154
+ return value.split('|').filter(Boolean);
155
+ }
156
+
157
+ /** The server filter that finds a person's work, joint or sole. */
158
+ export function ownerSubsFilter(sub: string): Record<string, string> {
159
+ return { 'attr.owner_subs__icontains': `|${sub}|` };
160
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * THE WORKSPACE ROSTER WITH NAMES (bd startsim-768w.38.29).
3
+ *
4
+ * `/api/v1/org/members/` carries only `sub` + `email` and is admin-only, so on
5
+ * its own it can never tell "Quinn" from anyone. `/api/v1/org/roster/` is the
6
+ * narrower read any member may make: `{sub, label}`, the label being the
7
+ * person's name. Each is read soft (a failure yields nothing for that source)
8
+ * and joined by `sub`: the roster supplies the name, the members list the email.
9
+ */
10
+ import type { RosterMember } from './owner-link';
11
+
12
+ interface Http {
13
+ get<T>(path: string, options?: { params?: Record<string, unknown> }): Promise<T>;
14
+ }
15
+ interface Page { results?: Array<Record<string, unknown>>; next_cursor?: string | null }
16
+
17
+ const text = (v: unknown) => (typeof v === 'string' ? v : v == null ? '' : String(v));
18
+
19
+ export async function readRoster(
20
+ http: Http,
21
+ paths: { members: string; roster: string },
22
+ maxPages = 20,
23
+ ): Promise<RosterMember[]> {
24
+ const names = new Map<string, string>();
25
+ try {
26
+ let cursor = '';
27
+ for (let page = 0; page < maxPages; page += 1) {
28
+ const res = await http.get<Page>(paths.roster, cursor ? { params: { cursor } } : {});
29
+ for (const row of res.results ?? []) {
30
+ const sub = text(row.sub);
31
+ if (sub) names.set(sub, text(row.label ?? row.name));
32
+ }
33
+ cursor = text(res.next_cursor);
34
+ if (!cursor) break;
35
+ }
36
+ } catch { /* names unavailable: members still list, they just cannot be matched by name */ }
37
+
38
+ const out = new Map<string, RosterMember>();
39
+ try {
40
+ const res = await http.get<Page>(paths.members, {});
41
+ for (const row of res.results ?? []) {
42
+ const user = (row.user ?? {}) as Record<string, unknown>;
43
+ const sub = text(user.sub ?? row.sub);
44
+ if (!sub) continue;
45
+ const name = text(user.name) || names.get(sub) || '';
46
+ out.set(sub, { sub, email: text(user.email ?? row.email), ...(name ? { name } : {}) });
47
+ }
48
+ } catch { /* members is admin-only: fall back to the roster alone */ }
49
+ for (const [sub, name] of names) {
50
+ if (!out.has(sub)) out.set(sub, { sub, email: '', ...(name ? { name } : {}) });
51
+ }
52
+ return [...out.values()];
53
+ }
@@ -15,7 +15,8 @@
15
15
  */
16
16
  import { daysBetween, WEEK_DAYS } from './due-groups';
17
17
  import { dueDay, localDate } from './today';
18
- import type { Commitment } from './types';
18
+ import { compareCommitments } from './tracker-sort';
19
+ import type { Commitment, CommitmentSort } from './types';
19
20
 
20
21
  /** Subtypes that are things to do. The rest are what was said in the meeting. */
21
22
  const TASK_SUBTYPES = new Set(['action', 'requirement']);
@@ -49,7 +50,7 @@ type Row = Pick<Commitment, 'status' | 'dueAt' | 'subtype' | 'ownerName' | 'owne
49
50
 
50
51
  export function groupTracker<T extends Row>(
51
52
  items: T[],
52
- options: { now: number; timeZone?: string; staleDays?: number },
53
+ options: { now: number; timeZone?: string; staleDays?: number; sort?: CommitmentSort },
53
54
  ): TrackerGroups<T> {
54
55
  const timeZone = options.timeZone ?? 'UTC';
55
56
  const today = localDate(options.now, timeZone);
@@ -73,8 +74,11 @@ export function groupTracker<T extends Row>(
73
74
  (idle >= staleDays ? out.stale : out.later).push(entry);
74
75
  }
75
76
 
76
- const dated = (a: TrackerEntry<T>, b: TrackerEntry<T>) =>
77
- (a.due ?? '9999').localeCompare(b.due ?? '9999') || (a.item.priority ?? 99) - (b.item.priority ?? 99);
77
+ const byKey = compareCommitments(options.sort);
78
+ const dated = options.sort && options.sort !== 'due'
79
+ ? (a: TrackerEntry<T>, b: TrackerEntry<T>) => byKey(a.item as unknown as Commitment, b.item as unknown as Commitment)
80
+ : (a: TrackerEntry<T>, b: TrackerEntry<T>) =>
81
+ (a.due ?? '9999').localeCompare(b.due ?? '9999') || (a.item.priority ?? 99) - (b.item.priority ?? 99);
78
82
  const recent = (a: TrackerEntry<T>, b: TrackerEntry<T>) =>
79
83
  (b.item.resolvedAt ?? b.item.lastSeenAt ?? '').localeCompare(a.item.resolvedAt ?? a.item.lastSeenAt ?? '');
80
84
  for (const key of ['today', 'inProgress', 'upNext', 'later', 'stale', 'statements'] as const) out[key].sort(dated);
@@ -0,0 +1,51 @@
1
+ /**
2
+ * HOW THE TRACKER ORDERS WHAT IS OWED.
3
+ *
4
+ * One table drives both halves, so they cannot disagree: `order` is the server
5
+ * parameter (so page one of a long list is the right page one, not whatever the
6
+ * first 200 rows happened to be), and `compare` orders the rows already loaded
7
+ * (within each group, or each board column). Every key is a declared attribute
8
+ * of the commitment type, which is what makes it sortable server-side at all.
9
+ */
10
+ import type { Commitment, CommitmentSort } from './types';
11
+
12
+ type Sortable = Pick<Commitment, 'title' | 'ownerName' | 'dueAt' | 'lastSeenAt' | 'firstSeenAt'> & { priority?: number };
13
+
14
+ export const DEFAULT_TRACKER_SORT: CommitmentSort = 'due';
15
+
16
+ export const TRACKER_SORTS: ReadonlyArray<{ key: CommitmentSort; label: string; order: string }> = [
17
+ { key: 'due', label: 'Due date', order: 'attr.due_at' },
18
+ { key: 'updated', label: 'Recently updated', order: '-attr.last_seen_at' },
19
+ { key: 'newest', label: 'Newest first', order: '-attr.first_seen_at' },
20
+ { key: 'title', label: 'Title (A to Z)', order: 'attr.title' },
21
+ { key: 'owner', label: 'Owner (A to Z)', order: 'attr.owner_name' },
22
+ ];
23
+
24
+ /** The server `order=` value for a sort key. */
25
+ export function commitmentOrder(sort: CommitmentSort = DEFAULT_TRACKER_SORT): string {
26
+ return (TRACKER_SORTS.find((s) => s.key === sort) ?? TRACKER_SORTS[0]).order;
27
+ }
28
+
29
+ const text = (v: string | undefined | null) => (v ?? '').trim().toLowerCase();
30
+ /** Empty strings last: a missing owner or date is never "first". */
31
+ const blankLast = (a: string, b: string) => (a === '' ? (b === '' ? 0 : 1) : b === '' ? -1 : a.localeCompare(b));
32
+ const dueKey = (x: Sortable) => (x.dueAt ?? '').slice(0, 10);
33
+
34
+ /** Orders two rows the way `commitmentOrder(sort)` orders them on the server. */
35
+ export function compareCommitments(sort: CommitmentSort = DEFAULT_TRACKER_SORT) {
36
+ return (a: Sortable, b: Sortable): number => {
37
+ const byDue = blankLast(dueKey(a), dueKey(b)) || (a.priority ?? 99) - (b.priority ?? 99);
38
+ switch (sort) {
39
+ case 'updated':
40
+ return (b.lastSeenAt ?? '').localeCompare(a.lastSeenAt ?? '') || byDue;
41
+ case 'newest':
42
+ return (b.firstSeenAt ?? '').localeCompare(a.firstSeenAt ?? '') || byDue;
43
+ case 'title':
44
+ return text(a.title).localeCompare(text(b.title)) || byDue;
45
+ case 'owner':
46
+ return blankLast(text(a.ownerName), text(b.ownerName)) || byDue;
47
+ default:
48
+ return byDue;
49
+ }
50
+ };
51
+ }
@@ -734,6 +734,13 @@ export interface Commitment {
734
734
  * makes "assigned to me" a server filter instead of a scan over free text.
735
735
  */
736
736
  ownerSub?: string;
737
+ /**
738
+ * ALL owners as members, for a joint commitment. `ownerSub` is always the
739
+ * first of these, so single-owner readers keep working. Empty or absent means
740
+ * the owner is still only text. Stored as `owner_subs` (`|a|b|`, see
741
+ * `./owner-link`).
742
+ */
743
+ ownerSubs?: string[];
737
744
  /**
738
745
  * Where the row came from: `tenant-extraction`, `human`, `central-pipeline`.
739
746
  *
@@ -833,7 +840,12 @@ export interface ResolutionClaim {
833
840
  }
834
841
 
835
842
  /** Server-side filters for the tracking surface (CLAUDE.md rule 8). */
843
+ /** How the tracker orders a page of to-dos; see `tracker-sort.ts`. */
844
+ export type CommitmentSort = 'due' | 'updated' | 'newest' | 'title' | 'owner';
845
+
836
846
  export interface CommitmentQuery {
847
+ /** Server-side order. Default `due`. */
848
+ sort?: CommitmentSort;
837
849
  status?: CommitmentStatus | CommitmentStatus[];
838
850
  subtype?: CommitmentSubtype;
839
851
  owner?: string;
@@ -892,7 +904,7 @@ export interface CommitmentApi {
892
904
  * read-modify-write, which is the race the upsert exists to remove.
893
905
  */
894
906
  updateCommitment?(item: Commitment, patch: Partial<Pick<Commitment,
895
- 'status' | 'statusReason' | 'ownerName' | 'ownerSub' | 'dueAt' | 'subtype'
907
+ 'status' | 'statusReason' | 'ownerName' | 'ownerSub' | 'ownerSubs' | 'dueAt' | 'subtype'
896
908
  | 'title' | 'detail' | 'resolvedAt'>> & {
897
909
  /** `null` clears it (undoing a voice-set priority). */
898
910
  priority?: number | null;
@@ -6,6 +6,9 @@ import { createTabsNavigator, type TabsNavigator } from '../shell/navigator';
6
6
  import type { SessionState } from '../recording/session';
7
7
  import { createBanners } from './banners';
8
8
  import { createFoundryData } from './data';
9
+ import { fakeEntityRows } from './fakeEntities';
10
+ import { createFakeNativeCorpusApi, type FakeNativeCorpusApi } from '../corpus/fake';
11
+ import { fakeBriefingRows } from '../briefing/fakeReply';
9
12
  import type { FoundryDevice } from './device';
10
13
  import { readLaunch } from './launch';
11
14
  import { buildFoundryTabs, createScreenRegistry, type ScreenFactory } from './registry';
@@ -44,10 +47,17 @@ function Themed({ mode, children }: { mode: FoundryAppConfig['theme']['mode'] |
44
47
  function Root({ config, device, registry }: { config: FoundryAppConfig; device: FoundryDevice; registry: ReturnType<typeof createScreenRegistry> }) {
45
48
  const launch = useMemo(() => readLaunch((k) => Settings.get(k), config), [config]);
46
49
  const strings = useMemo(() => foundryStrings(config), [config]);
50
+ // The fake briefing's replies write to the very rows the Tracker tab reads, so both share one fake tenant.
51
+ const fakeCorpus = useMemo(
52
+ () => (launch.fakeBriefing
53
+ ? createFakeNativeCorpusApi({ scenario: launch.scenario, extraEntities: [...fakeEntityRows(config), ...fakeBriefingRows()] })
54
+ : null),
55
+ [config, launch],
56
+ );
47
57
  const { banners, services } = useMemo(() => {
48
58
  const b = createBanners();
49
- return { banners: b, services: createFoundryServices({ config, device, banners: b, strings, fakeBriefing: launch.fakeBriefing }) };
50
- }, [config, device, strings, launch]);
59
+ return { banners: b, services: createFoundryServices({ config, device, banners: b, strings, fakeBriefing: launch.fakeBriefing ? { corpus: fakeCorpus as FakeNativeCorpusApi, script: launch.fakeReply } : null }) };
60
+ }, [config, device, strings, launch, fakeCorpus]);
51
61
  // The engine is the device's; a haptic that throws (no taptic hardware, simulator) never breaks a screen.
52
62
  // Every call is logged to the diagnostics (`haptic`, then `haptic.result`) so a device run proves the engine was invoked.
53
63
  const haptic = useCallback((kind: HapticKind, source?: string) => {
@@ -66,8 +76,8 @@ function Root({ config, device, registry }: { config: FoundryAppConfig; device:
66
76
  const [expired, setExpired] = useState(false);
67
77
  const [showDiag, setShowDiag] = useState(false);
68
78
  const data = useMemo(
69
- () => createFoundryData({ config, authorizedFetch: services.session.authorizedFetch, fake: launch.fake, scenario: launch.scenario }),
70
- [config, services, launch],
79
+ () => createFoundryData({ config, authorizedFetch: services.session.authorizedFetch, fake: launch.fake, scenario: launch.scenario, ...(fakeCorpus ? { fakeCorpus } : {}) }),
80
+ [config, services, launch, fakeCorpus],
71
81
  );
72
82
 
73
83
  // The tenant's declared types fill what the config left to defaults (entity types, tabs, Home cards). Read once per
@@ -105,7 +115,15 @@ function Root({ config, device, registry }: { config: FoundryAppConfig; device:
105
115
  }, [launch]);
106
116
 
107
117
  useEffect(() => {
108
- if (launch.fake) { setAuth('signedIn'); return; }
118
+ if (launch.fake) {
119
+ setAuth('signedIn');
120
+ // Links and the morning notification work over the fakes too, so a simulator check can open the briefing from a link.
121
+ void services.deepLink.sessionReady();
122
+ void services.briefing?.syncNotification();
123
+ void Linking.getInitialURL().then((url) => url && services.deepLink.handle(url));
124
+ const sub = Linking.addEventListener('url', ({ url }) => services.deepLink.handle(url));
125
+ return () => sub.remove();
126
+ }
109
127
  const off = services.session.subscribe((next) => {
110
128
  setAuth(next);
111
129
  if (next === 'signedIn') { setExpired(false); void services.onReady(); }
@@ -125,13 +143,13 @@ function Root({ config, device, registry }: { config: FoundryAppConfig; device:
125
143
  // The GO screen reads the latest element through the ref, so it re-renders without rebuilding the tabs.
126
144
  const record = (
127
145
  services.recording
128
- ? <RecordScreen recording={services.recording} briefing={services.briefing?.controller ?? null} strings={strings} onOpenDiagnostics={() => setShowDiag(true)} onSignOut={() => { void services.session.signOut(); }} />
146
+ ? <RecordScreen recording={services.recording} briefing={services.briefing?.controller ?? null} briefingReply={services.briefing?.reply ?? null} strings={strings} onOpenDiagnostics={() => setShowDiag(true)} onSignOut={() => { void services.session.signOut(); }} />
129
147
  : null
130
148
  );
131
149
  const recordRef = useRef<ReactNode>(record);
132
150
  recordRef.current = record;
133
151
  const tabs = useMemo(
134
- () => buildFoundryTabs({ config: appConfig, corpus: data.corpus, notes: data.notes, record: () => recordRef.current, member: data.member, openUrl: data.openUrl ?? ((url) => Linking.openURL(url)) }, registry),
152
+ () => buildFoundryTabs({ config: appConfig, corpus: data.corpus, notes: data.notes, record: () => recordRef.current, member: data.member, itemsChanged: services.briefing?.itemsChanged, openUrl: data.openUrl ?? ((url) => Linking.openURL(url)) }, registry),
135
153
  [appConfig, data, registry],
136
154
  );
137
155