@startsimpli/integrations 0.2.160 → 0.2.162

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@startsimpli/integrations",
3
- "version": "0.2.160",
3
+ "version": "0.2.162",
4
4
  "description": "Provider-agnostic types, API clients, hooks, and UI primitives for email + calendar integrations across StartSimpli apps, plus foundry customer email (subpath ./comms).",
5
5
  "license": "MIT",
6
6
  "homepage": "https://startsimpli.com",
@@ -51,8 +51,8 @@
51
51
  "@startsimpli/ui-native": ">=0.1.12",
52
52
  "react-native-safe-area-context": ">=4.0.0",
53
53
  "@startsimpli/ui": "^0.4.181",
54
- "@startsimpli/utils": "^0.4.18",
55
- "@startsimpli/auth": "^0.4.51"
54
+ "@startsimpli/auth": "^0.4.52",
55
+ "@startsimpli/utils": "^0.4.18"
56
56
  },
57
57
  "peerDependenciesMeta": {
58
58
  "react": {
@@ -101,7 +101,7 @@
101
101
  "@startsimpli/llm": "0.4.31",
102
102
  "@startsimpli/ui": "0.4.181",
103
103
  "@startsimpli/ui-native": "0.1.14",
104
- "@startsimpli/auth": "0.4.51",
104
+ "@startsimpli/auth": "0.4.52",
105
105
  "@startsimpli/utils": "0.4.18"
106
106
  },
107
107
  "scripts": {
@@ -477,6 +477,37 @@ describe('PlanningPage', () => {
477
477
  await waitFor(() => expect(screen.getByText('Nothing filed under this yet')).toBeTruthy());
478
478
  });
479
479
 
480
+ it('lists in-progress items under a focus, not only open ones', async () => {
481
+ render(
482
+ <PlanningPage
483
+ api={fakeApi({
484
+ focuses: [FOCUS],
485
+ items: [commitment({ externalId: 'commit:wip', title: 'Draft the term sheet', status: 'in_progress' })],
486
+ })}
487
+ scope={SCOPE}
488
+ now={NOW}
489
+ />,
490
+ );
491
+ await userEvent.click(await screen.findByRole('button', { name: /Close the Series A/ }));
492
+ expect(await screen.findByText('Draft the term sheet')).toBeTruthy();
493
+ });
494
+
495
+ it('opens a focus whose work is all finished on its closed items, asking for done and dropped', async () => {
496
+ const queries: Array<{ status?: unknown }> = [];
497
+ const done = commitment({ externalId: 'commit:old', title: 'Ship the pilot', status: 'done' });
498
+ const api = fakeApi({ focuses: [FOCUS], onList: (q) => queries.push(q as { status?: unknown }) });
499
+ api.listCommitments = async (query) => {
500
+ queries.push(query as { status?: unknown });
501
+ const wanted = Array.isArray(query.status) ? query.status : [query.status];
502
+ const results = wanted.includes('done') ? [done] : [];
503
+ return { count: results.length, next: null, previous: null, results, appliedFilters: ['status'] };
504
+ };
505
+ render(<PlanningPage api={api} scope={SCOPE} now={NOW} />);
506
+ await userEvent.click(await screen.findByRole('button', { name: /Close the Series A/ }));
507
+ expect(await screen.findByText('Ship the pilot')).toBeTruthy();
508
+ expect(queries.some((q) => Array.isArray(q.status) && q.status.includes('dropped'))).toBe(true);
509
+ });
510
+
480
511
  it('reports done over total from counts', async () => {
481
512
  render(
482
513
  <PlanningPage
@@ -0,0 +1,28 @@
1
+ /** Spoken notes with what a careful human would say each to-do's due date and project are (bd startsim-tmrvi.8). */
2
+ export const NOW = Date.parse('2026-11-09T15:00:00Z'); // Monday 10:00 in New York
3
+ export const TIME_ZONE = 'America/New_York';
4
+ export const FOCUSES = [
5
+ { id: 'f-mkt', title: 'Marketing' }, { id: 'f-eng', title: 'Engineering' }, { id: 'f-ops', title: 'Operations' },
6
+ ];
7
+ /** due: ISO day, or '' when nothing was said. project: a focus id, or '' when it is personal or unclear. */
8
+ export interface Truth { match: string; due: string; project: string }
9
+ export interface MeasuredNote { transcript: string; truth: Truth[] }
10
+
11
+ export const NOTES: MeasuredNote[] = [
12
+ { transcript: 'Okay quick brain dump. I need to call the vet by Friday. Also send the invoice to Sam for the website thing. And somebody has to fix the login bug soon. Oh, and buy a birthday present for my sister.',
13
+ truth: [{ match: 'vet', due: '2026-11-13', project: '' }, { match: 'invoice', due: '', project: '' }, { match: 'login', due: '', project: 'f-eng' }, { match: 'birthday', due: '', project: '' }] },
14
+ { transcript: 'Marketing stuff for this week. Draft the November newsletter by Wednesday. Book the photographer for the launch shoot, tomorrow. Review the ad budget with Priya on Thursday.',
15
+ truth: [{ match: 'newsletter', due: '2026-11-11', project: 'f-mkt' }, { match: 'photographer', due: '2026-11-10', project: 'f-mkt' }, { match: 'budget', due: '2026-11-12', project: 'f-mkt' }] },
16
+ { transcript: 'Engineering notes. The checkout page times out on mobile, that needs fixing today. Upgrade the database driver sometime next week. Write up the incident report from last night.',
17
+ truth: [{ match: 'checkout', due: '2026-11-09', project: 'f-eng' }, { match: 'driver', due: '', project: 'f-eng' }, { match: 'incident', due: '', project: 'f-eng' }] },
18
+ { transcript: 'Operations. Renew the office lease before the end of the month. Order new laptops for the two new hires. Schedule the fire drill for next Tuesday.',
19
+ truth: [{ match: 'lease', due: '2026-11-30', project: 'f-ops' }, { match: 'laptops', due: '', project: 'f-ops' }, { match: 'fire drill', due: '2026-11-17', project: 'f-ops' }] },
20
+ { transcript: 'Personal stuff. Pick up the dry cleaning tomorrow. Book a dentist appointment. Call mom on Sunday.',
21
+ truth: [{ match: 'dry cleaning', due: '2026-11-10', project: '' }, { match: 'dentist', due: '', project: '' }, { match: 'mom', due: '2026-11-15', project: '' }] },
22
+ { transcript: 'All of these are for Friday. Send the press release, finish the sales deck, and confirm the venue.',
23
+ truth: [{ match: 'press release', due: '2026-11-13', project: 'f-mkt' }, { match: 'deck', due: '2026-11-13', project: 'f-mkt' }, { match: 'venue', due: '2026-11-13', project: '' }] },
24
+ { transcript: 'Remind me to look into the pricing page experiment. Also the on-call rota needs updating, and we should ask legal about the vendor contract.',
25
+ truth: [{ match: 'pricing', due: '', project: 'f-mkt' }, { match: 'rota', due: '', project: 'f-eng' }, { match: 'contract', due: '', project: 'f-ops' }] },
26
+ { transcript: 'Today I have to merge the auth refactor, reply to the investor email, and pay the AWS bill. The AWS bill is due on the fifteenth.',
27
+ truth: [{ match: 'auth', due: '2026-11-09', project: 'f-eng' }, { match: 'investor', due: '2026-11-09', project: '' }, { match: 'aws', due: '2026-11-15', project: 'f-ops' }] },
28
+ ];
@@ -0,0 +1,51 @@
1
+ // @vitest-environment node
2
+ /**
3
+ * Real-model measurement of the clarifying-question loop (bd startsim-tmrvi.8). NOT a unit test: it calls a
4
+ * paid model, so it runs only with MEASURE_VOICE=1 and a key in the environment.
5
+ * MEASURE_VOICE=1 npx vitest run src/__tests__/measure
6
+ * It prints questions per note and how often a field Tandem acted on without asking was actually wrong.
7
+ */
8
+ import { describe, expect, it } from 'vitest';
9
+
10
+ import { createVoiceAnalyzer } from '../../corpus/llm';
11
+ import { resolveSectionFields } from '../../corpus/voice-due';
12
+ import { FOCUSES, NOTES, NOW, TIME_ZONE } from './notes';
13
+
14
+ const day = (v: unknown) => (v == null ? '' : String(v).slice(0, 10));
15
+
16
+ describe.skipIf(!process.env.MEASURE_VOICE)('voice notes with a real model', () => {
17
+ it('measures questions per note and wrong silent assumptions', async () => {
18
+ const analyzer = createVoiceAnalyzer();
19
+ const rows: string[] = [];
20
+ let questions = 0, items = 0, silent = 0, silentWrong = 0, askedFine = 0, askedTotal = 0, missing = 0, matched = 0;
21
+ for (const note of NOTES) {
22
+ const a = await analyzer.analyze({ transcript: note.transcript, focuses: FOCUSES, now: NOW, timeZone: TIME_ZONE });
23
+ const r = resolveSectionFields(a.sections ?? [], {
24
+ now: NOW, timeZone: TIME_ZONE, transcript: note.transcript, noteWhen: a.noteWhen,
25
+ focusTitles: Object.fromEntries(FOCUSES.map((f) => [f.id, f.title])),
26
+ });
27
+ questions += r.flagged;
28
+ for (const t of note.truth) {
29
+ const rec = r.records.find((x) => x.title.toLowerCase().includes(t.match));
30
+ if (!rec) { missing += 1; rows.push(` MISSING item "${t.match}"`); continue; }
31
+ matched += 1; items += 1;
32
+ for (const [name, want, got] of [['due', t.due, day(rec.fields.due.value)], ['project', t.project, String(rec.fields.project.value ?? '').replace(/^personal$/, '')] as const]) {
33
+ const g = rec.fields[name as 'due' | 'project'];
34
+ const asked = Boolean(g.question);
35
+ if (asked) { askedTotal += 1; if (got === want) askedFine += 1; continue; }
36
+ silent += 1;
37
+ if (got !== want) { silentWrong += 1; rows.push(` WRONG ${name} "${rec.title}": acted ${JSON.stringify(got)} wanted ${JSON.stringify(want)} (${g.source}: ${g.reason})`); }
38
+ }
39
+ }
40
+ }
41
+ const out = [
42
+ `notes=${NOTES.length} items matched=${matched} missing=${missing}`,
43
+ `questions per note=${(questions / NOTES.length).toFixed(2)} (${questions} total)`,
44
+ `silent field decisions=${silent}, wrong=${silentWrong} (${silent ? ((100 * silentWrong) / silent).toFixed(1) : 0}%)`,
45
+ `field questions asked=${askedTotal}, of which the guess was already right=${askedFine}`,
46
+ ...rows,
47
+ ].join('\n');
48
+ console.log(out);
49
+ expect(matched).toBeGreaterThan(0);
50
+ }, 600_000);
51
+ });
@@ -0,0 +1,82 @@
1
+
2
+ // @vitest-environment node
3
+ /** Resolving from the corpus before asking (bd startsim-tmrvi.2): other items, Linear, calendar. */
4
+ import { describe, expect, it } from 'vitest';
5
+
6
+ import { guessOf, unknownGuess } from '../corpus/extraction-fields';
7
+ import { listOpenQuestions, syncOpenQuestions } from '../corpus/questions';
8
+ import { decideFromCorpus } from '../corpus/questions/evidence';
9
+ import type { ItemView } from '../corpus/questions/types';
10
+ import { tenant } from './helpers/question-tenant';
11
+
12
+ const view = (id: string, title: string, over: Partial<ItemView> = {}): ItemView => ({
13
+ id, title, status: 'open', dueAt: null, focusId: '', ownerName: '', ownerSub: '', openKind: '', openText: '', ...over,
14
+ });
15
+ const me = view('me', 'Newsletter draft for November launch');
16
+
17
+ describe('decideFromCorpus', () => {
18
+ it('settles a project when two similar to-dos from other places already live there', () => {
19
+ const items = [me, view('a', 'Newsletter draft November', { focusId: 'mkt' }), view('b', 'Launch newsletter outline', { focusId: 'mkt', linearKey: 'MKT-4' })];
20
+ const hit = decideFromCorpus({ kind: 'project', item: me, assumed: { value: 'mkt' } }, { items, events: [] });
21
+ expect(hit).toMatchObject({ agrees: true, source: 'linear' });
22
+ expect(hit?.evidence).toContain('MKT-4');
23
+ });
24
+ it('asks when one similar item lives elsewhere, or there is only one', () => {
25
+ const a = view('a', 'Newsletter draft November', { focusId: 'mkt' });
26
+ const b = view('b', 'Launch newsletter outline', { focusId: 'ops' });
27
+ expect(decideFromCorpus({ kind: 'project', item: me, assumed: { value: 'mkt' } }, { items: [me, a, b], events: [] })).toBeNull();
28
+ expect(decideFromCorpus({ kind: 'project', item: me, assumed: { value: 'mkt' } }, { items: [me, a], events: [] })).toBeNull();
29
+ });
30
+ it('one shared word is not similar', () => {
31
+ const items = [me, view('a', 'Newsletter budget', { focusId: 'mkt' }), view('b', 'Newsletter vendors', { focusId: 'mkt' })];
32
+ expect(decideFromCorpus({ kind: 'project', item: me, assumed: { value: 'mkt' } }, { items, events: [] })).toBeNull();
33
+ });
34
+ it('settles a due date from a calendar event that day, never a different day', () => {
35
+ const ev = [{ title: 'Newsletter send', date: '2026-11-20' }];
36
+ expect(decideFromCorpus({ kind: 'due_date', item: me, assumed: { value: '2026-11-20' } }, { items: [me], events: ev })).toMatchObject({ source: 'calendar' });
37
+ expect(decideFromCorpus({ kind: 'due_date', item: me, assumed: { value: '2026-11-21' } }, { items: [me], events: ev })).toBeNull();
38
+ });
39
+ it('settles a due date from a similar Linear issue due that day', () => {
40
+ const lin = view('l', 'Newsletter draft November copy', { linearKey: 'MKT-9', dueAt: '2026-11-18' });
41
+ expect(decideFromCorpus({ kind: 'due_date', item: me, assumed: { value: '2026-11-18' } }, { items: [me, lin], events: [] })).toMatchObject({ source: 'linear' });
42
+ expect(decideFromCorpus({ kind: 'due_date', item: me, assumed: { value: '2026-11-19' } }, { items: [me, lin], events: [] })).toBeNull();
43
+ });
44
+ });
45
+
46
+ const item = (id: string, data: Record<string, unknown>) => ({
47
+ id, entity_type: 'commitment', external_id: `commit:${id}`, name: String(data.title),
48
+ data: { status: 'open', mentions: [{ document_id: 'note1', quote: 'q' }], ...data },
49
+ });
50
+ describe('sync uses corpus evidence', () => {
51
+ it('does not ask, and records the evidence found', async () => {
52
+ const fields = { due: unknownGuess('x'), project: guessOf('mkt', 0.4, 'assumed', 'r', { question: 'Which project?' }), owner: unknownGuess('x'), priority: unknownGuess('x'), estimate: unknownGuess('x') };
53
+ const t = tenant([
54
+ item('a', { title: 'Newsletter draft November', external_focus_id: 'mkt' }),
55
+ item('b', { title: 'Launch newsletter outline', external_focus_id: 'mkt' }),
56
+ item('c', { title: 'Newsletter draft for November launch', external_focus_id: 'mkt' }),
57
+ { id: 'note1', entity_type: 'source_document', external_id: 'voice:n1', name: 'n', data: { source: 'voice', title: 'n', voice_items: JSON.stringify([{ section: 's', title: 'Newsletter draft for November launch', fields }]) } },
58
+ ]);
59
+ const deps = { http: t.http, scope: { orgId: 'o' } as never, ownerSub: 'me', now: () => Date.parse('2026-11-04T15:00:00Z'), timeZone: 'UTC' };
60
+ const counts = await syncOpenQuestions(deps);
61
+ expect(counts).toMatchObject({ opened: 0, decidedByContext: 1 });
62
+ const all = await listOpenQuestions(deps, { status: 'all' });
63
+ expect(all[0]).toMatchObject({ resolution: 'context' });
64
+ expect(all[0]?.answer?.label).toMatch(/^found: 2 similar/);
65
+ });
66
+ });
67
+
68
+ import { habitHints } from '../corpus/questions/learn';
69
+ import { renderVoicePrompt } from '../corpus/llm';
70
+
71
+ describe('habits as extraction hints', () => {
72
+ const pref = (key: string, value: string, count = 2, conflicts = 0) => ({ kind: 'project_word' as const, key, value, count, conflicts });
73
+ it('hints only confident habits for projects that still exist', () => {
74
+ const lines = habitHints([pref('newsletter', 'f-mkt'), pref('invoice', 'f-ops', 1), pref('rota', 'gone')], [{ id: 'f-mkt', title: 'Marketing' }, { id: 'f-ops', title: 'Operations' }]);
75
+ expect(lines).toEqual(['- to-dos about newsletter usually go to f-mkt (Marketing)']);
76
+ });
77
+ it('shows them to the model as a hint, and not at all when there are none', () => {
78
+ const base = { transcript: 'hi', focuses: [{ id: 'f-mkt', title: 'Marketing' }] };
79
+ expect(renderVoicePrompt({ ...base, habits: ['- to-dos about newsletter usually go to f-mkt (Marketing)'] })).toContain('HABITS');
80
+ expect(renderVoicePrompt(base)).not.toContain('HABITS');
81
+ });
82
+ });
@@ -148,6 +148,24 @@ describe('answerQuestionByVoice', () => {
148
148
  expect(await listOpenQuestions(deps)).toHaveLength(1);
149
149
  });
150
150
 
151
+ it('undo puts a project back and reopens the question', async () => {
152
+ const rows = [
153
+ item('deck', { title: 'Finish the deck', external_focus_id: 'f-mkt' }),
154
+ note([{ section: 's', title: 'Finish the deck', fields: fields({
155
+ project: guessOf('f-mkt', 0.5, 'assumed', 'by topic', { question: 'Which project is the deck for?' }),
156
+ }) }]),
157
+ ];
158
+ const { t, deps } = setup(rows, { options: async (q) => (q.kind === 'project' ? [{ value: 'f-mkt', label: 'Marketing' }, { value: 'f-eng', label: 'Engineering' }] : []) });
159
+ await syncOpenQuestions(deps);
160
+ await say(deps, 'engineering');
161
+ expect(t.rows.get('deck')!.data.external_focus_id).toBe('f-eng');
162
+ const out = await say(deps, 'undo that');
163
+ expect(out.kind).toBe('undone');
164
+ expect(t.rows.get('deck')!.data.external_focus_id).toBe('f-mkt');
165
+ expect(deps.fileItem).toHaveBeenLastCalledWith('deck', 'f-mkt');
166
+ expect(await listOpenQuestions(deps)).toHaveLength(1);
167
+ });
168
+
151
169
  it('says plainly when an answer cannot be undone by voice', async () => {
152
170
  const { deps } = setup([held('bench', "Order dad's bench")]);
153
171
  await syncOpenQuestions(deps);
@@ -158,6 +158,7 @@ export function PlanningPage({
158
158
  const [applied, setApplied] = React.useState<string[]>([]);
159
159
  const [members, setMembers] = React.useState<Array<{ sub: string; email: string; name?: string }>>([]);
160
160
  const [showDone, setShowDone] = React.useState(false);
161
+ const triedClosed = React.useRef<Record<string, boolean>>({});
161
162
  const [owner, setOwner] = React.useState('');
162
163
  const [loadingFocuses, setLoadingFocuses] = React.useState(true);
163
164
  const [loadingItems, setLoadingItems] = React.useState(false);
@@ -211,7 +212,7 @@ export function PlanningPage({
211
212
  // -- items ---------------------------------------------------------------
212
213
 
213
214
  const itemQuery = React.useMemo<CommitmentQuery>(() => ({
214
- status: showDone ? 'done' : (['open', 'in_progress', 'blocked'] as CommitmentStatus[]),
215
+ status: showDone ? (['done', 'dropped'] as CommitmentStatus[]) : (['open', 'in_progress', 'blocked'] as CommitmentStatus[]),
215
216
  ...(owner.trim() ? { owner: owner.trim() } : {}),
216
217
  ...(selected ? { focus: selected } : {}),
217
218
  // Each row names its project, and filing is an edge the entity row lacks.
@@ -234,6 +235,15 @@ export function PlanningPage({
234
235
  return () => { live = false; };
235
236
  }, [itemQuery, scope.orgId, epoch]);
236
237
 
238
+ // A project whose work is all finished (an imported tracker's history) would open on
239
+ // "Nothing is filed under this focus yet". Show the closed items once instead.
240
+ React.useEffect(() => {
241
+ if (!selected || loadingItems || showDone || items.length > 0) return;
242
+ if (triedClosed.current[selected]) return;
243
+ triedClosed.current[selected] = true;
244
+ setShowDone(true);
245
+ }, [selected, loadingItems, showDone, items.length]);
246
+
237
247
  React.useEffect(() => {
238
248
  let live = true;
239
249
  if (!api.listMembers) return undefined;
@@ -254,7 +264,7 @@ export function PlanningPage({
254
264
  const visible = React.useMemo(() => {
255
265
  const wanted = showDone
256
266
  ? (item: Commitment) => item.status === 'done' || item.status === 'dropped'
257
- : (item: Commitment) => item.status === 'open' || item.status === 'blocked';
267
+ : (item: Commitment) => item.status === 'open' || item.status === 'in_progress' || item.status === 'blocked';
258
268
  const byOwner = owner.trim().toLowerCase();
259
269
  return items
260
270
  .filter(wanted)
@@ -373,7 +383,7 @@ export function PlanningPage({
373
383
  <div className={cn.root}>
374
384
  <section className={cn.section} aria-label="Focus">
375
385
  <div className="flex flex-wrap items-center gap-2">
376
- <button type="button" className={cn.secondaryButton} onClick={() => setSelected(null)}>
386
+ <button type="button" className={cn.secondaryButton} onClick={() => { setSelected(null); setShowDone(false); }}>
377
387
  ← All focuses
378
388
  </button>
379
389
  {warningChip}
@@ -383,7 +393,7 @@ export function PlanningPage({
383
393
  standing={standings[selectedFocus.id] ?? null}
384
394
  selected
385
395
  classNames={cn}
386
- onSelect={() => setSelected(null)}
396
+ onSelect={() => { setSelected(null); setShowDone(false); }}
387
397
  />
388
398
  <FocusProgressHistory focus={selectedFocus} api={api} />
389
399
  {error ? <p className={cn.error} role="alert">{error}</p> : null}
package/src/corpus/llm.ts CHANGED
@@ -570,7 +570,7 @@ function freshNonce(): string {
570
570
  }
571
571
 
572
572
  export function renderVoicePrompt(
573
- input: { transcript: string; focuses: FocusChoice[]; now?: number; timeZone?: string },
573
+ input: { transcript: string; focuses: FocusChoice[]; now?: number; timeZone?: string; habits?: string[] },
574
574
  nonce: () => string = freshNonce,
575
575
  ): string {
576
576
  const list = input.focuses.length
@@ -582,7 +582,8 @@ export function renderVoicePrompt(
582
582
  const code = nonce();
583
583
  if (input.transcript.includes(code)) continue;
584
584
  const recorded = input.now === undefined ? '' : `RECORDED_AT: ${recordedAtLine(input.now, input.timeZone || 'UTC')}\n\n`;
585
- return `${recorded}PROJECTS (focusId must be one of these ids, or null):\n${list}\n\nTRANSCRIPT:\n${untrustedDocument(input.transcript, code)}`;
585
+ const habits = input.habits?.length ? `HABITS (what this speaker has told us before; a hint for choosing focusId when the topic really matches, never a reason to guess):\n${input.habits.join('\n')}\n\n` : '';
586
+ return `${recorded}PROJECTS (focusId must be one of these ids, or null):\n${list}\n\n${habits}TRANSCRIPT:\n${untrustedDocument(input.transcript, code)}`;
586
587
  }
587
588
  throw new Error('Could not pick a delimiter that the transcript does not contain.');
588
589
  }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * RESOLVE FROM THE CORPUS BEFORE ASKING (bd startsim-tmrvi.2).
3
+ *
4
+ * Habits (learn.ts) come from the person's own past answers. This is the other half: evidence already in
5
+ * the workspace. Other to-dos from other notes, Linear issues (to-dos that carry a Linear key) and calendar
6
+ * events say where similar work lives and when things happen. Like a habit, evidence can only CONFIRM the
7
+ * guess Tandem is already acting on, never change it; any similar item pointing elsewhere keeps the
8
+ * question open. Pure: callers read the rows, this decides and says why.
9
+ */
10
+ import { contentWords } from '../briefing/intent/match';
11
+ import type { EvidenceEvent } from './items';
12
+ import type { ItemView, QuestionKind } from './types';
13
+
14
+ const day = (v: string | null | undefined) => (v ? String(v).slice(0, 10) : '');
15
+ const long = (title: string) => [...new Set(contentWords(title).filter((w) => w.length >= 4))];
16
+
17
+ /** How many words two titles share. */
18
+ function shared(a: string[], b: string[]): string[] {
19
+ const set = new Set(b);
20
+ return a.filter((w) => set.has(w));
21
+ }
22
+
23
+ const label = (i: ItemView) => (i.linearKey ? `Linear ${i.linearKey}` : `"${i.title}"`);
24
+
25
+ /** Similar = at least two content words in common (one word is too loose to act on). */
26
+ function similarTo(item: ItemView, others: ItemView[]): ItemView[] {
27
+ const words = long(item.title);
28
+ if (words.length === 0) return [];
29
+ return others.filter((o) => o.id !== item.id && shared(words, long(o.title)).length >= 2);
30
+ }
31
+
32
+ export interface ContextHit { agrees: true; evidence: string; source: 'items' | 'linear' | 'calendar' }
33
+
34
+ export function decideFromCorpus(
35
+ input: { kind: QuestionKind; item: ItemView; assumed?: { value: string | null } },
36
+ corpus: { items: ItemView[]; events: EvidenceEvent[] },
37
+ ): ContextHit | null {
38
+ const assumed = input.assumed?.value;
39
+ if (!assumed) return null;
40
+ const { item } = input;
41
+
42
+ if (input.kind === 'project') {
43
+ const like = similarTo(item, corpus.items).filter((o) => o.focusId);
44
+ if (like.length < 2) return null;
45
+ if (like.some((o) => o.focusId !== assumed)) return null; // a similar item lives elsewhere: ask
46
+ const linear = like.some((o) => o.linearKey);
47
+ return {
48
+ agrees: true, source: linear ? 'linear' : 'items',
49
+ evidence: `${like.length} similar to-dos (${like.slice(0, 2).map(label).join(', ')}) are in the same project`,
50
+ };
51
+ }
52
+
53
+ if (input.kind === 'due_date') {
54
+ const target = day(assumed);
55
+ if (!target) return null;
56
+ const words = long(item.title);
57
+ const event = corpus.events.find((e) => e.date === target && shared(words, long(e.title)).length >= 1);
58
+ if (event) return { agrees: true, source: 'calendar', evidence: `calendar: "${event.title}" on ${target}` };
59
+ const linked = similarTo(item, corpus.items).filter((o) => o.linearKey && o.dueAt);
60
+ if (linked.length > 0 && linked.every((o) => day(o.dueAt) === target)) {
61
+ return { agrees: true, source: 'linear', evidence: `${label(linked[0] as ItemView)} is due ${target}` };
62
+ }
63
+ }
64
+ return null;
65
+ }
@@ -21,7 +21,10 @@ export { composeCheckIn } from './checkin';
21
21
  export type { CheckIn, CheckInEntry, CheckInOptions } from './checkin';
22
22
  export { buildCheckIn } from './checkin-handle';
23
23
  export type { CheckInResult } from './checkin-handle';
24
- export { createPreferenceStore, learnFromAnswer, nextEvidence, decideFromHabits, PREFERENCE_ATTRIBUTES, PREFERENCE_LABEL, PREFERENCE_TYPE } from './learn';
24
+ export { decideFromCorpus } from './evidence';
25
+ export type { ContextHit } from './evidence';
26
+ export type { EvidenceEvent } from './items';
27
+ export { createPreferenceStore, learnFromAnswer, nextEvidence, decideFromHabits, habitHints, PREFERENCE_ATTRIBUTES, PREFERENCE_LABEL, PREFERENCE_TYPE } from './learn';
25
28
  export type { Preference, PreferenceKind } from './learn';
26
29
  export { applyAnswerToItem, assumedLabel, chipsFor, formatAnswerValue, readTypedAnswer } from './inbox';
27
30
  export type { AnswerChip, AnswerableItem, ChipContext, TypedAnswer } from './inbox';
@@ -9,6 +9,26 @@ const PAGE_SIZE = 200;
9
9
  const MAX_PAGES = 100;
10
10
  const str = (v: unknown): string => (typeof v === 'string' ? v : '');
11
11
 
12
+ /** A dated calendar entry; read tolerantly because tenants model them under different keys. */
13
+ export interface EvidenceEvent { title: string; date: string }
14
+ export const CALENDAR_EVENT_TYPE = 'calendar_event';
15
+
16
+ export async function readEvidenceEvents(http: CorpusHttp, entitiesPath: string, type = CALENDAR_EVENT_TYPE): Promise<EvidenceEvent[]> {
17
+ const out: EvidenceEvent[] = [];
18
+ for (let page = 1; page <= 20; page += 1) {
19
+ const res = await http.get<{ results?: TenantEntity[]; next?: string | null }>(entitiesPath, { params: { type, page, page_size: PAGE_SIZE } });
20
+ const rows = res.results ?? [];
21
+ for (const row of rows) {
22
+ const d = (row.data ?? {}) as Record<string, unknown>;
23
+ const date = str(d.start ?? d.starts_at ?? d.startsAt ?? d.date ?? d.start_date).slice(0, 10);
24
+ const title = str(d.title ?? d.summary ?? d.name ?? row.name);
25
+ if (date && title) out.push({ title, date });
26
+ }
27
+ if (!res.next || rows.length === 0) break;
28
+ }
29
+ return out;
30
+ }
31
+
12
32
  export async function readItemViews(http: CorpusHttp, scope: CorpusScope, entitiesPath: string): Promise<ItemView[]> {
13
33
  const out: ItemView[] = [];
14
34
  for (let page = 1; page <= MAX_PAGES; page += 1) {
@@ -24,6 +44,7 @@ export async function readItemViews(http: CorpusHttp, scope: CorpusScope, entiti
24
44
  id: c.id, title: c.title, status: c.status, dueAt: c.dueAt ?? null,
25
45
  focusId: str(d.external_focus_id ?? d.externalFocusId), ownerName: c.ownerName ?? '', ownerSub: c.ownerSub ?? '',
26
46
  ...(noteId ? { noteId } : {}),
47
+ ...(c.sync?.key ? { linearKey: c.sync.key } : {}),
27
48
  openKind: str(d.open_question_kind ?? d.openQuestionKind),
28
49
  openText: str(d.open_question ?? d.openQuestion),
29
50
  });
@@ -133,3 +133,19 @@ export function decideFromHabits(
133
133
  }
134
134
  return null;
135
135
  }
136
+
137
+ /**
138
+ * Project habits as hints for the extraction prompt (bd startsim-tmrvi.18). Only confident ones, only for
139
+ * projects that still exist, and only as a hint: the model still chooses by what the section is about, and
140
+ * a habit never makes a project "stated".
141
+ */
142
+ export function habitHints(prefs: Preference[], focuses: Array<{ id: string; title: string }>): string[] {
143
+ const byId = new Map(focuses.map((f) => [f.id, f.title]));
144
+ const grouped = new Map<string, string[]>();
145
+ for (const p of prefs) {
146
+ if (p.kind !== 'project_word' || !confidentIn(prefs, 'project_word', p.key)) continue;
147
+ if (!byId.has(p.value)) continue;
148
+ grouped.set(p.value, [...(grouped.get(p.value) ?? []), p.key]);
149
+ }
150
+ return [...grouped].slice(0, 10).map(([id, words]) => `- to-dos about ${words.slice(0, 8).join(', ')} usually go to ${id} (${byId.get(id)})`);
151
+ }
@@ -5,7 +5,8 @@
5
5
  import type { CorpusHttp } from '../client';
6
6
  import type { CorpusScope } from '../types';
7
7
  import { CLOSED_STATUSES, deriveQuestions, scoreOf } from './derive';
8
- import { readItemViews, readVoiceRecords } from './items';
8
+ import { decideFromCorpus } from './evidence';
9
+ import { readEvidenceEvents, readItemViews, readVoiceRecords } from './items';
9
10
  import { createPreferenceStore, decideFromHabits } from './learn';
10
11
  import { createQuestionStore } from './store';
11
12
  import type { ItemView, OpenQuestion, QuestionResolution } from './types';
@@ -40,6 +41,7 @@ export async function syncOpenQuestions(deps: QuestionDeps): Promise<{ opened: n
40
41
  const existing = new Map((await store.all()).map((q) => [key(q.itemId, q.kind), q]));
41
42
 
42
43
  const prefs = await createPreferenceStore(deps).all().catch(() => []);
44
+ const events = await readEvidenceEvents(deps.http, path).catch(() => []);
43
45
  let opened = 0, resolved = 0, expired = 0, decidedByContext = 0;
44
46
  const wanted = new Set<string>();
45
47
 
@@ -56,11 +58,13 @@ export async function syncOpenQuestions(deps: QuestionDeps): Promise<{ opened: n
56
58
  };
57
59
  if (!have && d.assumed) {
58
60
  // Context first: a learned habit that agrees with the guess settles it, and the row says why.
59
- const hit = decideFromHabits({ kind: d.kind, title: byId.get(d.itemId)?.title ?? '', assumed: d.assumed }, prefs, (deps.now ?? Date.now)(), deps.timeZone ?? 'UTC');
61
+ const item = byId.get(d.itemId);
62
+ const hit = decideFromHabits({ kind: d.kind, title: item?.title ?? '', assumed: d.assumed }, prefs, (deps.now ?? Date.now)(), deps.timeZone ?? 'UTC')
63
+ ?? (item ? decideFromCorpus({ kind: d.kind, item, assumed: d.assumed }, { items, events }) : null);
60
64
  if (hit) {
61
65
  await store.put(d.itemId, d.kind, d.question, {
62
66
  ...body, status: 'resolved', resolution: 'context', resolved_at: iso(), created_at: iso(), updated_at: iso(),
63
- answer: JSON.stringify({ value: d.assumed.value ?? '', label: `learned: ${hit.evidence}` }),
67
+ answer: JSON.stringify({ value: d.assumed.value ?? '', label: `${'source' in hit ? 'found' : 'learned'}: ${hit.evidence}` }),
64
68
  });
65
69
  decidedByContext += 1;
66
70
  continue;
@@ -62,7 +62,7 @@ export interface QuestionAnswer {
62
62
  /** Set when the answer was spoken: the press that gave it, so a repeat press does nothing twice. */
63
63
  via?: string;
64
64
  /** What the item held before, so a spoken "undo" can put it back. */
65
- prior?: { dueAt?: string | null };
65
+ prior?: { dueAt?: string | null; focusId?: string | null; ownerSub?: string; ownerName?: string };
66
66
  }
67
67
 
68
68
  /** What the queue needs to know about an item (from its commitment row). */
@@ -75,6 +75,8 @@ export interface ItemView {
75
75
  ownerName: string;
76
76
  ownerSub: string;
77
77
  noteId?: string;
78
+ /** The Linear issue key when the item is synced to one. */
79
+ linearKey?: string;
78
80
  openKind: string;
79
81
  openText: string;
80
82
  }
@@ -15,6 +15,7 @@ import type { BriefingAudio, BriefingSynthesize } from '../briefing/generate';
15
15
  import { speakDatesIn, speakable } from '../briefing/speak';
16
16
  import { localDate } from '../today';
17
17
  import { answerQuestion, type AnswerDeps } from './answer';
18
+ import { readItemViews } from './items';
18
19
  import { close, listOpenQuestions, storeFor } from './sync';
19
20
  import type { OpenQuestion, QuestionAnswer } from './types';
20
21
  import { parseSpokenAnswer, type AnswerOption } from './voice-parse';
@@ -112,12 +113,19 @@ async function undoLast(deps: VoiceAnswerDeps, now: number): Promise<{ text: str
112
113
  .filter((q) => q.resolution === 'answered' && q.answer?.via && q.resolvedAt && now - Date.parse(q.resolvedAt) <= UNDO_WINDOW_MS)
113
114
  .sort((a, b) => (b.resolvedAt ?? '').localeCompare(a.resolvedAt ?? ''))[0];
114
115
  if (!last) return { text: 'There is nothing to undo.', question: null };
115
- if (last.kind !== 'due_date' || !last.answer?.prior) {
116
+ const prior = last.answer?.prior;
117
+ // A team answer also released the item to the tracker, so it cannot be quietly taken back.
118
+ if (!prior || !['due_date', 'project', 'ownership'].includes(last.kind)) {
116
119
  return { text: 'I cannot undo that one by voice. You can change it on the item.', question: last };
117
120
  }
118
121
  const item = await deps.seam.load(last.itemId);
119
122
  if (!item) return { text: 'That item is gone, so there is nothing to put back.', question: last };
120
- await deps.seam.update(item, { dueAt: last.answer.prior.dueAt ?? null });
123
+ if (last.kind === 'due_date') await deps.seam.update(item, { dueAt: prior.dueAt ?? null });
124
+ else if (last.kind === 'project') {
125
+ if (!deps.fileItem) return { text: 'I cannot undo that one by voice. You can change it on the item.', question: last };
126
+ await deps.fileItem(last.itemId, prior.focusId ?? null);
127
+ await deps.patchItem(last.itemId, { external_focus_id: prior.focusId ?? '' });
128
+ } else await deps.patchItem(last.itemId, { owner_sub: prior.ownerSub ?? '', owner_name: prior.ownerName ?? '' });
121
129
  const at = new Date(now).toISOString();
122
130
  const reopened = await storeFor(deps).put(last.itemId, last.kind, last.question, {
123
131
  status: 'open', resolution: '', resolved_at: '', answer: '', updated_at: at,
@@ -222,6 +230,17 @@ export async function answerQuestionByVoice(deps: VoiceAnswerDeps, req: VoiceAns
222
230
 
223
231
  /** Apply the answer, remembering what a due date was so "undo" can put it back. */
224
232
  async function applyAnswer(deps: VoiceAnswerDeps, q: OpenQuestion, answer: QuestionAnswer): Promise<OpenQuestion> {
225
- const prior = q.kind === 'due_date' ? await deps.seam.load(q.itemId).catch(() => null) : null;
226
- return answerQuestion(deps, q.id, prior ? { ...answer, prior: { dueAt: prior.dueAt ?? null } } : answer);
233
+ const prior = await priorOf(deps, q);
234
+ return answerQuestion(deps, q.id, prior ? { ...answer, prior } : answer);
235
+ }
236
+
237
+ async function priorOf(deps: VoiceAnswerDeps, q: OpenQuestion): Promise<QuestionAnswer['prior'] | null> {
238
+ if (q.kind === 'due_date') {
239
+ const item = await deps.seam.load(q.itemId).catch(() => null);
240
+ return item ? { dueAt: item.dueAt ?? null } : null;
241
+ }
242
+ if (q.kind !== 'project' && q.kind !== 'ownership') return null;
243
+ const view = (await readItemViews(deps.http, deps.scope, deps.entitiesPath ?? 'api/v1/entities').catch(() => [])).find((i) => i.id === q.itemId);
244
+ if (!view) return null;
245
+ return q.kind === 'project' ? { focusId: view.focusId || null } : { ownerSub: view.ownerSub, ownerName: view.ownerName };
227
246
  }
@@ -105,7 +105,7 @@ export interface VoiceUsage {
105
105
 
106
106
  export interface VoiceAnalyzer {
107
107
  /** `now` is when the note was recorded and `timeZone` the speaker's: the model is shown them so "today" means something. */
108
- analyze(input: { transcript: string; focuses: FocusChoice[]; now?: number; timeZone?: string }): Promise<VoiceAnalysis>;
108
+ analyze(input: { transcript: string; focuses: FocusChoice[]; now?: number; timeZone?: string; habits?: string[] }): Promise<VoiceAnalysis>;
109
109
  }
110
110
 
111
111
  export interface VoiceTranscriber {
@@ -214,6 +214,8 @@ export interface VoiceDeps {
214
214
  analyzer: VoiceAnalyzer;
215
215
  store: VoiceAudioStore;
216
216
  listFocuses(): Promise<FocusChoice[]>;
217
+ /** Learned project habits as prompt hints (bd startsim-tmrvi.18); best effort. */
218
+ listHabits?(focuses: FocusChoice[]): Promise<string[]>;
217
219
  now?: () => Date;
218
220
  }
219
221
 
@@ -323,7 +325,8 @@ export async function finishVoiceNote(
323
325
  const recordedAt = submission.recordedAt ? Date.parse(submission.recordedAt) : at.getTime();
324
326
  const timeZone = isTimeZone(submission.timeZone) ? submission.timeZone : 'UTC';
325
327
  const now = Number.isNaN(recordedAt) ? at.getTime() : recordedAt;
326
- const heardAnalysis = await deps.analyzer.analyze({ transcript, focuses, now, timeZone });
328
+ const habits = deps.listHabits ? await deps.listHabits(focuses).catch(() => [] as string[]) : [];
329
+ const heardAnalysis = await deps.analyzer.analyze({ transcript, focuses, now, timeZone, ...(habits.length ? { habits } : {}) });
327
330
  // Dates are computed HERE from what was said, whatever the model did: its `when` words are
328
331
  // resolved against the recording time and the speaker's zone, and a note-wide "plan for the
329
332
  // day" fills the rest. The summary is re-rendered so each to-do carries its due date.