Skip to content

Use Garry Tan's exact Claude Code setup: 23 opinionated tools that serve as CEO, Designer, Eng Manager, Release Manager, Doc Engineer, and QA

TypeScript
11.8 KB
Raw Blame
/**
 * Shared config for browse CLI + server.
 *
 * Resolution:
 *   1. BROWSE_STATE_FILE env → derive stateDir from parent
 *   2. git rev-parse --show-toplevel → projectDir/.gstack/
 *   3. process.cwd() fallback (non-git environments)
 *
 * The CLI computes the config and passes BROWSE_STATE_FILE to the
 * spawned server. The server derives all paths from that env var.
 */

import * as fs from 'fs';
import * as path from 'path';
import { mkdirSecure } from './file-permissions';
import { safeUnlinkQuiet } from './error-handling';
import { readConfigKey, resolveStateRoot } from '../../lib/state-root';
import { remoteSlug } from '../../lib/remote-identity';

export interface BrowseConfig {
  projectDir: string;
  stateDir: string;
  stateFile: string;
  consoleLog: string;
  networkLog: string;
  dialogLog: string;
  auditLog: string;
}

/**
 * Detect the git repository root, or null if not in a repo / git unavailable.
 */
export function getGitRoot(): string | null {
  try {
    const proc = Bun.spawnSync(['git', 'rev-parse', '--show-toplevel'], {
    windowsHide: true,
      stdout: 'pipe',
      stderr: 'pipe',
      // Raised from 2s: under heavy machine load `git rev-parse` routinely
      // takes >2s (measured 6.3s spikes). Timing out here returns null →
      // resolveConfig falls back to process.cwd() → state files scatter across
      // cwds (split-brain daemons; `goto` and `url` hit different servers). 8s
      // still bounds a genuinely broken .git from hanging the CLI forever.
      timeout: 8_000,
    });
    if (proc.exitCode !== 0) return null;
    return proc.stdout.toString().trim() || null;
  } catch {
    return null;
  }
}

/**
 * Resolve all browse config paths.
 *
 * If BROWSE_STATE_FILE is set (e.g. by CLI when spawning server, or by
 * tests for isolation), all paths are derived from it. Otherwise, the
 * project root is detected via git or cwd.
 */
export function resolveConfig(
  env: Record<string, string | undefined> = process.env,
): BrowseConfig {
  let stateFile: string;
  let stateDir: string;
  let projectDir: string;

  if (env.BROWSE_STATE_FILE) {
    stateFile = env.BROWSE_STATE_FILE;
    stateDir = path.dirname(stateFile);
    projectDir = path.dirname(stateDir); // parent of .gstack/
  } else {
    projectDir = getGitRoot() || process.cwd();
    stateDir = path.join(projectDir, '.gstack');
    stateFile = path.join(stateDir, 'browse.json');
  }

  return {
    projectDir,
    stateDir,
    stateFile,
    consoleLog: path.join(stateDir, 'browse-console.log'),
    networkLog: path.join(stateDir, 'browse-network.log'),
    dialogLog: path.join(stateDir, 'browse-dialog.log'),
    auditLog: path.join(stateDir, 'browse-audit.jsonl'),
  };
}

function isIgnoredByGit(projectDir: string, relPath: string): boolean {
  try {
    const proc = Bun.spawnSync(['git', 'check-ignore', '-q', '--', relPath], {
    windowsHide: true,
      cwd: projectDir, stdout: 'pipe', stderr: 'pipe',
      timeout: 2_000,
    });
    return proc.exitCode === 0;
  } catch {
    // git not found, timed out, or not a repo (exit 128). Fall through to
    // the text-check path — appending is the safe default when unsure.
    return false;
  }
}

function gitExcludePath(projectDir: string): string | null {
  try {
    const proc = Bun.spawnSync(['git', 'rev-parse', '--git-path', 'info/exclude'], {
    windowsHide: true,
      cwd: projectDir, stdout: 'pipe', stderr: 'pipe',
      timeout: 2_000,
    });
    if (proc.exitCode !== 0) return null;
    const rel = proc.stdout.toString().trim();
    return rel ? path.resolve(projectDir, rel) : null;
  } catch {
    return null;
  }
}

/**
 * Create the .gstack/ state directory if it doesn't exist.
 * Throws with a clear message on permission errors.
 */
export function ensureStateDir(config: BrowseConfig): void {
  try {
    mkdirSecure(config.stateDir);
  } catch (err: any) {
    if (err.code === 'EACCES') {
      throw new Error(`Cannot create state directory ${config.stateDir}: permission denied`);
    }
    if (err.code === 'ENOTDIR') {
      throw new Error(`Cannot create state directory ${config.stateDir}: a file exists at that path`);
    }
    throw err;
  }

  // Load-bearing guard: a self-contained ignore INSIDE the state dir so its
  // contents can NEVER be `git add`-ed, regardless of the project's own
  // ignore rules. The state dir holds session-state.json (live cookies +
  // localStorage/sessionStorage tokens) and browse-network.log /
  // browse-audit.jsonl (captured request headers can carry bearer tokens).
  // Written unconditionally, synchronously, before return.
  try {
    fs.writeFileSync(path.join(config.stateDir, '.gitignore'), '*\n');
  } catch {
    // Best-effort; the repository's info/exclude below is the fallback.
  }

  // Ensure git reads .gstack/ as ignored through the repository's own
  // info/exclude, never the project's .gitignore: that file is tracked, and
  // editing it mid-/ship changes the tree after pregate (PREGATE_STALE, #3560).
  if (isIgnoredByGit(config.projectDir, '.gstack/')) return;
  const excludePath = gitExcludePath(config.projectDir);
  if (!excludePath) return;
  try {
    const content = fs.existsSync(excludePath) ? fs.readFileSync(excludePath, 'utf-8') : '';
    if (!content.match(/^\.gstack\/?$/m)) {
      const separator = content === '' || content.endsWith('\n') ? '' : '\n';
      fs.mkdirSync(path.dirname(excludePath), { recursive: true });
      fs.appendFileSync(excludePath, `${separator}.gstack/\n`);
    }
  } catch (err: any) {
    const logPath = path.join(config.stateDir, 'browse-server.log');
    try {
      fs.appendFileSync(logPath, `[${new Date().toISOString()}] Warning: could not update ${excludePath}: ${err.message}\n`);
    } catch {
      // stateDir write failed too — nothing more we can do
    }
  }
}

/**
 * Derive a slug from the git remote origin URL via the shared rule in
 * lib/remote-identity.ts (owner-repo; "<last-two>-<16 hex>" for 3+-segment
 * nested-group remotes, #3003), so browse files state where gstack-slug does.
 * Falls back to the directory basename if no remote is configured.
 */
export function getRemoteSlug(): string {
  try {
    const proc = Bun.spawnSync(['git', 'remote', 'get-url', 'origin'], {
    windowsHide: true,
      stdout: 'pipe',
      stderr: 'pipe',
      timeout: 2_000,
    });
    if (proc.exitCode !== 0) throw new Error('no remote');
    const slug = remoteSlug(proc.stdout.toString().trim());
    if (slug) return slug;
    throw new Error('unparseable');
  } catch {
    const root = getGitRoot();
    return path.basename(root || process.cwd());
  }
}

/**
 * Read the binary version (git SHA) from browse/dist/.version.
 * Returns null if the file doesn't exist or can't be read.
 */
export function readVersionHash(execPath: string = process.execPath): string | null {
  try {
    const versionFile = path.resolve(path.dirname(execPath), '.version');
    return fs.readFileSync(versionFile, 'utf-8').trim() || null;
  } catch {
    return null;
  }
}

/** The gstack state root: delegates to the shared chain in lib/state-root.ts. */
export function resolveGstackHome(): string {
  return resolveStateRoot();
}

/**
 * Read one key from the flat-YAML config store via readConfigKey (the same
 * reader bin/gstack-config uses, including the most-restrictive merge for
 * privacy keys such as telemetry). Tolerates optional single/double quotes
 * around the value and a trailing `# comment`. Returns the unquoted value
 * string, or null when the file is missing or unreadable or the key is absent.
 *
 * Single source of truth for flat-YAML key reads — isPairAgentEnabled
 * (pair_agent) and telemetry.ts (telemetry tier) both route through it so
 * the two consent gates can never drift on parsing semantics.
 */
export function readGstackConfigYamlKey(key: string): string | null {
  const raw = readConfigKey(key);
  if (raw === null) return null;
  return raw.replace(/\s*#.*$/, '').trim().replace(/^(['"])(.*)\1$/, '$2');
}

/**
 * Is the remote pair-agent (ngrok tunnel) surface opt-in enabled?
 *
 * Fail-closed: the tunnel exposes the local browser to the internet, so it
 * stays OFF unless the user explicitly ran `gstack-config set pair_agent on`
 * (the /pair-agent skill asks once on first use and sets it). Any read/parse
 * failure (missing config, malformed JSON) also resolves OFF. The tunnel
 * egress receipts cite this gate as their consent — it must exist and gate
 * every activation point (#B6, fork port wave 2).
 *
 * Env override `GSTACK_PAIR_AGENT=on|off` wins (used by tests and as an
 * emergency knob), mirroring the telemetry env-hint convention.
 */
export function isPairAgentEnabled(): boolean {
  const env = process.env.GSTACK_PAIR_AGENT;
  if (env === 'on') return true;
  if (env === 'off') return false;
  // Canonical store: ~/.gstack/config.yaml (flat `key: value` lines, written
  // by bin/gstack-config — which is what the /pair-agent consent step runs).
  // The fork read config.json; porting that verbatim would have made the gate
  // silently un-enableable on main. JSON kept as a fallback shape only.
  // Anything other than exactly on/off (missing key, malformed value) falls
  // through to the JSON fallback and ultimately fails closed.
  const yamlValue = readGstackConfigYamlKey('pair_agent');
  if (yamlValue === 'on') return true;
  if (yamlValue === 'off') return false;
  try {
    const raw = fs.readFileSync(path.join(resolveGstackHome(), 'config.json'), 'utf-8');
    return JSON.parse(raw)?.pair_agent === 'on';
  } catch {
    return false;
  }
}

/**
 * Resolve the headed Chromium profile directory.
 *
 * Resolution order:
 *   1. `explicit` arg (no production caller passes one today; kept for
 *      direct programmatic use)
 *   2. CHROMIUM_PROFILE env (used by gbrowser's gbd per-workspace)
 *   3. <project state dir>/chromium-profile (default; per project since D5,
 *      #2492 — a machine-wide profile let one project's headed launch kill
 *      another project's live browser)
 */
export function resolveChromiumProfile(explicit?: string): string {
  if (explicit && explicit.length > 0) return explicit;
  const env = process.env.CHROMIUM_PROFILE;
  if (env && env.length > 0) return env;
  return path.join(resolveConfig().stateDir, 'chromium-profile');
}

/**
 * Pre-launch / shutdown cleanup of stale Chromium singleton lockfiles
 * (SingletonLock, SingletonSocket, SingletonCookie). Chromium's
 * ProcessSingleton refuses to start when these exist from a prior crash
 * (SIGKILL, hard crash, etc.) since they point at a PID that no longer exists.
 *
 * Defensive guard: refuses to operate unless ALL of these hold:
 *   1. `userDataDir` is an absolute path (no CWD-relative footguns)
 *   2. basename is exactly 'chromium-profile' OR the absolute path matches
 *      the absolute form of $CHROMIUM_PROFILE env value
 *
 * Prevents accidentally deleting lock files from an unrelated directory if
 * profile resolution is misconfigured upstream (CWD drift, env injection).
 *
 * Caller MUST ensure external coordination has already guaranteed no live
 * peer is using this profile (gbd.lock for gbrowser; single-instance CLI
 * check for gstack).
 */
export function cleanSingletonLocks(userDataDir: string): void {
  if (!path.isAbsolute(userDataDir)) {
    console.warn(`[browse] cleanSingletonLocks: refusing relative path: ${userDataDir}`);
    return;
  }
  const resolved = path.resolve(userDataDir);
  const basename = path.basename(resolved);
  const explicitProfile = process.env.CHROMIUM_PROFILE;
  const explicitAbs = explicitProfile && path.isAbsolute(explicitProfile)
    ? path.resolve(explicitProfile)
    : null;
  const isSafe = basename === 'chromium-profile' || (explicitAbs !== null && resolved === explicitAbs);
  if (!isSafe) {
    console.warn(`[browse] cleanSingletonLocks: refusing to clean unrecognized profile dir: ${resolved}`);
    return;
  }
  for (const lockFile of ['SingletonLock', 'SingletonSocket', 'SingletonCookie']) {
    safeUnlinkQuiet(path.join(resolved, lockFile));
  }
}