1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
|
import { describe, it, expect } from "bun:test";
import app from "../app";
import {
renderSleepModeDigest,
composeSleepModeReport,
computeHoursSaved,
type SleepModeReport,
} from "../lib/sleep-mode";
import {
runSleepModeDigestTaskOnce,
type SleepModeDigestCandidate,
} from "../lib/autopilot";
function emptyReport(): SleepModeReport {
return {
windowHours: 24,
prsAutoMerged: [],
issuesBuiltByAi: [],
aiReviewsPosted: 0,
securityIssuesAutoFixed: 0,
gateFailuresAutoRepaired: 0,
hoursSaved: 0,
};
}
function busyReport(): SleepModeReport {
return {
windowHours: 24,
prsAutoMerged: [
{ number: 1, title: "Bump axios", repo: "api" },
{ number: 2, title: "Fix retry", repo: "billing" },
],
issuesBuiltByAi: [
{ number: 7, title: "Add /metrics", repo: "api", prNumber: 8 },
],
aiReviewsPosted: 3,
securityIssuesAutoFixed: 1,
gateFailuresAutoRepaired: 2,
hoursSaved: 0,
};
}
describe("sleep-mode — computeHoursSaved", () => {
it("returns 0 for an empty report", () => {
expect(
computeHoursSaved({
prsAutoMerged: 0,
issuesBuiltByAi: 0,
aiReviewsPosted: 0,
securityIssuesAutoFixed: 0,
gateFailuresAutoRepaired: 0,
})
).toBe(0);
});
it("applies the documented heuristic (rounded to 1 decimal)", () => {
const v = computeHoursSaved({
prsAutoMerged: 2,
issuesBuiltByAi: 1,
aiReviewsPosted: 3,
securityIssuesAutoFixed: 1,
gateFailuresAutoRepaired: 2,
});
expect(v).toBe(4.4);
});
it("rounds .25 down per HALF_EVEN-ish .5-bias of Math.round", () => {
expect(
computeHoursSaved({
prsAutoMerged: 0,
issuesBuiltByAi: 0,
aiReviewsPosted: 1,
securityIssuesAutoFixed: 0,
gateFailuresAutoRepaired: 0,
})
).toBe(0.3);
});
});
describe("sleep-mode — renderSleepModeDigest", () => {
it("produces valid plaintext + html for an empty report", () => {
const out = renderSleepModeDigest(emptyReport(), { username: "alice" });
expect(out.subject).toContain("quiet night");
expect(out.text).toContain("Hi alice");
expect(out.text).toContain("Quiet night");
expect(out.html).toContain("<html>");
expect(out.html).toContain("Good morning, alice");
expect(out.html).not.toContain("PRs auto-merged</h3>");
});
it("produces a busy-night subject and lists every section", () => {
const out = renderSleepModeDigest(busyReport(), { username: "alice" });
expect(out.subject).toContain("Claude shipped");
expect(out.subject).toContain("9");
expect(out.html).toContain("PRs auto-merged");
expect(out.html).toContain("Issues built by AI");
expect(out.html).toContain("Automated guardrails");
expect(out.text).toContain("## PRs auto-merged");
expect(out.text).toContain("## Issues built by AI");
expect(out.text).toContain("## Automated guardrails");
});
it("escapes user-controlled titles, repo names, and usernames (no XSS)", () => {
const malicious: SleepModeReport = {
...emptyReport(),
prsAutoMerged: [
{
number: 1,
title: `<script>alert('pr')</script>`,
repo: `<img src=x onerror=1>`,
},
],
issuesBuiltByAi: [
{
number: 2,
title: `<svg/onload=alert(1)>`,
repo: `"><script>x</script>`,
},
],
};
const out = renderSleepModeDigest(malicious, {
username: `<b>boss</b>`,
});
const lower = out.html.toLowerCase();
expect(lower).not.toContain("<script>");
expect(lower).not.toContain("</script>");
expect(lower).not.toContain("<img");
expect(lower).not.toContain("<svg");
expect(out.html).toContain("<script>");
expect(out.html).toContain("<b>boss</b>");
expect(out.html).toContain("<img src=x onerror=1>");
expect(out.html).toContain("<svg/onload=alert(1)>");
expect(out.text).toContain("<script>alert('pr')</script>");
});
it("subject is singular vs plural for total=1 case", () => {
const r: SleepModeReport = {
...emptyReport(),
prsAutoMerged: [{ number: 1, title: "x", repo: "r" }],
};
const out = renderSleepModeDigest(r, { username: "alice" });
expect(out.subject).toContain("shipped 1 thing");
expect(out.subject).not.toContain("shipped 1 things");
});
});
describe("sleep-mode — composeSleepModeReport", () => {
it("returns a zero-valued report for a user with no repos (graceful)", async () => {
const r = await composeSleepModeReport(
"00000000-0000-0000-0000-000000000000"
);
expect(r.prsAutoMerged).toEqual([]);
expect(r.issuesBuiltByAi).toEqual([]);
expect(r.aiReviewsPosted).toBe(0);
expect(r.securityIssuesAutoFixed).toBe(0);
expect(r.gateFailuresAutoRepaired).toBe(0);
expect(r.hoursSaved).toBe(0);
expect(r.windowHours).toBe(24);
});
it("respects custom sinceHoursAgo", async () => {
const r = await composeSleepModeReport(
"00000000-0000-0000-0000-000000000000",
{ sinceHoursAgo: 48 }
);
expect(r.windowHours).toBe(48);
});
});
describe("sleep-mode — autopilot task (runSleepModeDigestTaskOnce)", () => {
const sentinelNow = new Date("2026-05-13T09:00:00Z");
function cand(
overrides: Partial<SleepModeDigestCandidate> = {}
): SleepModeDigestCandidate {
return {
userId: "u-1",
digestHourUtc: 9,
lastDigestSentAt: null,
...overrides,
};
}
it("sends for users whose current UTC hour matches their digestHourUtc and cooldown is clear", async () => {
const sent: string[] = [];
const summary = await runSleepModeDigestTaskOnce({
findCandidates: async () => [cand({ userId: "alice" })],
sendOne: async (id) => {
sent.push(id);
return { ok: true };
},
now: () => sentinelNow,
});
expect(sent).toEqual(["alice"]);
expect(summary).toEqual({ sent: 1, skipped: 0 });
});
it("skips users whose digestHourUtc does NOT match the current UTC hour", async () => {
const sent: string[] = [];
const summary = await runSleepModeDigestTaskOnce({
findCandidates: async () => [
cand({ userId: "alice", digestHourUtc: 9 }),
cand({ userId: "bob", digestHourUtc: 10 }),
cand({ userId: "carol", digestHourUtc: 8 }),
],
sendOne: async (id) => {
sent.push(id);
return { ok: true };
},
now: () => sentinelNow,
});
expect(sent).toEqual(["alice"]);
expect(summary).toEqual({ sent: 1, skipped: 2 });
});
it("skips users whose last digest was within the 23h cooldown", async () => {
const sent: string[] = [];
const recent = new Date(sentinelNow.getTime() - 60 * 60 * 1000);
const old = new Date(sentinelNow.getTime() - 24 * 60 * 60 * 1000);
const summary = await runSleepModeDigestTaskOnce({
findCandidates: async () => [
cand({ userId: "recent-user", lastDigestSentAt: recent }),
cand({ userId: "old-user", lastDigestSentAt: old }),
cand({ userId: "never-user", lastDigestSentAt: null }),
],
sendOne: async (id) => {
sent.push(id);
return { ok: true };
},
now: () => sentinelNow,
});
expect(sent.sort()).toEqual(["never-user", "old-user"]);
expect(summary).toEqual({ sent: 2, skipped: 1 });
});
it("counts sendOne ok:false as skipped (not sent)", async () => {
const summary = await runSleepModeDigestTaskOnce({
findCandidates: async () => [cand({ userId: "alice" })],
sendOne: async () => ({ ok: false, reason: "no email provider" }),
now: () => sentinelNow,
});
expect(summary).toEqual({ sent: 0, skipped: 1 });
});
it("isolates per-user failures — a thrown sendOne doesn't stop later users", async () => {
const sent: string[] = [];
const summary = await runSleepModeDigestTaskOnce({
findCandidates: async () => [
cand({ userId: "first" }),
cand({ userId: "second" }),
],
sendOne: async (id) => {
if (id === "first") throw new Error("kaboom");
sent.push(id);
return { ok: true };
},
now: () => sentinelNow,
});
expect(sent).toEqual(["second"]);
expect(summary).toEqual({ sent: 1, skipped: 1 });
});
it("returns zero summary if findCandidates throws", async () => {
const summary = await runSleepModeDigestTaskOnce({
findCandidates: async () => {
throw new Error("db down");
},
now: () => sentinelNow,
});
expect(summary).toEqual({ sent: 0, skipped: 0 });
});
it("honours a custom cap parameter", async () => {
let capRequested = -1;
await runSleepModeDigestTaskOnce({
findCandidates: async (cap) => {
capRequested = cap;
return [];
},
now: () => sentinelNow,
cap: 7,
});
expect(capRequested).toBe(7);
});
});
describe("sleep-mode — public marketing page", () => {
it("GET /sleep-mode returns 200 with the pitch", async () => {
const res = await app.request("/sleep-mode");
expect(res.status).toBe(200);
const body = await res.text();
expect(body).toContain("Sleep Mode");
expect(body).toContain("Wake up to a digest");
expect(body).toContain("Good morning");
expect(body).toContain('href="/settings"');
});
});
|