@startsimpli/integrations 0.2.188 → 0.2.190

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.
@@ -0,0 +1,159 @@
1
+ 'use client';
2
+
3
+ /**
4
+ * OVERVIEW: many projects, many stakeholders, one screen. Rows are the account's projects, columns are whoever
5
+ * the open items belong to, each cell a count and the most pressing item. Click a project to open it. The
6
+ * numbers come from `buildOverview` (pure); nothing about people, areas or workflow is built in.
7
+ */
8
+ import * as React from 'react';
9
+
10
+ import { buildOverview, NO_PROJECT, type OverviewRow } from '../../../corpus/overview';
11
+ import type { Commitment, CorpusScope, Focus, PlanningApi } from '../../../corpus/types';
12
+
13
+ export interface OverviewPageProps {
14
+ api: PlanningApi;
15
+ scope: CorpusScope;
16
+ /** Names that mean the signed-in user, so their column reads "Me". */
17
+ meNames?: string[];
18
+ onOpenProject: (focusId: string, owner?: string) => void;
19
+ now?: number;
20
+ }
21
+
22
+ const STATUS: Record<string, { label: string; cls: string }> = {
23
+ on_track: { label: 'On track', cls: 'bg-green-100 text-green-900' },
24
+ active: { label: 'Active', cls: 'bg-blue-100 text-blue-900' },
25
+ at_risk: { label: 'At risk', cls: 'bg-amber-100 text-amber-900' },
26
+ off_track: { label: 'Off track', cls: 'bg-red-100 text-red-900' },
27
+ draft: { label: 'Draft', cls: 'bg-gray-100 text-gray-700' },
28
+ };
29
+
30
+ async function readAll<T>(read: (page: number) => Promise<{ results: T[]; next: string | null }>, maxPages = 20): Promise<T[]> {
31
+ const out: T[] = [];
32
+ for (let page = 1; page <= maxPages; page++) {
33
+ const r = await read(page);
34
+ out.push(...r.results);
35
+ if (!r.next || !r.results.length) break;
36
+ }
37
+ return out;
38
+ }
39
+
40
+ export function OverviewPage({ api, scope, meNames, onOpenProject, now }: OverviewPageProps) {
41
+ const [data, setData] = React.useState<{ focuses: Focus[]; items: Array<Commitment & { focusId?: string }> } | null>(null);
42
+ const [error, setError] = React.useState('');
43
+ const [who, setWho] = React.useState<string | null>(null);
44
+
45
+ React.useEffect(() => {
46
+ let live = true;
47
+ setData(null);
48
+ setError('');
49
+ Promise.all([
50
+ readAll((page) => api.listFocuses({ page, pageSize: 100 })),
51
+ readAll((page) => api.listCommitments({ status: ['open', 'in_progress', 'blocked'], withFocus: true, page, pageSize: 200 } as never)),
52
+ ])
53
+ .then(([focuses, items]) => live && setData({ focuses, items: items as Array<Commitment & { focusId?: string }> }))
54
+ .catch((e: unknown) => live && setError(e instanceof Error ? e.message : 'Could not load the overview'));
55
+ return () => {
56
+ live = false;
57
+ };
58
+ }, [api, scope]);
59
+
60
+ const overview = React.useMemo(() => (data ? buildOverview(data.focuses, data.items, { meNames, now }) : null), [data, meNames, now]);
61
+ if (error) return <p className="text-sm text-red-600" role="alert">{error}</p>;
62
+ if (!overview) return <p className="text-sm text-gray-500">Loading…</p>;
63
+ if (!overview.rows.length) return <p className="text-sm text-gray-500">Nothing in flight yet. Projects and their open to-dos show up here as they are connected or planned.</p>;
64
+
65
+ // Nobody owns anything yet (e.g. every item is unassigned): one plain "Open" column, and no Waiting-on filter that would filter nothing.
66
+ const onlyUnassigned = overview.columns.length === 1 && overview.columns[0].key === '';
67
+ const cols = onlyUnassigned ? [{ ...overview.columns[0], label: 'Open' }] : overview.columns;
68
+ const filtered = who === null ? overview.rows : overview.rows.filter((r) => r.cells[who]);
69
+ // Projects with nothing open would bury the ones that matter at real volumes: fold them under one line.
70
+ const rows = filtered.filter((r) => r.open > 0);
71
+ const idle = filtered.filter((r) => r.open === 0);
72
+ // the name to pre-filter the project's to-dos by: the person's own name ("Me" is the signed-in user's), nothing for Unassigned
73
+ const searchFor = (key: string) => (key === '' ? undefined : overview.columns.find((c) => c.key === key)?.isMe ? meNames?.[0] : overview.columns.find((c) => c.key === key)?.label);
74
+ const open = (r: OverviewRow, ownerKey?: string) => r.id !== NO_PROJECT && onOpenProject(r.id, ownerKey === undefined ? undefined : searchFor(ownerKey));
75
+
76
+ return (
77
+ <div className="space-y-4" data-testid="overview">
78
+ {onlyUnassigned ? null : <div className="flex flex-wrap items-center gap-2" role="group" aria-label="Waiting on">
79
+ <span className="text-sm font-medium text-gray-600">Waiting on</span>
80
+ <Chip active={who === null} onClick={() => setWho(null)}>Everyone · {overview.columns.reduce((a, c) => a + c.total, 0)}</Chip>
81
+ {cols.map((c) => (
82
+ <Chip key={c.key || 'unassigned'} active={who === c.key} onClick={() => setWho(who === c.key ? null : c.key)}>{c.label} · {c.total}</Chip>
83
+ ))}
84
+ </div>}
85
+
86
+ <div className="hidden overflow-x-auto rounded-xl border border-gray-200 bg-white md:block">
87
+ <table className="w-full min-w-[720px] border-collapse text-sm">
88
+ <thead>
89
+ <tr className="bg-gray-50 text-left text-xs font-medium uppercase tracking-wide text-gray-600">
90
+ <th scope="col" className="px-4 py-3">Project</th>
91
+ {cols.map((c) => <th key={c.key || 'unassigned'} scope="col" className={`px-4 py-3 ${who === c.key ? 'text-indigo-700' : ''}`}>{c.label}</th>)}
92
+ <th scope="col" className="px-4 py-3">Last activity</th>
93
+ </tr>
94
+ </thead>
95
+ <tbody>
96
+ {rows.map((r) => (
97
+ <tr key={r.id} className="border-t border-gray-200 align-top hover:bg-gray-50">
98
+ <th scope="row" className="px-4 py-3 text-left font-medium text-gray-900">
99
+ {r.id === NO_PROJECT ? <span>{r.title}</span> : <button type="button" onClick={() => open(r)} className="text-left hover:underline">{r.title}</button>}
100
+ <div className="mt-1 flex items-center gap-2 font-normal">
101
+ {r.focus && STATUS[r.focus.status] ? <span className={`rounded-full px-2 py-0.5 text-xs ${STATUS[r.focus.status].cls}`}>{STATUS[r.focus.status].label}</span> : null}
102
+ <span className="text-xs text-gray-500">{r.open} open{r.overdue ? ` · ${r.overdue} overdue` : ''}</span>
103
+ </div>
104
+ </th>
105
+ {cols.map((c) => {
106
+ const cell = r.cells[c.key];
107
+ return (
108
+ <td key={c.key || 'unassigned'} className="px-4 py-3 text-gray-700">
109
+ {cell ? (
110
+ <button type="button" onClick={() => open(r, c.key)} className="text-left hover:underline" aria-label={`${r.title}, ${c.label}: ${cell.count} open`}>
111
+ <b className="text-gray-900">{cell.count}</b> <span className="text-gray-600">{cell.next?.title}</span>
112
+ </button>
113
+ ) : <span className="text-gray-300">–</span>}
114
+ </td>
115
+ );
116
+ })}
117
+ <td className="px-4 py-3 text-gray-500">{r.lastActivity ? new Date(r.lastActivity).toLocaleDateString(undefined, { month: 'short', day: 'numeric' }) : '–'}</td>
118
+ </tr>
119
+ ))}
120
+ </tbody>
121
+ </table>
122
+ </div>
123
+
124
+ <ul className="space-y-3 md:hidden">
125
+ {rows.map((r) => (
126
+ <li key={r.id} className="rounded-xl border border-gray-200 bg-white p-4">
127
+ <div className="flex items-center gap-2">
128
+ {r.id === NO_PROJECT ? <span className="flex-1 font-medium">{r.title}</span> : <button type="button" onClick={() => open(r)} className="flex-1 text-left font-medium hover:underline">{r.title}</button>}
129
+ {r.focus && STATUS[r.focus.status] ? <span className={`rounded-full px-2 py-0.5 text-xs ${STATUS[r.focus.status].cls}`}>{STATUS[r.focus.status].label}</span> : null}
130
+ </div>
131
+ <div className="mt-2 flex flex-wrap gap-1.5 text-xs">
132
+ {cols.filter((c) => r.cells[c.key]).map((c) => (
133
+ <button key={c.key || 'unassigned'} type="button" onClick={() => open(r, c.key)} className="rounded-md bg-gray-100 px-2 py-1 text-gray-800">{c.label} {r.cells[c.key].count}</button>
134
+ ))}
135
+ </div>
136
+ </li>
137
+ ))}
138
+ </ul>
139
+ {idle.length ? (
140
+ <details className="rounded-xl border border-gray-200 bg-white px-4 py-3 text-sm">
141
+ <summary className="cursor-pointer text-gray-600">{idle.length} {idle.length === 1 ? 'project has' : 'projects have'} nothing open</summary>
142
+ <ul className="mt-2 flex flex-wrap gap-2">
143
+ {idle.map((r) => (
144
+ <li key={r.id}><button type="button" onClick={() => open(r)} className="rounded-md bg-gray-100 px-2 py-1 text-gray-800 hover:bg-gray-200">{r.title}</button></li>
145
+ ))}
146
+ </ul>
147
+ </details>
148
+ ) : null}
149
+ </div>
150
+ );
151
+ }
152
+
153
+ function Chip({ active, onClick, children }: { active: boolean; onClick: () => void; children: React.ReactNode }) {
154
+ return (
155
+ <button type="button" onClick={onClick} aria-pressed={active} className={`rounded-full border px-3 py-1.5 text-sm ${active ? 'border-indigo-600 bg-indigo-600 text-white' : 'border-gray-300 bg-white text-gray-700'}`}>
156
+ {children}
157
+ </button>
158
+ );
159
+ }
@@ -0,0 +1,2 @@
1
+ export { OverviewPage } from './OverviewPage';
2
+ export type { OverviewPageProps } from './OverviewPage';
@@ -19,6 +19,9 @@ import { FLEET_FRESH_MS, ageWords } from './fleet';
19
19
  import { routeUtterance } from './route';
20
20
  import { spokenSummary } from './spoken-summary';
21
21
  import { sourcesOfDocs } from './sources';
22
+ import { WRAP_UP } from './wrap-up';
23
+ import { itemAnswer } from './item-answers';
24
+ import { followUp, mightFollowUp, type PlayedItem } from './followups';
22
25
  import { ACTIVITY_QUESTION, composeActivity, forOwner, type Activity, type ActivityWindow } from '../activity';
23
26
  import { questionWindow } from '../ask-items-intent';
24
27
  import { BRIEF_ME, NEEDS_ME, buildQueue, firstPrompt, relayItemsFrom, stepBriefing, type BriefingEffect, type BriefingState } from './briefing-queue';
@@ -63,8 +66,11 @@ const SMALL_TALK: Array<[RegExp, string]> = [
63
66
  /** What a fleet-status question is about: the agents, sessions, lanes, the relay, what is blocked or shipping. */
64
67
  export const FLEET_WORDS = /\b(agents?|sessions?|fleet|lanes?|relay|bridge|blocked|blocker|shipping|shipped|deploy(?:ed|ing|s)?|prs?|pull requests?|status|working on|up to)\b/i;
65
68
 
66
- /** Wrapping up, said short: nothing else in the line. */
67
- export const WRAP_UP = /^(?:(?:ok(?:ay)?|alright|all right|so)[, ]+)?(?:(?:please |just |go ahead and )?(?:parse|file|save|process|wrap up|wrap|finish|close)(?: out)?(?: that| this| the| my| it| up)*(?: note| notes| conversation| thing)?|that'?s (?:it|all|everything)|that is (?:it|all|everything)|i'?m (?:done|finished)|i am (?:done|finished)|we'?re (?:done|finished)|done|all done|end (?:the )?(?:note|conversation))\W*$/i;
69
+ const wordsIn = (s: string) => s.trim().split(/\s+/).filter(Boolean).length;
70
+ /** From this many words a statement is a dictated note. */
71
+ export const LONG_NOTE_WORDS = 22;
72
+ /** An explicit request to make or change a to-do: acts at once however long it is. */
73
+ const EXPLICIT_TODO = /^(?:(?:please|can you|could you)\s+)?(?:add|create|make|put|remind me|set a reminder|mark|move|push|defer|drop|delete|remove|cancel|undo|schedule|reschedule|bump|snooze)\b/i;
68
74
 
69
75
  /** A who/what/when/where/why/how question, or "tell/show/give me": answered, never acted on as an item edit. */
70
76
  const ASKING = /^(what|what's|whats|how|when|where|who|why|which|tell me|give me|show me)\b/i;
@@ -90,6 +96,7 @@ export const SHORT_ANSWER = 'Use at most 60 words. Lead with the answer. If it i
90
96
  export const WANTS_ALL = /\b(tell me more|more detail|in detail|details|list (them|all|everything)|all of them|the full list|the whole list|everything|read (them|it) all|expand)\b/i;
91
97
  const askQuestion = (utterance: string, history: HistoryLine[]) => `${questionWithHistory(utterance, history)}\n\n${NO_FILLER}${WANTS_ALL.test(utterance) ? '' : ` ${SHORT_ANSWER}`}`;
92
98
 
99
+ export { WRAP_UP };
93
100
  export const NO_FILLER = 'Answer directly and stop. Do not ask whether to continue, do not offer more help, do not ask a question back unless you cannot answer without it.';
94
101
 
95
102
  const intentItem = (i: BriefingItem): IntentItem => ({
@@ -176,7 +183,7 @@ export function createConverseBrain(deps: ConverseBrainDeps): ConverseBrain {
176
183
  return { text, briefing: step.state, intent: 'briefing' as const, ...(did?.length ? { did } : {}), ...(effect?.kind === 'relay' ? { forRelay: true, relayText: effect.text } : {}) };
177
184
  }
178
185
 
179
- async function run({ utterance, history, timeZone, now, briefing }: Parameters<ConverseBrain>[0], timed: Timed): ReturnType<ConverseBrain> {
186
+ async function run({ utterance, history, timeZone, now, briefing, context }: Parameters<ConverseBrain>[0], timed: Timed): ReturnType<ConverseBrain> {
180
187
  // Lines that name the relay go first, so "add a to-do for the relay" is for the relay, not a plan item.
181
188
  if (ADDRESSES_RELAY.test(utterance)) {
182
189
  const routed = await viaRoute(utterance, history, now, timed);
@@ -189,7 +196,21 @@ export function createConverseBrain(deps: ConverseBrainDeps): ConverseBrain {
189
196
  }
190
197
  // "Parse that note" / "that's it" / "I'm done": he is wrapping up. The turn files the conversation through the normal End.
191
198
  if (WRAP_UP.test(utterance.trim())) return { text: 'Filing it now.', finish: true, intent: 'note' as const };
199
+ // A follow-up about the items the last answer listed ("move the second one to Friday", "tell me more about the first").
200
+ let itemRows: BriefingItem[] | null = null;
201
+ if (context?.items?.length && mightFollowUp(utterance)) {
202
+ itemRows = await timed('items', () => deps.loadItems().catch(() => [] as BriefingItem[]));
203
+ const fu = followUp({ utterance, items: context.items, rows: itemRows, now, timeZone });
204
+ if (fu?.kind === 'answer' || fu?.kind === 'ask') return { text: fu.text, intent: 'question' as const };
205
+ if (fu?.kind === 'rewrite') utterance = fu.utterance;
206
+ }
192
207
  const small = smallTalkReply(utterance);
208
+ // A long dictated plan ("today I want to... and I also need to...") is a NOTE: acknowledged and kept for the wrap-up, which files it
209
+ // once, instead of being turned into a to-do per sentence the moment he says it. A short explicit instruction ("add ...", "remind me
210
+ // to ...") and any question still act at once.
211
+ if (!small && wordsIn(utterance) >= LONG_NOTE_WORDS && !QUESTION.test(utterance.trim()) && !ASKING.test(utterance.trim()) && !EXPLICIT_TODO.test(utterance.trim()) && !ADDRESSES_RELAY.test(utterance)) {
212
+ return { text: 'Got it.', intent: 'note' as const };
213
+ }
193
214
  if (small) return { text: small, intent: 'chat' as const };
194
215
  // "What did I do yesterday": answered from WHEN things happened (a window read, not a word search). Read only.
195
216
  if (deps.loadActivity && ACTIVITY_QUESTION.test(utterance.trim())) {
@@ -199,6 +220,13 @@ export function createConverseBrain(deps: ConverseBrainDeps): ConverseBrain {
199
220
  return { text: composeActivity(window, found), intent: 'question' as const, sources: sourcesOfDocs(found.docs) };
200
221
  }
201
222
  }
223
+ // "What is due this week / what is overdue": answered in code from his own items (about 1 s, no model), only when the question is
224
+ // purely about due dates; anything else about it goes on to Ask.
225
+ if (/\b(due|overdue|slipping|late|behind)\b/i.test(utterance) && !ADDRESSES_RELAY.test(utterance)) {
226
+ itemRows ??= await timed('items', () => deps.loadItems().catch(() => [] as BriefingItem[]));
227
+ const quick = itemAnswer({ question: utterance, items: itemRows, now, timeZone, ownerSub: deps.ownerSub });
228
+ if (quick) return { text: quick.text, intent: 'question' as const, sources: quick.sources, context: { items: quick.sources.map((x) => ({ id: x.id.replace(/^item:/, ''), title: x.title })) } };
229
+ }
202
230
  // "What is on my plate" starts a briefing: by project, one item at a time.
203
231
  if (BRIEF_ME.test(utterance.trim())) {
204
232
  const [rows, snap] = await Promise.all([
@@ -225,7 +253,7 @@ export function createConverseBrain(deps: ConverseBrainDeps): ConverseBrain {
225
253
  // done. A who/what/when/how question skips the edit path altogether (which also saves the intent model's wait).
226
254
  const asking = ASKING.test(utterance.trim());
227
255
  const [openRows, log] = asking ? [[] as BriefingItem[], null] : await Promise.all([
228
- timed('items', () => deps.loadItems().catch(() => [] as BriefingItem[])),
256
+ itemRows ? Promise.resolve(itemRows) : timed('items', () => deps.loadItems().catch(() => [] as BriefingItem[])),
229
257
  timed('log', () => deps.log.load().catch(() => null)),
230
258
  ]);
231
259
  const open = openRows.map(intentItem);
@@ -254,7 +282,8 @@ export function createConverseBrain(deps: ConverseBrainDeps): ConverseBrain {
254
282
  const full = speakable(answered.answer ?? '', 400) || (answered.answer ?? '').trim();
255
283
  if (!full || GIVE_UP.test(full)) return { text: CANNOT_SEE, intent: 'question' as const };
256
284
  const short = spokenSummary(full);
257
- return { text: full, intent: 'question' as const, ...(short ? { spoken: short } : {}), ...(answered.sources?.length ? { sources: answered.sources } : {}) };
285
+ const listed: PlayedItem[] = (answered.sources ?? []).filter((x) => x.id.startsWith('item:')).map((x) => ({ id: x.id.replace(/^item:/, ''), title: x.title }));
286
+ return { text: full, intent: 'question' as const, ...(short ? { spoken: short } : {}), ...(answered.sources?.length ? { sources: answered.sources } : {}), ...(listed.length ? { context: { items: listed } } : {}) };
258
287
  }
259
288
 
260
289
  return async (input) => {
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Follow-ups across turns: "move the second one to Friday", "mark that one done", "tell me more about the first", "when is the third due".
3
+ *
4
+ * An answer that listed items leaves those items (in the order they were SAID) on the conversation. The next turn resolves the reference
5
+ * against them: an edit becomes a plain sentence naming the item ("move \"Review the checkout copy\" to Friday") for the normal edit
6
+ * path, so the same grounding and undo apply; "tell me more" is answered from the item's own fields. A reference it cannot place
7
+ * ("that one" with three in play) asks which; anything that is not clearly a follow-up returns null and is handled as usual.
8
+ */
9
+ import { spokenWhen } from '../briefing/intent/dates';
10
+ import type { BriefingItem } from '../briefing/types';
11
+ import { dueDay, localDate } from '../today';
12
+
13
+ export interface PlayedItem { id: string; title: string }
14
+
15
+ export type FollowUp =
16
+ | { kind: 'rewrite'; utterance: string }
17
+ | { kind: 'answer'; text: string }
18
+ | { kind: 'ask'; text: string };
19
+
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;
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
+ const ORDINAL_REF = /\b(?:the\s+)?(first|second|third|fourth|last)(?:\s+one)?\b|\bnumber\s+(one|two|three|four)\b/i;
24
+ const THAT_ONE = /\b(?:that|this)\s+one\b/i;
25
+ const BARE_IT = /\b(?:it|that)\b/i;
26
+
27
+ /** 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));
29
+
30
+ const quote = (title: string) => `"${title}"`;
31
+
32
+ function describe(item: BriefingItem, now: number, timeZone: string): string {
33
+ const today = localDate(now, timeZone);
34
+ const day = dueDay(item.dueAt, timeZone);
35
+ const due = day ? (day < today ? `overdue since ${spokenWhen(day, today)}` : `due ${spokenWhen(day, today)}`) : '';
36
+ const priority = item.priority !== undefined && item.priority <= 1 ? (item.priority === 0 ? 'critical priority' : 'urgent priority') : '';
37
+ const status = item.status === 'in_progress' ? 'in progress' : item.status;
38
+ return `${item.title}: ${[item.focusName?.trim(), due, priority, status].filter(Boolean).join(', ')}.`;
39
+ }
40
+
41
+ export function followUp(input: { utterance: string; items: PlayedItem[]; rows: BriefingItem[]; now: number; timeZone: string }): FollowUp | null {
42
+ const { items } = input;
43
+ const said = input.utterance.trim().replace(/[?!.]+$/, '');
44
+ if (!items.length || !said) return null;
45
+ const edit = EDIT.test(said);
46
+ const detail = DETAIL.test(said);
47
+ if (!edit && !detail) return null;
48
+
49
+ // Which item, and the words that named it.
50
+ let index: number | null = null;
51
+ let span: string | null = null;
52
+ const ord = ORDINAL_REF.exec(said);
53
+ if (ord) {
54
+ const word = (ord[1] ?? ord[2]).toLowerCase();
55
+ index = word === 'last' ? items.length - 1 : ORDINALS[word];
56
+ span = ord[0];
57
+ } else if (THAT_ONE.test(said) || (edit && items.length === 1 && BARE_IT.test(said) && !/^do\b/i.test(said))) {
58
+ if (items.length > 1) return { kind: 'ask', text: `Which one: ${items.length === 2 ? items.map((i) => i.title).join(' or ') : `${items.slice(0, -1).map((i) => i.title).join(', ')} or ${items[items.length - 1].title}`}?` };
59
+ index = 0;
60
+ span = (THAT_ONE.exec(said) ?? BARE_IT.exec(said))![0];
61
+ }
62
+ if (index === null || span === null || index < 0 || index >= items.length) return null;
63
+ const item = items[index];
64
+
65
+ if (detail) {
66
+ const row = input.rows.find((r) => r.id === item.id);
67
+ return row ? { kind: 'answer', text: describe(row, input.now, input.timeZone) } : null;
68
+ }
69
+ return { kind: 'rewrite', utterance: said.replace(span, quote(item.title)).replace(/\s+/g, ' ').trim() };
70
+ }
@@ -12,6 +12,9 @@ import { unhandledAsks } from './handled-asks';
12
12
  import { renderNextSteps, renderTranscript, renderWhatHeSaid, titleFor } from './transcript';
13
13
  import { createEntityConversationStore } from './store';
14
14
  import { speakSide } from './speak';
15
+ import { speakable } from '../briefing/speak';
16
+ import { localDate } from '../today';
17
+ import { toSpoken } from './spoken-form';
15
18
  import { addRelayOrder } from './relay-inbox';
16
19
  import {
17
20
  CLIENT_ID, ConverseError, MAX_CONVERSE_AUDIO_BYTES, turnAudioPath,
@@ -19,6 +22,14 @@ import {
19
22
  } from './types';
20
23
 
21
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;
30
+ 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
+ }
22
33
  const NOT_HEARD = 'Sorry, I did not catch that. Can you say that again?';
23
34
  const BRAIN_FAILED = 'I am having trouble thinking right now. Your words are saved. Try again in a moment.';
24
35
 
@@ -91,11 +102,12 @@ export async function handleConverseTurn(deps: ConverseDeps, req: ConverseTurnRe
91
102
  let sources: ConverseTurn['sources'];
92
103
  let finish = false;
93
104
  let briefing = record?.briefing;
105
+ let context = record?.context;
94
106
  if (utterance) {
95
107
  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);
96
108
  const history = lines.slice(-(deps.historyLines ?? DEFAULT_HISTORY_LINES));
97
109
  try {
98
- const out = await deps.brain({ utterance, history, timeZone, now, briefing: record?.briefing ?? null });
110
+ const out = await deps.brain({ utterance, history, timeZone, now, briefing: record?.briefing ?? null, context: record?.context ?? null });
99
111
  replyText = out.text.trim() || NOT_HEARD;
100
112
  did = out.did?.length ? out.did : undefined;
101
113
  forRelay = Boolean(out.forRelay);
@@ -105,6 +117,7 @@ export async function handleConverseTurn(deps: ConverseDeps, req: ConverseTurnRe
105
117
  sources = out.sources;
106
118
  finish = Boolean(out.finish);
107
119
  if (out.briefing !== undefined) briefing = out.briefing ?? undefined;
120
+ if (out.context !== undefined) context = out.context ?? undefined;
108
121
  lap('brain');
109
122
  for (const [k, v] of Object.entries(out.timings ?? {})) timing[`brain.${k}`] = v;
110
123
  } catch (error) {
@@ -117,6 +130,23 @@ export async function handleConverseTurn(deps: ConverseDeps, req: ConverseTurnRe
117
130
  const priorTurns = record?.turns.length ?? 0;
118
131
  if (finish && priorTurns === 0) { replyText = 'There is nothing to file yet.'; finish = false; spokenText = undefined; }
119
132
 
133
+ // He said "parse that note" / "that's it": file the conversation through the normal End FIRST, so the reply can say what was filed.
134
+ let ended: { ended: true; filed: { note: boolean; todos: number } } | undefined;
135
+ let endedRecord: ConversationRecord | null = null;
136
+ if (finish) {
137
+ try {
138
+ const done = await handleConverseEnd(deps, { conversationId });
139
+ ended = { ended: true, filed: { note: true, todos: done.asks.length } };
140
+ replyText = filedText(done.asks);
141
+ spokenText = undefined;
142
+ endedRecord = await store.get(conversationId);
143
+ } catch (error) {
144
+ console.error('[converse] wrap-up failed (the conversation is kept open)', error);
145
+ replyText = 'I could not file it just now. Your words are saved: say that again in a moment.';
146
+ spokenText = undefined;
147
+ }
148
+ }
149
+
120
150
  // 3. Keep both recordings; speak the reply. Neither is allowed to lose the turn.
121
151
  const user: ConverseSide = { text: utterance };
122
152
  if (req.audio && deps.audio) {
@@ -131,32 +161,24 @@ export async function handleConverseTurn(deps: ConverseDeps, req: ConverseTurnRe
131
161
  // Nothing was heard: the page stays quiet and listens again, so there is nothing to speak (the text is still kept).
132
162
  const assistant = req.audio && !utterance
133
163
  ? { text: replyText, audio_reason: 'nothing was heard' }
134
- : await speakSide(deps, `${conversationId}-t${n}-reply`, replyText, spokenText);
164
+ : await speakSide(deps, `${conversationId}-t${n}-reply`, replyText, spokenText ?? toSpoken(replyText, localDate(now, timeZone)) ?? undefined);
135
165
  lap('tts');
136
166
 
137
167
  // 4. Save.
138
168
  const turn: ConverseTurn = { n, turn_id: turnId, at: new Date(now).toISOString(), user, assistant, ...(did ? { did } : {}), ...(forRelay ? { for_relay: true } : {}), ...(intent ? { intent } : {}), ...(sources?.length ? { sources } : {}) };
139
- const startedAt = record?.startedAt ?? turn.at;
169
+ const base = endedRecord ?? record;
170
+ const startedAt = base?.startedAt ?? turn.at;
140
171
  await store.save({
141
- ...(record ?? { status: 'open' as const, conversationId, externalId: '' }),
142
- conversationId, startedAt, status: 'open',
143
- ...(req.timeZone || record?.timeZone ? { timeZone } : {}),
144
- title: record?.title || titleFor(startedAt, utterance),
145
- turns: [...(record?.turns ?? []), turn],
146
- ...(briefing ? { briefing } : { briefing: undefined }),
172
+ ...(base ?? { status: 'open' as const, conversationId, externalId: '' }),
173
+ conversationId, startedAt, status: endedRecord ? 'ended' : 'open',
174
+ ...(req.timeZone || base?.timeZone ? { timeZone } : {}),
175
+ title: base?.title || titleFor(startedAt, utterance),
176
+ turns: [...(base?.turns ?? []), turn],
177
+ ...(briefing && !endedRecord ? { briefing } : { briefing: undefined }),
178
+ ...(context && !endedRecord ? { context } : { context: undefined }),
147
179
  });
148
180
  // The relay finds its work in one list, so a passed-on turn is also recorded there. Never allowed to lose the turn.
149
181
  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));
150
- // He said "parse that note" / "that's it": file the conversation through the normal End, here, in the same turn.
151
- let ended: { ended: true; filed: { note: boolean; todos: number } } | undefined;
152
- if (finish) {
153
- try {
154
- const done = await handleConverseEnd(deps, { conversationId });
155
- ended = { ended: true, filed: { note: true, todos: done.asks.length } };
156
- } catch (error) {
157
- console.error('[converse] wrap-up failed (the conversation is kept open)', error);
158
- }
159
- }
160
182
  lap('save');
161
183
  timing.total = Date.now() - clock.t0;
162
184
  deps.onTiming?.(timing, { conversationId, turn: n });
@@ -174,7 +196,7 @@ export async function handleConverseEnd(deps: ConverseDeps, req: { conversationI
174
196
  });
175
197
  if (record.status === 'ended') return done(record);
176
198
 
177
- const base = { ...record, briefing: undefined, status: 'ended' as const, endedAt: new Date((deps.now ?? Date.now)()).toISOString() };
199
+ const base = { ...record, briefing: undefined, context: undefined, status: 'ended' as const, endedAt: new Date((deps.now ?? Date.now)()).toISOString() };
178
200
  let asks: string[] = [];
179
201
  let decisions: string[] = [];
180
202
  const heard = renderWhatHeSaid(base);
@@ -35,3 +35,4 @@ export { PASSED_TO_RELAY, NO_FLEET_STATUS, NO_FILLER } from './brain';
35
35
  export { ACTIVITY_QUESTION, activityOf, composeActivity, forOwner, loadActivity } from '../activity';
36
36
  export type { Activity, ActivityWindow, ActivityNote } from '../activity';
37
37
  export { askSources, sourceOf, sourcesOfDocs } from './sources';
38
+ export { itemAnswer } from './item-answers';
@@ -0,0 +1,67 @@
1
+ /**
2
+ * "What is due this week / today / what is overdue": answered IN CODE from his own items (no model, about 1 s instead of the 4 to 8 s
3
+ * a model call takes), and only when the question is purely about due dates and states. A question with any other topic ("...about the
4
+ * roll", "who is blocked", "is the bench overdue") returns null and goes to Ask, so this can never answer something it did not understand.
5
+ */
6
+ import { itemIntent, questionWindow } from '../ask-items-intent';
7
+ import { speakable } from '../briefing/speak';
8
+ import type { BriefingItem } from '../briefing/types';
9
+ import { dueDay } from '../today';
10
+ import type { ConverseSource } from './types';
11
+
12
+ /** Words that may appear in a due-date question without making it about something else. */
13
+ const PLAIN = new Set(('what whats what\'s which is are do does did have has had i my me mine the this next last that and a an all any anything ' +
14
+ 'there on for in of by to now right still yet open list show tell give things thing items item tasks task todos todo to-dos to-do ' +
15
+ 'due overdue late behind slipping slipped missed today tomorrow yesterday week month weekend ' +
16
+ 'monday tuesday wednesday thursday friday saturday sunday').split(/\s+/));
17
+
18
+ const FINISHED = new Set(['done', 'dropped']);
19
+ const LINEAR_FINISHED = new Set(['completed', 'canceled', 'cancelled']);
20
+
21
+ function listOf(titles: string[], total: number): string {
22
+ const t = titles.map((x) => speakable(x, 12) || 'untitled');
23
+ const more = total - t.length;
24
+ if (more > 0) return `${t.join(', ')}, and ${more} more`;
25
+ if (t.length <= 2) return t.join(' and ');
26
+ return `${t.slice(0, -1).join(', ')} and ${t[t.length - 1]}`;
27
+ }
28
+
29
+ export function itemAnswer(input: { question: string; items: BriefingItem[]; now: number; timeZone: string; ownerSub?: string }): { text: string; sources: ConverseSource[] } | null {
30
+ const { question, items, now, timeZone, ownerSub } = input;
31
+ const intent = itemIntent(question, now, timeZone);
32
+ if (!intent || (intent.focus !== 'due' && intent.focus !== 'slipping')) return null;
33
+ const window = questionWindow(question, now, timeZone);
34
+ if (intent.focus === 'due' && !window) return null;
35
+
36
+ // Anything beyond plain due-date words must be the name of one of his projects, or this is not our question.
37
+ const projects = [...new Set(items.map((i) => i.focusName?.trim()).filter(Boolean) as string[])];
38
+ const words = question.toLowerCase().replace(/[’]/g, "'").split(/[^a-z0-9'-]+/).filter(Boolean);
39
+ const extra = words.filter((w) => !PLAIN.has(w) && !/^\d+$/.test(w));
40
+ const asked = new Set<string>();
41
+ for (const project of projects) {
42
+ const parts = project.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
43
+ if (parts.length && parts.every((p) => words.includes(p))) asked.add(project);
44
+ }
45
+ const covered = new Set([...asked].flatMap((p) => p.toLowerCase().split(/[^a-z0-9]+/)));
46
+ if (extra.some((w) => !covered.has(w) && !['for', 'in', 'on'].includes(w))) return null;
47
+
48
+ const today = intent.today;
49
+ const open = items.filter((i) => !FINISHED.has(i.status) && !LINEAR_FINISHED.has(i.linearState ?? '')
50
+ && (!ownerSub || !i.ownerSub || i.ownerSub === ownerSub)
51
+ && (!asked.size || (i.focusName && asked.has(i.focusName.trim()))));
52
+ const dated = open.map((i) => ({ i, day: dueDay(i.dueAt, timeZone) }));
53
+ const picked = (intent.focus === 'slipping'
54
+ ? dated.filter((x) => (x.day !== null && x.day < today) || x.i.status === 'blocked')
55
+ : dated.filter((x) => x.day !== null && x.day >= window!.from && x.day <= window!.to))
56
+ .sort((a, b) => String(a.day ?? '9999').localeCompare(String(b.day ?? '9999')) || (a.i.priority ?? 9) - (b.i.priority ?? 9));
57
+
58
+ const label = intent.focus === 'slipping' ? 'overdue' : `due ${/^(this|next|last) |^today$|^tomorrow$|^yesterday$|^the last/.test(window!.label) ? window!.label : `on ${window!.label}`}`;
59
+ if (!picked.length) return { text: `Nothing is ${label}.`, sources: [] };
60
+ const top = picked.slice(0, 3);
61
+ const noun = picked.length === 1 ? 'thing is' : 'things are';
62
+ return {
63
+ text: `${picked.length} ${noun} ${label}: ${listOf(top.map((x) => x.i.title), picked.length)}.`,
64
+ sources: top.map((x) => ({ kind: 'todo', title: x.i.title, id: `item:${x.i.id}` })),
65
+ };
66
+ }
67
+
@@ -0,0 +1,25 @@
1
+ /**
2
+ * What the voice says is not always what the screen shows: an ISO date ("due 2026-11-20") is said "due Friday", a ticket id ("SIM-1234") is
3
+ * dropped, markdown is stripped. The screen keeps the text as written; null means the voice can say it as it is.
4
+ */
5
+ import { spokenWhen } from '../briefing/intent/dates';
6
+ import { IDENTIFIER } from '../briefing/speak';
7
+
8
+ const ISO_DATE = /\b(\d{4}-\d{2}-\d{2})\b/g;
9
+ const MARKUP = /[*_#`~<>|\\]|\[|\]|^\s*[-•>]\s/m;
10
+
11
+ export function toSpoken(text: string, today: string): string | null {
12
+ if (!ISO_DATE.test(text) && !new RegExp(IDENTIFIER.source).test(text) && !MARKUP.test(text)) { ISO_DATE.lastIndex = 0; return null; }
13
+ ISO_DATE.lastIndex = 0;
14
+ const out = text
15
+ .replace(ISO_DATE, (d) => spokenWhen(d, today))
16
+ .replace(/\s*\(\s*[A-Za-z]{2,10}-\d+\s*\)/g, '')
17
+ .replace(IDENTIFIER, '')
18
+ .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
19
+ .replace(/[*_#`~<>|\\]/g, '')
20
+ .replace(/^\s*[-•>]\s+/gm, '')
21
+ .replace(/\s+/g, ' ')
22
+ .replace(/\s+([,.;:!?])/g, '$1')
23
+ .trim();
24
+ return out && out !== text ? out : null;
25
+ }
@@ -31,6 +31,7 @@ function toRecord(entity: TenantEntity): ConversationRecord {
31
31
  ...(d.asks ? { asks: list(d.asks) } : {}),
32
32
  ...(d.decisions ? { decisions: list(d.decisions) } : {}),
33
33
  ...(d.briefing && typeof d.briefing === 'object' ? { briefing: d.briefing as ConversationRecord['briefing'] } : {}),
34
+ ...(d.context && typeof d.context === 'object' ? { context: d.context as ConversationRecord['context'] } : {}),
34
35
  };
35
36
  }
36
37
 
@@ -70,6 +71,7 @@ export function createEntityConversationStore(http: ConverseDeps['http'], ownerS
70
71
  ...(record.asks ? { asks: record.asks } : {}),
71
72
  ...(record.decisions ? { decisions: record.decisions } : {}),
72
73
  briefing: record.briefing ?? null,
74
+ context: record.context ?? null,
73
75
  },
74
76
  });
75
77
  return { ...record, id: String(row.id) };
@@ -1,5 +1,6 @@
1
1
  /** A conversation as a document: what is saved as the record's `body` at End. Pure. */
2
2
  import type { ConversationRecord } from './types';
3
+ import { WRAP_UP } from './wrap-up';
3
4
 
4
5
  export function renderTranscript(record: Pick<ConversationRecord, 'turns' | 'startedAt' | 'timeZone' | 'asks' | 'decisions'>): string {
5
6
  const lines: string[] = [];
@@ -23,7 +24,7 @@ export function renderTranscript(record: Pick<ConversationRecord, 'turns' | 'sta
23
24
  const ASKING_ABOUT_HIS_DATA = /^(?:is|are|was|were|what|what's|whats|when|where|who|how|why|which|did|does|do i|have i|has|any)\b[^]*\?\s*$/i;
24
25
 
25
26
  export function renderWhatHeSaid(record: Pick<ConversationRecord, 'turns'>): string {
26
- const said = record.turns.filter((t) => t.from !== 'relay' && t.user.text.trim() && !ASKING_ABOUT_HIS_DATA.test(t.user.text.trim())).map((t) => `- ${t.user.text.trim()}`);
27
+ const said = record.turns.filter((t) => t.from !== 'relay' && t.user.text.trim() && !ASKING_ABOUT_HIS_DATA.test(t.user.text.trim()) && !WRAP_UP.test(t.user.text.trim())).map((t) => `- ${t.user.text.trim()}`);
27
28
  return said.length ? ['## What he said', ...said].join('\n') : '';
28
29
  }
29
30
 
@@ -64,6 +64,8 @@ export interface ConversationRecord {
64
64
  decisions?: string[];
65
65
  /** A briefing in progress: the queue of items and the one being asked. */
66
66
  briefing?: BriefingState;
67
+ /** The items the last answer listed, for follow-ups ("the second one"). */
68
+ context?: { items: PlayedItem[] };
67
69
  }
68
70
 
69
71
  export interface ConversationStore {
@@ -74,8 +76,11 @@ export interface ConversationStore {
74
76
 
75
77
  /** What the assistant works out for one utterance. */
76
78
  import type { BriefingState } from './briefing-queue';
79
+ import type { PlayedItem } from './followups';
77
80
 
78
81
  export interface ConverseBrainInput {
82
+ /** The items the last answer listed, in the order they were said: what "the second one" and "that one" mean. */
83
+ context?: { items: PlayedItem[] } | null;
79
84
  /** A briefing in progress (the queue and where it is), kept on the conversation; the next answer belongs to it. */
80
85
  briefing?: BriefingState | null;
81
86
  utterance: string;
@@ -96,6 +101,8 @@ export interface ConverseBrainOutput {
96
101
  relayText?: string;
97
102
  /** The briefing after this turn: null = over; absent = unchanged. */
98
103
  briefing?: BriefingState | null;
104
+ /** The items this answer listed (null clears; absent keeps what was there). */
105
+ context?: { items: PlayedItem[] } | null;
99
106
  /** What kind of thing was said (shown by the app, kept on the turn). */
100
107
  intent?: ConverseIntent;
101
108
  /** The records the answer came from. */
@@ -0,0 +1,3 @@
1
+ /** Wrapping up, said short ("parse that note", "that's it", "I'm done", "file it"): a command to the assistant, never something to file. */
2
+ export const WRAP_UP = /^(?:(?:ok(?:ay)?|alright|all right|so)[, ]+)?(?:(?:please |just |go ahead and )?(?:parse|file|save|process|wrap up|wrap|finish|close)(?: out)?(?: that| this| the| my| it| up)*(?: note| notes| conversation| thing)?|that'?s (?:it|all|everything)|that is (?:it|all|everything)|i'?m (?:done|finished)|i am (?:done|finished)|we'?re (?:done|finished)|done|all done|end (?:the )?(?:note|conversation))\W*$/i;
3
+
@@ -307,6 +307,8 @@ export type { DueBucket, DueEntry, DueGroup, DueGroups } from './due-groups';
307
307
  export { STALE_DAYS, groupTracker, isTask } from './tracker-groups';
308
308
  export type { TrackerEntry, TrackerGroups } from './tracker-groups';
309
309
  export { DEFAULT_TRACKER_SORT, TRACKER_SORTS, commitmentOrder, compareCommitments } from './tracker-sort';
310
+ export { buildOverview, NO_PROJECT } from './overview';
311
+ export type { Overview, OverviewRow, OverviewColumn, OverviewCell } from './overview';
310
312
  export { summarizeFocuses } from './focus-overview';
311
313
  export type { FocusSummary } from './focus-overview';
312
314
  export { focusToGoalRow } from './goal-rows';