fix(gbrain-sync): centralize gbrain spawn surface + seed DATABASE_URL

Cherry-picked from #1508 by jasshultz, restructured per codex review #4
and #7 to widen scope and centralize the spawn surface.

The bug: gbrain auto-loads .env.local from cwd via dotenv. When
/sync-gbrain runs inside a Next.js / Prisma / Rails project whose
.env.local defines its own DATABASE_URL (pointing at the app's local
DB), gbrain reads that value instead of its own
~/.gbrain/config.json — auth fails, code + memory stages crash.

This commit:

- Adds lib/gbrain-exec.ts: buildGbrainEnv, spawnGbrain, execGbrainJson,
  execGbrainText, spawnGbrainAsync (the last one for memory-ingest's
  streaming gbrain import call). buildGbrainEnv seeds DATABASE_URL from
  ${GBRAIN_HOME:-$HOME/.gbrain}/config.json, returns a fresh env object
  (never the caller's by identity — codex review #11), and honors the
  GSTACK_RESPECT_ENV_DATABASE_URL=1 escape hatch.

- Routes every gbrain spawn in bin/gstack-gbrain-sync.ts and
  bin/gstack-memory-ingest.ts through the helpers. Both files now own
  zero direct spawnSync("gbrain"|spawn("gbrain"|execFileSync("gbrain"
  call sites.

- Threads buildGbrainEnv into the spawnSync("bun", [memory-ingest], ...)
  grandchild in runMemoryIngest (codex review #7). Without this, the
  parent fix is half-baked — the bun child inherits a clean env but
  needs DATABASE_URL pre-seeded too. spawnGbrainAsync inside
  memory-ingest provides defense in depth for standalone invocations.

- Adds GBRAIN_HOME support — aligns with detectEngineTier (already
  honors GBRAIN_HOME) so all gstack-side gbrain calls agree on which
  config file matters. Resolves baseEnv.HOME first, then homedir(), so
  test injection works without process-wide HOME mutation.

- Adds test/build-gbrain-env.test.ts: 10 unit tests covering all five
  env-seeding branches (seed from config / override caller /
  GSTACK_RESPECT escape hatch / missing config / unparseable config /
  no database_url field / GBRAIN_HOME path / object-identity guard /
  unrelated-vars preservation / idempotent-when-matches).

- Adds test/gbrain-exec-invariant.test.ts: static-source check that
  greps both bin/gstack-gbrain-sync.ts and bin/gstack-memory-ingest.ts
  for direct spawnSync("gbrain"|spawn("gbrain"|execFileSync("gbrain"|
  execSync(...gbrain matches and fails the build if any are found.
  Refactor-proof against future contributors adding a new gbrain spawn
  without env threading.

The invariant is intentionally narrow — only the two files where the
DATABASE_URL bug actually hurts users are guarded. Migrating the
spawn sites in lib/gbrain-local-status.ts, lib/gstack-memory-helpers.ts,
and bin/gstack-brain-context-load.ts is a follow-up.

Co-Authored-By: Jason Shultz <jasshultz@gmail.com>
Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Garry Tan
2026-05-16 14:05:24 -07:00
parent f8e4291521
commit 0fb7fa6c1e
6 changed files with 420 additions and 52 deletions
+120
View File
@@ -0,0 +1,120 @@
/**
* Unit tests for `buildGbrainEnv` in lib/gbrain-exec.ts.
*
* The helper is the single source of truth for "what DATABASE_URL does
* gbrain see when spawned from gstack." The bug it prevents: gbrain's
* dotenv autoload pulls a host project's `.env.local` `DATABASE_URL`
* instead of gbrain's own `~/.gbrain/config.json`. Every helper test
* asserts on the **effective value** of the returned env, never object
* identity — Codex review #11 flagged that returning the same mutable
* object can leak later mutation.
*/
import { describe, it, expect, beforeEach, afterEach } from "bun:test";
import { mkdtempSync, writeFileSync, mkdirSync, rmSync } from "fs";
import { tmpdir } from "os";
import { join } from "path";
import { buildGbrainEnv } from "../lib/gbrain-exec";
describe("buildGbrainEnv", () => {
let home: string;
let gbrainHome: string;
beforeEach(() => {
home = mkdtempSync(join(tmpdir(), "gstack-build-env-"));
gbrainHome = join(home, ".gbrain");
mkdirSync(gbrainHome, { recursive: true });
});
afterEach(() => {
rmSync(home, { recursive: true, force: true });
});
it("seeds DATABASE_URL from ~/.gbrain/config.json when caller env has no DATABASE_URL", () => {
writeFileSync(join(gbrainHome, "config.json"), JSON.stringify({ database_url: "postgresql://gbrain/db" }));
const baseEnv = { HOME: home };
const result = buildGbrainEnv({ baseEnv });
expect(result.DATABASE_URL).toBe("postgresql://gbrain/db");
});
it("overrides caller's DATABASE_URL when config differs", () => {
writeFileSync(join(gbrainHome, "config.json"), JSON.stringify({ database_url: "postgresql://gbrain/db" }));
const baseEnv = { HOME: home, DATABASE_URL: "postgresql://app-local/wrong" };
const result = buildGbrainEnv({ baseEnv });
expect(result.DATABASE_URL).toBe("postgresql://gbrain/db");
});
it("leaves DATABASE_URL untouched when GSTACK_RESPECT_ENV_DATABASE_URL=1", () => {
writeFileSync(join(gbrainHome, "config.json"), JSON.stringify({ database_url: "postgresql://gbrain/db" }));
const baseEnv = {
HOME: home,
DATABASE_URL: "postgresql://intentional/app-db",
GSTACK_RESPECT_ENV_DATABASE_URL: "1",
};
const result = buildGbrainEnv({ baseEnv });
expect(result.DATABASE_URL).toBe("postgresql://intentional/app-db");
});
it("returns caller env unchanged when config file is missing", () => {
// No config.json written.
const baseEnv = { HOME: home, DATABASE_URL: "postgresql://app/db" };
const result = buildGbrainEnv({ baseEnv });
expect(result.DATABASE_URL).toBe("postgresql://app/db");
});
it("returns caller env unchanged when config file is unparseable", () => {
writeFileSync(join(gbrainHome, "config.json"), "{not json");
const baseEnv = { HOME: home, DATABASE_URL: "postgresql://app/db" };
const result = buildGbrainEnv({ baseEnv });
expect(result.DATABASE_URL).toBe("postgresql://app/db");
});
it("returns caller env unchanged when config has no database_url field", () => {
writeFileSync(join(gbrainHome, "config.json"), JSON.stringify({ engine: "pglite" }));
const baseEnv = { HOME: home, DATABASE_URL: "postgresql://app/db" };
const result = buildGbrainEnv({ baseEnv });
expect(result.DATABASE_URL).toBe("postgresql://app/db");
});
it("honors GBRAIN_HOME when set (config aligned with detectEngineTier)", () => {
// Move the config to an alternate dir; set GBRAIN_HOME to point at it.
const altGbrainHome = join(home, "alt-gbrain");
mkdirSync(altGbrainHome, { recursive: true });
writeFileSync(join(altGbrainHome, "config.json"), JSON.stringify({ database_url: "postgresql://alt/db" }));
// No file at the default ~/.gbrain location.
const baseEnv = { HOME: home, GBRAIN_HOME: altGbrainHome };
const result = buildGbrainEnv({ baseEnv });
expect(result.DATABASE_URL).toBe("postgresql://alt/db");
});
it("returns a fresh env object — never the caller's env by identity", () => {
// Codex review #11: object-identity equality lets later mutation of the
// returned env leak back into the caller's view. The helper MUST clone.
writeFileSync(join(gbrainHome, "config.json"), JSON.stringify({ database_url: "postgresql://gbrain/db" }));
const baseEnv: NodeJS.ProcessEnv = { HOME: home, FOO: "bar" };
const result = buildGbrainEnv({ baseEnv });
expect(result).not.toBe(baseEnv);
// Mutating result must not affect baseEnv.
result.FOO = "changed";
expect(baseEnv.FOO).toBe("bar");
});
it("preserves unrelated env vars from the base env", () => {
writeFileSync(join(gbrainHome, "config.json"), JSON.stringify({ database_url: "postgresql://gbrain/db" }));
const baseEnv = { HOME: home, PATH: "/usr/bin", FOO: "bar" };
const result = buildGbrainEnv({ baseEnv });
expect(result.PATH).toBe("/usr/bin");
expect(result.FOO).toBe("bar");
expect(result.HOME).toBe(home);
});
it("does not modify DATABASE_URL when caller's value already matches config", () => {
// Subtle: helper should be a no-op when caller already has the right value.
// Lets us skip the stderr announce on idempotent re-invocation.
writeFileSync(join(gbrainHome, "config.json"), JSON.stringify({ database_url: "postgresql://gbrain/db" }));
const baseEnv = { HOME: home, DATABASE_URL: "postgresql://gbrain/db" };
const result = buildGbrainEnv({ baseEnv });
expect(result.DATABASE_URL).toBe("postgresql://gbrain/db");
});
});
+80
View File
@@ -0,0 +1,80 @@
/**
* Static-source invariant: every gbrain CLI invocation in the hot-path
* sync code MUST route through `lib/gbrain-exec.ts` (or accept env via
* the existing `lib/gbrain-sources.ts` opts surface). A future contributor
* who adds a `spawnSync("gbrain", ...)` call directly in
* `bin/gstack-gbrain-sync.ts` or `bin/gstack-memory-ingest.ts` silently
* regresses the DATABASE_URL fix from #1508 + codex review #7 — gbrain's
* dotenv autoload pulls a host project's `.env.local` value instead of
* gbrain's own config.
*
* This test reads each source file directly and asserts zero direct
* `spawnSync("gbrain"`, `spawn("gbrain"`, `execFileSync("gbrain"`, or
* `execSync(...gbrain` matches. Bun runs TS directly so there is no
* compiled artifact to grep — the .ts source is the truth.
*
* The check is intentionally narrow: only the two files where the bug
* actually hurts users are guarded. Other gbrain spawn sites
* (`lib/gbrain-sources.ts`, `lib/gbrain-local-status.ts`,
* `lib/gstack-memory-helpers.ts`, `bin/gstack-brain-context-load.ts`)
* either already accept env from callers or run probes that don't need
* DATABASE_URL. Expanding the invariant to those files is a follow-up.
*/
import { describe, it, expect } from "bun:test";
import { readFileSync } from "fs";
import { join } from "path";
const ROOT = join(import.meta.dir, "..");
const GUARDED_FILES = [
"bin/gstack-gbrain-sync.ts",
"bin/gstack-memory-ingest.ts",
];
// Patterns that would bypass lib/gbrain-exec.ts. Match the literal `"gbrain"`
// as the first argument since these helpers are the failure mode.
const BANNED_PATTERNS: Array<{ name: string; regex: RegExp }> = [
{ name: 'spawnSync("gbrain", ...)', regex: /spawnSync\s*\(\s*["']gbrain["']/g },
{ name: 'spawn("gbrain", ...)', regex: /\bspawn\s*\(\s*["']gbrain["']/g },
{ name: 'execFileSync("gbrain", ...)', regex: /execFileSync\s*\(\s*["']gbrain["']/g },
{ name: 'execSync("...gbrain...")', regex: /execSync\s*\(\s*["'`][^"'`]*\bgbrain\b/g },
];
describe("gbrain-exec invariant", () => {
for (const relpath of GUARDED_FILES) {
it(`${relpath} routes every gbrain spawn through lib/gbrain-exec.ts`, () => {
const source = readFileSync(join(ROOT, relpath), "utf-8");
// Strip block comments and line comments before scanning — a
// documentation reference like `// spawnSync("gbrain", ...)` in a
// comment shouldn't trip the invariant. The strip is approximate
// (sufficient for the patterns we care about); production code
// should match cleanly.
const stripped = source
.replace(/\/\*[\s\S]*?\*\//g, "")
.replace(/\/\/.*$/gm, "");
for (const { name, regex } of BANNED_PATTERNS) {
const matches = stripped.match(regex) || [];
if (matches.length > 0) {
// Find the line numbers to make the failure actionable.
const lines = stripped.split("\n");
const hits: string[] = [];
for (let i = 0; i < lines.length; i++) {
if (new RegExp(regex.source).test(lines[i])) {
hits.push(` ${relpath}:${i + 1}: ${lines[i].trim()}`);
}
}
throw new Error(
`Found ${matches.length} direct gbrain invocation(s) in ${relpath} matching \`${name}\`:\n${hits.join("\n")}\n\n`
+ `Route every gbrain spawn through \`spawnGbrain\`/\`execGbrainJson\`/\`execGbrainText\` `
+ `in lib/gbrain-exec.ts so DATABASE_URL is seeded from gbrain's config.`,
);
}
}
// Positive assertion: the file should import from lib/gbrain-exec.
expect(source).toMatch(/from\s+["']\.\.\/lib\/gbrain-exec["']/);
});
}
});
+4 -1
View File
@@ -425,7 +425,10 @@ describe("gstack-memory-ingest writer (gbrain v0.20+ batch `import` interface)",
const source = readFileSync(SCRIPT, "utf-8");
expect(source).not.toContain('command -v gbrain');
expect(source).toContain('execFileSync("gbrain", ["--help"]');
// v1.40.0.0: probe routes through lib/gbrain-exec.ts's execGbrainText helper
// (codex review #4 — centralized gbrain spawn surface). Pre-v1.40 the call
// was a direct `execFileSync("gbrain", ["--help"], ...)` inline.
expect(source).toContain('execGbrainText(["--help"]');
});
it("invokes `gbrain import <dir> --no-embed --json` exactly once with hierarchical staging", () => {