@startsimpli/integrations 0.2.158 → 0.2.160

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Tracked items as ANSWERABLE, CITABLE records (bd startsim-tmrvi).
3
+ *
4
+ * Ask used to retrieve documents only, so "what did I commit to this week" had no
5
+ * path to the item rows that actually hold status, due date, owner and Linear
6
+ * state. An item becomes a `SourceDocument` here (like a money event does) so the
7
+ * existing citation resolver traces the answer to the exact item record — the id
8
+ * is `item:<id>`, which can never collide with a document id.
9
+ */
10
+ import { itemIntent, type ItemIntent } from './ask-items-intent';
11
+ import { dueDay } from './today';
12
+ import type { Commitment, CommitmentApi, CorpusScope, RetrievedDocument, SourceDocument } from './types';
13
+ import { isInScope } from './retrieval';
14
+
15
+ export const ITEM_ID_PREFIX = 'item:';
16
+ /** The item id behind a cited record id, or null when it is a document. */
17
+ export const itemIdOf = (documentId: string): string | null =>
18
+ documentId.startsWith(ITEM_ID_PREFIX) ? documentId.slice(ITEM_ID_PREFIX.length) : null;
19
+ export const ITEM_SUBTYPE = 'tracked_item';
20
+ const FINISHED = new Set(['done', 'dropped']);
21
+ const LINEAR_FINISHED = new Set(['completed', 'canceled', 'cancelled']);
22
+
23
+ export interface ItemContext {
24
+ now: number;
25
+ timeZone?: string;
26
+ /** The reader's member id, for "my". */
27
+ ownerSub?: string;
28
+ /** Project names by focus id, when the caller has them. */
29
+ focusNames?: Record<string, string>;
30
+ }
31
+
32
+ /** One item as a record the model can read and the screen can cite. */
33
+ export function itemAsDocument(item: Commitment, ctx: ItemContext): SourceDocument {
34
+ const zone = ctx.timeZone ?? 'UTC';
35
+ const due = dueDay(item.dueAt, zone);
36
+ const project = item.focusId ? ctx.focusNames?.[item.focusId] : undefined;
37
+ const lines = [
38
+ `Status: ${item.status}${item.statusReason ? ` (${item.statusReason})` : ''}`,
39
+ `Due: ${due ?? 'no date'}`,
40
+ `Owner: ${item.ownerName ?? 'unassigned'}`,
41
+ `Project: ${project ?? (item.destination === 'personal' ? 'Personal' : item.focusId ? 'filed' : 'unfiled')}`,
42
+ item.priority !== undefined ? `Priority: ${item.priority} (0 critical .. 4 backlog)` : '',
43
+ item.sync?.key ? `Linear: ${item.sync.key}${item.sync.stateName ? ` — ${item.sync.stateName}` : ''}` : '',
44
+ item.firstSeenAt ? `First said: ${item.firstSeenAt.slice(0, 10)}` : '',
45
+ item.detail ? `Detail: ${item.detail}` : '',
46
+ ].filter(Boolean);
47
+ return {
48
+ id: `${ITEM_ID_PREFIX}${item.externalId}`,
49
+ title: item.title,
50
+ body: lines.join('\n'),
51
+ sections: [],
52
+ occurredAt: item.firstSeenAt,
53
+ source: item.source,
54
+ sourceLabel: 'Tracked item',
55
+ subtype: ITEM_SUBTYPE,
56
+ sourceRef: item.id,
57
+ participants: [],
58
+ scope: item.scope,
59
+ };
60
+ }
61
+
62
+ /** Which of `items` the intent asks about, in the order worth reading. Pure. */
63
+ export function selectItems(items: Commitment[], intent: ItemIntent, ctx: ItemContext): Commitment[] {
64
+ const zone = ctx.timeZone ?? 'UTC';
65
+ const inWindow = (day: string | null) => Boolean(day && (!intent.from || day >= intent.from) && (!intent.to || day <= intent.to));
66
+ const finished = (i: Commitment) => FINISHED.has(i.status) || LINEAR_FINISHED.has((i.sync?.stateName ?? '').toLowerCase());
67
+ const picked = items.filter((item) => {
68
+ if (intent.mine && ctx.ownerSub && item.ownerSub !== ctx.ownerSub && !item.ownerSubs?.includes(ctx.ownerSub)) return false;
69
+ const due = dueDay(item.dueAt, zone);
70
+ const said = item.firstSeenAt ? dueDay(item.firstSeenAt, zone) : null;
71
+ switch (intent.focus) {
72
+ case 'slipping': return !finished(item) && (item.status === 'blocked' || Boolean(due && due < intent.today));
73
+ case 'due': return intent.from ? inWindow(due) : Boolean(due) && !finished(item);
74
+ case 'committed': return intent.from ? inWindow(due) || inWindow(said) : !finished(item);
75
+ default: return intent.from ? inWindow(due) || inWindow(said) : !finished(item);
76
+ }
77
+ });
78
+ return picked.sort((a, b) =>
79
+ (dueDay(a.dueAt, zone) ?? '9999').localeCompare(dueDay(b.dueAt, zone) ?? '9999') || (a.priority ?? 9) - (b.priority ?? 9));
80
+ }
81
+
82
+ /** Items for a question: read, scope-check, select, convert. Empty when it is not an item question. */
83
+ export async function retrieveItems(
84
+ question: string,
85
+ api: Pick<CommitmentApi, 'listCommitments'> | undefined,
86
+ scope: CorpusScope,
87
+ ctx: ItemContext,
88
+ limit: number,
89
+ ): Promise<{ intent: ItemIntent | null; retrieved: RetrievedDocument[]; matched: number }> {
90
+ const intent = itemIntent(question, ctx.now, ctx.timeZone);
91
+ if (!intent || !api) return { intent: null, retrieved: [], matched: 0 };
92
+ const page = await api.listCommitments({ pageSize: 200, sort: 'due', withFocus: true }).catch(() => null);
93
+ if (!page) return { intent, retrieved: [], matched: 0 };
94
+ const selected = selectItems(page.results.filter((item) => isInScope(item, scope)), intent, ctx);
95
+ const retrieved = selected.slice(0, limit).map((item): RetrievedDocument => {
96
+ const document = itemAsDocument(item, ctx);
97
+ return { document, score: 1, matchedTerms: [], snippet: document.body.split('\n').slice(0, 2).join(' · ') };
98
+ });
99
+ return { intent, retrieved, matched: selected.length };
100
+ }
package/src/corpus/ask.ts CHANGED
@@ -18,6 +18,7 @@
18
18
  * cannot trust with a contract. A model that cites a document id it was never
19
19
  * given has invented a source, and the only safe rendering of that is to say so.
20
20
  */
21
+ import { retrieveItems } from './ask-items';
21
22
  import { moneyEventAsDocument } from './entities';
22
23
  import { retrieveForQuestion, searchTermFor } from './retrieval';
23
24
  import { documentText } from './text';
@@ -26,6 +27,7 @@ import type {
26
27
  AskRequest,
27
28
  AskResult,
28
29
  Citation,
30
+ CommitmentApi,
29
31
  CorpusApi,
30
32
  CorpusLlm,
31
33
  PromptDocument,
@@ -43,12 +45,21 @@ export interface AskCorpusOptions {
43
45
  maxCharsPerDocument?: number;
44
46
  /** Injectable clock for the recency prior. */
45
47
  now?: number;
48
+ /** How many tracked items an item question may put in front of the model. */
49
+ itemLimit?: number;
50
+ /** The reader's IANA zone, so "Friday" and "overdue" mean THEIR calendar. */
51
+ timeZone?: string;
52
+ /** The reader's member id, for "what did I commit to". */
53
+ ownerSub?: string;
54
+ /** Project names by focus id, for the item records. */
55
+ focusNames?: Record<string, string>;
46
56
  }
47
57
 
48
- const DEFAULTS: Required<Omit<AskCorpusOptions, 'now'>> = {
58
+ const DEFAULTS = {
49
59
  candidateLimit: 200,
50
60
  contextLimit: 8,
51
61
  maxCharsPerDocument: 6000,
62
+ itemLimit: 30,
52
63
  };
53
64
 
54
65
  /**
@@ -75,6 +86,7 @@ function systemPrompt(mode: AskRequest['mode']): string {
75
86
  'You answer questions about a company using only that company\'s own records.',
76
87
  ...shared,
77
88
  'Be specific and short. Prefer naming the record and the date over hedging.',
89
+ 'Documents whose id starts with "item:" are TRACKED ITEMS (to-dos): their Status, Due, Owner, Project and Linear lines are the facts. Answer from those lines exactly, compare dates against the "today" given, and cite each item you mention by its id.',
78
90
  'A document may list "withheld_from_this_reader". Those parts were deliberately not shown to you: never claim something was not said or did not happen on the basis of a document that lists them — say the record is partly withheld instead.',
79
91
  ].join('\n');
80
92
  }
@@ -84,6 +96,7 @@ export function buildAnswerRequest(
84
96
  request: AskRequest,
85
97
  retrieved: RetrievedDocument[],
86
98
  maxChars: number,
99
+ extra: { today?: string; itemWindow?: string } = {},
87
100
  ): AnswerRequest {
88
101
  const documents: PromptDocument[] = retrieved.map(({ document }) => ({
89
102
  id: document.id,
@@ -102,6 +115,8 @@ export function buildAnswerRequest(
102
115
  mode: request.mode,
103
116
  instructions: request.instructions,
104
117
  documents,
118
+ ...(extra.today ? { today: extra.today } : {}),
119
+ ...(extra.itemWindow ? { itemWindow: extra.itemWindow } : {}),
105
120
  };
106
121
  }
107
122
 
@@ -147,6 +162,7 @@ export function renderAnswerPrompt(input: AnswerRequest): string {
147
162
  ? `DRAFT REQUEST:\n${input.question}`
148
163
  : `QUESTION:\n${input.question}`;
149
164
  return [
165
+ input.today ? `TODAY: ${input.today}${input.itemWindow ? ` · asked about ${input.itemWindow}` : ''}` : '',
150
166
  `DOCUMENTS (${input.documents.length}):`,
151
167
  blocks.join('\n\n'),
152
168
  '',
@@ -333,10 +349,10 @@ function noEvidenceCopy(total: number): string {
333
349
  */
334
350
  export async function askCorpus(
335
351
  request: AskRequest,
336
- deps: { corpus: CorpusApi; llm: CorpusLlm },
352
+ deps: { corpus: CorpusApi; llm: CorpusLlm; commitments?: Pick<CommitmentApi, 'listCommitments'> },
337
353
  options: AskCorpusOptions = {},
338
354
  ): Promise<AskResult> {
339
- const { candidateLimit, contextLimit, maxCharsPerDocument } = { ...DEFAULTS, ...options };
355
+ const { candidateLimit, contextLimit, maxCharsPerDocument, itemLimit } = { ...DEFAULTS, ...options };
340
356
  const { corpus, llm } = deps;
341
357
 
342
358
  // An empty scope grants nothing (see `isInScope`). Refusing here rather than
@@ -351,15 +367,40 @@ export async function askCorpus(
351
367
  request,
352
368
  candidateLimit,
353
369
  );
354
- const { retrieved, droppedOutOfScope } = retrieveForQuestion(
370
+ const { retrieved: documents, droppedOutOfScope } = retrieveForQuestion(
355
371
  candidates,
356
372
  request.question,
357
373
  request.scope,
358
374
  { limit: contextLimit, now: options.now },
359
375
  );
376
+ // TRACKED ITEMS. Selected by dates and states in code, in their own budget so
377
+ // documents can never crowd them out; they lead the prompt.
378
+ const items = request.mode === 'ask'
379
+ ? await retrieveItems(
380
+ request.question,
381
+ deps.commitments,
382
+ request.scope,
383
+ { now: options.now ?? Date.now(), timeZone: options.timeZone, ownerSub: options.ownerSub, focusNames: options.focusNames },
384
+ itemLimit,
385
+ )
386
+ : { intent: null, retrieved: [], matched: 0 };
387
+ const retrieved = [...items.retrieved, ...documents];
360
388
 
361
389
  const freshness = await corpus.listSources().catch(() => [] as SourceFreshness[]);
362
390
 
391
+ if (retrieved.length === 0 && items.intent && deps.commitments) {
392
+ return {
393
+ status: 'no_evidence',
394
+ answer: `No tracked items match${items.intent.windowLabel ? ` ${items.intent.windowLabel}` : ''}, and no documents do either.`,
395
+ citations: [],
396
+ considered: [],
397
+ unresolvedCitations: [],
398
+ droppedOutOfScope,
399
+ provider: llm.describe(),
400
+ freshness,
401
+ };
402
+ }
403
+
363
404
  if (retrieved.length === 0) {
364
405
  // An unfiltered pull already tells us the size, so the extra read only
365
406
  // happens on the path that is about to make a claim about the corpus.
@@ -379,7 +420,9 @@ export async function askCorpus(
379
420
  const withheldFields = collectWithheld(retrieved);
380
421
 
381
422
  const draft = await llm.answer(
382
- buildAnswerRequest(request, retrieved, maxCharsPerDocument),
423
+ buildAnswerRequest(request, retrieved, maxCharsPerDocument, items.intent
424
+ ? { today: items.intent.today, itemWindow: items.intent.windowLabel }
425
+ : {}),
383
426
  );
384
427
  const { citations, unresolved } = resolveCitations(draft, retrieved);
385
428
 
@@ -0,0 +1,89 @@
1
+ /**
2
+ * THE WEEKLY SUMMARY ROUTE'S LOGIC (bd startsim-tmrvi), the weekly twin of
3
+ * `generateBriefing`: load -> compose -> script -> speak -> keep, one row per
4
+ * (owner, local day), a repeat tap costs nothing, text always returned, speech
5
+ * best-effort. SAME deps, SAME store, SAME audio path; only the composer and the
6
+ * wording differ. The row is the OWNER'S: there is no delivery beyond the app.
7
+ */
8
+ import { hashString } from './cache-key';
9
+ import { composeWeekly, weeklyScript } from './weekly';
10
+ import { createEntityBriefingStore, type BriefingRecord } from './store';
11
+ import type { BriefingDeps, BriefingRequest } from './generate';
12
+ import type { WeeklySummary } from './weekly';
13
+
14
+ export const WEEKLY_SCRIPT_VERSION = 1;
15
+ export const weeklyExternalId = (ownerSub: string, localDate: string) => `weekly:${localDate}:${ownerSub}`;
16
+
17
+ export interface WeeklyResult {
18
+ summaryId: string;
19
+ text: string;
20
+ audioUrl: string | null;
21
+ audioReason?: string;
22
+ counts: WeeklySummary['counts'];
23
+ window: WeeklySummary['window'];
24
+ cached: boolean;
25
+ }
26
+
27
+ const reasonOf = (error: unknown) => (error instanceof Error ? error.message : String(error)).slice(0, 300);
28
+
29
+ export async function generateWeekly(deps: BriefingDeps, request: BriefingRequest = {}): Promise<WeeklyResult> {
30
+ const now = (deps.now ?? Date.now)();
31
+ const timeZone = request.timeZone ?? deps.timeZone ?? 'UTC';
32
+ const ttl = Math.min(deps.audioTtlSeconds ?? 300, 600);
33
+ const store = deps.store ?? createEntityBriefingStore(deps.http, deps.ownerSub);
34
+
35
+ const summary = composeWeekly(await deps.loadItems(), { ownerSub: deps.ownerSub, now, timeZone });
36
+ const script = weeklyScript(summary, { now, timeZone, name: deps.name });
37
+ const hash = hashString(`w${WEEKLY_SCRIPT_VERSION}␞${summary.window.today}␞${script.text}`);
38
+ const externalId = weeklyExternalId(deps.ownerSub, summary.window.today);
39
+ const stored = request.force ? null : await store.find(externalId);
40
+ const current = stored && stored.contentHash === hash ? stored : null;
41
+
42
+ const linkFor = async (ref: string | undefined, id: string): Promise<string | null> => {
43
+ if (!ref) return null;
44
+ try { return await deps.audio.url(ref, ttl, id); } catch { return null; }
45
+ };
46
+ const result = (record: BriefingRecord, audioUrl: string | null, cached: boolean, reason?: string): WeeklyResult => ({
47
+ summaryId: record.id,
48
+ text: record.text,
49
+ audioUrl,
50
+ ...(audioUrl ? {} : { audioReason: reason ?? record.audioReason ?? 'No audio was generated.' }),
51
+ counts: summary.counts,
52
+ window: summary.window,
53
+ cached,
54
+ });
55
+
56
+ if (current?.audioRef) {
57
+ const url = await linkFor(current.audioRef, current.id);
58
+ if (url) return result(current, url, true);
59
+ }
60
+
61
+ let audioRef: string | undefined;
62
+ let audioMime: string | undefined;
63
+ let audioReason: string | undefined;
64
+ let usage: Record<string, unknown> | undefined;
65
+ try {
66
+ const spoken = await deps.synthesize({ text: script.text });
67
+ audioRef = await deps.audio.put({ noteId: `weekly-${summary.window.today}-${hash}`, audio: spoken.audio, mimeType: spoken.mimeType });
68
+ audioMime = spoken.mimeType;
69
+ usage = { provider: spoken.provider, model: spoken.model, characters: spoken.usage.characters, costUsd: spoken.usage.costUsd };
70
+ } catch (error) {
71
+ audioReason = `Speech is unavailable right now: ${reasonOf(error)}`;
72
+ }
73
+
74
+ const saved = await store.save({
75
+ externalId,
76
+ localDate: summary.window.today,
77
+ contentHash: hash,
78
+ text: script.text,
79
+ scriptSource: 'template',
80
+ items: [],
81
+ remaining: 0,
82
+ context: { itemIds: [], localDate: summary.window.today, timeZone, offsets: [] },
83
+ ...(audioRef ? { audioRef, audioMime } : {}),
84
+ ...(audioReason ? { audioReason } : {}),
85
+ ...(usage ? { usage } : {}),
86
+ createdAt: new Date(now).toISOString(),
87
+ });
88
+ return result(saved, await linkFor(audioRef, saved.id), Boolean(current), audioReason);
89
+ }
@@ -6,8 +6,12 @@ export { writeBriefingScript, templateScript, scriptPrompt, scriptSystemPrompt }
6
6
  export type { BriefingScript, BriefingScriptLlm, BriefingScriptOptions, ScriptSegment } from './script';
7
7
  export { speakCount, speakDate, speakable, isUnspeakable, partOfDay, wordCount } from './speak';
8
8
  export { generateBriefing } from './generate';
9
+ export { composeWeekly, weeklyScript } from './weekly';
10
+ export type { WeeklyEntry, WeeklyKind, WeeklyOptions, WeeklyScript, WeeklyScriptOptions, WeeklySummary } from './weekly';
11
+ export { generateWeekly, weeklyExternalId } from './generate-weekly';
12
+ export type { WeeklyResult } from './generate-weekly';
9
13
  export type { BriefingAudio, BriefingDeps, BriefingRequest, BriefingResult, BriefingSynthesize } from './generate';
10
- export { briefingResponse, briefingAudioResponse } from './respond';
14
+ export { briefingResponse, weeklyResponse, briefingAudioResponse } from './respond';
11
15
  export { createEntityBriefingStore, briefingExternalId, BRIEFING_SOURCE } from './store';
12
16
  export type { BriefingContextRecord, BriefingRecord, BriefingStore } from './store';
13
17
  export { briefingContentHash, hashString, SCRIPT_VERSION } from './cache-key';
@@ -6,9 +6,10 @@
6
6
  import type { CorpusHttp } from '../client';
7
7
  import type { TenantEntity } from '../entities';
8
8
  import { voiceErrorResponse } from '../voice-manage';
9
- import { generateBriefing, type BriefingDeps } from './generate';
9
+ import { generateBriefing, type BriefingDeps, type BriefingRequest } from './generate';
10
+ import { generateWeekly } from './generate-weekly';
10
11
 
11
- export async function briefingResponse(request: Request, deps: BriefingDeps): Promise<Response> {
12
+ async function respondWith(request: Request, run: (options: BriefingRequest) => Promise<unknown>): Promise<Response> {
12
13
  let body: { force?: unknown; timeZone?: unknown } = {};
13
14
  try {
14
15
  const raw = await request.text();
@@ -24,12 +25,19 @@ export async function briefingResponse(request: Request, deps: BriefingDeps): Pr
24
25
  }
25
26
  }
26
27
  try {
27
- return Response.json(await generateBriefing(deps, { force, timeZone }));
28
+ return Response.json(await run({ force, timeZone }));
28
29
  } catch (error) {
29
30
  return voiceErrorResponse(error);
30
31
  }
31
32
  }
32
33
 
34
+ export const briefingResponse = (request: Request, deps: BriefingDeps): Promise<Response> =>
35
+ respondWith(request, (options) => generateBriefing(deps, options));
36
+
37
+ /** The weekly summary: same request shape, same owner-only row and audio route. */
38
+ export const weeklyResponse = (request: Request, deps: BriefingDeps): Promise<Response> =>
39
+ respondWith(request, (options) => generateWeekly(deps, options));
40
+
33
41
  /** The audio, to the briefing's owner only: the row is read as the caller, so another member's id is a 404. */
34
42
  export async function briefingAudioResponse(
35
43
  id: string,
@@ -19,6 +19,8 @@ export interface BriefingItem {
19
19
  /** Linear's own state type when the item is synced (`started`, `completed`, `canceled`, ...). */
20
20
  linearState?: string;
21
21
  linearIdentifier?: string;
22
+ /** When it was finished, when known (the weekly summary counts a done item only with this). */
23
+ resolvedAt?: string | null;
22
24
  }
23
25
 
24
26
  export type BriefingKind = 'overdue' | 'in_progress' | 'due_today';
@@ -0,0 +1,155 @@
1
+ /**
2
+ * THE WEEKLY SUMMARY (bd startsim-tmrvi): what got done, what is slipping and
3
+ * what is due in the coming week, for ONE person, spoken in the app.
4
+ *
5
+ * Built from the briefing's own parts: the same `BriefingItem` input, the same
6
+ * ownership and finished-state rules as `composeBriefing`, the same spoken-form
7
+ * helpers, the same store and delivery path (`generateWeekly`). PURE, like the
8
+ * composer: the caller passes `now` and the reader's zone.
9
+ *
10
+ * It is composed per OWNER and nothing here addresses anyone else: there is no
11
+ * recipient list, no email and no push, only a row the owner's own session reads.
12
+ */
13
+ import { dueDay, localDate } from '../today';
14
+ import { isUnspeakable, partOfDay, speakCount, speakDate, speakable, wordCount } from './speak';
15
+ import type { BriefingItem } from './types';
16
+
17
+ export type WeeklyKind = 'done' | 'slipping' | 'upcoming';
18
+
19
+ export interface WeeklyEntry {
20
+ id: string;
21
+ title: string;
22
+ kind: WeeklyKind;
23
+ /** Project name, or `Personal`. */
24
+ group: string;
25
+ dueDate: string | null;
26
+ doneDate?: string | null;
27
+ }
28
+
29
+ export interface WeeklySummary {
30
+ done: WeeklyEntry[];
31
+ slipping: WeeklyEntry[];
32
+ upcoming: WeeklyEntry[];
33
+ counts: Record<WeeklyKind, number>;
34
+ empty: boolean;
35
+ /** First day (inclusive) of the look-back, today, and last day of the look-ahead. */
36
+ window: { from: string; today: string; to: string; timeZone: string };
37
+ }
38
+
39
+ export interface WeeklyOptions {
40
+ ownerSub: string;
41
+ now: number;
42
+ timeZone?: string;
43
+ /** Days back for "done" and ahead for "upcoming". Default 7. */
44
+ days?: number;
45
+ /** Entries kept per section. Default 8. */
46
+ perSection?: number;
47
+ }
48
+
49
+ const FINISHED = new Set(['done', 'dropped']);
50
+ const LINEAR_FINISHED = new Set(['completed', 'canceled', 'cancelled']);
51
+
52
+ const addDays = (day: string, n: number): string => {
53
+ const d = new Date(`${day}T00:00:00Z`);
54
+ d.setUTCDate(d.getUTCDate() + n);
55
+ return d.toISOString().slice(0, 10);
56
+ };
57
+
58
+ export function composeWeekly(items: BriefingItem[], options: WeeklyOptions): WeeklySummary {
59
+ const timeZone = options.timeZone ?? 'UTC';
60
+ const days = options.days ?? 7;
61
+ const max = options.perSection ?? 8;
62
+ const today = localDate(options.now, timeZone);
63
+ const from = addDays(today, -days);
64
+ const to = addDays(today, days);
65
+ const buckets: Record<WeeklyKind, WeeklyEntry[]> = { done: [], slipping: [], upcoming: [] };
66
+ const counts: Record<WeeklyKind, number> = { done: 0, slipping: 0, upcoming: 0 };
67
+
68
+ for (const item of items) {
69
+ if (!item.ownerSub || item.ownerSub !== options.ownerSub) continue;
70
+ const due = dueDay(item.dueAt, timeZone);
71
+ const group = item.focusName?.trim() || 'Personal';
72
+ const linearDone = Boolean(item.linearState && LINEAR_FINISHED.has(item.linearState.toLowerCase()));
73
+ let kind: WeeklyKind | null = null;
74
+ let doneDate: string | null = null;
75
+ if (item.status === 'done' || linearDone) {
76
+ doneDate = dueDay(item.resolvedAt, timeZone);
77
+ // "Done" counts only when we know WHEN: a done item with no timestamp is not evidence of this week.
78
+ if (doneDate && doneDate >= from && doneDate <= today) kind = 'done';
79
+ } else if (!FINISHED.has(item.status)) {
80
+ if (due && due < today) kind = 'slipping';
81
+ else if (item.status === 'blocked' && !due) kind = 'slipping';
82
+ else if (due && due >= today && due <= to) kind = 'upcoming';
83
+ }
84
+ if (!kind) continue;
85
+ counts[kind] += 1;
86
+ buckets[kind].push({ id: item.id, title: item.title, kind, group, dueDate: due, ...(doneDate ? { doneDate } : {}) });
87
+ }
88
+
89
+ const byDue = (a: WeeklyEntry, b: WeeklyEntry) => (a.dueDate ?? '9999').localeCompare(b.dueDate ?? '9999');
90
+ buckets.slipping.sort(byDue);
91
+ buckets.upcoming.sort(byDue);
92
+ buckets.done.sort((a, b) => (b.doneDate ?? '').localeCompare(a.doneDate ?? ''));
93
+ return {
94
+ done: buckets.done.slice(0, max),
95
+ slipping: buckets.slipping.slice(0, max),
96
+ upcoming: buckets.upcoming.slice(0, max),
97
+ counts,
98
+ empty: counts.done + counts.slipping + counts.upcoming === 0,
99
+ window: { from, today, to, timeZone },
100
+ };
101
+ }
102
+
103
+ // -- the spoken script --------------------------------------------------------
104
+
105
+ export interface WeeklyScriptOptions {
106
+ now: number;
107
+ timeZone?: string;
108
+ name?: string;
109
+ /** Items named per section before "and N more". Default 4. */
110
+ named?: number;
111
+ /** Word budget. Default 260. */
112
+ maxWords?: number;
113
+ }
114
+
115
+ export interface WeeklyScript { text: string; words: number; source: 'template' }
116
+
117
+ const title = (e: WeeklyEntry) => speakable(e.title) || 'an untitled item';
118
+ const list = (parts: string[]) => (parts.length < 2 ? parts.join('') : `${parts.slice(0, -1).join(', ')}, and ${parts[parts.length - 1]}`);
119
+ const cap = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);
120
+ const noun = (n: number) => (n === 1 ? 'item' : 'items');
121
+
122
+ /** Deterministic wording: nothing a model could invent, nothing unspeakable. */
123
+ export function weeklyScript(summary: WeeklySummary, options: WeeklyScriptOptions): WeeklyScript {
124
+ const zone = options.timeZone ?? 'UTC';
125
+ const part = partOfDay(options.now, zone);
126
+ const named = options.named ?? 4;
127
+ const today = summary.window.today;
128
+ const sentences: string[] = [options.name ? `Good ${part}, ${options.name}. Here is your week.` : `Good ${part}. Here is your week.`];
129
+ if (summary.empty) {
130
+ sentences.push('Nothing was finished, nothing is slipping and nothing is due in the coming week.');
131
+ } else {
132
+ const { counts } = summary;
133
+ if (counts.done) {
134
+ const shown = summary.done.slice(0, named).map(title);
135
+ const more = counts.done - shown.length;
136
+ sentences.push(`You finished ${speakCount(counts.done)} ${noun(counts.done)} this past week: ${list(shown)}${more > 0 ? `, and ${speakCount(more)} more` : ''}.`);
137
+ } else sentences.push('Nothing was marked done this past week.');
138
+ if (counts.slipping) {
139
+ const shown = summary.slipping.slice(0, named).map((e) => `${title(e)}${e.dueDate ? `, due ${speakDate(e.dueDate, today)}` : ', blocked'}`);
140
+ const more = counts.slipping - shown.length;
141
+ sentences.push(`${cap(speakCount(counts.slipping))} ${noun(counts.slipping)} ${counts.slipping === 1 ? 'is' : 'are'} slipping: ${list(shown)}${more > 0 ? `, and ${speakCount(more)} more` : ''}.`);
142
+ } else sentences.push('Nothing is slipping.');
143
+ if (counts.upcoming) {
144
+ const shown = summary.upcoming.slice(0, named).map((e) => `${title(e)}, ${e.dueDate ? speakDate(e.dueDate, today) : ''}`.replace(/, $/, ''));
145
+ const more = counts.upcoming - shown.length;
146
+ sentences.push(`Coming up in the next week: ${list(shown)}${more > 0 ? `, and ${speakCount(more)} more` : ''}.`);
147
+ } else sentences.push('Nothing is due in the coming week.');
148
+ }
149
+ let text = sentences.join(' ');
150
+ const budget = options.maxWords ?? 260;
151
+ if (wordCount(text) > budget && (options.named ?? 4) > 1) return weeklyScript(summary, { ...options, named: named - 1 });
152
+ // A title that slipped past `speakable` must not reach the voice.
153
+ if (isUnspeakable(text)) text = text.replace(/\b\d{4}-\d{2}-\d{2}\b/g, 'a date');
154
+ return { text, words: wordCount(text), source: 'template' };
155
+ }
@@ -109,6 +109,9 @@ export {
109
109
  resolveCitations,
110
110
  } from './ask';
111
111
  export type { AskCorpusOptions } from './ask';
112
+ export { itemAsDocument, selectItems, retrieveItems, ITEM_ID_PREFIX, ITEM_SUBTYPE, itemIdOf } from './ask-items';
113
+ export { itemIntent } from './ask-items-intent';
114
+ export type { ItemIntent, ItemFocus } from './ask-items-intent';
112
115
 
113
116
  // Extraction — conversations in, trackable commitments out (bd startsim-768w.38.25).
114
117
  export {
@@ -0,0 +1,108 @@
1
+ /**
2
+ * THE "NEEDS YOUR CALL" INBOX, as pure functions (bd startsim-tmrvi.7): how a
3
+ * question reads as answer chips, how typed words become an answer, and what an
4
+ * answer does to the to-do it is about while the save is still in flight.
5
+ * No React, no storage, no clock: the card in components/pages/questions and a
6
+ * native screen can both use these.
7
+ */
8
+ import { parseSpokenAnswer, type AnswerOption } from './voice-parse';
9
+ import type { OpenQuestion, QuestionAnswer } from './types';
10
+
11
+ export interface AnswerChip {
12
+ value: string;
13
+ label: string;
14
+ /** The value Tandem is already acting on: tapping it confirms the guess. */
15
+ assumed: boolean;
16
+ /** Why this one was offered, when the model said. */
17
+ reason?: string;
18
+ }
19
+
20
+ export interface ChipContext {
21
+ /** Names for ids (a project's id to its title, a member's sub to their name). */
22
+ labels?: Record<string, string>;
23
+ timeZone?: string;
24
+ /** More choices (team, owner) the host knows by name. */
25
+ options?: AnswerOption[];
26
+ /** Cap on offered chips. Default 4. */
27
+ max?: number;
28
+ }
29
+
30
+ const ISO_DAY = /^\d{4}-\d{2}-\d{2}/;
31
+
32
+ /** "Fri, Nov 14" for a date, the known name for an id, else the value as given. */
33
+ export function formatAnswerValue(q: Pick<OpenQuestion, 'kind'> & { options?: AnswerOption[] }, value: string, ctx: ChipContext = {}): string {
34
+ if (q.kind === 'due_date') {
35
+ if (!value) return 'No date';
36
+ if (!ISO_DAY.test(value)) return value;
37
+ const d = new Date(`${value.slice(0, 10)}T00:00:00Z`);
38
+ return d.toLocaleDateString(undefined, { weekday: 'short', month: 'short', day: 'numeric', timeZone: 'UTC' });
39
+ }
40
+ return ctx.labels?.[value] ?? ctx.options?.find((o) => o.value === value)?.label ?? (q as { options?: AnswerOption[] }).options?.find((o) => o.value === value)?.label ?? value;
41
+ }
42
+
43
+ /** The label of what Tandem is assuming, for the quiet line under the question. */
44
+ export function assumedLabel(q: OpenQuestion, ctx: ChipContext = {}): string {
45
+ const a = q.assumed;
46
+ if (!a) return '';
47
+ if (a.display) return a.display;
48
+ return a.value ? formatAnswerValue(q, a.value, ctx) : '';
49
+ }
50
+
51
+ /** The assumed value first (one tap keeps it), then the other candidates, no repeats. */
52
+ export function chipsFor(q: OpenQuestion, ctx: ChipContext = {}): AnswerChip[] {
53
+ const out: AnswerChip[] = [];
54
+ const seen = new Set<string>();
55
+ const add = (chip: AnswerChip) => {
56
+ if (!chip.value && q.kind !== 'due_date') return;
57
+ if (seen.has(chip.value)) return;
58
+ seen.add(chip.value);
59
+ out.push(chip);
60
+ };
61
+ const a = q.assumed;
62
+ if (a?.value) add({ value: a.value, label: a.display ?? formatAnswerValue(q, a.value, ctx), assumed: true, ...(a.reason ? { reason: a.reason } : {}) });
63
+ for (const c of q.candidates) {
64
+ add({ value: c.value, label: formatAnswerValue(q, c.value, ctx), assumed: false, ...(c.reason ? { reason: c.reason } : {}) });
65
+ }
66
+ // No candidates (a team, say): offer the first named choices instead.
67
+ if (out.length === 0) {
68
+ for (const o of (ctx.options ?? q.options ?? []).slice(0, ctx.max ?? 4)) add({ value: o.value, label: o.label, assumed: false });
69
+ }
70
+ return out.slice(0, ctx.max ?? 4);
71
+ }
72
+
73
+ export type TypedAnswer =
74
+ | { kind: 'answer'; answer: QuestionAnswer }
75
+ | { kind: 'skip' }
76
+ | { kind: 'unclear'; message: string };
77
+
78
+ /** What typed words mean: the same small grammar the voice answer uses, so the two cannot disagree. */
79
+ export function readTypedAnswer(
80
+ q: OpenQuestion, text: string, ctx: { now: number; timeZone?: string; options?: AnswerOption[]; labels?: Record<string, string> },
81
+ ): TypedAnswer {
82
+ const options = ctx.options ?? Object.entries(ctx.labels ?? {}).map(([value, label]) => ({ value, label }));
83
+ const parsed = parseSpokenAnswer(q, text, { now: ctx.now, timeZone: ctx.timeZone ?? 'UTC', options });
84
+ switch (parsed.kind) {
85
+ case 'answer': return { kind: 'answer', answer: { value: parsed.value, ...(parsed.label ? { label: parsed.label } : {}) } };
86
+ case 'accept': {
87
+ const value = q.assumed?.value ?? '';
88
+ return value ? { kind: 'answer', answer: { value, ...(q.assumed?.display ? { label: q.assumed.display } : {}) } } : { kind: 'unclear', message: q.question };
89
+ }
90
+ case 'skip': return { kind: 'skip' };
91
+ case 'undo': return { kind: 'unclear', message: 'Nothing to undo here. Type the answer, or skip it.' };
92
+ case 'unclear': return { kind: 'unclear', message: parsed.question };
93
+ }
94
+ }
95
+
96
+ /** The fields of a to-do an answer can change. */
97
+ export interface AnswerableItem { id: string; dueAt?: string | null; focusId?: string; ownerName?: string }
98
+
99
+ /** The to-do as it will read once this answer is saved: shown while the save is in flight. */
100
+ export function applyAnswerToItem<T extends AnswerableItem>(item: T, q: Pick<OpenQuestion, 'kind' | 'itemId'>, answer: QuestionAnswer): T {
101
+ if (item.id !== q.itemId) return item;
102
+ switch (q.kind) {
103
+ case 'due_date': return { ...item, dueAt: answer.value || null };
104
+ case 'project': return { ...item, focusId: answer.value };
105
+ case 'ownership': return { ...item, ownerName: answer.label ?? answer.value };
106
+ default: return item;
107
+ }
108
+ }
@@ -23,3 +23,5 @@ export { buildCheckIn } from './checkin-handle';
23
23
  export type { CheckInResult } from './checkin-handle';
24
24
  export { createPreferenceStore, learnFromAnswer, nextEvidence, decideFromHabits, PREFERENCE_ATTRIBUTES, PREFERENCE_LABEL, PREFERENCE_TYPE } from './learn';
25
25
  export type { Preference, PreferenceKind } from './learn';
26
+ export { applyAnswerToItem, assumedLabel, chipsFor, formatAnswerValue, readTypedAnswer } from './inbox';
27
+ export type { AnswerChip, AnswerableItem, ChipContext, TypedAnswer } from './inbox';