* fix(plan-tune): reject never-ask on one-way ids at --write --check already ignored those prefs; --write still stored them and --stats counted them as a working NEVER_ASK. Refuse the write and count leftover on-disk prefs as INERT_ONE_WAY. Co-authored-by: Cursor <cursoragent@cursor.com> * Fix: gstack-config get returns "" with exit 0 for keys that have no default Skill preambles read configuration with VAR=$(gstack-config get <key> 2>/dev/null || echo "<default>") and that fallback only fires on a non-zero exit. lookup_default ended in a catch-all that echoed "" and returned 0, so for any key missing from the table VAR came back empty and the default written right there in the preamble was unreachable. The skill then branched on a value it never specified: "skip entirely if QUESTION_TUNING is false", reached with QUESTION_TUNING="". Four keys that skills actually read had no entry and took that path: question_tuning -> callers assume "false" repo_mode -> callers assume "unknown" team_mode -> callers assume "false" transcript_ingest_mode -> callers assume "off" Each default above is the value the call sites already substitute in their own `|| echo` fallback, so this only makes reachable what was already intended. The catch-all now returns non-zero. That is deliberately scoped to the unknown-key arm alone: keys whose default is intentionally empty still exit 0, because "" is their real answer and their callers depend on it -- cross_project_learnings ("unset triggers the first-time prompt"), redact_repo_visibility ("empty falls through to gh/glab detection"), salience_allowlist, user_slug_at_*. Making every empty answer an error would have broken those. test/gstack-config-defaults.test.ts pins the class rather than the four instances: it parses the case arms and asserts every `gstack-config get <key>` site in the tree is covered, so adding a read without a default fails CI. It also pins the exit-code contract in both directions. Verified failing against the pre-fix script, where it names exactly those four keys. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(redact): a typo'd subcommand no longer exits 0 having done nothing main() recognised exactly two subcommands and let everything else fall through to the stdin scan. On empty stdin that prints "(no findings)" and exits 0, so: $ gstack-redact install-prepush-hooks # plural typo gstack-redact scan — repo UNKNOWN (no findings) $ echo $? 0 No hook was installed, and the operator has every reason to believe the credential guard is armed. A guard that silently no-ops must never exit 0. Two smaller faults in the same dispatch, both of which lead people here: - There was no --help handler, so `gstack-redact --help` fell through to the scanner. Piping a credential to it scanned the secret and exited 3. - With no piped input and no --from-file, readInput() blocks on readSync(fd 0) until an EOF that an interactive terminal never sends. That prints nothing at all, so it reads as a hang rather than as "this is a filter, feed it". Now: --help/-h/help prints usage and exits 0; an unrecognised positional prints the offender and exits 1; a TTY with nothing piped in prints usage instead of blocking. "scan" stays accepted, because the human output header reads "gstack-redact scan — repo …" and that is what people type. Usage errors exit 1, deliberately not 2 or 3. Those mean MEDIUM and HIGH findings and callers gate dispatch on them, so a usage error exiting 2 would be read as "medium findings — prompt the user". A test pins that. Tests: 4 written failing first, then fixed. Full suite 7,722 pass / 0 fail. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(browse): one ambiguous ref no longer kills the whole annotated screenshot `snapshot -a` exits 1 with "Selector matched multiple elements" on most real pages, so /qa, /canary and /land-and-deploy silently produce reports whose screenshots do not exist. Plain `screenshot <path>` is unaffected. Refs are built as getByRole(role, {name}) and disambiguated with .nth() when role+name repeats. That disambiguation cannot fire for a node with NO accessible name: the locator degrades to getByRole(role) with no name filter, and the count driving .nth() is taken from the FILTERED aria snapshot while getByRole matches the unfiltered DOM. Measured on a live page: the tree surfaced 2 unnamed paragraphs, the DOM had 9. Landmarks (banner/main/contentinfo) and paragraphs are correctly unnamed per ARIA, so this is the common case rather than an edge case. boundingBox() then hits Playwright strict mode, and the catch allowlisted only timeout/closed/Target/Execution-context messages — so the strict-mode error was re-thrown and aborted every remaining annotation. Two changes: - `.first()` before boundingBox(), so an ambiguous ref draws a box on its first match instead of aborting. The heatmap path below has always tolerated this via a bare `catch {}`; annotate was the only path that could be killed outright. - the catch no longer re-throws on unrecognised messages. A box we cannot measure is a box we do not draw, never a reason to lose the rest of the page. Set BROWSE_DEBUG to see what was skipped. Also: `-o` passed without `-a`/`-H` was silently ignored (exit 0, no file), which reads as "screenshots are broken" rather than "you forgot a flag". It now warns and points at `browse screenshot <path>`. Verified by rebuilding both ways against the same page with 51 refs present: before — "Selector matched multiple elements", no file written after — exit 0, 229KB PNG Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(version-bump): missing or empty VERSION no longer repairs a fabricated 0.0.0.0 into package.json repair now fails with exit 2 when the VERSION file is absent or empty instead of folding to DEFAULT ("0.0.0.0") — which passed VERSION_RE and regressed package.json below where it started. classify gains an additive versionFileExists field so /ship can tell a real 0.0.0.0 from a fabricated one. Re-derived from PR #2612 under the generated-file screening rule. Fixes #2600 (repair half; the path-configurability half landed in v1.67 via #2531). Contributed by @Lockyer228 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(memory-ingest): --probe counts post-attribution, through the same gate --bulk uses probeMode previously stat'd every walked file, so setup-gbrain gated its silent bulk ingest on pre-filter counts that the write path would never ingest (#2394). The attribution decision now lives in ONE shared gate (sessionIsAttributable — cheap-parse: cwd extraction + memoized resolveGitRemote, never a full page build) used by BOTH probeMode and preparePages, so the two stages' post-attribution counts are structurally identical. ProbeReport gains skipped_unattributed; the probe prints what it excluded and --include-unattributed restores raw counts. The parity is pinned at the prepare stage (probe post-attribution == transcripts reaching import), deliberately NOT == final written. Re-derived from PR #2612 under the generated-file screening rule; the shared-gate design and the remote memo are additions from the plan review. Fixes #2394. Contributed by @Lockyer228 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(browse): allow CPU and network throttling for performance measurement Adds Emulation.setCPUThrottlingRate and Network.emulateNetworkConditions to CDP_ALLOWLIST. Motivation: diagnosing a real "uploads take 1-2 minutes" report, the only machine available was a fast developer workstation. Client-side processing measured 1.4s where the user experienced minutes, so the conclusion had to be reached arithmetically rather than observed. Throttling would have let the measurement reproduce the reporter's conditions directly. Both fit the existing posture rather than widening it: - Emulation already allows setDeviceMetricsOverride, clearDeviceMetricsOverride and setUserAgentOverride, which are equally mutating and scoped to the tab. - Neither method reads page content. setCPUThrottlingRate affects only timing; emulateNetworkConditions constrains traffic rather than inspecting it, so no request bodies, headers or cookies are exposed. Both are output: 'trusted' because they return no page-derived data. scope 'tab' for both, matching the surrounding Emulation entries. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(session-update): lock pidfile records the live holder; hard TTL bounds every wedge (#2613) echo $$ inside the backgrounded subshell recorded the PARENT hook's PID — which exits immediately — so every subsequent session judged the lock stale and rm -rf'd a LIVE holder's lock, letting concurrent updaters run over each other. The pidfile now records ${BASHPID:-$(sh -c 'echo $PPID')} (macOS bash 3.2 has no BASHPID; the sh child's PPID is exactly this subshell). Staleness is now two independent detectors: PID liveness (as before, but against the real holder), and a 30-minute hard TTL on the heartbeat mtime — reclaimed regardless of kill -0, so a recycled PID or hung holder can't wedge the lock forever. The holder touches the pidfile after the pull and after setup, so a legitimately-slow run keeps itself alive. Empty and missing pidfiles are respected inside the TTL window (the mkdir→echo race) and reclaimed past it. Fixes #2613. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * chore(browse): explicit windowsHide on every Bun.spawn site + census tripwire (#2575 residual) Bun.spawn sites were structurally outside the windowsHide census (it swept child_process bindings only). The runtime was already safe — native Bun hides consoles by default and bun-polyfill.cjs defaults windowsHide !== false since #2523/#2539 — but implicit defaults are exactly what regress silently. Every Bun.spawn/spawnSync in browse/src now carries the explicit flag (harmless on unix-only sites like Xvfb/xattr/open), and a second SWEEP in windows-spawn-hide.test.ts fails CI on any new flagless Bun.spawn site. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(gbrain): brain worktree advances on the daily sync — no more silently stale brains (#2516) The daily pull refreshed only ~/.gstack itself, never the detached worktree at ~/.gstack-brain-worktree that gbrain actually indexes — so after setup the brain served stale pages forever unless setup-gbrain/sync-gbrain happened to run. brain-sync --once now advances the worktree once per 24h behind an ATTEMPT stamp (.brain-worktree-last-advance — a persistently-failing advance warns once a day, not at every skill boundary), inside the existing run lock and before any ingest step touches the worktree. The new gstack-gbrain-source-wireup --advance-only is built for the unattended cadence: git-only (no gbrain prereqs), pins every operation to the managed worktree (refuses paths that are not worktrees of the artifacts repo), refuses dirty worktrees, and never runs the force-remove recovery — a cron path must not be able to delete local changes. A static pin keeps the force-remove out. docs/gbrain-sync.md stops overclaiming the old cadence. Fixes #2516. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(memory-ingest): honor the per-remote deny/read-only trust policy (#2392) Transcript ingest now respects the same trust store as code import — the gate existed only in gstack-gbrain-sync's runCodeImport, so memory-ingest happily ingested transcripts from deny-listed repos. preparePages filters prepared transcript pages through ONE batch policy lookup (new 'get --batch' verb on bin/gstack-gbrain-repo-policy — the script owns URL normalization; the client adds repoPolicyTierBatch, one spawn for all distinct remotes, so large corpora never pay a 10s-timeout subprocess per remote). Outcomes match code-import semantics: read-only → clean skip (skipped_policy_readonly), deny → counted refusal (skipped_policy_deny), corrupted/unreadable store → HARD ERROR before any write (state, staging, egress receipt, and import all untouched) with the recovery command named — policy corruption must never read as successful ingestion. Artifacts are never policy-filtered (their git_remote is a project slug, not a remote). Fixes #2392. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(config): repo_mode keeps its empty no-default semantics (#2611 follow-up) The ported defaults table synthesized repo_mode → "unknown", but EMPTY is load-bearing for that key: gstack-repo-mode treats any non-empty answer as a user override and skips its own repo classification — the synthesized default turned the classifier into dead code (REPO_MODE=unknown everywhere; caught by test/gstack-repo-mode.test.ts via the wave's cross-agent blame protocol). repo_mode joins the empty-is-real carve-outs (empty output, exit 0). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(pair-agent): consent before killing a healthy headless daemon The pair-agent headed switch spawned 'connect --force-restart' unconditionally — auto-killing a live headless daemon (open tabs, cookies, logins) in direct contradiction of the iron rule it sits beside ('only an explicit --force-restart may kill a live daemon'). The CLI now captures daemon liveness BEFORE ensureServer (which can itself boot a fresh daemon) and relaunches only when the user passed --force-restart to pair-agent; otherwise it prints the tab count and continues against the existing daemon. The /pair-agent skill gains a matching one-way-door consent question (template half rides the wave's template block). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(gbrain-status): MCP scoping is per-project, and project-local beats user scope hasRemoteOnlyGbrainMcp scanned EVERY project's mcpServers in ~/.claude.json, so one project's remote gbrain registration reclassified broken local engines as thin-client machine-wide. It now reads user scope plus only the cwd's nearest-ancestor project key. The precedence itself was verified empirically and hermetically (fake HOME + CLAUDE_CONFIG_DIR fixtures, claude 2.1.233): with both scopes defining gbrain, 'claude mcp get gbrain' reports Scope: Local config — PROJECT-LOCAL WINS. Both in-repo consumers assumed the opposite; brain-cache's endpoint resolution flips to nearest-ancestor-project-first, and the stale user-first pin in brain-cache-roundtrip now pins the verified precedence. (The user-first jq in the brain-sync preamble resolver gets the same swap in the template block.) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(slug): gstack-slug matches remote-slug's owner-repo canonical form (live misfile bug) Found live during this wave's CEO review: bin/gstack-slug emitted SLUG=garrytan for this garrytan/gstack worktree while remote-slug correctly gave garrytan-gstack — decisions, timeline, ceo-plans, and learnings were filing into the wrong project store (observed polluting Context Recovery with another repo's decisions). Root cause: a stray empty ~/.git directory made the walk-up crown $HOME as the outermost project root; the remote lookup ran only against that root, failed silently, and the basename fallback cached 'garrytan' sticky. NOT worktree-specific — any strong marker on a non-repo ancestor triggered it. Fix: the walk now finds the outermost ancestor whose .git actually resolves an origin remote and derives owner-repo with remote-slug's byte-identical parse; marker-only ancestors keep anchoring the basename fallback but can no longer shadow a real remote. A new cache self-heal recomputes the poisoned shape (cached == basename of a marker root while a remote-bearing repo exists below), preserving legit #2212 stickiness. Nested-repo walk-up, no-remote and non-git fallbacks, and the SLUG=/BRANCH= eval contract are unchanged, pinned by a 10-case parity suite. Store migration for pre-fix data is tracked in TODOS.md. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(brain-sync): per-record spool dir — the enqueue/drain race dies structurally Producers appended lines to .brain-queue.jsonl while the drain re-read and os.replace'd it; the in-code comment admitted a lockless append between the re-read and the replace was lost. Locks and rename-rotation designs were both reviewed and rejected (each retained a tail race); the shipped design is a maildir-style spool: one FILE per record in .brain-queue.d/ (tmp + atomic rename), the drain snapshots filenames, processes, and deletes exactly what it snapshotted. Writer and drainer never share an inode — nothing to race. Semantics: at-least-once (a crash between process and unlink re-drains; downstream content-hash dedup absorbs duplicates); retained (privacy-held) records keep their files; unparseable records are kept + warned, never destroyed. Legacy .brain-queue.jsonl migrates atomically on the next drain (crash-leftover .migrating files recovered too); status/drop-queue count both surfaces; discover-new writes spool records and advances its cursor per-record-written. The preamble's queue-depth line switches to spool count in this wave's template block. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(bin-context): native slug fallback walks up like bash gstack-slug slugFromEnvironment derived the slug from the INNERMOST repo's origin while bash gstack-slug walks to the outermost project root — nested/vendored repos split their stores across the bash/native boundary (win32 hits the native path constantly). The native fallback now ports _outermost_project_root faithfully (strong/weak markers, outermost-strong-wins, 64-depth cap, fixed-point termination) plus the full resolution order: env override → walk-up → sticky cache with the #1125 self-heal → remote get-url → basename. Twelve mirrored scenarios drive BOTH implementations against the same fixtures and pin identical slugs. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(next-version): git fallback queries the live remote, never mutates, and keeps 3-digit width The degraded path counted every remote-tracking ref on every remote — stale experiment branches and second remotes inflated version allocation, and a failed base read flipped 3-digit repos to 4-digit slots. Now: ls-remote --heads origin first (GIT_TERMINAL_PROMPT=0, 5s timeout, zero local ref mutation); on failure, local refs/remotes/origin ONLY with an explicit stale-refs warning; a failed base read zeroes at the LOCAL version file's width so a 3-digit repo allocates 0.0.1, not 0.0.1.0. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(setup): hooks register the global-install path and re-point stale ones Registering hooks from a dev worktree baked that worktree's absolute path into settings.json — deleting the worktree left a dead hook erroring on every session stop, and the presence-only dedup (list-sources | grep) could never re-point it. setup's hook paths now route through _hook_install_path (global install preferred, source dir fallback), and the new ensure-event verb on gstack-settings-hook compares the registered command payload against canonical: identical → no write, different → single atomic replacement (never zero or two registrations). The plan-tune hooks had the same stale pattern and get the same fix without re-triggering their consent prompt. Also hardened: bun 1.3.13 turns an uncaught sync fs error in bun -e into a SILENT exit 0 — the registrar's write path now catches, prints, and exits 1, so a failed update can never report fake-green. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(preamble): learnings capture is unconditional at completion (#2402) 43 of 44 learnings entries came from explicit /learn — the completion-status prose read 'if you discovered a durable project quirk... log it', which models treated as optional. The step now ALWAYS runs: review the session for durable learnings, log each one, and state 'No durable learnings this session' explicitly when the review comes up empty — an empty result, never a skipped step. Re-derived from PR #2612 under the generated-file screening rule. Fixes #2402. Contributed by @Lockyer228 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(scrape): untrusted-content warning on the page-fetching skills (#2441) /scrape and /skillify consumed page content with zero injection guidance — the CHANGELOG claimed coverage the skills didn't have. The warning now lives in ONE exported const (UNTRUSTED_CONTENT_WARNING in resolvers/browse.ts), embedded in the browse COMMAND_REFERENCE as before AND injected standalone into both skills via the new {{UNTRUSTED_CONTENT_WARNING}} token — single source, wording can never drift between surfaces. Re-derived from PR #2612 under the generated-file screening rule. (Structural isolation for skillify-generated code is tracked as its own TODO.) Fixes #2441. Contributed by @Lockyer228 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(review): checklist paths resolve from the installed skill root (#2518) /review Step 2 read .claude/skills/review/checklist.md — a path relative to the TARGET repo, which only resolves in gstack's own checkout. Every checklist/greptile-triage/TODOS-format reference (six across five templates — two more than the issue named, same class) now uses the installed-root form ~/.claude/skills/gstack/review/... that the templates' other references already use. The install-root class itself (non-default install dirs) is #1882, deliberately its own PR. Fixes #2518. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(pair-agent): one-way-door consent question before a daemon relaunch (template half) The skill flow now checks daemon liveness before Step 4 and asks an explicit one-way-door question (tabs/cookies/logins are lost) before passing --force-restart — never proceeding on a vague reply. Pairs with the CLI-half commit that stopped pair-agent auto-killing live daemons. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs(codex): resume does not amortize the ~21K session prelude (#2387) Measured (#2387): every codex exec call pays Codex's session prelude, and a resumed call came in slightly ABOVE a fresh one — resume buys continuity, never token savings. The skill now says so where the resume flow lives: prefer one codex call per skill, batch questions into it. Fixes #2387. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(upgrade): fast-forward first; reset --hard only behind a proved-safe gate (#2517) /gstack-upgrade went straight to stash + reset --hard origin/main. Now it tries git pull --ff-only --autostash first (the same policy session-update's auto-upgrade uses). The destructive fallback runs unprompted ONLY when both git status --porcelain AND git rev-list origin/main..HEAD are empty — a clean tree with unpushed local commits is NOT safe, reset destroys them. Anything else requires an explicit one-way-door confirmation that lists every dirty file and unpushed commit being discarded. Fixes #2517. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(preamble): brain-sync block counts the spool queue and resolves MCP project-first Two resolver halves deferred from earlier wave commits: the queue-depth line counts .brain-queue.d/*.json spool records (plus legacy lines until the drain migrates them), and GBRAIN_MCP_ENTRY_JQ swaps its operands to nearest-ancestor-project-first — matching the empirically verified Claude Code precedence (project-local beats user scope) instead of the backwards user-first assumption. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * chore: regenerate SKILL.md docs + golden fixtures (single regen for the template block) Pure generator output for the six template/resolver commits above (learnings capture, untrusted-content warning, review paths, pair-agent consent, codex resume note, upgrade ff-only, brain-sync block) — bun run gen:skill-docs + --host codex + --host factory, with the three ship golden fixtures refreshed per the documented procedure. The three sidecar-path pins in gen-skill-docs.test.ts move to the new installed-root/$GSTACK_ROOT contract (#2518). Restores template freshness; full suite green from here. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * chore: TODOS.md — strike the six wave-fixed residuals, add two follow-ups The v1.67 adversarial-review residuals section shrinks to the one item the wave couldn't reach (iOS tap routing — needs real-device verification). New entries: skillify structural isolation (a prose warning is not a boundary for page-derived generated code) and the slug store migration (pre-fix sessions on stray-marker machines filed data under the degraded slug; post-fix reads go to the correct store, so history needs a merge/alias). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test: align cross-cutting pins with the wave's contracts Three suites pinned pre-wave behavior: browse's gstack-config test asserted the old unknown-key ''/exit-0 shape (#2611 made it exit 1); the Windows-paths suite pinned O_APPEND enqueue atomicity (the spool design satisfies the same invariant via tmp + os.replace, one file per record — pinned in its new form); and nine carve-guard skeleton ceilings absorbed the #2402 unconditional-learnings prose (~450B per skill), bumped with measured values per the guard's own protocol. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test: re-anchor the referenced-path scanner self-check to the gstack-rooted review refs The self-check pinned the review checklist as a class-1 alias-relative ref; #2518 moved those refs to the installed gstack root (class 2). The guard now proves the scanner sees them in their new class, so the class-2 assertion can't go vacuous. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test: pin the wave's prose-tier behaviors (ship coverage-audit gap closure) The coverage audit found one regression-shaped gap: nothing pinned that the upgrade template's ff-only pull precedes the gated reset --hard (#2517) — a future template edit reverting to reset-first would fail nothing. Pinned: the ordering, the FF_OK gate, and the unpushed-commits check. Also pinned the two minor gaps: the {{UNTRUSTED_CONTENT_WARNING}} injection points in scrape/skillify (#2441) and brain-uninstall's spool-dir cleanup. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix: pre-landing review round — 8 auto-fixes + 8 accepted findings hardened The ship review army (4 specialists + red-team + checklist, 29 findings) produced 8 mechanical auto-fixes and 11 decisions; the accepted set: - win32 slug parity completed: lib/bin-context.ts gains the remote-first outermost walk + degraded-cache self-heal the bash side got this wave — the two implementations now agree on the stray-marker live-bug shape, pinned by shared fixtures (multi-specialist 9/10 finding). - probe honors the plan's bounded-read decision: 256KB prefix, extraction semantics mirrored from parseTranscriptJsonl so probe/prepare can never diverge on the same file (>1MB transcript test). - policy normalize parity: bash normalize() now matches canonicalizeRemote on .git/-trailing and uppercase-.GIT shapes (7-shape corpus pinned two ways) — a deny for those shapes could previously slip the transcript gate. - session-update reclaim is TOCTOU-safe (atomic mv-aside on both branches). - settings-hook: unparseable settings.json errors instead of being replaced with {}; ensure-event keys on (event, source) so matcher changes update in place — never zero or two registrations. - dot-only slug guard at both parse sites (hostile 'url = ..' can't escape projects/); enqueue tmp-file janitor (1h TTL, inside the drain lock); brain-sync .migrating never clobbered; drop-queue/status count .migrating; snapshot -o warning correct + surfaced in diff mode; version-bump test order-dependence removed; uninstall clears the advance stamp. Deferred with record: slug heal-probe cost sentinel (P3 TODO), FF_OK conflation (noted, misdiagnosis-only). 270 pass / 0 fail across the 10 touched suites. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix: adversarial round — the P0 finalize fail-safe and 12 hardened findings Three adversarial passes (Claude fresh-context, Codex chaos, Codex structured with P1 gate) on the full wave diff. Multi-source findings, all fixed: - P0: finalize_queue is now explicit-delete-only — a record is unlinked ONLY when classification proves it staged or dropped; a classifier crash, a missing class file, or a malformed pulled .brain-privacy-map.json (which previously nuked the whole snapshotted queue, remotely triggerable) now retains everything, warns, and re-drains next run. load_privacy_map treats corrupt maps as retain-all, never as empty. - next-version cannot silently drop a live claim: unreadable advertised refs get a targeted --depth=1 fetch + retry; still-unreadable claims surface as UNKNOWN warnings instead of duplicate-version silence. - session-update lock: ownership-checked EXIT trap (a TTL-reclaimed holder can no longer delete the new holder's lock) + a 5-min background heartbeat so a legitimately-slow pull/setup is never reclaimed while alive. - ensure-event collapses ALL same-(event,source) duplicates to one canonical entry; unique per-process tmp path; setup call sites surface (not swallow) the hardened refusals. - memory-ingest: --limit counts only policy-permitted pages (denied records no longer starve permitted ones); --probe applies the same policy filter as --bulk (skipped_policy_* fields on the report). - version-bump repair accepts a genuine literal 0.0.0.0 VERSION file. - slug heal restricted to the stray-.git shape — package.json-anchored wrapper roots keep their legit sticky identity (#2212 preserved). - brain-sync: idle fast path sees leftover .migrating records; unparseable spool records quarantine instead of warning forever; migration comment stops overclaiming the transition-window race. - CDP throttling justifications document override persistence (callers own restoration), pinned in the allowlist test. Deferred with record: deny retroactivity for already-ingested pages (P2 TODO, same semantics as the code-import gate); legacy-migration tail race (transition-window, requires pre-spool writers). 288 pass / 0 fail across the 10 touched suites. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * chore: regenerate SKILL.md docs + goldens (Windows-separator jq fix) Pure generator output for the brain-sync block's jq ancestor match now accepting backslash-formed Windows project keys — previously project-scoped brains were invisible on Windows while the TS scope resolvers saw them. Golden ship fixtures refreshed per the documented procedure. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix: codex verify-pass residuals — chunked cwd read, post-filter partial count, migrating depth The verify re-review passed the P1 gate (0 P1s) and left three residuals, all applied: transcriptCwdFromPrefix reads in chunks until one complete record (4MB cap) so a giant first prompt can't truncate mid-JSON and break probe/bulk parity; partial_pages derives from the FINAL prepared set instead of the whole scanned corpus; the preamble queue-depth line counts leftover .brain-queue.jsonl.migrating records like the status path does (regen + goldens included). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * chore: bump version and changelog (v1.68.0.0) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: update project documentation for v1.68.0.0 BROWSER.md: fix the $B cdp example (positional JSON params, not --json; depth is the real CDP param) and add the new perf-throttling examples (Emulation.setCPUThrottlingRate, Network.emulateNetworkConditions) with their clear-override counterparts. USING_GBRAIN_WITH_GSTACK.md: the state-files table row for the sync queue now names the maildir-style spool dir .brain-queue.d/ that replaced .brain-queue.jsonl this release. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test: align memory-pipeline probe pins with the #2394 stage-count contract The paid-tier E2E pinned the pre-fix contract (probe headline = raw discovered). Probe now counts post-attribution — the same gate --bulk uses — with an explicit unattributed-skip line. Adds the --include-unattributed companion pin so all 9 fixtures stay accounted for. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(next-version): batch missing-tip fetches — one bounded round trip, never a per-branch crawl The targeted-fetch retry for branches whose advertised tip has no local object ran ONE git fetch per branch (10s cap each). On a shallow clone against a busy remote that crawls the network for minutes — CI's shard deadline killed the free suite mid-file. Missing tips now collect into a single batched shallow fetch (15s cap); refs still missing after the batch (one unservable ref fails the whole transfer) get a capped per-branch retry, and anything past the cap warns as an UNKNOWN claim instead of fetching. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(next-version): pin the batched fetch + make the offline-contract tests hermetic Two new G2 pins: N unfetched claim branches resolve with exactly ONE fetch spawn (PATH-shimmed git counts invocations), and one unservable ref no longer poisons the batch — live claims resolve via the bounded retry while only the ghost warns UNKNOWN. The #2545 offline-contract tests now run the CLI in a local fixture repo instead of the repo's own checkout: the checkout path did a live ls-remote against the real origin (operator-network-dependent, and the CI shard-deadline hang). The online-contract test gains a succeeding gh stub, so fallback:null is asserted deterministically instead of only when the operator happens to be authed. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(redact-cli): derive the synthetic AWS-key fixture — no contiguous credential literal in source The CI quality gate scans every ADDED diff line with the redact engine, so the #2610 port's raw fixture literals failed the very gate they exist to test. The fixture is now assembled at runtime; the scanner still receives the identical bytes. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(next-version): pin the fixture's host via origin-URL sniff — kills the last environment dependence The hermetic offline-contract fixture had no origin remote, so detectHost() fell through to auth probes: a machine with glab authed passed via the gitlab path while a bare CI runner read host:unknown (offline stays false there) and failed. The fixture now pushes to a local bare origin at a path containing github.com — the URL sniff pins host:github identically everywhere, asserted explicitly in both tests, with every git call still local. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: y$un_ <forrest.sun527@gmail.com> Co-authored-by: Cursor <cursoragent@cursor.com> Co-authored-by: benjamin beres <benjamin.beres@bienpreter.com> Co-authored-by: Claude Opus 5 <noreply@anthropic.com> Co-authored-by: Ricky <ricky@kinokostudio.com.hk> Co-authored-by: Connex Client Access <paul@paulkortman.com> Co-authored-by: henbima <henbima@gmail.com>
30 KiB
Using GBrain with GStack
Your coding agent, with a memory it actually keeps.
GBrain is a persistent knowledge base designed for AI agents. It stores what your agent learns, what you've decided, what worked and what didn't, and lets the agent search all of it on demand. GStack gives you a one-command path from zero to "gbrain is running, and my agent can call it" — with paths for try-it-local, share-with-your-team, and everything between.
This is the full monty: every scenario, every flag, every helper bin, every troubleshooting step. For the quick pitch, see the README's GBrain section. For error codes and sync-specific issues, see docs/gbrain-sync.md.
The one-command install
/setup-gbrain
That's it. The skill detects your current state, asks three questions at most, and walks you through install, init, MCP registration for Claude Code, and per-repo trust policy. On a clean Mac with nothing installed it finishes in under five minutes. On a Mac where something's already set up it takes seconds (it detects the existing state and skips done work).
What you get after setup
Once /setup-gbrain finishes, your coding agent has two retrieval surfaces it didn't have before:
- Semantic code search across this repo.
gbrain search "browser security canary"returns ranked file regions, not exact-match grep hits.gbrain code-def,code-refs,code-callers,code-calleeswalk the call graph by symbol — useful when you don't know which file holds the implementation but you know what it does. The agent prefers these over Grep when the question is semantic; CLAUDE.md gets a## GBrain Search Guidanceblock that teaches it the routing rules. - Cross-session memory. Plans, retros, decisions, and learnings from past sessions live in
~/.gstack/and (if you opted in to artifacts sync) get pushed to a private git repo that gbrain indexes.gbrain search "what did we decide about auth?"actually finds the prior CEO plan instead of you re-describing context every session.
If you also enabled remote MCP (Path 4 below), brain queries route to a shared brain server that other machines can write to — your laptop, your desktop, and a teammate's machine all see the same memory.
The four paths
You pick one when the skill asks "Where should your brain live?"
Path 1: Supabase, you already have a connection string
Best for: you (or a teammate's cloud agent) already provisioned a Supabase brain and you want this local machine to use the same data.
What happens: Paste the Session Pooler URL (Settings → Database → Connection Pooler → Session → copy URI, port 6543). The skill reads it with echo off, shows you a redacted preview (aws-0-us-east-1.pooler.supabase.com:6543/postgres — host visible, password masked), hands it to gbrain init via the GBRAIN_DATABASE_URL environment variable, and the URL is never written to argv or your shell history.
Trust warning: Pasting this URL gives your local Claude Code full read/write access to every page in the shared brain. If that's not the trust level you want, pick PGLite local (Path 3) instead and accept the brains are disjoint.
Path 2a: Supabase, auto-provision a new project
Best for: fresh Supabase account, you want a clean new project with zero clicking.
What happens: You paste a Supabase Personal Access Token (PAT). The skill shows you the scope disclosure first — the token grants full access to every project in your Supabase account, not just the one we're about to create. It lists your organizations, asks which one and which region (default us-east-1), generates a database password, calls POST /v1/projects, polls GET /v1/projects/{ref} every 5 seconds until the project is ACTIVE_HEALTHY (180s timeout), fetches the pooler URL, hands it to gbrain init. End-to-end: ~90 seconds.
At the end: explicit reminder to revoke the PAT at https://supabase.com/dashboard/account/tokens. The skill already discarded it from memory.
If you Ctrl-C mid-provision: The SIGINT trap prints your in-flight project ref + a resume command. You can delete the orphan at the Supabase dashboard, or run /setup-gbrain --resume-provision <ref> to pick up where you left off.
Path 2b: Supabase, create manually
Best for: you'd rather click through supabase.com yourself than paste a PAT.
What happens: The skill walks you through the four manual steps (signup → new project → wait ~2 min → copy Session Pooler URL), then takes over from Path 1's paste step. Same security treatment as Path 1.
Path 3: PGLite local
Best for: try-it-first, no account, no cloud, no sharing. Or a dedicated "this Mac's brain" that stays isolated from any cloud agent.
What happens: gbrain init --pglite. Brain lives at ~/.gbrain/brain.pglite. No network calls for the init itself. Done in 30 seconds.
Embedding model. When VOYAGE_API_KEY is set, gstack inits PGLite with voyage-code-3 (1024-dim) — Voyage's code-specialized embedding model, which beats their general-purpose voyage-4-large and OpenAI text-embedding-3-large head-to-head on this codebase's symbol queries. Without VOYAGE_API_KEY, gbrain auto-selects (OpenAI 1536-dim when OPENAI_API_KEY is present, else falls down its provider chain). Either way, the embeddings call out to the chosen provider's API during sync — set the key for the provider you want before running /sync-gbrain.
This is the best first choice if you just want to see what gbrain feels like before committing to cloud. You can always migrate later with /setup-gbrain --switch.
Path 4: Remote gbrain MCP (split-engine)
Best for: your brain runs on another machine you control (Tailscale, ngrok, internal LAN) or a teammate's server. You want the cross-machine memory benefit without standing up a local database, and you still want symbol-aware code search on this Mac.
What happens: You paste an MCP URL (e.g. https://wintermute.tail554574.ts.net:3131/mcp) and a bearer token. The skill verifies the URL over the wire, registers gbrain as an HTTP MCP in ~/.claude.json at user scope, and offers to also stand up a tiny local PGLite for code search (~30 seconds, ~120 MB disk).
If you accept the local PGLite, you end up in split-engine mode:
- Brain/context queries (
mcp__gbrain__search,mcp__gbrain__query,mcp__gbrain__get_page) route to the remote MCP. Plans, retros, learnings, cross-machine memory — all on the shared server. - Code queries (
gbrain code-def,code-refs,code-callers,code-callees,gbrain searchfor code) route to the local PGLite via the.gbrain-sourcepin in each worktree. Indexed locally, fast, never leaves the machine.
The two engines are independent. Wiping the local PGLite doesn't touch the remote brain; rotating the remote MCP bearer doesn't affect local code search. This is also the right configuration if your remote brain admin can't (or shouldn't) index every developer's checkout — local code stays local.
MCP registration for Claude Code
By default the skill asks "Give Claude Code a typed tool surface for gbrain?" If you say yes, it runs:
claude mcp add gbrain -- gbrain serve
That registers gbrain's stdio MCP server with Claude Code. Now gbrain search, gbrain put, gbrain get, etc. show up as first-class tools in every session, not bash shell-outs.
If claude is not on PATH, the skill skips MCP registration gracefully with a manual-register hint. The CLI resolver still works from any skill that shells out to gbrain — MCP is an upgrade, not a prerequisite.
Other local agents (Cursor, Codex CLI, etc.) need their own MCP registration. The skill is Claude-Code-targeted for v1; other hosts can register gbrain serve manually in their own MCP config.
Per-remote trust policy (the triad)
Every repo on your machine gets a policy decision: read-write, read-only, or deny.
- read-write — your agent can
gbrain searchfrom this repo's context AND write new pages back to the brain. Default for your own projects. - read-only — your agent can search the brain but never writes new pages from this repo's sessions. Ideal for multi-client consultants: search the shared brain, don't contaminate it with Client A's code while you're in Client B's repo.
- deny — no gbrain interaction at all. The repo is invisible to gbrain tooling.
The skill asks once per repo the first time you run a gstack skill there. After that the decision is sticky — every worktree + branch of the same git remote shares the same policy, so you set it once and it follows you.
SSH and HTTPS remote variants collapse to the same key: https://github.com/foo/bar.git and git@github.com:foo/bar.git are the same repo.
To change a policy:
/setup-gbrain --repo # re-prompt for this repo only
# Or directly:
~/.claude/skills/gstack/bin/gstack-gbrain-repo-policy set "github.com/foo/bar" read-only
To see every policy:
~/.claude/skills/gstack/bin/gstack-gbrain-repo-policy list
Storage: ~/.gstack/gbrain-repo-policy.json, mode 0600, schema-versioned so future migrations stay deterministic.
Keeping the brain current with /sync-gbrain
/setup-gbrain is one-time onboarding. /sync-gbrain is the verb you run every time you want gbrain to see fresh changes in this repo's code.
/sync-gbrain # incremental: mtime fast-path, ~seconds on a clean tree
/sync-gbrain --full # full reindex (~25-35 minutes on a big Mac)
/sync-gbrain --code-only # only the code stage; skip memory + brain-sync
/sync-gbrain --dry-run # preview what would sync; no writes
The skill runs three stages — code, memory, brain-sync — independently. A failure in one doesn't block the others. State persists to ~/.gstack/.gbrain-sync-state.json so re-running picks up cleanly.
Stages that can send data off-machine (code sync into a possibly-remote gbrain DB, memory ingest, the brain-sync push) each write a tamper-evident receipt to the egress ledger (~/.gstack/security/egress.jsonl) before sending, fail-closed: if the receipt can't be written, the stage refuses with EGRESS_RECEIPT_FAILED instead of syncing unrecorded. Fix is usually mkdir -p ~/.gstack/security && chmod -R u+w ~/.gstack/security, then re-run. Inspect receipts with gstack-egress list.
What it does on a fresh worktree:
- Pre-flight. Checks
gbrain_local_status(the local engine's health). If the engine isbroken-dborbroken-config, the skill STOPs with a remediation menu — it refuses to silently degrade. If the local engine is missing and you're in remote-MCP mode (Path 4), the code stage SKIPs cleanly and only brain-sync runs. - Code stage. Registers the cwd as a federated source via
gbrain sources add, writes a.gbrain-sourcepin file in the repo root (kubectl-style context — every worktree gets its own pin, so Conductor sibling worktrees don't collide), runsgbrain sync --strategy code. - Memory stage. Stages your
~/.gstack/transcripts + curated memory. In local-stdio MCP mode, ingests into the local engine. In remote-http MCP mode, persists staged markdown to~/.gstack/transcripts/run-<pid>-<ts>/for the remote brain admin's pull pipeline. The ingest timeout is 30 minutes by default; raise it for a big brain withGSTACK_INGEST_TIMEOUT_MS(accepts 1 min–24h). On timeout the gbrain import checkpoint is preserved, so the next/sync-gbrainresumes instead of starting over. - Brain-sync stage. Pushes curated artifacts (plans, designs, retros) to your private artifacts repo if you have one configured.
- CLAUDE.md guidance. Capability-checks the round-trip (write a page → search → find it). If green, writes the
## GBrain Search Guidanceblock to your project's CLAUDE.md. If red, REMOVES the block — the agent should never be told to use a tool that isn't installed.
The watermark. Sync state advances by commit hash. If gbrain hits a file it can't index (5 MB hard limit per file, or a file vanished mid-sync), the watermark stays put and subsequent syncs retry. To acknowledge an unfixable failure and move past it:
gbrain sync --source <source-id> --skip-failed
Re-runnable, idempotent, safe to run from multiple terminals on the same machine (locked at ~/.gstack/.sync-gbrain.lock).
Switching engines later
Picked PGLite and now want to join a team brain? One command:
/setup-gbrain --switch
The skill runs gbrain migrate --to supabase --url "$URL" wrapped in timeout 180s. Migration is bidirectional (Supabase → PGLite also works) and lossless — pages, chunks, embeddings, links, tags, and timeline all copy. Your original brain is preserved as a backup.
If migration hangs: another gstack session may be holding a lock on the source brain. The timeout fires at 3 minutes with an actionable message. Close other workspaces and re-run.
GStack memory sync (a separate concern)
This is different from gbrain itself. Your gstack state (~/.gstack/ — learnings, plans, retros, timeline, developer profile) is machine-local by default. "GStack memory sync" optionally pushes a curated, secret-scanned subset to a private git repo so your memory follows you across machines — and, if you're running gbrain, that git repo becomes indexable there too.
Turn it on with:
gstack-artifacts-init
You'll get a one-time privacy prompt: everything allowlisted / artifacts only (plans, designs, retros, learnings — skip behavioral data like timelines) / off. Every skill run syncs the queue at start and end — no daemon, no background process.
Secret-shaped content (AWS keys, GitHub tokens, PEM blocks, JWTs, bearer tokens) is blocked from sync before it leaves your machine.
On a new machine: Copy ~/.gstack-artifacts-remote.txt over (the legacy
~/.gstack-brain-remote.txt name still works), run gstack-brain-restore, and
yesterday's learnings surface on today's laptop.
Full guide: docs/gbrain-sync.md. Error index: docs/gbrain-sync-errors.md.
/setup-gbrain offers to wire this up for you at the end of initial setup — it's one more AskUserQuestion, and it integrates with the same private-repo infrastructure.
Cleanup orphan projects
If you Ctrl-C'd mid-provision, tried three different names before settling on one, or otherwise accumulated gbrain-shaped Supabase projects you don't use, there's a subcommand for that:
/setup-gbrain --cleanup-orphans
The skill re-collects a PAT (one-time, discarded after), lists every project in your Supabase account whose name starts with gbrain and whose ref doesn't match your active ~/.gbrain/config.json pooler URL. For each orphan it asks per-project: "Delete orphan project <ref> (<name>, created <date>)?" — no batching, no "delete all" shortcut. The active brain is never offered for deletion.
Command + flag reference
/setup-gbrain entry modes
| Invocation | What it does |
|---|---|
/setup-gbrain |
Full flow: detect state, pick path, install, init, MCP, policy, optional memory-sync |
/setup-gbrain --repo |
Flip the per-remote trust policy for the current repo only |
/setup-gbrain --switch |
Migrate engine (PGLite ↔ Supabase) without re-running the other steps |
/setup-gbrain --resume-provision <ref> |
Resume a path-2a auto-provision that was interrupted during polling |
/setup-gbrain --cleanup-orphans |
List + per-project delete of orphan Supabase projects |
Bin helpers (for scripting)
| Bin | Purpose |
|---|---|
gstack-gbrain-detect |
Emit current state as JSON: gbrain on PATH, version, config engine, doctor status, sync mode |
gstack-gbrain-install |
Detect-first installer (probes ~/git/gbrain, ~/gbrain, then fresh clone). Has --dry-run and --validate-only flags. PATH-shadow check exits 3 with remediation menu. |
gstack-gbrain-lib.sh |
Sourced, not executed. Provides read_secret_to_env VARNAME "prompt" [--echo-redacted "<sed-expr>"] |
gstack-gbrain-supabase-verify |
Structural URL check. Rejects direct-connection URLs (db.*.supabase.co:5432) with exit 3 |
gstack-gbrain-supabase-provision |
Management API wrapper. Subcommands: list-orgs, create, wait, pooler-url, list-orphans, delete-project. All require SUPABASE_ACCESS_TOKEN in env. create and pooler-url also require DB_PASS. --json mode available on every subcommand. |
gstack-gbrain-repo-policy |
Per-remote trust triad. Subcommands: get, set, list, normalize |
gstack-gbrain-source-wireup |
Registers your ~/.gstack/ brain repo with gbrain as a federated source via gbrain sources add + git worktree, then runs an initial gbrain sync. Idempotent. Replaces the dead consumers.json + /ingest-repo HTTP wireup from v1.12.x. Flags: --strict, --source-id <id>, --no-pull, --uninstall, --probe. |
gbrain CLI (upstream tool)
Gbrain itself ships with these that gstack wraps:
| Command | Purpose |
|---|---|
gbrain init --pglite |
Initialize a local PGLite brain |
gbrain init --non-interactive |
Initialize via env (GBRAIN_DATABASE_URL or DATABASE_URL). Never pass a URL as argv — it'll leak to shell history. |
gbrain doctor --json |
Health check. Returns `{status: "ok" |
gbrain migrate --to supabase --url ... |
Move a PGLite brain to Supabase (lossless, preserves source as backup) |
gbrain migrate --to pglite |
Reverse migration |
gbrain search "query" |
Search the brain |
gbrain put "<slug>" --content "<markdown-with-frontmatter>" |
Write a page (title/tags go in YAML frontmatter inside --content) |
gbrain get "<slug>" |
Fetch a page |
gbrain serve |
Start the MCP stdio server (used by claude mcp add) |
Config files + state
| Path | What lives there |
|---|---|
~/.gbrain/config.json |
Engine (pglite/postgres), database URL or path, API keys. Mode 0600. Written by gbrain init. |
~/.gstack/gbrain-repo-policy.json |
Per-remote trust triad. Schema v2. Mode 0600. |
~/.gstack/.setup-gbrain.lock.d |
Concurrent-run lock (atomic mkdir). Released on normal exit + SIGINT. |
~/.gstack/.brain-queue.d/ |
Pending sync records for gstack memory sync — maildir-style spool, one file per record. A legacy .brain-queue.jsonl from older releases migrates automatically on the next drain. |
~/.gstack/.brain-last-push |
Timestamp of last sync push (for /health scoring) |
~/.gstack-artifacts-remote.txt |
URL of your gstack memory sync remote (safe to copy between machines; legacy name ~/.gstack-brain-remote.txt still read) |
~/.gstack/.setup-gbrain-inflight.json |
Reserved for future --resume-provision persisted state |
Environment variables
| Var | Where it's read | What it does |
|---|---|---|
SUPABASE_ACCESS_TOKEN |
gstack-gbrain-supabase-provision |
PAT for Management API calls. Discarded after each setup run. |
DB_PASS |
gstack-gbrain-supabase-provision (create, pooler-url) |
Generated DB password. Never in argv. |
GBRAIN_DATABASE_URL |
gbrain init, gbrain doctor, etc. |
Postgres connection string (Supabase pooler URL for us). Env takes precedence over ~/.gbrain/config.json. |
DATABASE_URL |
gbrain init (fallback) |
Same semantics as GBRAIN_DATABASE_URL; checked second. |
SUPABASE_API_BASE |
gstack-gbrain-supabase-provision |
Override the Management API host. Used by tests to point at a mock server. |
GBRAIN_INSTALL_DIR |
gstack-gbrain-install |
Override default install path (~/gbrain) |
GSTACK_HOME |
every bin helper | Override ~/.gstack state dir. Heavy test use. |
VOYAGE_API_KEY |
gbrain embed subprocess; gstack PGLite init |
When set, gstack inits PGLite with voyage-code-3 (1024-dim), Voyage's code-specialized embedding model. Beats voyage-4-large and OpenAI text-embedding-3-large head-to-head on this codebase's symbol queries. See CHANGELOG v1.43.1.0 for the A/B numbers. |
OPENAI_API_KEY |
gbrain embed subprocess |
Used for embeddings during gbrain sync / /sync-gbrain when VOYAGE_API_KEY is not set (gbrain's auto-selected fallback, text-embedding-3-large 1536-dim). Without either key, pages are imported structurally (symbol tables, chunks) but semantic search degrades — you'll see [gbrain] embedding failed for code file ... in the sync log. |
ANTHROPIC_API_KEY |
claude-agent-sdk, paid evals |
Required for bun run test:evals and any direct query() call against Claude. |
GSTACK_OPENAI_API_KEY |
lib/conductor-env-shim.ts |
Conductor-injected fallback. Promoted to OPENAI_API_KEY when the canonical name is empty. |
GSTACK_ANTHROPIC_API_KEY |
lib/conductor-env-shim.ts |
Same pattern as above for Anthropic. |
Conductor + GSTACK_* env vars
If you run gstack inside a Conductor workspace, Conductor explicitly strips ANTHROPIC_API_KEY and OPENAI_API_KEY from the workspace env. Setting them in ~/.zshrc or .env won't help — the strip happens after env inheritance. To get a usable API key into a workspace, set GSTACK_ANTHROPIC_API_KEY and GSTACK_OPENAI_API_KEY in Conductor's workspace env config instead. Conductor passes those through untouched.
lib/conductor-env-shim.ts bridges the gap on the gstack side: when imported as a side effect (import "../lib/conductor-env-shim";), it promotes GSTACK_FOO_API_KEY to FOO_API_KEY for any subprocess that doesn't see the canonical name. The shim is already wired into:
bin/gstack-gbrain-sync.ts— so/sync-gbrainpicks up OpenAI for embeddingsbin/gstack-model-benchmark— so--judgeruns work without manual env mappingscripts/preflight-agent-sdk.ts— so paid-eval auth probes worktest/helpers/e2e-helpers.ts— sobun run test:evalsfinds Anthropic
If you add a new TS entry point that hits a paid API or needs gbrain embeddings, add the same one-line import at the top. See CONTRIBUTING.md "Conductor workspaces" for the contributor checklist.
bin/gstack-codex-probe is bash and doesn't read these directly — it relies on ~/.codex/ auth managed by the Codex CLI.
Security model
One rule for every secret this skill touches: env var only, never argv, never logged, never written to disk by us. The only persistent storage is gbrain's own ~/.gbrain/config.json at mode 0600, which is gbrain's discipline, not ours.
Enforced in code:
- CI grep test in
test/skill-validation.test.tsfails the build if$SUPABASE_ACCESS_TOKENor$GBRAIN_DATABASE_URLappears in an argv position - CI grep test fails if
--insecure,-k, orNODE_TLS_REJECT_UNAUTHORIZED=0appear inbin/gstack-gbrain-supabase-provision set +xat the top of the provision helper prevents debug tracing from leaking PAT- Telemetry payload contains only enumerated categorical values (scenario, install result, MCP opt-in, trust tier) — never free-form strings that could contain secrets
Enforced via tests:
test/secret-sink-harness.test.tsruns every secret-handling bin with a seeded secret and asserts the seed never appears in any captured channel (stdout, stderr, files under$HOME, telemetry JSONL). Four match rules per seed: exact, URL-decoded, first-12-char prefix, base64.- Positive controls in the same test file deliberately leak seeds in every covered channel and assert the harness catches each one. Without the positive controls, a harness that silently under-reports would look identical to a working harness.
What you can still leak (the honest limits of v1):
- If you paste a secret into a normal chat message outside
read -s, it's in the conversation transcript and any host-side logging - The leak harness doesn't dump subprocess environment — a bin that
env >> ~/.logwould evade detection (no bin in v1 does this; grep tests prevent it) - Your shell's own
HISTFILEbehavior is your shell's, not ours — we never pass secrets to argv so they don't land there via our code, but nothing stops you from pasting one into a rawcurlcommand yourself
Troubleshooting
"PATH SHADOWING DETECTED" during install
Another gbrain binary is earlier in PATH than the one the installer just linked. The installer's version check caught it. Fix one of:
rm $(which gbrain)if you don't need the other one- Prepend
~/.bun/binto PATH in your shell rc so the linked binary wins - Set
GBRAIN_INSTALL_DIRto the shadowing binary's install directory and re-run
Then re-run /setup-gbrain.
"rejected direct-connection URL"
You pasted a db.<ref>.supabase.co:5432 URL. Those are IPv6-only and fail in most environments. Use the Session Pooler URL instead: Supabase dashboard → Settings → Database → Connection Pooler → Session → copy URI (port 6543).
Auto-provision times out at 180s
The Supabase project is still initializing. Your ref was printed in the exit message. Wait a minute, then:
/setup-gbrain --resume-provision <ref>
The skill re-collects a PAT, skips project creation, resumes polling.
"Another /setup-gbrain instance is running"
You have a stale lock directory. If you're sure no other instance is actually running:
rm -rf ~/.gstack/.setup-gbrain.lock.d
Then re-run.
"No cross-model tension" on policy file
You edited ~/.gstack/gbrain-repo-policy.json by hand with legacy allow values? No problem. On the next read, gstack auto-migrates allow → read-write and adds _schema_version: 2. One log line on stderr, idempotent, deterministic.
gbrain doctor says "warnings"
/health treats that as yellow, not red. Check gbrain doctor --json | jq .checks to see which sub-checks are warning. Typical causes: resolver MECE overlap (skill names clashing) or DB connection not yet configured.
/sync-gbrain reports OK but gbrain search returns nothing semantic
Embeddings probably failed during import. Symbol queries (code-def, code-refs) still work because they don't need embeddings, but gbrain search "<terms>" falls back to a degraded BM25 path. Look in the sync output for lines like:
[gbrain] embedding failed for code file <name>: OpenAI embedding requires OPENAI_API_KEY
The fix is to put a provider API key in the process env before re-running. VOYAGE_API_KEY is preferred for code (gstack defaults PGLite to voyage-code-3 when set); otherwise OPENAI_API_KEY falls back to text-embedding-3-large. On a bare Mac shell, source the key from ~/.zshrc before calling. In Conductor, the lib/conductor-env-shim.ts shim promotes GSTACK_ANTHROPIC_API_KEY / GSTACK_OPENAI_API_KEY to their canonical names automatically; for VOYAGE_API_KEY, set it directly in your Conductor workspace env. Re-run /sync-gbrain --code-only to backfill embeddings on already-imported pages.
gbrain sync blocked at a commit hash — FILE_TOO_LARGE
A file in your tree exceeds gbrain's 5 MB hard limit (MAX_FILE_SIZE in gbrain/src/core/import-file.ts). Common culprits: response replay caches, captured screenshots, large JSON fixtures. Gbrain doesn't honor .gitignore-style exclude lists for code sync; the only knob is acknowledging the failure:
gbrain sync --source <source-id> --skip-failed
Watermark advances past the offending commit. The same file fails again if it changes; re-skip when that happens.
Switching PGLite → Supabase hangs
Another gstack session in a sibling Conductor workspace may be holding a lock on your local PGLite file via its preamble's gstack-brain-sync call. Close other workspaces, re-run /setup-gbrain --switch. The timeout is bounded at 180s so you'll never actually wait forever.
Why this design
Why per-remote trust triad and not binary allow/deny? Multi-client consultants need search without write-back. A freelance dev working on Client A in the morning and Client B in the afternoon can't let A's code insights leak into a brain Client B can search. Read-only solves that cleanly.
Why not bundle gbrain into gstack? Gbrain is a separate, actively-developed project with its own release cadence, schema migrations, and MCP surface. Bundling would mean gstack has to gate gbrain updates, which slows gbrain improvements from reaching users. Separate-but-integrated lets each ship on its own cadence.
Why gbrain init --non-interactive via env var and not a flag? Connection strings contain database passwords. Passing them as argv lands the password in ps, shell history, and process listings. Env-var handoff keeps the secret in process memory only. Gbrain supports both GBRAIN_DATABASE_URL and DATABASE_URL; we use the former to avoid collisions with non-gbrain tooling.
Why fail-hard on PATH shadowing instead of warn-and-continue? A shadowed gbrain means every subsequent command calls a different binary than the one we just installed. That's a silent version-drift bug that surfaces as mysterious feature gaps weeks later. Setup skills have one job — set up a working environment. Refusing to install into a broken one is the setup-skill-correct behavior.
Why not auto-import every repo? Privacy + noise. An auto-import preamble hook that ingests every repo you touch would: (a) leak work code into a shared brain without consent, and (b) clog search with throwaway repos. The per-remote policy makes ingestion an explicit, per-repo decision. /setup-gbrain doesn't install any auto-import hook today — but the policy store is forward-compatible for one later.
Related skills + next steps
/health— includes a GBrain dimension (doctor status, sync queue depth, last-push age) in its 0-10 composite score. The dimension is omitted when gbrain isn't installed; running/healthon a non-gbrain machine doesn't penalize that choice./gstack-upgrade— keeps gstack itself up to date. Does NOT upgrade gbrain independently. gbrain installs at the latest HEAD by default; to refresh it,git pullin your gbrain clone (default~/gbrain) and re-run/setup-gbrain. Pin a specific commit withgstack-gbrain-install --pinned-commit <sha>if you need reproducibility. Installs below the minimum tested version are refused./retro— weekly retrospective pulls learnings and plans from your gbrain when memory sync is on, letting the retro reference cross-machine history.
Run /setup-gbrain and see what sticks.