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
repository.ts18.8 KB · 703 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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
import { join } from "path";
import { mkdir } from "fs/promises";
import { config } from "../lib/config";
import { gitCache, cached } from "../lib/cache";

export interface GitCommit {
  sha: string;
  message: string;
  author: string;
  authorEmail: string;
  date: string;
  parentShas: string[];
}

export interface GitTreeEntry {
  mode: string;
  type: "blob" | "tree" | "commit";
  sha: string;
  name: string;
  size?: number;
}

export interface GitBlob {
  content: string;
  size: number;
  isBinary: boolean;
}

export interface GitDiffFile {
  path: string;
  oldPath?: string;
  status: string;
  additions: number;
  deletions: number;
  patch: string;
}

function repoPath(owner: string, name: string): string {
  return join(config.gitReposPath, owner, `${name}.git`);
}

async function exec(
  cmd: string[],
  opts?: { cwd?: string; env?: Record<string, string> }
): Promise<{ stdout: string; stderr: string; exitCode: number }> {
  const proc = Bun.spawn(cmd, {
    cwd: opts?.cwd,
    env: { ...process.env, ...opts?.env },
    stdout: "pipe",
    stderr: "pipe",
  });
  const [stdout, stderr] = await Promise.all([
    new Response(proc.stdout).text(),
    new Response(proc.stderr).text(),
  ]);
  const exitCode = await proc.exited;
  return { stdout, stderr, exitCode };
}

export async function initBareRepo(
  owner: string,
  name: string
): Promise<string> {
  const path = repoPath(owner, name);
  await mkdir(join(config.gitReposPath, owner), { recursive: true });
  await exec(["git", "init", "--bare", path]);
  // Set default branch to main
  await exec(["git", "symbolic-ref", "HEAD", "refs/heads/main"], {
    cwd: path,
  });
  return path;
}

export async function repoExists(
  owner: string,
  name: string
): Promise<boolean> {
  const path = repoPath(owner, name);
  const file = Bun.file(join(path, "HEAD"));
  return file.exists();
}

export function getRepoPath(owner: string, name: string): string {
  return repoPath(owner, name);
}

export async function listBranches(
  owner: string,
  name: string
): Promise<string[]> {
  return cached(gitCache as any, `${owner}/${name}:branches`, async () => {
    const path = repoPath(owner, name);
    const { stdout, exitCode } = await exec(
      ["git", "for-each-ref", "--format=%(refname:short)", "refs/heads/"],
      { cwd: path }
    );
    if (exitCode !== 0) return [];
    return stdout.trim().split("\n").filter(Boolean);
  });
}

export async function getDefaultBranch(
  owner: string,
  name: string
): Promise<string | null> {
  return cached(gitCache as any, `${owner}/${name}:defaultBranch`, async () => {
    const path = repoPath(owner, name);
    const { stdout, exitCode } = await exec(
      ["git", "symbolic-ref", "--short", "HEAD"],
      { cwd: path }
    );
    if (exitCode !== 0) return null;
    return stdout.trim() || null;
  });
}

export async function resolveRef(
  owner: string,
  name: string,
  ref: string
): Promise<string | null> {
  const path = repoPath(owner, name);
  const { stdout, exitCode } = await exec(
    ["git", "rev-parse", "--verify", ref],
    { cwd: path }
  );
  if (exitCode !== 0) return null;
  return stdout.trim();
}

/**
 * List all tags (newest first by commit date).
 * Returns array of { name, sha, date }.
 */
export async function listTags(
  owner: string,
  name: string
): Promise<Array<{ name: string; sha: string; date: string }>> {
  const path = repoPath(owner, name);
  const { stdout, exitCode } = await exec(
    [
      "git",
      "for-each-ref",
      "--sort=-creatordate",
      "--format=%(refname:short)%00%(objectname)%00%(creatordate:iso-strict)",
      "refs/tags/",
    ],
    { cwd: path }
  );
  if (exitCode !== 0) return [];
  return stdout
    .trim()
    .split("\n")
    .filter(Boolean)
    .map((line) => {
      const [tname, sha, date] = line.split("\0");
      return { name: tname, sha, date };
    });
}

/**
 * Create a lightweight git tag pointing at a commit.
 */
export async function createTag(
  owner: string,
  name: string,
  tag: string,
  sha: string,
  annotation?: string
): Promise<boolean> {
  const path = repoPath(owner, name);
  const args = annotation
    ? ["git", "tag", "-a", tag, sha, "-m", annotation]
    : ["git", "tag", tag, sha];
  const { exitCode } = await exec(args, { cwd: path });
  return exitCode === 0;
}

/**
 * Delete a tag.
 */
export async function deleteTag(
  owner: string,
  name: string,
  tag: string
): Promise<boolean> {
  const path = repoPath(owner, name);
  const { exitCode } = await exec(["git", "tag", "-d", tag], { cwd: path });
  return exitCode === 0;
}

/**
 * Rename a branch (refs/heads/<from> → refs/heads/<to>). Preserves the
 * commit SHA. Writes the new ref first, then deletes the old one (so a
 * mid-op crash never leaves the branch unreachable). Returns true on
 * success. Caller is responsible for any semantics around the default
 * branch (HEAD symbolic-ref update) + cache invalidation — we flush
 * this repo's branch cache here as a convenience. Block J24.
 */
export async function renameBranch(
  owner: string,
  name: string,
  from: string,
  to: string
): Promise<boolean> {
  const path = repoPath(owner, name);
  const { stdout: shaOut, exitCode: revCode } = await exec(
    ["git", "rev-parse", "--verify", `refs/heads/${from}`],
    { cwd: path }
  );
  if (revCode !== 0) return false;
  const sha = shaOut.trim();
  if (!sha) return false;

  const { exitCode: createCode } = await exec(
    ["git", "update-ref", `refs/heads/${to}`, sha],
    { cwd: path }
  );
  if (createCode !== 0) return false;

  const { exitCode: deleteCode } = await exec(
    ["git", "update-ref", "-d", `refs/heads/${from}`, sha],
    { cwd: path }
  );
  if (deleteCode !== 0) {
    // Best-effort rollback — remove the newly-created ref so we don't
    // leak a duplicate.
    await exec(["git", "update-ref", "-d", `refs/heads/${to}`], {
      cwd: path,
    });
    return false;
  }
  gitCache.invalidatePrefix(`${owner}/${name}:`);
  return true;
}

/**
 * Update `HEAD` to point at a different branch. Used when the default
 * branch is renamed (Block J24).
 */
export async function setHeadBranch(
  owner: string,
  name: string,
  branch: string
): Promise<boolean> {
  const path = repoPath(owner, name);
  const { exitCode } = await exec(
    ["git", "symbolic-ref", "HEAD", `refs/heads/${branch}`],
    { cwd: path }
  );
  if (exitCode !== 0) return false;
  gitCache.invalidatePrefix(`${owner}/${name}:`);
  return true;
}

/**
 * List commits between two refs (excluding `from`, including `to`).
 */
export async function commitsBetween(
  owner: string,
  name: string,
  from: string | null,
  to: string
): Promise<GitCommit[]> {
  const path = repoPath(owner, name);
  const format = "%H%x00%s%x00%an%x00%ae%x00%aI%x00%P";
  const range = from ? `${from}..${to}` : to;
  const { stdout, exitCode } = await exec(
    ["git", "log", `--format=${format}`, "-500", range],
    { cwd: path }
  );
  if (exitCode !== 0) return [];
  return stdout
    .trim()
    .split("\n")
    .filter(Boolean)
    .map((line) => {
      const [sha, message, author, authorEmail, date, parents] = line.split("\0");
      return {
        sha,
        message,
        author,
        authorEmail,
        date,
        parentShas: parents ? parents.split(" ").filter(Boolean) : [],
      };
    });
}

export async function getCommit(
  owner: string,
  name: string,
  sha: string
): Promise<GitCommit | null> {
  const path = repoPath(owner, name);
  const format = "%H%n%s%n%an%n%ae%n%aI%n%P";
  const { stdout, exitCode } = await exec(
    ["git", "log", "-1", `--format=${format}`, sha],
    { cwd: path }
  );
  if (exitCode !== 0) return null;
  const lines = stdout.trim().split("\n");
  if (lines.length < 5) return null;
  return {
    sha: lines[0],
    message: lines[1],
    author: lines[2],
    authorEmail: lines[3],
    date: lines[4],
    parentShas: lines[5] ? lines[5].split(" ").filter(Boolean) : [],
  };
}

export async function getCommitFullMessage(
  owner: string,
  name: string,
  sha: string
): Promise<string> {
  const path = repoPath(owner, name);
  const { stdout } = await exec(
    ["git", "log", "-1", "--format=%B", sha],
    { cwd: path }
  );
  return stdout.trim();
}

export async function listCommits(
  owner: string,
  name: string,
  ref: string,
  limit = 30,
  offset = 0
): Promise<GitCommit[]> {
  return cached(gitCache as any, `${owner}/${name}:commits:${ref}:${limit}:${offset}`, async () => {
    const path = repoPath(owner, name);
    const format = "%H%x00%s%x00%an%x00%ae%x00%aI%x00%P";
    const { stdout, exitCode } = await exec(
      [
        "git",
        "log",
        `--format=${format}`,
        `--skip=${offset}`,
        `-${limit}`,
        ref,
      ],
      { cwd: path }
    );
    if (exitCode !== 0) return [];
    return stdout
      .trim()
      .split("\n")
      .filter(Boolean)
      .map((line) => {
        const [sha, message, author, authorEmail, date, parents] =
          line.split("\0");
        return {
          sha,
          message,
          author,
          authorEmail,
          date,
          parentShas: parents ? parents.split(" ").filter(Boolean) : [],
        };
      });
  });
}

export async function getTree(
  owner: string,
  name: string,
  ref: string,
  treePath = ""
): Promise<GitTreeEntry[]> {
  return cached(gitCache as any, `${owner}/${name}:tree:${ref}:${treePath}`, async () => {
    const path = repoPath(owner, name);
    const treeish = treePath ? `${ref}:${treePath}` : `${ref}`;
    const { stdout, exitCode } = await exec(
      ["git", "ls-tree", "-l", treeish],
      { cwd: path }
    );
    if (exitCode !== 0) return [];
    return stdout
      .trim()
      .split("\n")
      .filter(Boolean)
      .map((line) => {
        // format: <mode> <type> <sha>\t<size>\t<name>
        // Actually: <mode> SP <type> SP <sha> SP <size> TAB <name>
        const match = line.match(
          /^(\d+)\s+(blob|tree|commit)\s+([0-9a-f]+)\s+(-|\d+)\t(.+)$/
        );
        if (!match) return null;
        return {
          mode: match[1],
          type: match[2] as "blob" | "tree" | "commit",
          sha: match[3],
          size: match[4] === "-" ? undefined : parseInt(match[4], 10),
          name: match[5],
        };
      })
      .filter((e): e is GitTreeEntry => e !== null)
      .sort((a, b) => {
        // directories first, then files
        if (a.type === "tree" && b.type !== "tree") return -1;
        if (a.type !== "tree" && b.type === "tree") return 1;
        return a.name.localeCompare(b.name);
      });
  });
}

export async function getBlob(
  owner: string,
  name: string,
  ref: string,
  filePath: string
): Promise<GitBlob | null> {
  const path = repoPath(owner, name);
  const { stdout, exitCode } = await exec(
    ["git", "cat-file", "-s", `${ref}:${filePath}`],
    { cwd: path }
  );
  if (exitCode !== 0) return null;
  const size = parseInt(stdout.trim(), 10);

  // Check if binary
  const { stdout: content, exitCode: catCode } = await exec(
    ["git", "show", `${ref}:${filePath}`],
    { cwd: path }
  );
  if (catCode !== 0) return null;

  const isBinary = content.includes("\0");
  return {
    content: isBinary ? "" : content,
    size,
    isBinary,
  };
}

export async function getDiff(
  owner: string,
  name: string,
  sha: string
): Promise<{ files: GitDiffFile[]; raw: string }> {
  const path = repoPath(owner, name);
  // For initial commits (no parent), diff against empty tree
  const commit = await getCommit(owner, name, sha);
  if (!commit) return { files: [], raw: "" };

  let diffCmd: string[];
  if (commit.parentShas.length === 0) {
    const emptyTree = "4b825dc642cb6eb9a060e54bf899d15363da7b23";
    diffCmd = ["git", "diff", emptyTree, sha];
  } else {
    diffCmd = ["git", "diff", `${commit.parentShas[0]}..${sha}`];
  }

  const { stdout: raw } = await exec(diffCmd, { cwd: path });

  // Also get --stat for file-level summary
  const { stdout: stat } = await exec([...diffCmd, "--numstat"], {
    cwd: path,
  });

  const files = stat
    .trim()
    .split("\n")
    .filter(Boolean)
    .map((line) => {
      const [add, del, filePath] = line.split("\t");
      return {
        path: filePath,
        status: "modified",
        additions: add === "-" ? 0 : parseInt(add, 10),
        deletions: del === "-" ? 0 : parseInt(del, 10),
        patch: "",
      };
    });

  return { files, raw };
}

export interface BlameLine {
  sha: string;
  author: string;
  date: string;
  lineNum: number;
  content: string;
}

export async function getBlame(
  owner: string,
  name: string,
  ref: string,
  filePath: string
): Promise<BlameLine[]> {
  const path = repoPath(owner, name);
  const { stdout, exitCode } = await exec(
    ["git", "blame", "--porcelain", ref, "--", filePath],
    { cwd: path }
  );
  if (exitCode !== 0) return [];

  const lines: BlameLine[] = [];
  const commits: Record<string, { author: string; date: string }> = {};
  let currentSha = "";
  let currentLineNum = 0;

  for (const line of stdout.split("\n")) {
    // Header line: <sha> <orig-line> <final-line> [<group-lines>]
    const headerMatch = line.match(
      /^([0-9a-f]{40}) \d+ (\d+)/
    );
    if (headerMatch) {
      currentSha = headerMatch[1];
      currentLineNum = parseInt(headerMatch[2], 10);
      continue;
    }

    if (line.startsWith("author ")) {
      if (!commits[currentSha]) commits[currentSha] = { author: "", date: "" };
      commits[currentSha].author = line.slice(7);
    } else if (line.startsWith("author-time ")) {
      if (!commits[currentSha]) commits[currentSha] = { author: "", date: "" };
      commits[currentSha].date = new Date(
        parseInt(line.slice(12), 10) * 1000
      ).toISOString();
    } else if (line.startsWith("\t")) {
      const info = commits[currentSha] || { author: "unknown", date: "" };
      lines.push({
        sha: currentSha,
        author: info.author,
        date: info.date,
        lineNum: currentLineNum,
        content: line.slice(1),
      });
    }
  }

  return lines;
}

export async function getRawBlob(
  owner: string,
  name: string,
  ref: string,
  filePath: string
): Promise<Uint8Array | null> {
  const path = repoPath(owner, name);
  const proc = Bun.spawn(["git", "show", `${ref}:${filePath}`], {
    cwd: path,
    stdout: "pipe",
    stderr: "pipe",
  });
  const data = await new Response(proc.stdout).arrayBuffer();
  const exitCode = await proc.exited;
  if (exitCode !== 0) return null;
  return new Uint8Array(data);
}

/**
 * Return the raw commit object (`git cat-file commit <sha>`) including any
 * `gpgsig` / `gpgsig-sha256` headers. Used by Block J3 signature verification.
 */
export async function getRawCommitObject(
  owner: string,
  name: string,
  sha: string
): Promise<string | null> {
  const path = repoPath(owner, name);
  const { stdout, exitCode } = await exec(
    ["git", "cat-file", "commit", sha],
    { cwd: path }
  );
  if (exitCode !== 0) return null;
  return stdout;
}

export async function searchCode(
  owner: string,
  name: string,
  ref: string,
  query: string,
  maxResults = 50
): Promise<Array<{ file: string; lineNum: number; line: string }>> {
  const path = repoPath(owner, name);
  const { stdout, exitCode } = await exec(
    ["git", "grep", "-n", "-I", `--max-count=${maxResults}`, query, ref],
    { cwd: path }
  );
  if (exitCode !== 0) return [];

  return stdout
    .trim()
    .split("\n")
    .filter(Boolean)
    .slice(0, maxResults)
    .map((line) => {
      // Format: <ref>:<file>:<lineNum>:<content>
      const refPrefix = ref + ":";
      const rest = line.startsWith(refPrefix) ? line.slice(refPrefix.length) : line;
      const colonIdx = rest.indexOf(":");
      if (colonIdx === -1) return null;
      const file = rest.slice(0, colonIdx);
      const afterFile = rest.slice(colonIdx + 1);
      const numColonIdx = afterFile.indexOf(":");
      if (numColonIdx === -1) return null;
      const lineNum = parseInt(afterFile.slice(0, numColonIdx), 10);
      const content = afterFile.slice(numColonIdx + 1);
      return { file, lineNum, line: content };
    })
    .filter((r): r is { file: string; lineNum: number; line: string } => r !== null);
}

export async function getReadme(
  owner: string,
  name: string,
  ref: string
): Promise<string | null> {
  return cached(gitCache as any, `${owner}/${name}:readme:${ref}`, async () => {
    const tree = await getTree(owner, name, ref);
    const readme = tree.find((e) =>
      /^readme(\.(md|txt|rst))?$/i.test(e.name)
    );
    if (!readme) return null;
    const blob = await getBlob(owner, name, ref, readme.name);
    return blob?.content || null;
  });
}

/**
 * Recursive flat tree listing at `ref` — returns every blob (file) path +
 * size in bytes. Useful for language breakdowns and large-file audits.
 * Skips symlinks and submodules. Returns `[]` on any git failure.
 */
export async function listTreeRecursive(
  owner: string,
  name: string,
  ref: string
): Promise<Array<{ path: string; size: number }>> {
  return cached(
    gitCache as any,
    `${owner}/${name}:tree-recursive:${ref}`,
    async () => {
      const path = repoPath(owner, name);
      const { stdout, exitCode } = await exec(
        ["git", "ls-tree", "-r", "-l", "-z", ref],
        { cwd: path }
      );
      if (exitCode !== 0) return [];
      const entries: Array<{ path: string; size: number }> = [];
      for (const line of stdout.split("\0")) {
        if (!line) continue;
        // Format: <mode> SP <type> SP <sha> SP <size> TAB <name>
        const match = line.match(
          /^(\d+)\s+(blob|tree|commit)\s+[0-9a-f]+\s+(-|\d+)\t(.+)$/
        );
        if (!match) continue;
        if (match[2] !== "blob") continue; // skip submodules / trees
        // Mode 120000 is a symlink — skip so size doesn't skew stats.
        if (match[1] === "120000") continue;
        const sz = match[3] === "-" ? 0 : Number.parseInt(match[3]!, 10);
        if (!Number.isFinite(sz) || sz < 0) continue;
        entries.push({ path: match[4]!, size: sz });
      }
      return entries;
    }
  );
}

/**
 * Count commits ahead and behind: commits on `head` not on `base` (ahead) and
 * commits on `base` not on `head` (behind). Returns null when either ref is
 * missing or git errors out.
 *
 * Uses `git rev-list --left-right --count <base>...<head>`; git emits
 * `<behind>\t<ahead>` (left is `base`, right is `head`).
 */
export async function aheadBehind(
  owner: string,
  name: string,
  base: string,
  head: string
): Promise<{ ahead: number; behind: number } | null> {
  const path = repoPath(owner, name);
  const { stdout, exitCode } = await exec(
    [
      "git",
      "rev-list",
      "--left-right",
      "--count",
      `${base}...${head}`,
    ],
    { cwd: path }
  );
  if (exitCode !== 0) return null;
  const parts = stdout.trim().split(/\s+/);
  if (parts.length !== 2) return null;
  const behind = Number.parseInt(parts[0]!, 10);
  const ahead = Number.parseInt(parts[1]!, 10);
  if (!Number.isFinite(ahead) || !Number.isFinite(behind)) return null;
  return { ahead, behind };
}