@yaks/inbox 0.0.0-stage → 0.2.36

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 (88) hide show
  1. package/LICENSE +202 -0
  2. package/Person.tsx +275 -0
  3. package/Project.tsx +83 -0
  4. package/README.md +311 -2
  5. package/_dist/actions-browser.d.ts +8 -0
  6. package/_dist/actions-browser.d.ts.map +1 -0
  7. package/_dist/actions.d.ts +22 -0
  8. package/_dist/actions.d.ts.map +1 -0
  9. package/_dist/asks.d.ts +15 -0
  10. package/_dist/asks.d.ts.map +1 -0
  11. package/_dist/graph.d.ts +12 -0
  12. package/_dist/graph.d.ts.map +1 -0
  13. package/_dist/letters.d.ts +24 -0
  14. package/_dist/letters.d.ts.map +1 -0
  15. package/_dist/mail.d.ts +4 -0
  16. package/_dist/mail.d.ts.map +1 -0
  17. package/_dist/mod.d.ts +7 -0
  18. package/_dist/mod.d.ts.map +1 -0
  19. package/_dist/options.d.ts +18 -0
  20. package/_dist/options.d.ts.map +1 -0
  21. package/_dist/queries.d.ts +23 -0
  22. package/_dist/queries.d.ts.map +1 -0
  23. package/_dist/read.d.ts +18 -0
  24. package/_dist/read.d.ts.map +1 -0
  25. package/_dist/reader.d.ts +25 -0
  26. package/_dist/reader.d.ts.map +1 -0
  27. package/_dist/service.d.ts +8 -0
  28. package/_dist/service.d.ts.map +1 -0
  29. package/_dist/threads.d.ts +33 -0
  30. package/_dist/threads.d.ts.map +1 -0
  31. package/_dist/tools.d.ts +12 -0
  32. package/_dist/tools.d.ts.map +1 -0
  33. package/_dist/vocab.d.ts +5 -0
  34. package/_dist/vocab.d.ts.map +1 -0
  35. package/actions-browser.js +165 -0
  36. package/actions-browser.js.map +1 -0
  37. package/actions-browser.ts +158 -0
  38. package/actions.js +34 -0
  39. package/actions.js.map +1 -0
  40. package/actions.ts +53 -0
  41. package/asks.js +76 -0
  42. package/asks.js.map +1 -0
  43. package/asks.ts +94 -0
  44. package/deno.json +1 -0
  45. package/front.js +41 -0
  46. package/front.js.map +1 -0
  47. package/front.json +68 -0
  48. package/front.ts +38 -0
  49. package/graph.js +176 -0
  50. package/graph.js.map +1 -0
  51. package/graph.ts +182 -0
  52. package/inspect.tsx +22 -0
  53. package/letters.js +233 -0
  54. package/letters.js.map +1 -0
  55. package/letters.ts +325 -0
  56. package/mail.js +122 -0
  57. package/mail.js.map +1 -0
  58. package/mail.ts +148 -0
  59. package/mod.js +11 -0
  60. package/mod.js.map +1 -0
  61. package/mod.ts +24 -0
  62. package/options.js +15 -0
  63. package/options.js.map +1 -0
  64. package/options.ts +42 -0
  65. package/package.json +76 -4
  66. package/queries.js +240 -0
  67. package/queries.js.map +1 -0
  68. package/queries.ts +302 -0
  69. package/read.js +453 -0
  70. package/read.js.map +1 -0
  71. package/read.ts +476 -0
  72. package/reader.js +105 -0
  73. package/reader.js.map +1 -0
  74. package/reader.ts +147 -0
  75. package/service.js +29 -0
  76. package/service.js.map +1 -0
  77. package/service.ts +45 -0
  78. package/threads.js +182 -0
  79. package/threads.js.map +1 -0
  80. package/threads.ts +276 -0
  81. package/tools.js +101 -0
  82. package/tools.js.map +1 -0
  83. package/tools.ts +103 -0
  84. package/views.tsx +30 -0
  85. package/vocab.js +12 -0
  86. package/vocab.js.map +1 -0
  87. package/vocab.json +242 -0
  88. package/vocab.ts +11 -0
package/letters.js ADDED
@@ -0,0 +1,233 @@
1
+ /** The inbox's letters: which threads cross to a mail client, and how each is
2
+ * rendered. The graph keeps each queued snapshot (`mail_notice`); @yaks/mail
3
+ * sends the letters, and clocks are supplied at the boundary. */ import { line, sub } from "@yaks/query";
4
+ import { derivedEid } from "@yaks/graph/identity";
5
+ import { held } from "@yaks/graph/held";
6
+ import { showing, shown } from "@yaks/task";
7
+ import { readInbox } from "./read.js";
8
+ let str = (v)=>String(v ?? '');
9
+ let comp = (b, name)=>b[name] ?? {};
10
+ let link = (options, eid)=>`${options.base.replace(/\/$/, '')}/${encodeURIComponent(eid)}`;
11
+ let reply = (options, eid)=>`${eid}@${options.from.split('@')[1]}`;
12
+ // The components a shown entity is drawn by in a letter.
13
+ let SHOWN = [
14
+ 'artifact',
15
+ 'doc',
16
+ 'web'
17
+ ];
18
+ // Each decision's shown entities, read through its `shows` edges.
19
+ let showsOf = async (tx, vocab, eids)=>{
20
+ if (!vocab.comp('shows') || !vocab.comp('edge')) return new Map();
21
+ let byDecision = new Map(await Promise.all(eids.map(async (eid)=>[
22
+ eid,
23
+ shown(await tx.read(line`${sub(showing(eid))}&*`, {
24
+ native: true
25
+ }))
26
+ ])));
27
+ let ids = [
28
+ ...new Set([
29
+ ...byDecision.values()
30
+ ].flatMap((s)=>[
31
+ ...s.values()
32
+ ].flat()))
33
+ ];
34
+ let comps = SHOWN.filter((name)=>vocab.comp(name));
35
+ let found = new Map((ids.length ? await tx.get(ids, comps, {
36
+ native: true
37
+ }) : []).map((b)=>[
38
+ b.entity.eid,
39
+ b
40
+ ]));
41
+ return new Map([
42
+ ...byDecision
43
+ ].map(([eid, s])=>[
44
+ eid,
45
+ new Map([
46
+ ...s
47
+ ].map(([label, to])=>[
48
+ label,
49
+ to.flatMap((id)=>found.get(id) ?? [])
50
+ ]))
51
+ ]));
52
+ };
53
+ // One shown entity in mail-safe Markdown, indented under its choice: an
54
+ // image by its bytes at the door's base, other bytes as a link to them, prose
55
+ // quoted, a page by its address.
56
+ let drawn = (options, label, b)=>{
57
+ let artifact = comp(b, 'artifact');
58
+ let doc = comp(b, 'doc');
59
+ let page = str(comp(b, 'web').url);
60
+ let indent = (text)=>text.replace(/^/gm, ' ');
61
+ if (artifact.address) {
62
+ let src = `${options.base.replace(/\/$/, '')}/blob/${artifact.address}`;
63
+ return indent(str(artifact.media_type).startsWith('image/') ? `![${label}](${src})` : `[${str(doc.title) || label}](${src})`);
64
+ }
65
+ if (page) return indent(`<${page}>`);
66
+ let words = str(doc.body || doc.title).trim();
67
+ return words ? indent(words.replace(/^/gm, '> ')) : '';
68
+ };
69
+ /** Each door reads the same policy, including mute, archive and blockers. */ export let inboxAt = async (tx, vocab, who)=>{
70
+ let inbox = await readInbox(tx, vocab, who);
71
+ // Inbox summaries deliberately carry no bodies or choice arrays. Mail
72
+ // renders complete words, but needs only each root and latest message,
73
+ // not the history of every thread in a daily digest.
74
+ let ids = [
75
+ ...new Set(inbox.flatMap((t)=>[
76
+ t.row.eid,
77
+ t.latest.eid
78
+ ]))
79
+ ];
80
+ let comps = [
81
+ 'doc',
82
+ 'content',
83
+ 'decision'
84
+ ].filter((name)=>vocab.comp(name));
85
+ let full = new Map((await tx.get(ids, comps, {
86
+ native: true
87
+ })).map((b)=>[
88
+ b.entity.eid,
89
+ b
90
+ ]));
91
+ let hydrate = (r)=>{
92
+ let b = full.get(r.eid);
93
+ return {
94
+ ...r,
95
+ comps: {
96
+ ...r.comps,
97
+ ...Object.fromEntries(comps.filter((name)=>b?.[name]).map((name)=>[
98
+ name,
99
+ b[name]
100
+ ]))
101
+ }
102
+ };
103
+ };
104
+ let shows = await showsOf(tx, vocab, inbox.filter((t)=>full.get(t.row.eid)?.decision).map((t)=>t.row.eid));
105
+ return inbox.map((t)=>({
106
+ ...t,
107
+ row: hydrate(t.row),
108
+ latest: hydrate(t.latest),
109
+ ...shows.get(t.row.eid)?.size ? {
110
+ shows: shows.get(t.row.eid)
111
+ } : {}
112
+ }));
113
+ };
114
+ /** Only outstanding needs and replies cross this door by default. */ export let eligible = (thread, options)=>thread.unread && (thread.reason == 'alert' ? options.alerts == true : thread.lane == 'Updates' ? options.updates == true : thread.lane == 'Needs you' || thread.lane == 'Replies');
115
+ /** A thread's question, numbered choices with what each shows, and latest
116
+ * words, in mail-safe markdown. */ export let rendered = (thread, options)=>{
117
+ let root = thread.row.comps;
118
+ let d = root.decision;
119
+ let latest = thread.latest.comps;
120
+ let choices = d?.choices.map((c, i)=>[
121
+ `${i + 1}. ${c.label}: ${c.description}${c.label == d.recommended ? ' (recommended)' : ''}`,
122
+ ...(thread.shows?.get(c.label) ?? []).map((b)=>drawn(options, c.label, b)).filter(Boolean)
123
+ ].join('\n\n')).join('\n');
124
+ return [
125
+ d?.question || str(root.doc?.title) || 'Inbox thread',
126
+ choices,
127
+ d ? 'Reply with a choice number or your own answer.' : '',
128
+ str(latest.doc?.body || latest.content?.body || root.doc?.body),
129
+ `Open thread: ${link(options, thread.eid)}`,
130
+ `Reply to this thread: ${reply(options, thread.latest.comps.comment ? thread.latest.eid : thread.eid)}`
131
+ ].filter(Boolean).join('\n\n');
132
+ };
133
+ let letter = (eid, options, at, title, body)=>({
134
+ entity: {
135
+ eid
136
+ },
137
+ doc: {
138
+ title,
139
+ body
140
+ },
141
+ mail: {
142
+ from: options.from,
143
+ at
144
+ },
145
+ deliver: {
146
+ to: options.person
147
+ },
148
+ mail_notice: {
149
+ activity: at
150
+ }
151
+ });
152
+ /** Pure queue plan. Notices are snapshots of activity, never new inbox activity.
153
+ * The queued letter, not a second cursor, is the durable deduplication record. */ export let planned = (inbox, notices, options, now, daily = false)=>{
154
+ let pending = inbox.filter((t)=>eligible(t, options));
155
+ let through = (target)=>notices.filter((n)=>comp(n, 'deliver').to == options.person && (comp(n, 'mail').target == target || comp(n, 'mail_notice').thread == target)).map((n)=>str(comp(n, 'mail_notice').activity)).sort().at(-1) ?? '';
156
+ let out = pending.filter((t)=>t.blocking && t.row.comps.decision && !notices.some((n)=>comp(n, 'mail').target == t.eid && comp(n, 'mail_notice').activity == t.at)).map((t)=>{
157
+ let eid = derivedEid(`mail-inbox|${options.person}|${t.eid}|${t.at}`);
158
+ let previous = notices.filter((n)=>comp(n, 'deliver').to == options.person && comp(n, 'mail').target == t.eid).sort((a, b)=>str(comp(a, 'mail').at).localeCompare(str(comp(b, 'mail').at))).at(-1);
159
+ let b = letter(eid, options, t.at, str(t.row.comps.doc?.title) || 'Decision needed', rendered(t, options));
160
+ b.mail = {
161
+ ...comp(b, 'mail'),
162
+ target: t.eid,
163
+ ...previous ? {
164
+ reply_to: previous.entity.eid
165
+ } : {}
166
+ };
167
+ b.mail_notice = {
168
+ activity: t.at,
169
+ ...t.latest.comps.comment ? {
170
+ comment: t.latest.eid
171
+ } : {}
172
+ };
173
+ return b;
174
+ });
175
+ let day = now.slice(0, 10);
176
+ let digest = derivedEid(`mail-digest|${options.person}|${day}`);
177
+ let others = pending.filter((t)=>t.at > through(t.eid) && !(t.blocking && t.row.comps.decision));
178
+ if (daily && others.length && !notices.some((n)=>n.entity.eid == digest)) {
179
+ out.push(letter(digest, options, now, 'Your inbox', others.map((t)=>`## ${str(t.row.comps.doc?.title) || 'Inbox thread'}\n\n${rendered(t, options)}`).join('\n\n---\n\n') + '\n\nUse each thread’s reply address above; replying to this digest ' + 'does not choose a thread.'));
180
+ out.push(...others.map((t)=>({
181
+ entity: {
182
+ eid: derivedEid(`mail-digest-thread|${digest}|${t.eid}`)
183
+ },
184
+ mail_notice: {
185
+ activity: t.at,
186
+ thread: t.eid,
187
+ letter: digest
188
+ },
189
+ deliver: {
190
+ to: options.person
191
+ }
192
+ })));
193
+ }
194
+ return out;
195
+ };
196
+ /** Read and write at the boundary. Replays find the same queued letters. */ export let queue = async (tx, vocab, options, write, now = new Date().toISOString(), daily = false)=>{
197
+ let inbox = await inboxAt(tx, vocab, options.person);
198
+ let notices = await tx.read(line`.mail_notice&.deliver.to=${options.person}&*`, {
199
+ native: true
200
+ });
201
+ let bundles = planned(inbox, notices, options, now, daily);
202
+ if (!bundles.length) return;
203
+ let existing = new Set((await tx.get(bundles.map((b)=>b.entity.eid), [], {
204
+ native: true
205
+ })).map((b)=>b.entity.eid));
206
+ let fresh = bundles.filter((b)=>!existing.has(b.entity.eid));
207
+ if (fresh.length) await write(fresh);
208
+ };
209
+ /** `queue` again after commits, at the cost of what they touched: its reads
210
+ * are held across passes (@yaks/graph/held), and a pass none of whose reads
211
+ * changed queues what it queued before, so it does nothing. Each call hears
212
+ * the eids every other writer committed since the last; the pass knows its
213
+ * own letters. */ export let queueing = (graph, vocab, options, write)=>{
214
+ let reads = held(graph, vocab);
215
+ let owed = true;
216
+ let wrote = [];
217
+ let queued = async (bundles)=>{
218
+ wrote.push(...bundles.map((b)=>b.entity.eid));
219
+ await write(bundles);
220
+ };
221
+ return async (moved, now = new Date().toISOString(), daily = false)=>{
222
+ let touched = [
223
+ ...moved,
224
+ ...wrote
225
+ ];
226
+ wrote = [];
227
+ if (!await reads.moved(touched) && !owed && !daily) return;
228
+ owed = true;
229
+ await queue(reads, vocab, options, queued, now, daily);
230
+ owed = false;
231
+ };
232
+ };
233
+ //# sourceMappingURL=letters.js.map
package/letters.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"letters.js","sources":["./letters.ts"],"names":[],"mappings":"AAAA;;+DAE+D,GAE/D,SAAS,IAAI,EAAE,GAAG,2BAAgC;AAClD,SAAS,UAAU,oCAAyC;AAC5D,SAAS,IAAI,gCAAqC;AAElD,SAAwB,OAAO,EAAE,KAAK,0BAA+B;AAErE,SAAS,SAAS,oBAAmB;AAGrC,IAAI,MAAM,CAAC,IAAuB,OAAO,KAAK;AAC9C,IAAI,OAAO,CAAC,GAAW,OAAuB,CAAC,CAAC,KAAK,IAAY,CAAC;AAClE,IAAI,OAAO,CAAC,SAAe,MACzB,GAAG,QAAQ,IAAI,CAAC,OAAO,CAAC,OAAO,IAAI,CAAC,EAAE,mBAAmB,MAAM;AACjE,IAAI,QAAQ,CAAC,SAAe,MAC1B,GAAG,IAAI,CAAC,EAAE,QAAQ,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,EAAE;AAQxC,yDAAyD;AACzD,IAAI,QAAQ;EAAC;EAAY;EAAO;CAAM;AAEtC,kEAAkE;AAClE,IAAI,UAAU,OACZ,IACA,OACA;EAEA,IAAI,CAAC,MAAM,IAAI,CAAC,YAAY,CAAC,MAAM,IAAI,CAAC,SAAS,OAAO,IAAI;EAC5D,IAAI,aAAa,IAAI,IACnB,MAAM,QAAQ,GAAG,CACf,KAAK,GAAG,CAAC,OAAO,MACd;MACE;MACA,MAAM,MAAM,G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GAAG,CAAC,EAAE,MAAM,CAAC,GAAG;EAC5D,IAAI,MAAM,MAAM,EAAE,MAAM,MAAM;AAChC,EAAC;AAED;;;;gBAIgB,GAChB,OAAO,IAAI,WAAW,CACpB,OACA,OACA,SACA;EAMA,IAAI,QAAQ,KAAK,OAAO;EACxB,IAAI,OAAO;EACX,IAAI,QAAkB,EAAE;EACxB,IAAI,SAAS,OAAO;IAClB,MAAM,IAAI,IAAI,QAAQ,GAAG,CAAC,CAAC,IAAM,EAAE,MAAM,CAAC,GAAG;IAC7C,MAAM,MAAM;EACd;EACA,OAAO,OACL,OACA,MAAc,IAAI,OAAO,WAAW,EAAE,EACtC,QAAQ,KAAK;IAEb,IAAI,UAAU;SAAI;SAAU;KAAM;IAClC,QAAQ,EAAE;IACV,IAAI,CAAC,MAAM,MAAM,KAAK,CAAC,YAAY,CAAC,QAAQ,CAAC,OAAO;IACpD,OAAO;IACP,MAAM,MAAM,OAAO,OAAO,SAAS,QAAQ,KAAK;IAChD,OAAO;EACT;AACF,EAAC"}
package/letters.ts ADDED
@@ -0,0 +1,325 @@
1
+ /** The inbox's letters: which threads cross to a mail client, and how each is
2
+ * rendered. The graph keeps each queued snapshot (`mail_notice`); @yaks/mail
3
+ * sends the letters, and clocks are supplied at the boundary. */
4
+ import type { Bundle, Comp, Graph } from 'jsr:@yaks/graph@0.2.36'
5
+ import { line, sub } from '@yaks/query'
6
+ import { derivedEid } from '@yaks/graph/identity'
7
+ import { held } from '@yaks/graph/held'
8
+ import type { Vocab } from 'jsr:@yaks/vocab@0.2.36'
9
+ import { type Decision, showing, shown } from '@yaks/task'
10
+ import type { Door } from './options.ts'
11
+ import { readInbox } from './read.js'
12
+ import type { Thread } from './threads.ts'
13
+
14
+ let str = (v: unknown): string => String(v ?? '')
15
+ let comp = (b: Bundle, name: string): Comp => b[name] as Comp ?? {}
16
+ let link = (options: Door, eid: string) =>
17
+ `${options.base.replace(/\/$/, '')}/${encodeURIComponent(eid)}`
18
+ let reply = (options: Door, eid: string) =>
19
+ `${eid}@${options.from.split('@')[1]}`
20
+
21
+ /** What each choice of a thread's decision shows, by label: the shown
22
+ * entities with the components a letter draws them by. */
23
+ export type Shows = Map<string, Bundle[]>
24
+ /** A thread as a letter reads it: its decision's shown entities beside it. */
25
+ export type Lettered = Thread & { shows?: Shows }
26
+
27
+ // The components a shown entity is drawn by in a letter.
28
+ let SHOWN = ['artifact', 'doc', 'web']
29
+
30
+ // Each decision's shown entities, read through its `shows` edges.
31
+ let showsOf = async (
32
+ tx: Pick<Graph, 'get' | 'read'>,
33
+ vocab: Vocab,
34
+ eids: string[],
35
+ ): Promise<Map<string, Shows>> => {
36
+ if (!vocab.comp('shows') || !vocab.comp('edge')) return new Map()
37
+ let byDecision = new Map(
38
+ await Promise.all(
39
+ eids.map(async (eid) =>
40
+ [
41
+ eid,
42
+ shown(await tx.read(line`${sub(showing(eid))}&*`, { native: true })),
43
+ ] as const
44
+ ),
45
+ ),
46
+ )
47
+ let ids = [
48
+ ...new Set([...byDecision.values()].flatMap((s) => [...s.values()].flat())),
49
+ ]
50
+ let comps = SHOWN.filter((name) => vocab.comp(name))
51
+ let found = new Map(
52
+ (ids.length ? await tx.get(ids, comps, { native: true }) : [])
53
+ .map((b) => [b.entity.eid, b]),
54
+ )
55
+ return new Map(
56
+ [...byDecision].map(([eid, s]) => [
57
+ eid,
58
+ new Map(
59
+ [...s].map(([label, to]) => [
60
+ label,
61
+ to.flatMap((id) => found.get(id) ?? []),
62
+ ]),
63
+ ),
64
+ ]),
65
+ )
66
+ }
67
+
68
+ // One shown entity in mail-safe Markdown, indented under its choice: an
69
+ // image by its bytes at the door's base, other bytes as a link to them, prose
70
+ // quoted, a page by its address.
71
+ let drawn = (options: Door, label: string, b: Bundle): string => {
72
+ let artifact = comp(b, 'artifact')
73
+ let doc = comp(b, 'doc')
74
+ let page = str(comp(b, 'web').url)
75
+ let indent = (text: string) => text.replace(/^/gm, ' ')
76
+ if (artifact.address) {
77
+ let src = `${options.base.replace(/\/$/, '')}/blob/${artifact.address}`
78
+ return indent(
79
+ str(artifact.media_type).startsWith('image/')
80
+ ? `![${label}](${src})`
81
+ : `[${str(doc.title) || label}](${src})`,
82
+ )
83
+ }
84
+ if (page) return indent(`<${page}>`)
85
+ let words = str(doc.body || doc.title).trim()
86
+ return words ? indent(words.replace(/^/gm, '> ')) : ''
87
+ }
88
+
89
+ /** Each door reads the same policy, including mute, archive and blockers. */
90
+ export let inboxAt = async (
91
+ tx: Pick<Graph, 'get' | 'read'>,
92
+ vocab: Vocab,
93
+ who: string,
94
+ ): Promise<Lettered[]> => {
95
+ let inbox = await readInbox(tx, vocab, who)
96
+ // Inbox summaries deliberately carry no bodies or choice arrays. Mail
97
+ // renders complete words, but needs only each root and latest message,
98
+ // not the history of every thread in a daily digest.
99
+ let ids = [...new Set(inbox.flatMap((t) => [t.row.eid, t.latest.eid]))]
100
+ let comps = ['doc', 'content', 'decision'].filter((name) => vocab.comp(name))
101
+ let full = new Map(
102
+ (await tx.get(ids, comps, { native: true })).map((b) => [b.entity.eid, b]),
103
+ )
104
+ let hydrate = (r: Thread['row']): Thread['row'] => {
105
+ let b = full.get(r.eid)
106
+ return {
107
+ ...r,
108
+ comps: {
109
+ ...r.comps,
110
+ ...Object.fromEntries(
111
+ comps.filter((name) => b?.[name])
112
+ .map((name) => [name, b![name] as Comp]),
113
+ ),
114
+ },
115
+ }
116
+ }
117
+ let shows = await showsOf(
118
+ tx,
119
+ vocab,
120
+ inbox.filter((t) => full.get(t.row.eid)?.decision).map((t) => t.row.eid),
121
+ )
122
+ return inbox.map((t) => ({
123
+ ...t,
124
+ row: hydrate(t.row),
125
+ latest: hydrate(t.latest),
126
+ ...shows.get(t.row.eid)?.size ? { shows: shows.get(t.row.eid) } : {},
127
+ }))
128
+ }
129
+
130
+ /** Only outstanding needs and replies cross this door by default. */
131
+ export let eligible = (thread: Thread, options: Door): boolean =>
132
+ thread.unread &&
133
+ (thread.reason == 'alert'
134
+ ? options.alerts == true
135
+ : thread.lane == 'Updates'
136
+ ? options.updates == true
137
+ : thread.lane == 'Needs you' || thread.lane == 'Replies')
138
+
139
+ /** A thread's question, numbered choices with what each shows, and latest
140
+ * words, in mail-safe markdown. */
141
+ export let rendered = (thread: Lettered, options: Door): string => {
142
+ let root = thread.row.comps
143
+ let d = root.decision as Decision | undefined
144
+ let latest = thread.latest.comps
145
+ let choices = d?.choices.map((c, i) =>
146
+ [
147
+ `${i + 1}. ${c.label}: ${c.description}${
148
+ c.label == d.recommended ? ' (recommended)' : ''
149
+ }`,
150
+ ...(thread.shows?.get(c.label) ?? []).map((b) =>
151
+ drawn(options, c.label, b)
152
+ ).filter(Boolean),
153
+ ].join('\n\n')
154
+ ).join('\n')
155
+ return [
156
+ d?.question || str(root.doc?.title) || 'Inbox thread',
157
+ choices,
158
+ d ? 'Reply with a choice number or your own answer.' : '',
159
+ str(latest.doc?.body || latest.content?.body || root.doc?.body),
160
+ `Open thread: ${link(options, thread.eid)}`,
161
+ `Reply to this thread: ${
162
+ reply(
163
+ options,
164
+ thread.latest.comps.comment ? thread.latest.eid : thread.eid,
165
+ )
166
+ }`,
167
+ ].filter(Boolean).join('\n\n')
168
+ }
169
+
170
+ let letter = (
171
+ eid: string,
172
+ options: Door,
173
+ at: string,
174
+ title: string,
175
+ body: string,
176
+ ): Bundle => ({
177
+ entity: { eid },
178
+ doc: { title, body },
179
+ mail: { from: options.from, at },
180
+ deliver: { to: options.person },
181
+ mail_notice: { activity: at },
182
+ })
183
+
184
+ /** Pure queue plan. Notices are snapshots of activity, never new inbox activity.
185
+ * The queued letter, not a second cursor, is the durable deduplication record. */
186
+ export let planned = (
187
+ inbox: Lettered[],
188
+ notices: Bundle[],
189
+ options: Door,
190
+ now: string,
191
+ daily = false,
192
+ ): Bundle[] => {
193
+ let pending = inbox.filter((t) => eligible(t, options))
194
+ let through = (target: string) =>
195
+ notices.filter((n) =>
196
+ comp(n, 'deliver').to == options.person &&
197
+ (comp(n, 'mail').target == target ||
198
+ comp(n, 'mail_notice').thread == target)
199
+ ).map((n) => str(comp(n, 'mail_notice').activity)).sort().at(-1) ?? ''
200
+ let out = pending.filter((t) =>
201
+ t.blocking && t.row.comps.decision &&
202
+ !notices.some((n) =>
203
+ comp(n, 'mail').target == t.eid &&
204
+ comp(n, 'mail_notice').activity == t.at
205
+ )
206
+ ).map(
207
+ (t) => {
208
+ let eid = derivedEid(`mail-inbox|${options.person}|${t.eid}|${t.at}`)
209
+ let previous = notices.filter((n) =>
210
+ comp(n, 'deliver').to == options.person &&
211
+ comp(n, 'mail').target == t.eid
212
+ ).sort((a, b) =>
213
+ str(comp(a, 'mail').at).localeCompare(str(comp(b, 'mail').at))
214
+ )
215
+ .at(-1)
216
+ let b = letter(
217
+ eid,
218
+ options,
219
+ t.at,
220
+ str(t.row.comps.doc?.title) ||
221
+ 'Decision needed',
222
+ rendered(t, options),
223
+ )
224
+ b.mail = {
225
+ ...comp(b, 'mail'),
226
+ target: t.eid,
227
+ ...(previous ? { reply_to: previous.entity.eid } : {}),
228
+ }
229
+ b.mail_notice = {
230
+ activity: t.at,
231
+ ...(t.latest.comps.comment ? { comment: t.latest.eid } : {}),
232
+ }
233
+ return b
234
+ },
235
+ )
236
+ let day = now.slice(0, 10)
237
+ let digest = derivedEid(`mail-digest|${options.person}|${day}`)
238
+ let others = pending.filter((t) =>
239
+ t.at > through(t.eid) &&
240
+ !(t.blocking && t.row.comps.decision)
241
+ )
242
+ if (daily && others.length && !notices.some((n) => n.entity.eid == digest)) {
243
+ out.push(
244
+ letter(
245
+ digest,
246
+ options,
247
+ now,
248
+ 'Your inbox',
249
+ others.map((t) =>
250
+ `## ${str(t.row.comps.doc?.title) || 'Inbox thread'}\n\n${
251
+ rendered(t, options)
252
+ }`
253
+ ).join('\n\n---\n\n') +
254
+ '\n\nUse each thread’s reply address above; replying to this digest ' +
255
+ 'does not choose a thread.',
256
+ ),
257
+ )
258
+ out.push(...others.map((t) => ({
259
+ entity: { eid: derivedEid(`mail-digest-thread|${digest}|${t.eid}`) },
260
+ mail_notice: { activity: t.at, thread: t.eid, letter: digest },
261
+ deliver: { to: options.person },
262
+ })))
263
+ }
264
+ return out
265
+ }
266
+
267
+ /** Read and write at the boundary. Replays find the same queued letters. */
268
+ export let queue = async (
269
+ tx: Pick<Graph, 'get' | 'read'>,
270
+ vocab: Vocab,
271
+ options: Door,
272
+ write: (bundles: Bundle[]) => unknown,
273
+ now: string = new Date().toISOString(),
274
+ daily = false,
275
+ ): Promise<void> => {
276
+ let inbox = await inboxAt(tx, vocab, options.person)
277
+ let notices = await tx.read(
278
+ line`.mail_notice&.deliver.to=${options.person}&*`,
279
+ { native: true },
280
+ )
281
+ let bundles = planned(inbox, notices, options, now, daily)
282
+ if (!bundles.length) return
283
+ let existing = new Set(
284
+ (await tx.get(bundles.map((b) => b.entity.eid), [], { native: true }))
285
+ .map((b) => b.entity.eid),
286
+ )
287
+ let fresh = bundles.filter((b) => !existing.has(b.entity.eid))
288
+ if (fresh.length) await write(fresh)
289
+ }
290
+
291
+ /** `queue` again after commits, at the cost of what they touched: its reads
292
+ * are held across passes (@yaks/graph/held), and a pass none of whose reads
293
+ * changed queues what it queued before, so it does nothing. Each call hears
294
+ * the eids every other writer committed since the last; the pass knows its
295
+ * own letters. */
296
+ export let queueing = (
297
+ graph: Pick<Graph, 'get' | 'read'>,
298
+ vocab: Vocab,
299
+ options: Door,
300
+ write: (bundles: Bundle[]) => unknown,
301
+ ): (
302
+ moved: Iterable<string>,
303
+ now?: string,
304
+ daily?: boolean,
305
+ ) => Promise<void> => {
306
+ let reads = held(graph, vocab)
307
+ let owed = true
308
+ let wrote: string[] = []
309
+ let queued = async (bundles: Bundle[]) => {
310
+ wrote.push(...bundles.map((b) => b.entity.eid))
311
+ await write(bundles)
312
+ }
313
+ return async (
314
+ moved: Iterable<string>,
315
+ now: string = new Date().toISOString(),
316
+ daily = false,
317
+ ): Promise<void> => {
318
+ let touched = [...moved, ...wrote]
319
+ wrote = []
320
+ if (!await reads.moved(touched) && !owed && !daily) return
321
+ owed = true
322
+ await queue(reads, vocab, options, queued, now, daily)
323
+ owed = false
324
+ }
325
+ }