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
email-digest.ts8.9 KB · 312 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
/**
 * Block I7 — Weekly email digest.
 *
 * Composes a per-user digest of activity over the last 7 days (or a custom
 * window) and sends it via the shared email module. Run from a cron or
 * manually via `POST /admin/digests/run`.
 *
 * Data sources:
 *   - notifications    (unread + read-last-7d)
 *   - gate_runs        (failed / repaired)
 *   - pull_requests    (merged by the user's repos)
 *
 * Never throws — the caller can fire-and-forget.
 */

import { and, desc, eq, gte, inArray, sql } from "drizzle-orm";
import { db } from "./../db";
import {
  gateRuns,
  notifications,
  pullRequests,
  repositories,
  users,
} from "./../db/schema";
import { sendEmail, type EmailResult } from "./email";
import { config } from "./config";

export interface DigestInput {
  userId: string;
  since?: Date;
  /** When false, skip `sendEmail` and just compose. Used for preview. */
  send?: boolean;
}

export interface DigestBody {
  subject: string;
  text: string;
  html: string;
  counts: {
    notifications: number;
    failedGates: number;
    repairedGates: number;
    mergedPrs: number;
  };
}

function fmtRange(from: Date, to: Date): string {
  const f = from.toISOString().slice(0, 10);
  const t = to.toISOString().slice(0, 10);
  return f === t ? f : `${f} \u2192 ${t}`;
}

export async function composeDigest(
  userId: string,
  since?: Date
): Promise<DigestBody | null> {
  const now = new Date();
  const from = since || new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
  try {
    const [user] = await db
      .select()
      .from(users)
      .where(eq(users.id, userId))
      .limit(1);
    if (!user) return null;

    // Pull notifications
    const notifs = await db
      .select()
      .from(notifications)
      .where(
        and(
          eq(notifications.userId, userId),
          gte(notifications.createdAt, from)
        )
      )
      .orderBy(desc(notifications.createdAt))
      .limit(25);

    // User's repos (owner only — org-aware digest can come later)
    const ownedRepos = await db
      .select({ id: repositories.id, name: repositories.name })
      .from(repositories)
      .where(eq(repositories.ownerId, userId));
    const repoIds = ownedRepos.map((r) => r.id);

    let failedGates: Array<{ repoName: string; gateName: string; sha: string }> = [];
    let repairedGates: Array<{ repoName: string; gateName: string; sha: string }> = [];
    let mergedPrs: Array<{ repoName: string; title: string }> = [];

    if (repoIds.length > 0) {
      const gates = await db
        .select()
        .from(gateRuns)
        .where(
          and(
            inArray(gateRuns.repositoryId, repoIds),
            gte(gateRuns.createdAt, from)
          )
        )
        .orderBy(desc(gateRuns.createdAt))
        .limit(50);
      const byId = new Map(ownedRepos.map((r) => [r.id, r.name]));
      for (const g of gates) {
        const repoName = byId.get(g.repositoryId) || "?";
        if (g.status === "failed") {
          failedGates.push({
            repoName,
            gateName: g.gateName,
            sha: g.commitSha.slice(0, 7),
          });
        } else if (g.status === "repaired") {
          repairedGates.push({
            repoName,
            gateName: g.gateName,
            sha: g.commitSha.slice(0, 7),
          });
        }
      }

      const merged = await db
        .select()
        .from(pullRequests)
        .where(
          and(
            inArray(pullRequests.repositoryId, repoIds),
            eq(pullRequests.state, "merged"),
            gte(pullRequests.updatedAt, from)
          )
        )
        .limit(25);
      for (const pr of merged) {
        mergedPrs.push({
          repoName: byId.get(pr.repositoryId) || "?",
          title: pr.title,
        });
      }
    }

    const counts = {
      notifications: notifs.length,
      failedGates: failedGates.length,
      repairedGates: repairedGates.length,
      mergedPrs: mergedPrs.length,
    };

    const base = config.appBaseUrl || "https://gluecron.com";
    const subject = `Your Gluecron digest (${fmtRange(from, now)})`;
    const lines: string[] = [];
    lines.push(`Hi ${user.username},`);
    lines.push("");
    lines.push(`Here's what happened across your repos this week.`);
    lines.push("");
    lines.push(
      `Notifications: ${counts.notifications}  ·  Failed gates: ${counts.failedGates}  ·  Auto-repaired: ${counts.repairedGates}  ·  PRs merged: ${counts.mergedPrs}`
    );
    lines.push("");

    if (notifs.length > 0) {
      lines.push("## Notifications");
      for (const n of notifs.slice(0, 10)) {
        const when = new Date(n.createdAt).toLocaleDateString();
        lines.push(`- [${n.kind}] ${n.title || "(untitled)"}${when}`);
      }
      lines.push("");
    }

    if (failedGates.length > 0) {
      lines.push("## Failed gates");
      for (const g of failedGates.slice(0, 10)) {
        lines.push(`- ${g.repoName}${g.gateName} (${g.sha})`);
      }
      lines.push("");
    }

    if (repairedGates.length > 0) {
      lines.push("## Auto-repairs");
      for (const g of repairedGates.slice(0, 10)) {
        lines.push(`- ${g.repoName}${g.gateName} (${g.sha})`);
      }
      lines.push("");
    }

    if (mergedPrs.length > 0) {
      lines.push("## Merged PRs");
      for (const pr of mergedPrs.slice(0, 10)) {
        lines.push(`- ${pr.repoName}${pr.title}`);
      }
      lines.push("");
    }

    lines.push("---");
    lines.push(
      `You're receiving this because you opted into weekly digests. Manage at ${base}/settings.`
    );

    const text = lines.join("\n");
    const html = textToHtml(text, base);
    return { subject, text, html, counts };
  } catch (err) {
    console.error("[digest] composeDigest error:", err);
    return null;
  }
}

function textToHtml(text: string, base: string): string {
  const lines = text.split("\n");
  const out: string[] = [
    `<html><body style="font-family:system-ui,sans-serif;max-width:640px;margin:0 auto;padding:24px;color:#111">`,
  ];
  for (const line of lines) {
    if (line.startsWith("## ")) {
      out.push(
        `<h3 style="border-bottom:1px solid #eee;padding-bottom:4px;margin-top:24px">${escapeHtml(line.slice(3))}</h3>`
      );
    } else if (line.startsWith("- ")) {
      out.push(`<li>${escapeHtml(line.slice(2))}</li>`);
    } else if (line === "---") {
      out.push(`<hr style="border:none;border-top:1px solid #eee;margin:24px 0" />`);
    } else if (line.trim() === "") {
      out.push("<br>");
    } else {
      out.push(`<p>${escapeHtml(line)}</p>`);
    }
  }
  out.push(
    `<p style="font-size:12px;color:#777"><a href="${escapeHtml(base)}">${escapeHtml(base)}</a></p>`
  );
  out.push("</body></html>");
  return out.join("\n");
}

function escapeHtml(s: string): string {
  return s
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;");
}

/** Compose + send for a single user. Records `last_digest_sent_at` on success. */
export async function sendDigestForUser(
  userId: string
): Promise<EmailResult | { ok: false; provider: "none"; skipped: string }> {
  try {
    const [user] = await db
      .select()
      .from(users)
      .where(eq(users.id, userId))
      .limit(1);
    if (!user) return { ok: false, provider: "none", skipped: "user not found" };
    if (!user.notifyEmailDigestWeekly) {
      return { ok: false, provider: "none", skipped: "opted out" };
    }
    const body = await composeDigest(userId);
    if (!body) {
      return { ok: false, provider: "none", skipped: "compose failed" };
    }
    const result = await sendEmail({
      to: user.email,
      subject: body.subject,
      text: body.text,
      html: body.html,
    });
    if (result.ok) {
      await db
        .update(users)
        .set({ lastDigestSentAt: new Date() })
        .where(eq(users.id, userId));
    }
    return result;
  } catch (err) {
    console.error("[digest] sendDigestForUser error:", err);
    return { ok: false, provider: "none", skipped: "error" };
  }
}

/** Iterates all opted-in users. Returns per-user results for logging. */
export async function sendDigestsToAll(): Promise<
  Array<{ userId: string; username: string; ok: boolean; skipped?: string }>
> {
  const results: Array<{
    userId: string;
    username: string;
    ok: boolean;
    skipped?: string;
  }> = [];
  try {
    const opted = await db
      .select({ id: users.id, username: users.username })
      .from(users)
      .where(eq(users.notifyEmailDigestWeekly, true));
    for (const u of opted) {
      const r = await sendDigestForUser(u.id);
      results.push({
        userId: u.id,
        username: u.username,
        ok: r.ok,
        skipped: "skipped" in r ? r.skipped : undefined,
      });
    }
  } catch (err) {
    console.error("[digest] sendDigestsToAll error:", err);
  }
  return results;
}

/** Pure helper exported for tests. */
export const __internal = { textToHtml, escapeHtml, fmtRange };

// Keep sql unused-import warnings silent
void sql;