@yaks/tracker 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 (198) hide show
  1. package/Histogram.js +71 -0
  2. package/Histogram.js.map +1 -0
  3. package/Histogram.ts +100 -0
  4. package/LICENSE +202 -0
  5. package/README.md +639 -2
  6. package/_dist/brief.d.ts +25 -0
  7. package/_dist/brief.d.ts.map +1 -0
  8. package/_dist/changes.d.ts +9 -0
  9. package/_dist/changes.d.ts.map +1 -0
  10. package/_dist/chart.d.ts +24 -0
  11. package/_dist/chart.d.ts.map +1 -0
  12. package/_dist/digest.d.ts +64 -0
  13. package/_dist/digest.d.ts.map +1 -0
  14. package/_dist/effects.d.ts +73 -0
  15. package/_dist/effects.d.ts.map +1 -0
  16. package/_dist/errors.d.ts +14 -0
  17. package/_dist/errors.d.ts.map +1 -0
  18. package/_dist/everywhere.d.ts +13 -0
  19. package/_dist/everywhere.d.ts.map +1 -0
  20. package/_dist/fault.d.ts +29 -0
  21. package/_dist/fault.d.ts.map +1 -0
  22. package/_dist/file.d.ts +6 -0
  23. package/_dist/file.d.ts.map +1 -0
  24. package/_dist/fixtime.d.ts +20 -0
  25. package/_dist/fixtime.d.ts.map +1 -0
  26. package/_dist/frames.d.ts +6 -0
  27. package/_dist/frames.d.ts.map +1 -0
  28. package/_dist/graph.d.ts +3 -0
  29. package/_dist/graph.d.ts.map +1 -0
  30. package/_dist/group.d.ts +21 -0
  31. package/_dist/group.d.ts.map +1 -0
  32. package/_dist/instrument.d.ts +37 -0
  33. package/_dist/instrument.d.ts.map +1 -0
  34. package/_dist/intake.d.ts +21 -0
  35. package/_dist/intake.d.ts.map +1 -0
  36. package/_dist/merge.d.ts +11 -0
  37. package/_dist/merge.d.ts.map +1 -0
  38. package/_dist/mod.d.ts +7 -0
  39. package/_dist/mod.d.ts.map +1 -0
  40. package/_dist/model.d.ts +20 -0
  41. package/_dist/model.d.ts.map +1 -0
  42. package/_dist/outage.d.ts +7 -0
  43. package/_dist/outage.d.ts.map +1 -0
  44. package/_dist/people.d.ts +3 -0
  45. package/_dist/people.d.ts.map +1 -0
  46. package/_dist/poll.d.ts +101 -0
  47. package/_dist/poll.d.ts.map +1 -0
  48. package/_dist/poll_thread.d.ts +8 -0
  49. package/_dist/poll_thread.d.ts.map +1 -0
  50. package/_dist/reading.d.ts +34 -0
  51. package/_dist/reading.d.ts.map +1 -0
  52. package/_dist/remote.d.ts +61 -0
  53. package/_dist/remote.d.ts.map +1 -0
  54. package/_dist/report.d.ts +324 -0
  55. package/_dist/report.d.ts.map +1 -0
  56. package/_dist/resolution.d.ts +22 -0
  57. package/_dist/resolution.d.ts.map +1 -0
  58. package/_dist/routes.d.ts +33 -0
  59. package/_dist/routes.d.ts.map +1 -0
  60. package/_dist/script.d.ts +8 -0
  61. package/_dist/script.d.ts.map +1 -0
  62. package/_dist/service.d.ts +30 -0
  63. package/_dist/service.d.ts.map +1 -0
  64. package/_dist/sync_health.d.ts +4 -0
  65. package/_dist/sync_health.d.ts.map +1 -0
  66. package/_dist/ticket.d.ts +14 -0
  67. package/_dist/ticket.d.ts.map +1 -0
  68. package/_dist/tools.d.ts +39 -0
  69. package/_dist/tools.d.ts.map +1 -0
  70. package/_dist/trace-intake.d.ts +25 -0
  71. package/_dist/trace-intake.d.ts.map +1 -0
  72. package/_dist/views.d.ts +11 -0
  73. package/_dist/views.d.ts.map +1 -0
  74. package/_dist/vocab.d.ts +9 -0
  75. package/_dist/vocab.d.ts.map +1 -0
  76. package/box.json +51 -0
  77. package/brief.js +86 -0
  78. package/brief.js.map +1 -0
  79. package/brief.ts +120 -0
  80. package/changes.js +57 -0
  81. package/changes.js.map +1 -0
  82. package/changes.ts +70 -0
  83. package/chart.js +186 -0
  84. package/chart.js.map +1 -0
  85. package/chart.ts +193 -0
  86. package/deno.json +1 -0
  87. package/digest.js +329 -0
  88. package/digest.js.map +1 -0
  89. package/digest.ts +406 -0
  90. package/effects.js +136 -0
  91. package/effects.js.map +1 -0
  92. package/effects.ts +178 -0
  93. package/errors.js +130 -0
  94. package/errors.js.map +1 -0
  95. package/errors.ts +185 -0
  96. package/everywhere.js +46 -0
  97. package/everywhere.js.map +1 -0
  98. package/everywhere.ts +66 -0
  99. package/fault.js +65 -0
  100. package/fault.js.map +1 -0
  101. package/fault.ts +107 -0
  102. package/file.js +87 -0
  103. package/file.js.map +1 -0
  104. package/file.ts +93 -0
  105. package/fixtime.js +67 -0
  106. package/fixtime.js.map +1 -0
  107. package/fixtime.ts +86 -0
  108. package/frames.js +77 -0
  109. package/frames.js.map +1 -0
  110. package/frames.ts +69 -0
  111. package/graph.js +7 -0
  112. package/graph.js.map +1 -0
  113. package/graph.ts +8 -0
  114. package/group.js +444 -0
  115. package/group.js.map +1 -0
  116. package/group.ts +533 -0
  117. package/inspect.js +471 -0
  118. package/inspect.js.map +1 -0
  119. package/inspect.ts +693 -0
  120. package/instrument.js +69 -0
  121. package/instrument.js.map +1 -0
  122. package/instrument.ts +93 -0
  123. package/intake.js +43 -0
  124. package/intake.js.map +1 -0
  125. package/intake.ts +84 -0
  126. package/merge.js +126 -0
  127. package/merge.js.map +1 -0
  128. package/merge.ts +115 -0
  129. package/migrate.ts +36 -0
  130. package/mod.js +8 -0
  131. package/mod.js.map +1 -0
  132. package/mod.ts +19 -0
  133. package/model.js +8 -0
  134. package/model.js.map +1 -0
  135. package/model.ts +27 -0
  136. package/outage.js +129 -0
  137. package/outage.js.map +1 -0
  138. package/outage.ts +158 -0
  139. package/package.json +133 -4
  140. package/page.d.ts +2 -0
  141. package/page.js +905 -0
  142. package/people.js +51 -0
  143. package/people.js.map +1 -0
  144. package/people.ts +82 -0
  145. package/poll.js +277 -0
  146. package/poll.js.map +1 -0
  147. package/poll.ts +411 -0
  148. package/poll_thread.js +104 -0
  149. package/poll_thread.js.map +1 -0
  150. package/poll_thread.ts +126 -0
  151. package/poll_worker.ts +45 -0
  152. package/reading.js +122 -0
  153. package/reading.js.map +1 -0
  154. package/reading.ts +162 -0
  155. package/reconcile.js +113 -0
  156. package/reconcile.js.map +1 -0
  157. package/reconcile.ts +130 -0
  158. package/remote.js +312 -0
  159. package/remote.js.map +1 -0
  160. package/remote.ts +397 -0
  161. package/report.js +825 -0
  162. package/report.js.map +1 -0
  163. package/report.ts +944 -0
  164. package/resolution.js +114 -0
  165. package/resolution.js.map +1 -0
  166. package/resolution.ts +123 -0
  167. package/routes.js +130 -0
  168. package/routes.js.map +1 -0
  169. package/routes.ts +163 -0
  170. package/script.js +13 -0
  171. package/script.js.map +1 -0
  172. package/script.ts +16 -0
  173. package/service.js +174 -0
  174. package/service.js.map +1 -0
  175. package/service.ts +215 -0
  176. package/spread.js +94 -0
  177. package/spread.js.map +1 -0
  178. package/spread.ts +101 -0
  179. package/sync_health.js +36 -0
  180. package/sync_health.js.map +1 -0
  181. package/sync_health.ts +65 -0
  182. package/ticket.js +6 -0
  183. package/ticket.js.map +1 -0
  184. package/ticket.ts +24 -0
  185. package/tools.js +305 -0
  186. package/tools.js.map +1 -0
  187. package/tools.ts +411 -0
  188. package/trace-intake.js +164 -0
  189. package/trace-intake.js.map +1 -0
  190. package/trace-intake.ts +148 -0
  191. package/views.js +247 -0
  192. package/views.js.map +1 -0
  193. package/views.ts +254 -0
  194. package/vocab.js +20 -0
  195. package/vocab.js.map +1 -0
  196. package/vocab.json +834 -0
  197. package/vocab.ts +14 -0
  198. package/yak-tracker@.service +22 -0
package/digest.ts ADDED
@@ -0,0 +1,406 @@
1
+ // The daily digest: one letter a morning in place of a letter per bug. It
2
+ // says what opened and what was fixed since yesterday's, how long the fixes
3
+ // took, what is still open and who is on it, and which of them reached a
4
+ // person, above a chart of the last two weeks. It is written from the bug
5
+ // rows, and the chart counts the warnings too, which open no bug; agents
6
+ // heard of each bug when it opened (@yaks/heal).
7
+
8
+ import type { Bundle } from 'jsr:@yaks/graph@0.2.36'
9
+ import { derivedEid } from '@yaks/graph/identity'
10
+ import { Stale } from '@yaks/graph/errors'
11
+ import { token } from '@yaks/graph/sha256'
12
+ import { next } from '@yaks/wake'
13
+ import { comp, type Desk, str } from './model.js'
14
+ import { headline, whom } from './brief.js'
15
+ import { fixtime, opened, span, spread } from './fixtime.js'
16
+ import { type Day, query } from './chart.js'
17
+ import { platform as PLATFORM, remoteBug } from './reading.js'
18
+ import {
19
+ absent,
20
+ and,
21
+ eq,
22
+ every,
23
+ fields,
24
+ ge,
25
+ le,
26
+ lt,
27
+ present,
28
+ } from '@yaks/query'
29
+ import {
30
+ FRAME,
31
+ INTERACTION,
32
+ type InteractionSummary,
33
+ interactionSummary,
34
+ SLOW,
35
+ } from '@yaks/timing/interaction'
36
+
37
+ /** The owner's time zone: the digest goes out in his morning, and its days
38
+ * are his. */
39
+ export let ZONE = 'America/Detroit'
40
+ /** When the digest goes out. */
41
+ export let EVERY = `0 7 * * * ${ZONE}`
42
+ /** How many days the chart shows. */
43
+ export let SPAN = 14
44
+ // The most bugs a section lists; it counts the rest.
45
+ let LISTED = 15
46
+ let DAY = 86_400_000
47
+
48
+ /// day(Date.parse('2026-11-20T04:00:00Z')) -> '2026-11-19'
49
+ /** A moment's date in the owner's zone, as YYYY-MM-DD. */
50
+ export let day = (t: number, zone = ZONE): string =>
51
+ new Intl.DateTimeFormat('en-CA', {
52
+ timeZone: zone,
53
+ year: 'numeric',
54
+ month: '2-digit',
55
+ day: '2-digit',
56
+ }).format(t)
57
+
58
+ let at = (b: Bundle, name: string, prop = 'at') =>
59
+ Date.parse(str(comp(b, name)[prop]))
60
+ let open = (b: Bundle) => !b.resolved && !b.archived
61
+ let person = (b: Bundle) => comp(b, 'bug').account == 'person'
62
+
63
+ // Each time a bug opened that its row still records: its first occurrence,
64
+ // and its latest regression.
65
+ let openings = (b: Bundle) =>
66
+ [at(b, 'bug', 'first'), at(b, 'regressed')].filter(Number.isFinite)
67
+
68
+ /** The chart's days: the `n` days up to and including `now`'s, each with the
69
+ * bugs that opened and were fixed on it, the warnings caught on it (from
70
+ * their times), and the median time to fix. */
71
+ export let series = (
72
+ bugs: Bundle[],
73
+ now: number,
74
+ warnings: number[] = [],
75
+ n = SPAN,
76
+ ): Day[] => {
77
+ let keys = Array.from({ length: n }, (_, i) => day(now - (n - 1 - i) * DAY))
78
+ let days = new Map(
79
+ keys.map((k) => [k, { opened: 0, warned: 0, fixes: [] as number[] }]),
80
+ )
81
+ let on = (t: number) => Number.isFinite(t) ? days.get(day(t)) : undefined
82
+ for (let b of bugs) {
83
+ for (let t of openings(b)) {
84
+ let d = on(t)
85
+ if (d) d.opened++
86
+ }
87
+ let ms = fixtime(b), d = on(at(b, 'resolved'))
88
+ if (d && ms != undefined) d.fixes.push(ms)
89
+ }
90
+ for (let t of warnings) {
91
+ let d = on(t)
92
+ if (d) d.warned++
93
+ }
94
+ return keys.map((k) => {
95
+ let { opened, warned, fixes } = days.get(k)!
96
+ let median = spread(fixes.map((ms) => ({ ms, of: 0 }))).median
97
+ return {
98
+ day: k,
99
+ opened,
100
+ fixed: fixes.length,
101
+ warned,
102
+ ...median == undefined ? {} : { fix: median },
103
+ }
104
+ })
105
+ }
106
+
107
+ /** Where the digest's links and chart point. */
108
+ export type Places = {
109
+ /** A bug's page. */
110
+ bug: (eid: string) => string
111
+ /** The chart's image, its days' query string appended. */
112
+ chart?: string
113
+ }
114
+
115
+ // A cell holds a pipe as `\|`, and a line of its own.
116
+ let cell = (s: string) => s.replace(/\|/g, '\\|').replace(/\s+/g, ' ')
117
+ // A bug's name in a cell: its headline, cut to a line a table holds.
118
+ let WIDE = 90
119
+ let short = (s: string) =>
120
+ s.length > WIDE ? `${s.slice(0, WIDE - 1).trimEnd()}…` : s
121
+ let name = (b: Bundle, places: Places) =>
122
+ `[${
123
+ cell(short(headline(str(comp(b, 'doc').title))) || b.entity.eid.slice(0, 8))
124
+ }](${places.bug(b.entity.eid)})`
125
+ let reached = (b: Bundle) => {
126
+ let { account, people } = comp(b, 'bug')
127
+ return account == 'person'
128
+ ? `**${people ? whom(Number(people), 'person') : 'a person'}**`
129
+ : account == 'test'
130
+ ? 'test'
131
+ : ''
132
+ }
133
+ let on = (b: Bundle) => str(comp(b, 'taken').task) || (b.taken ? 'taken' : '')
134
+ let table = (head: string[], rows: string[][]) =>
135
+ [head, head.map(() => '---'), ...rows].map((r) => `| ${r.join(' | ')} |`)
136
+ .join('\n')
137
+ let interactions = ({ n, under16, under100, kinds }: InteractionSummary) => {
138
+ let share = (count: number) => `${(count * 100 / n).toFixed(1)}%`
139
+ let head = '## yaks.app interactions\n\n'
140
+ if (!n) return head + 'No interactions recorded in the last 24 hours.'
141
+ return head + `${n.toLocaleString('en-US')} in the last 24 hours. ` +
142
+ `${share(under16)} under ${FRAME} ms and ${
143
+ share(under100)
144
+ } under ${SLOW} ms.\n\n` +
145
+ table(
146
+ ['Slowest kinds', 'Interactions', 'Peak', 'Mean'],
147
+ kinds
148
+ .slice(0, 5).map(({ name, n, max, total }) => [
149
+ cell(name),
150
+ String(n),
151
+ `${Math.round(max)} ms`,
152
+ `${Math.round(total / n)} ms`,
153
+ ]),
154
+ )
155
+ }
156
+ let when = (t: number) =>
157
+ new Intl.DateTimeFormat('en-US', {
158
+ timeZone: ZONE,
159
+ month: 'short',
160
+ day: 'numeric',
161
+ }).format(t)
162
+
163
+ /** What the digest is written from besides the bugs: the day's interactions
164
+ * on the platform, and the times of the chart's warnings. */
165
+ export type Seen = { timing?: InteractionSummary; warnings?: number[] }
166
+
167
+ /**
168
+ * The digest of `bugs` at `now`: what opened and was fixed in the day before
169
+ * it, what is open, and the chart of the days before that.
170
+ *
171
+ * ```ts
172
+ * import { digest } from '@yaks/tracker/digest'
173
+ * import { equal } from '@yaks/testing'
174
+ *
175
+ * let now = Date.parse('2026-11-20T12:00:00Z')
176
+ * let { title } = digest([
177
+ * { entity: { eid: 'a' }, doc: { title: 'TypeError: x' }, bug: { first: '2026-11-20T09:00:00Z', hits: 2, account: 'person', people: 1 } },
178
+ * { entity: { eid: 'b' }, doc: { title: 'Error: y' }, bug: { first: '2026-11-19T10:00:00Z' }, resolved: { at: '2026-11-19T13:00:00Z' } },
179
+ * ], now, { bug: (eid) => `https://bugs.example/${eid}` })
180
+ * equal(title, 'Bugs, Nov 20: 1 new, 1 fixed, 1 open, 1 reached a person')
181
+ * ```
182
+ */
183
+ export let digest = (
184
+ bugs: Bundle[],
185
+ now: number,
186
+ places: Places,
187
+ { timing, warnings }: Seen = {},
188
+ ): { title: string; body: string } => {
189
+ let since = now - DAY
190
+ let hits = (b: Bundle) => Number(comp(b, 'bug').hits ?? 1)
191
+ // A person's bugs first, then the worst by `worst`.
192
+ let rank = (worst: (b: Bundle) => number) => (a: Bundle, b: Bundle) =>
193
+ Number(person(b)) - Number(person(a)) || worst(b) - worst(a)
194
+ let fresh = bugs.filter((b) => opened(b) >= since && opened(b) <= now)
195
+ .sort(rank(hits))
196
+ let fixed = bugs.filter((b) =>
197
+ at(b, 'resolved') >= since && fixtime(b) != undefined
198
+ ).sort(rank((b) => fixtime(b)!))
199
+ let still = bugs.filter(open).sort(rank(hits))
200
+ let hit = new Set([...fresh, ...fixed, ...still].filter(person))
201
+ let days = series(bugs, now, warnings)
202
+ let fixes = spread(fixed.map((b) => ({ ms: fixtime(b)!, of: b })))
203
+ // A section lists its first fifteen and counts the rest.
204
+ let section = (
205
+ head: string,
206
+ rows: Bundle[],
207
+ cols: string[],
208
+ row: (b: Bundle) => string[],
209
+ lead = '',
210
+ ) => {
211
+ let shown = rows.slice(0, LISTED), rest = rows.length - shown.length
212
+ return `## ${head} (${rows.length})\n\n${
213
+ rows.length
214
+ ? lead + table(cols, shown.map(row)) +
215
+ (rest ? `\n\nAnd ${rest} more.` : '')
216
+ : 'None.'
217
+ }`
218
+ }
219
+ let body = [
220
+ ...places.chart
221
+ ? [
222
+ `![Bugs opened and fixed each day, warnings, and time to fix](${places.chart}${
223
+ places.chart.includes('?') ? '&' : '?'
224
+ }${query(days)})`,
225
+ `Last ${SPAN} days, ${when(now - (SPAN - 1) * DAY)} to ${
226
+ when(now)
227
+ }: opened in red, fixed in green, warnings in grey (a press or an open slower than its budget but within twice it, which opens no bug), and the median time to fix of each day's fixes in amber (the highest ${
228
+ span(Math.max(1, ...days.map((d) => d.fix ?? 0)))
229
+ }).`,
230
+ ]
231
+ : [],
232
+ ...timing ? [interactions(timing)] : [],
233
+ section(
234
+ 'New',
235
+ fresh,
236
+ ['Bug', 'Hits', 'Reached', 'On it'],
237
+ (b) => [name(b, places), String(hits(b)), reached(b), on(b)],
238
+ ),
239
+ section(
240
+ 'Fixed',
241
+ fixed,
242
+ ['Bug', 'Time to fix', 'Reached'],
243
+ (b) => [name(b, places), span(fixtime(b)!), reached(b)],
244
+ fixes.median == undefined
245
+ ? ''
246
+ : `Median time to fix ${span(fixes.median)}.\n\n`,
247
+ ),
248
+ section(
249
+ 'Open',
250
+ still,
251
+ ['Bug', 'Open for', 'Hits', 'Reached', 'On it'],
252
+ (b) => [
253
+ name(b, places),
254
+ span(Math.max(0, now - opened(b))),
255
+ String(hits(b)),
256
+ reached(b),
257
+ on(b) || 'nobody',
258
+ ],
259
+ ),
260
+ ].join('\n\n')
261
+ return {
262
+ title: `Bugs, ${
263
+ when(now)
264
+ }: ${fresh.length} new, ${fixed.length} fixed, ${still.length} open${
265
+ hit.size ? `, ${hit.size} reached a person` : ''
266
+ }`,
267
+ body,
268
+ }
269
+ }
270
+
271
+ /** The recurring wake that sends the digest each morning, from `now` on. One
272
+ * store holds one, under a fixed eid, so writing it again moves nothing. */
273
+ export let wake = (now: number): Bundle => ({
274
+ entity: { eid: derivedEid('tracker-digest') },
275
+ wake: { every: EVERY, at: next(EVERY, now), note: 'The daily bug digest' },
276
+ digest: {},
277
+ })
278
+
279
+ // What the digest reads: every open bug, and every one that opened or was
280
+ // fixed within the chart's days.
281
+ let reads = (since: string) =>
282
+ [
283
+ eq('bug.status', 'open'),
284
+ ge('bug.first', since),
285
+ ge('regressed.at', since),
286
+ ge('resolved.at', since),
287
+ ].map((p) => and(present('bug'), p, every()))
288
+
289
+ /** What the digest is sent with: its recipient by entity, the address it is
290
+ * from, the tracker web's address, this store's global eid, and where its
291
+ * chart is drawn (a `/chart.png` that reads its query string, ./chart.ts). */
292
+ export type Sending = {
293
+ to?: string
294
+ from?: string
295
+ url?: string
296
+ store?: string
297
+ chart?: string
298
+ /** What makes this letter one of its own: the day by default, so the
299
+ * day's firings write one; a request that asks for one names its moment. */
300
+ key?: string
301
+ /** The wake's firing, to which the scheduled letter belongs. */
302
+ fired?: { entity: Bundle['entity']; at: string }
303
+ /** Sections of the host's own, in Markdown, below the bugs' chart: the
304
+ * platform's trials (workers/tracker). One that fails leaves the digest
305
+ * without it, reported. */
306
+ more?: (now: number) => Promise<string[]>
307
+ }
308
+
309
+ let letterEid = (store: string | undefined, to: string, key: string) =>
310
+ derivedEid(`tracker-digest|${JSON.stringify([store, to, key])}`)
311
+
312
+ // A scheduled digest has a day as its key. Explicit requests name their
313
+ // moment instead and do not supersede one another or a daily digest.
314
+ let superseded = async (
315
+ g: Desk,
316
+ store: string | undefined,
317
+ to: string,
318
+ now: string,
319
+ eid: string,
320
+ ): Promise<Bundle[]> => {
321
+ let waiting = await g.read(and(
322
+ eq('deliver.to', to),
323
+ lt('mail.at', now),
324
+ absent('delivered'),
325
+ absent('bounced'),
326
+ fields('mail.at'),
327
+ ))
328
+ return waiting.filter((b) => {
329
+ let at = Date.parse(str(comp(b, 'mail').at))
330
+ return b.entity.eid != eid && Number.isFinite(at) &&
331
+ b.entity.eid == letterEid(store, to, day(at))
332
+ }).map((b) => ({ entity: b.entity, deliver: null }))
333
+ }
334
+
335
+ /** Write the digest due at `now` as a letter to `to`, once a day: a retried
336
+ * firing finds the day's letter. Only the newest scheduled digest still
337
+ * asks to go when the sender comes back. */
338
+ export let send = async (
339
+ g: Desk,
340
+ now: number,
341
+ { to, from, url, store, chart, key, fired, more }: Sending,
342
+ report: (error: unknown) => void = () => {},
343
+ ): Promise<void> => {
344
+ if (!to) return
345
+ let eid = letterEid(store, to, key ?? day(now))
346
+ let [held] = await g.get([eid], ['mail'])
347
+ if (held?.mail) return
348
+ let since = new Date(now - SPAN * DAY).toISOString()
349
+ let found = new Map<string, Bundle>()
350
+ for (let q of reads(since)) {
351
+ for (let b of await g.read(q)) found.set(b.entity.eid, b)
352
+ }
353
+ let link = (path: string) => url ? new URL(path, url).href : path
354
+ let timings = store == 'platform' || store == PLATFORM
355
+ ? interactionSummary(
356
+ await g.read(and(
357
+ eq('timing.op', INTERACTION),
358
+ ge('timing.at', new Date(now - DAY).toISOString()),
359
+ le('timing.at', new Date(now).toISOString()),
360
+ every(),
361
+ )),
362
+ )
363
+ : undefined
364
+ let warnings = await g.read(and(
365
+ eq('error.level', 'warning'),
366
+ ge('error.at', since),
367
+ fields('error.at'),
368
+ ))
369
+ let { title, body } = digest([...found.values()], now, {
370
+ bug: (bug) => link(remoteBug('yaks.app', bug, { scope: store })),
371
+ ...chart ? { chart } : {},
372
+ }, {
373
+ timing: timings,
374
+ warnings: warnings.map((b) => Date.parse(str(comp(b, 'error').at))),
375
+ })
376
+ let extra = more
377
+ ? await more(now).catch((e) => {
378
+ report(e)
379
+ return []
380
+ })
381
+ : []
382
+ if (extra.length) body = [...extra, body].join('\n\n')
383
+ let at = new Date(now).toISOString()
384
+ let older = fired ? await superseded(g, store, to, at, eid) : []
385
+ try {
386
+ await g.apply([
387
+ ...fired
388
+ ? [{ entity: fired.entity, $was: { fired: { at: token(fired.at) } } }]
389
+ : [],
390
+ ...older,
391
+ {
392
+ entity: { eid },
393
+ doc: { title, body },
394
+ mail: { at, ...from ? { from } : {} },
395
+ deliver: { to },
396
+ $was: { mail: { at: null } },
397
+ },
398
+ ], { trusted: true })
399
+ } catch (error) {
400
+ if (
401
+ !(error instanceof Stale) ||
402
+ !(error.eid == eid && error.comp == 'mail' ||
403
+ error.eid == fired?.entity.eid && error.comp == 'fired')
404
+ ) throw error
405
+ }
406
+ }
package/effects.js ADDED
@@ -0,0 +1,136 @@
1
+ // The downstream jobs. Intake never groups in its transaction; it only
2
+ // counts a flood's occurrences past what their bug keeps. No job writes a
3
+ // letter about one bug: agents hear of each bug from the open-bug watch
4
+ // (@yaks/heal), and a person from the daily digest (./digest.ts).
5
+ import { comp, str } from "./model.js";
6
+ import { group, reframe, trim } from "./group.js";
7
+ import { enrichFrames } from "./frames.js";
8
+ import { occurring } from "./reading.js";
9
+ import { explanation, unexplained } from "./resolution.js";
10
+ import { tags } from "./spread.js";
11
+ import { send } from "./digest.js";
12
+ /** A resolved bug closes the reports its occurrences stand for elsewhere: an
13
+ * occurrence tagged with another tracker's `scope` and its `occurrence` there
14
+ * (a break in a person's app, which yaks.app also records) is archived in
15
+ * that tracker, so the app's owner and their Operator stop hearing of a break
16
+ * yaks.app fixed; the reason is the resolution's cause. The resolution's
17
+ * explanation goes with them, and resolves the space's bug they leave with no
18
+ * open occurrence, so one fix never leaves a second copy open. An occurrence
19
+ * tagged `rerun` stopped work its owner (a space) keeps under the
20
+ * occurrence's fault, and each owner is handed the faults, so it runs that
21
+ * work again now it can finish (the tracker keeps one such occurrence of each
22
+ * owner, `retained`). Only occurrences from before the resolution are closed
23
+ * or run again; a later one is the bug back, open in both. Archiving again
24
+ * changes nothing, and an owner runs its work once for each bug, so a retry
25
+ * is safe.
26
+ *
27
+ * ```ts
28
+ * import { settle } from './effects.ts'
29
+ * import { equal } from '@yaks/testing'
30
+ * let at = (eid: string, t: string, tags = {}) =>
31
+ * ({ entity: { eid }, error: { at: t, bug: 'b', fault: 'f', tags } })
32
+ * let rows = [
33
+ * { entity: { eid: 'b' }, bug: {}, resolved: { at: '2026-10-18T16:00Z', cause: 'a leak', recur: 'no' } },
34
+ * at('e1', '2026-10-18T15:49Z', { scope: 's', occurrence: 'o1' }),
35
+ * at('e2', '2026-10-18T15:50Z', { scope: 's', occurrence: 'o2' }),
36
+ * at('e3', '2026-10-18T15:51Z'),
37
+ * at('e4', '2026-10-19T09:00Z', { scope: 's', occurrence: 'o4' }),
38
+ * at('e5', '2026-10-18T15:52Z', { rerun: 'ada' }),
39
+ * at('e6', '2026-10-19T09:01Z', { rerun: 'bo' }),
40
+ * ]
41
+ * let g = {
42
+ * get: (eids: string[]) => Promise.resolve(rows.filter((r) => eids.includes(r.entity.eid))),
43
+ * read: () => Promise.resolve(rows.filter((r) => 'error' in r)),
44
+ * }
45
+ * let sent: unknown[][] = [], ran: unknown[][] = []
46
+ * await settle(g as never, 'b', {
47
+ * settle: (...a) => Promise.resolve(sent.push(a)),
48
+ * rerun: (...a) => Promise.resolve(ran.push(a)),
49
+ * })
50
+ * let said = { cause: 'a leak', recur: 'no' }
51
+ * equal(sent, [['s', ['o1', 'o2'], 'Fixed by yaks.app: a leak', said]])
52
+ * equal(ran, [['ada', ['f'], 'b', said]])
53
+ * ```
54
+ */ export let settle = async (g, eid, options)=>{
55
+ if (!options.settle && !options.rerun) return;
56
+ let [row] = await g.get([
57
+ eid
58
+ ]);
59
+ if (!row?.bug || !row.resolved) return;
60
+ let resolved = comp(row, 'resolved');
61
+ let until = str(resolved.at);
62
+ let why = str(resolved.cause) || str(resolved.broke);
63
+ let reason = why ? `Fixed by yaks.app: ${why}` : 'Fixed by yaks.app';
64
+ // A resolution from before explanations were kept resolves nothing more.
65
+ let said = unexplained(resolved).length ? undefined : explanation(resolved);
66
+ let by = new Map(), runs = new Map();
67
+ for (let b of (await g.read(occurring(eid)))){
68
+ let error = comp(b, 'error');
69
+ if (str(error.at) > until) continue;
70
+ let { scope, occurrence, rerun } = Object.fromEntries(tags(b));
71
+ if (scope && occurrence) by.set(scope, [
72
+ ...by.get(scope) ?? [],
73
+ occurrence
74
+ ]);
75
+ if (rerun && error.fault) {
76
+ runs.set(rerun, (runs.get(rerun) ?? new Set()).add(str(error.fault)));
77
+ }
78
+ }
79
+ if (options.settle) {
80
+ for (let [scope, eids] of by){
81
+ await options.settle(scope, eids, reason, said);
82
+ }
83
+ }
84
+ if (options.rerun) {
85
+ for (let [owner, faults] of runs){
86
+ await options.rerun(owner, [
87
+ ...faults
88
+ ], eid, said);
89
+ }
90
+ }
91
+ };
92
+ export let effects = (host, options = {})=>{
93
+ let enrich = options.enrich ?? enrichFrames();
94
+ return {
95
+ // Grouping trims the bug it grew, which reads one row until the bug
96
+ // outgrows what it keeps: a run of its own per report cost more rows
97
+ // than the report.
98
+ error_group: async (e)=>{
99
+ let bug = await group(host.graph, e.entity.eid);
100
+ if (bug) await trim(host.graph, bug, options.retain);
101
+ },
102
+ error_frames: async (e, _tx, _write, attempt)=>{
103
+ try {
104
+ await reframe(host.graph, e.entity.eid, enrich);
105
+ } catch (error) {
106
+ if (attempt?.defer && error && typeof error == 'object' && 'retry' in error) {
107
+ await attempt.defer(5_000);
108
+ return;
109
+ }
110
+ throw error;
111
+ }
112
+ },
113
+ // The day's digest is the one due when its wake fired, so a retry
114
+ // writes the same letter.
115
+ bug_digest: async (e)=>{
116
+ let [row] = await host.graph.get([
117
+ e.entity.eid
118
+ ], [
119
+ 'fired'
120
+ ]);
121
+ let fired = str(comp(row, 'fired').at);
122
+ let at = Date.parse(fired);
123
+ if (Number.isFinite(at)) {
124
+ await send(host.graph, at, {
125
+ ...options,
126
+ fired: {
127
+ entity: row.entity,
128
+ at: fired
129
+ }
130
+ }, (e)=>void options.report?.(e));
131
+ }
132
+ },
133
+ bug_settle: (e)=>settle(host.graph, e.entity.eid, options)
134
+ };
135
+ };
136
+ //# sourceMappingURL=effects.js.map
package/effects.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"effects.js","sources":["./effects.ts"],"names":[],"mappings":"AAAA,uEAAuE;AACvE,0EAA0E;AAC1E,wEAAwE;AACxE,kEAAkE;AAIlE,SAAS,IAAI,EAAa,GAAG,qBAAoB;AACjD,SAAsB,KAAK,EAAE,OAAO,EAAE,IAAI,qBAAoB;AAC9D,SAAS,YAAY,sBAAqB;AAC1C,SAAS,SAAS,uBAAsB;AACxC,SAA2B,WAAW,EAAE,WAAW,0BAAyB;AAC5E,SAAS,IAAI,sBAAqB;AAClC,SAAS,IAAI,sBAAqB;A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