@startsimpli/integrations 0.2.224 → 0.2.225

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@startsimpli/integrations",
3
- "version": "0.2.224",
3
+ "version": "0.2.225",
4
4
  "description": "Provider-agnostic types, API clients, hooks, and UI primitives for email + calendar integrations across StartSimpli apps, plus foundry customer email (subpath ./comms).",
5
5
  "license": "MIT",
6
6
  "homepage": "https://startsimpli.com",
@@ -50,9 +50,9 @@
50
50
  "react-native": ">=0.74.0",
51
51
  "@startsimpli/ui-native": ">=0.1.12",
52
52
  "react-native-safe-area-context": ">=4.0.0",
53
- "@startsimpli/ui": "^0.4.211",
54
53
  "@startsimpli/auth": "^0.4.64",
55
- "@startsimpli/utils": "^0.4.23"
54
+ "@startsimpli/utils": "^0.4.23",
55
+ "@startsimpli/ui": "^0.4.211"
56
56
  },
57
57
  "peerDependenciesMeta": {
58
58
  "react": {
@@ -0,0 +1,51 @@
1
+ // @vitest-environment node
2
+ /** Importance score (bd startsim-nd3qa.2): money, outward-facing and only-he-can-provide push an item up; call-me counts only important ones. */
3
+ import { describe, expect, it } from 'vitest';
4
+ import { ATTENTION_DEFAULTS, buildNeedsYou, importanceOf, itemId, resolveAttentionPolicy } from '../corpus/attention';
5
+
6
+ const P = ATTENTION_DEFAULTS;
7
+ const it_ = (text: string, source: 'fleet' | 'decision' = 'fleet') => ({ id: itemId(text), text, source });
8
+ const queue = (waiting: string[], policy = P) => buildNeedsYou({ view: { waitingOnQuinn: waiting }, decisions: [], policy });
9
+
10
+ describe('importanceOf', () => {
11
+ it('urgent is always the top score', () => { expect(importanceOf(it_('URGENT: prod is down'), 'urgent', P)).toBe(100); });
12
+ it('a plain needs-answer line scores low; money, outward-facing and only-he-can-provide each raise it', () => {
13
+ const plain = importanceOf(it_('Which colour for the button?'), 'needs-answer', P);
14
+ const money = importanceOf(it_('Approve the $400 invoice refund'), 'needs-answer', P);
15
+ const outward = importanceOf(it_('Send the launch email to customers'), 'needs-answer', P);
16
+ const onlyYou = importanceOf(it_('Need your Stripe API key'), 'needs-answer', P);
17
+ expect(plain).toBeLessThan(P.callMeMinImportance);
18
+ for (const s of [money, outward, onlyYou]) { expect(s).toBeGreaterThan(plain); expect(s).toBeGreaterThanOrEqual(P.callMeMinImportance); }
19
+ });
20
+ it('signals stack but never reach urgent; digest and noise stay below needs-answer', () => {
21
+ const all = importanceOf(it_('Pay the $900 invoice and email customers; need your approval'), 'needs-answer', P);
22
+ expect(all).toBeGreaterThan(60); expect(all).toBeLessThan(100);
23
+ expect(importanceOf(it_('Optional: send the newsletter'), 'digest', P)).toBeLessThan(P.callMeMinImportance);
24
+ expect(importanceOf(it_('FYI'), 'noise', P)).toBe(0);
25
+ });
26
+ it('a pending decision is something only he can answer', () => {
27
+ expect(importanceOf(it_('Which build goes first?', 'decision'), 'needs-answer', P)).toBeGreaterThanOrEqual(P.callMeMinImportance);
28
+ });
29
+ it('the patterns and threshold come from the policy', () => {
30
+ const custom = resolveAttentionPolicy({ moneyPatterns: ['\\bwidgets\\b'] });
31
+ expect(importanceOf(it_('Order more widgets'), 'needs-answer', custom)).toBeGreaterThan(importanceOf(it_('Order more widgets'), 'needs-answer', P));
32
+ });
33
+ });
34
+
35
+ describe('queue: ordered by importance; call-me counts only the important', () => {
36
+ it('orders by importance score, urgent first', () => {
37
+ const q = queue(['Pick a colour', 'Send the launch email to customers', 'Pay the $900 invoice, need your approval', 'URGENT: checkout is down']);
38
+ expect(q.items.map((i) => i.text)[0]).toMatch(/URGENT/);
39
+ const scores = q.items.map((i) => i.importance);
40
+ expect(scores).toEqual([...scores].sort((a, b) => b - a));
41
+ expect(q.items[q.items.length - 1].text).toBe('Pick a colour');
42
+ });
43
+ it('three trivial questions do not trigger call-me; three important ones do', () => {
44
+ expect(queue(['Pick a colour', 'Pick a font', 'Pick an icon']).callMe).toBe(false);
45
+ const q = queue(['Send the launch email to customers', 'Pay the $900 invoice', 'Need your Stripe key']);
46
+ expect(q.callMe).toBe(true); expect(q.waiting).toBe(3);
47
+ });
48
+ it('lowering the threshold to 0 counts everything, like before', () => {
49
+ expect(queue(['Pick a colour', 'Pick a font', 'Pick an icon'], resolveAttentionPolicy({ callMeMinImportance: 0 })).callMe).toBe(true);
50
+ });
51
+ });
@@ -73,16 +73,16 @@ describe('buildNeedsYou', () => {
73
73
  it('queues fleet bullets and pending decisions, urgent first, noise dropped, ids stable', () => {
74
74
  const q = buildNeedsYou({ view: view(LOOPS('Approve staging promote', 'FYI merged', 'TEST: urgent sample B, no action needed')), decisions: [{ id: 'dec-0001', title: 'Pick a colour', status: 'pending', created_at: '' }], policy: P });
75
75
  expect(q.items.map((i) => i.class)).toEqual(['urgent', 'needs-answer', 'needs-answer']);
76
- expect(q.items.map((i) => i.text)).toEqual(['TEST: urgent sample B, no action needed', 'Pick a colour', 'Approve staging promote']);
76
+ expect(q.items.map((i) => i.text)).toEqual(['TEST: urgent sample B, no action needed', 'Approve staging promote', 'Pick a colour']);
77
77
  expect(q.items[0].id).toBe(itemId('TEST: urgent sample B, no action needed'));
78
78
  expect(q.counts).toEqual({ urgent: 1, 'needs-answer': 2, digest: 0, noise: 1 });
79
79
  });
80
80
  it('callMe turns on at the threshold of waiting items (urgent included)', () => {
81
- const two = buildNeedsYou({ view: view(LOOPS('a one', 'a two')), decisions: [], policy: P });
81
+ const two = buildNeedsYou({ view: view(LOOPS('Pay invoice one', 'Pay invoice two')), decisions: [], policy: P });
82
82
  expect(two.callMe).toBe(false);
83
- const three = buildNeedsYou({ view: view(LOOPS('a one', 'a two', 'a three')), decisions: [], policy: P });
83
+ const three = buildNeedsYou({ view: view(LOOPS('Pay invoice one', 'Pay invoice two', 'Pay invoice three')), decisions: [], policy: P });
84
84
  expect(three.callMe).toBe(true);
85
- expect(buildNeedsYou({ view: view(LOOPS('a one', 'a two', 'a three')), decisions: [], policy: resolveAttentionPolicy({ callMeAt: 4 }) }).callMe).toBe(false);
85
+ expect(buildNeedsYou({ view: view(LOOPS('Pay invoice one', 'Pay invoice two', 'Pay invoice three')), decisions: [], policy: resolveAttentionPolicy({ callMeAt: 4 }) }).callMe).toBe(false);
86
86
  });
87
87
  it('an item id is the same however the line is spaced or cased', () => {
88
88
  expect(itemId('Approve the PR ')).toBe(itemId('approve the pr'));
@@ -119,7 +119,7 @@ describe('runAttention: push on a fleet snapshot', () => {
119
119
  });
120
120
  it('sends one call-me ping when enough are waiting, and only once for that same set', async () => {
121
121
  const { deps, sent } = setup();
122
- const v = view(LOOPS('a one', 'a two', 'a three'));
122
+ const v = view(LOOPS('Pay invoice one', 'Pay invoice two', 'Pay invoice three'));
123
123
  const out = await runAttention(deps, { view: v, now });
124
124
  expect(out.pushed.map((p) => p.reason)).toEqual(['call-me']);
125
125
  expect(sent[0]).toMatchObject({ title: expect.stringMatching(/3/), data: { kind: 'attention' } });
@@ -129,12 +129,12 @@ describe('runAttention: push on a fleet snapshot', () => {
129
129
  it('quiet hours hold needs-answer and call-me, but urgent goes through', async () => {
130
130
  const { deps, sent } = setup();
131
131
  const quiet = at('2026-11-20T08:00:00Z'); // 00:00 PST
132
- const v = view(LOOPS('a one', 'a two', 'a three'));
132
+ const v = view(LOOPS('Pay invoice one', 'Pay invoice two', 'Pay invoice three'));
133
133
  const { setSettings } = await import('../corpus/notify');
134
134
  await setSettings(deps, { attention: { quiet_mode: 'auto' } });
135
135
  expect((await runAttention(deps, { view: v, now: quiet })).pushed).toEqual([]);
136
136
  expect(sent).toHaveLength(0);
137
- const u = view(LOOPS('TEST: urgent sample D', 'a two', 'a three'));
137
+ const u = view(LOOPS('TEST: urgent sample D', 'Pay invoice two', 'Pay invoice three'));
138
138
  expect((await runAttention(deps, { view: u, now: quiet })).pushed.map((p) => p.reason)).toEqual(['urgent']);
139
139
  });
140
140
  it('sends nothing when the queue is empty', async () => {
@@ -81,8 +81,8 @@ function tenant() {
81
81
 
82
82
  describe('the stored run', () => {
83
83
  it('starts from the real queue, records answers into the queue, and answered items leave it', async () => {
84
- const { deps, fleet } = tenant();
85
- fleet('TEST: urgent sample A, no action needed', 'TEST: sample B', 'TEST: sample C');
84
+ const { deps } = tenant();
85
+ for (const t of ['TEST: urgent sample A, no action needed', 'TEST: sample B', 'TEST: sample C']) await createDecision(deps, { title: t, questions: ['TEST: ok?'] });
86
86
  const run = createAttentionRun(deps);
87
87
  const start = await run.start('conv-0001');
88
88
  expect(start).toMatchObject({ active: true, of: 3 });
@@ -92,13 +92,22 @@ describe('the stored run', () => {
92
92
  expect(second!.text).toContain('Question 2 of 3');
93
93
  const st = await loadState(deps);
94
94
  expect(Object.keys(st.answered ?? {})).toHaveLength(1);
95
- const q = buildNeedsYou({ view: buildFleetView({ loops: '## Waiting on Quinn\n- TEST: urgent sample A, no action needed\n- TEST: sample B\n- TEST: sample C\n' }), decisions: [], policy: policyFrom(st.attention), answered: st.answered });
96
- expect(q.items.map((i) => i.text)).toEqual(['TEST: sample B', 'TEST: sample C']);
95
+ const q = buildNeedsYou({ view: null, decisions: st.decisions.filter((d) => d.status === 'pending'), policy: policyFrom(st.attention), answered: st.answered });
96
+ expect(q.items.map((i) => i.text)).toEqual(expect.arrayContaining(['TEST: sample B', 'TEST: sample C']));
97
+ expect(q.items.map((i) => i.text)).not.toContain('TEST: urgent sample A, no action needed');
97
98
  await run.answer('conv-0001', 'no');
98
99
  const last = await run.answer('conv-0001', 'skip');
99
100
  expect(last).toMatchObject({ active: false });
100
101
  expect(await run.answer('conv-0001', 'yes')).toBeNull();
101
102
  });
103
+ it('plain fleet lines are never asked (no yes/no on prose); they stay in the queue', async () => {
104
+ const { deps, fleet } = tenant();
105
+ fleet('Who owns the site?', 'Approve the staging promote');
106
+ expect(await createAttentionRun(deps).start('conv-0005')).toMatchObject({ text: 'Nothing is waiting on you right now.', active: false });
107
+ const st = await loadState(deps);
108
+ const q = buildNeedsYou({ view: buildFleetView({ loops: '## Waiting on Quinn\n- Who owns the site?\n- Approve the staging promote\n' }), decisions: [], policy: policyFrom(st.attention) });
109
+ expect(q.items).toHaveLength(2);
110
+ });
102
111
  it('an answer to a one-question decision is delivered to that decision', async () => {
103
112
  const { deps } = tenant();
104
113
  const made = await createDecision(deps, { title: 'TEST: sample decision, pick a colour', questions: ['TEST: blue or green?'] });
@@ -115,8 +124,8 @@ describe('the stored run', () => {
115
124
  expect(await createAttentionRun(deps).start('conv-0003')).toMatchObject({ text: 'Nothing is waiting on you right now.', active: false });
116
125
  });
117
126
  it('asks only a batch at a time, most important first', async () => {
118
- const { deps, fleet } = tenant();
119
- fleet(...Array.from({ length: 8 }, (_, i) => `TEST: sample ${i + 1}`));
127
+ const { deps } = tenant();
128
+ for (let i = 1; i <= 8; i += 1) await createDecision(deps, { title: `TEST: sample ${i}`, questions: ['TEST: ok?'] });
120
129
  const start = await createAttentionRun(deps, { batch: 3 }).start('conv-0004');
121
130
  expect(start).toMatchObject({ of: 3 });
122
131
  });
@@ -67,15 +67,15 @@ describe('runAttention uses the saved settings', () => {
67
67
  it('manual quiet on holds the call-me but urgent still goes through', async () => {
68
68
  const { deps, sent } = setup();
69
69
  await setSettings(deps, { attention: { quiet_mode: 'on' } });
70
- await runAttention(deps, { view: view('a one', 'a two', 'a three') });
70
+ await runAttention(deps, { view: view('Pay invoice one', 'Pay invoice two', 'Pay invoice three') });
71
71
  expect(sent).toHaveLength(0);
72
- await runAttention(deps, { view: view('TEST: urgent sample D', 'a two', 'a three') });
72
+ await runAttention(deps, { view: view('TEST: urgent sample D', 'Pay invoice two', 'Pay invoice three') });
73
73
  expect(sent.map((m) => m.title)).toEqual([expect.stringContaining('TEST: urgent sample D')]);
74
74
  });
75
75
  it('quiet off pushes the call-me at night; a saved urgent word pushes; a raised threshold holds', async () => {
76
76
  const { deps, sent } = setup();
77
77
  await setSettings(deps, { attention: { quiet_mode: 'off', urgent_words: ['overdue'] } });
78
- await runAttention(deps, { view: view('a one', 'a two', 'a three'), now: NIGHT });
78
+ await runAttention(deps, { view: view('Pay invoice one', 'Pay invoice two', 'Pay invoice three'), now: NIGHT });
79
79
  expect(sent).toHaveLength(1);
80
80
  await runAttention(deps, { view: view('Invoice overdue'), now: NIGHT });
81
81
  expect(sent).toHaveLength(2);
@@ -9,9 +9,24 @@ describe('normalizeAssistantName: the assistant is Roci; there is no wake word',
9
9
  expect(normalizeAssistantName('ROSSI what is on my plate')).toBe('Roci what is on my plate');
10
10
  });
11
11
  it('leaves Rocky, Roxy, Rosie (real names and words) and words that merely contain Rossi alone', () => {
12
- const same = ['Rocky, read my brief', 'book the Rocky Mountain trip', 'Roxy called', 'ask Rosie', 'Rossiter and the Rossini deal'];
12
+ const same = ['book the Rocky Mountain trip', 'Roxy called', 'ask Rosie', 'Rossiter and the Rossini deal'];
13
13
  for (const t of same) expect(normalizeAssistantName(t)).toBe(t);
14
14
  });
15
+ it('turns the non-words the transcriber produces (Rochie, Rochi, Rossie) into Roci', () => {
16
+ expect(normalizeAssistantName('Rochie, what is due?')).toBe('Roci, what is due?');
17
+ expect(normalizeAssistantName('hey rochi read my brief')).toBe('hey Roci read my brief');
18
+ expect(normalizeAssistantName('Rossie are you there')).toBe('Roci are you there');
19
+ });
20
+ it('turns Rosie/Rocky into Roci ONLY when addressed (opening the utterance with a comma, or after hey/hi/ok/okay)', () => {
21
+ expect(normalizeAssistantName('Rosie, what is due today?')).toBe('Roci, what is due today?');
22
+ expect(normalizeAssistantName('Rocky what is due')).toBe('Rocky what is due');
23
+ expect(normalizeAssistantName('hey Rosie what is due')).toBe('hey Roci what is due');
24
+ expect(normalizeAssistantName('okay Rocky, read the brief')).toBe('okay Roci, read the brief');
25
+ expect(normalizeAssistantName('Ok, Rosie. Read it')).toBe('Ok, Roci. Read it');
26
+ });
27
+ it('leaves Rosie/Rocky alone when they are plainly someone else', () => {
28
+ for (const t of ['Tell Rosie, the dog is out', 'I saw Rocky yesterday', 'Rosie called me', 'meet with Rosie Rocky and Roxy']) expect(normalizeAssistantName(t)).toBe(t);
29
+ });
15
30
  it('leaves Roci and empty text alone', () => {
16
31
  expect(normalizeAssistantName('Roci is here')).toBe('Roci is here');
17
32
  expect(normalizeAssistantName('')).toBe('');
@@ -0,0 +1,89 @@
1
+ // @vitest-environment node
2
+ /** The relay's own feed into the needs-you queue, and the answers back to it (bd startsim-nd3qa). */
3
+ import { describe, expect, it, vi } from 'vitest';
4
+ import { createAttentionRun } from '../corpus/attention/run';
5
+ import { buildNeedsYou, policyFrom } from '../corpus/attention';
6
+ import { postRelayItems, relayAnswers } from '../corpus/notify/relay-items';
7
+ import { loadState, saveState } from '../corpus/notify/state';
8
+ import { startRun } from '../corpus/attention/run-steps';
9
+
10
+ const NOW = '2026-11-20T00:00:00Z';
11
+ function tenant() {
12
+ const rows = new Map<string, any>();
13
+ let seq = 0;
14
+ const http = {
15
+ get: vi.fn(async (_p: string, o?: { params?: Record<string, unknown> }) => ({ results: [...rows.values()].filter((r) => r.external_id === o?.params?.external_id__in) })),
16
+ post: vi.fn(async (_p: string, b: any) => { const row = { id: String(++seq), external_id: b.external_id, data: b.data }; rows.set(b.external_id, row); return row; }),
17
+ };
18
+ return { deps: { http: http as never, ownerSub: 'me', now: () => Date.parse(NOW), newId: () => `generated-${++seq}` }, rows };
19
+ }
20
+ const Q1 = { id: 'prod-mail-poll', text: 'Should Google and Microsoft mail and calendar get scheduled polling on production?', source: 'Tandem sources' };
21
+ const Q2 = { id: 'local-scheduler', text: 'Should your local Tandem also run a scheduler for them, or stay manual?', options: ['schedule', 'manual'], source: 'Tandem sources' };
22
+
23
+ describe('posting relay items', () => {
24
+ it('stores them, idempotent by id: the same post twice is still two items; a changed text updates in place', async () => {
25
+ const { deps } = tenant();
26
+ await postRelayItems(deps, { items: [Q1, Q2] });
27
+ await postRelayItems(deps, { items: [Q1, { ...Q2, text: 'Should your local Tandem also run a scheduler?' }] });
28
+ const st = await loadState(deps);
29
+ expect(st.relay_items?.map((i) => i.id)).toEqual(['prod-mail-poll', 'local-scheduler']);
30
+ expect(st.relay_items?.[1].text).toBe('Should your local Tandem also run a scheduler?');
31
+ });
32
+ it('rejects a bad id or an empty question (400) and keeps what was stored', async () => {
33
+ const { deps } = tenant();
34
+ await expect(postRelayItems(deps, { items: [{ id: 'x y', text: 'ok question here' }] })).rejects.toMatchObject({ status: 400 });
35
+ await expect(postRelayItems(deps, { items: [{ id: 'good-id', text: ' ' }] })).rejects.toMatchObject({ status: 400 });
36
+ await expect(postRelayItems(deps, { items: 'nope' as never })).rejects.toMatchObject({ status: 400 });
37
+ });
38
+ it('an answered item is not re-opened by a repeated post, and can be removed by id', async () => {
39
+ const { deps } = tenant();
40
+ await postRelayItems(deps, { items: [Q1] });
41
+ const st = await loadState(deps);
42
+ await saveState(deps, { ...st, answered: { 'relay:prod-mail-poll': { answer: 'yes', at: NOW, conversation_id: 'c-1', source: 'relay' } } });
43
+ await postRelayItems(deps, { items: [Q1, Q2] });
44
+ const answers = await relayAnswers(deps);
45
+ expect(answers.find((a) => a.id === 'prod-mail-poll')).toMatchObject({ answered: true, answer: 'yes' });
46
+ expect(answers.find((a) => a.id === 'local-scheduler')).toMatchObject({ answered: false });
47
+ await postRelayItems(deps, { remove: ['local-scheduler'] });
48
+ expect((await relayAnswers(deps)).map((a) => a.id)).toEqual(['prod-mail-poll']);
49
+ });
50
+ });
51
+
52
+ describe('the queue and the briefing', () => {
53
+ it('relay items are needs-answer (never urgent, even with an urgent-sounding word), listed with their source, and leave when answered', () => {
54
+ const policy = policyFrom(undefined);
55
+ const relay = [{ id: 'a-1', text: 'This is urgent: should we ship it?', source: 'Tandem sources', at: NOW }];
56
+ const q = buildNeedsYou({ view: null, decisions: [], policy, relay });
57
+ expect(q.items).toHaveLength(1);
58
+ expect(q.items[0]).toMatchObject({ id: 'relay:a-1', class: 'needs-answer', source: 'relay', from: 'Tandem sources' });
59
+ expect(q.counts.urgent).toBe(0);
60
+ expect(buildNeedsYou({ view: null, decisions: [], policy, relay, answered: { 'relay:a-1': {} } }).items).toHaveLength(0);
61
+ });
62
+ it('a choice item is asked with its options, not "yes or no"', () => {
63
+ const { reply } = startRun({ conversationId: 'conv-0001', items: [{ id: 'relay:l', text: Q2.text, options: ['schedule', 'manual'] }], now: NOW });
64
+ expect(reply.text).toContain('Say schedule or manual.');
65
+ expect(reply.text).not.toContain('Yes or no');
66
+ });
67
+ it('his voice answer to a relay item is stored AND handed to the delivery hook once', async () => {
68
+ const { deps } = tenant();
69
+ await postRelayItems(deps, { items: [Q1] });
70
+ const delivered: Array<{ id: string; answer: string; text: string }> = [];
71
+ const run = createAttentionRun(deps, { deliverRelay: async (a) => { delivered.push({ id: a.id, answer: a.answer, text: a.text }); } });
72
+ const start = await run.start('conv-0001');
73
+ expect(start!.text).toContain('Question 1 of 1');
74
+ const done = await run.answer('conv-0001', 'yes');
75
+ expect(done!.text).toContain('That was the last one.');
76
+ expect(delivered).toEqual([{ id: 'prod-mail-poll', answer: 'yes', text: Q1.text }]);
77
+ expect((await relayAnswers(deps))[0]).toMatchObject({ answered: true, answer: 'yes', delivered: true });
78
+ // a second start finds nothing waiting
79
+ expect((await run.start('conv-0002'))!.text).toBe('Nothing is waiting on you right now.');
80
+ });
81
+ it('a failing delivery does not lose the answer: it stays stored, marked undelivered, for the relay to read back', async () => {
82
+ const { deps } = tenant();
83
+ await postRelayItems(deps, { items: [Q1] });
84
+ const run = createAttentionRun(deps, { deliverRelay: async () => { throw new Error('bridge down'); } });
85
+ await run.start('conv-0001');
86
+ await run.answer('conv-0001', 'no');
87
+ expect((await relayAnswers(deps))[0]).toMatchObject({ answered: true, answer: 'no', delivered: false });
88
+ });
89
+ });
@@ -0,0 +1,17 @@
1
+ /** Importance score 0-100 (bd startsim-nd3qa.2). Pure. Urgent is 100; noise 0; the rest is a base by class plus what the item touches. */
2
+ import type { AttentionClass, AttentionItem, AttentionPolicy } from './types';
3
+
4
+ const BASE: Record<AttentionClass, number> = { urgent: 100, 'needs-answer': 20, digest: 5, noise: 0 };
5
+ const compile = (sources: string[]): RegExp[] => sources.flatMap((s) => { try { return [new RegExp(s, 'i')]; } catch { return []; } });
6
+ const hits = (sources: string[], text: string) => compile(sources).some((r) => r.test(text));
7
+
8
+ export function importanceOf(item: AttentionItem, cls: AttentionClass, policy: AttentionPolicy): number {
9
+ if (cls === 'urgent' || cls === 'noise') return BASE[cls];
10
+ const w = policy.importanceWeights;
11
+ let score = BASE[cls];
12
+ if (hits(policy.moneyPatterns, item.text)) score += w.money;
13
+ if (hits(policy.outwardPatterns, item.text)) score += w.outward;
14
+ if (item.source === 'decision' || hits(policy.onlyYouPatterns, item.text)) score += w.onlyYou;
15
+ // A digest line waits for the daily brief however much it touches; it never reaches the call-me threshold.
16
+ return Math.min(score, cls === 'digest' ? Math.max(0, policy.callMeMinImportance - 1) : 95);
17
+ }
@@ -1,6 +1,7 @@
1
1
  export * from './types';
2
2
  export { classifyItem, inQuietHours, isQuiet, type QuietMode, itemId, resolveAttentionPolicy } from './policy';
3
3
  export { buildNeedsYou } from './queue';
4
+ export { importanceOf } from './importance';
4
5
  export { callMeTitle, runAttention, type AttentionPush } from './push';
5
6
  export { mergeAttention, policyFrom, settingsView, type AttentionSettings as AttentionSettingsValues, type StoredAttention } from './settings';
6
7
  export { createAttentionController, quietSummary, type AttentionController, type AttentionState } from './controller';
@@ -5,13 +5,15 @@ export function resolveAttentionPolicy(over: AttentionPolicyInput = {}): Attenti
5
5
  const d = ATTENTION_DEFAULTS;
6
6
  return {
7
7
  ...d, ...over,
8
- quiet: { ...d.quiet, ...over.quiet }, brief: { ...d.brief, ...over.brief }, wrap: { ...d.wrap, ...over.wrap },
8
+ quiet: { ...d.quiet, ...over.quiet }, importanceWeights: { ...d.importanceWeights, ...over.importanceWeights }, brief: { ...d.brief, ...over.brief }, wrap: { ...d.wrap, ...over.wrap },
9
9
  };
10
10
  }
11
11
 
12
12
  const compile = (sources: string[]): RegExp[] => sources.flatMap((s) => { try { return [new RegExp(s, 'i')]; } catch { return []; } });
13
13
 
14
14
  export function classifyItem(item: AttentionItem, policy: AttentionPolicy): AttentionClass {
15
+ // The relay asks a question and waits for his answer: it never interrupts (needs-answer), whatever words the question has.
16
+ if (item.source === 'relay') return 'needs-answer';
15
17
  const words = policy.urgentWords.map((w) => w.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).filter(Boolean).map((w) => `(^|[^\\w])${w}($|[^\\w])`);
16
18
  if (compile([...policy.urgentPatterns, ...words]).some((r) => r.test(item.text))) return 'urgent';
17
19
  if (compile(policy.noisePatterns).some((r) => r.test(item.text))) return 'noise';
@@ -24,7 +24,7 @@ export async function runAttention(deps: NotifyDeps, input: { view: Pick<FleetVi
24
24
  const autoAnswered = await answerRoutine(deps, policy);
25
25
  const state = autoAnswered.length ? await loadState(deps) : first;
26
26
  const now = input.now ?? (deps.now ?? Date.now)();
27
- const queue = buildNeedsYou({ view: input.view, decisions: state.decisions, policy, answered: state.answered });
27
+ const queue = buildNeedsYou({ view: input.view, decisions: state.decisions, policy, answered: state.answered, relay: state.relay_items });
28
28
  const pushed: AttentionPush[] = [];
29
29
 
30
30
  for (const it of queue.items.filter((i): i is QueuedItem => i.class === 'urgent')) {
@@ -1,22 +1,26 @@
1
1
  /** The "needs you" queue: the fleet's waiting-on-Quinn lines plus his pending decisions, classified. */
2
2
  import type { FleetView } from '../converse/fleet-view';
3
- import type { DecisionIndexRow } from '../notify/types';
3
+ import type { DecisionIndexRow, RelayItem } from '../notify/types';
4
+ import { importanceOf } from './importance';
4
5
  import { classifyItem, itemId } from './policy';
5
6
  import type { AttentionClass, AttentionItem, AttentionPolicy, NeedsYouQueue, QueuedItem } from './types';
6
7
 
7
8
  const ORDER: AttentionClass[] = ['urgent', 'needs-answer', 'digest', 'noise'];
8
9
  const clean = (s: string) => s.replace(/`|\*\*/g, '').replace(/\s+/g, ' ').trim();
9
10
 
10
- export function buildNeedsYou(input: { view: Pick<FleetView, 'waitingOnQuinn'> | null; decisions: DecisionIndexRow[]; policy: AttentionPolicy; /** Items already answered (by id): they leave the queue. */ answered?: Record<string, unknown> }): NeedsYouQueue {
11
- const raw: AttentionItem[] = [
11
+ export function buildNeedsYou(input: { view: Pick<FleetView, 'waitingOnQuinn'> | null; decisions: DecisionIndexRow[]; policy: AttentionPolicy; /** Items already answered (by id): they leave the queue. */ answered?: Record<string, unknown>; /** Questions the relay posted for him (their own list, never touched by the fleet snapshot). */ relay?: RelayItem[] }): NeedsYouQueue {
12
+ type Raw = Omit<AttentionItem, 'id'> & { id?: string };
13
+ const rawIn: Raw[] = [
14
+ ...(input.relay ?? []).map((r) => ({ id: `relay:${r.id}`, text: clean(r.text), source: 'relay' as const, ...(r.options?.length ? { options: r.options } : {}), ...(r.source ? { from: r.source } : {}), ...(r.link ? { link: r.link } : {}) })),
12
15
  ...input.decisions.filter((d) => d.status === 'pending').map((d) => ({ text: clean(d.title), source: 'decision' as const, ref: d.id })),
13
16
  ...(input.view?.waitingOnQuinn ?? []).map((t) => ({ text: clean(t), source: 'fleet' as const })),
14
- ].filter((i) => i.text).map((i) => ({ ...i, id: itemId(i.text) }));
17
+ ];
18
+ const raw: AttentionItem[] = rawIn.filter((i) => i.text).map((i) => ({ ...i, id: i.id ?? itemId(i.text) }));
15
19
  const seen = new Set<string>(Object.keys(input.answered ?? {}));
16
- const all: QueuedItem[] = raw.filter((i) => !seen.has(i.id) && seen.add(i.id)).map((i) => ({ ...i, class: classifyItem(i, input.policy) }));
20
+ const all: QueuedItem[] = raw.filter((i) => !seen.has(i.id) && seen.add(i.id)).map((i) => { const cls = classifyItem(i, input.policy); return { ...i, class: cls, importance: importanceOf(i, cls, input.policy) }; });
17
21
  const counts: Record<AttentionClass, number> = { urgent: 0, 'needs-answer': 0, digest: 0, noise: 0 };
18
22
  for (const i of all) counts[i.class] += 1;
19
- const items = all.filter((i) => i.class !== 'noise').sort((a, b) => ORDER.indexOf(a.class) - ORDER.indexOf(b.class));
20
- const waiting = counts.urgent + counts['needs-answer'];
23
+ const items = all.filter((i) => i.class !== 'noise').sort((a, b) => b.importance - a.importance || ORDER.indexOf(a.class) - ORDER.indexOf(b.class));
24
+ const waiting = all.filter((i) => (i.class === 'urgent' || i.class === 'needs-answer') && i.importance >= input.policy.callMeMinImportance).length;
21
25
  return { items, counts, callMe: waiting >= input.policy.callMeAt, waiting };
22
26
  }
@@ -3,7 +3,7 @@
3
3
  * answer, records it, moves on, and ends by saying what it did. Pure: the caller stores the run and speaks the text.
4
4
  * Never a chat message: nothing here is ever shown as something the person said.
5
5
  */
6
- export interface RunItem { id: string; text: string; ref?: string }
6
+ export interface RunItem { id: string; text: string; ref?: string; /** A choice instead of yes/no. */ options?: string[] }
7
7
  export interface RunAnswer { answer: string; at: string }
8
8
  export interface AttentionRunState {
9
9
  conversation_id: string;
@@ -38,7 +38,8 @@ export function hear(utterance: string): Heard {
38
38
  const plain = (s: string) => s.replace(/\s+/g, ' ').replace(/[.?!]+$/, '').trim();
39
39
  export const questionText = (run: Pick<AttentionRunState, 'items' | 'index'>): string => {
40
40
  const item = run.items[run.index];
41
- return `Question ${run.index + 1} of ${run.items.length}: ${plain(item.text)}. Yes or no?`;
41
+ const ask = item.options?.length ? `Say ${item.options.length === 2 ? item.options.join(' or ') : `${item.options.slice(0, -1).join(', ')} or ${item.options[item.options.length - 1]}`}.` : 'Yes or no?';
42
+ return `Question ${run.index + 1} of ${run.items.length}: ${plain(item.text)}. ${ask}`;
42
43
  };
43
44
  const reply = (run: AttentionRunState, text: string, recorded?: RunReply['recorded']): RunReply => ({ text, active: run.status === 'asking', index: Math.min(run.index, run.items.length), of: run.items.length, ...(recorded ? { recorded } : {}) });
44
45
 
@@ -15,15 +15,19 @@ export interface AttentionRunApi {
15
15
  answer(conversationId: string, utterance: string): Promise<RunReply | null>;
16
16
  }
17
17
 
18
- export function createAttentionRun(deps: Pick<NotifyDeps, 'http' | 'ownerSub' | 'now'>, opts: { batch?: number } = {}): AttentionRunApi {
18
+ /** What the relay is told when he answers one of its questions. */
19
+ export interface RelayDelivery { id: string; text: string; answer: string; source?: string; link?: string }
20
+
21
+ export function createAttentionRun(deps: Pick<NotifyDeps, 'http' | 'ownerSub' | 'now'>, opts: { batch?: number; /** Tells the relay his answer (the server runs the bridge). A failure keeps the answer stored for the relay to read back. */ deliverRelay?: (d: RelayDelivery) => Promise<void> } = {}): AttentionRunApi {
19
22
  const nowIso = () => new Date((deps.now ?? Date.now)()).toISOString();
20
23
  return {
21
24
  async start(conversationId) {
22
25
  const state = await loadState(deps);
23
26
  const snap = await loadFleetSnapshot(deps as never).catch(() => null);
24
27
  const policy = policyFrom(state.attention);
25
- const queue = buildNeedsYou({ view: snap?.inputs ? buildFleetView(snap.inputs) : null, decisions: state.decisions, policy, answered: state.answered });
26
- const items = queue.items.filter((i) => i.class === 'urgent' || i.class === 'needs-answer').slice(0, opts.batch ?? policy.briefBatch).map((i) => ({ id: i.id, text: i.text, ...(i.ref ? { ref: i.ref } : {}) }));
28
+ const queue = buildNeedsYou({ view: snap?.inputs ? buildFleetView(snap.inputs) : null, decisions: state.decisions, policy, answered: state.answered, relay: state.relay_items });
29
+ // Fleet lines are prose, not questions: they stay in the queue (and still drive pushes) but are never asked as yes/no. The relay posts real questions through relay-items, with options.
30
+ const items = queue.items.filter((i) => i.source !== 'fleet' && (i.class === 'urgent' || i.class === 'needs-answer')).slice(0, opts.batch ?? policy.briefBatch).map((i) => ({ id: i.id, text: i.text, ...(i.ref ? { ref: i.ref } : {}), ...(i.options?.length ? { options: i.options } : {}) }));
27
31
  const { run, reply } = startRun({ conversationId, items, now: nowIso() });
28
32
  await saveState(deps as never, { ...state, attention_run: run });
29
33
  return reply;
@@ -36,7 +40,13 @@ export function createAttentionRun(deps: Pick<NotifyDeps, 'http' | 'ownerSub' |
36
40
  let answered = state.answered;
37
41
  if (reply.recorded) {
38
42
  const { item, answer } = reply.recorded;
39
- let delivered: 'decision' | undefined;
43
+ let delivered: 'decision' | 'relay' | undefined;
44
+ let deliveryFailed = false;
45
+ const relayItem = item.id.startsWith('relay:') ? (state.relay_items ?? []).find((r) => `relay:${r.id}` === item.id) : undefined;
46
+ if (relayItem && opts.deliverRelay) {
47
+ try { await opts.deliverRelay({ id: relayItem.id, text: relayItem.text, answer, ...(relayItem.source ? { source: relayItem.source } : {}), ...(relayItem.link ? { link: relayItem.link } : {}) }); delivered = 'relay'; }
48
+ catch (e) { deliveryFailed = true; console.error('[attention] could not tell the relay his answer (kept for it to read back)', e); }
49
+ }
40
50
  if (item.ref) {
41
51
  // A decision with ONE question takes his answer directly; a longer one is only recorded here.
42
52
  try {
@@ -44,7 +54,7 @@ export function createAttentionRun(deps: Pick<NotifyDeps, 'http' | 'ownerSub' |
44
54
  if (d.questions.length === 1) { await answerDecision(deps as never, item.ref, { answer }); delivered = 'decision'; }
45
55
  } catch (e) { console.error('[attention] could not deliver the answer to its decision', e); }
46
56
  }
47
- answered = { ...state.answered, [item.id]: { answer, at: nowIso(), conversation_id: conversationId, ...(item.ref ? { ref: item.ref } : {}), ...(delivered ? { delivered } : {}) } };
57
+ answered = { ...state.answered, [item.id]: { answer, at: nowIso(), conversation_id: conversationId, ...(item.ref ? { ref: item.ref } : {}), ...(delivered ? { delivered } : {}), ...(relayItem ? { source: 'relay' as const } : {}), ...(deliveryFailed ? { delivery_failed: true } : {}) } };
48
58
  const keys = Object.keys(answered);
49
59
  if (keys.length > 300) answered = Object.fromEntries(keys.slice(-300).map((k) => [k, answered![k]]));
50
60
  }
@@ -4,10 +4,10 @@
4
4
  * approvals ping, self-answering routine questions) are fields here, never constants in the logic.
5
5
  */
6
6
  export type AttentionClass = 'urgent' | 'needs-answer' | 'digest' | 'noise';
7
- export type AttentionSource = 'fleet' | 'decision';
7
+ export type AttentionSource = 'fleet' | 'decision' | 'relay';
8
8
 
9
- export interface AttentionItem { id: string; text: string; source: AttentionSource; /** The decision id, for an item that is a pending decision (opens its card). */ ref?: string }
10
- export interface QueuedItem extends AttentionItem { class: AttentionClass }
9
+ export interface AttentionItem { id: string; text: string; source: AttentionSource; /** The decision id, for an item that is a pending decision (opens its card). */ ref?: string; /** A relay item's choices ("schedule" or "manual"): asked as a choice, not yes/no. */ options?: string[]; /** Who asked, in plain words (a relay item's source project). */ from?: string; /** Where to look at it, when there is somewhere. */ link?: string }
10
+ export interface QueuedItem extends AttentionItem { class: AttentionClass; /** 0-100; urgent 100. Orders the queue and gates call-me. */ importance: number }
11
11
 
12
12
  export interface AttentionPolicy {
13
13
  /** Which waiting items count as "needs you": his decisions only, or the fleet's approvals too. */
@@ -16,6 +16,13 @@ export interface AttentionPolicy {
16
16
  quiet: { enabled: boolean; start: number; end: number; timeZone: string };
17
17
  /** This many waiting items (urgent included) earns one call-me push. */
18
18
  callMeAt: number;
19
+ /** An item must score at least this (see importance.ts) to count toward call-me; urgent always does. 0 counts every waiting item. */
20
+ callMeMinImportance: number;
21
+ /** Case-insensitive RegExp sources for what raises an item's importance: money, outward-facing actions, only he can provide. */
22
+ moneyPatterns: string[];
23
+ outwardPatterns: string[];
24
+ onlyYouPatterns: string[];
25
+ importanceWeights: { money: number; outward: number; onlyYou: number };
19
26
  /** Daily rhythm (slice 5 reads these). */
20
27
  brief: { hour: number };
21
28
  wrap: { hour: number };
@@ -34,14 +41,19 @@ export interface AttentionPolicy {
34
41
  digestPatterns: string[];
35
42
  }
36
43
 
37
- export type AttentionPolicyInput = Partial<Omit<AttentionPolicy, 'quiet' | 'brief' | 'wrap'>> & {
38
- quiet?: Partial<AttentionPolicy['quiet']>; brief?: Partial<AttentionPolicy['brief']>; wrap?: Partial<AttentionPolicy['wrap']>;
44
+ export type AttentionPolicyInput = Partial<Omit<AttentionPolicy, 'quiet' | 'brief' | 'wrap' | 'importanceWeights'>> & {
45
+ quiet?: Partial<AttentionPolicy['quiet']>; brief?: Partial<AttentionPolicy['brief']>; wrap?: Partial<AttentionPolicy['wrap']>; importanceWeights?: Partial<AttentionPolicy['importanceWeights']>;
39
46
  };
40
47
 
41
48
  export const ATTENTION_DEFAULTS: AttentionPolicy = {
42
49
  notifyScope: 'decisions+fleet',
43
50
  quiet: { enabled: true, start: 22, end: 7, timeZone: 'America/Los_Angeles' },
44
51
  callMeAt: 3,
52
+ callMeMinImportance: 40,
53
+ moneyPatterns: ['\\$\\s?\\d', '\\b(pay|paid|payment|invoice|refund|charge[ds]?|billing|bill|subscription|stripe|budget|spend|price|pricing|purchase|buy|wire|payroll|tax(es)?)\\b'],
54
+ outwardPatterns: ['\\b(send|sends|publish|post|announce|launch|ship|deploy|promote|release|merge to main|go live|email|emails|customers?|clients?|investors?|press|tweet|public)\\b'],
55
+ onlyYouPatterns: ['\\b(your|you)\\b.*\\b(approval|approve|sign|signature|password|key|token|credential|login|decision|decide|call)\\b', '\\b(approve|sign off|sign-off|need(s)? (you|him)|only (you|he) can)\\b', '\\b(api key|password|token|credentials?)\\b'],
56
+ importanceWeights: { money: 30, outward: 25, onlyYou: 25 },
45
57
  brief: { hour: 8 },
46
58
  wrap: { hour: 18 },
47
59
  selfAnswerRoutine: true,
@@ -158,7 +158,7 @@ export async function converseFleetViewResponse(deps: ConverseDeps): Promise<Res
158
158
  const snap = await loadFleetSnapshot(deps);
159
159
  const view = snap?.inputs ? buildFleetView(snap.inputs) : null;
160
160
  const state = await loadState(deps);
161
- const needs_you = buildNeedsYou({ view, decisions: state.decisions, policy: policyFrom(state.attention), answered: state.answered });
161
+ const needs_you = buildNeedsYou({ view, decisions: state.decisions, policy: policyFrom(state.attention), answered: state.answered, relay: state.relay_items });
162
162
  const body = snap
163
163
  ? { snapshot: { text: snap.text, updatedAt: snap.updatedAt, view, todoSync: parseTodoSyncRecord(snap.inputs?.todo_sync) }, needs_you }
164
164
  : { snapshot: null, needs_you };
@@ -1,13 +1,20 @@
1
1
  /**
2
2
  * THE ASSISTANT'S NAME. It is Roci. There is no wake word: nothing listens for the name. But Quinn types it the way it
3
3
  * sounds, "Rossi". Normalised on the way IN, before the model sees the text, so the assistant is never confused about
4
- * who it is being asked. ONLY "Rossi" (whole word): Rocky, Roxy and Rosie can be real names or other words, so they are
5
- * left exactly as written.
4
+ * who it is being asked. Rosie and Rocky can be real names, so they change only when plainly addressed (see below);
5
+ * Roxy and words merely containing Rossi are left exactly as written.
6
6
  */
7
7
  export const ASSISTANT_NAME = 'Roci';
8
8
 
9
- const ROSSI = /\brossi\b/gi;
9
+ /** Always Roci: "Rossi" is how it sounds typed; Rochie/Rochi/Rossie are what the transcriber writes and are not words. */
10
+ const ALWAYS = /\b(?:rossi|rossie|rochie|rochi)\b/gi;
11
+ /** Rosie and Rocky are real names: Roci only when the utterance opens with it plus a comma, or follows hey/hi/ok/okay. */
12
+ const ADDRESSED_OPENER = /^\s*(?:rosie|rocky)\s*,/i;
13
+ const AFTER_HELLO = /\b((?:hey|hi|ok|okay)[\s,]+)(?:rosie|rocky)\b/gi;
10
14
 
11
15
  export function normalizeAssistantName(text: string, name: string = ASSISTANT_NAME): string {
12
- return text ? text.replace(ROSSI, name) : text;
16
+ if (!text) return text;
17
+ let out = text.replace(ALWAYS, name).replace(AFTER_HELLO, (_m, hello: string) => hello + name);
18
+ if (ADDRESSED_OPENER.test(out)) out = out.replace(/^(\s*)(?:rosie|rocky)\b/i, (_m, lead: string) => lead + name);
19
+ return out;
13
20
  }
@@ -5,3 +5,5 @@ export type { NotifyRequest, NotifyResult, CreateDecisionRequest } from './handl
5
5
  export * from './respond';
6
6
  export { createNotifyClient, NotifyClientError } from './client';
7
7
  export type { NotifyClient } from './client';
8
+ export { postRelayItems, relayAnswers } from './relay-items';
9
+ export type { RelayAnswer } from './relay-items';
@@ -0,0 +1,53 @@
1
+ /** The relay's own feed into the needs-you queue, and the answers read back. Request-free: a Next route and a test call these. */
2
+ import { loadState, saveState } from './state';
3
+ import { NotifyError, type NotifyDeps, type RelayItem } from './types';
4
+
5
+ const ID = /^[A-Za-z0-9_-]{3,64}$/;
6
+ const MAX_ITEMS = 100;
7
+ const clip = (s: unknown, n: number) => String(s ?? '').replace(/\s+/g, ' ').trim().slice(0, n);
8
+
9
+ export interface RelayItemInput { id?: unknown; text?: unknown; options?: unknown; source?: unknown; link?: unknown }
10
+
11
+ /** Adds or updates questions by id (idempotent: the same post twice is the same list) and removes the ones named in `remove`. An answered id is never reopened. */
12
+ export async function postRelayItems(deps: NotifyDeps, req: { items?: unknown; remove?: unknown }) {
13
+ if (req.items !== undefined && !Array.isArray(req.items)) throw new NotifyError('items must be a list.', 400);
14
+ if (req.remove !== undefined && !Array.isArray(req.remove)) throw new NotifyError('remove must be a list of ids.', 400);
15
+ const incoming: RelayItem[] = [];
16
+ for (const raw of (req.items ?? []) as RelayItemInput[]) {
17
+ const id = String(raw?.id ?? '');
18
+ const text = clip(raw?.text, 400);
19
+ if (!ID.test(id)) throw new NotifyError('Each item needs an id of 3-64 letters, digits, - or _.', 400);
20
+ if (text.length < 3) throw new NotifyError(`Item ${id} needs a plain-language question.`, 400);
21
+ const options = Array.isArray(raw.options) ? raw.options.map((o) => clip(o, 40)).filter(Boolean).slice(0, 6) : [];
22
+ const link = clip(raw.link, 300);
23
+ const source = clip(raw.source, 60);
24
+ incoming.push({ id, text, at: new Date((deps.now ?? Date.now)()).toISOString(), ...(options.length ? { options } : {}), ...(source ? { source } : {}), ...(/^https?:\/\//.test(link) ? { link } : {}) });
25
+ }
26
+ const state = await loadState(deps);
27
+ const drop = new Set((req.remove ?? []).map(String));
28
+ let items = (state.relay_items ?? []).filter((i) => !drop.has(i.id));
29
+ for (const item of incoming) {
30
+ if (state.answered?.[`relay:${item.id}`]) continue;
31
+ const at = items.findIndex((i) => i.id === item.id);
32
+ if (at >= 0) items[at] = { ...item, at: items[at].at };
33
+ else items.push(item);
34
+ }
35
+ items = items.slice(-MAX_ITEMS);
36
+ await saveState(deps, { ...state, relay_items: items });
37
+ return { items: items.length };
38
+ }
39
+
40
+ export interface RelayAnswer { id: string; text: string; answered: boolean; answer?: string; at?: string; delivered?: boolean }
41
+
42
+ /** What the relay reads back: every question it posted, answered or not. */
43
+ export async function relayAnswers(deps: NotifyDeps): Promise<RelayAnswer[]> {
44
+ const state = await loadState(deps);
45
+ const answeredIds = Object.keys(state.answered ?? {}).filter((k) => k.startsWith('relay:')).map((k) => k.slice(6));
46
+ const known = new Map((state.relay_items ?? []).map((i) => [i.id, i]));
47
+ const ids = [...new Set([...known.keys(), ...answeredIds])];
48
+ return ids.map((id) => {
49
+ const a = state.answered?.[`relay:${id}`];
50
+ const text = known.get(id)?.text ?? '';
51
+ return a ? { id, text, answered: true, answer: a.answer, at: a.at, delivered: a.delivered === 'relay' } : { id, text, answered: false };
52
+ }).filter((r) => r.text || r.answered);
53
+ }
@@ -1,6 +1,7 @@
1
1
  /** Fetch-`Response` wrappers for the tenant frontend's route files. Each reads JSON, runs one handler, maps errors to statuses. */
2
2
  import { voiceErrorResponse } from '../voice-manage';
3
3
  import { answerDecision, createDecision, getDecision, getSettings, listDecisions, notify, registerDevice, setSettings, unregisterDevice } from './handle';
4
+ import { postRelayItems, relayAnswers } from './relay-items';
4
5
  import { NotifyError, type NotifyDeps } from './types';
5
6
 
6
7
  async function json(request: Request): Promise<Record<string, unknown>> {
@@ -41,3 +42,8 @@ export const decisionsPostResponse = (r: Request, d: NotifyDeps) => run(async ()
41
42
  export const decisionsListResponse = (status: string | null, d: NotifyDeps) => run(() => listDecisions(d, { status: status ?? undefined }));
42
43
  export const decisionGetResponse = (id: string, d: NotifyDeps) => run(() => getDecision(d, id));
43
44
  export const decisionAnswerResponse = (r: Request, id: string, d: NotifyDeps) => run(async () => { const b = await json(r); return answerDecision(d, id, { answers: b.answers, answer: b.answer }); });
45
+
46
+ /** POST /corpus/notify/relay-items {items:[{id,text,options?,source?,link?}], remove?:[id]}: the relay's questions for him (idempotent by id). */
47
+ export const relayItemsPostResponse = (r: Request, d: NotifyDeps) => run(async () => { const b = await json(r); return postRelayItems(d, { items: b.items, remove: b.remove }); });
48
+ /** GET /corpus/notify/relay-items: every question the relay posted with his answer, when there is one. */
49
+ export const relayItemsGetResponse = (d: NotifyDeps) => run(async () => ({ items: await relayAnswers(d) }));
@@ -28,6 +28,7 @@ export async function loadState(deps: Pick<NotifyDeps, 'http' | 'ownerSub'>): Pr
28
28
  ...(d.attention && typeof d.attention === 'object' ? { attention: d.attention } : {}),
29
29
  ...(d.attention_run && typeof d.attention_run === 'object' ? { attention_run: d.attention_run } : {}),
30
30
  ...(d.answered && typeof d.answered === 'object' ? { answered: d.answered } : {}),
31
+ ...(Array.isArray(d.relay_items) ? { relay_items: d.relay_items } : {}),
31
32
  };
32
33
  }
33
34
 
@@ -19,6 +19,9 @@ export interface DecisionIndexRow { id: string; title: string; status: 'pending'
19
19
  import type { AttentionRunState } from '../attention/run-steps';
20
20
  import type { StoredAttention } from '../attention/settings';
21
21
 
22
+ /** A question the relay posted for him: its own list in the notify state, separate from the fleet snapshot the sync job rewrites. */
23
+ export interface RelayItem { id: string; text: string; options?: string[]; source?: string; link?: string; at: string }
24
+
22
25
  export interface NotifyState {
23
26
  /** Default on: absent means true. */
24
27
  push_enabled: boolean;
@@ -30,7 +33,9 @@ export interface NotifyState {
30
33
  /** The needs-you briefing in progress (see ../attention/run). */
31
34
  attention_run?: AttentionRunState;
32
35
  /** Needs-you items he has answered, by item id: they leave the queue. The slice-4 delivery reads this. */
33
- answered?: Record<string, { answer: string; at: string; conversation_id: string; ref?: string; delivered?: 'decision' }>;
36
+ answered?: Record<string, { answer: string; at: string; conversation_id: string; ref?: string; delivered?: 'decision' | 'relay'; source?: 'relay'; /** The relay could not be told yet: it reads this back. */ delivery_failed?: boolean }>;
37
+ /** Questions the relay posted for him (see ./relay-items). */
38
+ relay_items?: RelayItem[];
34
39
  }
35
40
 
36
41
  export interface DecisionQuestion { n: number; text: string; options?: string[] }