@startsimpli/integrations 0.2.197 → 0.2.201

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/package.json +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__/converse-brain.test.ts +64 -1
  5. package/src/__tests__/converse-handoff.test.ts +8 -0
  6. package/src/__tests__/converse-meeting-brief.test.ts +72 -8
  7. package/src/__tests__/converse-meeting-duplex.test.ts +132 -0
  8. package/src/__tests__/converse-meeting-keep-speech.test.ts +87 -0
  9. package/src/__tests__/converse-meeting-vad.test.ts +1 -1
  10. package/src/__tests__/converse-spoken-form.test.ts +10 -0
  11. package/src/__tests__/converse-spoken-summary.test.ts +27 -6
  12. package/src/__tests__/converse.test.ts +29 -2
  13. package/src/__tests__/corpus-ask-items.test.ts +14 -0
  14. package/src/__tests__/corpus-ask.test.ts +22 -0
  15. package/src/__tests__/corpus-tracker.test.tsx +12 -0
  16. package/src/__tests__/extract-classify.test.ts +17 -0
  17. package/src/__tests__/fleet-page.test.tsx +57 -0
  18. package/src/__tests__/fleet-view.test.ts +149 -0
  19. package/src/__tests__/project-basis-entity.test.ts +19 -0
  20. package/src/__tests__/project-basis.test.ts +21 -0
  21. package/src/__tests__/relay-cli.test.ts +10 -1
  22. package/src/__tests__/spoken-time.test.ts +4 -0
  23. package/src/__tests__/task-detail-project-guess.test.tsx +46 -0
  24. package/src/__tests__/voice-due-later-sentence.test.ts +26 -0
  25. package/src/components/index.ts +2 -0
  26. package/src/components/pages/FleetPage.tsx +115 -0
  27. package/src/components/pages/TaskDetailPage.tsx +27 -1
  28. package/src/components/pages/TrackerPage.tsx +1 -1
  29. package/src/components/pages/task-tracker/ProjectGuess.tsx +42 -0
  30. package/src/corpus/ask-items-intent.ts +24 -0
  31. package/src/corpus/ask-items.ts +7 -4
  32. package/src/corpus/ask.ts +1 -1
  33. package/src/corpus/briefing/actions/confirm.ts +9 -1
  34. package/src/corpus/briefing/actions/execute.ts +71 -11
  35. package/src/corpus/briefing/actions/log.ts +1 -1
  36. package/src/corpus/briefing/actions/seam.ts +18 -2
  37. package/src/corpus/briefing/actions/types.ts +14 -0
  38. package/src/corpus/briefing/intent/describe.ts +5 -1
  39. package/src/corpus/briefing/intent/edits.ts +92 -0
  40. package/src/corpus/briefing/intent/grammar.ts +3 -0
  41. package/src/corpus/briefing/intent/ground.ts +5 -1
  42. package/src/corpus/briefing/intent/match.ts +3 -1
  43. package/src/corpus/briefing/intent/model.ts +36 -3
  44. package/src/corpus/briefing/intent/resolve.ts +12 -1
  45. package/src/corpus/briefing/intent/types.ts +8 -0
  46. package/src/corpus/briefing/speak.ts +13 -0
  47. package/src/corpus/client.ts +2 -0
  48. package/src/corpus/converse/brain.ts +41 -13
  49. package/src/corpus/converse/briefing-queue.ts +105 -27
  50. package/src/corpus/converse/client.ts +6 -0
  51. package/src/corpus/converse/fleet-view.ts +126 -0
  52. package/src/corpus/converse/fleet.ts +18 -5
  53. package/src/corpus/converse/followups.ts +12 -2
  54. package/src/corpus/converse/handle.ts +21 -12
  55. package/src/corpus/converse/handoff.ts +7 -2
  56. package/src/corpus/converse/index.ts +5 -3
  57. package/src/corpus/converse/meeting-config.ts +8 -4
  58. package/src/corpus/converse/meeting.ts +66 -11
  59. package/src/corpus/converse/respond.ts +14 -2
  60. package/src/corpus/converse/spoken-form.ts +9 -2
  61. package/src/corpus/converse/spoken-summary.ts +30 -8
  62. package/src/corpus/converse/store.ts +2 -0
  63. package/src/corpus/converse/types.ts +14 -1
  64. package/src/corpus/entities.ts +2 -0
  65. package/src/corpus/extract.ts +9 -4
  66. package/src/corpus/project-basis.ts +23 -0
  67. package/src/corpus/spoken-time.ts +18 -2
  68. package/src/corpus/types.ts +6 -0
  69. package/src/corpus/voice-due.ts +24 -0
  70. package/src/native/app/converseServices.ts +5 -3
  71. package/src/native/app/device.ts +2 -0
  72. package/src/native/converse/ConverseScreen.tsx +28 -0
  73. package/src/native/converse/__tests__/liveScreen.test.tsx +35 -2
  74. package/src/native/converse/__tests__/meetingIO.test.ts +55 -1
  75. package/src/native/converse/format.ts +2 -2
  76. package/src/native/converse/io.ts +15 -5
@@ -0,0 +1,92 @@
1
+ /**
2
+ * The item edits that carry words of their own: rename, add a note, estimate, change project.
3
+ *
4
+ * Kept apart from the main grammar because their text is FREE (a new title, a note) and must keep the case it was
5
+ * said in, and because "move X to the Crochets project" must be read before "move X to <when>".
6
+ * Returns null when the reply is none of these, so the main grammar goes on as before.
7
+ */
8
+ import { splitWhen } from './dates';
9
+ import { contentWords } from './match';
10
+ import { resolveTarget } from './target';
11
+ import type { IntentContext, VoiceAction } from './types';
12
+
13
+ const FILLER = /^(?:(?:hey|ok|okay|um|uh|so|well|actually|please|yeah|yes|alright|can you|could you|would you|will you|i want to|i would like to|i'd like to|let's|lets|i need you to|go ahead and|just)\b[,\s]*)+/;
14
+ const RENAME = /^(?:rename|retitle|(?:change|update)\s+(?:the\s+)?(?:name|title)\s+of)\s+(.+?)\s+(?:to|as)\s+(?=\S)/;
15
+ const DETAIL = /^(?:add|attach|put|write|append|leave)\s+(?:a\s+)?(?:note|detail|details|comment|description)s?\s+(?:to|on|for|onto)\s+(.+?)\s*(?::|,|\bsaying\b|\bthat says\b|\bwhich says\b|\bsays\b)\s*(?=\S)/;
16
+ const PROJECT = /^(?:move|file|put|add|assign|send|switch|change)\s+(.+?)\s+(?:to|into|in|under|onto)\s+(?:the\s+)?(.+)$/;
17
+ const ESTIMATE_TRIGGER = /\b(?:estimate|estimated|will take|should take|would take|takes|time ?box|budget)\b/;
18
+
19
+ const NUMBER_WORDS: Record<string, number> = { a: 1, an: 1, one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9, ten: 10, fifteen: 15, twenty: 20, thirty: 30, forty: 40, 'forty five': 45, sixty: 60, ninety: 90 };
20
+ const DURATION = /\b(?:(an? hour and a half|half an hour|an? half hour)|(\d+(?:\.\d+)?|an?|one|two|three|four|five|six|seven|eight|nine|ten|fifteen|twenty|thirty|forty[ -]five|forty|sixty|ninety)(?:\s+and a half)?\s*(hours?|hrs?|minutes?|mins?))\b/;
21
+
22
+ /** "two hours" -> 120, "half an hour" -> 30, "an hour and a half" -> 90; null when it is not a length of time. */
23
+ export function parseDuration(text: string): { minutes: number; span: [number, number] } | null {
24
+ const m = DURATION.exec(text.toLowerCase());
25
+ if (!m) return null;
26
+ const span: [number, number] = [m.index, m.index + m[0].length];
27
+ if (m[1]) return { minutes: /half an hour|half hour/.test(m[1]) ? 30 : 90, span };
28
+ const n = Number(m[2]) || NUMBER_WORDS[m[2].replace('-', ' ')];
29
+ if (!n) return null;
30
+ const unit = /^h/.test(m[3]) ? 60 : 1;
31
+ return { minutes: Math.round(n * unit + (/and a half/.test(m[0]) ? unit / 2 : 0)), span };
32
+ }
33
+
34
+ const projectKey = (s: string) => s.toLowerCase().replace(/\b(?:the|project|projects)\b/g, ' ').replace(/[^a-z0-9]+/g, ' ').trim();
35
+ const TARGET_NOISE = /\b(?:set|give|make|put|the|an?|estimate|estimated|for|of|at|to|about|around|roughly|will|should|would|take|takes|time ?box|budget|is|as)\b/g;
36
+
37
+ export function parseItemEdit(ctx: IntentContext): VoiceAction[] | null {
38
+ const orig = ctx.utterance.replace(/[‘’]/g, "'").trim().replace(/[.!?]+$/, '');
39
+ const raw = orig.toLowerCase();
40
+ const off = FILLER.exec(raw)?.[0].length ?? 0;
41
+ const text = raw.slice(off);
42
+ const said = orig.slice(off);
43
+ const reading = ctx.readingId;
44
+ const pick = (phrase: string) => resolveTarget(phrase, ctx, reading);
45
+
46
+ const rename = RENAME.exec(text);
47
+ if (rename) {
48
+ const title = said.slice(rename[0].length).trim();
49
+ const target = pick(rename[1]);
50
+ if (!target.ok) return [{ type: 'clarify', question: target.question }];
51
+ return title ? [{ type: 'rename', itemId: target.item.id, title: title[0].toUpperCase() + title.slice(1) }] : [{ type: 'clarify', question: 'What should I call it?' }];
52
+ }
53
+
54
+ const detail = DETAIL.exec(text);
55
+ if (detail) {
56
+ const note = said.slice(detail[0].length).trim();
57
+ const target = pick(detail[1]);
58
+ if (!target.ok) return [{ type: 'clarify', question: target.question }];
59
+ return note ? [{ type: 'add_detail', itemId: target.item.id, detail: note[0].toUpperCase() + note.slice(1) }] : [{ type: 'clarify', question: 'What should the note say?' }];
60
+ }
61
+
62
+ if (ESTIMATE_TRIGGER.test(text)) {
63
+ const length = parseDuration(text);
64
+ if (length) {
65
+ const phrase = (text.slice(0, length.span[0]) + ' ' + text.slice(length.span[1])).replace(TARGET_NOISE, ' ');
66
+ const target = pick(phrase);
67
+ if (!target.ok) return [{ type: 'clarify', question: target.question }];
68
+ return [{ type: 'set_estimate', itemId: target.item.id, minutes: length.minutes }];
69
+ }
70
+ }
71
+
72
+ const project = PROJECT.exec(text);
73
+ if (project) {
74
+ const dest = project[2].trim();
75
+ const mentionsProject = /\bproject\b/.test(text);
76
+ const known = new Set([...ctx.briefed, ...ctx.open].map((i) => projectKey(i.focusName ?? '')).filter(Boolean));
77
+ const key = projectKey(dest);
78
+ const isKnown = key.length > 0 && [...known].some((k) => k === key || k.includes(key) || key.includes(k));
79
+ // A date after "to" is a reschedule ("move it to Friday"); a project needs the word "project" or a name we know.
80
+ if ((mentionsProject || isKnown) && !(splitWhen(dest, ctx.now, ctx.timeZone) && !isKnown)) {
81
+ const spoken = dest.replace(/\s+project$/, '').trim();
82
+ const named = [...ctx.briefed, ...ctx.open].map((i) => i.focusName).find((f) => f && projectKey(f) === key);
83
+ const target = pick(project[1]);
84
+ if (!target.ok) return [{ type: 'clarify', question: target.question }];
85
+ return [{ type: 'set_project', itemId: target.item.id, project: named ?? spoken }];
86
+ }
87
+ }
88
+ return null;
89
+ }
90
+
91
+ /** Words of the phrase that describe an item (exported for tests). */
92
+ export const describing = (phrase: string) => contentWords(phrase);
@@ -15,6 +15,7 @@
15
15
  import { localDate } from '../../today';
16
16
  import { normalizeSpeech, splitWhen, type SpokenWhen } from './dates';
17
17
  import { describeActions } from './describe';
18
+ import { parseItemEdit } from './edits';
18
19
  import { contentWords } from './match';
19
20
  import { resolveTarget } from './target';
20
21
  import type { IntentContext, IntentResult, VoiceAction } from './types';
@@ -159,6 +160,8 @@ function deferTo(itemId: string, when: SpokenWhen, today: string): VoiceAction {
159
160
 
160
161
  export function parseWithGrammar(ctx: IntentContext): IntentResult {
161
162
  const raw = ctx.utterance.toLowerCase().replace(/[‘’]/g, "'").trim();
163
+ const edit = parseItemEdit(ctx);
164
+ if (edit) return { actions: edit, source: 'grammar', understood: describeActions(edit, ctx), notes: [] };
162
165
  const actions: VoiceAction[] = [];
163
166
  let reading = ctx.readingId;
164
167
  for (const clause of clauses(raw)) {
@@ -55,7 +55,11 @@ export function ungrounded(actions: VoiceAction[], ctx: IntentContext): string |
55
55
  const targeted = actions.filter((a): a is Extract<VoiceAction, { itemId: string }> => 'itemId' in a);
56
56
  if (!targeted.length) return null;
57
57
  const all = [...ctx.briefed, ...ctx.open.filter((o) => !ctx.briefed.some((b) => b.id === o.id))];
58
- const text = words(ctx.utterance);
58
+ // What an edit WRITES (a new title, a note) is not a description of an item: only what was said before it is.
59
+ const written = actions.flatMap((a) => (a.type === 'rename' ? [a.title] : a.type === 'add_detail' ? [a.detail] : []));
60
+ const cutAt = written.map((w) => ctx.utterance.toLowerCase().lastIndexOf(w.toLowerCase())).filter((i) => i > 0);
61
+ const described = cutAt.length ? ctx.utterance.slice(0, Math.min(...cutAt)) : ctx.utterance;
62
+ const text = words(described);
59
63
  const spoken = text.filter((w) => contentWords(w).length && !COMMAND.has(w));
60
64
  const idx = ctx.readingId ? ctx.briefed.findIndex((i) => i.id === ctx.readingId) : -1;
61
65
  const briefedIds = new Set(ctx.briefed.map((i) => i.id));
@@ -20,7 +20,9 @@ export const words = (text: string): string[] =>
20
20
  /** The content words of a description: what is left after the filler. */
21
21
  export const contentWords = (text: string): string[] => words(text).filter((w) => !STOP.has(w));
22
22
 
23
- const same = (a: string, b: string) => a === b || (a.length >= 4 && b.length >= 4 && (a.startsWith(b.slice(0, 4)) && b.startsWith(a.slice(0, 4))));
23
+ /** "dad" is "dad's" (the apostrophe is dropped, leaving "dads"). */
24
+ const bare = (w: string) => (w.length > 3 && w.endsWith('s') ? w.slice(0, -1) : w);
25
+ const same = (a: string, b: string) => a === b || bare(a) === bare(b) || (a.length >= 4 && b.length >= 4 && (a.startsWith(b.slice(0, 4)) && b.startsWith(a.slice(0, 4))));
24
26
 
25
27
  export interface Scored { item: IntentItem; score: number }
26
28
 
@@ -11,7 +11,7 @@ import { isIsoDate, parseWhen, spokenWhen, weekdayName } from './dates';
11
11
  import { PRIORITY_NAMES } from './describe';
12
12
  import type { IntentContext, IntentItem, VoiceAction } from './types';
13
13
 
14
- export const MAX_ACTIONS = 5;
14
+ export const MAX_ACTIONS = 8;
15
15
  const MAX_OPEN_SHOWN = 40;
16
16
 
17
17
  export function intentSystemPrompt(): string {
@@ -23,7 +23,11 @@ export function intentSystemPrompt(): string {
23
23
  '{"type":"done","item_id":ID} {"type":"drop","item_id":ID}',
24
24
  '{"type":"set_priority","item_id":ID,"priority":0..4} 0 critical, 1 urgent or high, 2 medium, 3 low, 4 lowest',
25
25
  '{"type":"add_item","title":"Imperative short title","due":null | "YYYY-MM-DD"} a NEW item the person asked to add',
26
- '{"type":"undo"} undo the last change',
26
+ '{"type":"rename","item_id":ID,"title":"the new title"} change an item\'s title',
27
+ '{"type":"add_detail","item_id":ID,"detail":"the note, in the person\'s words"} add a note to an existing item (not a new item)',
28
+ '{"type":"set_estimate","item_id":ID,"minutes":number} how long it will take, in minutes (an hour is 60)',
29
+ '{"type":"set_project","item_id":ID,"project":"project name as said"} file an existing item under a project',
30
+ '{"type":"undo"} undo the last change (all of the last reply\'s changes)',
27
31
  '{"type":"clarify","question":"one short spoken question"} when you cannot tell which item or when',
28
32
  'RULES',
29
33
  '- Acting on the wrong item is far worse than asking. When unsure, return a single clarify and nothing else.',
@@ -35,6 +39,9 @@ export function intentSystemPrompt(): string {
35
39
  '- Match descriptions loosely against titles ("the bench one", "the lease call").',
36
40
  '- Adding something new ("add X", "remind me to X", "I need to X by Friday") is add_item with the thing as an imperative title and the date as due. Do not add anything that already exists as an item.',
37
41
  '- The title is the WORK itself, never the act of adding it. "add a to-do for the relay to keep the status current" is the title "Keep the status current" (say who it is for only when it matters); "remind me to call the bank" is "Call the bank". Never start a title with add, create, remind me, a to-do or a task. Keep every detail the person gave, in full: do not shorten it.',
42
+ '- "all of those", "both", "every one" mean EVERY item in the spoken list: one action per item.',
43
+ '- "add a note to X" is add_detail on the existing item X, never add_item. A new title or note is kept exactly as said, in full.',
44
+ '- "take it out of its project", "remove it from the X project", "unfile it" is set_project with "project": null, never the named project.',
38
45
  '- Several instructions in one reply are several actions in the order spoken.',
39
46
  '- Anything that is not an instruction about to-dos (greetings, chatter, questions): one clarify asking them to say it again.',
40
47
  '- Dates: resolve against today in the person\'s zone. A bare weekday is the next such day after today; "next week" is Monday of next week; "next Friday" is Friday of next week. Never return a date before today.',
@@ -89,7 +96,7 @@ export function checkModelReply(reply: string, ctx: IntentContext): Checked {
89
96
  if (!raw || typeof raw !== 'object') return { ok: false, reason: 'action is not an object' };
90
97
  const type = raw.type;
91
98
  const id = typeof raw.item_id === 'string' ? raw.item_id : '';
92
- const needsItem = ['defer', 'pull_today', 'done', 'drop', 'set_priority'].includes(String(type));
99
+ const needsItem = ['defer', 'pull_today', 'done', 'drop', 'set_priority', 'rename', 'add_detail', 'set_estimate', 'set_project'].includes(String(type));
93
100
  if (needsItem && !known.has(id)) return { ok: false, reason: `unknown item ${JSON.stringify(raw.item_id)}` };
94
101
  switch (type) {
95
102
  case 'defer': {
@@ -123,6 +130,32 @@ export function checkModelReply(reply: string, ctx: IntentContext): Checked {
123
130
  out.push({ type: 'add_item', title: t[0].toUpperCase() + t.slice(1), dueDate: due });
124
131
  break;
125
132
  }
133
+ case 'rename': {
134
+ const t = typeof raw.title === 'string' ? raw.title.trim() : '';
135
+ if (!t || t.length > 200) return { ok: false, reason: 'bad title' };
136
+ out.push({ type: 'rename', itemId: id, title: t[0].toUpperCase() + t.slice(1) });
137
+ break;
138
+ }
139
+ case 'add_detail': {
140
+ const d = typeof raw.detail === 'string' ? raw.detail.trim() : '';
141
+ if (!d || d.length > 2000) return { ok: false, reason: 'bad detail' };
142
+ out.push({ type: 'add_detail', itemId: id, detail: d[0].toUpperCase() + d.slice(1) });
143
+ break;
144
+ }
145
+ case 'set_estimate': {
146
+ const m = raw.minutes;
147
+ if (m === null) { out.push({ type: 'set_estimate', itemId: id, minutes: null }); break; }
148
+ if (typeof m !== 'number' || !Number.isFinite(m) || m <= 0 || m > 60 * 24 * 30) return { ok: false, reason: 'bad estimate' };
149
+ out.push({ type: 'set_estimate', itemId: id, minutes: Math.round(m) });
150
+ break;
151
+ }
152
+ case 'set_project': {
153
+ if (raw.project === null) { out.push({ type: 'set_project', itemId: id, project: null }); break; }
154
+ const p = typeof raw.project === 'string' ? raw.project.trim() : '';
155
+ if (!p || p.length > 100) return { ok: false, reason: 'bad project' };
156
+ out.push({ type: 'set_project', itemId: id, project: p });
157
+ break;
158
+ }
126
159
  case 'undo': out.push({ type: 'undo' }); break;
127
160
  case 'clarify': {
128
161
  const q = typeof raw.question === 'string' ? raw.question.trim() : '';
@@ -6,6 +6,7 @@
6
6
  * contradicts the data. A low-confidence model answer asks instead of acting.
7
7
  * NEVER executes anything.
8
8
  */
9
+ import { matchItems } from './match';
9
10
  import { describeActions } from './describe';
10
11
  import { parseWithGrammar } from './grammar';
11
12
  import { ungrounded } from './ground';
@@ -21,10 +22,20 @@ function byGrammar(ctx: IntentContext, notes: string[]): IntentResult {
21
22
  return { ...out, confidence: out.actions.some((a) => a.type !== 'clarify' && a.type !== 'none') ? 1 : 0, notes };
22
23
  }
23
24
 
25
+ /**
26
+ * The words that answer "which one?": when they name exactly one open item, the earlier instruction is read again against that item
27
+ * alone, so "the dad one" settles "move the bench one to Friday". Otherwise both are read together.
28
+ */
29
+ function withAnswer(asked: IntentContext, thread: { utterance: string; question: string }): IntentContext {
30
+ const found = matchItems(asked.utterance, [...asked.briefed, ...asked.open.filter((o) => !asked.briefed.some((b) => b.id === o.id))]);
31
+ if (found.kind === 'one') return { ...asked, utterance: thread.utterance, briefed: [found.item], open: [found.item], thread: undefined };
32
+ return { ...asked, utterance: `${thread.utterance} ${asked.utterance}` };
33
+ }
34
+
24
35
  export async function resolveVoiceIntent(asked: IntentContext, options: IntentOptions = {}): Promise<IntentResult> {
25
36
  const notes: string[] = [];
26
37
  // An answer to our question is read WITH what was said first: dates and items come from either.
27
- const ctx: IntentContext = asked.thread ? { ...asked, utterance: `${asked.thread.utterance} ${asked.utterance}` } : asked;
38
+ const ctx: IntentContext = asked.thread ? withAnswer(asked, asked.thread) : asked;
28
39
  if (!asked.utterance.trim()) return byGrammar(ctx, ['empty utterance']);
29
40
 
30
41
  if (options.llm) {
@@ -42,6 +42,14 @@ export type VoiceAction =
42
42
  /** 0 critical, 1 urgent, 2 medium, 3 low, 4 lowest. */
43
43
  | { type: 'set_priority'; itemId: string; priority: number }
44
44
  | { type: 'add_item'; title: string; dueDate: string | null }
45
+ /** Change an item's title. */
46
+ | { type: 'rename'; itemId: string; title: string }
47
+ /** Add a note to an item's detail (appended; what was there stays). */
48
+ | { type: 'add_detail'; itemId: string; detail: string }
49
+ /** How long it will take, in minutes; null clears it. */
50
+ | { type: 'set_estimate'; itemId: string; minutes: number | null }
51
+ /** File it under a project, by the name said; null takes it out of its project. */
52
+ | { type: 'set_project'; itemId: string; project: string | null }
45
53
  | { type: 'undo' }
46
54
  /** A short thing to say back when the reply was not clear enough to act on. */
47
55
  | { type: 'clarify'; question: string }
@@ -79,3 +79,16 @@ export function speakDatesIn(text: string, today: string): string {
79
79
  return month >= 1 && month <= 12 && Number(d) >= 1 && Number(d) <= 31 ? speakDate(m, today) : m;
80
80
  });
81
81
  }
82
+
83
+ /** Minutes as a person says a length of time: `an hour and a half`, `forty-five minutes`, `two hours`. */
84
+ export function spokenMinutes(total: number): string {
85
+ const n = Math.max(0, Math.round(total));
86
+ if (n === 30) return 'half an hour';
87
+ const hours = Math.floor(n / 60);
88
+ const rest = n % 60;
89
+ const h = hours === 1 ? 'an hour' : `${speakCount(hours)} hours`;
90
+ if (!hours) return `${speakCount(rest)} ${rest === 1 ? 'minute' : 'minutes'}`;
91
+ if (!rest) return h;
92
+ if (rest === 30) return `${h} and a half`;
93
+ return `${h} and ${speakCount(rest)} ${rest === 1 ? 'minute' : 'minutes'}`;
94
+ }
@@ -1445,8 +1445,10 @@ export function createPlanningApi(options: CreateCorpusApiOptions): PlanningApi
1445
1445
  wire.owner_sub = patch.ownerSubs[0] ?? '';
1446
1446
  }
1447
1447
  if (patch.dueAt !== undefined) wire.due_at = patch.dueAt;
1448
+ if (patch.projectBasis !== undefined) wire.project_basis = patch.projectBasis ?? '';
1448
1449
  if (patch.subtype !== undefined) wire.subtype = patch.subtype;
1449
1450
  if (patch.priority !== undefined) wire.priority = patch.priority;
1451
+ if (patch.estimateMinutes !== undefined) wire.estimate_minutes = patch.estimateMinutes;
1450
1452
  if (patch.resolvedAt !== undefined) wire.resolved_at = patch.resolvedAt;
1451
1453
  // WHEN it was finished, stamped on the transition to done only (never on
1452
1454
  // an edit to an already-done item, never over a value the caller sent):
@@ -17,14 +17,16 @@ import { speakable } from '../briefing/speak';
17
17
  import type { BriefingItem } from '../briefing/types';
18
18
  import { FLEET_FRESH_MS, ageWords } from './fleet';
19
19
  import { routeUtterance } from './route';
20
- import { spokenSummary } from './spoken-summary';
21
- import { sourcesOfDocs } from './sources';
20
+ import { spokenRest, spokenSummary, WANTS_THE_REST } from './spoken-summary';
21
+ import { askSources, sourcesOfDocs } from './sources';
22
+ import type { SourceDocument } from '../types';
22
23
  import { WRAP_UP } from './wrap-up';
23
24
  import { itemAnswer } from './item-answers';
24
25
  import { followUp, mightFollowUp, type PlayedItem } from './followups';
25
26
  import { ACTIVITY_QUESTION, composeActivity, forOwner, type Activity, type ActivityWindow } from '../activity';
27
+ import { localDate } from '../today';
26
28
  import { questionWindow } from '../ask-items-intent';
27
- import { BRIEF_ME, NEEDS_ME, buildQueue, firstPrompt, relayItemsFrom, stepBriefing, type BriefingEffect, type BriefingState } from './briefing-queue';
29
+ import { BRIEF_ME, NEEDS_ME, buildQueue, firstPrompt, relayItemsFrom, startBriefing, stepBriefing, type BriefingEffect, type BriefingState } from './briefing-queue';
28
30
  import type { ConverseBrain, ConverseSource, HistoryLine } from './types';
29
31
 
30
32
  const MIN_AUTO = 0.85;
@@ -42,7 +44,7 @@ export interface ConverseBrainDeps {
42
44
  /** What happened in a calendar window (to-dos finished or added, conversations, notes): "what did I do yesterday". Omit: those go to Ask. */
43
45
  loadActivity?(window: ActivityWindow, timeZone: string): Promise<Activity>;
44
46
  /** Answers a question over the person's items, notes and documents; the app wires `askCorpus`. */
45
- ask(input: { question: string; timeZone: string; now: number }): Promise<{ answer: string; status?: string; sources?: ConverseSource[] }>;
47
+ ask(input: { question: string; timeZone: string; now: number }): Promise<{ answer: string; status?: string; sources?: ConverseSource[]; /** Ask's own citations: used for the sources when `sources` is not given. */ citations?: Array<{ document: SourceDocument }> }>;
46
48
  minAutoConfidence?: number;
47
49
  /** Sorts a line into work for the relay / a fleet-status question / other. Omit: everything not an item edit goes to Ask. */
48
50
  routeLlm?: BriefingScriptLlm | null;
@@ -172,6 +174,15 @@ export function createConverseBrain(deps: ConverseBrainDeps): ConverseBrain {
172
174
  const effect: BriefingEffect | undefined = step.effect;
173
175
  let text = step.reply;
174
176
  let did: string[] | undefined;
177
+ if (effect?.kind === 'skip') {
178
+ // Remembered for today only: a new day brings it back.
179
+ const today = localDate(now, timeZone);
180
+ const log = await deps.log.load().catch(() => null);
181
+ if (log) {
182
+ const kept = log.skips?.date === today ? log.skips.keys : [];
183
+ await deps.log.save({ ...log, skips: { date: today, keys: [...new Set([...kept, effect.key])].slice(-200) } }).catch(() => undefined);
184
+ }
185
+ }
175
186
  if (effect?.kind === 'todo') {
176
187
  const outcome = await timed('act', () => executeVoiceActions({
177
188
  actions: [effect.action], clientActionId: `brief-${now}-${Math.abs(hash(`${utterance}${'itemId' in effect.action ? effect.action.itemId : ''}`))}`.slice(0, 64),
@@ -183,7 +194,7 @@ export function createConverseBrain(deps: ConverseBrainDeps): ConverseBrain {
183
194
  return { text, briefing: step.state, intent: 'briefing' as const, ...(did?.length ? { did } : {}), ...(effect?.kind === 'relay' ? { forRelay: true, relayText: effect.text } : {}) };
184
195
  }
185
196
 
186
- async function run({ utterance, history, timeZone, now, briefing, context }: Parameters<ConverseBrain>[0], timed: Timed): ReturnType<ConverseBrain> {
197
+ async function run({ utterance, history, timeZone, now, briefing, context, pending }: Parameters<ConverseBrain>[0], timed: Timed): ReturnType<ConverseBrain> {
187
198
  // Lines that name the relay go first, so "add a to-do for the relay" is for the relay, not a plan item.
188
199
  if (ADDRESSES_RELAY.test(utterance)) {
189
200
  const routed = await viaRoute(utterance, history, now, timed);
@@ -191,11 +202,20 @@ export function createConverseBrain(deps: ConverseBrainDeps): ConverseBrain {
191
202
  }
192
203
  // A briefing in progress: this is the answer to the item being asked.
193
204
  if (briefing) {
194
- const step = stepBriefing(briefing, utterance);
205
+ const step = stepBriefing(briefing, utterance, { now, timeZone });
195
206
  if (!step.passThrough) return applyStep(step, utterance, now, timeZone, timed);
196
207
  }
197
208
  // "Parse that note" / "that's it" / "I'm done": he is wrapping up. The turn files the conversation through the normal End.
198
209
  if (WRAP_UP.test(utterance.trim())) return { text: 'Filing it now.', finish: true, intent: 'note' as const };
210
+ // "Yes" / "the rest" right after a shortened answer: read what was left out (itself said short, with another offer when it is long).
211
+ if (!pending && WANTS_THE_REST.test(utterance.trim())) {
212
+ const lastSaid = [...history].reverse().find((l) => l.role === 'assistant')?.text;
213
+ const rest = lastSaid ? spokenRest(lastSaid) : undefined;
214
+ if (rest) {
215
+ const short = spokenSummary(rest);
216
+ return { text: rest, intent: 'question' as const, ...(short ? { spoken: short } : {}) };
217
+ }
218
+ }
199
219
  // A follow-up about the items the last answer listed ("move the second one to Friday", "tell me more about the first").
200
220
  let itemRows: BriefingItem[] | null = null;
201
221
  if (context?.items?.length && mightFollowUp(utterance)) {
@@ -233,9 +253,10 @@ export function createConverseBrain(deps: ConverseBrainDeps): ConverseBrain {
233
253
  timed('items', () => deps.loadItems().catch(() => [] as BriefingItem[])),
234
254
  timed('fleet', async () => deps.loadFleetStatus?.().catch(() => null) ?? null),
235
255
  ]);
236
- const queue = buildQueue({ items: rows, relayItems: snap ? relayItemsFrom(snap.text) : [], now, timeZone, relayFirst: NEEDS_ME.test(utterance) });
237
- if (!queue.length) return { text: 'Nothing needs you right now.', intent: 'briefing' as const };
238
- const state: BriefingState = { queue, index: 0 };
256
+ const log = await timed('log', () => deps.log.load().catch(() => null));
257
+ const skipped = log?.skips?.date === localDate(now, timeZone) ? log.skips.keys : [];
258
+ const state = startBriefing({ items: rows, relayItems: snap ? relayItemsFrom(snap.text) : [], now, timeZone, relayFirst: NEEDS_ME.test(utterance), skipped });
259
+ if (!state) return { text: 'Nothing needs you right now.', intent: 'briefing' as const };
239
260
  return { text: firstPrompt(state), briefing: state, intent: 'briefing' as const };
240
261
  }
241
262
  // A QUESTION is almost never an item edit, and the routing model does not depend on the intent model: start it now so a
@@ -258,10 +279,16 @@ export function createConverseBrain(deps: ConverseBrainDeps): ConverseBrain {
258
279
  ]);
259
280
  const open = openRows.map(intentItem);
260
281
  const intent = asking ? null : await timed('intent', () => resolveVoiceIntent(
261
- { utterance, now, timeZone, briefed: [], open, readingId: null, hasUndo: Boolean(log?.stack.length) },
282
+ { utterance, now, timeZone, briefed: [], open, readingId: null, hasUndo: Boolean(log?.stack.length), ...(pending ? { thread: pending } : {}) },
262
283
  { llm: deps.intentLlm ?? null, ...(deps.intentTimeoutMs ? { timeoutMs: deps.intentTimeoutMs } : {}) },
263
284
  ).catch(() => null));
264
285
 
286
+ // A which-one question about an instruction is asked out loud and kept, so the next words answer it ("the dad one").
287
+ const clarify = intent?.actions.length === 1 && intent.actions[0].type === 'clarify' ? intent.actions[0].question : null;
288
+ if (clarify && !pending && /\bwhich\b/i.test(clarify) && EXPLICIT_TODO.test(utterance.trim())) {
289
+ return { text: clarify, intent: 'command' as const, pending: { utterance, question: clarify } };
290
+ }
291
+
265
292
  const real = intent?.actions.filter((a) => a.type !== 'clarify' && a.type !== 'none') ?? [];
266
293
  const sure = intent && real.length === intent.actions.length && real.length > 0 && (intent.confidence ?? 1) >= (deps.minAutoConfidence ?? MIN_AUTO);
267
294
  if (intent && sure) {
@@ -269,7 +296,7 @@ export function createConverseBrain(deps: ConverseBrainDeps): ConverseBrain {
269
296
  actions: intent.actions, clientActionId: `converse-${now}-${Math.abs(hash(utterance))}`.slice(0, 64), seam: deps.seam, log: deps.log,
270
297
  ownerSub: deps.ownerSub, now: () => now, timeZone,
271
298
  }));
272
- return { text: outcome.text, did: outcome.results.map((r) => r.spoken).filter(Boolean), intent: 'command' as const };
299
+ return { text: outcome.text, did: outcome.results.map((r) => r.spoken).filter(Boolean), intent: 'command' as const, pending: null };
273
300
  }
274
301
 
275
302
  if (!ADDRESSES_RELAY.test(utterance)) {
@@ -282,8 +309,9 @@ export function createConverseBrain(deps: ConverseBrainDeps): ConverseBrain {
282
309
  const full = speakable(answered.answer ?? '', 400) || (answered.answer ?? '').trim();
283
310
  if (!full || GIVE_UP.test(full)) return { text: CANNOT_SEE, intent: 'question' as const };
284
311
  const short = spokenSummary(full);
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 } } : {}) };
312
+ const sources = answered.sources ?? (answered.citations ? askSources(answered) : undefined);
313
+ const listed: PlayedItem[] = (sources ?? []).filter((x) => x.id.startsWith('item:')).map((x) => ({ id: x.id.replace(/^item:/, ''), title: x.title }));
314
+ return { text: full, intent: 'question' as const, ...(short ? { spoken: short } : {}), ...(sources?.length ? { sources } : {}), ...(listed.length ? { context: { items: listed } } : {}) };
287
315
  }
288
316
 
289
317
  return async (input) => {
@@ -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));