Pre-launch — Gluecron is in final validation. Public signups and git hosting for non-owner users open after launch review.
CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
claude/adoring-hopper-5x74bqclaude/affectionate-feynman-ykrf1hclaude/architecture-audit-design-wxprenclaude/build-status-update-3MXsfclaude/charming-meitner-mllb5rclaude/compare-gate-gluecron-s4mFQclaude/confident-faraday-tikcwbclaude/continue-work-XMTlIclaude/crontech-gluecron-deploy-7MIECclaude/crontech-platform-setup-SeKfwclaude/design-2026claude/ecstatic-ptolemy-jMdigclaude/enhance-github-integration-QNHdGclaude/fix-aa-loop-issue-PonMQclaude/fix-actions-and-processclaude/fix-desktop-errors-XqoW8claude/fix-red-workflowsclaude/fix-website-access-6FKJNclaude/gatetest-integration-hardeningclaude/github-audit-improvements-bDFr9claude/gluecron-launch-status-FoMRlclaude/hopeful-lamport-olfCTclaude/issue-to-pr-and-protectionsclaude/jolly-heisenberg-2sg1Qclaude/launch-preparation-QmTb6claude/new-session-xk1l7claude/plan-platform-architecture-kkN4yclaude/platform-analysis-roadmap-1nUGLclaude/platform-launch-assessment-8dWV8claude/polish-platform-release-AeDrUclaude/resume-previous-work-KzyLwclaude/review-crontech-handoff-qYEVqclaude/review-project-completeness-lHhS2claude/review-readme-docs-ulqPKclaude/serene-edison-rj87weclaude/setup-multi-repo-dev-BCwNQclaude/ship-fixes-and-tests-Jvz1cclaude/site-audit-competitive-pctlwgclaude/site-migration-vercel-XstpKclaude/standalone-product-repos-XHFTDcopilot/feat-smart-empty-states-keyboard-first-enhancementcopilot/feat-smart-morning-digest-review-context-restorecopilot/fix-and-process-workflowscopilot/update-ai-powered-code-reviewfeat/debt-mapfeat/push-policy-codeowners-hardeningfeat/smart-digest-contextfeat/stage-impactfeat/t1-secret-migrationfeat/u-polishfeat/w-self-hostfeat/w2-claude-configfix/agent-journey-orphan-sweepgatetest/auto-fix-1776586424172gatetest/auto-fix-1776586534814gatetest/auto-fix-1776590685143gatetest/auto-fix-1776590808199mainops/redeploy-retriggerstyle/dxt-cta-themeworktree-agent-a3377aad30d55da26worktree-agent-a7ef607b7ee1d6c74
sleep-mode.test.ts12.1 KB · 355 lines
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
/**
 * Block L1 — Sleep Mode tests.
 *
 * Covers:
 *   - `renderSleepModeDigest` HTML + plaintext output, including XSS resistance
 *   - `computeHoursSaved` heuristic
 *   - autopilot `sleep-mode-digest` task: cooldown, hour-match, enabled filter,
 *     per-tick cap, per-user failure isolation
 *   - `/sleep-mode` public marketing page returns 200
 *   - `composeSleepModeReport` zero report for a user with no repos
 *
 * DI test pattern follows K3's `autopilot-ai-tasks.test.ts` — every DB call is
 * dependency-injected so tests run without a real DB.
 */

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";

// ---------------------------------------------------------------------------
// Fixtures
// ---------------------------------------------------------------------------

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,
  };
}

// ---------------------------------------------------------------------------
// computeHoursSaved
// ---------------------------------------------------------------------------

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)", () => {
    // 2*0.3 + 1*1.5 + 3*0.25 + (1+2)*0.5 = 0.6 + 1.5 + 0.75 + 1.5 = 4.35 -> 4.4
    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", () => {
    // 1*0.25 = 0.25 -> rounded *10 = 2.5 -> Math.round(2.5)=3 -> 0.3
    expect(
      computeHoursSaved({
        prsAutoMerged: 0,
        issuesBuiltByAi: 0,
        aiReviewsPosted: 1,
        securityIssuesAutoFixed: 0,
        gateFailuresAutoRepaired: 0,
      })
    ).toBe(0.3);
  });
});

// ---------------------------------------------------------------------------
// renderSleepModeDigest
// ---------------------------------------------------------------------------

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");
    // No section headers on the empty report — nothing to list.
    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");
    // 2 PRs + 1 issue + 3 reviews + 1 sec + 2 gates = 9 items
    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();
    // No raw <script> tags — they must be escaped to &lt;script&gt;.
    expect(lower).not.toContain("<script>");
    expect(lower).not.toContain("</script>");
    // No live attribute injection — the `<img` open-tag and `<svg` open-tag
    // must be escaped. (Substring search for `onerror=` would yield a false
    // positive because the escaped &lt;img&gt; still contains the literal
    // characters, but inside escaped angle-brackets they can't execute.)
    expect(lower).not.toContain("<img");
    expect(lower).not.toContain("<svg");
    // The escaped form must be present.
    expect(out.html).toContain("&lt;script&gt;");
    expect(out.html).toContain("&lt;b&gt;boss&lt;/b&gt;");
    expect(out.html).toContain("&lt;img src=x onerror=1&gt;");
    expect(out.html).toContain("&lt;svg/onload=alert(1)&gt;");
    // Plaintext should still contain the un-escaped strings (it IS plain text).
    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");
  });
});

// ---------------------------------------------------------------------------
// composeSleepModeReport (DB-touching; graceful when DB unavailable)
// ---------------------------------------------------------------------------

describe("sleep-mode — composeSleepModeReport", () => {
  it("returns a zero-valued report for a user with no repos (graceful)", async () => {
    // Use a random UUID — guaranteed no owned repos. Either the DB query
    // returns empty (and we get an empty report) or the DB is unavailable
    // (and we fall through the catch block to the same empty report).
    // Either way the function must NEVER throw and must return all-zeros.
    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);
  });
});

// ---------------------------------------------------------------------------
// runSleepModeDigestTaskOnce
// ---------------------------------------------------------------------------

describe("sleep-mode — autopilot task (runSleepModeDigestTaskOnce)", () => {
  const sentinelNow = new Date("2026-05-13T09:00:00Z"); // UTC hour = 9

  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[] = [];
    // Sent 1h ago — within cooldown.
    const recent = new Date(sentinelNow.getTime() - 60 * 60 * 1000);
    // Sent 24h ago — past cooldown.
    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);
  });
});

// ---------------------------------------------------------------------------
// /sleep-mode public route
// ---------------------------------------------------------------------------

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");
    // Sample digest is rendered inline as part of the page.
    expect(body).toContain("Good morning");
    // CTA link target.
    expect(body).toContain('href="/settings"');
  });
});