From 3deb055529239d23d28e8c9c1f45ea9499b1e502 Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Sun, 22 Nov 2026 03:33:35 -0800 Subject: [PATCH] browse --session before the command, Gemini AQ. keys, /verify trust across worktrees, and two more fixes from outside reports (#4684) Five bugs reported by outside contributors are fixed, each with a test that fails on main: `browse --session` before the command, a stray blank tab in the handoff window, new Gemini keys refused by `$D setup`, `/verify` asking for trust again in every worktree, and `/context-restore` missing a second Claude profile's transcripts. Nothing to do after merge. Co-authored-by: Basim Rauf <22585821+Simba3696@users.noreply.github.com> Co-authored-by: Lockyer <135391289+Lockyer228@users.noreply.github.com> Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Review-Finding: p1v/outside-voice#1 reader=outside-voice Review-Finding: p1v/outside-voice#2 reader=outside-voice Review-Finding: p1v/outside-voice#3 reader=outside-voice Review-Finding: p1v/outside-voice#4 reader=outside-voice --- BROWSER.md | 5 ++++- browse/src/browser-manager.ts | 8 ++++++++ browse/src/cli.ts | 13 ++++++++++--- browse/src/read-commands.ts | 4 ++-- browse/test/cli-chain-stdin.test.ts | 13 ++++++++++--- browse/test/handoff.test.ts | 21 +++++++++++++++++++++ browse/test/proxy-config.test.ts | 10 ++++++++++ changelog.d/fix-outside-browse-design.md | 5 +++++ context-restore/sections/transcripts.md | 2 +- design/scripts/live-gemini-check.ts | 2 +- design/src/auth.ts | 2 +- design/src/cli.ts | 11 ++++++----- design/test/gemini-provider.test.ts | 23 +++++++++++++++++++++++ lib/checks.ts | 24 ++++++++++++++++++++---- lib/redact-patterns.ts | 4 ++-- scripts/resolvers/transcripts.ts | 4 ++-- test/context-restore-transcripts.test.ts | 21 +++++++++++++++++---- test/gstack-checks.test.ts | 22 ++++++++++++++++++++++ test/redact-engine.test.ts | 6 ++++++ 19 files changed, 171 insertions(+), 29 deletions(-) create mode 100644 changelog.d/fix-outside-browse-design.md diff --git a/BROWSER.md b/BROWSER.md index d319829e2..1266512fe 100644 --- a/BROWSER.md +++ b/BROWSER.md @@ -638,7 +638,10 @@ names it, so you can switch away or close it without `--force-restart`. known agent harness (Claude Code, Codex and others) gets a session named after that agent process; its first command opens the session's own tab and later commands stay there without moving the shared active tab. Name one with -`--session ` or `BROWSE_SESSION=`; `BROWSE_SESSION=` turns it off. +`--session ` (before or after the command) or `BROWSE_SESSION=`; +`BROWSE_SESSION=` turns it off. Windows has no automatic session (the harness +lookup reads `/proc` or `ps`), so give each parallel agent its own +`BROWSE_SESSION` there. `--tab-id` and `BROWSE_TAB` win over a session and no longer move the active tab either. Sessions isolate tabs, not cookies or storage, and only the local root token can name one. diff --git a/browse/src/browser-manager.ts b/browse/src/browser-manager.ts index dd67b248c..d35366fa2 100644 --- a/browse/src/browser-manager.ts +++ b/browse/src/browser-manager.ts @@ -1918,6 +1918,7 @@ export class BrowserManager { */ async restoreState(state: BrowserState): Promise { if (!this.context) throw new Error('Browser not launched'); + const startup = new Set(this.context.pages()); // Restore cookies if (state.cookies.length > 0) { @@ -1995,6 +1996,13 @@ export class BrowserManager { // If no pages were saved, create a blank one if (this.pages.size === 0) await this.newTab(); + + // A new persistent context (the headed handoff window) opens a blank tab of + // its own that no saved page maps to; close it, and only it (#4323). + const tracked = new Set(this.pages.values()); + for (const stray of startup) { + if (!tracked.has(stray) && stray.url() === 'about:blank') await stray.close().catch(() => {}); + } this.activeTabId = activeId ?? [...this.pages.keys()][0]; const scope = this.tabScope.getStore(); if (scope && !this.pages.has(this.resolveScopeTab(scope))) scope.tabId = scope.picked = this.activeTabId; diff --git a/browse/src/cli.ts b/browse/src/cli.ts index e1f4f06f3..66bc8ad48 100644 --- a/browse/src/cli.ts +++ b/browse/src/cli.ts @@ -1359,7 +1359,7 @@ function hasFlag(args: string[], flag: string): boolean { } export interface GlobalFlags { - /** Cleaned argv with --proxy/--headed stripped out. */ + /** Cleaned argv with --proxy/--headed stripped out and a leading --session moved right after the command. */ args: string[]; /** Resolved proxy URL (with creds embedded) or null for direct. */ proxyUrl: string | null; @@ -1394,10 +1394,15 @@ export function extractGlobalFlags(rawArgs: string[], env: NodeJS.ProcessEnv, pl let proxyUrl: string | null = null; let headed = false; let forceRestart = false; + const leadingSession: string[] = []; for (let i = 0; i < rawArgs.length; i++) { const arg = rawArgs[i]; if (arg === '--force-restart') { forceRestart = true; continue; } + if (arg === '--session' && out.length === 0 && rawArgs[i + 1] !== undefined) { + leadingSession.push(arg, rawArgs[++i]); + continue; + } if (arg === '--proxy') { const value = rawArgs[i + 1]; if (!value) { @@ -1417,6 +1422,7 @@ export function extractGlobalFlags(rawArgs: string[], env: NodeJS.ProcessEnv, pl if (arg === '--headed') { headed = true; continue; } out.push(arg); } + out.splice(1, 0, ...leadingSession); // Resolve --proxy, BROWSE_PROXY_URL or the standard proxy variables, with // creds embedded (server reads BROWSE_PROXY_URL from env, which passes to @@ -1875,7 +1881,8 @@ Compare: diff Multi-step: chain (reads JSON from stdin) Tabs: tabs | tab | newtab [url] | closetab [id] --session | BROWSE_SESSION=: this caller's own tab - (agents get one per agent process; BROWSE_SESSION= turns it off) + (agents get one per agent process, not on Windows; + BROWSE_SESSION= turns it off) Server: status | cookie = | header : useragent | stop | restart profiles [list] | profiles prune [--days N] (per-project headed profiles) @@ -2212,7 +2219,7 @@ Refs: After 'snapshot', use @e1, @e2... as selectors: // alive, so a piped flow exited 0 with nothing sent to the daemon (#3039). // No flow (a terminal, empty input, an unreadable stdin) is a usage error // before ensureServer(): it never boots a daemon. - if (command === 'chain' && commandArgs.length === 0) { + if (command === 'chain' && extractSession(commandArgs).args.length === 0) { const flow = readChainFlow(Boolean(process.stdin.isTTY), () => fs.readFileSync(0, 'utf8')); if (!flow.ok) { console.error(flow.error); diff --git a/browse/src/read-commands.ts b/browse/src/read-commands.ts index db94dd003..a7a89e5be 100644 --- a/browse/src/read-commands.ts +++ b/browse/src/read-commands.ts @@ -20,7 +20,7 @@ export { validateReadPath } from './path-security'; // Redaction patterns for sensitive cookie/storage values — exported for test coverage export const SENSITIVE_COOKIE_NAME = /(^|[_.-])(token|secret|key|password|credential|auth|jwt|session|csrf|sid)($|[_.-])|api.?key/i; -export const SENSITIVE_COOKIE_VALUE = /^(eyJ|sk-|sk_live_|sk_test_|pk_live_|pk_test_|rk_live_|sk-ant-|ghp_|gho_|github_pat_|xox[bpsa]-|AKIA[A-Z0-9]{16}|AIza|SG\.|Bearer\s|sbp_)/; +export const SENSITIVE_COOKIE_VALUE = /^(eyJ|sk-|sk_live_|sk_test_|pk_live_|pk_test_|rk_live_|sk-ant-|ghp_|gho_|github_pat_|xox[bpsa]-|AKIA[A-Z0-9]{16}|AIza|AQ\.|SG\.|Bearer\s|sbp_)/; /** Detect await keyword, ignoring comments. Accepted risk: await in string literals triggers wrapping (harmless). */ export function hasAwait(code: string): boolean { @@ -595,7 +595,7 @@ export async function handleReadCommand( })); // Redact values that look like secrets (tokens, keys, passwords, JWTs) const SENSITIVE_KEY = /(^|[_.-])(token|secret|key|password|credential|auth|jwt|session|csrf)($|[_.-])|api.?key/i; - const SENSITIVE_VALUE = /^(eyJ|sk-|sk_live_|sk_test_|pk_live_|pk_test_|rk_live_|sk-ant-|ghp_|gho_|github_pat_|xox[bpsa]-|AKIA[A-Z0-9]{16}|AIza|SG\.|Bearer\s|sbp_)/; + const SENSITIVE_VALUE = /^(eyJ|sk-|sk_live_|sk_test_|pk_live_|pk_test_|rk_live_|sk-ant-|ghp_|gho_|github_pat_|xox[bpsa]-|AKIA[A-Z0-9]{16}|AIza|AQ\.|SG\.|Bearer\s|sbp_)/; const redacted = JSON.parse(JSON.stringify(storage)); for (const storeType of ['localStorage', 'sessionStorage'] as const) { const store = redacted[storeType]; diff --git a/browse/test/cli-chain-stdin.test.ts b/browse/test/cli-chain-stdin.test.ts index aaa64fd04..3aadbc7c5 100644 --- a/browse/test/cli-chain-stdin.test.ts +++ b/browse/test/cli-chain-stdin.test.ts @@ -19,7 +19,7 @@ const CLI = path.resolve(import.meta.dir, '../src/cli.ts'); describe('#3039: chain reads its flow from piped stdin', () => { let scratch: string; let daemon: ReturnType; - let received: Array<{ command: string; args: string[] }>; + let received: Array<{ command: string; args: string[]; session?: string }>; let hits: string[]; beforeEach(() => { @@ -48,7 +48,7 @@ describe('#3039: chain reads its flow from piped stdin', () => { fs.rmSync(scratch, { recursive: true, force: true }); }); - async function runChain(stdin: string | 'ignore', opts: { daemon?: boolean } = {}) { + async function runChain(stdin: string | 'ignore', opts: { daemon?: boolean; args?: string[] } = {}) { const stateFile = path.join(scratch, 'browse.json'); if (opts.daemon !== false) { fs.writeFileSync(stateFile, JSON.stringify({ pid: process.pid, port: daemon.port, token: 'chain-stdin-test', mode: 'launched' })); @@ -60,7 +60,7 @@ describe('#3039: chain reads its flow from piped stdin', () => { // Browser dependencies unavailable: a daemon boot attempt could not succeed. Object.assign(env, { HOME: scratch, GSTACK_HOME: path.join(scratch, '.gstack'), BROWSE_STATE_FILE: stateFile, PLAYWRIGHT_BROWSERS_PATH: path.join(scratch, 'no-browsers') }); - const cli = Bun.spawn([process.execPath, CLI, 'chain'], { + const cli = Bun.spawn([process.execPath, CLI, ...(opts.args ?? ['chain'])], { cwd: scratch, env, stdin: stdin === 'ignore' ? 'ignore' : new TextEncoder().encode(stdin), stdout: 'pipe', stderr: 'pipe', }); const timer = setTimeout(() => cli.kill('SIGKILL'), 30_000); @@ -77,6 +77,13 @@ describe('#3039: chain reads its flow from piped stdin', () => { expect(r.code).toBe(0); }, 45_000); + test('a --session before chain still reads the flow from stdin', async () => { + const flow = '[["js","1+1"]]'; + const r = await runChain(`${flow}\n`, { args: ['--session', 'inventory', 'chain'] }); + expect(received).toEqual([{ command: 'chain', args: [flow], session: 'inventory' }]); + expect(r.code).toBe(0); + }, 45_000); + test('empty stdin is a usage error, never a silent exit 0, and never reaches the daemon', async () => { const r = await runChain(''); expect(r.code).toBe(1); diff --git a/browse/test/handoff.test.ts b/browse/test/handoff.test.ts index d0bfeb86a..62a4f68bf 100644 --- a/browse/test/handoff.test.ts +++ b/browse/test/handoff.test.ts @@ -169,6 +169,27 @@ describe('restoreState', () => { expect(stateAfter.cookies.some(c => c.name === 'restored')).toBe(true); expect(stateAfter.pages.length).toBeGreaterThanOrEqual(1); }, 30000); + + test('closes the blank tab a fresh persistent context opens on its own', async () => { + await handleWriteCommand('goto', [baseUrl + '/basic.html'], bm); + const state = await bm.saveState(); + + // Mirror handoff(): a new persistent context starts with an about:blank + // tab of its own and empty tab maps, then restoreState() opens the saved + // tabs. Without the cleanup that first tab stays open in the headed window. + const context = (bm as any).context; + const oldPages = [...(bm as any).pages.values()]; + (bm as any).pages = new Map(); + (bm as any).tabSessions = new Map(); + for (const page of oldPages) await page.close(); + const stray = await context.newPage(); + + await bm.restoreState(state); + + expect(stray.isClosed()).toBe(true); + expect(context.pages().length).toBe((bm as any).pages.size); + expect((await bm.saveState()).pages.some((p: { url: string }) => p.url.includes('/basic.html'))).toBe(true); + }, 30000); }); // ─── Unit Tests: Handoff Edge Cases ────────────────────────────── diff --git a/browse/test/proxy-config.test.ts b/browse/test/proxy-config.test.ts index bc2725c8f..40e543733 100644 --- a/browse/test/proxy-config.test.ts +++ b/browse/test/proxy-config.test.ts @@ -114,6 +114,16 @@ describe('extractGlobalFlags', () => { expect(result.headed).toBe(true); }); + // #4662: `browse --session inventory goto …` read --session as the command. + test('a --session before the command moves after it, where the session is read', () => { + expect(extractGlobalFlags(['--session', 'inventory', 'goto', 'https://x'], ENV_EMPTY).args).toEqual(['goto', '--session', 'inventory', 'https://x']); + expect(extractGlobalFlags(['--session', 'a', 'chain'], ENV_EMPTY).args).toEqual(['chain', '--session', 'a']); + expect(extractGlobalFlags(['--session', 'a', 'goto', 'https://x', '--session', 'b'], ENV_EMPTY).args).toEqual(['goto', '--session', 'a', 'https://x', '--session', 'b']); + expect(extractGlobalFlags(['--headed', '--session', 'a', 'tabs'], ENV_EMPTY).args).toEqual(['tabs', '--session', 'a']); + expect(extractGlobalFlags(['goto', 'https://x', '--session', 'b'], ENV_EMPTY).args).toEqual(['goto', 'https://x', '--session', 'b']); + expect(extractGlobalFlags(['fill', '@e1', '--session'], ENV_EMPTY).args).toEqual(['fill', '@e1', '--session']); + }); + test('supports --proxy=value form', () => { const result = extractGlobalFlags( ['goto', 'https://x', '--proxy=socks5://h:1080'], diff --git a/changelog.d/fix-outside-browse-design.md b/changelog.d/fix-outside-browse-design.md new file mode 100644 index 000000000..53d4de0b3 --- /dev/null +++ b/changelog.d/fix-outside-browse-design.md @@ -0,0 +1,5 @@ +- **`browse --session ` works with the flag before the command.** Before, `--session` in front was read as the command name and failed with `Unknown command: '--session'`. The help and BROWSER.md now also say Windows gets no automatic per-agent session, so each parallel agent there sets `BROWSE_SESSION`. (#4662) +- **The `browse handoff` window no longer opens with a stray blank tab** that `browse tabs` did not list and no command could close. (#4323, #4330) +- **`$D setup` accepts the Gemini keys Google AI Studio issues now, which start with `AQ.`**, and saves a key typed with no `--provider` as a Gemini key. gstack's secret scan and browse's cookie masking now recognize `AQ.` keys too. (#4239) +- **`/verify` trusts a repository's checks in every worktree of it.** Trust was keyed by the checkout folder, so an agent app that starts each session in a fresh worktree asked again every time. The command set still has to match, so a worktree whose checks differ still asks, and only folders git lists as worktrees of the repository share its trust. (#4407) +- **`/context-restore` finds Claude Code transcripts under `CLAUDE_CONFIG_DIR`** (and Codex sessions under `CODEX_HOME`) when a second profile is in use. (#4559) diff --git a/context-restore/sections/transcripts.md b/context-restore/sections/transcripts.md index 85efa66bb..70b3e92e4 100644 --- a/context-restore/sections/transcripts.md +++ b/context-restore/sections/transcripts.md @@ -32,7 +32,7 @@ echo "TRANSCRIPT_PROJECT: $PROJECT_ROOT" if [ -n "${GSTACK_CAPY:-}" ]; then echo "TRANSCRIPTS: none (Capy keeps no session transcript on this machine; use the shared record and git)" else - TRANSCRIPT_DIR="$HOME/.claude/projects/$(printf '%s' "$PROJECT_ROOT" | sed 's/[^A-Za-z0-9]/-/g')" + TRANSCRIPT_DIR="${CLAUDE_CONFIG_DIR:-$HOME/.claude}/projects/$(printf '%s' "$PROJECT_ROOT" | sed 's/[^A-Za-z0-9]/-/g')" if [ -d "$TRANSCRIPT_DIR" ]; then TRANSCRIPT_COUNT=0 while IFS= read -r f; do TRANSCRIPT_COUNT=$((TRANSCRIPT_COUNT + 1)); echo "TRANSCRIPT: $f"; done < <(find "$TRANSCRIPT_DIR" -maxdepth 1 -name '*.jsonl' -mtime -"$TRANSCRIPT_DAYS" 2>/dev/null | sort) diff --git a/design/scripts/live-gemini-check.ts b/design/scripts/live-gemini-check.ts index d4b6261a7..f4899f135 100644 --- a/design/scripts/live-gemini-check.ts +++ b/design/scripts/live-gemini-check.ts @@ -26,7 +26,7 @@ if (!key) { process.exit(2); } const gemini = { provider: "gemini" as const, key, source: "GEMINI_API_KEY environment variable" }; -const redact = (s: string) => s.replace(/\bAIza[0-9A-Za-z_-]{10,}/g, "[redacted]").slice(0, 400); +const redact = (s: string) => s.replace(/\b(?:AIza|AQ\.)[0-9A-Za-z_-]{10,}/g, "[redacted]").slice(0, 400); let failed = false; const report = (call: string, ok: boolean, detail: string) => { if (!ok) failed = true; diff --git a/design/src/auth.ts b/design/src/auth.ts index b287e9354..5092fa142 100644 --- a/design/src/auth.ts +++ b/design/src/auth.ts @@ -2,7 +2,7 @@ * Auth resolution for the design binary's image providers. * * OpenAI key: ~/.gstack/openai.json → { "api_key": "sk-..." }, then OPENAI_API_KEY. - * Gemini key: ~/.gstack/gemini.json → { "api_key": "AIza..." }, then GEMINI_API_KEY. + * Gemini key: ~/.gstack/gemini.json → { "api_key": "AIza..." or "AQ...." }, then GEMINI_API_KEY. * * Provider (resolveProvider), one fixed order: GSTACK_DESIGN_PROVIDER=openai|gemini * when set; else OpenAI when an OpenAI key resolves; else Gemini when a Gemini diff --git a/design/src/cli.ts b/design/src/cli.ts index dc49452e1..9dfb9653d 100644 --- a/design/src/cli.ts +++ b/design/src/cli.ts @@ -92,7 +92,8 @@ function printUsage(): void { console.log("Setup: $D setup [--provider openai|gemini] [--key-stdin]"); } -const KEY_PREFIX: Record = { openai: "sk-", gemini: "AIza" }; +const KEY_PREFIXES: Record = { openai: ["sk-"], gemini: ["AIza", "AQ."] }; +const hasKeyPrefix = (key: string, provider: ProviderName) => KEY_PREFIXES[provider].some((prefix) => key.startsWith(prefix)); const KEY_PAGE: Record = { openai: "https://platform.openai.com/api-keys", gemini: "https://aistudio.google.com/apikey" }; async function readStdinKey(): Promise { @@ -128,13 +129,13 @@ async function runSetup(flags: Record): Promise if (!flags["key-stdin"]) { console.log(provider ? `Enter your ${provider === "gemini" ? "Gemini" : "OpenAI"} API key (get one at ${KEY_PAGE[provider]}).` - : `No API key found. Enter an OpenAI key (sk-…, ${KEY_PAGE.openai}) or a free Gemini key (AIza…, ${KEY_PAGE.gemini}).`); + : `No API key found. Enter an OpenAI key (sk-…, ${KEY_PAGE.openai}) or a free Gemini key (AIza… or AQ.…, ${KEY_PAGE.gemini}).`); process.stdout.write("API key: "); } const key = await readStdinKey(); - provider ??= key.startsWith(KEY_PREFIX.gemini) ? "gemini" : "openai"; - if (!key || !key.startsWith(KEY_PREFIX[provider])) { - console.error(`Invalid key. A${provider === "openai" ? "n OpenAI" : " Gemini"} key starts with '${KEY_PREFIX[provider]}'.`); + provider ??= hasKeyPrefix(key, "gemini") ? "gemini" : "openai"; + if (!key || !hasKeyPrefix(key, provider)) { + console.error(`Invalid key. A${provider === "openai" ? "n OpenAI" : " Gemini"} key starts with ${KEY_PREFIXES[provider].map((p) => `'${p}'`).join(" or ")}.`); process.exit(1); } saveApiKey(key, provider); diff --git a/design/test/gemini-provider.test.ts b/design/test/gemini-provider.test.ts index e1b2b0188..2417566c0 100644 --- a/design/test/gemini-provider.test.ts +++ b/design/test/gemini-provider.test.ts @@ -24,6 +24,7 @@ import { listReceipts } from "../../lib/egress-receipt"; const TINY_PNG = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkAAIAAAoAAv/lxKUAAAAASUVORK5CYII="; const GEMINI_KEY = "AIzaFixtureNotARealKey0000000000000000"; +const GEMINI_AQ_KEY = "AQ.AbExampleFixtureNotARealKey00000000"; const ENV_KEYS = ["HOME", "GSTACK_HOME", "OPENAI_API_KEY", "OPENAI_BASE_URL", "GEMINI_API_KEY", "GSTACK_DESIGN_PROVIDER", DESIGN_MODEL_ENV, DESIGN_IMAGE_MODEL_ENV]; /** Google's documented generateContent answer: candidates[0].content.parts with an inlineData image. */ @@ -156,6 +157,28 @@ describe("$D setup reaches Gemini without a terminal", () => { expect(r.stdout).toContain("Fix: export GSTACK_DESIGN_PROVIDER=gemini"); }); + // #4239: Google AI Studio now issues Gemini keys that start with "AQ.". + test("an AQ. Gemini key is saved and smoke-tested, with or without --provider", () => { + const explicit = cli(["--provider", "gemini", "--key-stdin"], {}, GEMINI_AQ_KEY); + expect(explicit.status, explicit.stderr).toBe(0); + expect(explicit.stdout).toContain("Smoke test PASSED."); + expect(explicit.stdout + explicit.stderr).not.toContain(GEMINI_AQ_KEY); + expect(JSON.parse(fs.readFileSync(path.join(dir, ".gstack", "gemini.json"), "utf8"))).toEqual({ api_key: GEMINI_AQ_KEY }); + fs.rmSync(path.join(dir, ".gstack"), { recursive: true, force: true }); + + const inferred = cli(["--key-stdin"], { OPENAI_API_KEY: "sk-unverified" }, GEMINI_AQ_KEY); + expect(inferred.status, inferred.stderr).toBe(0); + expect(JSON.parse(fs.readFileSync(path.join(dir, ".gstack", "gemini.json"), "utf8"))).toEqual({ api_key: GEMINI_AQ_KEY }); + expect(fs.existsSync(path.join(dir, ".gstack", "openai.json"))).toBe(false); + }); + + test("a Gemini setup still rejects a key that starts with neither AIza nor AQ.", () => { + const r = cli(["--provider", "gemini", "--key-stdin"], {}, "aq.FixtureNotARealKey0000000000000000"); + expect(r.status).toBe(1); + expect(r.stderr).toContain("Invalid key. A Gemini key starts with 'AIza' or 'AQ.'."); + expect(fs.existsSync(path.join(dir, ".gstack", "gemini.json"))).toBe(false); + }); + test("no switch line when the saved key is the one later runs pick", () => { const r = cli(["--provider", "gemini", "--key-stdin"], {}, GEMINI_KEY); expect(r.status, r.stderr).toBe(0); diff --git a/lib/checks.ts b/lib/checks.ts index 729753b5d..bb2fac658 100644 --- a/lib/checks.ts +++ b/lib/checks.ts @@ -24,6 +24,7 @@ import { createHash } from 'node:crypto'; import * as fs from 'node:fs'; import * as path from 'node:path'; import { slugFromEnvironment } from './bin-context'; +import { spawnSync } from './spawn-sync'; import { resolveStateRoot } from './state-root'; import { gbrainConfigDir } from './gbrain-exec'; import { wtreeFingerprint } from './script-invocation'; @@ -213,17 +214,32 @@ function trustRows(store: string): Array<[string, string]> { return (read(store) ?? '').split('\n').filter(Boolean).map(l => l.split('\t') as [string, string]).filter(r => r.length === 2); } +/** Trust belongs to the repository, so every registered worktree of it shares one row (#4407); any other folder, and rows from before that, are keyed by the checkout folder. */ +function trustKeys(root: string): string[] { + const folder = realRoot(root); + const env = { ...process.env }; + for (const name of ['GIT_DIR', 'GIT_COMMON_DIR', 'GIT_WORK_TREE']) delete env[name]; + const git = (args: string[]) => spawnSync('git', args, { cwd: root, env, encoding: 'utf8', timeout: 10_000 }); + const common = git(['rev-parse', '--path-format=absolute', '--git-common-dir']); + const dir = common.status === 0 ? common.stdout.trim() : ''; + if (!path.isAbsolute(dir) || dir.includes('\n')) return [folder]; + const list = git(['--git-dir', dir, 'worktree', 'list', '--porcelain']); + const registered = list.status === 0 && list.stdout.split('\n').some(l => l.startsWith('worktree ') && realRoot(l.slice('worktree '.length)) === folder); + return registered ? [realRoot(dir), folder] : [folder]; +} + export function isTrusted(root: string, set: string, env: NodeJS.ProcessEnv = process.env): boolean { - const key = realRoot(root); - return trustRows(trustStore(env)).some(([p, h]) => p === key && h === set); + const keys = trustKeys(root); + return trustRows(trustStore(env)).some(([p, h]) => keys.includes(p) && h === set); } /** Record root -> command-set hash (0600, atomic, one row per repo) and log the grant beside the verify-gate grants. */ export function recordTrust(root: string, set: string, checks: readonly Check[], config: Pick, env: NodeJS.ProcessEnv = process.env): void { const store = trustStore(env); - const key = realRoot(root); + const keys = trustKeys(root); + const key = keys[0]; fs.mkdirSync(path.dirname(store), { recursive: true }); - const rows = trustRows(store).filter(([p]) => p !== key).concat([[key, set]]); + const rows = trustRows(store).filter(([p]) => !keys.includes(p)).concat([[key, set]]); const tmp = `${store}.tmp.${process.pid}`; fs.writeFileSync(tmp, rows.map(r => r.join('\t')).join('\n') + '\n', { mode: 0o600 }); fs.renameSync(tmp, store); diff --git a/lib/redact-patterns.ts b/lib/redact-patterns.ts index 71167845d..60c6765bb 100644 --- a/lib/redact-patterns.ts +++ b/lib/redact-patterns.ts @@ -1734,8 +1734,8 @@ export const PATTERNS: RedactPattern[] = [ id: "google.api_key", tier: "MEDIUM", category: "secret", - description: "Google API key (AIza…; sometimes a public client key)", - regex: /\b(AIza[0-9A-Za-z\-_]{35})\b/, + description: "Google API key (AIza… or AQ.…; sometimes a public client key)", + regex: /\b(AIza[0-9A-Za-z\-_]{35}|AQ\.[0-9A-Za-z\-_]{20,})\b/, }, { id: "jwt", diff --git a/scripts/resolvers/transcripts.ts b/scripts/resolvers/transcripts.ts index 90f4784ab..684d55ea7 100644 --- a/scripts/resolvers/transcripts.ts +++ b/scripts/resolvers/transcripts.ts @@ -60,7 +60,7 @@ export function generateTranscriptDiscovery(ctx: TemplateContext): string { } else if (ctx.host === 'claude') { body = [ 'else', - ' TRANSCRIPT_DIR="$HOME/.claude/projects/$(printf \'%s\' "$PROJECT_ROOT" | sed \'s/[^A-Za-z0-9]/-/g\')"', + ' TRANSCRIPT_DIR="${CLAUDE_CONFIG_DIR:-$HOME/.claude}/projects/$(printf \'%s\' "$PROJECT_ROOT" | sed \'s/[^A-Za-z0-9]/-/g\')"', ' if [ -d "$TRANSCRIPT_DIR" ]; then', ' TRANSCRIPT_COUNT=0', ' while IFS= read -r f; do TRANSCRIPT_COUNT=$((TRANSCRIPT_COUNT + 1)); echo "TRANSCRIPT: $f"; done < <(find "$TRANSCRIPT_DIR" -maxdepth 1 -name \'*.jsonl\' -mtime -"$TRANSCRIPT_DAYS" 2>/dev/null | sort)', @@ -73,7 +73,7 @@ export function generateTranscriptDiscovery(ctx: TemplateContext): string { } else if (ctx.host === 'codex') { body = [ 'else', - ' TRANSCRIPT_DIR="$HOME/.codex/sessions"', + ' TRANSCRIPT_DIR="${CODEX_HOME:-$HOME/.codex}/sessions"', ' if [ -d "$TRANSCRIPT_DIR" ]; then', ' TRANSCRIPT_COUNT=0', ' while IFS= read -r f; do', diff --git a/test/context-restore-transcripts.test.ts b/test/context-restore-transcripts.test.ts index 568df7f8a..c1774e807 100644 --- a/test/context-restore-transcripts.test.ts +++ b/test/context-restore-transcripts.test.ts @@ -72,7 +72,8 @@ describe('context-restore carve: the transcript fallback', () => { const sources = generateTranscriptSources(ctx); if (host.transcripts) { expect(sources, host.name).toContain(host.transcripts.root); - expect(discovery, host.name).toContain('TRANSCRIPT_DIR="' + host.transcripts.root.replace(/^~/, '$HOME').split(/\/(?=<|\*)/)[0]); + const dir = host.transcripts.root.replace(/^~\/\.claude/, '${CLAUDE_CONFIG_DIR:-$HOME/.claude}').replace(/^~\/\.codex/, '${CODEX_HOME:-$HOME/.codex}').replace(/^~/, '$HOME'); + expect(discovery, host.name).toContain('TRANSCRIPT_DIR="' + dir.split(/\/(?=<|\*)/)[0]); expect(discovery, host.name).not.toContain('declares no transcript store'); } else { expect(sources, host.name).toContain('| ' + host.displayName + ' | none |'); @@ -98,8 +99,8 @@ describe('context-restore carve: the transcript fallback', () => { test('hosts with no declared store render a one-line none; Claude and Codex render their own discovery', () => { const ctx = (host: string) => ({ host, skillName: 'context-restore', paths: { binDir: '$GSTACK_BIN' } }) as never; expect(generateTranscriptDiscovery(ctx('cursor'))).toContain('TRANSCRIPTS: none (Cursor declares no transcript store'); - expect(generateTranscriptDiscovery(ctx('claude'))).toContain('$HOME/.claude/projects/'); - expect(generateTranscriptDiscovery(ctx('codex'))).toContain('$HOME/.codex/sessions'); + expect(generateTranscriptDiscovery(ctx('claude'))).toContain('${CLAUDE_CONFIG_DIR:-$HOME/.claude}/projects/'); + expect(generateTranscriptDiscovery(ctx('codex'))).toContain('${CODEX_HOME:-$HOME/.codex}/sessions'); for (const host of ['claude', 'codex', 'cursor']) expect(generateTranscriptDiscovery(ctx(host))).toContain('if [ -n "${GSTACK_CAPY:-}" ]'); }); }); @@ -113,7 +114,7 @@ describe('the discovery block against fixture transcripts', () => { function sh(script: string, extra: Record = {}, cwd = project) { const env: Record = {}; - for (const [k, v] of Object.entries(process.env)) if (v !== undefined && !k.startsWith('GSTACK_') && k !== 'CLAUDE_PROJECT_DIR') env[k] = v; + for (const [k, v] of Object.entries(process.env)) if (v !== undefined && !k.startsWith('GSTACK_') && !['CLAUDE_PROJECT_DIR', 'CLAUDE_CONFIG_DIR', 'CODEX_HOME'].includes(k)) env[k] = v; const r = spawnSync('bash', ['-c', script], { cwd, env: { ...env, HOME: home, ...extra }, encoding: 'utf8', timeout: 30_000 }); return { out: (r.stdout ?? '') + (r.stderr ?? ''), status: r.status ?? -1 }; } @@ -157,6 +158,18 @@ describe('the discovery block against fixture transcripts', () => { expect(r.out).toMatch(/TRANSCRIPTS: .*\(1 files in the last 7 days\)/); }); + // #4559: a second Claude Code profile (CLAUDE_CONFIG_DIR) keeps its transcripts under its own folder. + test('Claude Code: reads the CLAUDE_CONFIG_DIR profile when one is set', () => { + const profile = path.join(tmp, 'claude-work'); + fs.mkdirSync(path.join(profile, 'projects', slug(project)), { recursive: true }); + fs.copyFileSync(FIXTURE, path.join(profile, 'projects', slug(project), 'w0rk.jsonl')); + const r = sh(block, { CLAUDE_CONFIG_DIR: profile }); + expect(r.status, r.out).toBe(0); + expect(r.out).toContain('/w0rk.jsonl'); + expect(r.out).not.toContain('/7c2f.jsonl'); + expect(r.out).toMatch(/TRANSCRIPTS: .*\(1 files in the last 7 days\)/); + }); + test('a wider window admits the old file; a missing folder and Capy both print none', () => { expect(sh(block, { TRANSCRIPT_DAYS: '30' }).out).toContain('/old.jsonl'); const empty = path.join(tmp, 'work', 'fresh'); diff --git a/test/gstack-checks.test.ts b/test/gstack-checks.test.ts index 4ef977318..1e3cd02c0 100644 --- a/test/gstack-checks.test.ts +++ b/test/gstack-checks.test.ts @@ -122,6 +122,28 @@ describe('gstack-checks on a fixture repo', () => { // Value: protects=nothing runs before consent, including pregate's selection manifest command, and any change to a check or a // selection command needs consent again; fails_when=an untrusted or edited command executes; why_new=the boundary is new; // seam=the fixture's selection command writes a marker when it runs; no_claim=the trust grant log's contents + // #4407: an agent app that starts every session in a fresh git worktree asked for trust every time. + test('trust covers every worktree of the repository while the command set matches', () => { + const s = setup(); + expect(s.checks(['trust']).status).toBe(0); + const wt = path.join(s.repo.root, 'wt-two'); + s.repo.git('worktree', 'add', '-q', wt, '-b', 'scratch'); + const inWorktree = (args: string[]) => runBin(s.repo, 'gstack-checks', [...args, '--base', 'main'], { SELECTION_MARK: s.mark }, wt); + expect(inWorktree(['detect']).out).toContain('TRUST trusted'); + write(wt, 'package.json', JSON.stringify({ name: 'fixture', version: '1.0.0', scripts: { test: 'node --test test/*.test.js', typecheck: 'node scripts/other.js' } }, null, 2) + '\n'); + expect(inWorktree(['detect']).out).toContain('TRUST untrusted'); + expect(s.checks(['detect']).out).toContain('TRUST trusted'); + }); + + test('a folder whose .git file points at a trusted repository, without being its worktree, still asks', () => { + const s = setup(); + expect(s.checks(['trust']).status).toBe(0); + const forged = path.join(s.repo.root, 'forged'); + fs.cpSync(s.repo.work, forged, { recursive: true, filter: src => path.basename(src) !== '.git' }); + fs.writeFileSync(path.join(forged, '.git'), `gitdir: ${path.join(s.repo.work, '.git')}\n`); + expect(runBin(s.repo, 'gstack-checks', ['detect', '--base', 'main'], { SELECTION_MARK: s.mark }, forged).out).toContain('TRUST untrusted'); + }); + test('consent covers the checks and the selection manifest commands', () => { const s = setup(); commit(s.repo, { 'lib/util.js': 'exports.add = (a, b) => b + a;\n' }); diff --git a/test/redact-engine.test.ts b/test/redact-engine.test.ts index 34a46d9c7..795c9bc22 100644 --- a/test/redact-engine.test.ts +++ b/test/redact-engine.test.ts @@ -190,6 +190,12 @@ describe("MEDIUM demoted credential-shaped patterns (TENSION-1)", () => { ); expect(f?.tier).toBe("MEDIUM"); }); + test("an AQ. Gemini key from Google AI Studio is google.api_key", () => { + const f = scan("AQ.Ab" + "c".repeat(40), { repoVisibility: "private" }).findings.find( + (x) => x.id === "google.api_key", + ); + expect(f?.tier).toBe("MEDIUM"); + }); test("jwt is MEDIUM", () => { const jwt = "eyJhbGciOiJ.eyJzdWIiOiI." + "x".repeat(20); const f = scan(jwt, { repoVisibility: "private" }).findings.find((x) => x.id === "jwt");