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
ai-hours-saved.ts15.0 KB · 413 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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
/**
 * Block L9 — AI hours-saved counter.
 *
 * Pure compute layer for the "Claude saved you X hours this week" widget
 * on the Command Center dashboard. Tallies AI-driven events across repos
 * the user owns and translates them into a transparent, audit-friendly
 * hours-saved estimate.
 *
 * ─── Formula (conservative, intentionally) ──────────────────────────
 *
 *   hoursSaved =
 *       prsAutoMerged       * 0.30   // avoid a click + a refresh
 *     + issuesBuiltByAi     * 1.50   // AI did the writing
 *     + aiReviewsPosted     * 0.25   // saved a manual review pass
 *     + aiTriagesPosted     * 0.10   // labels + reviewer suggestions
 *     + aiCommitMsgs        * 0.05   // tiny but counts
 *     + secretsAutoRepaired * 0.50   // would've been a panic
 *     + gateAutoRepairs     * 0.40   // would've been a re-run
 *
 * Round the final number to 1 decimal place. Constants are heuristics
 * — keep them conservative so users trust the counter. Audit-friendly
 * is the brand.
 *
 * `computeHoursSaved` is exported so L1 Sleep Mode (and anyone else
 * who needs the same value) can reuse the identical formula.
 *
 * Every async function in this module **never throws**: on DB error,
 * the report falls back to all-zero counts so the dashboard widget
 * always renders.
 */

import { and, eq, gte, inArray, like, or, sql } from "drizzle-orm";
import { db } from "../db";
import {
  auditLog,
  gateRuns,
  issueComments,
  issues,
  prComments,
  pullRequests,
  repositories,
  users,
} from "../db/schema";

// ───────────────────────────────────────────────────────────────────
// Types
// ───────────────────────────────────────────────────────────────────

export type AiSavingsBreakdown = {
  prsAutoMerged: number;
  issuesBuiltByAi: number;
  aiReviewsPosted: number;
  aiTriagesPosted: number;
  aiCommitMsgs: number;
  secretsAutoRepaired: number;
  gateAutoRepairs: number;
};

export type AiSavingsReport = {
  windowHours: number;
  breakdown: AiSavingsBreakdown;
  hoursSaved: number;
};

export type AiSavingsLifetimeReport = {
  hoursSaved: number;
  breakdown: AiSavingsBreakdown;
  sinceCreatedAt: Date;
};

/**
 * Marker substrings used to identify AI-authored content in tables
 * that don't have a dedicated `is_ai_*` flag. Importing from each
 * module would create a circular dependency in some test setups,
 * so we duplicate the small string constants here. If they ever
 * drift, the search will under-count — preferable to over-counting.
 */
const PR_TRIAGE_MARKER_FRAGMENT = "gluecron-pr-triage:summary";
const ISSUE_TRIAGE_MARKER_FRAGMENT = "gluecron-issue-triage:summary";

/** Audit-log action constants we look for. Public so callers (and
 *  tests) don't have to repeat string literals. */
export const AI_AUDIT_ACTIONS = {
  AUTO_MERGE_MERGED: "auto_merge.merged",
  AI_BUILD_DISPATCHED: "ai_build.dispatched",
  AI_COMMIT_MESSAGE: "ai.commit_message.generated",
} as const;

// ───────────────────────────────────────────────────────────────────
// Pure formula
// ───────────────────────────────────────────────────────────────────

/**
 * Pure decision helper. Translates an event breakdown into hours
 * saved using the documented formula. Synchronous + deterministic.
 *
 * Re-exported so Block L1 (Sleep Mode) can call the same function
 * and stay in lock-step with the dashboard widget number.
 */
export function computeHoursSaved(breakdown: AiSavingsBreakdown): number {
  const raw =
    breakdown.prsAutoMerged * 0.30 +
    breakdown.issuesBuiltByAi * 1.50 +
    breakdown.aiReviewsPosted * 0.25 +
    breakdown.aiTriagesPosted * 0.10 +
    breakdown.aiCommitMsgs * 0.05 +
    breakdown.secretsAutoRepaired * 0.50 +
    breakdown.gateAutoRepairs * 0.40;
  // Round to 1dp without floating-point drift surfacing in the UI.
  return Math.round(raw * 10) / 10;
}

/** Zero-valued breakdown — used as the fallback on DB error. */
export function emptyBreakdown(): AiSavingsBreakdown {
  return {
    prsAutoMerged: 0,
    issuesBuiltByAi: 0,
    aiReviewsPosted: 0,
    aiTriagesPosted: 0,
    aiCommitMsgs: 0,
    secretsAutoRepaired: 0,
    gateAutoRepairs: 0,
  };
}

// ───────────────────────────────────────────────────────────────────
// DI seam — collaborator interface for the counters
// ───────────────────────────────────────────────────────────────────

/**
 * One async function per breakdown counter, plus a `getRepoIds` helper
 * that resolves the set of repos a user owns. The default implementations
 * hit the DB; tests inject deterministic fakes.
 */
export interface AiSavingsDeps {
  getRepoIds: (userId: string) => Promise<string[]>;
  countPrsAutoMerged: (repoIds: string[], since: Date) => Promise<number>;
  countIssuesBuiltByAi: (repoIds: string[], since: Date) => Promise<number>;
  countAiReviewsPosted: (repoIds: string[], since: Date) => Promise<number>;
  countAiTriagesPosted: (repoIds: string[], since: Date) => Promise<number>;
  countAiCommitMsgs: (repoIds: string[], since: Date) => Promise<number>;
  countSecretsAutoRepaired: (repoIds: string[], since: Date) => Promise<number>;
  countGateAutoRepairs: (repoIds: string[], since: Date) => Promise<number>;
  getUserCreatedAt: (userId: string) => Promise<Date | null>;
}

// ───────────────────────────────────────────────────────────────────
// Default DB-backed implementations
// ───────────────────────────────────────────────────────────────────

const SECRET_GATE_NAMES = ["Secret scan", "Secret Scan", "Security scan", "Security Scan"];

async function defaultGetRepoIds(userId: string): Promise<string[]> {
  const rows = await db
    .select({ id: repositories.id })
    .from(repositories)
    .where(eq(repositories.ownerId, userId));
  return rows.map((r) => r.id);
}

async function defaultGetUserCreatedAt(userId: string): Promise<Date | null> {
  const rows = await db
    .select({ createdAt: users.createdAt })
    .from(users)
    .where(eq(users.id, userId))
    .limit(1);
  return rows[0]?.createdAt ?? null;
}

async function countAuditAction(
  repoIds: string[],
  since: Date,
  action: string
): Promise<number> {
  if (repoIds.length === 0) return 0;
  const rows = await db
    .select({ n: sql<number>`count(*)::int` })
    .from(auditLog)
    .where(
      and(
        eq(auditLog.action, action),
        inArray(auditLog.repositoryId, repoIds),
        gte(auditLog.createdAt, since)
      )
    );
  return Number(rows[0]?.n ?? 0);
}

async function defaultCountPrsAutoMerged(repoIds: string[], since: Date): Promise<number> {
  return countAuditAction(repoIds, since, AI_AUDIT_ACTIONS.AUTO_MERGE_MERGED);
}

async function defaultCountIssuesBuiltByAi(repoIds: string[], since: Date): Promise<number> {
  return countAuditAction(repoIds, since, AI_AUDIT_ACTIONS.AI_BUILD_DISPATCHED);
}

async function defaultCountAiCommitMsgs(repoIds: string[], since: Date): Promise<number> {
  // FOLLOW-UP: no producer currently emits this action — `ai-generators.ts
  // generateCommitMessage` is wired into routes but doesn't audit. Count is
  // always zero until a producer is added. Keep the formula honest by leaving
  // the constant at the smallest weight (0.05) so its omission rounds away.
  return countAuditAction(repoIds, since, AI_AUDIT_ACTIONS.AI_COMMIT_MESSAGE);
}

async function defaultCountAiReviewsPosted(repoIds: string[], since: Date): Promise<number> {
  if (repoIds.length === 0) return 0;
  const rows = await db
    .select({ n: sql<number>`count(*)::int` })
    .from(prComments)
    .innerJoin(pullRequests, eq(prComments.pullRequestId, pullRequests.id))
    .where(
      and(
        eq(prComments.isAiReview, true),
        inArray(pullRequests.repositoryId, repoIds),
        gte(prComments.createdAt, since)
      )
    );
  return Number(rows[0]?.n ?? 0);
}

async function defaultCountAiTriagesPosted(repoIds: string[], since: Date): Promise<number> {
  if (repoIds.length === 0) return 0;
  const [prRows, issueRows] = await Promise.all([
    db
      .select({ n: sql<number>`count(*)::int` })
      .from(prComments)
      .innerJoin(pullRequests, eq(prComments.pullRequestId, pullRequests.id))
      .where(
        and(
          like(prComments.body, `%${PR_TRIAGE_MARKER_FRAGMENT}%`),
          inArray(pullRequests.repositoryId, repoIds),
          gte(prComments.createdAt, since)
        )
      ),
    db
      .select({ n: sql<number>`count(*)::int` })
      .from(issueComments)
      .innerJoin(issues, eq(issueComments.issueId, issues.id))
      .where(
        and(
          like(issueComments.body, `%${ISSUE_TRIAGE_MARKER_FRAGMENT}%`),
          inArray(issues.repositoryId, repoIds),
          gte(issueComments.createdAt, since)
        )
      ),
  ]);
  return Number(prRows[0]?.n ?? 0) + Number(issueRows[0]?.n ?? 0);
}

async function defaultCountSecretsAutoRepaired(
  repoIds: string[],
  since: Date
): Promise<number> {
  if (repoIds.length === 0) return 0;
  const rows = await db
    .select({ n: sql<number>`count(*)::int` })
    .from(gateRuns)
    .where(
      and(
        eq(gateRuns.status, "repaired"),
        inArray(gateRuns.gateName, SECRET_GATE_NAMES),
        inArray(gateRuns.repositoryId, repoIds),
        gte(gateRuns.createdAt, since)
      )
    );
  return Number(rows[0]?.n ?? 0);
}

async function defaultCountGateAutoRepairs(
  repoIds: string[],
  since: Date
): Promise<number> {
  if (repoIds.length === 0) return 0;
  // All gates EXCEPT the secret/security ones (those are counted separately).
  const rows = await db
    .select({ n: sql<number>`count(*)::int` })
    .from(gateRuns)
    .where(
      and(
        eq(gateRuns.status, "repaired"),
        inArray(gateRuns.repositoryId, repoIds),
        gte(gateRuns.createdAt, since),
        sql`${gateRuns.gateName} NOT IN ('Secret scan','Secret Scan','Security scan','Security Scan')`
      )
    );
  return Number(rows[0]?.n ?? 0);
}

const DEFAULT_DEPS: AiSavingsDeps = {
  getRepoIds: defaultGetRepoIds,
  countPrsAutoMerged: defaultCountPrsAutoMerged,
  countIssuesBuiltByAi: defaultCountIssuesBuiltByAi,
  countAiReviewsPosted: defaultCountAiReviewsPosted,
  countAiTriagesPosted: defaultCountAiTriagesPosted,
  countAiCommitMsgs: defaultCountAiCommitMsgs,
  countSecretsAutoRepaired: defaultCountSecretsAutoRepaired,
  countGateAutoRepairs: defaultCountGateAutoRepairs,
  getUserCreatedAt: defaultGetUserCreatedAt,
};

// ───────────────────────────────────────────────────────────────────
// Public orchestrators
// ───────────────────────────────────────────────────────────────────

/**
 * Compute the rolling-window savings report for a single user.
 *
 * `windowHours` defaults to one week (168h). `now` lets tests pin
 * the cutoff deterministically. Never throws — DB errors degrade
 * to an all-zero breakdown.
 */
export async function computeAiSavingsForUser(
  userId: string,
  opts: { windowHours?: number; now?: Date; deps?: AiSavingsDeps } = {}
): Promise<AiSavingsReport> {
  const windowHours = opts.windowHours ?? 168;
  const now = opts.now ?? new Date();
  const since = new Date(now.getTime() - windowHours * 3600 * 1000);
  const deps = opts.deps ?? DEFAULT_DEPS;

  try {
    const repoIds = await deps.getRepoIds(userId);
    const [
      prsAutoMerged,
      issuesBuiltByAi,
      aiReviewsPosted,
      aiTriagesPosted,
      aiCommitMsgs,
      secretsAutoRepaired,
      gateAutoRepairs,
    ] = await Promise.all([
      deps.countPrsAutoMerged(repoIds, since),
      deps.countIssuesBuiltByAi(repoIds, since),
      deps.countAiReviewsPosted(repoIds, since),
      deps.countAiTriagesPosted(repoIds, since),
      deps.countAiCommitMsgs(repoIds, since),
      deps.countSecretsAutoRepaired(repoIds, since),
      deps.countGateAutoRepairs(repoIds, since),
    ]);

    const breakdown: AiSavingsBreakdown = {
      prsAutoMerged,
      issuesBuiltByAi,
      aiReviewsPosted,
      aiTriagesPosted,
      aiCommitMsgs,
      secretsAutoRepaired,
      gateAutoRepairs,
    };

    return {
      windowHours,
      breakdown,
      hoursSaved: computeHoursSaved(breakdown),
    };
  } catch (err) {
    console.error("[ai-hours-saved] degraded to zeros:", err);
    return {
      windowHours,
      breakdown: emptyBreakdown(),
      hoursSaved: 0,
    };
  }
}

/**
 * Compute the lifetime savings report for a single user — same shape
 * as the windowed version but the cutoff is the user's `created_at`.
 * Falls back to "30 days ago" if the user row can't be fetched.
 */
export async function computeLifetimeAiSavingsForUser(
  userId: string,
  opts: { deps?: AiSavingsDeps; now?: Date } = {}
): Promise<AiSavingsLifetimeReport> {
  const deps = opts.deps ?? DEFAULT_DEPS;
  const now = opts.now ?? new Date();
  try {
    const createdAt =
      (await deps.getUserCreatedAt(userId)) ??
      new Date(now.getTime() - 30 * 24 * 3600 * 1000);
    const windowHours = Math.max(
      1,
      Math.ceil((now.getTime() - createdAt.getTime()) / (3600 * 1000))
    );
    const report = await computeAiSavingsForUser(userId, {
      windowHours,
      now,
      deps,
    });
    return {
      hoursSaved: report.hoursSaved,
      breakdown: report.breakdown,
      sinceCreatedAt: createdAt,
    };
  } catch (err) {
    console.error("[ai-hours-saved] lifetime degraded to zeros:", err);
    return {
      hoursSaved: 0,
      breakdown: emptyBreakdown(),
      sinceCreatedAt: now,
    };
  }
}

// ───────────────────────────────────────────────────────────────────
// Test-only seam
// ───────────────────────────────────────────────────────────────────

export const __test = {
  DEFAULT_DEPS,
  PR_TRIAGE_MARKER_FRAGMENT,
  ISSUE_TRIAGE_MARKER_FRAGMENT,
};