Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(bootstrap): Gate 2 checks only the active gh account, not every registered one (#4063)
Masa697016f69d2b
diff --git a/src/core/bootstrap/repo.ts b/src/core/bootstrap/repo.tsindex d8ec0b6196..ad26e80487 100644--- a/src/core/bootstrap/repo.ts+++ b/src/core/bootstrap/repo.ts@@ -133,6 +133,28 @@ function isRateLimitOr5xx(stderr: string): boolean {return /HTTP 5\d\d|HTTP 429|rate limit/i.test(stderr);}+/** `gh auth status`'s `--active` flag (added in cli/cli v2.57.0, 2024-09-11)+ * scopes the check to only the active account instead of aggregating every+ * registered account. On an older `gh`, passing an unrecognized flag makes+ * the WHOLE command fail — so Gate 2 must detect support before using it. */+const GH_ACTIVE_FLAG_MIN_VERSION = [2, 57, 0] as const;++/** Parses the `X.Y.Z` out of `gh --version`'s first line (`gh version X.Y.Z (DATE)`).+ * Returns null on any unrecognized format — callers treat that as "unknown,+ * don't assume support". */+function parseGhVersion(versionOutput: string): readonly [number, number, number] | null {+ const m = /\bgh version (\d+)\.(\d+)\.(\d+)/.exec(versionOutput);+ if (!m) return null;+ return [Number(m[1]), Number(m[2]), Number(m[3])];+}++function ghVersionAtLeast(v: readonly [number, number, number], min: readonly [number, number, number]): boolean {+ for (let i = 0; i < 3; i++) {+ if (v[i] !== min[i]) return v[i]! > min[i]!;+ }+ return true;+}+/** The authenticated gh login, or null when it cannot be read/parsed. */async function fetchAuthedLogin(runner: ExecRunner): Promise<string | null> {const res = await runner(['gh', 'api', 'user']);@@ -594,7 +616,22 @@ export async function createPrivateRepo(}// Gate 2: authenticated. Exit-code-2 — the human runs `gh auth login`.- const ghAuth = await runner(['gh', 'auth', 'status']);+ // `--hostname github.com` scopes the check to the host this flow actually+ // targets (every downstream call — parseGithubOwnerRepo, the repo-create+ // URL fallback, etc. — is github.com-only), so an unrelated broken account+ // on some other configured host (e.g. a GitHub Enterprise instance) can't+ // false-block it either. `--active` (only when the installed `gh` supports+ // it) further restricts that host's check to the active account. Bare+ // `gh auth status` aggregates EVERY registered account on EVERY host and+ // exits 1 if any one of them is invalid — even an unused, long-expired+ // account — which false-blocks this gate while the active account (what+ // `gh`/`git` actually use) is perfectly healthy.+ const ghVersionTuple = parseGhVersion(ghVersion.stdout);+ const ghSupportsActiveFlag = ghVersionTuple !== null && ghVersionAtLeast(ghVersionTuple, GH_ACTIVE_FLAG_MIN_VERSION);+ const ghAuthArgv = ghSupportsActiveFlag+ ? ['gh', 'auth', 'status', '--active', '--hostname', 'github.com']+ : ['gh', 'auth', 'status', '--hostname', 'github.com'];+ const ghAuth = await runner(ghAuthArgv);if (ghAuth.code !== 0) {throw new BootstrapError('GH_AUTH',diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 0fadb34157..9934ba1187 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -17,7 +17,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'backfill': ['--aliases', '--all', '--batch-size', '--brain', '--concurrency', '--dry-run', '--fresh', '--help', '--include-null-signature', '--json', '--keep-index', '--list', '--max-errors', '--max-rows', '--no-extract', '--pattern', '--pending', '--reset', '--resolve', '--resume', '--source', '--stale', '--supersessions', '--thin'],'bench': ['--baseline', '--brain', '--explain', '--force', '--from', '--help', '--json', '--label', '--lang', '--limit', '--markdown', '--multimodal', '--near-symbol', '--restore-only', '--source', '--stale', '--symbol-kind', '--thin', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-top1', '--to', '--tool'],'book-mirror': ['--aliases', '--all', '--allow-empty', '--apply', '--asof', '--author', '--auto', '--background', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--brain-wide-max-cost-usd', '--budget-usd-per-day', '--by-mention', '--chapters-dir', '--content', '--context-file', '--date', '--days', '--dry-run', '--entities', '--explain', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--help', '--http', '--image', '--include-null-signature', '--json', '--kind', '--limit', '--max-turns', '--max-usd', '--mode', '--model', '--multimodal', '--no-confirm', '--no-embedding', '--no-extract', '--no-follow', '--offset', '--path', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reset', '--resolve', '--save', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--stale', '--stats', '--supersessions', '--surface', '--thin', '--timeout', '--timeout-ms', '--title', '--trusted-extraction', '--url', '--with-db', '--yes'],- 'bootstrap': ['--abbrev-ref', '--abort', '--accept-visibility-change-consequences', '--all', '--allow-unverified-remote', '--brain', '--branch', '--cached', '--compile', '--confirm', '--count', '--delete-brain', '--diff-filter', '--env', '--error-unmatch', '--exclude-standard', '--fast', '--file', '--flag', '--force', '--from-pages', '--full', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--harness', '--heads', '--help', '--home', '--http', '--init', '--is-inside-work-tree', '--isolated', '--jq', '--json', '--local', '--minimal', '--name-only', '--no-cron', '--no-embedding', '--no-hooks', '--no-verify', '--once', '--only', '--others', '--pat-file', '--path', '--pglite', '--porcelain', '--private', '--push', '--push-only', '--quiet', '--rebase', '--repair', '--scope', '--set', '--short', '--show', '--show-toplevel', '--skip', '--source', '--status', '--surface', '--unset-all', '--verify', '--version', '--visibility', '--workspace', '--yes'],+ 'bootstrap': ['--abbrev-ref', '--abort', '--accept-visibility-change-consequences', '--active', '--all', '--allow-unverified-remote', '--brain', '--branch', '--cached', '--compile', '--confirm', '--count', '--delete-brain', '--diff-filter', '--env', '--error-unmatch', '--exclude-standard', '--fast', '--file', '--flag', '--force', '--from-pages', '--full', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--harness', '--heads', '--help', '--home', '--hostname', '--http', '--init', '--is-inside-work-tree', '--isolated', '--jq', '--json', '--local', '--minimal', '--name-only', '--no-cron', '--no-embedding', '--no-hooks', '--no-verify', '--once', '--only', '--others', '--pat-file', '--path', '--pglite', '--porcelain', '--private', '--push', '--push-only', '--quiet', '--rebase', '--repair', '--scope', '--set', '--short', '--show', '--show-toplevel', '--skip', '--source', '--status', '--surface', '--unset-all', '--verify', '--version', '--visibility', '--workspace', '--yes'],'brainstorm': ['--aliases', '--all', '--brain', '--chunker-debug', '--code', '--compile', '--fast', '--fix', '--force', '--force-rechunk', '--force-resume', '--from-pages', '--full', '--help', '--http', '--include-null-signature', '--json', '--judge-model', '--lang', '--limit', '--list-runs', '--markdown', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--model', '--no-embed', '--no-embedding', '--no-extract', '--no-save', '--pattern', '--pending', '--reset', '--resolve', '--resume', '--retry-failed', '--retry-judge', '--save', '--source', '--stale', '--strict-budget', '--supersessions', '--surface', '--thin', '--timeout', '--yes'],'cache': ['--brain', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--no-embedding', '--source', '--surface', '--yes'],'calibration': ['--ab', '--aliases', '--all', '--allow-empty', '--apply', '--asof', '--auto', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--by-mention', '--content', '--date', '--days', '--dry-run', '--entities', '--explain', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--help', '--holder', '--http', '--image', '--include-null-signature', '--json', '--key-prefix', '--kind', '--lang', '--limit', '--markdown', '--max-usd', '--mode', '--multimodal', '--near-symbol', '--no-embedding', '--no-extract', '--no-federated', '--offset', '--path', '--pattern', '--pending', '--phase', '--progress-interval', '--progress-json', '--quiet', '--regenerate', '--repo', '--reset', '--resolve', '--restore-only', '--save', '--scrub-gstack', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--stale', '--stats', '--supersessions', '--surface', '--symbol-kind', '--thin', '--trusted-extraction', '--undo-wave', '--url', '--with-calibration', '--with-db', '--yes'],diff --git a/test/bootstrap-repo.test.ts b/test/bootstrap-repo.test.tsindex c370d3cb1e..e9fadd6c22 100644--- a/test/bootstrap-repo.test.ts+++ b/test/bootstrap-repo.test.ts@@ -88,7 +88,9 @@ afterEach(() => {function happyRules(overrides: Rule[] = []): Rule[] {return [...overrides,- { key: 'gh --version', code: 0 },+ // Realistic modern `gh --version` output — Gate 2 parses this to decide+ // whether `--active` (added in cli/cli v2.57.0) is safe to pass.+ { key: 'gh --version', code: 0, stdout: 'gh version 2.97.0 (2026-07-31)\nhttps://github.com/cli/cli/releases/tag/v2.97.0\n' },{ key: 'auth status', code: 0 },// First origin probe: no remote yet. After create, git reports the URL.{ key: 'remote get-url origin', times: 1, code: 2, stderr: 'error: No such remote' },@@ -393,6 +395,61 @@ describe('createPrivateRepo', () => {expect(err.message).toContain('gh auth login');});+ test('Gate 2 on a modern gh checks only the active account on github.com — a stale, invalid non-active/other-host account must not false-block bootstrap', async () => {+ // `gh auth status` (no flags) aggregates every registered account on+ // every host and exits 1 if ANY one of them is invalid, even if the+ // active github.com account (what `gh`/`git` actually use for this+ // flow) is perfectly healthy — confirmed against cli/cli's status.go+ // (statusRun: the non-active-account loop at `if opts.Active { continue }`+ // is skipped entirely under `--active`, so only the active account's+ // entry can contribute to the exit code; `--hostname` narrows Hosts()+ // to the given host before that loop even starts). Gate 2 must pass+ // both flags on a `gh` that supports them — this test pins the exact+ // argv so a regression back to the unscoped bare form is caught.+ const { runner, calls } = makeRunner(happyRules());+ await createPrivateRepo(ws, { runner, gbrainHomeDir: home });+ const authCall = calls.find((c) => c[0] === 'gh' && c[1] === 'auth' && c[2] === 'status');+ expect(authCall).toEqual(['gh', 'auth', 'status', '--active', '--hostname', 'github.com']);+ });++ test('Gate 2 on a pre-2.57.0 gh (no `--active` support) falls back to the host-scoped bare form instead of hard-failing on an unknown flag', async () => {+ // `--active` was added in cli/cli v2.57.0 (confirmed: present in the+ // v2.57.0 status.go, absent in v2.56.0 and earlier). Passing it to an+ // older `gh` would make the WHOLE command fail on an unrecognized flag —+ // a false GH_AUTH for a perfectly authenticated user. Gate 2 must detect+ // this from the `gh --version` output already captured in Gate 1 and+ // drop only `--active` (keeping `--hostname`, which has existed since+ // gh's early versions). Pinned right at the boundary (2.56.0, one minor+ // below the flag's introduction) rather than an arbitrarily old version,+ // so an off-by-one in the `>=` comparison would fail this test.+ const { runner, calls } = makeRunner(+ happyRules([+ { key: 'gh --version', code: 0, stdout: 'gh version 2.56.0 (2024-08-01)\n' },+ ]),+ );+ await createPrivateRepo(ws, { runner, gbrainHomeDir: home });+ const authCall = calls.find((c) => c[0] === 'gh' && c[1] === 'auth' && c[2] === 'status');+ expect(authCall).toEqual(['gh', 'auth', 'status', '--hostname', 'github.com']);+ });++ test('Gate 2 on exactly gh 2.57.0 (the version that introduced `--active`) uses the enhanced form', async () => {+ const { runner, calls } = makeRunner(+ happyRules([{ key: 'gh --version', code: 0, stdout: 'gh version 2.57.0 (2024-09-11)\n' }]),+ );+ await createPrivateRepo(ws, { runner, gbrainHomeDir: home });+ const authCall = calls.find((c) => c[0] === 'gh' && c[1] === 'auth' && c[2] === 'status');+ expect(authCall).toEqual(['gh', 'auth', 'status', '--active', '--hostname', 'github.com']);+ });++ test('Gate 2 with an unparseable `gh --version` falls back to the host-scoped bare form (fail conservative, not assume `--active` support)', async () => {+ const { runner, calls } = makeRunner(+ happyRules([{ key: 'gh --version', code: 0, stdout: 'not a recognizable version string\n' }]),+ );+ await createPrivateRepo(ws, { runner, gbrainHomeDir: home });+ const authCall = calls.find((c) => c[0] === 'gh' && c[1] === 'auth' && c[2] === 'status');+ expect(authCall).toEqual(['gh', 'auth', 'status', '--hostname', 'github.com']);+ });+// ── create-repo-first adoption (the human made the repo, opened it in Claude// Code / Codex, then ran bootstrap) + hardening of the adoption path ──────