Files
gstack/browse/src/find-browse.ts
T
Garry Tan 07b4e15b34 feat: v0.3.2 — project-local state, diff-aware QA, Greptile integration (#36)
* fix: cookie import picker returns JSON instead of HTML

jsonResponse() was defined at module scope but referenced `url` which
only existed as a parameter of handleCookiePickerRoute(). Every API call
crashed, the catch block also crashed, and Bun returned a default HTML
page that the frontend couldn't parse as JSON.

Thread port via corsOrigin() helper and options objects. Add route-level
tests to prevent this class of bug from shipping again.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: add help command to browse server

Agents that don't have SKILL.md loaded (or misread flags) had no way to
self-discover the CLI. The help command returns a formatted reference of
all commands and snapshot flags.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: version-aware find-browse with META signal protocol

Agents in other workspaces found stale browse binaries that were missing
newer flags. find-browse now compares the local binary's git SHA against
origin/main via git ls-remote (4hr cache), and emits META:UPDATE_AVAILABLE
when behind. SKILL.md setup checks parse META signals and prompt the user
to update.

- New compiled binary: browse/dist/find-browse (TypeScript, testable)
- Bash shim at browse/bin/find-browse delegates to compiled binary
- .version file written at build time with git commit SHA
- Build script compiles both browse and find-browse binaries
- Graceful degradation: offline, missing .version, corrupt cache all skip check

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* chore: clean up .bun-build temp files after compile

bun build --compile leaves ~58MB temp files in the working directory.
Add rm -f .*.bun-build to the build script to clean up after each build.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: make help command reachable by removing it from META_COMMANDS

help was in META_COMMANDS, so it dispatched to handleMetaCommand() which
threw "Unknown meta command: help". Removing it from the set lets the
dedicated else-if handler in handleCommand() execute correctly.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* chore: bump version and changelog (v0.3.2)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: add shared Greptile comment triage reference doc

Shared reference for fetching, filtering, and classifying Greptile
review comments on GitHub PRs. Used by both /review and /ship skills.
Includes parallel API fetching, suppressions check, classification
logic, reply APIs, and history file writes.

* feat: make /review and /ship Greptile-aware

/review: Step 2.5 fetches and classifies Greptile comments, Step 5
resolves them with AskUserQuestion for valid issues and false positives.

/ship: Step 3.75 triages Greptile comments between pre-landing review
and version bump. Adds Greptile Review section to PR body in Step 8.
Re-runs tests if any Greptile fixes are applied.

* feat: add Greptile batting average to /retro

Reads ~/.gstack/greptile-history.md, computes signal ratio
(valid catches vs false positives), includes in metrics table,
JSON snapshot, and Code Quality Signals narrative.

* docs: add Greptile integration section to README

Personal endorsement, two-layer review narrative, full UX walkthrough
transcript, skills table updates. Add Greptile training feedback loop
to TODO.md future ideas.

* feat: add local dev mode for testing skills from within the repo

bin/dev-setup creates .claude/skills/gstack symlink to the working tree
so Claude Code discovers skills locally. bin/dev-teardown cleans up.
DEVELOPING_GSTACK.md documents the workflow.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: narrow gitignore to .claude/skills/ instead of all .claude/

Avoids ignoring legitimate Claude Code config like settings.json or CLAUDE.md.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* docs: rename DEVELOPING_GSTACK.md to CONTRIBUTING.md

Rewritten as a contributor-friendly guide instead of a dry plan doc.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* docs: explain why dev-setup is needed in CONTRIBUTING.md quick start

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: add browser interaction guidance to CLAUDE.md

Prevents Claude from using mcp__claude-in-chrome__* tools instead of /browse.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: add shared config module for project-local browse state

Centralizes path resolution (git root detection, state dir, log paths) into
config.ts. Both cli.ts and server.ts import from it, eliminating duplicated
PORT_OFFSET/BROWSE_PORT/STATE_FILE logic.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: rewrite port selection to use random ports

Replace CONDUCTOR_PORT magic offset and 9400-9409 scan with random port
10000-60000. Atomic state file writes, log paths from config module,
binaryVersion field for auto-restart on update.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: move browse state from /tmp to project-local .gstack/

CLI now uses config module for state paths, passes BROWSE_STATE_FILE to
spawned server. Adds version mismatch auto-restart, legacy /tmp cleanup
with PID verification, and removes stale global install fallback.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: update crash log path reference to .gstack/

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* test: add config tests and update CLI lifecycle test

14 new tests for config resolution, ensureStateDir, readVersionHash,
resolveServerScript, and version mismatch detection. Remove obsolete
CONDUCTOR_PORT/BROWSE_PORT filtering from commands.test.ts.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* docs: update BROWSER.md and TODO.md for project-local state

Replace /tmp paths with .gstack/, remove CONDUCTOR_PORT docs, document
random port selection and per-project isolation. Add server bundling TODO.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* docs: update README, CHANGELOG, and CONTRIBUTING for v0.3.2

- README: replace Conductor-aware language with project-local isolation,
  add Greptile setup note
- CHANGELOG: comprehensive v0.3.2 entry with all state management changes
- CONTRIBUTING: add instructions for testing branches in other repos

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: add diff-aware mode to /qa — auto-tests affected pages from branch diff

When on a feature branch, /qa now reads git diff main, identifies affected
pages/routes from changed files, and tests them automatically. No URL required.
The most natural flow: write code, /ship, /qa.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* chore: update CHANGELOG for complete v0.3.2 coverage

Add missing entries: diff-aware QA mode, Greptile integration,
local dev mode, crash log path fix, README/SKILL.md updates.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 18:10:56 -07:00

182 lines
5.3 KiB
TypeScript

/**
* 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();