Pre-launch — Gluecron is in final validation. Public signups and git hosting for non-owner users open after launch review.
CodeIssuesPull RequestsActionsSecurityInsightsSettings
✨ AI
More
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
branch-age.ts9.8 KB · 363 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
/**
 * Block J27 — Branch staleness / age report. Pure rollup helpers.
 *
 * Given a set of branches with tip-commit metadata + ahead/behind counts
 * vs the default branch, produces a per-branch view with age classification,
 * bucket counts, and summary statistics. IO-free so the route can
 * orchestrate git subprocess calls and feed the pre-fetched rows here.
 */

export const DAY_MS = 24 * 60 * 60 * 1000;

/** Canonical thresholds (in days) exposed to the UI select. */
export const VALID_THRESHOLDS = [0, 30, 60, 90, 180] as const;
export type Threshold = (typeof VALID_THRESHOLDS)[number];

export const DEFAULT_THRESHOLD: Threshold = 0;

export type BranchSort =
  | "age-desc"
  | "age-asc"
  | "name"
  | "ahead-desc"
  | "behind-desc";

export const VALID_SORTS: readonly BranchSort[] = [
  "age-desc",
  "age-asc",
  "name",
  "ahead-desc",
  "behind-desc",
];

export const DEFAULT_SORT: BranchSort = "age-desc";

/** Raw input row: tip commit + ahead/behind relative to default. */
export interface BranchInputRow {
  name: string;
  tipSha: string;
  tipDate: Date | string | null;
  tipAuthor: string | null;
  tipMessage: string | null;
  /** Commits on this branch not on default. */
  ahead: number;
  /** Commits on default not on this branch. */
  behind: number;
  /** True when this branch is the repo default. */
  isDefault: boolean;
}

export type BranchAgeCategory = "fresh" | "aging" | "stale" | "abandoned";

export interface BranchReportRow {
  name: string;
  tipSha: string;
  tipDate: Date | null;
  tipAuthor: string | null;
  tipMessage: string | null;
  ahead: number;
  behind: number;
  isDefault: boolean;
  daysOld: number | null;
  category: BranchAgeCategory;
  merged: boolean;
}

export interface BranchBuckets {
  fresh: number;
  aging: number;
  stale: number;
  abandoned: number;
}

export interface BranchSummary {
  total: number;
  /** Excludes the default branch from the count. */
  nonDefault: number;
  merged: number;
  unmerged: number;
  withoutTip: number;
  oldestName: string | null;
  oldestDaysOld: number | null;
  averageAgeDays: number | null;
  medianAgeDays: number | null;
}

export interface BranchReport {
  now: number;
  threshold: Threshold;
  sort: BranchSort;
  defaultBranch: string | null;
  rows: BranchReportRow[];
  filtered: BranchReportRow[];
  buckets: BranchBuckets;
  summary: BranchSummary;
}

/** Accept `number | string | null | undefined` on the query; coerce to allow-listed Threshold. */
export function parseThreshold(raw: unknown): Threshold {
  if (raw === undefined || raw === null) return DEFAULT_THRESHOLD;
  const s = String(raw).trim();
  if (s === "") return DEFAULT_THRESHOLD;
  const n = Number.parseInt(s, 10);
  if (!Number.isFinite(n)) return DEFAULT_THRESHOLD;
  if ((VALID_THRESHOLDS as readonly number[]).includes(n)) return n as Threshold;
  return DEFAULT_THRESHOLD;
}

export function parseSort(raw: unknown): BranchSort {
  if (typeof raw !== "string") return DEFAULT_SORT;
  const t = raw.trim() as BranchSort;
  return VALID_SORTS.includes(t) ? t : DEFAULT_SORT;
}

function toDate(v: Date | string | null | undefined): Date | null {
  if (v === null || v === undefined) return null;
  if (v instanceof Date) return Number.isNaN(v.getTime()) ? null : v;
  if (typeof v !== "string") return null;
  const d = new Date(v);
  return Number.isNaN(d.getTime()) ? null : d;
}

/** How old in whole days. `null` when `tipDate` is missing/unparseable. */
export function computeDaysOld(
  tipDate: Date | string | null | undefined,
  now: number
): number | null {
  const d = toDate(tipDate);
  if (!d) return null;
  const ms = now - d.getTime();
  if (ms < 0) return 0;
  return Math.floor(ms / DAY_MS);
}

/**
 * Four categories:
 *   <30 days   → fresh
 *   30–59     → aging
 *   60–89     → stale
 *   ≥90       → abandoned
 *
 * Branches with no tipDate → `abandoned` (we can't verify they're alive).
 */
export function classifyBranchAge(
  daysOld: number | null
): BranchAgeCategory {
  if (daysOld === null) return "abandoned";
  if (daysOld < 30) return "fresh";
  if (daysOld < 60) return "aging";
  if (daysOld < 90) return "stale";
  return "abandoned";
}

export function computeBranchRow(
  input: BranchInputRow,
  now: number
): BranchReportRow {
  const daysOld = computeDaysOld(input.tipDate, now);
  return {
    name: input.name,
    tipSha: input.tipSha,
    tipDate: toDate(input.tipDate),
    tipAuthor: input.tipAuthor,
    tipMessage: input.tipMessage,
    ahead: Math.max(0, input.ahead | 0),
    behind: Math.max(0, input.behind | 0),
    isDefault: input.isDefault,
    daysOld,
    category: classifyBranchAge(daysOld),
    // "merged" means no commits ahead of default AND not the default itself.
    merged: !input.isDefault && (input.ahead | 0) === 0,
  };
}

export function bucketBranches(rows: readonly BranchReportRow[]): BranchBuckets {
  const out: BranchBuckets = { fresh: 0, aging: 0, stale: 0, abandoned: 0 };
  for (const r of rows) {
    if (r.isDefault) continue; // default branch never enters the buckets
    out[r.category]++;
  }
  return out;
}

export function filterByThreshold(
  rows: readonly BranchReportRow[],
  threshold: Threshold
): BranchReportRow[] {
  if (threshold === 0) return rows.slice();
  return rows.filter(
    (r) => !r.isDefault && r.daysOld !== null && r.daysOld >= threshold
  );
}

function percentile(sorted: readonly number[], p: number): number | null {
  if (sorted.length === 0) return null;
  if (sorted.length === 1) return sorted[0]!;
  const rank = (p / 100) * (sorted.length - 1);
  const lo = Math.floor(rank);
  const hi = Math.ceil(rank);
  if (lo === hi) return sorted[lo]!;
  const w = rank - lo;
  return sorted[lo]! + (sorted[hi]! - sorted[lo]!) * w;
}

export function summariseBranches(
  rows: readonly BranchReportRow[]
): BranchSummary {
  const nonDefault = rows.filter((r) => !r.isDefault);
  const withAge = nonDefault
    .filter((r): r is BranchReportRow & { daysOld: number } => r.daysOld !== null);
  const sortedAges = withAge.map((r) => r.daysOld).sort((a, b) => a - b);
  const sum = sortedAges.reduce((a, b) => a + b, 0);
  const avg = sortedAges.length > 0 ? Math.round(sum / sortedAges.length) : null;
  const med = percentile(sortedAges, 50);
  let oldestName: string | null = null;
  let oldestDays: number | null = null;
  for (const r of withAge) {
    if (oldestDays === null || r.daysOld > oldestDays) {
      oldestDays = r.daysOld;
      oldestName = r.name;
    }
  }
  return {
    total: rows.length,
    nonDefault: nonDefault.length,
    merged: nonDefault.filter((r) => r.merged).length,
    unmerged: nonDefault.filter((r) => !r.merged).length,
    withoutTip: nonDefault.filter((r) => r.daysOld === null).length,
    oldestName,
    oldestDaysOld: oldestDays,
    averageAgeDays: avg,
    medianAgeDays: med === null ? null : Math.round(med),
  };
}

function cmpString(a: string, b: string): number {
  if (a < b) return -1;
  if (a > b) return 1;
  return 0;
}

export function sortBranchRows(
  rows: readonly BranchReportRow[],
  sort: BranchSort
): BranchReportRow[] {
  const out = rows.slice();
  switch (sort) {
    case "name":
      out.sort((a, b) => cmpString(a.name, b.name));
      break;
    case "age-asc":
      out.sort((a, b) => {
        // null daysOld sinks to the bottom
        const av = a.daysOld ?? Number.POSITIVE_INFINITY;
        const bv = b.daysOld ?? Number.POSITIVE_INFINITY;
        if (av !== bv) return av - bv;
        return cmpString(a.name, b.name);
      });
      break;
    case "age-desc":
      out.sort((a, b) => {
        const av = a.daysOld ?? -1;
        const bv = b.daysOld ?? -1;
        if (av !== bv) return bv - av;
        return cmpString(a.name, b.name);
      });
      break;
    case "ahead-desc":
      out.sort((a, b) => {
        if (a.ahead !== b.ahead) return b.ahead - a.ahead;
        return cmpString(a.name, b.name);
      });
      break;
    case "behind-desc":
      out.sort((a, b) => {
        if (a.behind !== b.behind) return b.behind - a.behind;
        return cmpString(a.name, b.name);
      });
      break;
  }
  return out;
}

export interface BuildReportOptions {
  branches: readonly BranchInputRow[];
  defaultBranch: string | null;
  threshold?: Threshold;
  sort?: BranchSort;
  now?: number;
}

/** One-shot report builder used by the route. */
export function buildBranchReport(opts: BuildReportOptions): BranchReport {
  const now = opts.now ?? Date.now();
  const threshold = opts.threshold ?? DEFAULT_THRESHOLD;
  const sort = opts.sort ?? DEFAULT_SORT;
  const rows = opts.branches.map((b) => computeBranchRow(b, now));
  const sorted = sortBranchRows(rows, sort);
  const filtered = filterByThreshold(sorted, threshold);
  return {
    now,
    threshold,
    sort,
    defaultBranch: opts.defaultBranch,
    rows: sorted,
    filtered,
    buckets: bucketBranches(rows),
    summary: summariseBranches(rows),
  };
}

/** Short human label for category pills. */
export function categoryLabel(c: BranchAgeCategory): string {
  switch (c) {
    case "fresh":
      return "Fresh";
    case "aging":
      return "Aging";
    case "stale":
      return "Stale";
    case "abandoned":
      return "Abandoned";
  }
}

export function thresholdLabel(t: Threshold): string {
  return t === 0 ? "All branches" : `≥ ${t} days old`;
}

export function sortLabel(s: BranchSort): string {
  switch (s) {
    case "age-desc":
      return "Oldest first";
    case "age-asc":
      return "Newest first";
    case "name":
      return "Name A–Z";
    case "ahead-desc":
      return "Most ahead";
    case "behind-desc":
      return "Most behind";
  }
}

export const __internal = {
  DAY_MS,
  VALID_THRESHOLDS,
  VALID_SORTS,
  DEFAULT_THRESHOLD,
  DEFAULT_SORT,
  parseThreshold,
  parseSort,
  computeDaysOld,
  classifyBranchAge,
  computeBranchRow,
  bucketBranches,
  filterByThreshold,
  summariseBranches,
  sortBranchRows,
  buildBranchReport,
  categoryLabel,
  thresholdLabel,
  sortLabel,
};