@getchomp/cli 0.0.0-stage → 0.2.43

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +39 -2
  3. package/dist/commands/analyze.d.ts +49 -0
  4. package/dist/commands/analyze.js +280 -0
  5. package/dist/commands/connect.d.ts +12 -0
  6. package/dist/commands/connect.js +255 -0
  7. package/dist/commands/export.d.ts +29 -0
  8. package/dist/commands/export.js +356 -0
  9. package/dist/commands/health.d.ts +19 -0
  10. package/dist/commands/health.js +259 -0
  11. package/dist/commands/init.d.ts +40 -0
  12. package/dist/commands/init.js +659 -0
  13. package/dist/commands/mcp.d.ts +2 -0
  14. package/dist/commands/mcp.js +12 -0
  15. package/dist/commands/plugin.d.ts +8 -0
  16. package/dist/commands/plugin.js +198 -0
  17. package/dist/commands/ui.d.ts +20 -0
  18. package/dist/commands/ui.js +252 -0
  19. package/dist/commands/uninstall.d.ts +8 -0
  20. package/dist/commands/uninstall.js +246 -0
  21. package/dist/index.d.ts +3 -0
  22. package/dist/index.js +37 -0
  23. package/dist/ports/portHydrator.d.ts +63 -0
  24. package/dist/ports/portHydrator.js +954 -0
  25. package/dist/ports/portHydratorWorker.d.ts +22 -0
  26. package/dist/ports/portHydratorWorker.js +75 -0
  27. package/dist/server/buildStatusTracker.d.ts +45 -0
  28. package/dist/server/buildStatusTracker.js +122 -0
  29. package/dist/server/graphLayoutState.d.ts +205 -0
  30. package/dist/server/graphLayoutState.js +930 -0
  31. package/dist/server/loopbackSecurity.d.ts +18 -0
  32. package/dist/server/loopbackSecurity.js +57 -0
  33. package/dist/server/routes/authSourceRoutes.d.ts +18 -0
  34. package/dist/server/routes/authSourceRoutes.js +231 -0
  35. package/dist/server/routes/layoutRoutes.d.ts +3 -0
  36. package/dist/server/routes/layoutRoutes.js +857 -0
  37. package/dist/server/routes/pluginRoutes.d.ts +3 -0
  38. package/dist/server/routes/pluginRoutes.js +368 -0
  39. package/dist/server/routes/viewRulesRoutes.d.ts +3 -0
  40. package/dist/server/routes/viewRulesRoutes.js +173 -0
  41. package/dist/server/uiHotkeys.d.ts +26 -0
  42. package/dist/server/uiHotkeys.js +160 -0
  43. package/dist/utils/branding.d.ts +126 -0
  44. package/dist/utils/branding.js +978 -0
  45. package/dist/utils/credentials.d.ts +22 -0
  46. package/dist/utils/credentials.js +126 -0
  47. package/dist/utils/git.d.ts +95 -0
  48. package/dist/utils/git.js +780 -0
  49. package/dist/utils/masterContext.d.ts +112 -0
  50. package/dist/utils/masterContext.js +642 -0
  51. package/dist/visualizer/cloudLayoutClient.d.ts +84 -0
  52. package/dist/visualizer/cloudLayoutClient.js +1200 -0
  53. package/dist/visualizer/layoutCache.d.ts +25 -0
  54. package/dist/visualizer/layoutCache.js +406 -0
  55. package/dist/visualizer/localEngineBridge.d.ts +50 -0
  56. package/dist/visualizer/localEngineBridge.js +80 -0
  57. package/dist/visualizer/pluginPresentationApi.d.ts +111 -0
  58. package/dist/visualizer/pluginPresentationApi.js +432 -0
  59. package/dist/visualizer/rulesConfig.d.ts +11 -0
  60. package/dist/visualizer/rulesConfig.js +266 -0
  61. package/dist/visualizer/sourceAccess.d.ts +45 -0
  62. package/dist/visualizer/sourceAccess.js +204 -0
  63. package/package.json +52 -3
@@ -0,0 +1,780 @@
1
+ import { execFile, execSync } from 'node:child_process';
2
+ import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs';
3
+ import { basename, dirname, resolve } from 'node:path';
4
+ import { promisify } from 'node:util';
5
+ const execFileAsync = promisify(execFile);
6
+ export function cleanGitEnv() {
7
+ const env = { ...process.env };
8
+ delete env.GIT_DIR;
9
+ delete env.GIT_WORK_TREE;
10
+ delete env.GIT_INDEX_FILE;
11
+ delete env.GIT_OBJECT_DIRECTORY;
12
+ delete env.GIT_ALTERNATE_OBJECT_DIRECTORIES;
13
+ delete env.GIT_CEILING_DIRECTORIES;
14
+ delete env.GIT_COMMON_DIR;
15
+ delete env.GIT_PREFIX;
16
+ return env;
17
+ }
18
+ function safeRealpath(targetPath) {
19
+ try {
20
+ return realpathSync(targetPath);
21
+ }
22
+ catch {
23
+ return resolve(targetPath);
24
+ }
25
+ }
26
+ /**
27
+ * Resolves Git repository / worktree identity using pure filesystem reads (zero subprocesses).
28
+ * Distinguishes primary checkouts from linked Git worktrees (`git worktree add`) and maps
29
+ * linked worktrees back to their shared `commonDir` and `primaryRepoRoot`.
30
+ */
31
+ export function getGitRepoIdentity(inputPath) {
32
+ const abs = resolve(inputPath);
33
+ let dir = abs;
34
+ try {
35
+ if (existsSync(abs) && !statSync(abs).isDirectory()) {
36
+ dir = dirname(abs);
37
+ }
38
+ }
39
+ catch {
40
+ return null;
41
+ }
42
+ let cur = dir;
43
+ let gitEntryPath;
44
+ let gitOwnerDir;
45
+ for (let i = 0; i < 8; i++) {
46
+ const candidate = resolve(cur, '.git');
47
+ if (existsSync(candidate)) {
48
+ gitEntryPath = candidate;
49
+ gitOwnerDir = cur;
50
+ break;
51
+ }
52
+ const parent = dirname(cur);
53
+ if (parent === cur)
54
+ break;
55
+ cur = parent;
56
+ }
57
+ if (!gitEntryPath || !gitOwnerDir)
58
+ return null;
59
+ try {
60
+ const stat = statSync(gitEntryPath);
61
+ const repoRoot = safeRealpath(gitOwnerDir);
62
+ if (stat.isDirectory()) {
63
+ const gitDir = safeRealpath(gitEntryPath);
64
+ return {
65
+ repoRoot,
66
+ gitDir,
67
+ commonDir: gitDir,
68
+ primaryRepoRoot: repoRoot,
69
+ isLinkedWorktree: false,
70
+ };
71
+ }
72
+ if (stat.isFile()) {
73
+ const ptr = readFileSync(gitEntryPath, 'utf-8').trim();
74
+ const match = /^gitdir:\s*(.+)$/i.exec(ptr);
75
+ if (!match)
76
+ return null;
77
+ const rawGitDir = resolve(gitOwnerDir, match[1].trim());
78
+ const gitDir = safeRealpath(rawGitDir);
79
+ let commonDir = gitDir;
80
+ let hasCommonDirPointer = false;
81
+ const commonDirFile = resolve(rawGitDir, 'commondir');
82
+ if (existsSync(commonDirFile)) {
83
+ const relCommon = readFileSync(commonDirFile, 'utf-8').trim();
84
+ if (relCommon) {
85
+ commonDir = safeRealpath(resolve(rawGitDir, relCommon));
86
+ hasCommonDirPointer = true;
87
+ }
88
+ }
89
+ const normalizedGitDir = gitDir.replace(/\\/g, '/');
90
+ const wtMatch = /^(.*\/\.git)\/worktrees\/[^/]+\/?$/.exec(normalizedGitDir);
91
+ const isLinkedWorktree = (hasCommonDirPointer && commonDir !== gitDir) || Boolean(wtMatch);
92
+ let primaryRepoRoot = repoRoot;
93
+ if (isLinkedWorktree) {
94
+ if (basename(commonDir) === '.git') {
95
+ primaryRepoRoot = safeRealpath(dirname(commonDir));
96
+ }
97
+ else if (wtMatch && wtMatch[1]) {
98
+ primaryRepoRoot = safeRealpath(dirname(wtMatch[1]));
99
+ }
100
+ }
101
+ return {
102
+ repoRoot,
103
+ gitDir,
104
+ commonDir,
105
+ primaryRepoRoot,
106
+ isLinkedWorktree,
107
+ };
108
+ }
109
+ }
110
+ catch {
111
+ return null;
112
+ }
113
+ return null;
114
+ }
115
+ /**
116
+ * Returns `true` when `inputPath` resides inside a linked Git worktree (created via
117
+ * `git worktree add`) rather than the repository's primary checkout.
118
+ */
119
+ export function isLinkedGitWorktree(inputPath) {
120
+ return getGitRepoIdentity(inputPath)?.isLinkedWorktree ?? false;
121
+ }
122
+ /**
123
+ * Returns `true` when `pathA` and `pathB` belong to the same underlying Git repository
124
+ * (e.g., `main` and a linked Git worktree sharing the same `.git` common directory).
125
+ */
126
+ export function sharesGitRepository(pathA, pathB) {
127
+ const idA = getGitRepoIdentity(pathA);
128
+ const idB = getGitRepoIdentity(pathB);
129
+ if (!idA || !idB)
130
+ return false;
131
+ return idA.commonDir === idB.commonDir;
132
+ }
133
+ /**
134
+ * Resolves the canonical repository name for `inputPath` (`[PAT-VIS-24]`, `[PAT-CLI-13]`).
135
+ *
136
+ * When running inside a Git worktree (where `.git` is a pointer file containing
137
+ * `gitdir: /path/to/<repo>/.git/worktrees/<worktree>`), resolves `commondir` back to
138
+ * the parent repository root (`<repo>`) instead of returning the worktree/branch directory name.
139
+ * Preserves standalone non-git fixture directories (`fixtures/cloned-repos/<name>`,
140
+ * `fixtures/test-repos/<name>`, or isolated `.chomp/` target directories).
141
+ */
142
+ export function resolveRepoName(inputPath) {
143
+ const abs = resolve(inputPath);
144
+ let dir = abs;
145
+ try {
146
+ if (existsSync(abs) && !statSync(abs).isDirectory()) {
147
+ dir = dirname(abs);
148
+ }
149
+ }
150
+ catch {
151
+ // Path may not exist yet (e.g. dry-run); fall back to basename(abs)
152
+ }
153
+ const posixDir = dir.replace(/\\/g, '/');
154
+ const fixtureMatch = /\/fixtures\/(?:cloned-repos|test-repos)\/([^/]+)(?:\/|$)/.exec(posixDir);
155
+ if (fixtureMatch) {
156
+ const matchEnd = posixDir.indexOf(fixtureMatch[0]) + fixtureMatch[0].replace(/\/$/, '').length;
157
+ const fixtureRoot = dir.slice(0, matchEnd);
158
+ if (!existsSync(resolve(fixtureRoot, '.git'))) {
159
+ return fixtureMatch[1];
160
+ }
161
+ }
162
+ if (existsSync(resolve(dir, '.chomp')) && !existsSync(resolve(dir, '.git'))) {
163
+ return basename(dir);
164
+ }
165
+ try {
166
+ let cur = dir;
167
+ let gitEntryPath;
168
+ let gitOwnerDir;
169
+ for (let i = 0; i < 8; i++) {
170
+ const candidate = resolve(cur, '.git');
171
+ if (existsSync(candidate)) {
172
+ gitEntryPath = candidate;
173
+ gitOwnerDir = cur;
174
+ break;
175
+ }
176
+ const parent = dirname(cur);
177
+ if (parent === cur)
178
+ break;
179
+ cur = parent;
180
+ }
181
+ if (gitEntryPath && gitOwnerDir) {
182
+ const stat = statSync(gitEntryPath);
183
+ if (stat.isFile()) {
184
+ const ptr = readFileSync(gitEntryPath, 'utf-8').trim();
185
+ const match = /^gitdir:\s*(.+)$/i.exec(ptr);
186
+ if (match) {
187
+ const gitDir = resolve(gitOwnerDir, match[1].trim());
188
+ const commonDirFile = resolve(gitDir, 'commondir');
189
+ if (existsSync(commonDirFile)) {
190
+ const relCommon = readFileSync(commonDirFile, 'utf-8').trim();
191
+ if (relCommon) {
192
+ const commonDir = resolve(gitDir, relCommon);
193
+ if (basename(commonDir) === '.git') {
194
+ return basename(dirname(commonDir));
195
+ }
196
+ const cleanBare = basename(commonDir).replace(/\.git$/i, '');
197
+ if (cleanBare)
198
+ return cleanBare;
199
+ }
200
+ }
201
+ const normalizedGitDir = gitDir.replace(/\\/g, '/');
202
+ const wtMatch = /^(.*)\/\.git\/worktrees\/[^/]+\/?$/.exec(normalizedGitDir);
203
+ if (wtMatch && wtMatch[1]) {
204
+ return basename(wtMatch[1]);
205
+ }
206
+ return basename(gitOwnerDir);
207
+ }
208
+ }
209
+ if (stat.isDirectory()) {
210
+ if (gitOwnerDir !== dir &&
211
+ existsSync(resolve(dir, 'package.json')) &&
212
+ !dir.startsWith(resolve(gitOwnerDir, 'packages') + '/') &&
213
+ !dir.startsWith(resolve(gitOwnerDir, 'apps') + '/')) {
214
+ return basename(dir);
215
+ }
216
+ if (!posixDir.includes('/.chomp/')) {
217
+ return basename(gitOwnerDir);
218
+ }
219
+ }
220
+ }
221
+ }
222
+ catch {
223
+ // Fall back to basename(dir)
224
+ }
225
+ return basename(dir);
226
+ }
227
+ export function normalizeGitRemoteWebUrl(rawUrl) {
228
+ if (!rawUrl)
229
+ return undefined;
230
+ const trimmed = rawUrl.trim();
231
+ if (!trimmed)
232
+ return undefined;
233
+ // SSH SCP-like syntax: git@github.com:owner/repo.git
234
+ const scpMatch = /^(?:[^@]+@)?([a-zA-Z0-9.-]+):([a-zA-Z0-9._/-]+?)(?:\.git)?\/?$/.exec(trimmed);
235
+ if (scpMatch && !trimmed.includes('://')) {
236
+ const [, host, repoPath] = scpMatch;
237
+ return `https://${host}/${repoPath.replace(/^\/+/, '')}`;
238
+ }
239
+ try {
240
+ const parsed = new URL(trimmed);
241
+ if (parsed.protocol === 'http:' || parsed.protocol === 'https:' || parsed.protocol === 'ssh:') {
242
+ const cleanPath = parsed.pathname.replace(/\.git\/?$/, '').replace(/\/+$/, '');
243
+ if (!cleanPath || cleanPath === '/')
244
+ return undefined;
245
+ const protocol = parsed.protocol === 'http:' ? 'http:' : 'https:';
246
+ return `${protocol}//${parsed.host}${cleanPath}`;
247
+ }
248
+ }
249
+ catch {
250
+ // Ignore malformed remote URLs
251
+ }
252
+ return undefined;
253
+ }
254
+ function readRemoteOriginFromGitConfig(commonDir) {
255
+ try {
256
+ const configPath = resolve(commonDir, 'config');
257
+ if (!existsSync(configPath))
258
+ return undefined;
259
+ const raw = readFileSync(configPath, 'utf-8');
260
+ const originBlock = /\[remote\s+"origin"\]([\s\S]*?)(?:\n\[|$)/.exec(raw);
261
+ if (!originBlock)
262
+ return undefined;
263
+ const urlLine = /^\s*url\s*=\s*(.+)$/m.exec(originBlock[1]);
264
+ return normalizeGitRemoteWebUrl(urlLine?.[1]);
265
+ }
266
+ catch {
267
+ return undefined;
268
+ }
269
+ }
270
+ function readGitInfoFromFs(startDir) {
271
+ try {
272
+ let cur = resolve(startDir);
273
+ let gitEntryPath;
274
+ for (let i = 0; i < 8; i++) {
275
+ const candidate = resolve(cur, '.git');
276
+ if (existsSync(candidate)) {
277
+ gitEntryPath = candidate;
278
+ break;
279
+ }
280
+ const parent = dirname(cur);
281
+ if (parent === cur)
282
+ break;
283
+ cur = parent;
284
+ }
285
+ if (!gitEntryPath)
286
+ return {};
287
+ let gitDir = gitEntryPath;
288
+ if (statSync(gitEntryPath).isFile()) {
289
+ const ptr = readFileSync(gitEntryPath, 'utf-8').trim();
290
+ if (ptr.startsWith('gitdir:')) {
291
+ gitDir = resolve(dirname(gitEntryPath), ptr.slice('gitdir:'.length).trim());
292
+ }
293
+ }
294
+ let commonDir = gitDir;
295
+ const commonDirFile = resolve(gitDir, 'commondir');
296
+ if (existsSync(commonDirFile)) {
297
+ const relCommon = readFileSync(commonDirFile, 'utf-8').trim();
298
+ if (relCommon) {
299
+ commonDir = resolve(gitDir, relCommon);
300
+ }
301
+ }
302
+ let commitMessage;
303
+ for (const base of [gitDir, commonDir]) {
304
+ const editMsgFile = resolve(base, 'COMMIT_EDITMSG');
305
+ if (existsSync(editMsgFile)) {
306
+ const rawMsg = readFileSync(editMsgFile, 'utf-8')
307
+ .split('\n')
308
+ .filter((line) => !line.startsWith('#'))
309
+ .join('\n')
310
+ .trim();
311
+ if (rawMsg) {
312
+ commitMessage = rawMsg;
313
+ break;
314
+ }
315
+ }
316
+ }
317
+ const remoteUrl = readRemoteOriginFromGitConfig(commonDir);
318
+ const headFile = resolve(gitDir, 'HEAD');
319
+ if (!existsSync(headFile))
320
+ return remoteUrl ? { remoteUrl } : {};
321
+ const headRaw = readFileSync(headFile, 'utf-8').trim();
322
+ if (headRaw.startsWith('ref:')) {
323
+ const refPath = headRaw.slice('ref:'.length).trim();
324
+ const branchName = refPath.startsWith('refs/heads/')
325
+ ? refPath.slice('refs/heads/'.length)
326
+ : undefined;
327
+ for (const base of [gitDir, commonDir]) {
328
+ const looseRef = resolve(base, refPath);
329
+ if (existsSync(looseRef)) {
330
+ const sha = readFileSync(looseRef, 'utf-8').trim();
331
+ if (sha)
332
+ return { commitSha: sha, branchName, commitMessage, remoteUrl };
333
+ }
334
+ }
335
+ const packedRefs = resolve(commonDir, 'packed-refs');
336
+ if (existsSync(packedRefs)) {
337
+ const lines = readFileSync(packedRefs, 'utf-8').split('\n');
338
+ for (const line of lines) {
339
+ if (!line || line.startsWith('#') || line.startsWith('^'))
340
+ continue;
341
+ const [sha, ref] = line.trim().split(/\s+/);
342
+ if (ref === refPath && sha) {
343
+ return { commitSha: sha, branchName, commitMessage, remoteUrl };
344
+ }
345
+ }
346
+ }
347
+ return { branchName, commitMessage, remoteUrl };
348
+ }
349
+ if (/^[0-9a-f]{7,40}$/i.test(headRaw)) {
350
+ return { commitSha: headRaw, commitMessage, remoteUrl };
351
+ }
352
+ return remoteUrl ? { remoteUrl } : {};
353
+ }
354
+ catch {
355
+ return {};
356
+ }
357
+ }
358
+ export function getGitInfo(cwd) {
359
+ const absCwd = resolve(cwd);
360
+ if ((absCwd.includes('/fixtures/cloned-repos/') || absCwd.includes('/fixtures/test-repos/')) &&
361
+ !existsSync(resolve(absCwd, '.git'))) {
362
+ return {};
363
+ }
364
+ try {
365
+ const commitSha = execSync('git rev-parse HEAD', {
366
+ cwd,
367
+ encoding: 'utf-8',
368
+ stdio: ['ignore', 'pipe', 'ignore'],
369
+ }).trim();
370
+ const branchName = execSync('git rev-parse --abbrev-ref HEAD', {
371
+ cwd,
372
+ encoding: 'utf-8',
373
+ stdio: ['ignore', 'pipe', 'ignore'],
374
+ }).trim();
375
+ let commitMessage;
376
+ try {
377
+ commitMessage = execSync('git log -1 --pretty=%B', {
378
+ cwd,
379
+ encoding: 'utf-8',
380
+ stdio: ['ignore', 'pipe', 'ignore'],
381
+ }).trim();
382
+ }
383
+ catch {
384
+ // Ignore if git log fails on empty repo
385
+ }
386
+ let remoteUrl;
387
+ try {
388
+ const rawRemote = execSync('git config --get remote.origin.url', {
389
+ cwd,
390
+ encoding: 'utf-8',
391
+ stdio: ['ignore', 'pipe', 'ignore'],
392
+ }).trim();
393
+ remoteUrl = normalizeGitRemoteWebUrl(rawRemote);
394
+ }
395
+ catch {
396
+ // Ignore if origin remote is not configured
397
+ }
398
+ return {
399
+ commitSha: commitSha || undefined,
400
+ branchName: branchName === 'HEAD' ? undefined : branchName || undefined, // handle detached head
401
+ commitMessage: commitMessage || undefined,
402
+ remoteUrl,
403
+ };
404
+ }
405
+ catch {
406
+ // Fallback to direct .git/HEAD filesystem inspection if git CLI fails or is restricted
407
+ return readGitInfoFromFs(cwd);
408
+ }
409
+ }
410
+ const gitInfoAsyncCache = new Map();
411
+ const gitInfoInFlight = new Map();
412
+ const commitMessageByShaCache = new Map();
413
+ /**
414
+ * Fast, zero-subprocess branch/HEAD reader backed purely by `.git/HEAD` filesystem reads.
415
+ * Safe to invoke on high-frequency polling routes (`/api/view`, `/api/status`) without blocking.
416
+ */
417
+ export function getGitInfoFromFs(cwd) {
418
+ const absCwd = resolve(cwd);
419
+ if ((absCwd.includes('/fixtures/cloned-repos/') || absCwd.includes('/fixtures/test-repos/')) &&
420
+ !existsSync(resolve(absCwd, '.git'))) {
421
+ return {};
422
+ }
423
+ return readGitInfoFromFs(absCwd);
424
+ }
425
+ /**
426
+ * Non-blocking, TTL-cached, single-flight equivalent of `getGitInfo` for HTTP server routes.
427
+ * Uses direct `.git/` filesystem reads first for `branchName`, `commitSha`, and `remoteUrl`,
428
+ * and only spawns async `git log -1` once per commit SHA (or falls back to async `git` when
429
+ * ref resolution isn't available directly on disk).
430
+ */
431
+ export async function getGitInfoAsync(cwd, options = {}) {
432
+ const absCwd = resolve(cwd);
433
+ if ((absCwd.includes('/fixtures/cloned-repos/') || absCwd.includes('/fixtures/test-repos/')) &&
434
+ !existsSync(resolve(absCwd, '.git'))) {
435
+ return {};
436
+ }
437
+ const ttlMs = options.ttlMs ?? 1500;
438
+ const includeCommitMessage = options.includeCommitMessage ?? true;
439
+ const cacheKey = `${absCwd}:${includeCommitMessage ? 'full' : 'meta'}`;
440
+ const now = Date.now();
441
+ const cached = gitInfoAsyncCache.get(cacheKey);
442
+ if (cached && cached.expiresAt > now) {
443
+ return cached.value;
444
+ }
445
+ const existing = gitInfoInFlight.get(cacheKey);
446
+ if (existing) {
447
+ return existing;
448
+ }
449
+ const promise = (async () => {
450
+ const fsInfo = readGitInfoFromFs(absCwd);
451
+ let commitSha = fsInfo.commitSha;
452
+ let branchName = fsInfo.branchName;
453
+ let remoteUrl = fsInfo.remoteUrl;
454
+ let commitMessage;
455
+ if (!commitSha) {
456
+ try {
457
+ const [shaRes, branchRes] = await Promise.all([
458
+ execFileAsync('git', ['rev-parse', 'HEAD'], { cwd: absCwd, timeout: 4000 }),
459
+ execFileAsync('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: absCwd, timeout: 4000 }),
460
+ ]);
461
+ const sha = shaRes.stdout.trim();
462
+ const br = branchRes.stdout.trim();
463
+ if (sha)
464
+ commitSha = sha;
465
+ if (br && br !== 'HEAD')
466
+ branchName = br;
467
+ }
468
+ catch {
469
+ // Not a git repo or unborn HEAD; keep filesystem result
470
+ }
471
+ }
472
+ if (includeCommitMessage && commitSha) {
473
+ const msgKey = `${absCwd}:${commitSha}`;
474
+ const cachedMsg = commitMessageByShaCache.get(msgKey);
475
+ if (cachedMsg !== undefined) {
476
+ commitMessage = cachedMsg || undefined;
477
+ }
478
+ else {
479
+ try {
480
+ const { stdout } = await execFileAsync('git', ['log', '-1', '--pretty=%B'], {
481
+ cwd: absCwd,
482
+ timeout: 4000,
483
+ });
484
+ const msg = stdout.trim();
485
+ if (commitMessageByShaCache.size >= 64) {
486
+ const oldest = commitMessageByShaCache.keys().next().value;
487
+ if (oldest)
488
+ commitMessageByShaCache.delete(oldest);
489
+ }
490
+ commitMessageByShaCache.set(msgKey, msg);
491
+ commitMessage = msg || undefined;
492
+ }
493
+ catch {
494
+ commitMessage = fsInfo.commitMessage;
495
+ }
496
+ }
497
+ }
498
+ else if (includeCommitMessage) {
499
+ commitMessage = fsInfo.commitMessage;
500
+ }
501
+ if (!remoteUrl && commitSha) {
502
+ try {
503
+ const { stdout } = await execFileAsync('git', ['config', '--get', 'remote.origin.url'], {
504
+ cwd: absCwd,
505
+ timeout: 4000,
506
+ });
507
+ remoteUrl = normalizeGitRemoteWebUrl(stdout.trim());
508
+ }
509
+ catch {
510
+ // No origin remote configured
511
+ }
512
+ }
513
+ const result = {
514
+ ...(commitSha ? { commitSha } : {}),
515
+ ...(branchName ? { branchName } : {}),
516
+ ...(commitMessage ? { commitMessage } : {}),
517
+ ...(remoteUrl ? { remoteUrl } : {}),
518
+ };
519
+ if (ttlMs > 0) {
520
+ if (gitInfoAsyncCache.size >= 64) {
521
+ const oldest = gitInfoAsyncCache.keys().next().value;
522
+ if (oldest)
523
+ gitInfoAsyncCache.delete(oldest);
524
+ }
525
+ gitInfoAsyncCache.set(cacheKey, {
526
+ expiresAt: Date.now() + ttlMs,
527
+ value: result,
528
+ });
529
+ }
530
+ return result;
531
+ })().finally(() => {
532
+ gitInfoInFlight.delete(cacheKey);
533
+ });
534
+ gitInfoInFlight.set(cacheKey, promise);
535
+ return promise;
536
+ }
537
+ function parseWorktreePorcelain(porcelainOut) {
538
+ const entries = [];
539
+ const blocks = porcelainOut.split(/\n\s*\n/);
540
+ for (const block of blocks) {
541
+ const lines = block.split('\n').map((l) => l.trim()).filter(Boolean);
542
+ if (lines.length === 0)
543
+ continue;
544
+ let wtPath;
545
+ let headSha;
546
+ let branchName;
547
+ for (const line of lines) {
548
+ if (line.startsWith('worktree ')) {
549
+ wtPath = safeRealpath(line.slice('worktree '.length).trim());
550
+ }
551
+ else if (line.startsWith('HEAD ')) {
552
+ headSha = line.slice('HEAD '.length).trim();
553
+ }
554
+ else if (line.startsWith('branch ')) {
555
+ const ref = line.slice('branch '.length).trim();
556
+ branchName = ref.startsWith('refs/heads/')
557
+ ? ref.slice('refs/heads/'.length)
558
+ : ref;
559
+ }
560
+ }
561
+ if (wtPath) {
562
+ entries.push({
563
+ worktreePath: wtPath,
564
+ headSha,
565
+ branchName,
566
+ hasCachedGraphDb: existsSync(resolve(wtPath, '.chomp', 'graph.db')),
567
+ });
568
+ }
569
+ }
570
+ return entries;
571
+ }
572
+ function countMeaningfulDirtyFiles(statusOut) {
573
+ let count = 0;
574
+ for (const line of statusOut.split('\n')) {
575
+ if (!line || line.length < 4)
576
+ continue;
577
+ const rawPath = line.slice(3).trim();
578
+ if (!rawPath)
579
+ continue;
580
+ const relPath = (rawPath.includes(' -> ')
581
+ ? rawPath.split(' -> ').pop().trim()
582
+ : rawPath).replace(/\\/g, '/');
583
+ if (((relPath.startsWith('.chomp/') || relPath === '.chomp') &&
584
+ !relPath.startsWith('.chomp/plugins/') &&
585
+ relPath !== '.chomp/shims.json') ||
586
+ relPath.endsWith('layout_debug.csv') ||
587
+ relPath.endsWith('matrix_debug.csv')) {
588
+ continue;
589
+ }
590
+ count++;
591
+ }
592
+ return count;
593
+ }
594
+ function assembleGitDiffTargets(params) {
595
+ const worktrees = parseWorktreePorcelain(params.worktreesOut);
596
+ const worktreeByBranch = new Map();
597
+ for (const wt of worktrees) {
598
+ if (wt.branchName) {
599
+ worktreeByBranch.set(wt.branchName, wt);
600
+ }
601
+ }
602
+ const rawBranches = [];
603
+ for (const line of params.forEachRefOut.split('\n')) {
604
+ if (!line.trim())
605
+ continue;
606
+ const [name, shortSha, fullSha, committedAt, ...subjectParts] = line.split('\t');
607
+ if (!name || !fullSha)
608
+ continue;
609
+ const wt = worktreeByBranch.get(name);
610
+ const subject = subjectParts.join('\t').trim();
611
+ rawBranches.push({
612
+ name,
613
+ commitSha: (shortSha || fullSha.slice(0, 7)).trim(),
614
+ fullCommitSha: fullSha.trim(),
615
+ ...(subject ? { subject } : {}),
616
+ ...(committedAt ? { committedAt: committedAt.trim() } : {}),
617
+ isCurrent: name === params.currentBranch,
618
+ ...(wt ? { worktreePath: wt.worktreePath, hasCachedGraphDb: wt.hasCachedGraphDb } : {}),
619
+ });
620
+ }
621
+ const branchNames = new Set(rawBranches.map((b) => b.name));
622
+ const originDefault = params.originHeadRef
623
+ ?.trim()
624
+ .replace(/^refs\/remotes\/origin\//, '')
625
+ .replace(/^origin\//, '');
626
+ const defaultBaseBranch = originDefault && branchNames.has(originDefault)
627
+ ? originDefault
628
+ : branchNames.has('main')
629
+ ? 'main'
630
+ : branchNames.has('master')
631
+ ? 'master'
632
+ : params.currentBranch || rawBranches[0]?.name || 'main';
633
+ const branches = rawBranches.map((b) => ({
634
+ ...b,
635
+ isDefaultBase: b.name === defaultBaseBranch,
636
+ }));
637
+ // Promote defaultBaseBranch and currentBranch to the top while preserving recent committerdate order
638
+ branches.sort((a, b) => {
639
+ const rank = (item) => item.isCurrent ? 0 : item.isDefaultBase ? 1 : 2;
640
+ return rank(a) - rank(b);
641
+ });
642
+ const dirtyFileCount = countMeaningfulDirtyFiles(params.statusOut);
643
+ return {
644
+ currentBranch: params.currentBranch || defaultBaseBranch,
645
+ currentCommitSha: params.currentCommitSha
646
+ ? params.currentCommitSha.slice(0, 7)
647
+ : '',
648
+ defaultBaseBranch,
649
+ workingTreeDirty: dirtyFileCount > 0,
650
+ dirtyFileCount,
651
+ branches,
652
+ };
653
+ }
654
+ /**
655
+ * Non-blocking discovery of local Git branches, linked Git worktrees, cached `.chomp/graph.db`
656
+ * availability, and working-tree dirty state (`GET /api/git/branches`).
657
+ */
658
+ export async function listGitBranchesAndWorktrees(repoPath) {
659
+ const absRepo = resolve(repoPath);
660
+ const env = cleanGitEnv();
661
+ const gitInfo = await getGitInfoAsync(absRepo, { ttlMs: 1000 });
662
+ const currentBranch = gitInfo.branchName || 'HEAD';
663
+ const currentCommitSha = gitInfo.commitSha || '';
664
+ try {
665
+ const [refsRes, wtRes, statusRes, originHeadRes] = await Promise.all([
666
+ execFileAsync('git', [
667
+ 'for-each-ref',
668
+ '--sort=-committerdate',
669
+ '--format=%(refname:short)\t%(objectname:short)\t%(objectname)\t%(committerdate:iso-strict)\t%(subject)',
670
+ 'refs/heads',
671
+ ], { cwd: absRepo, env, timeout: 6000, maxBuffer: 8 * 1024 * 1024 }),
672
+ execFileAsync('git', ['worktree', 'list', '--porcelain'], {
673
+ cwd: absRepo,
674
+ env,
675
+ timeout: 6000,
676
+ }).catch(() => ({ stdout: '' })),
677
+ execFileAsync('git', ['status', '--porcelain', '-uall'], {
678
+ cwd: absRepo,
679
+ env,
680
+ timeout: 6000,
681
+ maxBuffer: 16 * 1024 * 1024,
682
+ }).catch(() => ({ stdout: '' })),
683
+ execFileAsync('git', ['symbolic-ref', '-q', 'refs/remotes/origin/HEAD'], {
684
+ cwd: absRepo,
685
+ env,
686
+ timeout: 3000,
687
+ }).catch(() => ({ stdout: '' })),
688
+ ]);
689
+ return assembleGitDiffTargets({
690
+ currentBranch,
691
+ currentCommitSha,
692
+ forEachRefOut: refsRes.stdout,
693
+ worktreesOut: wtRes.stdout,
694
+ statusOut: statusRes.stdout,
695
+ originHeadRef: originHeadRes.stdout,
696
+ });
697
+ }
698
+ catch {
699
+ return {
700
+ currentBranch,
701
+ currentCommitSha: currentCommitSha ? currentCommitSha.slice(0, 7) : '',
702
+ defaultBaseBranch: currentBranch || 'main',
703
+ workingTreeDirty: false,
704
+ dirtyFileCount: 0,
705
+ branches: currentBranch
706
+ ? [
707
+ {
708
+ name: currentBranch,
709
+ commitSha: currentCommitSha.slice(0, 7),
710
+ fullCommitSha: currentCommitSha,
711
+ subject: gitInfo.commitMessage,
712
+ isCurrent: true,
713
+ isDefaultBase: true,
714
+ },
715
+ ]
716
+ : [],
717
+ };
718
+ }
719
+ }
720
+ export async function resolveGitRefInfo(repoPath, refOrBranch, gitTargets) {
721
+ const cleanRef = refOrBranch.trim();
722
+ if (!cleanRef || cleanRef.startsWith('-'))
723
+ return null;
724
+ if (gitTargets?.branches) {
725
+ const matched = gitTargets.branches.find((b) => b.name === cleanRef);
726
+ if (matched && /^[0-9a-f]{40}$/i.test(matched.fullCommitSha)) {
727
+ return {
728
+ ref: cleanRef,
729
+ commitSha: matched.commitSha || matched.fullCommitSha.slice(0, 7),
730
+ fullCommitSha: matched.fullCommitSha,
731
+ branchName: matched.name,
732
+ ...(matched.subject ? { commitMessage: matched.subject } : {}),
733
+ };
734
+ }
735
+ }
736
+ return resolveGitRefCommitAsync(repoPath, cleanRef);
737
+ }
738
+ export async function resolveGitRefCommitAsync(repoPath, refOrBranch) {
739
+ const cleanRef = refOrBranch.trim();
740
+ if (!cleanRef || cleanRef.startsWith('-'))
741
+ return null;
742
+ const absRepo = resolve(repoPath);
743
+ const env = cleanGitEnv();
744
+ try {
745
+ const { stdout: shaOut } = await execFileAsync('git', ['rev-parse', '--verify', `${cleanRef}^{commit}`], { cwd: absRepo, env, timeout: 5000 });
746
+ const fullCommitSha = shaOut.trim();
747
+ if (!/^[0-9a-f]{40}$/i.test(fullCommitSha))
748
+ return null;
749
+ let commitMessage;
750
+ try {
751
+ const { stdout: msgOut } = await execFileAsync('git', ['log', '-1', '--pretty=%B', fullCommitSha], { cwd: absRepo, env, timeout: 4000 });
752
+ commitMessage = msgOut.trim() || undefined;
753
+ }
754
+ catch {
755
+ // Ignore missing commit message
756
+ }
757
+ let branchName;
758
+ try {
759
+ const { stdout: refCheck } = await execFileAsync('git', ['show-ref', '--verify', '--quiet', `refs/heads/${cleanRef}`], { cwd: absRepo, env, timeout: 3000 });
760
+ void refCheck;
761
+ branchName = cleanRef;
762
+ }
763
+ catch {
764
+ if (cleanRef === 'HEAD') {
765
+ const info = await getGitInfoAsync(absRepo, { includeCommitMessage: false });
766
+ branchName = info.branchName;
767
+ }
768
+ }
769
+ return {
770
+ ref: cleanRef,
771
+ commitSha: fullCommitSha.slice(0, 7),
772
+ fullCommitSha,
773
+ ...(branchName ? { branchName } : {}),
774
+ ...(commitMessage ? { commitMessage } : {}),
775
+ };
776
+ }
777
+ catch {
778
+ return null;
779
+ }
780
+ }