@startsimpli/integrations 0.2.214 → 0.2.215

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/package.json +5 -5
  2. package/src/__tests__/connect-claude.test.tsx +2 -0
  3. package/src/__tests__/corpus-tracker.test.tsx +13 -2
  4. package/src/__tests__/engine-decide.test.ts +160 -0
  5. package/src/__tests__/engine-extract-policy.test.ts +145 -0
  6. package/src/__tests__/engine-replay.test.ts +126 -0
  7. package/src/__tests__/engine-scheduled-run.test.ts +74 -0
  8. package/src/__tests__/extract-skips-tandem-authored.test.ts +34 -0
  9. package/src/__tests__/load-error.test.tsx +3 -1
  10. package/src/__tests__/suggested-items-hidden.test.ts +74 -0
  11. package/src/__tests__/suggestion-ui.test.tsx +97 -0
  12. package/src/__tests__/todo-table.test.tsx +2 -1
  13. package/src/components/pages/ConnectClaudePage.tsx +2 -1
  14. package/src/components/pages/TaskDetailPage.tsx +10 -0
  15. package/src/components/pages/TrackerPage.tsx +32 -10
  16. package/src/components/pages/tracker/Suggestion.tsx +66 -0
  17. package/src/components/table/todo-model.ts +1 -0
  18. package/src/corpus/activity.ts +2 -3
  19. package/src/corpus/ask-items.ts +2 -2
  20. package/src/corpus/briefing/compose.ts +2 -2
  21. package/src/corpus/briefing/weekly.ts +2 -2
  22. package/src/corpus/client.ts +2 -0
  23. package/src/corpus/commitments.ts +20 -3
  24. package/src/corpus/converse/briefing-queue.ts +2 -1
  25. package/src/corpus/converse/item-answers.ts +2 -2
  26. package/src/corpus/due-groups.ts +2 -2
  27. package/src/corpus/engine/apply.ts +111 -0
  28. package/src/corpus/engine/decide.ts +106 -0
  29. package/src/corpus/engine/dry-extract.ts +98 -0
  30. package/src/corpus/engine/graduation.ts +49 -0
  31. package/src/corpus/engine/index.ts +14 -0
  32. package/src/corpus/engine/replay.ts +222 -0
  33. package/src/corpus/engine/rules.ts +58 -0
  34. package/src/corpus/engine/sources.ts +16 -0
  35. package/src/corpus/engine/suggestion.ts +72 -0
  36. package/src/corpus/engine/types.ts +147 -0
  37. package/src/corpus/entities.ts +7 -1
  38. package/src/corpus/extract-prompts.ts +139 -0
  39. package/src/corpus/extract.ts +46 -139
  40. package/src/corpus/focus-overview.ts +2 -2
  41. package/src/corpus/index.ts +9 -0
  42. package/src/corpus/item-status.ts +17 -0
  43. package/src/corpus/note-actions.ts +3 -3
  44. package/src/corpus/questions/derive.ts +2 -1
  45. package/src/corpus/questions/sync.ts +2 -1
  46. package/src/corpus/runs.ts +21 -1
  47. package/src/corpus/today.ts +2 -2
  48. package/src/corpus/tracker-groups.ts +3 -0
  49. package/src/corpus/tracker-timeline-client.ts +1 -1
  50. package/src/corpus/types.ts +12 -2
  51. package/src/native/screens/connect-claude/ConnectClaudeScreen.tsx +1 -1
  52. package/src/native/screens/connect-claude/fake.ts +1 -1
  53. package/src/native/tracker/format.ts +1 -1
@@ -46,6 +46,13 @@ import { applyDecisions, buildClassifyRequest, candidatesFromFocuses } from './c
46
46
  import { applyTeamDecisions, buildTeamRequest } from './classify-team';
47
47
  import { EXTRACTOR_VERSION, applyResolutions, mergeDrafts, reconcile } from './commitments';
48
48
  import { enforceScope } from './retrieval';
49
+ import { isTandemAuthored } from './engine/sources';
50
+ import { applyPolicy, ownerNamesFrom } from './engine/apply';
51
+ import { labelsFrom } from './engine/suggestion';
52
+ import type { EngineScope, PolicyOutcome } from './engine/apply';
53
+ import { extractSystemPrompt, renderExtractPrompt, renderVerifyPrompt, verifySystemPrompt } from './extract-prompts';
54
+
55
+ export { extractSystemPrompt, renderExtractPrompt, renderVerifyPrompt, verifySystemPrompt };
49
56
  import { META_LINE, parseItemMeta } from './extraction-fields';
50
57
  import { withStatedDue } from './stated-date';
51
58
  import type { ItemMeta } from './extraction-fields';
@@ -64,7 +71,6 @@ import type {
64
71
  PlanningApi,
65
72
  ResolutionClaim,
66
73
  SourceDocument,
67
- VerificationRequest,
68
74
  TeamCandidate,
69
75
  } from './types';
70
76
 
@@ -255,139 +261,6 @@ function toDraft(document: SourceDocument, line: string, detail: string): Commit
255
261
  const slug = (text: string) =>
256
262
  text.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 60);
257
263
 
258
- // ---------------------------------------------------------------------------
259
- // the prompt
260
- // ---------------------------------------------------------------------------
261
-
262
- /**
263
- * Every rule in here is also enforced in code, because a prompt is a request and
264
- * a check is a guarantee. What the prompt uniquely buys is the two things code
265
- * cannot derive: what a statement is ABOUT, and whether a later meeting settled
266
- * an earlier one.
267
- */
268
- export function extractSystemPrompt(): string {
269
- return [
270
- 'You read meeting records for one company and turn them into trackable items.',
271
- 'You are given documents that ALREADY have some items extracted from them, listed under ALREADY_FOUND. Do NOT repeat those. Find what they missed.',
272
- 'A document may contain a curated summary AND the verbatim transcript of the same meeting. ALREADY_FOUND was taken from the summary, so the items worth reporting are the ones that were said out loud and never made it into the summary.',
273
- 'An item is something a person now owes, has decided, needs, is at risk from, or has asked. It must be stated in the document — never inferred, never invented.',
274
- 'People in conversation say things they are not committing to. "We should probably look at that", "maybe next quarter", thinking aloud, reading an agenda, or describing what somebody else already did are NOT items.',
275
- 'BUT A VAGUE OPENING FOLLOWED BY A DECISION IS AN ITEM. "Somebody has to cancel that seat" — "put it on Megan" is one commitment with an owner, not two hedges. So is "we need to ask the city about the sidewalk" when nobody argues and the group moves on. Read the exchange, not the sentence: what matters is whether the thing ends up settled, and who ends up holding it.',
276
- 'For every item, copy a short verbatim "quote" from the document it came from, and echo that document\'s exact id. The quote must appear in the document CHARACTER FOR CHARACTER — it is checked, and an item whose quote is not found is discarded.',
277
- 'Set "subject" to what the item is ABOUT — a matter or case number, a property, a client, a system, a person. Copy an identifier verbatim when the text has one.',
278
- 'Set "owner" only to a name the document actually names. Leave it out otherwise.',
279
- 'Never estimate or invent a due date, and do not compute one: the system reads the date itself from your "quote". When the item has a stated date or day ("by 29th July", "tomorrow", "on Monday"), make sure those exact words are inside the quote; when the document states none, say nothing about a date.',
280
- 'Some documents are EMAILS (kind: email). The text starts with From, To and Direction lines. Direction "sent" means the mailbox owner wrote it, so commitments in it ("I will send...", "I will update...") belong to the owner. Direction "received" means somebody wrote to the owner: what the sender promises is theirs, what they ask for is the owner\'s.',
281
- 'In an email, "waiting on" matters as much as "to do": when the writer says they are blocked on, or waiting for, another person ("waiting on your reply", "I need the sheet before Friday"), report a "need" with status "blocked", owner set to the person being waited on, and the writer named in the detail. Quoted older messages (lines starting with >) are history, not new statements.',
282
- 'An issue key such as ENG-42 in a document is a strong "subject": copy it verbatim, including when the email says the work is finished or moved.',
283
- 'Also report RESOLUTIONS: statements that something previously outstanding is now done or abandoned. Give the subject, what happened, and a verbatim quote.',
284
- 'Respond with JSON only: {"items":[{"documentId":string,"subtype":"action"|"decision"|"need"|"risk"|"question","title":string,"detail":string,"status":"open"|"done"|"blocked","owner":string,"subject":string,"quote":string}],"resolutions":[{"documentId":string,"subject":string,"statement":string,"quote":string,"outcome":"done"|"dropped"}]}',
285
- '"title" must be one short imperative line.',
286
- ].join('\n');
287
- }
288
-
289
- /** ONE payload carrying every document, each tagged with the id to echo. */
290
- export function renderExtractPrompt(input: {
291
- documents: Array<{
292
- id: string; title: string; source: string; occurredAt: string | null;
293
- participants: string[]; kind?: string; text: string; alreadyFound: string[];
294
- }>;
295
- }): string {
296
- const blocks = input.documents.map((document) =>
297
- [
298
- `<document id="${document.id}">`,
299
- `title: ${document.title}`,
300
- `source: ${document.source}`,
301
- document.kind ? `kind: ${document.kind}` : '',
302
- `occurred_at: ${document.occurredAt ?? 'unknown'}`,
303
- document.participants.length ? `participants: ${document.participants.join(', ')}` : '',
304
- document.alreadyFound.length
305
- ? `ALREADY_FOUND (do not repeat these):\n${document.alreadyFound.map((title) => `- ${title}`).join('\n')}`
306
- : 'ALREADY_FOUND: none',
307
- '',
308
- document.text,
309
- '</document>',
310
- ]
311
- .filter((line) => line !== '')
312
- .join('\n'),
313
- );
314
- return [`DOCUMENTS (${input.documents.length}):`, blocks.join('\n\n')].join('\n');
315
- }
316
-
317
- // ---------------------------------------------------------------------------
318
- // the verification prompt
319
- // ---------------------------------------------------------------------------
320
-
321
- /**
322
- * THE PRICE OF READING MORE TEXT.
323
- *
324
- * Measured on the summaries alone, adding the model pass took recall 56.1% →
325
- * 65.9% and precision 95.8% → 67.5%. A transcript is roughly ten times the text
326
- * and it is text of a different KIND — verbatim speech is full of sentences that
327
- * have the grammar of a commitment and none of the substance. "I'll take a look
328
- * at that", said and forgotten, is indistinguishable from a commitment to any
329
- * extractor working sentence by sentence. So more text does not make the model
330
- * pass more precise; it makes it less precise, and the recall it buys is only
331
- * worth having if something else pays the precision back.
332
- *
333
- * This is that something else. A SECOND, CHEAPER, ADVERSARIAL pass whose only
334
- * job is to say no: given the record and a candidate, is this a thing a named
335
- * person actually took on, and where exactly does it say so. Anything it will
336
- * not stand behind with a span from the record is dropped.
337
- *
338
- * It is deliberately asked as a REFUSAL task rather than a scoring one. "Rate
339
- * your confidence 0-1" produces a number nobody can act on and a threshold
340
- * nobody can defend; "quote the sentence where this was agreed, or say it was
341
- * not" produces evidence, and evidence can be checked in code.
342
- */
343
- export function verifySystemPrompt(): string {
344
- return [
345
- 'You are checking a list of proposed commitments against the meeting records they were taken from. You are the last check before these appear on somebody\'s to-do list.',
346
- 'For each candidate, decide ONE thing: did a specific person, in this document, actually take on this specific thing?',
347
- 'Confirm it ONLY if you can copy the span of the document that says so. The span must appear in the document character for character.',
348
- // MEASURED, and the obvious loosening is the wrong call. This line used to
349
- // read "an unowned item can still be real — judge whether the document
350
- // states it as settled or required, not whether it names a person", which is
351
- // a perfectly good argument: the `need` subtype exists precisely for a
352
- // stated requirement with nobody on it. Run it and the verifier keeps 56% of
353
- // candidates instead of 37%, and the whole run scores 66.1% recall at 65.5%
354
- // precision instead of 65.3% at 75.5%. One point of recall for ten points of
355
- // precision. Requiring somebody to be on the hook is what makes this pass
356
- // worth its own model call; without it the verifier agrees with the
357
- // extractor, which is not a check.
358
- 'Refuse it if: nobody owns it; it is a suggestion, a hypothetical, a hedge ("we should", "maybe", "at some point"); it describes something already finished; it is somebody reading an agenda or restating a topic; it is a scheduling note like when the next call is; or you cannot find where the document says it.',
359
- 'Refusing a real commitment costs one missing row. Confirming an invented one puts work on a person who never agreed to it and makes the whole list untrustworthy. When you are unsure, refuse.',
360
- 'Echo every candidate id back exactly once.',
361
- 'Respond with JSON only: {"verdicts":[{"id":string,"confirmed":boolean,"quote":string,"reason":string}]}',
362
- ].join('\n');
363
- }
364
-
365
- /** ONE payload carrying every candidate and the records they claim to come from. */
366
- export function renderVerifyPrompt(input: VerificationRequest): string {
367
- const documents = input.documents.map((document) =>
368
- [`<document id="${document.id}">`, `title: ${document.title}`, '', document.text, '</document>'].join('\n'),
369
- );
370
- const candidates = input.candidates.map((candidate) =>
371
- [
372
- `<candidate id="${candidate.id}" document="${candidate.documentId}">`,
373
- `kind: ${candidate.subtype}`,
374
- `statement: ${candidate.title}`,
375
- candidate.owner ? `claimed owner: ${candidate.owner}` : '',
376
- `claimed evidence: ${candidate.quote}`,
377
- '</candidate>',
378
- ]
379
- .filter(Boolean)
380
- .join('\n'),
381
- );
382
- return [
383
- `DOCUMENTS (${input.documents.length}):`,
384
- documents.join('\n\n'),
385
- '',
386
- `CANDIDATES (${input.candidates.length}):`,
387
- candidates.join('\n'),
388
- ].join('\n');
389
- }
390
-
391
264
  // ---------------------------------------------------------------------------
392
265
  // the pipeline
393
266
  // ---------------------------------------------------------------------------
@@ -407,6 +280,19 @@ export interface ExtractRequest {
407
280
  */
408
281
  offset?: number;
409
282
  limit?: number;
283
+ /**
284
+ * Run the engine's decision policy over what this call would write (bd
285
+ * startsim-vrmx5): new items act, become suggestions or are skipped, and a
286
+ * later source never closes an item on its own. Omit for the old behaviour.
287
+ */
288
+ engine?: EngineScope;
289
+ /**
290
+ * A scheduled pass reads only what arrived after this instant (bd startsim-vrmx5
291
+ * slice 3): a document's ingestion time, or when it happened if that is unknown.
292
+ */
293
+ since?: string | null;
294
+ /** Sources not to read, e.g. voice notes and conversations that made their items at capture. */
295
+ skipSources?: string[];
410
296
  }
411
297
 
412
298
  export interface ExtractDeps {
@@ -436,7 +322,14 @@ export async function extractCommitments(
436
322
  }
437
323
 
438
324
  const { documents: candidates, matched } = await readDocuments(corpus, documentLimit, maxPages);
439
- const { kept, dropped } = enforceScope(candidates, request.scope);
325
+ // Tandem's own output (briefings and bookkeeping) is never evidence: reading a
326
+ // briefing back would extract every to-do it lists as a new one (bd startsim-vrmx5).
327
+ const skip = new Set(request.skipSources ?? []);
328
+ const arrived = (document: SourceDocument) => !request.since || String(document.ingestedAt ?? document.occurredAt ?? '') > request.since;
329
+ const { kept, dropped } = enforceScope(
330
+ candidates.filter((document) => !isTandemAuthored(document.source) && !skip.has(String(document.source)) && arrived(document)),
331
+ request.scope,
332
+ );
440
333
  const inScope = request.documentIds?.length
441
334
  ? kept.filter((document) => request.documentIds!.includes(document.id))
442
335
  : kept;
@@ -541,9 +434,10 @@ export async function extractCommitments(
541
434
  const reconciled = reconcile(existing, groups, { scope: request.scope, documents });
542
435
 
543
436
  // 6. resolutions, against the documents the scope guard approved and nothing else.
544
- const resolutions = applyResolutions(reconciled.commitments, claims, { documents });
437
+ const resolutions = applyResolutions(reconciled.commitments, claims, { documents, proposeOnly: Boolean(request.engine) });
545
438
 
546
439
  let classified: number | undefined;
440
+ let policy: PolicyOutcome | undefined;
547
441
  let teamsPlaced: number | undefined;
548
442
  let classifyFailure: ExtractionModelFailure | null | undefined;
549
443
 
@@ -593,11 +487,23 @@ export async function extractCommitments(
593
487
  if (corpus.listTeams && extractor.classifyTeam) teamsPlaced = teams.size;
594
488
  classified = classification.placed.size;
595
489
  classifyFailure = classification.failure;
490
+ // THE POLICY decides what of the fresh half is written, and how (bd startsim-vrmx5).
491
+ const freshIds = new Set(fresh.map((item) => item.externalId));
492
+ let written = resolutions.commitments;
493
+ if (request.engine) {
494
+ const ownerNames = [...new Set([...request.engine.ownerNames, ...ownerNamesFrom(existing, request.engine.ownerSub)])];
495
+ // The owner's own reviews graduate a rule (./engine/graduation); automation never reviews.
496
+ const labels = request.engine.labels ?? labelsFrom(existing.filter((item) => item.scope?.ownerSub === request.engine!.ownerSub));
497
+ policy = applyPolicy(fresh, { scope: { ...request.engine, ownerNames, labels }, documents });
498
+ const kept = new Map(policy.kept.map((item) => [item.externalId, item]));
499
+ written = resolutions.commitments.flatMap((item) =>
500
+ freshIds.has(item.externalId) ? (kept.has(item.externalId) ? [kept.get(item.externalId)!] : []) : [item]);
501
+ }
596
502
  const fileUnder: Record<string, string> = {};
597
- for (const item of fresh) {
598
- if (item.focusId) fileUnder[item.externalId] = item.focusId;
503
+ for (const item of written) {
504
+ if (freshIds.has(item.externalId) && item.focusId) fileUnder[item.externalId] = item.focusId;
599
505
  }
600
- const rows = resolutions.commitments.filter((item) => changed.has(item.externalId));
506
+ const rows = written.filter((item) => changed.has(item.externalId));
601
507
  await (Object.keys(fileUnder).length ? corpus.saveCommitments(rows, { fileUnder }) : corpus.saveCommitments(rows));
602
508
  }
603
509
 
@@ -624,6 +530,7 @@ export async function extractCommitments(
624
530
  ...(classified !== undefined ? { classified } : {}),
625
531
  ...(teamsPlaced !== undefined ? { teamsPlaced } : {}),
626
532
  ...(classifyFailure ? { classifyFailure } : {}),
533
+ ...(policy ? { engine: { acted: policy.acted, proposed: policy.proposed, skipped: policy.skipped } } : {}),
627
534
  };
628
535
  void matched;
629
536
  }
@@ -9,9 +9,9 @@
9
9
  import { daysBetween } from './due-groups';
10
10
  import { dueDay, localDate } from './today';
11
11
  import type { Commitment, Focus } from './types';
12
+ import { isLiveStatus } from './item-status';
12
13
 
13
14
  const CLOSED_FOCUS = new Set(['completed', 'cancelled']);
14
- const FINISHED = new Set(['done', 'dropped']);
15
15
 
16
16
  export interface FocusSummary {
17
17
  focus: Focus;
@@ -37,7 +37,7 @@ export function summarizeFocuses(
37
37
  }
38
38
  for (const item of items) {
39
39
  const row = item.focusId ? rows.get(item.focusId) : undefined;
40
- if (!row || FINISHED.has(item.status)) continue;
40
+ if (!row || !isLiveStatus(item.status)) continue;
41
41
  row.open += 1;
42
42
  const due = dueDay(item.dueAt, timeZone);
43
43
  if (!due) continue;
@@ -337,3 +337,12 @@ export * from './nav-copy';
337
337
 
338
338
  // Projects as answerable records for Ask.
339
339
  export { PROJECT_ID_PREFIX, projectIdOf, projectIntent, retrieveProjects, selectProjects } from './ask-projects';
340
+
341
+ // The engine's decision policy (bd startsim-vrmx5, Todo: ENG-151).
342
+ export { applyPolicy, ownerNamesFrom, ownerRelationOf } from './engine/apply';
343
+ export type { EngineScope, PolicyOutcome } from './engine/apply';
344
+ export { decide, RULES, SAFE_RULES, isTandemAuthored, TANDEM_AUTHORED_SOURCES } from './engine';
345
+ export type { Decision, DecisionLabel, RuleId } from './engine';
346
+ export { labelsFrom, readSuggestion, writeSuggestion } from './engine/suggestion';
347
+ export type { Suggestion } from './engine/suggestion';
348
+ export { CLOSED_STATUSES, SUGGESTED_STATUS, isLiveStatus } from './item-status';
@@ -0,0 +1,17 @@
1
+ /**
2
+ * WHICH ITEMS ARE ON THE OWNER'S LIST (bd startsim-vrmx5 slice 2).
3
+ *
4
+ * `suggested` is an item the engine proposed and the owner has not accepted
5
+ * yet. Until they do it is not on their list: Today, the due groups, the
6
+ * briefings, Ask and the tracker push all leave it out, exactly as they leave
7
+ * out a closed item. Accepting moves it to `open`; rejecting moves it to `dropped`.
8
+ */
9
+ export const SUGGESTED_STATUS = 'suggested';
10
+
11
+ export const CLOSED_STATUSES: ReadonlySet<string> = new Set(['done', 'dropped']);
12
+
13
+ /** Neither closed nor waiting for the owner's review. */
14
+ export function isLiveStatus(status: string | null | undefined): boolean {
15
+ const value = String(status ?? '');
16
+ return value !== SUGGESTED_STATUS && !CLOSED_STATUSES.has(value);
17
+ }
@@ -6,6 +6,7 @@
6
6
  */
7
7
  import { isTask } from './tracker-groups';
8
8
  import type { Commitment } from './types';
9
+ import { isLiveStatus } from './item-status';
9
10
 
10
11
  export interface NoteActions {
11
12
  /** To-dos raised in the note: open before finished, then by due date. */
@@ -16,7 +17,6 @@ export interface NoteActions {
16
17
  open: number;
17
18
  }
18
19
 
19
- const FINISHED = new Set(['done', 'dropped']);
20
20
 
21
21
  export function actionsByNote(commitments: Commitment[], noteIds: string[]): Map<string, NoteActions> {
22
22
  const out = new Map<string, NoteActions>(noteIds.map((id) => [id, { tasks: [], statements: 0, open: 0 }]));
@@ -32,12 +32,12 @@ export function actionsByNote(commitments: Commitment[], noteIds: string[]): Map
32
32
  seen.add(mention.documentId);
33
33
  if (!isTask(item)) { row.statements += 1; continue; }
34
34
  row.tasks.push(item);
35
- if (!FINISHED.has(item.status)) row.open += 1;
35
+ if (isLiveStatus(item.status)) row.open += 1;
36
36
  }
37
37
  }
38
38
  for (const row of out.values()) {
39
39
  row.tasks.sort((a, b) =>
40
- Number(FINISHED.has(a.status)) - Number(FINISHED.has(b.status))
40
+ Number(!isLiveStatus(a.status)) - Number(!isLiveStatus(b.status))
41
41
  || (a.dueAt ?? '9999').localeCompare(b.dueAt ?? '9999'));
42
42
  }
43
43
  return out;
@@ -6,6 +6,7 @@ import { openQuestions } from '../extraction-fields';
6
6
  import type { FieldGuess, ItemFields } from '../extraction-fields';
7
7
  import type { VoiceItemRecord } from '../voice-due';
8
8
  import type { DerivedQuestion, ItemView, QuestionKind } from './types';
9
+ import { isLiveStatus } from '../item-status';
9
10
 
10
11
  export const CLOSED_STATUSES: ReadonlySet<string> = new Set(['done', 'dropped']);
11
12
 
@@ -41,7 +42,7 @@ export function deriveQuestions(
41
42
  ): DerivedQuestion[] {
42
43
  const out: DerivedQuestion[] = [];
43
44
  for (const item of items) {
44
- if (CLOSED_STATUSES.has(item.status)) continue;
45
+ if (!isLiveStatus(item.status)) continue;
45
46
  const base = item.noteId ? { noteId: item.noteId } : {};
46
47
 
47
48
  if (item.openKind === 'team' || item.openKind === 'personal_space') {
@@ -10,6 +10,7 @@ import { readEvidenceEvents, readItemViews, readVoiceRecords } from './items';
10
10
  import { createPreferenceStore, decideFromHabits } from './learn';
11
11
  import { createQuestionStore } from './store';
12
12
  import type { ItemView, OpenQuestion, QuestionResolution } from './types';
13
+ import { isLiveStatus } from '../item-status';
13
14
 
14
15
  export interface QuestionDeps {
15
16
  http: CorpusHttp;
@@ -35,7 +36,7 @@ export async function syncOpenQuestions(deps: QuestionDeps): Promise<{ opened: n
35
36
 
36
37
  const items = await readItemViews(deps.http, deps.scope, path);
37
38
  const byId = new Map<string, ItemView>(items.map((i) => [i.id, i]));
38
- const noteIds = items.filter((i) => !CLOSED_STATUSES.has(i.status) && i.noteId).map((i) => i.noteId as string);
39
+ const noteIds = items.filter((i) => isLiveStatus(i.status) && i.noteId).map((i) => i.noteId as string);
39
40
  const notes = await readVoiceRecords(deps.http, noteIds, path);
40
41
  const derived = deriveQuestions(items, notes);
41
42
  const existing = new Map((await store.all()).map((q) => [key(q.itemId, q.kind), q]));
@@ -106,9 +106,19 @@ export interface StartExtractionRunRequest {
106
106
  * is what makes "somebody else took it" detectable at all.
107
107
  */
108
108
  driverId?: string;
109
+ /**
110
+ * A scheduled pass (bd startsim-vrmx5 slice 3): a new run reads only what
111
+ * arrived since the last run that FINISHED started, so a failed run's window is
112
+ * read again rather than lost.
113
+ */
114
+ incremental?: boolean;
115
+ /** Sources the run does not read. */
116
+ skipSources?: string[];
109
117
  }
110
118
 
111
119
  export interface ExtractionRunOptions extends ExtractCommitmentsOptions {
120
+ /** Run the engine's decision policy for this owner (bd startsim-vrmx5). */
121
+ engine?: import('./engine/apply').EngineScope;
112
122
  /**
113
123
  * Documents one step may ask for. The TEXT budget cuts it again — see
114
124
  * `ExtractCommitmentsOptions.maxCharsPerRun` — so this is a ceiling, not a
@@ -343,8 +353,13 @@ export async function startExtractionRun(
343
353
  .then((page) => page.count)
344
354
  .catch(() => existing?.totalDocuments ?? 0);
345
355
 
356
+ const since = request.incremental && existing
357
+ ? (existing.status === 'succeeded' ? existing.startedAt : existing.since ?? null)
358
+ : null;
346
359
  const fresh: ExtractionRun = {
347
360
  ...newExtractionRun({ scope: request.scope, totalDocuments, now: at }),
361
+ ...(since ? { since } : {}),
362
+ ...(request.skipSources?.length ? { skipSources: request.skipSources } : {}),
348
363
  status: 'queued',
349
364
  leaseOwner: driver,
350
365
  leaseUntil: new Date(at + config.leaseMs).toISOString(),
@@ -397,7 +412,12 @@ export async function advanceExtractionRun(
397
412
  }
398
413
 
399
414
  const result = await extractCommitments(
400
- { scope: run.scope, offset: run.cursor, limit: config.documentsPerSlice },
415
+ {
416
+ scope: run.scope, offset: run.cursor, limit: config.documentsPerSlice,
417
+ ...(options.engine ? { engine: options.engine } : {}),
418
+ ...(run.since ? { since: run.since } : {}),
419
+ ...(run.skipSources?.length ? { skipSources: run.skipSources } : {}),
420
+ },
401
421
  deps,
402
422
  options,
403
423
  );
@@ -7,6 +7,7 @@
7
7
  * done, dropped and blocked items are not in it. The tenant answers the same
8
8
  * question server-side at `GET /api/v1/entities/today/?tz=`; the two agree.
9
9
  */
10
+ import { isLiveStatus } from './item-status';
10
11
 
11
12
  /** `YYYY-MM-DD` of an instant in a zone. */
12
13
  export function localDate(instant: number, timeZone = 'UTC'): string {
@@ -41,11 +42,10 @@ export interface TodayRule {
41
42
  includeBlocked?: boolean;
42
43
  }
43
44
 
44
- const FINISHED = new Set(['done', 'dropped']);
45
45
 
46
46
  /** Why an item is in Today, or null when it is not. `due` is the already-resolved calendar day. */
47
47
  export function todayKind(item: TodayItem, due: string | null, today: string, rule: TodayRule = {}): TodayKind | null {
48
- if (FINISHED.has(item.status) || (item.status === 'blocked' && !rule.includeBlocked)) return null;
48
+ if (!isLiveStatus(item.status) || (item.status === 'blocked' && !rule.includeBlocked)) return null;
49
49
  if (due && due < today) return 'overdue';
50
50
  if (due === today) return 'due_today';
51
51
  if (!due && rule.includeUndatedInProgress && item.status === 'in_progress') return 'in_progress';
@@ -18,6 +18,7 @@ import { daysBetween, WEEK_DAYS } from './due-groups';
18
18
  import { dueDay, localDate } from './today';
19
19
  import { compareCommitments } from './tracker-sort';
20
20
  import type { Commitment, CommitmentSort } from './types';
21
+ import { SUGGESTED_STATUS } from './item-status';
21
22
 
22
23
  /** Subtypes that are things to do. The rest are what was said in the meeting. */
23
24
  const TASK_SUBTYPES = new Set(['action', 'requirement']);
@@ -66,6 +67,8 @@ export function groupTracker<T extends Row>(
66
67
  const due = dueDay(item.dueAt, timeZone);
67
68
  const days = due ? daysBetween(today, due) : null;
68
69
  const entry: TrackerEntry<T> = { item, due, days };
70
+ // A suggestion is not on the list until accepted (bd startsim-vrmx5).
71
+ if (item.status === SUGGESTED_STATUS) continue;
69
72
  if (FINISHED.has(item.status)) { out.done.push(entry); continue; }
70
73
  if (!isTask(item)) { out.statements.push(entry); continue; }
71
74
  if (days !== null && days <= 0) { out.today.push(entry); continue; }
@@ -26,7 +26,7 @@ import type { CommitmentStatus } from './types';
26
26
  const PAGE = 200;
27
27
  /** Distinct stored values in a 90-day window stay far under this; it is a stop, not a target. */
28
28
  const MAX_COUNT_PAGES = 10;
29
- const STATUSES = ['open', 'in_progress', 'done', 'blocked', 'dropped'];
29
+ const STATUSES = ['open', 'in_progress', 'done', 'blocked', 'dropped', 'suggested'];
30
30
 
31
31
  export interface TimelineReaderOptions {
32
32
  http: Pick<CorpusHttp, 'get'>;
@@ -135,6 +135,8 @@ export interface SourceDocument {
135
135
  /** Deep link into the vendor, when it has one. */
136
136
  url?: string;
137
137
  participants: PartyRef[];
138
+ /** How many people the source says were there, when participants were not resolved. */
139
+ participantCount?: number;
138
140
  scope: CorpusScope;
139
141
  /** When the connector last wrote this row. Drives the freshness claim. */
140
142
  ingestedAt?: string | null;
@@ -669,7 +671,7 @@ export type CommitmentSubtype = string;
669
671
  * `blocked` — owed, but waiting on something named in `statusReason`.
670
672
  * `dropped` — explicitly abandoned. Not the same as done and must not read as it.
671
673
  */
672
- export type CommitmentStatus = 'open' | 'in_progress' | 'done' | 'blocked' | 'dropped';
674
+ export type CommitmentStatus = 'open' | 'in_progress' | 'done' | 'blocked' | 'dropped' | 'suggested';
673
675
 
674
676
  /**
675
677
  * One time a commitment was talked about.
@@ -835,6 +837,8 @@ export interface Commitment {
835
837
  * on the row; nothing here ever changes `status` by itself.
836
838
  */
837
839
  possiblyDone?: PossiblyDone[];
840
+ /** The engine decision that put this item here, and the owner's review of it (bd startsim-vrmx5). */
841
+ suggestion?: import('./engine/suggestion').Suggestion;
838
842
  firstSeenAt: string | null;
839
843
  lastSeenAt: string | null;
840
844
  /** Which extractor produced it, so a later one can re-derive without orphaning. */
@@ -996,7 +1000,7 @@ export interface CommitmentApi {
996
1000
  */
997
1001
  updateCommitment?(item: Commitment, patch: Partial<Pick<Commitment,
998
1002
  'status' | 'statusReason' | 'ownerName' | 'ownerSub' | 'ownerSubs' | 'dueAt' | 'subtype'
999
- | 'title' | 'detail' | 'resolvedAt' | 'possiblyDone'>> & {
1003
+ | 'title' | 'detail' | 'resolvedAt' | 'possiblyDone' | 'suggestion'>> & {
1000
1004
  /** `private` hides the item from everyone but its owner; `null` makes it shared again. */
1001
1005
  visibility?: 'private' | null;
1002
1006
  /** `null` clears it (undoing a voice-set priority). */
@@ -1308,6 +1312,10 @@ export interface ExtractionRun {
1308
1312
  * overwrites it with the adopter's freshly proven scope.
1309
1313
  */
1310
1314
  scope: CorpusScope;
1315
+ /** A scheduled run reads only documents that arrived after this (bd startsim-vrmx5). */
1316
+ since?: string | null;
1317
+ /** Sources this run does not read. */
1318
+ skipSources?: string[];
1311
1319
  status: ExtractionRunStatus;
1312
1320
  /**
1313
1321
  * The next document offset to process. THE resumption mechanism: a sweep
@@ -1434,6 +1442,8 @@ export interface ExtractionResult {
1434
1442
  classifyFailure?: ExtractionModelFailure | null;
1435
1443
  /** New items the team classifier placed. Absent when it did not run. */
1436
1444
  teamsPlaced?: number;
1445
+ /** What the engine's policy did with this call's new items, when it ran (bd startsim-vrmx5). */
1446
+ engine?: { acted: number; proposed: number; skipped: Partial<Record<string, number>> };
1437
1447
  }
1438
1448
 
1439
1449
  /**
@@ -84,7 +84,7 @@ export function ConnectClaudeScreen({ controller }: { controller: ConnectClaudeC
84
84
  </View>
85
85
  </Section>
86
86
  <Alert variant="notice" title="Before you create this">
87
- It reads this workspace as you: whatever you can see, it can see. It is shown once and cannot be retrieved again, and it cannot be cancelled before it expires. Turning off your access to the workspace stops new ones being made; it does not switch this one off.
87
+ It reads this workspace as you: whatever you can see, it can see. It can also add, move and delete events on your connected calendar. It is shown once and cannot be retrieved again, and it cannot be cancelled before it expires. Turning off your access to the workspace stops new ones being made; it does not switch this one off.
88
88
  </Alert>
89
89
  {s.error ? <Alert variant="destructive">{s.error}</Alert> : null}
90
90
  <Button testID="connect-claude-create" title={s.minting ? 'Creating...' : 'Create connection token'} size="lg" disabled={!s.selected || s.minting} onPress={() => { void controller.mint(); }} />
@@ -61,7 +61,7 @@ export function createFakeMcpTokensApi(options: FakeMcpTokensOptions = {}): Fake
61
61
  expires_at: new Date(issued + ttl * 86_400_000).toISOString(),
62
62
  mcp_url: foundry.mcp_url,
63
63
  claude_code_command: `claude mcp add --transport http ${foundry.slug} ${foundry.mcp_url} --header "Authorization: Bearer fake-mcp-token-${minted}"`,
64
- notice: 'This token is shown once. It reads this workspace as you and can be revoked from the list.',
64
+ notice: 'This token is shown once. It reads this workspace as you, can add and change events on your connected calendar, and can be revoked from the list.',
65
65
  };
66
66
  },
67
67
  async listTokens(): Promise<McpIssuedToken[]> {
@@ -67,7 +67,7 @@ const PRIORITY = ['Critical', 'High', 'Medium', 'Low', 'Backlog'];
67
67
  export const priorityText = (p?: number): string | null => (p === undefined || p === null ? null : PRIORITY[p] ?? null);
68
68
 
69
69
  export function statusText(status: CommitmentStatus): string {
70
- return { open: 'Open', in_progress: 'In progress', blocked: 'Blocked', done: 'Done', dropped: 'Dropped' }[status] ?? status;
70
+ return { open: 'Open', in_progress: 'In progress', blocked: 'Blocked', done: 'Done', dropped: 'Dropped', suggested: 'Suggested' }[status] ?? status;
71
71
  }
72
72
 
73
73
  /**