@startsimpli/integrations 0.2.131 → 0.2.133
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 +4 -4
- package/src/__tests__/connectable-entries.test.tsx +45 -0
- package/src/__tests__/connections.test.tsx +5 -1
- package/src/__tests__/fixtures/voice-quinn-notes.ts +72 -0
- package/src/__tests__/spoken-time.test.ts +128 -0
- package/src/__tests__/voice-due-eval.test.ts +80 -0
- package/src/__tests__/voice-due.test.ts +219 -0
- package/src/components/pages/ConnectionsPage.tsx +2 -1
- package/src/components/pages/connectable-entries.ts +19 -0
- package/src/corpus/commitments.ts +13 -1
- package/src/corpus/entities.ts +8 -0
- package/src/corpus/extract.ts +20 -1
- package/src/corpus/extraction-fields.ts +118 -0
- package/src/corpus/index.ts +8 -0
- package/src/corpus/llm.ts +16 -3
- package/src/corpus/spoken-time.ts +336 -0
- package/src/corpus/types.ts +13 -0
- package/src/corpus/voice-due.ts +222 -0
- package/src/corpus/voice-manage.ts +8 -1
- package/src/corpus/voice-sections.ts +40 -2
- package/src/corpus/voice.ts +48 -2
- package/src/native/recording/__tests__/notes.test.ts +2 -1
- package/src/native/recording/notes.ts +3 -1
- package/src/native/voice/__tests__/sections.test.ts +12 -0
- package/src/native/voice/sections.ts +3 -0
package/src/corpus/types.ts
CHANGED
|
@@ -693,6 +693,12 @@ export interface Commitment {
|
|
|
693
693
|
* unreviewed rows in the middle of a list somebody is trying to triage.
|
|
694
694
|
*/
|
|
695
695
|
priority?: number;
|
|
696
|
+
/** Minutes in total, when a length of time was spoken (voice notes). */
|
|
697
|
+
estimateMinutes?: number;
|
|
698
|
+
/** Why `dueAt` is what it is: what was said, or the plan it was assumed from. */
|
|
699
|
+
dueBasis?: string;
|
|
700
|
+
/** 0..1 */
|
|
701
|
+
dueConfidence?: number;
|
|
696
702
|
/**
|
|
697
703
|
* Which focus this item is filed under, when it is filed at all.
|
|
698
704
|
*
|
|
@@ -764,6 +770,13 @@ export interface CommitmentDraft {
|
|
|
764
770
|
ownerName?: string;
|
|
765
771
|
subject?: string;
|
|
766
772
|
dueAt?: string | null;
|
|
773
|
+
/** 0 critical .. 4 lowest; only when the source signalled it. */
|
|
774
|
+
priority?: number;
|
|
775
|
+
/** Minutes, in total, when a length of time was spoken. */
|
|
776
|
+
estimateMinutes?: number;
|
|
777
|
+
/** Why this due date (what was said, or which plan it was assumed from). */
|
|
778
|
+
dueBasis?: string;
|
|
779
|
+
dueConfidence?: number;
|
|
767
780
|
quote: string;
|
|
768
781
|
extractor: 'rules' | 'model';
|
|
769
782
|
/** The project of the voice-note section this bullet sits in, when that section is filed. */
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DUE DATES, PRIORITY, ESTIMATE AND PROJECT FOR A VOICE NOTE'S ITEMS
|
|
3
|
+
* (bd startsim-b7kir).
|
|
4
|
+
*
|
|
5
|
+
* The model reports WHAT the speaker said about time (`when`: "today", "by
|
|
6
|
+
* Friday") and this file turns it into dates, because date arithmetic belongs in
|
|
7
|
+
* code (./spoken-time). It also works with NO model help at all: when the model
|
|
8
|
+
* gave nothing, the item's own words, the sentence it came from, the section
|
|
9
|
+
* and finally a note-wide "this is my plan for the day" are tried in that order.
|
|
10
|
+
*
|
|
11
|
+
* Specific beats general, and "sometime" blocks every general rule above it: an
|
|
12
|
+
* item the speaker left open stays unscheduled rather than being swept into
|
|
13
|
+
* today. Every field comes out as a guess (./extraction-fields) with a
|
|
14
|
+
* confidence, a reason and its alternatives, and only the genuinely ambiguous
|
|
15
|
+
* ones carry a question.
|
|
16
|
+
*/
|
|
17
|
+
import {
|
|
18
|
+
AMBIGUITY_GAP, guessOf, unknownGuess,
|
|
19
|
+
} from './extraction-fields';
|
|
20
|
+
import type { FieldGuess, ItemFields } from './extraction-fields';
|
|
21
|
+
import { noteWideWhen, resolveSpokenTime } from './spoken-time';
|
|
22
|
+
import type { SpokenTime } from './spoken-time';
|
|
23
|
+
import type { VoiceItem, VoiceSection } from './voice-sections';
|
|
24
|
+
|
|
25
|
+
export interface DueContext {
|
|
26
|
+
/** When the note was recorded, ms. */
|
|
27
|
+
now: number;
|
|
28
|
+
/** The speaker's IANA zone. */
|
|
29
|
+
timeZone: string;
|
|
30
|
+
transcript: string;
|
|
31
|
+
/** Time words for the whole note, if the model gave any. */
|
|
32
|
+
noteWhen?: string;
|
|
33
|
+
/** Titles of the offered projects by id, to tell a named project from a guessed one. */
|
|
34
|
+
focusTitles?: Record<string, string>;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** One item with everything known about it: what the later question step reads. */
|
|
38
|
+
export interface VoiceItemRecord {
|
|
39
|
+
section: string;
|
|
40
|
+
title: string;
|
|
41
|
+
owner?: string;
|
|
42
|
+
fields: ItemFields;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// ---------------------------------------------------------------------------
|
|
46
|
+
// the sentence an item came from
|
|
47
|
+
// ---------------------------------------------------------------------------
|
|
48
|
+
|
|
49
|
+
const STOP = new Set(['with', 'that', 'this', 'from', 'have', 'need', 'into', 'then', 'them', 'they', 'what', 'when', 'will', 'your', 'some', 'more', 'also']);
|
|
50
|
+
const stem = (w: string) => w.toLowerCase().replace(/[^a-z0-9]/g, '').slice(0, 5);
|
|
51
|
+
|
|
52
|
+
/** The sentence of the transcript that shares most of the item's content words, if it shares enough to trust. */
|
|
53
|
+
export function evidenceSentence(title: string, transcript: string): string | null {
|
|
54
|
+
const words = [...new Set(title.split(/\s+/).map(stem).filter((w) => w.length >= 4 && !STOP.has(w)))];
|
|
55
|
+
if (words.length < 2) return null;
|
|
56
|
+
let best: { text: string; score: number; hits: number } | null = null;
|
|
57
|
+
for (const text of transcript.split(/(?<=[.!?])\s+/)) {
|
|
58
|
+
const have = new Set(text.split(/\s+/).map(stem));
|
|
59
|
+
const hits = words.filter((w) => have.has(w)).length;
|
|
60
|
+
const score = hits / words.length;
|
|
61
|
+
if (hits >= 2 && score >= 0.5 && (!best || score > best.score)) best = { text, score, hits };
|
|
62
|
+
}
|
|
63
|
+
return best?.text ?? null;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// ---------------------------------------------------------------------------
|
|
67
|
+
// estimate
|
|
68
|
+
// ---------------------------------------------------------------------------
|
|
69
|
+
|
|
70
|
+
const COUNTS: Record<string, number> = { two: 2, three: 3, four: 4, '2': 2, '3': 3, '4': 4 };
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Minutes for the item, in TOTAL: "two sessions of 15 minutes" is 30. The speaker called them two separate
|
|
74
|
+
* tasks, but the tracker merges near-identical titles into one row (verified: "(1 of 2)" / "(2 of 2)" and
|
|
75
|
+
* "Spend 15 minutes" / "Spend another 15 minutes" all collapse), so they stay one item until dedupe can
|
|
76
|
+
* tell sessions apart (bead filed).
|
|
77
|
+
*/
|
|
78
|
+
export function spokenMinutes(text: string): number | null {
|
|
79
|
+
let m = /\b(two|three|four|2|3|4)\s+(?:[a-z-]+\s+){0,2}?(?:of\s+)?(\d+)[- ]?(?:minute|min)/i.exec(text);
|
|
80
|
+
if (m) return COUNTS[m[1].toLowerCase()] * Number(m[2]);
|
|
81
|
+
if ((m = /\b(\d+)[- ]?(?:minute|min)/i.exec(text))) return Number(m[1]);
|
|
82
|
+
if (/\bhalf an hour\b|\bhalf-hour\b/i.test(text)) return 30;
|
|
83
|
+
if ((m = /\b(\d+(?:\.\d+)?)[- ]hours?\b/i.exec(text))) return Math.round(Number(m[1]) * 60);
|
|
84
|
+
if (/\b(?:an|one) hour\b/i.test(text)) return 60;
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// ---------------------------------------------------------------------------
|
|
89
|
+
// project
|
|
90
|
+
// ---------------------------------------------------------------------------
|
|
91
|
+
|
|
92
|
+
const HEDGE = /\b(?:i guess|i think|maybe|not sure|sort of|kind of|i suppose)\b/i;
|
|
93
|
+
|
|
94
|
+
function projectGuess(section: VoiceSection, ctx: DueContext): FieldGuess<string> {
|
|
95
|
+
const label = section.label;
|
|
96
|
+
const at = ctx.transcript.toLowerCase().indexOf(label.toLowerCase());
|
|
97
|
+
const near = at >= 0 ? ctx.transcript.slice(at, at + 220) : '';
|
|
98
|
+
if (section.kind === 'personal' || section.kind === 'other' || !section.focusId) {
|
|
99
|
+
// "Quinn AI … is a personal effort, personal work, I guess, still under work": both readings are live.
|
|
100
|
+
if (near && /\bpersonal\b/i.test(near) && /\bwork\b/i.test(near) && HEDGE.test(near)) {
|
|
101
|
+
return guessOf('personal', 0.5, 'assumed', `"${label}" was called personal and work in the same breath`, {
|
|
102
|
+
candidates: [
|
|
103
|
+
{ value: 'personal', confidence: 0.5, reason: 'called it a personal effort' },
|
|
104
|
+
{ value: 'work', confidence: 0.45, reason: 'said it is still under work' },
|
|
105
|
+
],
|
|
106
|
+
question: `Is "${label}" personal or work?`,
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
if (section.kind === 'personal') return guessOf('personal', 0.85, 'stated', 'the section was introduced as personal');
|
|
110
|
+
return unknownGuess(section.kind === 'other' ? 'work that matches none of the projects' : 'no project matched');
|
|
111
|
+
}
|
|
112
|
+
const title = ctx.focusTitles?.[section.focusId];
|
|
113
|
+
const named = title ? ctx.transcript.toLowerCase().includes(title.toLowerCase()) : false;
|
|
114
|
+
return named
|
|
115
|
+
? guessOf(section.focusId, 0.9, 'stated', `the project "${title}" was named`)
|
|
116
|
+
: guessOf(section.focusId, 0.75, 'assumed', `placed under "${title ?? label}" by topic`);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// ---------------------------------------------------------------------------
|
|
120
|
+
// due
|
|
121
|
+
// ---------------------------------------------------------------------------
|
|
122
|
+
|
|
123
|
+
function fmtCandidate(c: { date: string; time?: string }): string {
|
|
124
|
+
return c.time ? `${c.date} ${c.time}` : c.date;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function dueGuess(item: VoiceItem, section: VoiceSection, ctx: DueContext): { due: FieldGuess<string>; priority?: number } {
|
|
128
|
+
const resolve = (text: string | undefined) => (text ? resolveSpokenTime(text, ctx) : null);
|
|
129
|
+
const sentence = evidenceSentence(item.title, ctx.transcript);
|
|
130
|
+
// The model over-applies "sometime" (it put it on all six items of a section after hearing it once, about
|
|
131
|
+
// one). Leaving an item open is a claim about THIS item, so it needs "sometime" in the item's own words or
|
|
132
|
+
// the sentence it came from.
|
|
133
|
+
const modelWhen = resolve(item.when);
|
|
134
|
+
const ownWords = (sentence ? resolve(sentence) : null) ?? resolve(item.title);
|
|
135
|
+
const heardOpen = ownWords?.kind === 'unscheduled';
|
|
136
|
+
const itemLevel = modelWhen?.kind === 'unscheduled' && !heardOpen ? null : modelWhen;
|
|
137
|
+
|
|
138
|
+
// Most specific first. Each level is [text, how it counts, source].
|
|
139
|
+
const levels: Array<{ res: SpokenTime | null; source: 'stated' | 'assumed'; cap: number; where: string }> = [
|
|
140
|
+
{ res: itemLevel, source: 'stated', cap: 1, where: 'the speaker' },
|
|
141
|
+
{ res: resolve(item.title), source: 'stated', cap: 1, where: 'the item' },
|
|
142
|
+
{ res: sentence ? resolve(sentence) : null, source: 'stated', cap: 0.9, where: 'the sentence it came from' },
|
|
143
|
+
{ res: resolve(section.when), source: 'assumed', cap: 0.75, where: 'the section' },
|
|
144
|
+
{ res: resolve(ctx.noteWhen), source: 'assumed', cap: 0.75, where: 'the note' },
|
|
145
|
+
{ res: noteWideWhen(ctx.transcript, ctx), source: 'assumed', cap: 0.6, where: 'the plan for the day' },
|
|
146
|
+
];
|
|
147
|
+
|
|
148
|
+
for (const level of levels) {
|
|
149
|
+
const res = level.res;
|
|
150
|
+
if (!res) continue;
|
|
151
|
+
if (res.kind === 'unscheduled') {
|
|
152
|
+
// Only the speaker's words about THIS item can leave it open. A model that wrote "sometime" on a
|
|
153
|
+
// whole section (it did, for "sometime in the next few hours") must not undate every item in it.
|
|
154
|
+
if (level.source === 'assumed') continue;
|
|
155
|
+
return { due: { ...unknownGuess<string>(`said "${res.phrase}": left open on purpose`), source: 'stated', confidence: res.score }, priority: res.priority };
|
|
156
|
+
}
|
|
157
|
+
const confidence = Math.min(res.score, level.cap);
|
|
158
|
+
const display = res.time ? `${res.date} ${res.time} ${ctx.timeZone}` : res.date;
|
|
159
|
+
const reason = level.source === 'assumed' ? `${level.where === 'the plan for the day' ? 'the plan for the day' : `${res.phrase} (${level.where})`}` : res.reason;
|
|
160
|
+
const candidates = res.candidates.map((c) => ({ value: c.dueAt, confidence: c.score, reason: c.reason }));
|
|
161
|
+
const gap = res.candidates.length > 1 ? res.candidates[0].score - res.candidates[1].score : 1;
|
|
162
|
+
const question = gap < AMBIGUITY_GAP
|
|
163
|
+
? `Due ${fmtCandidate(res.candidates[0])} or ${fmtCandidate(res.candidates[1])}?`
|
|
164
|
+
: undefined;
|
|
165
|
+
return {
|
|
166
|
+
due: guessOf(res.dueAt as string, confidence, level.source, reason, { candidates, question, display }),
|
|
167
|
+
priority: res.priority,
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
return { due: unknownGuess('nothing was said about when') };
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// ---------------------------------------------------------------------------
|
|
174
|
+
// an item, and a note
|
|
175
|
+
// ---------------------------------------------------------------------------
|
|
176
|
+
|
|
177
|
+
export function resolveItemFields(item: VoiceItem, section: VoiceSection, ctx: DueContext): ItemFields {
|
|
178
|
+
const { due, priority: spokenPriority } = dueGuess(item, section, ctx);
|
|
179
|
+
const sentence = evidenceSentence(item.title, ctx.transcript);
|
|
180
|
+
|
|
181
|
+
const priority: FieldGuess<number> = item.priority !== undefined
|
|
182
|
+
? guessOf(item.priority, 0.8, 'stated', 'the speaker signalled how important it is')
|
|
183
|
+
: spokenPriority !== undefined
|
|
184
|
+
? guessOf(spokenPriority, 0.8, 'stated', 'said it is urgent')
|
|
185
|
+
: unknownGuess('no priority was signalled');
|
|
186
|
+
|
|
187
|
+
const minutes = item.estimateMinutes ?? spokenMinutes(item.title) ?? (sentence ? spokenMinutes(sentence) : null);
|
|
188
|
+
const estimate: FieldGuess<number> = minutes
|
|
189
|
+
? guessOf(minutes, item.estimateMinutes ? 0.8 : 0.9, 'stated', 'a length of time was spoken')
|
|
190
|
+
: unknownGuess('no length of time was said');
|
|
191
|
+
|
|
192
|
+
const owner: FieldGuess<string> = item.owner
|
|
193
|
+
? guessOf(item.owner, ctx.transcript.toLowerCase().includes(item.owner.toLowerCase()) ? 0.9 : 0.6, ctx.transcript.toLowerCase().includes(item.owner.toLowerCase()) ? 'stated' : 'assumed', 'a person was named for it')
|
|
194
|
+
: unknownGuess('nobody else was named, so it is the speaker\'s');
|
|
195
|
+
|
|
196
|
+
return { due, priority, estimate, owner, project: projectGuess(section, ctx) };
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
export interface DueResult {
|
|
200
|
+
sections: VoiceSection[];
|
|
201
|
+
records: VoiceItemRecord[];
|
|
202
|
+
/** Distinct genuine questions across the note. */
|
|
203
|
+
flagged: number;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export function resolveSectionFields(sections: VoiceSection[], ctx: DueContext): DueResult {
|
|
207
|
+
const records: VoiceItemRecord[] = [];
|
|
208
|
+
const asked = new Set<string>();
|
|
209
|
+
const out = sections.map((section) => ({
|
|
210
|
+
...section,
|
|
211
|
+
items: section.items.map((item) => {
|
|
212
|
+
const fields = resolveItemFields(item, section, ctx);
|
|
213
|
+
// One question per thing asked: a section's "personal or work?" is one question, not one per to-do.
|
|
214
|
+
for (const [name, f] of Object.entries(fields)) {
|
|
215
|
+
if (f.question) asked.add(name === 'project' ? `${section.label}|${f.question}` : `${section.label}|${item.title}|${f.question}`);
|
|
216
|
+
}
|
|
217
|
+
records.push({ section: section.label, title: item.title, ...(item.owner ? { owner: item.owner } : {}), fields });
|
|
218
|
+
return { ...item, fields };
|
|
219
|
+
}),
|
|
220
|
+
}));
|
|
221
|
+
return { sections: out, records, flagged: asked.size };
|
|
222
|
+
}
|
|
@@ -146,7 +146,13 @@ export async function retryVoiceNote(
|
|
|
146
146
|
error: '',
|
|
147
147
|
}));
|
|
148
148
|
const started: StartedVoiceNote = { id: String(owned.entity.id), noteId, audioRef: owned.audioRef };
|
|
149
|
-
const
|
|
149
|
+
const row = (owned.entity.data ?? {}) as Record<string, unknown>;
|
|
150
|
+
const timeZone = typeof (row.voice_time_zone ?? row.voiceTimeZone) === 'string' ? String(row.voice_time_zone ?? row.voiceTimeZone) : undefined;
|
|
151
|
+
const submission = {
|
|
152
|
+
noteId, audio, mimeType: mimeType || owned.audioMime || 'audio/webm', durationMs: owned.note.durationMs,
|
|
153
|
+
...(timeZone ? { timeZone } : {}),
|
|
154
|
+
...(owned.note.occurredAt ? { recordedAt: owned.note.occurredAt } : {}),
|
|
155
|
+
};
|
|
150
156
|
return { started, finish: () => finishVoiceNote(started, submission, deps) };
|
|
151
157
|
}
|
|
152
158
|
|
|
@@ -231,6 +237,7 @@ export function createVoiceServerClient(options: {
|
|
|
231
237
|
const body = new FormData();
|
|
232
238
|
body.append('audio', audio, 'voice-note');
|
|
233
239
|
body.append('durationMs', String(durationMs));
|
|
240
|
+
body.append('timeZone', Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC');
|
|
234
241
|
return (await (await call('', { method: 'POST', body }, 'Saving the recording failed')).json()) as { id: string };
|
|
235
242
|
},
|
|
236
243
|
async retry(noteId) {
|
|
@@ -22,12 +22,22 @@
|
|
|
22
22
|
* person picks a project — no focus is ever created automatically.
|
|
23
23
|
*/
|
|
24
24
|
|
|
25
|
+
import { itemMetaLine } from './extraction-fields';
|
|
26
|
+
|
|
25
27
|
export type VoiceSectionKind = 'project' | 'personal' | 'other';
|
|
26
28
|
|
|
27
29
|
export interface VoiceItem {
|
|
28
30
|
title: string;
|
|
29
31
|
/** Only when the speaker named who will do it. */
|
|
30
32
|
owner?: string;
|
|
33
|
+
/** The time words the speaker used for THIS item, quoted ("today", "by Friday"). Resolved to a date in code, never by the model. */
|
|
34
|
+
when?: string;
|
|
35
|
+
/** 0 critical, 1 urgent, 2 normal, 3 low (the briefing's scale). Only when the speaker signalled it. */
|
|
36
|
+
priority?: number;
|
|
37
|
+
/** Minutes the speaker said it would take, in total. */
|
|
38
|
+
estimateMinutes?: number;
|
|
39
|
+
/** Set by `resolveItemFields` (./voice-due): what is known about each field, how sure, and what is still a question. */
|
|
40
|
+
fields?: import('./extraction-fields').ItemFields;
|
|
31
41
|
}
|
|
32
42
|
|
|
33
43
|
export interface VoiceSection {
|
|
@@ -36,6 +46,8 @@ export interface VoiceSection {
|
|
|
36
46
|
/** One of the offered focus ids, or null. */
|
|
37
47
|
focusId: string | null;
|
|
38
48
|
summary: string;
|
|
49
|
+
/** Time words that apply to the whole section ("these are for today"). */
|
|
50
|
+
when?: string;
|
|
39
51
|
items: VoiceItem[];
|
|
40
52
|
}
|
|
41
53
|
|
|
@@ -57,13 +69,35 @@ const oneLine = (value: unknown, prose = false): string => {
|
|
|
57
69
|
return (prose ? flat.replace(/^#+\s*/, '').replace(/\*\*/g, '') : flat.replace(/[#*]+/g, '')).trim();
|
|
58
70
|
};
|
|
59
71
|
|
|
72
|
+
const PRIORITY_WORDS: Array<[RegExp, number]> = [
|
|
73
|
+
[/^(?:critical|highest|p0)$/i, 0], [/^(?:urgent|high|p1|important)$/i, 1],
|
|
74
|
+
[/^(?:normal|medium|regular|p2)$/i, 2], [/^(?:low|minor|p3)$/i, 3],
|
|
75
|
+
];
|
|
76
|
+
|
|
77
|
+
/** The model may say 1, "1", "high" or null. Anything else is no priority. */
|
|
78
|
+
export function parsePriority(raw: unknown): number | undefined {
|
|
79
|
+
if (typeof raw === 'number' && Number.isInteger(raw) && raw >= 0 && raw <= 4) return raw;
|
|
80
|
+
if (typeof raw !== 'string') return undefined;
|
|
81
|
+
if (/^[0-4]$/.test(raw.trim())) return Number(raw.trim());
|
|
82
|
+
return PRIORITY_WORDS.find(([re]) => re.test(raw.trim()))?.[1];
|
|
83
|
+
}
|
|
84
|
+
|
|
60
85
|
/** A model-written value is data: it must not be able to open a heading or close a bold. */
|
|
61
86
|
function cleanItem(raw: unknown): VoiceItem | null {
|
|
62
87
|
const row = (raw && typeof raw === 'object' ? raw : { title: raw }) as Record<string, unknown>;
|
|
63
88
|
const title = oneLine(row.title).replace(/^[-–—\s]+/, '');
|
|
64
89
|
if (!title) return null;
|
|
65
90
|
const owner = oneLine(row.owner).replace(/[()]/g, '').trim();
|
|
66
|
-
|
|
91
|
+
const when = oneLine(row.when ?? row.dueText).slice(0, 80);
|
|
92
|
+
const priority = parsePriority(row.priority);
|
|
93
|
+
const minutes = Number(row.estimateMinutes ?? row.estimate_minutes);
|
|
94
|
+
return {
|
|
95
|
+
title,
|
|
96
|
+
...(owner ? { owner } : {}),
|
|
97
|
+
...(when && !/^(?:null|none|n\/a|unknown)$/i.test(when) ? { when } : {}),
|
|
98
|
+
...(priority !== undefined ? { priority } : {}),
|
|
99
|
+
...(Number.isFinite(minutes) && minutes > 0 && minutes <= 24 * 60 ? { estimateMinutes: Math.round(minutes) } : {}),
|
|
100
|
+
};
|
|
67
101
|
}
|
|
68
102
|
|
|
69
103
|
/** Shape-check the model's `sections`. An id that was not offered becomes null; the section stays. */
|
|
@@ -85,6 +119,7 @@ export function parseSections(raw: unknown, offered: Set<string>): VoiceSection[
|
|
|
85
119
|
kind,
|
|
86
120
|
focusId: typeof rawFocus === 'string' && offered.has(rawFocus) ? rawFocus : null,
|
|
87
121
|
summary: oneLine(row.summary, true),
|
|
122
|
+
...(oneLine(row.when).slice(0, 80) ? { when: oneLine(row.when).slice(0, 80) } : {}),
|
|
88
123
|
items: (Array.isArray(row.items) ? row.items : []).map(cleanItem).filter((i): i is VoiceItem => i !== null),
|
|
89
124
|
});
|
|
90
125
|
}
|
|
@@ -97,7 +132,10 @@ export function renderSectionsSummary(overall: string, sections: VoiceSection[])
|
|
|
97
132
|
`## ${s.label}`,
|
|
98
133
|
...(s.summary ? [s.summary] : []),
|
|
99
134
|
...(s.items.length ? [''] : []),
|
|
100
|
-
...s.items.
|
|
135
|
+
...s.items.flatMap((i) => {
|
|
136
|
+
const meta = i.fields ? itemMetaLine(i.fields) : '';
|
|
137
|
+
return [`- **${i.title}**${i.owner ? ` (${i.owner})` : ''}`, ...(meta ? [meta] : [])];
|
|
138
|
+
}),
|
|
101
139
|
].join('\n'));
|
|
102
140
|
return [overall.trim(), ...blocks].filter(Boolean).join('\n\n');
|
|
103
141
|
}
|
package/src/corpus/voice.ts
CHANGED
|
@@ -37,6 +37,10 @@ import { withSourceEntity } from './source-entity';
|
|
|
37
37
|
import type { VoiceNotesPage, VoiceNotesQuery } from './voice-query';
|
|
38
38
|
import type { FilingMove } from './voice-refile';
|
|
39
39
|
import type { SectionFiling, VoiceSection } from './voice-sections';
|
|
40
|
+
import { renderSectionsSummary } from './voice-sections';
|
|
41
|
+
import { resolveSectionFields } from './voice-due';
|
|
42
|
+
import { isTimeZone } from './spoken-time';
|
|
43
|
+
import type { VoiceItemRecord } from './voice-due';
|
|
40
44
|
import type { FocusChoice } from './filing';
|
|
41
45
|
|
|
42
46
|
export { ABOUT_FOCUS };
|
|
@@ -44,6 +48,10 @@ export type { FocusChoice };
|
|
|
44
48
|
export type { VoiceNotesPage, VoiceNotesQuery, VoiceNoteOrder } from './voice-query';
|
|
45
49
|
export type { SectionFiling, VoiceSection, VoiceItem, VoiceSectionKind } from './voice-sections';
|
|
46
50
|
|
|
51
|
+
/** The analyzer already stripped placeholder owners from the summary; the re-render must not bring them back. */
|
|
52
|
+
const stripPlaceholderOwnersOf = (summary: string): string =>
|
|
53
|
+
summary.replace(/\s*\((?:owner|name|person|someone|unknown|n\/a|none)\)/gi, '');
|
|
54
|
+
|
|
47
55
|
export const VOICE_SOURCE = 'voice';
|
|
48
56
|
export const VOICE_SOURCE_LABEL = 'Voice note';
|
|
49
57
|
export type VoiceStatus = 'processing' | 'ready' | 'failed';
|
|
@@ -64,6 +72,10 @@ export interface VoiceAnalysis {
|
|
|
64
72
|
focusId: string | null;
|
|
65
73
|
/** One entry per topic spoken (bd startsim-ij1lw.6). Absent on a single-topic / pre-sections analysis. */
|
|
66
74
|
sections?: VoiceSection[];
|
|
75
|
+
/** The one-sentence overall context the summary opens with (kept so the summary can be re-rendered). */
|
|
76
|
+
overall?: string;
|
|
77
|
+
/** Time words for the whole note, as the model heard them. Resolved in code, never trusted as a date. */
|
|
78
|
+
noteWhen?: string;
|
|
67
79
|
usage?: AnalysisUsage;
|
|
68
80
|
}
|
|
69
81
|
|
|
@@ -92,7 +104,8 @@ export interface VoiceUsage {
|
|
|
92
104
|
}
|
|
93
105
|
|
|
94
106
|
export interface VoiceAnalyzer {
|
|
95
|
-
|
|
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>;
|
|
96
109
|
}
|
|
97
110
|
|
|
98
111
|
export interface VoiceTranscriber {
|
|
@@ -136,6 +149,10 @@ export function voiceToEntity(input: {
|
|
|
136
149
|
usage?: VoiceUsage;
|
|
137
150
|
/** Where each section is filed. Kept as `voice_sections` — never `sections`, which the extractor reads as text. */
|
|
138
151
|
sections?: Array<{ label: string; kind: SectionFiling['kind']; focusId: string | null }>;
|
|
152
|
+
/** The speaker's zone, kept for retries. */
|
|
153
|
+
timeZone?: string;
|
|
154
|
+
/** What was known about each item (due, project, owner, priority, estimate: value, confidence, reason, candidates, question). */
|
|
155
|
+
items?: VoiceItemRecord[];
|
|
139
156
|
}): { entity_type: string; external_id: string; name: string; data: Record<string, unknown> } {
|
|
140
157
|
return {
|
|
141
158
|
entity_type: 'source_document',
|
|
@@ -156,6 +173,9 @@ export function voiceToEntity(input: {
|
|
|
156
173
|
...(input.error !== undefined ? { voice_error: input.error } : {}),
|
|
157
174
|
...(input.usage ? { voice_usage: usageToRow(input.usage) } : {}),
|
|
158
175
|
...(input.sections?.length ? { voice_sections: filingsToRow(input.sections) } : {}),
|
|
176
|
+
...(input.timeZone ? { voice_time_zone: input.timeZone } : {}),
|
|
177
|
+
// JSON in one string: the tenant's snake_case transform would rewrite nested keys.
|
|
178
|
+
...(input.items ? { voice_items: JSON.stringify(input.items) } : {}),
|
|
159
179
|
},
|
|
160
180
|
};
|
|
161
181
|
}
|
|
@@ -202,6 +222,10 @@ export interface VoiceSubmission {
|
|
|
202
222
|
audio: Uint8Array;
|
|
203
223
|
mimeType: string;
|
|
204
224
|
durationMs?: number;
|
|
225
|
+
/** The speaker's IANA zone ("America/Boise"): what "today" means. Kept on the row so a retry resolves the same day. */
|
|
226
|
+
timeZone?: string;
|
|
227
|
+
/** When it was recorded (ISO). Defaults to now; a retry passes the original. */
|
|
228
|
+
recordedAt?: string;
|
|
205
229
|
}
|
|
206
230
|
|
|
207
231
|
export interface StartedVoiceNote {
|
|
@@ -232,6 +256,7 @@ export async function startVoiceNote(
|
|
|
232
256
|
audioRef,
|
|
233
257
|
audioMime: submission.mimeType,
|
|
234
258
|
durationMs: submission.durationMs,
|
|
259
|
+
timeZone: isTimeZone(submission.timeZone) ? submission.timeZone : undefined,
|
|
235
260
|
}),
|
|
236
261
|
);
|
|
237
262
|
return { id: String(row.id), noteId: submission.noteId, audioRef };
|
|
@@ -295,13 +320,34 @@ export async function finishVoiceNote(
|
|
|
295
320
|
const transcript = outcome.text.trim();
|
|
296
321
|
if (!transcript) throw new Error('No speech was detected in the recording.');
|
|
297
322
|
|
|
298
|
-
const
|
|
323
|
+
const recordedAt = submission.recordedAt ? Date.parse(submission.recordedAt) : at.getTime();
|
|
324
|
+
const timeZone = isTimeZone(submission.timeZone) ? submission.timeZone : 'UTC';
|
|
325
|
+
const now = Number.isNaN(recordedAt) ? at.getTime() : recordedAt;
|
|
326
|
+
const heardAnalysis = await deps.analyzer.analyze({ transcript, focuses, now, timeZone });
|
|
327
|
+
// Dates are computed HERE from what was said, whatever the model did: its `when` words are
|
|
328
|
+
// resolved against the recording time and the speaker's zone, and a note-wide "plan for the
|
|
329
|
+
// day" fills the rest. The summary is re-rendered so each to-do carries its due date.
|
|
330
|
+
const resolved = heardAnalysis.sections?.length
|
|
331
|
+
? resolveSectionFields(heardAnalysis.sections, {
|
|
332
|
+
now, timeZone, transcript, noteWhen: heardAnalysis.noteWhen,
|
|
333
|
+
focusTitles: Object.fromEntries(focuses.map((f) => [f.id, f.title])),
|
|
334
|
+
})
|
|
335
|
+
: null;
|
|
336
|
+
const analysis = resolved
|
|
337
|
+
? {
|
|
338
|
+
...heardAnalysis,
|
|
339
|
+
sections: resolved.sections,
|
|
340
|
+
summary: stripPlaceholderOwnersOf(renderSectionsSummary(heardAnalysis.overall ?? heardAnalysis.summary.split(/\n\s*##/)[0], resolved.sections)),
|
|
341
|
+
}
|
|
342
|
+
: heardAnalysis;
|
|
299
343
|
const title = analysis.title || defaultVoiceTitle(at);
|
|
300
344
|
|
|
301
345
|
await deps.http.post('api/v1/entities/upsert', voiceToEntity({
|
|
302
346
|
noteId: started.noteId, title, status: 'ready', occurredAt: at.toISOString(),
|
|
303
347
|
body: transcript, summary: analysis.summary,
|
|
304
348
|
sections: analysis.sections,
|
|
349
|
+
timeZone,
|
|
350
|
+
items: resolved?.records,
|
|
305
351
|
usage: noteUsage(outcome, analysis.usage, submission.durationMs),
|
|
306
352
|
}));
|
|
307
353
|
// Filing is best-effort AFTER the note is already `ready`: a refused edge
|
|
@@ -13,7 +13,7 @@ function entity(id: number, data: Record<string, unknown>) {
|
|
|
13
13
|
describe('notes', () => {
|
|
14
14
|
it('posts multipart audio + durationMs + the client noteId to /corpus/voice', async () => {
|
|
15
15
|
const authorizedFetch = vi.fn().mockResolvedValue(json({ id: '9', noteId: 'abc' }, 202));
|
|
16
|
-
const notes = createNotes({ tandemUrl: 'http://tandem/', authorizedFetch });
|
|
16
|
+
const notes = createNotes({ tandemUrl: 'http://tandem/', authorizedFetch, timeZone: 'America/Boise' });
|
|
17
17
|
await notes.upload({ id: 'abc12345', uri: 'file:///d/a.m4a', durationMs: 3100 });
|
|
18
18
|
const [url, init] = authorizedFetch.mock.calls[0];
|
|
19
19
|
expect(url).toBe('http://tandem/corpus/voice');
|
|
@@ -23,6 +23,7 @@ describe('notes', () => {
|
|
|
23
23
|
expect(byName.audio).toMatchObject({ uri: 'file:///d/a.m4a', type: 'audio/mp4', name: 'note.m4a' });
|
|
24
24
|
expect(byName.durationMs.string).toBe('3100');
|
|
25
25
|
expect(byName.noteId.string).toBe('abc12345');
|
|
26
|
+
expect(byName.timeZone.string).toBe('America/Boise');
|
|
26
27
|
});
|
|
27
28
|
|
|
28
29
|
it('does not set Content-Type itself (the boundary is fetch\'s to add)', async () => {
|
|
@@ -9,7 +9,7 @@ export interface NoteFile {
|
|
|
9
9
|
type AuthorizedFetch = (url: string, init?: RequestInit) => Promise<Response>;
|
|
10
10
|
|
|
11
11
|
/** Send recordings to Tandem and read the latest back; the note logic is the shared corpus voice api. */
|
|
12
|
-
export function createNotes(deps: { tandemUrl: string; authorizedFetch: AuthorizedFetch; limit?: number; createForm?: () => FormData; filePart?: (uri: string) => Blob }) {
|
|
12
|
+
export function createNotes(deps: { tandemUrl: string; authorizedFetch: AuthorizedFetch; limit?: number; createForm?: () => FormData; filePart?: (uri: string) => Blob; timeZone?: string }) {
|
|
13
13
|
const base = deps.tandemUrl.replace(/\/+$/, '');
|
|
14
14
|
|
|
15
15
|
const http: CorpusHttp = {
|
|
@@ -38,6 +38,8 @@ export function createNotes(deps: { tandemUrl: string; authorizedFetch: Authoriz
|
|
|
38
38
|
else body.append('audio', { uri: file.uri, name: 'note.m4a', type: 'audio/mp4' } as unknown as Blob);
|
|
39
39
|
body.append('durationMs', String(file.durationMs));
|
|
40
40
|
body.append('noteId', file.id);
|
|
41
|
+
// What "today" means to the speaker: the note's due dates are computed in this zone.
|
|
42
|
+
body.append('timeZone', deps.timeZone ?? (Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC'));
|
|
41
43
|
const res = await deps.authorizedFetch(`${base}/corpus/voice`, { method: 'POST', body });
|
|
42
44
|
if (!res.ok) throw Object.assign(new Error(`Upload failed (${res.status})`), { status: res.status });
|
|
43
45
|
},
|
|
@@ -65,3 +65,15 @@ describe('noteSections', () => {
|
|
|
65
65
|
expect(noteLead({ ...base, summary: 'Lead.\n\n## Next Steps\n- **Do it**' })).toBe('');
|
|
66
66
|
});
|
|
67
67
|
});
|
|
68
|
+
|
|
69
|
+
describe('resolved due lines under a bullet (bd startsim-b7kir)', () => {
|
|
70
|
+
it('are data for the extractor and never leak into the section text', () => {
|
|
71
|
+
const summary = 'Lead.\n\n## Work\nOne line.\n\n- **Check the backend today**\n ↳ due 2026-11-06 · basis the plan for the day (assumed) · confidence 0.6 · est 15m\n- **Call the bank**';
|
|
72
|
+
const [section] = noteSections({ ...base, summary, focusId: null } as VoiceNote);
|
|
73
|
+
expect(section.items).toEqual(['Check the backend today', 'Call the bank']);
|
|
74
|
+
const labelled = noteSections({ ...base, summary, focusId: null, sections: [{ label: 'Work', kind: 'other', focusId: null }] } as never)[0];
|
|
75
|
+
expect(labelled.summary).not.toContain('↳');
|
|
76
|
+
expect(labelled.items).toEqual(['Check the backend today', 'Call the bank']);
|
|
77
|
+
expect(section.items).toHaveLength(2);
|
|
78
|
+
});
|
|
79
|
+
});
|
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
* them, an older note gets ONE section built from its single summary + project.
|
|
6
6
|
*/
|
|
7
7
|
import type { VoiceNote } from '../../corpus/voice';
|
|
8
|
+
import { META_LINE } from '../../corpus/extraction-fields';
|
|
8
9
|
|
|
9
10
|
export type SectionKind = 'project' | 'personal' | 'other';
|
|
10
11
|
|
|
@@ -59,6 +60,8 @@ function parseSummary(summary: string): { lead: string; blocks: SummaryBlock[] }
|
|
|
59
60
|
const blocks: SummaryBlock[] = [];
|
|
60
61
|
let cur: SummaryBlock | null = null;
|
|
61
62
|
for (const line of (summary ?? '').split('\n')) {
|
|
63
|
+
// The resolved due date under a bullet (` ↳ due …`) is data for the extractor, not prose for the section.
|
|
64
|
+
if (META_LINE.test(line)) continue;
|
|
62
65
|
const h = line.match(/^\s*#{1,6}\s+(.+?)\s*$/);
|
|
63
66
|
if (h) { cur = { heading: h[1], text: '', items: [] }; blocks.push(cur); continue; }
|
|
64
67
|
const b = line.match(BULLET);
|