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
notify.ts8.3 KB · 309 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
/**
 * Notifications + audit log helpers.
 * Swallows DB failures so notifications never break the primary request path.
 *
 * Email fan-out (Block A8):
 *   For certain kinds (mention / assigned / gate_failed / review_requested)
 *   we ALSO send an email, if the recipient has opted in via their profile
 *   preferences. Email failures are logged and swallowed.
 */

import { inArray, eq, and, desc, sql } from "drizzle-orm";
import { db } from "../db";
import { notifications as notificationsMain, auditLog, users } from "../db/schema";
import { notifications as notificationsExt } from "../db/schema-extensions";
import { sendEmail, absoluteUrl } from "./email";

// ─── Public helpers (schema-extensions notifications table) ─────────────────
// These operate on the schema-extensions `notifications` table (which has
// `type`, `isRead`, `actorId` columns) — the same table the inbox page uses.

/** Create a single in-app notification. Fire-and-forget safe: swallows errors. */
export async function createNotification(params: {
  userId: string;
  type: string;
  title: string;
  body?: string;
  url?: string;
  repoId?: string;
}): Promise<void> {
  try {
    await db.insert(notificationsExt).values({
      userId: params.userId,
      type: params.type,
      title: params.title,
      body: params.body,
      url: params.url,
      repositoryId: params.repoId,
    });
  } catch (err) {
    console.error("[createNotification] failed:", err);
  }
}

/** Return the count of unread notifications for a user. Returns 0 on error. */
export async function getUnreadCount(userId: string): Promise<number> {
  try {
    const [row] = await db
      .select({ count: sql<number>`count(*)` })
      .from(notificationsExt)
      .where(and(eq(notificationsExt.userId, userId), eq(notificationsExt.isRead, false)));
    return Number(row?.count ?? 0);
  } catch {
    return 0;
  }
}

/** Return notifications for a user (most recent first). Returns [] on error. */
export async function getNotifications(
  userId: string,
  limit = 50
): Promise<typeof notificationsExt.$inferSelect[]> {
  try {
    return await db
      .select()
      .from(notificationsExt)
      .where(eq(notificationsExt.userId, userId))
      .orderBy(desc(notificationsExt.createdAt))
      .limit(limit);
  } catch {
    return [];
  }
}

/** Mark a single notification as read (only if it belongs to userId). */
export async function markRead(notificationId: string, userId: string): Promise<void> {
  try {
    await db
      .update(notificationsExt)
      .set({ isRead: true })
      .where(and(eq(notificationsExt.id, notificationId), eq(notificationsExt.userId, userId)));
  } catch (err) {
    console.error("[markRead] failed:", err);
  }
}

/** Mark all of a user's notifications as read. */
export async function markAllRead(userId: string): Promise<void> {
  try {
    await db
      .update(notificationsExt)
      .set({ isRead: true })
      .where(and(eq(notificationsExt.userId, userId), eq(notificationsExt.isRead, false)));
  } catch (err) {
    console.error("[markAllRead] failed:", err);
  }
}

export type NotificationKind =
  | "mention"
  | "review_requested"
  | "pr_opened"
  | "pr_merged"
  | "pr_closed"
  | "issue_opened"
  | "issue_closed"
  | "assigned"
  | "ai_review"
  | "gate_failed"
  | "gate_repaired"
  | "gate_passed"
  | "security_alert"
  | "deploy_success"
  | "deploy_failed"
  | "deployment_approval"
  | "release_published"
  | "repo_archived"
  | "pr_stale"
  | "issue_stale";

/** Kinds that can trigger email delivery. Keep this list conservative — any
 *  kind here must map to a user preference column on the users table. */
const EMAIL_ELIGIBLE: ReadonlySet<NotificationKind> = new Set([
  "mention",
  "review_requested",
  "assigned",
  "gate_failed",
]);

/** Map notification kind → user preference column name. */
function prefFor(kind: NotificationKind):
  | "notifyEmailOnMention"
  | "notifyEmailOnAssign"
  | "notifyEmailOnGateFail"
  | null {
  switch (kind) {
    case "mention":
    case "review_requested":
      return "notifyEmailOnMention";
    case "assigned":
      return "notifyEmailOnAssign";
    case "gate_failed":
      return "notifyEmailOnGateFail";
    default:
      return null;
  }
}

function subjectFor(kind: NotificationKind, title: string): string {
  const tag =
    kind === "gate_failed"
      ? "[gate failed]"
      : kind === "assigned"
      ? "[assigned]"
      : kind === "review_requested"
      ? "[review requested]"
      : kind === "mention"
      ? "[mention]"
      : `[${kind}]`;
  return `${tag} ${title}`.slice(0, 180);
}

function bodyFor(title: string, body: string | undefined, url: string | undefined): string {
  const lines = [title];
  if (body) lines.push("", body);
  if (url) lines.push("", absoluteUrl(url));
  lines.push("", "—", "You can opt out of these emails at /settings.");
  return lines.join("\n");
}

async function maybeEmail(
  userIds: string[],
  kind: NotificationKind,
  opts: { title: string; body?: string; url?: string }
): Promise<void> {
  if (!EMAIL_ELIGIBLE.has(kind)) return;
  const prefCol = prefFor(kind);
  if (!prefCol) return;
  if (userIds.length === 0) return;

  let recipients: Array<{ email: string; pref: boolean }> = [];
  try {
    const rows = await db
      .select({
        id: users.id,
        email: users.email,
        mention: users.notifyEmailOnMention,
        assign: users.notifyEmailOnAssign,
        gate: users.notifyEmailOnGateFail,
      })
      .from(users)
      .where(inArray(users.id, userIds));
    recipients = rows.map((r) => ({
      email: r.email,
      pref:
        prefCol === "notifyEmailOnMention"
          ? r.mention
          : prefCol === "notifyEmailOnAssign"
          ? r.assign
          : r.gate,
    }));
  } catch (err) {
    console.error("[notify] email recipient lookup failed:", err);
    return;
  }

  const subject = subjectFor(kind, opts.title);
  const text = bodyFor(opts.title, opts.body, opts.url);

  // Fire in parallel; each call swallows its own errors.
  await Promise.all(
    recipients
      .filter((r) => r.pref && r.email)
      .map((r) =>
        sendEmail({ to: r.email, subject, text }).catch((err) => {
          console.error("[notify] sendEmail threw:", err);
          return { ok: false as const, provider: "none" as const };
        })
      )
  );
}

export async function notify(
  userId: string,
  opts: {
    kind: NotificationKind;
    title: string;
    body?: string;
    url?: string;
    repositoryId?: string;
  }
): Promise<void> {
  try {
    await db.insert(notificationsMain).values({
      userId,
      kind: opts.kind,
      title: opts.title,
      body: opts.body,
      url: opts.url,
      repositoryId: opts.repositoryId,
    });
  } catch (err) {
    console.error("[notify] failed:", err);
  }
  await maybeEmail([userId], opts.kind, opts);
}

export async function notifyMany(
  userIds: string[],
  opts: {
    kind: NotificationKind;
    title: string;
    body?: string;
    url?: string;
    repositoryId?: string;
  }
): Promise<void> {
  const unique = Array.from(new Set(userIds));
  if (unique.length === 0) return;
  try {
    await db.insert(notificationsMain).values(
      unique.map((userId) => ({
        userId,
        kind: opts.kind,
        title: opts.title,
        body: opts.body,
        url: opts.url,
        repositoryId: opts.repositoryId,
      }))
    );
  } catch (err) {
    console.error("[notify] batch failed:", err);
  }
  await maybeEmail(unique, opts.kind, opts);
}

export async function audit(opts: {
  userId?: string | null;
  repositoryId?: string | null;
  action: string;
  targetType?: string;
  targetId?: string;
  ip?: string;
  userAgent?: string;
  metadata?: Record<string, unknown>;
}): Promise<void> {
  try {
    await db.insert(auditLog).values({
      userId: opts.userId ?? null,
      repositoryId: opts.repositoryId ?? null,
      action: opts.action,
      targetType: opts.targetType,
      targetId: opts.targetId,
      ip: opts.ip,
      userAgent: opts.userAgent,
      metadata: opts.metadata ? JSON.stringify(opts.metadata) : null,
    });
  } catch (err) {
    // Audit must never break the primary flow
    console.error("[audit] failed:", err);
  }
}

/** Test-only hook so unit tests can assert the kind→pref mapping. */
export const __internal = {
  EMAIL_ELIGIBLE,
  prefFor,
  subjectFor,
  bodyFor,
};