~cytrogen/gstack

ref: e04ad1bea0597e595b4b26dfd0bb3b3a0000f960 gstack/browse/src/find-browse.ts -rw-r--r-- 5.2 KiB
e04ad1be — Garry Tan feat: QA test plan tiers with per-page risk scoring a month ago
                                                                                
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
/**
 * find-browse — locate the gstack browse binary + check for updates.
 *
 * Compiled to browse/dist/find-browse (standalone binary, no bun runtime needed).
 *
 * Output protocol:
 *   Line 1: /path/to/binary              (always present)
 *   Line 2+: META:<TYPE> <json-payload>   (optional, 0 or more)
 *
 * META types:
 *   META:UPDATE_AVAILABLE — local binary is behind origin/main
 *
 * All version checks are best-effort: network failures, missing files, and
 * cache errors degrade gracefully to outputting only the binary path.
 */

import { existsSync } from 'fs';
import { readFileSync, writeFileSync } from 'fs';
import { join, dirname } from 'path';
import { homedir } from 'os';

const REPO_URL = 'https://github.com/garrytan/gstack.git';
const CACHE_PATH = '/tmp/gstack-latest-version';
const CACHE_TTL = 14400; // 4 hours in seconds

// ─── Binary Discovery ───────────────────────────────────────────

function getGitRoot(): string | null {
  try {
    const proc = Bun.spawnSync(['git', 'rev-parse', '--show-toplevel'], {
      stdout: 'pipe',
      stderr: 'pipe',
    });
    if (proc.exitCode !== 0) return null;
    return proc.stdout.toString().trim();
  } catch {
    return null;
  }
}

export function locateBinary(): string | null {
  const root = getGitRoot();
  const home = homedir();

  // Workspace-local takes priority (for development)
  if (root) {
    const local = join(root, '.claude', 'skills', 'gstack', 'browse', 'dist', 'browse');
    if (existsSync(local)) return local;
  }

  // Global fallback
  const global = join(home, '.claude', 'skills', 'gstack', 'browse', 'dist', 'browse');
  if (existsSync(global)) return global;

  return null;
}

// ─── Version Check ──────────────────────────────────────────────

interface CacheEntry {
  sha: string;
  timestamp: number;
}

function readCache(): CacheEntry | null {
  try {
    const content = readFileSync(CACHE_PATH, 'utf-8').trim();
    const parts = content.split(/\s+/);
    if (parts.length < 2) return null;
    const sha = parts[0];
    const timestamp = parseInt(parts[1], 10);
    if (!sha || isNaN(timestamp)) return null;
    // Validate SHA is hex
    if (!/^[0-9a-f]{40}$/i.test(sha)) return null;
    return { sha, timestamp };
  } catch {
    return null;
  }
}

function writeCache(sha: string, timestamp: number): void {
  try {
    writeFileSync(CACHE_PATH, `${sha} ${timestamp}\n`);
  } catch {
    // Cache write failure is non-fatal
  }
}

function fetchRemoteSHA(): string | null {
  try {
    const proc = Bun.spawnSync(['git', 'ls-remote', REPO_URL, 'refs/heads/main'], {
      stdout: 'pipe',
      stderr: 'pipe',
      timeout: 10_000, // 10s timeout
    });
    if (proc.exitCode !== 0) return null;
    const output = proc.stdout.toString().trim();
    const sha = output.split(/\s+/)[0];
    if (!sha || !/^[0-9a-f]{40}$/i.test(sha)) return null;
    return sha;
  } catch {
    return null;
  }
}

function resolveSkillDir(binaryPath: string): string | null {
  const home = homedir();
  const globalPrefix = join(home, '.claude', 'skills', 'gstack');
  if (binaryPath.startsWith(globalPrefix)) return globalPrefix;

  // Workspace-local: binary is at $ROOT/.claude/skills/gstack/browse/dist/browse
  // Skill dir is $ROOT/.claude/skills/gstack
  const parts = binaryPath.split('/.claude/skills/gstack/');
  if (parts.length === 2) return parts[0] + '/.claude/skills/gstack';

  return null;
}

export function checkVersion(binaryDir: string): string | null {
  // Read local version
  const versionFile = join(binaryDir, '.version');
  let localSHA: string;
  try {
    localSHA = readFileSync(versionFile, 'utf-8').trim();
  } catch {
    return null; // No .version file → skip check
  }
  if (!localSHA) return null;

  const now = Math.floor(Date.now() / 1000);

  // Check cache
  let remoteSHA: string | null = null;
  const cache = readCache();
  if (cache && (now - cache.timestamp) < CACHE_TTL) {
    remoteSHA = cache.sha;
  }

  // Fetch from remote if cache miss
  if (!remoteSHA) {
    remoteSHA = fetchRemoteSHA();
    if (remoteSHA) {
      writeCache(remoteSHA, now);
    }
  }

  if (!remoteSHA) return null; // Offline or error → skip check

  // Compare
  if (localSHA === remoteSHA) return null; // Up to date

  // Determine skill directory for update command
  const binaryPath = join(binaryDir, 'browse');
  const skillDir = resolveSkillDir(binaryPath);
  if (!skillDir) return null;

  const payload = JSON.stringify({
    current: localSHA.slice(0, 8),
    latest: remoteSHA.slice(0, 8),
    command: `cd ${skillDir} && git stash && git fetch origin && git reset --hard origin/main && ./setup`,
  });

  return `META:UPDATE_AVAILABLE ${payload}`;
}

// ─── Main ───────────────────────────────────────────────────────

function main() {
  const bin = locateBinary();
  if (!bin) {
    process.stderr.write('ERROR: browse binary not found. Run: cd <skill-dir> && ./setup\n');
    process.exit(1);
  }

  console.log(bin);

  const meta = checkVersion(dirname(bin));
  if (meta) console.log(meta);
}

main();