@startsimpli/integrations 0.2.200 → 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 (70) hide show
  1. package/package.json +6 -6
  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.test.ts +22 -0
  14. package/src/__tests__/corpus-tracker.test.tsx +12 -0
  15. package/src/__tests__/extract-classify.test.ts +17 -0
  16. package/src/__tests__/fleet-page.test.tsx +57 -0
  17. package/src/__tests__/fleet-view.test.ts +149 -0
  18. package/src/__tests__/project-basis-entity.test.ts +19 -0
  19. package/src/__tests__/project-basis.test.ts +21 -0
  20. package/src/__tests__/relay-cli.test.ts +10 -1
  21. package/src/__tests__/task-detail-project-guess.test.tsx +46 -0
  22. package/src/components/index.ts +2 -0
  23. package/src/components/pages/FleetPage.tsx +115 -0
  24. package/src/components/pages/TaskDetailPage.tsx +27 -1
  25. package/src/components/pages/TrackerPage.tsx +1 -1
  26. package/src/components/pages/task-tracker/ProjectGuess.tsx +42 -0
  27. package/src/corpus/ask-items.ts +7 -4
  28. package/src/corpus/ask.ts +1 -1
  29. package/src/corpus/briefing/actions/confirm.ts +9 -1
  30. package/src/corpus/briefing/actions/execute.ts +71 -11
  31. package/src/corpus/briefing/actions/log.ts +1 -1
  32. package/src/corpus/briefing/actions/seam.ts +18 -2
  33. package/src/corpus/briefing/actions/types.ts +14 -0
  34. package/src/corpus/briefing/intent/describe.ts +5 -1
  35. package/src/corpus/briefing/intent/edits.ts +92 -0
  36. package/src/corpus/briefing/intent/grammar.ts +3 -0
  37. package/src/corpus/briefing/intent/ground.ts +5 -1
  38. package/src/corpus/briefing/intent/match.ts +3 -1
  39. package/src/corpus/briefing/intent/model.ts +36 -3
  40. package/src/corpus/briefing/intent/resolve.ts +12 -1
  41. package/src/corpus/briefing/intent/types.ts +8 -0
  42. package/src/corpus/briefing/speak.ts +13 -0
  43. package/src/corpus/client.ts +2 -0
  44. package/src/corpus/converse/brain.ts +41 -13
  45. package/src/corpus/converse/briefing-queue.ts +105 -27
  46. package/src/corpus/converse/client.ts +6 -0
  47. package/src/corpus/converse/fleet-view.ts +126 -0
  48. package/src/corpus/converse/fleet.ts +18 -5
  49. package/src/corpus/converse/followups.ts +12 -2
  50. package/src/corpus/converse/handle.ts +21 -12
  51. package/src/corpus/converse/handoff.ts +7 -2
  52. package/src/corpus/converse/index.ts +5 -3
  53. package/src/corpus/converse/meeting-config.ts +8 -4
  54. package/src/corpus/converse/meeting.ts +66 -11
  55. package/src/corpus/converse/respond.ts +14 -2
  56. package/src/corpus/converse/spoken-form.ts +9 -2
  57. package/src/corpus/converse/spoken-summary.ts +30 -8
  58. package/src/corpus/converse/store.ts +2 -0
  59. package/src/corpus/converse/types.ts +14 -1
  60. package/src/corpus/entities.ts +2 -0
  61. package/src/corpus/extract.ts +9 -4
  62. package/src/corpus/project-basis.ts +23 -0
  63. package/src/corpus/types.ts +6 -0
  64. package/src/native/app/converseServices.ts +5 -3
  65. package/src/native/app/device.ts +2 -0
  66. package/src/native/converse/ConverseScreen.tsx +28 -0
  67. package/src/native/converse/__tests__/liveScreen.test.tsx +35 -2
  68. package/src/native/converse/__tests__/meetingIO.test.ts +55 -1
  69. package/src/native/converse/format.ts +2 -2
  70. package/src/native/converse/io.ts +15 -5
@@ -22,11 +22,12 @@ import { OwnerPicker } from './task-tracker/OwnerPicker';
22
22
  import type { RosterMember } from '../../corpus/owner-link';
23
23
  import { ExternalLinkChip } from './task-tracker/ExternalLinkChip';
24
24
  import { failureMessage } from './work-items';
25
+ import { ProjectGuess } from './task-tracker/ProjectGuess';
25
26
  import { PossiblyDoneNote, markDonePatch, notDonePatch } from './tracker/PossiblyDone';
26
27
  import type { MemberConnectionsApi } from './types';
27
28
 
28
29
  export interface TaskDetailPageProps {
29
- api: Pick<CommitmentApi, 'listCommitments' | 'updateCommitment'> & {
30
+ api: Pick<CommitmentApi, 'listCommitments' | 'updateCommitment'> & Partial<Pick<CommitmentApi, 'fileCommitment'>> & {
30
31
  /** The workspace roster; absent means the owner stays text, as before. */
31
32
  listMembers?: () => Promise<RosterMember[]>;
32
33
  };
@@ -146,6 +147,26 @@ export function TaskDetailPage({
146
147
  }
147
148
  };
148
149
 
150
+ const confirmProject = async () => {
151
+ await patchItem({ projectBasis: null });
152
+ setItem((cur) => { if (!cur) return cur; const { projectBasis: _was, ...rest } = cur; return rest as Commitment; });
153
+ };
154
+ const changeProject = async (focusId: string) => {
155
+ if (!item || !apiRef.current.fileCommitment) return;
156
+ setBusy(true);
157
+ setError('');
158
+ try {
159
+ await apiRef.current.fileCommitment(item, focusId);
160
+ await apiRef.current.updateCommitment?.(item, { projectBasis: null });
161
+ const { projectBasis: _was, ...rest } = item;
162
+ setItem({ ...rest, focusId } as Commitment);
163
+ } catch (err) {
164
+ setError(failureMessage(err));
165
+ } finally {
166
+ setBusy(false);
167
+ }
168
+ };
169
+
149
170
  const setStatus = async (status: CommitmentStatus) => {
150
171
  if (!item || !apiRef.current.updateCommitment) return;
151
172
  setBusy(true);
@@ -227,6 +248,11 @@ export function TaskDetailPage({
227
248
  {project ? <span className={cn.badge}>{project}</span> : null}
228
249
  {item.sync ? <ExternalLinkChip sync={item.sync} trackerName={trackerName} className={cn.badge} /> : null}
229
250
  </div>
251
+ {item.projectBasis && project && !editing ? (
252
+ <ProjectGuess basis={item.projectBasis} projectId={item.focusId} projects={projectNames}
253
+ onConfirm={confirmProject} onChange={apiRef.current.fileCommitment ? changeProject : undefined}
254
+ disabled={busy || !canWrite} mutedClassName={cn.muted} buttonClassName={cn.secondaryButton} />
255
+ ) : null}
230
256
  {editing ? (
231
257
  <form className="mt-3 space-y-3" onSubmit={(e) => { e.preventDefault(); void save(); }}>
232
258
  <label className="block text-sm">Title
@@ -448,7 +448,7 @@ export function TrackerPage({
448
448
  <CompactItemRow
449
449
  key={entry.item.externalId}
450
450
  item={entry.item} due={entry.due} days={entry.days}
451
- project={extra?.chip ?? (entry.item.focusId ? projectNames[entry.item.focusId] : undefined)}
451
+ project={extra?.chip ?? (entry.item.focusId && projectNames[entry.item.focusId] ? `${projectNames[entry.item.focusId]}${entry.item.projectBasis ? ' (guessed)' : ''}` : undefined)}
452
452
  trackerName={trackerName}
453
453
  onOpen={onOpenItem || entry.item.mentions.length ? open : undefined}
454
454
  actions={extra?.actions}
@@ -0,0 +1,42 @@
1
+ /**
2
+ * "WE GUESSED THIS PROJECT" (bd startsim-tmrvi.22, Quinn: keep guessing, but show it and make it one tap to fix).
3
+ * Shown under an item's project only while the item carries `projectBasis`. Confirming or changing clears it.
4
+ */
5
+ import * as React from 'react';
6
+
7
+ export interface ProjectGuessProps {
8
+ basis: string;
9
+ projectId?: string;
10
+ projects: Record<string, string>;
11
+ /** Refile under another project. Absent: the picker is not offered. */
12
+ onChange?: (projectId: string) => Promise<void>;
13
+ onConfirm: () => Promise<void>;
14
+ disabled?: boolean;
15
+ mutedClassName?: string;
16
+ buttonClassName?: string;
17
+ }
18
+
19
+ export function ProjectGuess({ basis, projectId, projects, onChange, onConfirm, disabled, mutedClassName, buttonClassName }: ProjectGuessProps) {
20
+ const ids = Object.keys(projects);
21
+ return (
22
+ <div className="mt-2 flex flex-wrap items-center gap-2 text-sm" data-testid="project-guess">
23
+ <span className={mutedClassName}>Project {basis}.</span>
24
+ <button type="button" className={buttonClassName} disabled={disabled} onClick={() => void onConfirm()}>That’s right</button>
25
+ {onChange && ids.length > 1 ? (
26
+ <label className="inline-flex items-center gap-1">
27
+ <span className="sr-only">Change project</span>
28
+ <select
29
+ aria-label="Change project"
30
+ className="rounded-md border border-gray-300 px-2 py-1 text-sm"
31
+ disabled={disabled}
32
+ value={projectId ?? ''}
33
+ onChange={(e) => { if (e.target.value && e.target.value !== projectId) void onChange(e.target.value); }}
34
+ >
35
+ {projectId ? null : <option value="">Pick a project</option>}
36
+ {ids.map((id) => <option key={id} value={id}>{projects[id]}</option>)}
37
+ </select>
38
+ </label>
39
+ ) : null}
40
+ </div>
41
+ );
42
+ }
@@ -26,11 +26,11 @@ export interface ItemContext {
26
26
  /** The reader's member id, for "my". */
27
27
  ownerSub?: string;
28
28
  /** Project names by focus id, when the caller has them. */
29
- focusNames?: Record<string, string>;
29
+ focusNames?: Record<string, string> | Promise<Record<string, string>>;
30
30
  }
31
31
 
32
32
  /** One item as a record the model can read and the screen can cite. */
33
- export function itemAsDocument(item: Commitment, ctx: ItemContext): SourceDocument {
33
+ export function itemAsDocument(item: Commitment, ctx: Omit<ItemContext, 'focusNames'> & { focusNames?: Record<string, string> }): SourceDocument {
34
34
  const zone = ctx.timeZone ?? 'UTC';
35
35
  const due = dueDay(item.dueAt, zone);
36
36
  const project = item.focusId ? ctx.focusNames?.[item.focusId] : undefined;
@@ -91,9 +91,12 @@ export async function retrieveItems(
91
91
  if (!intent || !api) return { intent: null, retrieved: [], matched: 0 };
92
92
  const page = await api.listCommitments({ pageSize: 200, sort: 'due', withFocus: true }).catch(() => null);
93
93
  if (!page) return { intent, retrieved: [], matched: 0 };
94
- const selected = selectItems(page.results.filter((item) => isInScope(item, scope)), intent, ctx);
94
+ // The project names load beside the item list (the caller starts both), so they are awaited only now.
95
+ const names = await Promise.resolve(ctx.focusNames).catch(() => undefined);
96
+ const resolved = { ...ctx, focusNames: names };
97
+ const selected = selectItems(page.results.filter((item) => isInScope(item, scope)), intent, resolved);
95
98
  const retrieved = selected.slice(0, limit).map((item): RetrievedDocument => {
96
- const document = itemAsDocument(item, ctx);
99
+ const document = itemAsDocument(item, resolved);
97
100
  return { document, score: 1, matchedTerms: [], snippet: document.body.split('\n').slice(0, 2).join(' · ') };
98
101
  });
99
102
  return { intent, retrieved, matched: selected.length };
package/src/corpus/ask.ts CHANGED
@@ -56,7 +56,7 @@ export interface AskCorpusOptions {
56
56
  /** The reader's member id, for "what did I commit to". */
57
57
  ownerSub?: string;
58
58
  /** Project names by focus id, for the item records. */
59
- focusNames?: Record<string, string>;
59
+ focusNames?: Record<string, string> | Promise<Record<string, string>>;
60
60
  }
61
61
 
62
62
  const DEFAULTS = {
@@ -2,7 +2,7 @@
2
2
  import { localDate } from '../../today';
3
3
  import { spokenWhen } from '../intent/dates';
4
4
  import { PRIORITY_NAMES } from '../intent/describe';
5
- import { speakable } from '../speak';
5
+ import { spokenMinutes, speakable } from '../speak';
6
6
  import type { BriefingAudio, BriefingSynthesize } from '../generate';
7
7
  import type { ItemPatch, UndoEntry } from './types';
8
8
  import type { VoiceAction } from '../intent/types';
@@ -21,6 +21,10 @@ export function confirmText(action: VoiceAction, title: string, now: number, tim
21
21
  case 'drop': return `Dropped ${t}.`;
22
22
  case 'set_priority': return `Made ${t} ${PRIORITY_NAMES[action.priority] ?? `priority ${action.priority}`}.`;
23
23
  case 'add_item': return `Added ${shortTitle(action.title)}${action.dueDate ? ` for ${spokenWhen(action.dueDate, today)}` : ''}.`;
24
+ case 'rename': return `Renamed it to ${shortTitle(action.title)}.`;
25
+ case 'add_detail': return `Added a note to ${t}.`;
26
+ case 'set_estimate': return action.minutes === null ? `Cleared the estimate on ${t}.` : `Set ${t} to ${spokenMinutes(action.minutes)}.`;
27
+ case 'set_project': return action.project === null ? `Took ${t} out of its project.` : `Moved ${t} to ${shortTitle(action.project)}.`;
24
28
  default: return '';
25
29
  }
26
30
  }
@@ -35,6 +39,10 @@ export function undoText(entry: UndoEntry, now: number, timeZone: string): strin
35
39
  if ('dueAt' in b) parts.push(b.dueAt ? `due ${spokenWhen(String(b.dueAt).slice(0, 10), today)}` : 'no date');
36
40
  if ('status' in b && b.status) parts.push(b.status === 'open' ? 'open' : String(b.status));
37
41
  if ('priority' in b) parts.push(b.priority === null || b.priority === undefined ? 'no priority' : PRIORITY_NAMES[b.priority] ?? `priority ${b.priority}`);
42
+ if ('title' in b && b.title) parts.push(`called ${shortTitle(b.title)}`);
43
+ if ('detail' in b) parts.push('its old note');
44
+ if ('estimateMinutes' in b) parts.push(b.estimateMinutes ? `${spokenMinutes(b.estimateMinutes)}` : 'no estimate');
45
+ if ('focusId' in b) parts.push('its old project');
38
46
  return `Undid it. ${t} is back to ${parts.join(', ') || 'how it was'}.`;
39
47
  }
40
48
 
@@ -10,6 +10,7 @@
10
10
  * Only what really changed is on the undo stack.
11
11
  */
12
12
  import { localDate } from '../../today';
13
+ import { speakCount } from '../speak';
13
14
  import type { VoiceAction } from '../intent/types';
14
15
  import { confirmText, shortTitle, undoText } from './confirm';
15
16
  import { REMEMBERED_ACTIONS, UNDO_DEPTH } from './log';
@@ -41,6 +42,10 @@ function snapshot(item: EditableItem, patch: ItemPatch): ItemPatch {
41
42
  else if (key === 'resolvedAt') before.resolvedAt = item.resolvedAt ?? null;
42
43
  else if (key === 'statusReason') before.statusReason = item.statusReason ?? '';
43
44
  else if (key === 'status') before.status = item.status;
45
+ else if (key === 'title') before.title = item.title;
46
+ else if (key === 'detail') before.detail = item.detail ?? '';
47
+ else if (key === 'estimateMinutes') before.estimateMinutes = item.estimateMinutes ?? null;
48
+ else if (key === 'focusId') before.focusId = item.focusId ?? null;
44
49
  }
45
50
  return before;
46
51
  }
@@ -50,9 +55,43 @@ function changedSince(item: EditableItem, after: ItemPatch): boolean {
50
55
  if ('dueAt' in after && !sameDay(item.dueAt, after.dueAt)) return true;
51
56
  if ('status' in after && item.status !== after.status) return true;
52
57
  if ('priority' in after && (item.priority ?? null) !== (after.priority ?? null)) return true;
58
+ if ('title' in after && item.title !== after.title) return true;
59
+ if ('detail' in after && (item.detail ?? '') !== (after.detail ?? '')) return true;
60
+ if ('estimateMinutes' in after && (item.estimateMinutes ?? null) !== (after.estimateMinutes ?? null)) return true;
61
+ if ('focusId' in after && (item.focusId ?? null) !== (after.focusId ?? null)) return true;
53
62
  return false;
54
63
  }
55
64
 
65
+ const projectKey = (name: string) => name.toLowerCase().replace(/\b(?:the|project|projects)\b/g, ' ').replace(/[^a-z0-9]+/g, ' ').trim();
66
+
67
+ /** The project a spoken name means: an exact match, else the one project whose name holds it (or it holds). */
68
+ function findProject(name: string, focuses: Array<{ id: string; title: string }>) {
69
+ const key = projectKey(name);
70
+ if (!key) return null;
71
+ const exact = focuses.filter((f) => projectKey(f.title) === key);
72
+ if (exact.length === 1) return exact[0];
73
+ const near = focuses.filter((f) => { const k = projectKey(f.title); return k.includes(key) || key.includes(k); });
74
+ return near.length === 1 ? near[0] : null;
75
+ }
76
+
77
+ type Planned = { patch: ItemPatch; action: VoiceAction } | { ask: string };
78
+
79
+ async function planFor(action: VoiceAction, item: EditableItem, today: string, nowIso: string, seam: ItemEditSeam): Promise<Planned> {
80
+ switch (action.type) {
81
+ case 'rename': return { patch: { title: action.title }, action };
82
+ case 'add_detail': return { patch: { detail: item.detail ? `${item.detail}\n\n${action.detail}` : action.detail }, action };
83
+ case 'set_estimate': return { patch: { estimateMinutes: action.minutes }, action };
84
+ case 'set_project': {
85
+ if (action.project === null) return { patch: { focusId: null }, action };
86
+ if (!seam.listFocuses) throw new Error('This client cannot change projects.');
87
+ const focus = findProject(action.project, await seam.listFocuses());
88
+ if (!focus) return { ask: `I could not find a project called ${shortTitle(action.project)}.` };
89
+ return { patch: { focusId: focus.id }, action: { ...action, project: focus.title } };
90
+ }
91
+ default: return { patch: patchFor(action, today, nowIso) as ItemPatch, action };
92
+ }
93
+ }
94
+
56
95
  function patchFor(action: VoiceAction, today: string, nowIso: string): ItemPatch | null {
57
96
  switch (action.type) {
58
97
  case 'defer': return { dueAt: action.to === 'later' ? null : action.to };
@@ -75,10 +114,10 @@ function remember(log: ActionLog, key: string, result: ActionResult) {
75
114
  while (log.order.length > REMEMBERED_ACTIONS) delete log.applied[log.order.shift() as string];
76
115
  }
77
116
 
78
- async function undoOne(log: ActionLog, input: ExecuteInput, now: number): Promise<ActionResult> {
79
- const entry = log.stack[log.stack.length - 1];
80
- if (!entry) return { status: 'asked', spoken: 'There is nothing to undo.' };
81
- log.stack.pop(); // popped either way: an entry that cannot be restored must not block the ones under it
117
+ const groupOf = (entry: UndoEntry) => entry.actionId.split('#')[0];
118
+
119
+ /** Restores one entry. The caller has already taken it off the stack. */
120
+ async function undoEntry(entry: UndoEntry, input: ExecuteInput, now: number): Promise<ActionResult> {
82
121
  try {
83
122
  const item = await input.seam.load(entry.itemId);
84
123
  if (!item) return { status: 'asked', spoken: `${shortTitle(entry.title)} is gone, so I could not undo that.`, itemId: entry.itemId };
@@ -93,11 +132,29 @@ async function undoOne(log: ActionLog, input: ExecuteInput, now: number): Promis
93
132
  }
94
133
  return { status: 'applied', spoken: undoText(entry, now, input.timeZone), itemId: entry.itemId };
95
134
  } catch (error) {
96
- log.stack.push(entry); // nothing changed: it can be tried again
97
135
  return { status: 'failed', spoken: `I could not undo that: ${error instanceof Error ? error.message : 'the change did not go through'}.`, itemId: entry.itemId, reason: reasonOf(error) };
98
136
  }
99
137
  }
100
138
 
139
+ /** "Undo" reverts the last reply: every change made under the same client action id, newest first. */
140
+ async function undoLast(log: ActionLog, input: ExecuteInput, now: number): Promise<ActionResult> {
141
+ const top = log.stack[log.stack.length - 1];
142
+ if (!top) return { status: 'asked', spoken: 'There is nothing to undo.' };
143
+ const group = groupOf(top);
144
+ const entries: UndoEntry[] = [];
145
+ // Popped either way: an entry that cannot be restored must not block the ones under it.
146
+ while (log.stack.length && groupOf(log.stack[log.stack.length - 1]) === group) entries.push(log.stack.pop() as UndoEntry);
147
+ const results: ActionResult[] = [];
148
+ for (const entry of entries) {
149
+ const r = await undoEntry(entry, input, now);
150
+ if (r.status === 'failed') log.stack.push(entry); // nothing changed: it can be tried again
151
+ results.push(r);
152
+ }
153
+ if (results.length === 1) return results[0];
154
+ if (results.every((r) => r.status === 'applied')) return { status: 'applied', spoken: `Undid all ${speakCount(results.length)} changes.` };
155
+ return { status: results.some((r) => r.status === 'failed') ? 'failed' : 'asked', spoken: results.map((r) => r.spoken).join(' ') };
156
+ }
157
+
101
158
  export async function executeVoiceActions(input: ExecuteInput): Promise<ExecuteOutcome> {
102
159
  const now = (input.now ?? Date.now)();
103
160
  const today = localDate(now, input.timeZone);
@@ -115,7 +172,7 @@ export async function executeVoiceActions(input: ExecuteInput): Promise<ExecuteO
115
172
  let result: ActionResult;
116
173
  if (action.type === 'clarify') result = { status: 'asked', spoken: action.question };
117
174
  else if (action.type === 'none') result = { status: 'asked', spoken: 'Sorry, I did not catch that. Can you say that again?' };
118
- else if (action.type === 'undo') result = await undoOne(log, input, now);
175
+ else if (action.type === 'undo') result = await undoLast(log, input, now);
119
176
  else if (action.type === 'add_item') {
120
177
  try {
121
178
  const created = await input.seam.create({ title: action.title, ownerSub: input.ownerSub, dueAt: action.dueDate });
@@ -125,17 +182,20 @@ export async function executeVoiceActions(input: ExecuteInput): Promise<ExecuteO
125
182
  result = { status: 'failed', spoken: `I could not add ${shortTitle(action.title)}.`, reason: reasonOf(error) };
126
183
  }
127
184
  } else {
128
- const patch = patchFor(action, today, nowIso) as ItemPatch;
129
185
  let title = 'that item';
130
186
  try {
131
187
  const item = await input.seam.load(action.itemId);
132
188
  if (!item) result = { status: 'failed', spoken: 'I could not find that item.', itemId: action.itemId };
133
189
  else {
134
190
  title = item.title;
135
- const before = snapshot(item, patch);
136
- await input.seam.update(item, patch);
137
- pushUndo(log, { actionId: key, kind: 'edit', itemId: item.id, title: item.title, before, after: patch, at: nowIso });
138
- result = { status: 'applied', spoken: confirmText(action, item.title, now, input.timeZone), itemId: item.id };
191
+ const plan = await planFor(action, item, today, nowIso, input.seam);
192
+ if ('ask' in plan) result = { status: 'asked', spoken: plan.ask, itemId: item.id };
193
+ else {
194
+ const before = snapshot(item, plan.patch);
195
+ await input.seam.update(item, plan.patch);
196
+ pushUndo(log, { actionId: key, kind: 'edit', itemId: item.id, title: item.title, before, after: plan.patch, at: nowIso });
197
+ result = { status: 'applied', spoken: confirmText(plan.action, item.title, now, input.timeZone), itemId: item.id };
198
+ }
139
199
  }
140
200
  } catch (error) {
141
201
  result = { status: 'failed', spoken: `I could not update ${shortTitle(title)}.`, itemId: action.itemId, reason: reasonOf(error) };
@@ -42,7 +42,7 @@ export function createEntityActionLog(http: LogHttp, ownerSub: string): ActionLo
42
42
  });
43
43
  const hit = (page.results ?? []).find((r) => (r.external_id ?? (r as { externalId?: string }).externalId) === externalId && mine(r));
44
44
  const stored = ((hit?.data ?? {}) as Record<string, unknown>).action_log as Partial<ActionLog> | undefined;
45
- return stored ? { applied: stored.applied ?? {}, order: stored.order ?? [], stack: stored.stack ?? [], pending: stored.pending ?? [] } : emptyLog();
45
+ return stored ? { applied: stored.applied ?? {}, order: stored.order ?? [], stack: stored.stack ?? [], pending: stored.pending ?? [], ...(stored.skips ? { skips: stored.skips } : {}) } : emptyLog();
46
46
  },
47
47
  async save(log) {
48
48
  await http.post('api/v1/entities/upsert', {
@@ -2,14 +2,17 @@
2
2
  import type { CorpusHttp } from '../../client';
3
3
  import { isRecord, notFound } from '../../client';
4
4
  import { toCommitment } from '../../entities';
5
+ import { listFocusChoices } from '../../filing';
5
6
  import type { Commitment, CommitmentApi, CorpusScope } from '../../types';
6
7
  import type { EditableItem, ItemEditSeam } from './types';
7
8
 
8
9
  export function commitmentEditSeam(options: {
9
- api: Pick<CommitmentApi, 'updateCommitment' | 'createCommitment'>;
10
+ api: Pick<CommitmentApi, 'updateCommitment' | 'createCommitment'> & Partial<Pick<CommitmentApi, 'fileCommitment'>>;
10
11
  http: Pick<CorpusHttp, 'get'>;
11
12
  scope: CorpusScope;
12
13
  entitiesPath?: string;
14
+ /** The projects an item can be filed under. Default: every focus the tenant has. */
15
+ listFocuses?: () => Promise<Array<{ id: string; title: string }>>;
13
16
  }): ItemEditSeam {
14
17
  const { api, http, scope } = options;
15
18
  const entities = options.entitiesPath ?? 'api/v1/entities';
@@ -19,6 +22,8 @@ export function commitmentEditSeam(options: {
19
22
  id: c.id, externalId: c.externalId, title: c.title, status: c.status, dueAt: c.dueAt ?? null,
20
23
  ...(c.priority !== undefined ? { priority: c.priority } : {}),
21
24
  resolvedAt: c.resolvedAt ?? null, ...(c.statusReason ? { statusReason: c.statusReason } : {}),
25
+ ...(c.detail ? { detail: c.detail } : {}), ...(c.estimateMinutes !== undefined ? { estimateMinutes: c.estimateMinutes } : {}),
26
+ focusId: c.focusId ?? null,
22
27
  };
23
28
  raw.set(item, c);
24
29
  return item;
@@ -38,8 +43,19 @@ export function commitmentEditSeam(options: {
38
43
  if (!api.updateCommitment) throw new Error('This client cannot edit items.');
39
44
  const row = raw.get(item) ?? ({ id: item.id, externalId: item.externalId } as Commitment);
40
45
  if (!row.externalId) throw new Error('This item has no stable identity to edit.');
41
- return wrap(await api.updateCommitment(row, patch as never));
46
+ const { focusId, estimateMinutes, ...fields } = patch;
47
+ let current = item;
48
+ if (Object.keys(fields).length || estimateMinutes !== undefined) {
49
+ current = wrap(await api.updateCommitment(row, { ...fields, ...(estimateMinutes !== undefined ? { estimateMinutes } : {}) } as never));
50
+ }
51
+ if (focusId !== undefined) {
52
+ if (!api.fileCommitment) throw new Error('This client cannot change projects.');
53
+ await api.fileCommitment(row, focusId);
54
+ current = { ...current, focusId };
55
+ }
56
+ return current;
42
57
  },
58
+ listFocuses: options.listFocuses ?? (() => listFocusChoices(http as CorpusHttp, { entities })),
43
59
  async create(draft) {
44
60
  if (!api.createCommitment) throw new Error('This client cannot add items.');
45
61
  return wrap(await api.createCommitment({
@@ -19,6 +19,10 @@ export interface EditableItem {
19
19
  resolvedAt?: string | null;
20
20
  statusReason?: string;
21
21
  externalId?: string;
22
+ detail?: string;
23
+ estimateMinutes?: number;
24
+ focusId?: string | null;
25
+ focusName?: string;
22
26
  }
23
27
 
24
28
  /** The fields a voice reply changes. `null` clears (due date, priority, resolved time). */
@@ -28,6 +32,12 @@ export interface ItemPatch {
28
32
  dueAt?: string | null;
29
33
  priority?: number | null;
30
34
  resolvedAt?: string | null;
35
+ title?: string;
36
+ detail?: string;
37
+ /** Minutes; `null` clears it. */
38
+ estimateMinutes?: number | null;
39
+ /** The project's id; `null` takes the item out of its project. Written as an edge, not a field. */
40
+ focusId?: string | null;
31
41
  }
32
42
 
33
43
  export interface ItemDraft {
@@ -40,6 +50,8 @@ export interface ItemEditSeam {
40
50
  load(id: string): Promise<EditableItem | null>;
41
51
  update(item: EditableItem, patch: ItemPatch): Promise<EditableItem>;
42
52
  create(draft: ItemDraft): Promise<EditableItem>;
53
+ /** The projects an item can be filed under. Absent: this seam cannot change projects. */
54
+ listFocuses?(): Promise<Array<{ id: string; title: string }>>;
43
55
  }
44
56
 
45
57
  export type ActionStatus = 'applied' | 'failed' | 'asked';
@@ -89,6 +101,8 @@ export interface ActionLog {
89
101
  stack: UndoEntry[];
90
102
  /** The latest replies understood, newest last (see `PendingReply`). */
91
103
  pending?: PendingReply[];
104
+ /** What he skipped in a briefing today (by his local date): the next briefing does not bring it back. */
105
+ skips?: { date: string; keys: string[] };
92
106
  }
93
107
 
94
108
  export interface ActionLogStore {
@@ -1,6 +1,6 @@
1
1
  /** One line saying what was understood, shown BEFORE anything is applied. */
2
2
  import { localDate } from '../../today';
3
- import { speakable } from '../speak';
3
+ import { speakable, spokenMinutes } from '../speak';
4
4
  import { spokenWhen } from './dates';
5
5
  import type { IntentContext, VoiceAction } from './types';
6
6
 
@@ -18,6 +18,10 @@ export function describeActions(actions: VoiceAction[], ctx: IntentContext): str
18
18
  case 'drop': return `Drop ${name(a.itemId)}`;
19
19
  case 'set_priority': return `Make ${name(a.itemId)} ${PRIORITY_NAMES[a.priority] ?? 'priority ' + a.priority}`;
20
20
  case 'add_item': return `Add ${a.title}${a.dueDate ? ` for ${spokenWhen(a.dueDate, today)}` : ''}`;
21
+ case 'rename': return `Rename ${name(a.itemId)} to ${speakable(a.title, 10)}`;
22
+ case 'add_detail': return `Add a note to ${name(a.itemId)}`;
23
+ case 'set_estimate': return a.minutes === null ? `Clear the estimate on ${name(a.itemId)}` : `Set ${name(a.itemId)} to ${spokenMinutes(a.minutes)}`;
24
+ case 'set_project': return a.project === null ? `Take ${name(a.itemId)} out of its project` : `Move ${name(a.itemId)} to ${speakable(a.project, 6)}`;
21
25
  case 'undo': return 'Undo the last change';
22
26
  case 'clarify': return a.question;
23
27
  default: return '';
@@ -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