@startsimpli/integrations 0.2.200 → 0.2.202

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 (147) hide show
  1. package/package.json +7 -7
  2. package/src/__tests__/briefing-actions.test.ts +11 -0
  3. package/src/__tests__/briefing-edits.test.ts +98 -0
  4. package/src/__tests__/briefing-markdown.test.ts +64 -0
  5. package/src/__tests__/converse-brain.test.ts +64 -1
  6. package/src/__tests__/converse-cards.test.ts +53 -0
  7. package/src/__tests__/converse-handoff.test.ts +8 -0
  8. package/src/__tests__/converse-meeting-brief.test.ts +72 -8
  9. package/src/__tests__/converse-meeting-duplex.test.ts +132 -0
  10. package/src/__tests__/converse-meeting-keep-speech.test.ts +87 -0
  11. package/src/__tests__/converse-meeting-vad.test.ts +1 -1
  12. package/src/__tests__/converse-page.test.tsx +148 -37
  13. package/src/__tests__/converse-roci.test.ts +22 -0
  14. package/src/__tests__/converse-spoken-form.test.ts +10 -0
  15. package/src/__tests__/converse-spoken-summary.test.ts +27 -6
  16. package/src/__tests__/converse-structure.test.ts +27 -0
  17. package/src/__tests__/converse-view.test.ts +46 -0
  18. package/src/__tests__/converse.test.ts +29 -2
  19. package/src/__tests__/corpus-ask.test.ts +22 -0
  20. package/src/__tests__/corpus-tracker.test.tsx +42 -174
  21. package/src/__tests__/data-table-logic.test.ts +75 -0
  22. package/src/__tests__/data-table.test.tsx +133 -0
  23. package/src/__tests__/extract-classify.test.ts +17 -0
  24. package/src/__tests__/fleet-page.test.tsx +57 -0
  25. package/src/__tests__/fleet-view.test.ts +149 -0
  26. package/src/__tests__/home-brief.test.tsx +25 -40
  27. package/src/__tests__/library-call-shape.test.tsx +164 -0
  28. package/src/__tests__/load-error.test.tsx +1 -1
  29. package/src/__tests__/mini-markdown.test.tsx +24 -0
  30. package/src/__tests__/overview-page.test.tsx +36 -6
  31. package/src/__tests__/plan-shell.test.tsx +6 -4
  32. package/src/__tests__/project-basis-entity.test.ts +19 -0
  33. package/src/__tests__/project-basis.test.ts +21 -0
  34. package/src/__tests__/relay-cli.test.ts +10 -1
  35. package/src/__tests__/task-detail-project-guess.test.tsx +46 -0
  36. package/src/__tests__/timeline-events.test.ts +65 -0
  37. package/src/__tests__/timeline-table.test.tsx +66 -0
  38. package/src/__tests__/todo-table-model.test.ts +75 -0
  39. package/src/__tests__/todo-table.test.tsx +202 -0
  40. package/src/__tests__/tracker-timeline-component.test.tsx +4 -4
  41. package/src/__tests__/tracker-timeline-reader.test.ts +1 -1
  42. package/src/comms/__tests__/app-sends-page.test.tsx +69 -0
  43. package/src/comms/api/comms.ts +23 -0
  44. package/src/comms/components/ResultsPanel.tsx +2 -2
  45. package/src/comms/components/SendLog.tsx +20 -8
  46. package/src/comms/components/index.ts +1 -0
  47. package/src/comms/components/pages/AppSendsPage.tsx +58 -0
  48. package/src/comms/hooks/index.ts +8 -3
  49. package/src/components/FolderTree.tsx +12 -3
  50. package/src/components/index.ts +4 -1
  51. package/src/components/pages/ConversePage.tsx +114 -105
  52. package/src/components/pages/FleetPage.tsx +115 -0
  53. package/src/components/pages/LibraryPage.tsx +63 -24
  54. package/src/components/pages/TaskDetailPage.tsx +27 -1
  55. package/src/components/pages/TrackerPage.tsx +170 -474
  56. package/src/components/pages/converse/CardView.tsx +72 -0
  57. package/src/components/pages/converse/SettingsMenu.tsx +37 -0
  58. package/src/components/pages/converse/Thread.tsx +48 -33
  59. package/src/components/pages/converse/useNeedsYou.ts +60 -0
  60. package/src/components/pages/home/BriefCard.tsx +16 -7
  61. package/src/components/pages/home/HomeBriefPage.tsx +6 -91
  62. package/src/components/pages/home/MiniMarkdown.tsx +51 -0
  63. package/src/components/pages/home/{DueSoonLine.tsx → dueSoonText.ts} +2 -11
  64. package/src/components/pages/home/index.ts +1 -1
  65. package/src/components/pages/overview/OverviewPage.tsx +46 -83
  66. package/src/components/pages/plan/TalkPage.tsx +5 -14
  67. package/src/components/pages/plan/TimelinePage.tsx +4 -2
  68. package/src/components/pages/task-tracker/ProjectGuess.tsx +42 -0
  69. package/src/components/pages/tracker/SweepPanel.tsx +108 -0
  70. package/src/components/pages/tracker/TimelineTable.tsx +70 -0
  71. package/src/components/pages/tracker/TrackerTimeline.tsx +32 -15
  72. package/src/components/table/DataTable.tsx +92 -0
  73. package/src/components/table/RowMenu.tsx +35 -0
  74. package/src/components/table/TablePagination.tsx +63 -0
  75. package/src/components/table/TableToolbar.tsx +56 -0
  76. package/src/components/table/TodoTable.tsx +142 -0
  77. package/src/components/table/index.ts +10 -0
  78. package/src/components/table/table-logic.ts +60 -0
  79. package/src/components/table/todo-model.ts +93 -0
  80. package/src/corpus/ask-items.ts +7 -4
  81. package/src/corpus/ask.ts +1 -1
  82. package/src/corpus/briefing/actions/confirm.ts +9 -1
  83. package/src/corpus/briefing/actions/execute.ts +71 -11
  84. package/src/corpus/briefing/actions/log.ts +1 -1
  85. package/src/corpus/briefing/actions/seam.ts +18 -2
  86. package/src/corpus/briefing/actions/types.ts +14 -0
  87. package/src/corpus/briefing/generate-weekly.ts +4 -0
  88. package/src/corpus/briefing/generate.ts +4 -0
  89. package/src/corpus/briefing/index.ts +1 -0
  90. package/src/corpus/briefing/intent/describe.ts +5 -1
  91. package/src/corpus/briefing/intent/edits.ts +92 -0
  92. package/src/corpus/briefing/intent/grammar.ts +3 -0
  93. package/src/corpus/briefing/intent/ground.ts +5 -1
  94. package/src/corpus/briefing/intent/match.ts +3 -1
  95. package/src/corpus/briefing/intent/model.ts +36 -3
  96. package/src/corpus/briefing/intent/resolve.ts +12 -1
  97. package/src/corpus/briefing/intent/types.ts +8 -0
  98. package/src/corpus/briefing/markdown.ts +71 -0
  99. package/src/corpus/briefing/speak.ts +13 -0
  100. package/src/corpus/client.ts +40 -146
  101. package/src/corpus/converse/brain.ts +41 -13
  102. package/src/corpus/converse/briefing-queue.ts +105 -27
  103. package/src/corpus/converse/cards.ts +69 -0
  104. package/src/corpus/converse/client.ts +6 -0
  105. package/src/corpus/converse/fleet-view.ts +126 -0
  106. package/src/corpus/converse/fleet.ts +18 -5
  107. package/src/corpus/converse/followups.ts +12 -2
  108. package/src/corpus/converse/handle.ts +21 -12
  109. package/src/corpus/converse/handoff.ts +7 -2
  110. package/src/corpus/converse/index.ts +11 -3
  111. package/src/corpus/converse/meeting-config.ts +8 -4
  112. package/src/corpus/converse/meeting.ts +66 -11
  113. package/src/corpus/converse/respond.ts +14 -2
  114. package/src/corpus/converse/roci.ts +13 -0
  115. package/src/corpus/converse/spoken-form.ts +9 -2
  116. package/src/corpus/converse/spoken-summary.ts +30 -8
  117. package/src/corpus/converse/store.ts +2 -0
  118. package/src/corpus/converse/structure.ts +39 -0
  119. package/src/corpus/converse/types.ts +14 -1
  120. package/src/corpus/converse/view.ts +34 -0
  121. package/src/corpus/entities.ts +2 -0
  122. package/src/corpus/extract.ts +9 -4
  123. package/src/corpus/index.ts +2 -0
  124. package/src/corpus/participants.ts +220 -0
  125. package/src/corpus/project-basis.ts +23 -0
  126. package/src/corpus/timeline-events.ts +83 -0
  127. package/src/corpus/tracker-sort.ts +9 -3
  128. package/src/corpus/tracker-timeline-client.ts +2 -0
  129. package/src/corpus/tracker-timeline.ts +4 -0
  130. package/src/corpus/types.ts +38 -5
  131. package/src/native/app/__tests__/plan-talk-registry.test.tsx +2 -1
  132. package/src/native/app/converseServices.ts +5 -3
  133. package/src/native/app/device.ts +2 -0
  134. package/src/native/converse/ConverseScreen.tsx +30 -4
  135. package/src/native/converse/__tests__/liveScreen.test.tsx +35 -2
  136. package/src/native/converse/__tests__/meetingIO.test.ts +55 -1
  137. package/src/native/converse/format.ts +2 -2
  138. package/src/native/converse/io.ts +15 -5
  139. package/src/native/home/HomeScreen.tsx +1 -1
  140. package/src/native/home/tab.tsx +1 -2
  141. package/src/native/plan/PlanTab.tsx +1 -2
  142. package/src/native/plan/__tests__/plan-tab.test.tsx +5 -5
  143. package/src/native/talk/TalkTab.tsx +1 -1
  144. package/src/native/talk/__tests__/talk-tab.test.tsx +1 -1
  145. package/src/__tests__/home-needs-your-call.test.tsx +0 -65
  146. package/src/components/pages/tracker/TrackerBoard.tsx +0 -45
  147. package/src/components/pages/tracker/TrackerToolbar.tsx +0 -44
@@ -12,9 +12,10 @@
12
12
  * assistant and the briefing stays open where it was.
13
13
  */
14
14
  import type { BriefingItem } from '../briefing/types';
15
- import { speakable } from '../briefing/speak';
16
- import { spokenWhen } from '../briefing/intent/dates';
15
+ import { speakCount, speakable } from '../briefing/speak';
16
+ import { normalizeSpeech, spokenWhen, splitWhen } from '../briefing/intent/dates';
17
17
  import type { VoiceAction } from '../briefing/intent/types';
18
+ import { contentWords } from '../briefing/intent/match';
18
19
  import { dueDay, localDate } from '../today';
19
20
 
20
21
  export interface QueueItem {
@@ -32,11 +33,23 @@ export interface QueueItem {
32
33
  /** To-dos only: why it is in the queue. */
33
34
  when?: 'overdue' | 'today';
34
35
  }
35
- export interface BriefingState { queue: QueueItem[]; index: number }
36
+ export interface BriefingState {
37
+ queue: QueueItem[];
38
+ index: number;
39
+ /** Old overdue items left out of the walk (said once at the end, never read one by one). */
40
+ older?: number;
41
+ }
42
+
43
+ /** What an item with no project is called out loud. */
44
+ export const UNFILED = 'Unfiled';
45
+ /** The key a skip is remembered under for the day: the to-do's id, or the relay question's own words. */
46
+ export const skipKey = (q: QueueItem): string => (q.kind === 'todo' ? q.itemId ?? q.id : `relay:${q.project}:${q.text}`);
36
47
 
37
48
  /** What the walk wants done after an answer. The caller does it (it owns the item seam and the relay inbox). */
38
49
  export type BriefingEffect =
39
50
  | { kind: 'todo'; action: VoiceAction }
51
+ /** Skipped: remember it for the rest of today so the next briefing does not bring it back. */
52
+ | { kind: 'skip'; key: string }
40
53
  | { kind: 'relay'; text: string };
41
54
 
42
55
  export interface BriefingStep {
@@ -64,6 +77,8 @@ export const BRIEF_ME = new RegExp(
64
77
  const norm = (s: string) => s.toLowerCase().replace(/[’]/g, "'").replace(/[^a-z0-9' ]+/g, ' ').replace(/\s+/g, ' ').trim();
65
78
  const cap = (s: string) => (s ? s[0].toUpperCase() + s.slice(1) : s);
66
79
  const MAX_TODOS = 8;
80
+ /** Overdue items that are not urgent: how many are read out; the rest are a count. */
81
+ const MAX_OLD_OVERDUE = 3;
67
82
  const MAX_RELAY = 12;
68
83
 
69
84
  /** What the relay is waiting on him for, read from its snapshot: bullets under a "waiting on you / open questions" heading. */
@@ -94,28 +109,68 @@ export function relayItemsFrom(snapshot: string): Array<Pick<QueueItem, 'project
94
109
  /** "What needs me / what do you need from me" is about what is waiting on HIM: the relay's questions come first, his own due items after. */
95
110
  export const NEEDS_ME = /\b(needs? (me|my attention|a yes|a decision|an answer)|need from me)\b/i;
96
111
 
97
- export function buildQueue(input: { items: BriefingItem[]; relayItems: Array<Pick<QueueItem, 'project' | 'text' | 'more'>>; now: number; timeZone: string; relayFirst?: boolean }): QueueItem[] {
112
+ export interface QueueInput {
113
+ items: BriefingItem[];
114
+ relayItems: Array<Pick<QueueItem, 'project' | 'text' | 'more'>>;
115
+ now: number;
116
+ timeZone: string;
117
+ relayFirst?: boolean;
118
+ /** Keys (see `skipKey`) skipped earlier today: left out. */
119
+ skipped?: string[];
120
+ }
121
+
122
+ /** Most important first: urgent, then what is due today, then by priority, then the most recently overdue (not the oldest). */
123
+ function rank(a: { i: BriefingItem; day: string }, b: { i: BriefingItem; day: string }, today: string): number {
124
+ const urgent = (x: BriefingItem) => ((x.priority ?? 9) <= 1 ? 0 : 1);
125
+ const isToday = (d: string) => (d === today ? 0 : 1);
126
+ return urgent(a.i) - urgent(b.i) || isToday(a.day) - isToday(b.day) || (a.i.priority ?? 9) - (b.i.priority ?? 9) || (a.day < b.day ? 1 : a.day > b.day ? -1 : 0);
127
+ }
128
+
129
+ export function rankQueue(input: QueueInput): { queue: QueueItem[]; older: number } {
98
130
  const today = localDate(input.now, input.timeZone);
131
+ const skipped = new Set(input.skipped ?? []);
99
132
  const open = (i: BriefingItem) => !['done', 'dropped'].includes(i.status) && !['completed', 'canceled'].includes(i.linearState ?? '');
100
- const due = input.items
133
+ const ranked = input.items
101
134
  .filter(open)
135
+ .filter((i) => !skipped.has(i.id))
102
136
  .map((i) => ({ i, day: dueDay(i.dueAt, input.timeZone) }))
103
137
  .filter((x): x is { i: BriefingItem; day: string } => x.day !== null && x.day <= today)
104
- .sort((a, b) => (a.day < b.day ? -1 : a.day > b.day ? 1 : (a.i.priority ?? 9) - (b.i.priority ?? 9)))
105
- .slice(0, MAX_TODOS);
138
+ .sort((a, b) => rank(a, b, today));
139
+ const due: typeof ranked = [];
140
+ let older = 0;
141
+ let oldRead = 0;
142
+ for (const x of ranked) {
143
+ const old = x.day < today && (x.i.priority ?? 9) > 1;
144
+ if (old && oldRead >= MAX_OLD_OVERDUE) { older += 1; continue; }
145
+ if (due.length >= MAX_TODOS) { if (old) older += 1; continue; }
146
+ if (old) oldRead += 1;
147
+ due.push(x);
148
+ }
106
149
  const todos: QueueItem[] = due.map(({ i, day }) => {
107
150
  const overdue = day < today;
108
- const title = cap(speakable(i.title, 16)) || 'That item';
151
+ const title = cap(speakable(i.title, 12)) || 'That item';
109
152
  const dueWords = overdue ? `overdue since ${spokenWhen(day, today)}` : 'due today';
110
- return { id: `todo:${i.id}`, kind: 'todo', project: i.focusName?.trim() || 'Personal', text: title, question: 'Do it today?', more: `${title}, ${dueWords}.`, itemId: i.id, when: overdue ? 'overdue' : 'today' };
153
+ return { id: `todo:${i.id}`, kind: 'todo', project: i.focusName?.trim() || UNFILED, text: title, question: 'Do it today?', more: `${title}, ${dueWords}.`, itemId: i.id, when: overdue ? 'overdue' : 'today' };
111
154
  });
112
- const relay: QueueItem[] = input.relayItems.map((r, n) => ({ id: `relay:${n}`, kind: 'relay', project: r.project, text: r.text, question: 'Yes or no?', more: r.more }));
155
+ const relay: QueueItem[] = input.relayItems
156
+ .map((r, n): QueueItem => ({ id: `relay:${n}`, kind: 'relay', project: r.project, text: r.text, question: 'Yes or no?', more: r.more }))
157
+ .filter((q) => !skipped.has(skipKey(q)));
113
158
  // BY PROJECT: projects in the order they first appear (his own due items first), each with its to-dos then the relay's questions.
114
159
  const order: string[] = [];
115
160
  const lead = input.relayFirst ? relay : todos;
116
161
  const rest = input.relayFirst ? todos : relay;
117
162
  for (const q of [...lead, ...rest]) if (!order.includes(q.project)) order.push(q.project);
118
- return order.flatMap((p) => [...lead.filter((t) => t.project === p), ...rest.filter((r) => r.project === p)]);
163
+ return { queue: order.flatMap((p) => [...lead.filter((t) => t.project === p), ...rest.filter((r) => r.project === p)]), older };
164
+ }
165
+
166
+ export function buildQueue(input: QueueInput): QueueItem[] {
167
+ return rankQueue(input).queue;
168
+ }
169
+
170
+ /** A fresh walk, or null when nothing needs him. */
171
+ export function startBriefing(input: QueueInput): BriefingState | null {
172
+ const { queue, older } = rankQueue(input);
173
+ return queue.length ? { queue, index: 0, ...(older ? { older } : {}) } : null;
119
174
  }
120
175
 
121
176
  const sentence = (q: QueueItem) => `${q.text}${q.kind === 'todo' ? (q.when === 'overdue' ? ', overdue' : ', due today') : ''}`;
@@ -138,10 +193,24 @@ const SKIP = /^(skip( it)?|next( one)?|pass|move on|leave it)$/;
138
193
  const DONE = /^(done|finished|already (done|did it)|it'?s done|completed?)\b/;
139
194
  const DROP = /^(drop( it)?|delete it|cancel it|forget it|remove it)$/;
140
195
  const YES = /^(yes|yeah|yep|yup|sure|ok|okay|do it|go ahead|go|approved?|please do|today|do it today)\b/;
141
- const NO = /^(no|nope|nah|not today|not now|later|not yet|tomorrow)\b/;
196
+ const NO = /^(no|nope|nah|not today|not now|later|not yet)\b/;
197
+ /** "later today", "this afternoon", "tonight", "in a bit": not now, but today: it comes back at the end of this walk, with no change. */
198
+ const LATER_TODAY = /^(?:(?:ask me |remind me |come back |circle back )?(?:to it |about it )?(?:later today|later this (?:afternoon|evening)|this (?:afternoon|evening)|tonight|in a bit|in a while|after lunch|later on today)|ask me (?:again )?later)$/;
199
+
200
+ export interface StepContext { now: number; timeZone: string }
201
+
202
+ /** A date answer ("tomorrow", "next week", "Monday"): a short reply that is only a date. */
203
+ function dateAnswer(said: string, ctx: StepContext | undefined) {
204
+ if (!ctx) return null;
205
+ const split = splitWhen(said, ctx.now, ctx.timeZone);
206
+ if (!split || split.when.later || !split.when.date) return null;
207
+ const left = contentWords(split.rest.replace(/\b(?:move|push|put|do|it|that|this|to|until|till|on|for|by|please|can|you|make|set|snooze|remind|me|ask|about)\b/g, ' '));
208
+ return left.length ? null : split.when;
209
+ }
142
210
 
143
- export function stepBriefing(state: BriefingState, utterance: string): BriefingStep {
144
- const { queue, index } = state;
211
+ export function stepBriefing(state: BriefingState, utterance: string, ctx?: StepContext): BriefingStep {
212
+ let { queue } = state;
213
+ const { index } = state;
145
214
  const q = queue[index];
146
215
  if (!q) return { reply: 'That is everything.', state: null };
147
216
  const said = norm(utterance);
@@ -151,19 +220,28 @@ export function stepBriefing(state: BriefingState, utterance: string): BriefingS
151
220
  if (MORE.test(said)) return { reply: `${q.more} ${q.question}`, state };
152
221
 
153
222
  let effect: BriefingEffect | undefined;
154
- if (!SKIP.test(said)) {
155
- if (q.kind === 'relay') {
156
- effect = { kind: 'relay', text: `Answer on "${q.text}" (${q.project}): ${utterance.trim()}` };
157
- } else if (DROP.test(said)) effect = { kind: 'todo', action: { type: 'drop', itemId: q.itemId! } };
158
- else if (DONE.test(said)) effect = { kind: 'todo', action: { type: 'done', itemId: q.itemId! } };
159
- else if (YES.test(said)) effect = { kind: 'todo', action: { type: 'pull_today', itemId: q.itemId! } };
160
- else if (NO.test(said)) effect = { kind: 'todo', action: { type: 'defer', itemId: q.itemId!, to: 'later' } };
161
- else return { reply: '', state, passThrough: true };
162
- }
163
-
223
+ let backAtEnd = false;
224
+ const date = q.kind === 'todo' ? dateAnswer(said, ctx) : null;
225
+ if (SKIP.test(said)) effect = { kind: 'skip', key: skipKey(q) };
226
+ else if (q.kind === 'relay') {
227
+ effect = { kind: 'relay', text: `Answer on "${q.text}" (${q.project}): ${utterance.trim()}` };
228
+ } else if (LATER_TODAY.test(said)) backAtEnd = !q.id.endsWith(':again');
229
+ else if (DROP.test(said)) effect = { kind: 'todo', action: { type: 'drop', itemId: q.itemId! } };
230
+ else if (DONE.test(said)) effect = { kind: 'todo', action: { type: 'done', itemId: q.itemId! } };
231
+ else if (date && date.date === localDate(ctx!.now, ctx!.timeZone)) effect = { kind: 'todo', action: { type: 'pull_today', itemId: q.itemId!, label: 'today' } };
232
+ else if (date) effect = { kind: 'todo', action: { type: 'defer', itemId: q.itemId!, to: date.date as string, label: date.label } };
233
+ else if (YES.test(said)) effect = { kind: 'todo', action: { type: 'pull_today', itemId: q.itemId! } };
234
+ else if (NO.test(said)) effect = { kind: 'todo', action: { type: 'defer', itemId: q.itemId!, to: 'later' } };
235
+ else return { reply: '', state, passThrough: true };
236
+
237
+ // "Later today" changes nothing; the item is asked once more after the rest.
238
+ if (backAtEnd) queue = [...queue, { ...q, id: `${q.id}:again` }];
239
+ const noted = backAtEnd ? 'Noted, I will ask again at the end.' : 'Noted.';
164
240
  const next = index + 1;
165
- if (next >= queue.length) return { reply: 'Noted. That is everything.', state: null, ...(effect ? { effect } : {}) };
166
- const after = { queue, index: next };
167
- return { reply: `Noted. ${prompt(queue, next, true)}`, state: after, ...(effect ? { effect } : {}) };
241
+ const tail = state.older ? ` ${speakCountOf(state.older)} older overdue ${state.older === 1 ? 'item is' : 'items are'} still open. Ask me what is overdue.` : '';
242
+ if (next >= queue.length) return { reply: `${noted === 'Noted.' ? 'Noted. That is everything.' : `${noted} That is everything.`}${tail}`, state: null, ...(effect ? { effect } : {}) };
243
+ const after: BriefingState = { ...state, queue, index: next };
244
+ return { reply: `${noted} ${prompt(queue, next, true)}`, state: after, ...(effect ? { effect } : {}) };
168
245
  }
169
246
 
247
+ const speakCountOf = (n: number) => cap(speakCount(n));
@@ -0,0 +1,69 @@
1
+ /**
2
+ * THREAD CARDS: every item that needs Quinn (a question, an approval, the brief, a task, an email, a result) is ONE
3
+ * shape, drawn by one component with one layout: chip, who asked, time / title / one-line detail / actions.
4
+ * Pure data, no React: the web thread and the native thread read the same cards. Only real items become cards; a
5
+ * source that has nothing to say produces none, and a sample item is marked `sample` so it can never pass as urgent.
6
+ */
7
+ import type { DecisionRecord } from '../notify/types';
8
+
9
+ export type CardType = 'question' | 'approval' | 'brief' | 'task' | 'email' | 'result';
10
+
11
+ export const CARD_CHIP: Record<CardType, string> = { question: 'QUESTION', approval: 'APPROVAL', brief: 'BRIEF', task: 'TASK', email: 'EMAIL', result: 'RESULT' };
12
+
13
+ export interface CardAction { id: string; label: string; /** One primary action per card. */ primary?: boolean }
14
+
15
+ export interface ThreadCard {
16
+ /** Stable across reloads, so a card is never shown twice. */
17
+ id: string;
18
+ type: CardType;
19
+ /** Who asked. Always shown. */
20
+ from: string;
21
+ /** ISO time the item arrived; the thread keeps cards in this order. */
22
+ at: string;
23
+ title: string;
24
+ /** One line. */
25
+ detail?: string;
26
+ /** Markdown body (the brief's bullets). */
27
+ body?: string;
28
+ actions: CardAction[];
29
+ /** A question with no fixed options is answered in a typed reply. */
30
+ freeReply?: boolean;
31
+ /** Further questions waiting behind this one in the same decision. */
32
+ more?: number;
33
+ /** Set once answered: the card stays where it was and shows the answer. */
34
+ resolved?: string;
35
+ /** Labelled TEST SAMPLE on screen and never offered as urgent. */
36
+ sample?: boolean;
37
+ }
38
+
39
+ export const DEFAULT_SENDER = 'Tandem';
40
+
41
+ /** A decision record as a card: the first open question, its options as the actions (the first is the recommended one). */
42
+ export function decisionCard(d: DecisionRecord, from: string = DEFAULT_SENDER): ThreadCard {
43
+ const open = d.questions.filter((q) => !d.answers.some((a) => a.n === q.n));
44
+ const q = open[0] ?? d.questions[0];
45
+ const base: ThreadCard = { id: `decision:${d.id}`, type: 'question', from, at: d.created_at, title: d.title, detail: q?.text, actions: [], ...(/^TEST SAMPLE/i.test(d.title) ? { sample: true } : {}) };
46
+ if (d.status === 'answered' || !open.length) {
47
+ return { ...base, resolved: d.answers.map((a) => a.answer).join(' · ') || 'Answered' };
48
+ }
49
+ const options = q?.options ?? [];
50
+ return {
51
+ ...base,
52
+ actions: options.map((label, i) => ({ id: `option:${i}`, label, primary: i === 0 })),
53
+ freeReply: options.length === 0,
54
+ ...(open.length > 1 ? { more: open.length - 1 } : {}),
55
+ };
56
+ }
57
+
58
+ export function briefCard(b: { id: string; title: string; bullets: string[]; at: string }): ThreadCard {
59
+ return {
60
+ id: b.id, type: 'brief', from: 'Roci', at: b.at, title: b.title,
61
+ body: b.bullets.map((x) => `- ${x}`).join('\n'),
62
+ actions: [{ id: 'read', label: 'Read it aloud', primary: true }],
63
+ };
64
+ }
65
+
66
+ /** The same card, answered: it keeps its place in the thread and shows the answer instead of its actions. */
67
+ export function resolveCard(c: ThreadCard, answer: string): ThreadCard {
68
+ return { ...c, actions: [], freeReply: false, more: undefined, resolved: answer };
69
+ }
@@ -3,6 +3,7 @@
3
3
  * (an <audio src> cannot send one). No React, no DOM beyond fetch/FormData, so the web page and the native
4
4
  * tab call the same thing.
5
5
  */
6
+ import type { FleetView } from './fleet-view';
6
7
  import type { ConverseEndResult, ConverseThread, ConverseTurnResult } from './types';
7
8
 
8
9
  export class ConverseClientError extends Error {
@@ -19,6 +20,8 @@ export interface ConverseClient {
19
20
  end(conversationId: string): Promise<ConverseEndResult>;
20
21
  /** The thread from turn `after` + 1 on: how a page finds out the relay wrote into it. */
21
22
  thread(conversationId: string, after: number): Promise<ConverseThread>;
23
+ /** The relay's fleet snapshot, parsed (`snapshot: null` before the relay has posted). */
24
+ fleet(): Promise<{ snapshot: { text: string; updatedAt: string; view: FleetView | null } | null }>;
22
25
  /** Fetches a turn's audio and returns an object URL to play. */
23
26
  audioUrl(path: string): Promise<string>;
24
27
  }
@@ -53,6 +56,9 @@ export function createConverseClient(options: {
53
56
  body.append('timeZone', timeZone || Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC');
54
57
  return (await (await call(base, { method: 'POST', body }, 'That turn failed')).json()) as ConverseTurnResult;
55
58
  },
59
+ async fleet() {
60
+ return (await (await call(`${base}/fleet-status`, { method: 'GET', cache: 'no-store' }, 'Could not load the fleet')).json()) as Awaited<ReturnType<ConverseClient['fleet']>>;
61
+ },
56
62
  async end(conversationId) {
57
63
  return (await (await call(`${base}/end`, {
58
64
  method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ conversation_id: conversationId }),
@@ -0,0 +1,126 @@
1
+ /**
2
+ * The fleet as structure, not prose (Tandem /fleet). The relay posts three RAW inputs next to the text snapshot:
3
+ * `roles.md` (who leads what), the open-loops ledger (what waits on whom) and `bridge find ""` (who is live and what each
4
+ * is for). This module is the ONE parser: relay -> role leads -> the sessions each lead owns, then everyone else.
5
+ */
6
+ export interface FleetInputs { roles?: string; loops?: string; sessions?: string; ports?: string }
7
+ export interface FleetSection { title: string; items: string[] }
8
+ export interface FleetPort { project: string; range: string; base: string; url: string | null; notes: string }
9
+
10
+ export interface FleetSession { id: string; name: string; machine: string; goal: string; repo: string; branch: string; status: 'live' | 'dormant' }
11
+ export interface RoleRow { role: string; sessionId: string | null; childIds: string[]; notes: string }
12
+ export interface FleetLead { role: string; notes: string; session: FleetSession | null; children: FleetSession[]; /** The id roles.md lists, when it is not the live one. */ listedId?: string }
13
+ export interface FleetView {
14
+ relay: FleetSession | null;
15
+ leads: FleetLead[];
16
+ others: FleetSession[];
17
+ waitingOnQuinn: string[];
18
+ waitingOnSessions: string[];
19
+ rolesUpdated: string | null;
20
+ loopsUpdated: string | null;
21
+ ports: FleetPort[];
22
+ /** The ledger's other headed sections (state notes, parked items, ...), in file order. */
23
+ sections: FleetSection[];
24
+ /** Hand-edited markdown that did not fit: shown as-is, never a failure. */
25
+ unparsed: string[];
26
+ }
27
+
28
+ const HEX8 = /\b[0-9a-f]{8}\b/g;
29
+ const updatedOf = (md: string) => /^Updated\s+(.+)$/m.exec(md)?.[1].trim() ?? null;
30
+
31
+ export function parseRoles(md: string): { updated: string | null; rows: RoleRow[]; unparsed: string[] } {
32
+ const rows: RoleRow[] = [];
33
+ const unparsed: string[] = [];
34
+ for (const line of md.split('\n')) {
35
+ const t = line.trim();
36
+ if (t && !t.startsWith('|') && !t.startsWith('#') && !/^Updated\s/.test(t)) unparsed.push(t);
37
+ if (!t.startsWith('|')) continue;
38
+ const cells = line.trim().replace(/^\||\|$/g, '').split('|').map((c) => c.trim());
39
+ if (/^[-:\s]+$/.test(cells.join('')) || cells[0].toLowerCase() === 'role') continue;
40
+ if (cells.length < 2 || !cells[0]) { unparsed.push(t); continue; }
41
+ const [role, live, notes = ''] = cells;
42
+ const sessionId = /^none/i.test(live) ? null : live.match(HEX8)?.[0] ?? null;
43
+ const childIds = [...new Set(notes.match(HEX8) ?? [])].filter((id) => id !== sessionId);
44
+ rows.push({ role, sessionId, childIds, notes });
45
+ }
46
+ return { updated: updatedOf(md), rows, unparsed };
47
+ }
48
+
49
+ export function parseLoops(md: string): { updated: string | null; waitingOnQuinn: string[]; waitingOnSessions: string[]; sections: FleetSection[]; unparsed: string[] } {
50
+ const out = { updated: updatedOf(md), waitingOnQuinn: [] as string[], waitingOnSessions: [] as string[], sections: [] as FleetSection[], unparsed: [] as string[] };
51
+ let into: string[] | null = null;
52
+ for (const line of md.split('\n')) {
53
+ const h = /^#{2,}\s+(.*)$/.exec(line);
54
+ if (h) {
55
+ const title = h[1].trim();
56
+ if (/^waiting on quinn/i.test(title)) into = out.waitingOnQuinn;
57
+ else if (/^(waiting on sessions|relay owes)/i.test(title)) into = out.waitingOnSessions;
58
+ else { const sec = { title, items: [] as string[] }; out.sections.push(sec); into = sec.items; }
59
+ continue;
60
+ }
61
+ const t = line.trim();
62
+ const b = /^[-*]\s+(.+)$/.exec(t);
63
+ if (b && into) into.push(b[1].trim());
64
+ else if (t && !t.startsWith('#') && !/^Updated\s/.test(t)) (into ?? out.unparsed).push(t);
65
+ }
66
+ return out;
67
+ }
68
+
69
+ /** ports.md table: | Project | Range | Base (...) | Notes |; the URL is the first 4-digit port in the Base cell. */
70
+ export function parsePorts(md: string): FleetPort[] {
71
+ const out: FleetPort[] = [];
72
+ for (const line of md.split('\n')) {
73
+ const t = line.trim();
74
+ if (!t.startsWith('|')) continue;
75
+ const cells = t.replace(/^\||\|$/g, '').split('|').map((c) => c.trim());
76
+ if (cells.length < 3 || /^[-:\s]+$/.test(cells.join('')) || cells[0].toLowerCase() === 'project') continue;
77
+ const port = /\b(\d{4,5})\b/.exec(cells[2])?.[1];
78
+ out.push({ project: cells[0], range: cells[1], base: cells[2], url: port ? `http://localhost:${port}` : null, notes: cells[3] ?? '' });
79
+ }
80
+ return out;
81
+ }
82
+
83
+ /** `bridge find ""` lines: [live] `machine · name · id` goal repo@branch [model ..] */
84
+ export function parseBridgeFind(out: string): FleetSession[] {
85
+ const sessions: FleetSession[] = [];
86
+ for (const line of out.split('\n')) {
87
+ const m = /^\[(live|dormant)\]\s+`([^`]+)`\s*(.*)$/.exec(line);
88
+ if (!m) continue;
89
+ const parts = m[2].split(' · ').map((p) => p.trim());
90
+ const id = parts[parts.length - 1];
91
+ if (!/^[0-9a-f]{8}$/.test(id)) continue; // spawn runners and anything without a session id
92
+ const segs = m[3].split(/\s{2,}/).map((s) => s.trim()).filter(Boolean);
93
+ const rb = segs.find((s) => /^[^\s@]+@\S+$/.test(s)) ?? '';
94
+ const goal = segs[0] && segs[0] !== rb && !segs[0].startsWith('[') ? segs[0] : '';
95
+ const [repo = '', ...br] = rb.split('@');
96
+ sessions.push({ id, machine: parts[0] ?? '', name: parts.slice(1, -1).join(' · '), goal, repo, branch: br.join('@'), status: m[1] as 'live' | 'dormant' });
97
+ }
98
+ return sessions;
99
+ }
100
+
101
+ export function buildFleetView(inputs: FleetInputs): FleetView {
102
+ const roles = parseRoles(inputs.roles ?? '');
103
+ const loops = parseLoops(inputs.loops ?? '');
104
+ const sessions = parseBridgeFind(inputs.sessions ?? '');
105
+ const ports = parsePorts(inputs.ports ?? '');
106
+ const byId = new Map(sessions.map((s) => [s.id, s]));
107
+ const used = new Set<string>();
108
+ const take = (id: string | null) => { const s = id ? byId.get(id) ?? null : null; if (s) used.add(s.id); return s; };
109
+ let relay: FleetSession | null = null;
110
+ const leads: FleetLead[] = [];
111
+ for (const row of roles.rows) {
112
+ if (/^relay$/i.test(row.role)) { relay = take(row.sessionId); continue; }
113
+ let session = take(row.sessionId);
114
+ // roles.md is hand-edited and runs behind: when the listed id is not live, a live session named for the role stands in
115
+ if (!session && row.role.length > 3) {
116
+ const named = sessions.find((s) => !used.has(s.id) && s.status === 'live' && s.name.toLowerCase().startsWith(row.role.toLowerCase()));
117
+ if (named) { used.add(named.id); session = named; }
118
+ }
119
+ leads.push({ role: row.role, notes: row.notes, listedId: row.sessionId && session?.id !== row.sessionId ? row.sessionId : undefined, session, children: row.childIds.map((id) => take(id)).filter((s): s is FleetSession => !!s) });
120
+ }
121
+ return {
122
+ relay, leads, others: sessions.filter((s) => !used.has(s.id)),
123
+ waitingOnQuinn: loops.waitingOnQuinn, waitingOnSessions: loops.waitingOnSessions,
124
+ rolesUpdated: roles.updated, loopsUpdated: loops.updated, ports, sections: loops.sections, unparsed: [...roles.unparsed, ...loops.unparsed],
125
+ };
126
+ }
@@ -5,14 +5,27 @@
5
5
  */
6
6
  import type { TenantEntity } from '../entities';
7
7
  import { ConverseError, type ConverseDeps } from './types';
8
+ import type { FleetInputs } from './fleet-view';
8
9
 
9
10
  export const FLEET_SOURCE = 'fleet_status';
10
11
  export const MAX_FLEET_TEXT = 20000;
11
12
  export const fleetExternalId = (ownerSub: string) => `fleet-status:${ownerSub}`;
12
13
 
13
- export interface FleetSnapshot { text: string; updatedAt: string }
14
+ export const MAX_FLEET_INPUT = 200000;
15
+ export interface FleetSnapshot { text: string; updatedAt: string; inputs?: FleetInputs }
14
16
 
15
- export async function saveFleetSnapshot(deps: Pick<ConverseDeps, 'http' | 'ownerSub' | 'now'>, text: string): Promise<FleetSnapshot & { record_id: string }> {
17
+ /** Only the three known raw inputs, as capped strings. */
18
+ export function cleanFleetInputs(raw: unknown): FleetInputs | undefined {
19
+ if (!raw || typeof raw !== 'object') return undefined;
20
+ const out: FleetInputs = {};
21
+ for (const k of ['roles', 'loops', 'sessions', 'ports'] as const) {
22
+ const v = (raw as Record<string, unknown>)[k];
23
+ if (typeof v === 'string' && v.trim()) out[k] = v.slice(0, MAX_FLEET_INPUT);
24
+ }
25
+ return Object.keys(out).length ? out : undefined;
26
+ }
27
+
28
+ export async function saveFleetSnapshot(deps: Pick<ConverseDeps, 'http' | 'ownerSub' | 'now'>, text: string, inputs?: FleetInputs): Promise<FleetSnapshot & { record_id: string }> {
16
29
  const body = (text ?? '').trim();
17
30
  if (!body) throw new ConverseError('Send the snapshot text.', 400);
18
31
  if (body.length > MAX_FLEET_TEXT) throw new ConverseError('That snapshot is too long.', 413);
@@ -23,10 +36,10 @@ export async function saveFleetSnapshot(deps: Pick<ConverseDeps, 'http' | 'owner
23
36
  name: 'Fleet status',
24
37
  data: {
25
38
  title: 'Fleet status', source: FLEET_SOURCE, source_label: 'Fleet status', source_ref: fleetExternalId(deps.ownerSub),
26
- occurred_at: updatedAt, owner_sub: deps.ownerSub, body, updated_at: updatedAt,
39
+ occurred_at: updatedAt, owner_sub: deps.ownerSub, body, updated_at: updatedAt, ...(inputs ? { fleet_inputs: inputs } : {}),
27
40
  },
28
41
  });
29
- return { text: body, updatedAt, record_id: String(row.id) };
42
+ return { text: body, updatedAt, inputs, record_id: String(row.id) };
30
43
  }
31
44
 
32
45
  export async function loadFleetSnapshot(deps: Pick<ConverseDeps, 'http' | 'ownerSub'>): Promise<FleetSnapshot | null> {
@@ -39,7 +52,7 @@ export async function loadFleetSnapshot(deps: Pick<ConverseDeps, 'http' | 'owner
39
52
  return (r.external_id ?? r.externalId) === externalId && d.owner_sub === deps.ownerSub && d.source === FLEET_SOURCE;
40
53
  });
41
54
  const d = (hit?.data ?? {}) as Record<string, unknown>;
42
- return hit && typeof d.body === 'string' && d.body ? { text: d.body, updatedAt: typeof d.updated_at === 'string' ? d.updated_at : '' } : null;
55
+ return hit && typeof d.body === 'string' && d.body ? { text: d.body, updatedAt: typeof d.updated_at === 'string' ? d.updated_at : '', inputs: cleanFleetInputs(d.fleet_inputs) } : null;
43
56
  }
44
57
 
45
58
  /** "3 hours ago" for a timestamp; '' when it cannot be read. Said aloud, so words not numbers-with-units. */
@@ -18,14 +18,17 @@ export type FollowUp =
18
18
  | { kind: 'ask'; text: string };
19
19
 
20
20
  const ORDINALS: Record<string, number> = { first: 0, '1st': 0, one: 0, second: 1, '2nd': 1, two: 1, third: 2, '3rd': 2, three: 2, fourth: 3, '4th': 3, four: 3 };
21
- const EDIT = /^(?:(?:please|can you|could you)\s+)?(move|push|defer|bump|reschedule|schedule|mark|set|make|complete|finish|drop|delete|remove|cancel|do|put|pull|snooze)\b/i;
21
+ const EDIT = /^(?:(?:please|can you|could you)\s+)?(move|push|defer|bump|reschedule|schedule|mark|set|make|complete|finish|drop|delete|remove|cancel|do|put|pull|snooze|rename|retitle|file|add\s+(?:a\s+)?note)\b/i;
22
22
  const DETAIL = /^(?:tell me more (?:about|on)|more (?:about|on)|details? (?:on|about|of)|what about|how about|when is|when's)\b/i;
23
23
  const ORDINAL_REF = /\b(?:the\s+)?(first|second|third|fourth|last)(?:\s+one)?\b|\bnumber\s+(one|two|three|four)\b/i;
24
+ /** "all of those", "both of them", "every one": the whole list. */
25
+ const ALL_REF = /\b(?:all|both|every one|each one)(?:\s+of)?\s+(?:those|them|these|the (?:items|ones|to-?dos|tasks))\b|\b(?:them|those) all\b/i;
26
+ const MAX_BULK = 8;
24
27
  const THAT_ONE = /\b(?:that|this)\s+one\b/i;
25
28
  const BARE_IT = /\b(?:it|that)\b/i;
26
29
 
27
30
  /** Cheap check before reading anything: could this line be a follow-up about an item just listed? */
28
- export const mightFollowUp = (utterance: string): boolean => (EDIT.test(utterance.trim()) || DETAIL.test(utterance.trim())) && (ORDINAL_REF.test(utterance) || THAT_ONE.test(utterance) || BARE_IT.test(utterance));
31
+ export const mightFollowUp = (utterance: string): boolean => (EDIT.test(utterance.trim()) || DETAIL.test(utterance.trim())) && (ORDINAL_REF.test(utterance) || THAT_ONE.test(utterance) || BARE_IT.test(utterance) || ALL_REF.test(utterance));
29
32
 
30
33
  const quote = (title: string) => `"${title}"`;
31
34
 
@@ -46,6 +49,13 @@ export function followUp(input: { utterance: string; items: PlayedItem[]; rows:
46
49
  const detail = DETAIL.test(said);
47
50
  if (!edit && !detail) return null;
48
51
 
52
+ // The whole list: the same instruction once per item, as one sentence the edit path splits again ("mark A done and mark B done").
53
+ const all = ALL_REF.exec(said);
54
+ if (all && edit && items.length > 1) {
55
+ const each = items.slice(0, MAX_BULK).map((i) => said.replace(all[0], quote(i.title)).replace(/\s+/g, ' ').trim());
56
+ return { kind: 'rewrite', utterance: each.join(' and ') };
57
+ }
58
+
49
59
  // Which item, and the words that named it.
50
60
  let index: number | null = null;
51
61
  let span: string | null = null;
@@ -22,13 +22,14 @@ import {
22
22
  } from './types';
23
23
 
24
24
  const DEFAULT_HISTORY_LINES = 24;
25
- /** What is said after wrapping up: what was filed, in one short sentence. */
26
- function filedText(asks: string[]): string {
27
- if (!asks.length) return 'Filed the note.';
28
- const titles = asks.slice(0, 3).map((a) => speakable(a, 10) || 'a to-do');
29
- const more = asks.length - titles.length;
25
+ /** What is said after wrapping up: where the note went, and what was filed, so a mistake can be caught by ear. */
26
+ function filedText(filed: string[], project?: string | null): string {
27
+ const where = project ? ` under ${speakable(project, 6)}` : project === null ? ' with no project' : '';
28
+ if (!filed.length) return `Filed the note${where}.`;
29
+ const titles = filed.slice(0, 3).map((a) => speakable(a, 10) || 'a to-do');
30
+ const more = filed.length - titles.length;
30
31
  const list = more > 0 ? `${titles.join(', ')}, and ${more} more` : titles.length <= 2 ? titles.join(' and ') : `${titles.slice(0, -1).join(', ')} and ${titles[titles.length - 1]}`;
31
- return `Filed the note and ${asks.length} to-do${asks.length === 1 ? '' : 's'}: ${list}.`;
32
+ return `Filed the note${where} and ${filed.length} to-do${filed.length === 1 ? '' : 's'}: ${list}.`;
32
33
  }
33
34
  const NOT_HEARD = 'Sorry, I did not catch that. Can you say that again?';
34
35
  const BRAIN_FAILED = 'I am having trouble thinking right now. Your words are saved. Try again in a moment.';
@@ -103,11 +104,12 @@ export async function handleConverseTurn(deps: ConverseDeps, req: ConverseTurnRe
103
104
  let finish = false;
104
105
  let briefing = record?.briefing;
105
106
  let context = record?.context;
107
+ let pending: ConversationRecord['pending'];
106
108
  if (utterance) {
107
109
  const lines = (record?.turns ?? []).flatMap((t) => [{ role: 'user' as const, text: t.user.text }, { role: 'assistant' as const, text: t.from === 'relay' ? `The relay said: ${t.assistant.text}` : t.assistant.text }]).filter((l) => l.text);
108
110
  const history = lines.slice(-(deps.historyLines ?? DEFAULT_HISTORY_LINES));
109
111
  try {
110
- const out = await deps.brain({ utterance, history, timeZone, now, briefing: record?.briefing ?? null, context: record?.context ?? null });
112
+ const out = await deps.brain({ utterance, history, timeZone, now, briefing: record?.briefing ?? null, context: record?.context ?? null, pending: record?.pending ?? null });
111
113
  replyText = out.text.trim() || NOT_HEARD;
112
114
  did = out.did?.length ? out.did : undefined;
113
115
  forRelay = Boolean(out.forRelay);
@@ -118,6 +120,7 @@ export async function handleConverseTurn(deps: ConverseDeps, req: ConverseTurnRe
118
120
  finish = Boolean(out.finish);
119
121
  if (out.briefing !== undefined) briefing = out.briefing ?? undefined;
120
122
  if (out.context !== undefined) context = out.context ?? undefined;
123
+ pending = out.pending ?? undefined;
121
124
  lap('brain');
122
125
  for (const [k, v] of Object.entries(out.timings ?? {})) timing[`brain.${k}`] = v;
123
126
  } catch (error) {
@@ -136,8 +139,9 @@ export async function handleConverseTurn(deps: ConverseDeps, req: ConverseTurnRe
136
139
  if (finish) {
137
140
  try {
138
141
  const done = await handleConverseEnd(deps, { conversationId });
139
- ended = { ended: true, filed: { note: true, todos: done.asks.length } };
140
- replyText = filedText(done.asks);
142
+ const filedAsks = done.filed ?? done.asks;
143
+ ended = { ended: true, filed: { note: true, todos: filedAsks.length } };
144
+ replyText = filedText(filedAsks, done.project);
141
145
  spokenText = undefined;
142
146
  endedRecord = await store.get(conversationId);
143
147
  } catch (error) {
@@ -176,6 +180,7 @@ export async function handleConverseTurn(deps: ConverseDeps, req: ConverseTurnRe
176
180
  turns: [...(base?.turns ?? []), turn],
177
181
  ...(briefing && !endedRecord ? { briefing } : { briefing: undefined }),
178
182
  ...(context && !endedRecord ? { context } : { context: undefined }),
183
+ ...(pending && !endedRecord ? { pending } : { pending: undefined }),
179
184
  });
180
185
  // The relay finds its work in one list, so a passed-on turn is also recorded there. Never allowed to lose the turn.
181
186
  if (forRelay) await addRelayOrder(deps, { conversation_id: conversationId, turn: n, text: relayText ?? utterance, at: turn.at }).catch((e) => console.error('[converse] relay inbox write failed', e));
@@ -196,7 +201,7 @@ export async function handleConverseEnd(deps: ConverseDeps, req: { conversationI
196
201
  });
197
202
  if (record.status === 'ended') return done(record);
198
203
 
199
- const base = { ...record, briefing: undefined, context: undefined, status: 'ended' as const, endedAt: new Date((deps.now ?? Date.now)()).toISOString() };
204
+ const base = { ...record, briefing: undefined, context: undefined, pending: undefined, status: 'ended' as const, endedAt: new Date((deps.now ?? Date.now)()).toISOString() };
200
205
  let asks: string[] = [];
201
206
  let decisions: string[] = [];
202
207
  const heard = renderWhatHeSaid(base);
@@ -213,6 +218,10 @@ export async function handleConverseEnd(deps: ConverseDeps, req: { conversationI
213
218
  const summary = renderNextSteps(open);
214
219
  const saved = await store.save({ ...withAsks, body: renderTranscript(withAsks), ...(summary ? { summary } : {}) });
215
220
  // Filed like a voice note: under a project, and each ask a to-do. The transcript is already kept, so this never fails End.
216
- if (deps.handoff) await deps.handoff({ record: saved, asks: open, decisions }).catch((error) => console.error('[converse] handoff failed (conversation kept)', error));
217
- return done(saved);
221
+ let project: string | null | undefined;
222
+ if (deps.handoff) {
223
+ const handed = await deps.handoff({ record: saved, asks: open, decisions }).catch((error) => { console.error('[converse] handoff failed (conversation kept)', error); });
224
+ if (handed && 'project' in handed) project = handed.project ?? null;
225
+ }
226
+ return { ...done(saved), filed: open, ...(project !== undefined ? { project } : {}) };
218
227
  }
@@ -25,7 +25,8 @@ export interface ConverseHandoffDeps {
25
25
  }
26
26
 
27
27
  export function createConverseHandoff(deps: ConverseHandoffDeps) {
28
- return async ({ record, asks }: ConverseHandoffInput): Promise<void> => {
28
+ return async ({ record, asks }: ConverseHandoffInput): Promise<{ project: string | null }> => {
29
+ let project: string | null = null;
29
30
  const transcript = record.body ?? '';
30
31
  if (deps.analyzer && transcript) {
31
32
  try {
@@ -35,7 +36,10 @@ export function createConverseHandoff(deps: ConverseHandoffDeps) {
35
36
  transcript, focuses, now: deps.now?.() ?? Date.parse(record.startedAt), ...(record.timeZone ? { timeZone: record.timeZone } : {}),
36
37
  });
37
38
  // Only an id from the offered list files anything.
38
- if (analysis.focusId && focuses.some((f) => f.id === analysis.focusId)) await fileDocument(deps.http, record.id, analysis.focusId);
39
+ if (analysis.focusId && focuses.some((f) => f.id === analysis.focusId)) {
40
+ await fileDocument(deps.http, record.id, analysis.focusId);
41
+ project = focuses.find((f) => f.id === analysis.focusId)?.title ?? null;
42
+ }
39
43
  }
40
44
  } catch (error) {
41
45
  console.error('[converse] filing under a project failed (conversation kept)', error);
@@ -48,5 +52,6 @@ export function createConverseHandoff(deps: ConverseHandoffDeps) {
48
52
  console.error('[converse] to-do extraction failed (conversation kept)', error);
49
53
  }
50
54
  }
55
+ return { project };
51
56
  };
52
57
  }