Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
New folders show up in search on a personal brain, plain folders work without Git, and Codex keeps semantic search (GST-2732) (#9396)
Garry Tancb7b31853c8c
diff --git a/README.md b/README.mdindex fb11952ed0..2340cb4a7c 100644--- a/README.md+++ b/README.md@@ -316,7 +316,8 @@ GBrain combines keyword and semantic retrieval, typed graph traversal, optionalData flowing into the brain. Each integration is a recipe — markdown + setup hints — that ships in `recipes/` and is discoverable via `gbrain integrations list`. **Say to your agent:** *"Set up voice calls into my brain"* — *"Wire my email and calendar into the brain"* — your agent reads the recipe and walks the setup with you.-- **Voice**: Phone calls create brain pages via Twilio + OpenAI Realtime (or DIY STT+LLM+TTS). Setup recipe: [`recipes/twilio-voice-brain.md`](recipes/twilio-voice-brain.md).+- **Voice**: talk to your brain from a browser or phone with [`recipes/agent-voice.md`](recipes/agent-voice.md) (`gbrain integrations install agent-voice`); the older Twilio recipe is deprecated. Voice notes and chat transcripts you already have come in as files: put their Markdown in a folder and import it, or bring ChatGPT and Claude exports in with `gbrain transcripts ingest` ([chat connectors](docs/guides/chat-connectors.md)).+- **A second folder** (for example a company notes folder beside your personal one): `gbrain sources add company --path ~/company-notes`, then `gbrain sync --source company`. A plain folder works without Git. On a brain only you use, the new folder joins default search; on a shared brain, `gbrain sources federate company` adds it. More: [multi-source brains](docs/guides/multi-source-brains.md).- **Gmail + Calendar + Contacts (native)**: the google source kind syncs threads, events, and contacts through your own OAuth client and runs the open-loop engine on top (`gbrain waiting`). Setup: [`docs/guides/google-connect.md`](docs/guides/google-connect.md); recipes: [`recipes/email-to-brain.md`](recipes/email-to-brain.md), [`recipes/calendar-to-brain.md`](recipes/calendar-to-brain.md).- **Meeting notes + Slack channels (native)**: the `meetings` source kind (Fireflies first) writes one page per meeting and the `slack` source kind one page per channel per day, synced on a schedule, on brains with or without a Git repository. Setup: [`docs/guides/meeting-and-slack-sources.md`](docs/guides/meeting-and-slack-sources.md).- **Email + calendar (webhooks)**: webhook handlers that route to brain signals. [`docs/integrations/meeting-webhooks.md`](docs/integrations/meeting-webhooks.md).diff --git a/behavior-changes.d/new_sources_join_default_search_gst2732.md b/behavior-changes.d/new_sources_join_default_search_gst2732.mdnew file mode 100644index 0000000000..5a27368698--- /dev/null+++ b/behavior-changes.d/new_sources_join_default_search_gst2732.md@@ -0,0 +1 @@+A source added with no `--federated` or `--no-federated` choice is now federated (in default search, and readable by connections with no source grant) when the brain serves one person: `access.serves` reads one, `brain.audience` classifies personal and the client is not thin. Otherwise it stays unset as before, and `sources add` and `sync --source <id>` print the `source_not_in_default_search` notice with `gbrain sources federate <id>` as the fix (asking the user first on a shared brain). Existing sources are not changed. Adds from a remote MCP caller keep the old default.diff --git a/behavior-changes.d/plain_folder_sources_gst2732.md b/behavior-changes.d/plain_folder_sources_gst2732.mdnew file mode 100644index 0000000000..c3f7cd50cd--- /dev/null+++ b/behavior-changes.d/plain_folder_sources_gst2732.md@@ -0,0 +1 @@+`gbrain sources add <id> --path <folder>` no longer needs `--force` for a plain folder outside any git repository: it registers as a plain directory (sync imports its files without Git, a removed file keeps its page). The `not_a_git_repo` refusal now applies only to a path inside a git repository with no committed, tracked content.diff --git a/changelog.d/capy-first-run-sources-codex.md b/changelog.d/capy-first-run-sources-codex.mdnew file mode 100644index 0000000000..d146a0f6c5--- /dev/null+++ b/changelog.d/capy-first-run-sources-codex.md@@ -0,0 +1,12 @@+**A second folder of notes (say, your company's beside your own) shows up in search without Git and without guessing why it doesn't.**++### Changed+- On a brain only you use, a source you add without `--federated` or `--no-federated` joins default search, so `gbrain query` finds its pages right away. On a shared brain it stays out, and `gbrain sources add` and `gbrain sync --source <id>` say so with a `source_not_in_default_search` notice whose fix is `gbrain sources federate <id>` (also under `notices` in `--json`). Sources you already have keep their setting.+- `gbrain sources add <id> --path <folder>` accepts a plain folder that is not in a git repository, without `--force`, and says that git history is off for it. A git repository with nothing committed is still refused. `gbrain sources inspect` on a plain folder now points at `sources add`.+- `gbrain setup codex` lists the provider key names (`OPENAI_API_KEY`, `VOYAGE_API_KEY` and the rest) under `env_vars`, so Codex passes keys you already exported to gbrain and search stays semantic. Only names are written.+- The "sole non-default source ... routing to 'default'" line no longer prints on every command when that source is already in default search.+- `gbrain sources federate` on a keyless brain says embedding is off instead of telling you to run `gbrain embed --stale`, and `sources --help` and `pages --help` no longer show an old version in their header.+- README: the voice line points at agent-voice (the Twilio recipe is deprecated), says how voice notes and chat transcripts get in today, and shows how to add a second folder.++<!-- behavior-change: new_sources_join_default_search_gst2732 -->+<!-- behavior-change: plain_folder_sources_gst2732 -->diff --git a/docs/guides/multi-source-brains.md b/docs/guides/multi-source-brains.mdindex af9b402990..588fa855e2 100644--- a/docs/guides/multi-source-brains.md+++ b/docs/guides/multi-source-brains.md@@ -108,7 +108,14 @@ Every source row stores `config.federated: boolean` in its JSONB config.| Value | Meaning ||-------|---------|| `true` | Source participates in unqualified `gbrain search "X"` results. |-| `false` (default for new sources) | Source only searched when explicitly named via `--source <id>` or qualified citation. |+| `false` or unset | Source only searched when explicitly named via `--source <id>` or qualified citation. |++A new source added without `--federated` or `--no-federated` is federated on+a brain only you use (`access.serves` is one, `brain.audience` reads personal,+and you are not on a thin client). On a shared brain it stays unset, and+`sources add` and `sync --source <id>` print a `source_not_in_default_search`+notice whose fix is `gbrain sources federate <id>`. Sources you added before+this change keep their setting.The seeded `default` source is `federated=true` so single-source brainsbehave as you'd expect — every page appears in search.@@ -556,12 +563,13 @@ frozen manifest was classified under the old strategy. Connector sources## The git requirement for --path sources-Every `--path` source must be a git repository (or live inside one — a-subdirectory of a git repo works too) with at least one committed, tracked-file under that path. `gbrain sources add` validates this at registration-time and refuses a directory that doesn't qualify — no `.git` at all, a-`git init` with no commit yet, or a commit made before `git add` — with an-actionable error instead of silently registering a source that will fail+A plain folder that is not inside any git repository registers as is: sync+imports its files without Git, so there is no git history, and a file you+remove from the folder keeps its page. A `--path` inside a git repository+(or a subdirectory of one) needs at least one committed, tracked file under+that path. `gbrain sources add` validates this at registration time and+refuses a repository that doesn't qualify — a `git init` with no commit yet,+or a commit made before `git add` — with an actionable error instead of silently registering a source that will fail(or worse, "succeed" while importing nothing) on its first `gbrain sync`.Fix it with:diff --git a/docs/mcp/CODEX.md b/docs/mcp/CODEX.mdindex fc918aca30..acd3052c56 100644--- a/docs/mcp/CODEX.md+++ b/docs/mcp/CODEX.md@@ -34,6 +34,14 @@ each entry by its sha256 fingerprint. Transcript capture (`SessionEnd`, withsetup reports `native-verified` when it owns the trusted `UserPromptSubmit`hook. Details: [setup guide](../guides/setup.md#codex).+Codex starts an MCP server with a short list of environment variables, so a key+you exported in your shell does not reach gbrain on its own. Setup therefore+lists the provider key names (`OPENAI_API_KEY`, `VOYAGE_API_KEY`,+`ANTHROPIC_API_KEY` and the other provider `*_API_KEY` and `*_BASE_URL` names)+under `env_vars` in `[mcp_servers.gbrain]`. Codex forwards each one that is set+and skips the rest, so a key you already use gives the session semantic search.+Only names are written, never values.+## Install as a Codex plugin (recommended)gbrain ships as a native Codex plugin — MCP server + a curated brain-firstdiff --git a/llms-full.txt b/llms-full.txtindex e714ca4049..43f368c73d 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -4696,7 +4696,8 @@ GBrain combines keyword and semantic retrieval, typed graph traversal, optionalData flowing into the brain. Each integration is a recipe — markdown + setup hints — that ships in `recipes/` and is discoverable via `gbrain integrations list`. **Say to your agent:** *"Set up voice calls into my brain"* — *"Wire my email and calendar into the brain"* — your agent reads the recipe and walks the setup with you.-- **Voice**: Phone calls create brain pages via Twilio + OpenAI Realtime (or DIY STT+LLM+TTS). Setup recipe: [`recipes/twilio-voice-brain.md`](recipes/twilio-voice-brain.md).+- **Voice**: talk to your brain from a browser or phone with [`recipes/agent-voice.md`](recipes/agent-voice.md) (`gbrain integrations install agent-voice`); the older Twilio recipe is deprecated. Voice notes and chat transcripts you already have come in as files: put their Markdown in a folder and import it, or bring ChatGPT and Claude exports in with `gbrain transcripts ingest` ([chat connectors](docs/guides/chat-connectors.md)).+- **A second folder** (for example a company notes folder beside your personal one): `gbrain sources add company --path ~/company-notes`, then `gbrain sync --source company`. A plain folder works without Git. On a brain only you use, the new folder joins default search; on a shared brain, `gbrain sources federate company` adds it. More: [multi-source brains](docs/guides/multi-source-brains.md).- **Gmail + Calendar + Contacts (native)**: the google source kind syncs threads, events, and contacts through your own OAuth client and runs the open-loop engine on top (`gbrain waiting`). Setup: [`docs/guides/google-connect.md`](docs/guides/google-connect.md); recipes: [`recipes/email-to-brain.md`](recipes/email-to-brain.md), [`recipes/calendar-to-brain.md`](recipes/calendar-to-brain.md).- **Meeting notes + Slack channels (native)**: the `meetings` source kind (Fireflies first) writes one page per meeting and the `slack` source kind one page per channel per day, synced on a schedule, on brains with or without a Git repository. Setup: [`docs/guides/meeting-and-slack-sources.md`](docs/guides/meeting-and-slack-sources.md).- **Email + calendar (webhooks)**: webhook handlers that route to brain signals. [`docs/integrations/meeting-webhooks.md`](docs/integrations/meeting-webhooks.md).diff --git a/src/commands/pages.ts b/src/commands/pages.tsindex c1c1299fbb..59a9e90402 100644--- a/src/commands/pages.ts+++ b/src/commands/pages.ts@@ -104,7 +104,7 @@ async function runPurgeDeleted(engine: BrainEngine, args: string[]): Promise<voi}export function printUsage(): void {- console.log(`gbrain pages — page-level operator commands (v0.26.5)+ console.log(`gbrain pages — page-level operator commandsSubcommands:ghosts [--source <id>] [--json] List live pages whose canonical file is missing on thediff --git a/src/commands/sources-add-next.ts b/src/commands/sources-add-next.tsindex 0a3893aafb..387edd85c2 100644--- a/src/commands/sources-add-next.ts+++ b/src/commands/sources-add-next.ts@@ -9,6 +9,8 @@* the new source readable. The stored federation default is unchanged.*/import type { BrainEngine } from '../core/engine.ts';+import type { Notice, RenderedNotice } from '../core/agent-output.ts';+import { newSourceJoinsDefaultSearch } from '../core/source-default-search.ts';import { localFederatedSourceIds } from '../core/source-resolver.ts';import { privatePagesFilterFragment, resolveExcludePrivatePages } from '../core/search/private-visibility.ts';import { quarantineFilterFragment } from '../core/quarantine.ts';@@ -34,3 +36,65 @@ export async function noGrantFloorNext(engine: BrainEngine, id: string): Promisewhy: `Connections with no source grant read only the default source and federated sources, and none of them holds a page, so their reads are refused until "${id}" is federated or they are granted sources.`,};}++/** The notice for a source left out of default search; shared says the brain's shape kept it out. Federating is the user's call when shared or when `ask` (a source that predates this add). */+export function notInDefaultSearchNotice(id: string, shared: boolean, ask = shared): Notice {+ return {+ code: 'source_not_in_default_search',+ kind: 'info',+ why: `The source "${id}" is not federated, so it is not in default search: a search, query or recall that names no source leaves its pages out, and a remote token or agent connection with no source grant cannot read them.`+ + (shared ? ' This brain serves several people or is not marked personal, so a new source stays out until someone chooses to add it.' : '')+ + ` Run \`gbrain sources federate ${id}\` to add it, or grant one token with \`gbrain auth rescope --token <name> --sources ${id}\`.`,+ fix: {+ argv: ['gbrain', 'sources', 'federate', id],+ consent: [],+ actor: 'agent',+ ...(ask ? { ask_user: true as const } : {}),+ requires_exclusive: false,+ why: 'Adds the source to default search and to what connections with no source grant can read.',+ verify: { argv: ['gbrain', 'sources', 'list', '--json'] },+ },+ };+}++/** After `gbrain sync --source <id>`: the same notice when that source holds pages and its federated setting is unset. */+export async function syncOutOfSearchNotice(engine: BrainEngine, args: string[]): Promise<Notice | null> {+ if (args[0] === 'status' || args[0] === 'unblock' || args.includes('--dry-run')) return null;+ const id = args.find((_, i) => args[i - 1] === '--source');+ if (!id || id === 'default') return null;+ try {+ const [row] = await engine.executeRaw<{ f: unknown; remote: unknown; pages: number }>(+ `SELECT config->'federated' AS f, config->'added_by_remote_caller' AS remote, (SELECT count(*)::int FROM pages WHERE source_id = $1 AND deleted_at IS NULL) AS pages FROM sources WHERE id = $1`, [id]);+ if (!row || row.f != null || row.remote === true || !Number(row.pages)) return null;+ return notInDefaultSearchNotice(id, !(await newSourceJoinsDefaultSearch(engine)), true);+ } catch {+ return null;+ }+}++/** Writes the sync notice on stderr when it applies. */+export async function noteSyncOutOfSearch(engine: BrainEngine, args: string[]): Promise<void> {+ const notice = await syncOutOfSearchNotice(engine, args);+ if (notice) (await import('../cli/cli-error.ts')).writeCliNotice(notice);+}++/**+ * GST-2732: what a finished add means, for both CLI add paths. `chosen` is the --federated / --no-federated choice+ * (null when none was made); `path` is the local folder of a plain --path add, else null. Prints on `say`, writes the+ * notice on stderr unless json, and returns the rendered notices for the JSON document.+ */+export async function reportAddOutcome(input: { id: string; chosen: boolean | null | undefined; federated: boolean; path: string | null; json: boolean; say: (line: string) => void }): Promise<RenderedNotice[] | undefined> {+ const { existsSync } = await import('node:fs');+ if (input.path && existsSync(input.path) && !(await import('../core/git-remote.ts')).inGitCheckout(input.path)) {+ input.say(' plain folder (not a git repository): sync imports its files without Git, so git history is off and a file removed from it keeps its page');+ }+ if (input.chosen != null) return undefined;+ if (input.federated) {+ input.say(` this brain serves one person, so a new source joins default search; \`gbrain sources unfederate ${input.id}\` takes it out`);+ return undefined;+ }+ const notice = notInDefaultSearchNotice(input.id, true);+ if (!input.json) (await import('../cli/cli-error.ts')).writeCliNotice(notice);+ const { cliRenderContext, renderNotice } = await import('../core/agent-output.ts');+ return [renderNotice(notice, cliRenderContext())];+}diff --git a/src/commands/sources-lifecycle.ts b/src/commands/sources-lifecycle.tsindex 5a5f1cc1c7..8ba18ff0ba 100644--- a/src/commands/sources-lifecycle.ts+++ b/src/commands/sources-lifecycle.ts@@ -49,7 +49,25 @@ export async function executeSourceLifecycle(engine: BrainEngine, parsed: Parsedreturn runPersistenceAdministration(engine, parsed.operation, parsed.params);}-async function render(result: Record<string, unknown>): Promise<void> {+/** GST-2732: what a committed add means for default search and a plain folder, on stderr and as `notices`. */+async function addOutcome(result: Record<string, unknown>, parsed?: ParsedSourceLifecycle, engine?: BrainEngine): Promise<Record<string, unknown>> {+ const options = parsed?.operation === 'source_add' ? parsed.params.options as AddSourceOpts | undefined : undefined;+ if (!options || result.dry_run === true || result.state !== 'committed') return result;+ let federated = (result.config as Record<string, unknown> | undefined)?.federated;+ if (federated === undefined && engine) {+ const rows = await engine.executeRaw<{ f: unknown }>(`SELECT config->'federated' AS f FROM sources WHERE id = $1`, [options.id]).catch(() => []);+ federated = rows[0]?.f ?? (rows.length ? false : undefined);+ }+ if (federated === undefined) return result;+ const connector = !!(options.github || options.google || options.meetings || options.slack);+ const notices = await (await import('./sources-add-next.ts')).reportAddOutcome({ id: options.id, chosen: connector ? true : options.federated,+ federated: federated === true,+ path: options.localPath && typeof result.local_path === 'string' ? result.local_path : null, json: false, say: line => console.error(line.trim()) });+ return notices ? { ...result, notices } : result;+}++async function render(result: Record<string, unknown>, parsed?: ParsedSourceLifecycle, engine?: BrainEngine): Promise<void> {+ result = await addOutcome(result, parsed, engine);await writeStdoutFinal(JSON.stringify(result, null, 2) + '\n');if (result.dry_run !== true) {try { assertTopologyCommitted(result); }@@ -60,7 +78,8 @@ async function render(result: Record<string, unknown>): Promise<void> {/** Also called by connected command users so no legacy raw DELETE/UPDATE slips through. */export async function runConnectedSourceLifecycle(engine: BrainEngine, args: string[]): Promise<boolean> {if (!await managedPersistenceEnabled(engine)) return false;- await render(await executeSourceLifecycle(engine, parseSourceLifecycleArgs(args)));+ const parsed = parseSourceLifecycleArgs(args);+ await render(await executeSourceLifecycle(engine, parsed), parsed, engine);return true;}@@ -85,7 +104,7 @@ export async function runSourceLifecycleCli(args: string[], getEngine: () => Proconst delegated = await maybeDelegateLocalAdministration(parsed.operation,{ ...parsed.params, ...(parsed.legacyOnly ? { legacy_hardening: true } : {}) }, config,{ timeoutMs: getCliOptions().timeoutMs ?? undefined });- if (delegated.handled) { await render(delegated.result as Record<string, unknown>); return; }+ if (delegated.handled) { await render(delegated.result as Record<string, unknown>, parsed); return; }} else {// An invalid mutation must not attempt another datastore open while its owner is live.const { inspectLockHolder } = await import('../core/pglite-lock.ts');@@ -94,7 +113,7 @@ export async function runSourceLifecycleCli(args: string[], getEngine: () => Proconst engine = await getEngine();if (await managedPersistenceEnabled(engine)) {if (!parsed) throw parseError;- await render(await executeSourceLifecycle(engine, parsed));+ await render(await executeSourceLifecycle(engine, parsed), parsed, engine);} else {const { runSources } = await import('./sources.ts');await runSources(engine, args);diff --git a/src/commands/sources.ts b/src/commands/sources.tsindex 86c3d68b3e..df480e877d 100644--- a/src/commands/sources.ts+++ b/src/commands/sources.ts@@ -60,7 +60,7 @@ import {import { isValidRepoName } from '../core/github-source.ts';import { ALL_GOOGLE_SERVICES, DEFAULT_CALENDAR_ID } from '../core/google/types.ts';import { defaultGoogleAddTuning, parseGoogleAddFlag } from './sources-google-flags.ts';-import { noGrantFloorNext } from './sources-add-next.ts';+import { noGrantFloorNext, reportAddOutcome } from './sources-add-next.ts';import {resolveSourceWithTier,SOURCE_TIER_NAMES,@@ -463,7 +463,7 @@ async function runAdd(engine: BrainEngine, args: string[]): Promise<void> {say(` federated: ${fed}${fed ? ' — appears in cross-source default search' : ' — only searched when explicitly named via --source'}`,);- if (!fed && federated === null) console.error(`Warning: source "${id}" is not federated. A remote token or agent connection with no source grant cannot read its pages, so its searches leave them out. Run \`gbrain sources federate ${id}\` to let every such connection read it, or grant one token with \`gbrain auth rescope --token <name> --sources ${id}\`.`);+ const notices = await reportAddOutcome({ id, chosen: ghKind || gKind ? true : federated, federated: fed, path: finalRemoteUrl || ghKind || gKind ? null : created.local_path, json, say });const next = !fed && federated === null ? await noGrantFloorNext(engine, id).catch(() => null) : null;if (next) say(` next: ${next.command} — ${next.why}`);if (ghKind || gKind) {@@ -499,7 +499,7 @@ async function runAdd(engine: BrainEngine, args: string[]): Promise<void> {console.error(` Run \`gbrain sources harden ${id}\` to retry.`);}}- if (json) console.log(JSON.stringify({ id, name: created.name, local_path: created.local_path, remote_url: finalRemoteUrl ?? null, federated: fed, ...(next ? { next } : {}) }));+ if (json) console.log(JSON.stringify({ id, name: created.name, local_path: created.local_path, remote_url: finalRemoteUrl ?? null, federated: fed, ...(next ? { next } : {}), ...(notices ? { notices } : {}) }));}/**@@ -1231,7 +1231,7 @@ async function runFederate(engine: BrainEngine, args: string[], value: boolean):} else if (sub.status === 'spend_capped') {say(` → embed-backfill skipped (24h spend cap $${sub.spendCapUsd} reached for this source).`);} else if (sub.status === 'no_worker_surface') {- say(` → embed-backfill not queued (${sub.engineKind} has no recognized persistent worker); run: gbrain embed --stale --source ${id}`);+ if (await (await import('../core/embedding-disabled.ts')).embeddingsDisabled(engine)) say(' → embed-backfill not queued: embedding is disabled on this brain (keyless by choice; keyword search works).'); else say(` → embed-backfill not queued (${sub.engineKind} has no recognized persistent worker); run: gbrain embed --stale --source ${id}`);} else if (sub.status === 'stalled') {say(` → embed-backfill not queued: the last ${sub.failures} runs failed on the same blocked pages with nothing embedded. See: gbrain doctor --only embed_backfill_stalled`);} else if (sub.status === 'embedding_disabled') {@@ -2001,7 +2001,7 @@ export async function runSources(engine: BrainEngine, args: string[]): Promise<v}function printHelp(): void {- console.log(`gbrain sources — manage multi-source brain configuration (v0.26.5)+ console.log(`gbrain sources — manage multi-source brain configurationSubcommands:inspect <path> [--profile company-brain] [--json] [--out <file>]diff --git a/src/commands/sync.ts b/src/commands/sync.tsindex 2a7b3b081c..0072c2c46c 100644--- a/src/commands/sync.ts+++ b/src/commands/sync.ts@@ -449,7 +449,7 @@ export async function runSync(engine: BrainEngine, args: string[]) {// `sync status|unblock --json` (sync/operator.ts) write through// writeJsonDocument, the guard's only stdout path.const stopTrace = startMemoryTrace('sync');- try { return await (args.includes('--json') ? withHumanLogsToStderr(() => runSyncInner(engine, args)) : runSyncInner(engine, args)); } finally { stopTrace(); }+ try { const out = await (args.includes('--json') ? withHumanLogsToStderr(() => runSyncInner(engine, args)) : runSyncInner(engine, args)); await (await import('./sources-add-next.ts')).noteSyncOutOfSearch(engine, args); return out; } finally { stopTrace(); }}/**diff --git a/src/commands/sync/plain-directory.ts b/src/commands/sync/plain-directory.tsindex 4c05e96c9a..563a175be9 100644--- a/src/commands/sync/plain-directory.ts+++ b/src/commands/sync/plain-directory.ts@@ -20,14 +20,8 @@ import { assertSourceFilesystemActive } from '../../core/minions/source-filesystimport { currentJobSignal } from '../../core/minions/submission-authority.ts';import { buildPartialResult } from '../../core/sync-lock.ts';import type { SyncOpts, SyncResult } from '../sync.ts';+import { underGitCheckout } from '../../core/git-remote.ts';-/** Whether `dir` or any directory above it has a `.git` entry (read from the filesystem, no Git process). */-function underGitCheckout(dir: string): boolean {- for (let current = dir; ; current = dirname(current)) {- if (existsSync(join(current, '.git'))) return true;- if (current === dirname(current)) return false;- }-}/*** The registered root of a plain-directory source, or null when sync's Git path applies: a connector, a path overridediff --git a/src/core/company-brain/inspection.ts b/src/core/company-brain/inspection.tsindex 1c148be49f..1e874b2493 100644--- a/src/core/company-brain/inspection.ts+++ b/src/core/company-brain/inspection.ts@@ -1,4 +1,5 @@import { createHash } from 'node:crypto';+import { isInsideGitRepo } from '../git-remote.ts';import { posix } from 'node:path';import { parseDataFrontmatter } from '../data-frontmatter.ts';import { parseMarkdown } from '../markdown.ts';@@ -346,7 +347,7 @@ export async function inspectCompanyBrain(options: InspectCompanyBrainOptions):if (companyBrainDigest(after) !== companyBrainDigest(plan.revision)) finding(plan, 'error', 'plan_stale', 'The checkout identity or revision changed during inspection; inspect again.');} catch (error) {finding(plan, 'error', error instanceof OperationError ? error.code : 'invalid_source',- error instanceof OperationError && error.code === 'request_too_large' ? 'Inspection exceeds the bounded entry or metadata limit; partition the repository or narrow selection.' : 'Inspect a committed local Git directory with a stable, safe root. No input was changed.');+ error instanceof OperationError && error.code === 'request_too_large' ? 'Inspection exceeds the bounded entry or metadata limit; partition the repository or narrow selection.' : notGitRepository(options.path) ? 'This folder is not a Git repository, and sources inspect reviews a committed company-brain checkout. To add a plain folder of notes, run gbrain sources add <id> --path <folder>. No input was changed.' : 'Inspect a committed local Git directory with a stable, safe root. No input was changed.');}for (const entry of plan.manifest) { plan.counts.tracked++; plan.counts[entry.disposition]++; }plan.counts.dirty_eligible = plan.uncommitted.filter(item => item.eligible).length;@@ -397,3 +398,9 @@ export async function validateCompanyBrainPlan(saved: unknown, options: InspectCreturn { valid: true, code: 'ok', findings: fresh.findings, plan: fresh };} catch { return stale(); }}+++/** GST-2732: a plain folder gets a pointer to \`sources add\` instead of the generic Git refusal. */+function notGitRepository(path: string): boolean {+ try { return !isInsideGitRepo(path); } catch { return false; }+}diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 8f34550999..ea90a691fe 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -1049,6 +1049,7 @@ export const NOTICE_CODES = {first_run_decisions: { kind: 'ask', summary: 'init finished (or a stdio MCP session started on a brain with open decisions); the first-run settings (search mode, writeback, skills, upkeep) are in effect as listed and the user may change them later: relay them once in the reply that reports the install, never hold the install open on them. The one muteable ask.' },harness_wiring: { kind: 'info', summary: 'init finished and no agent harness is registered yet: connecting gbrain to the agent is an install step the agent does now (`gbrain setup claude-code|codex`, or registering the stdio serve command in another host), not a setting that waits for the user.' },first_run_decisions_muted: { kind: 'info', summary: 'First-run decisions are still open, but the user muted them; the fix shows them again (`gbrain notices unmute first_run_decisions`).' },+ source_not_in_default_search: { kind: 'info', summary: 'gbrain sources add or sync left a source out of default search (its federated setting is unset): searches, queries and recalls that name no source skip its pages, and connections with no source grant cannot read them. The fix is gbrain sources federate <id>; on a brain that serves several people or is not marked personal, federating is the user\'s call. docs/guides/multi-source-brains.md' },migrations_pending: { kind: 'safety', summary: 'Schema migrations are pending or failed to apply on this brain.' },unscoped_multi_user_token: { kind: 'safety', summary: 'An install route (gbrain setup openclaw|hermes|grok-bot|muse, setup claude-code with a chat-channel plugin, mcp grant, connect, skillpack scaffold for a bot harness, auth create, auth register-client) set up access that reads the same pages whoever talks to a likely multi-user agent: a bot harness, or a grant that reads chat from 2+ channels. Several people talking to that agent may get each other\'s messages. The notice names the fixes (a one-source grant, gbrain sources unfederate, visibility: private, a credential bound to each person, or one shared agent with may_act_for and a per-request audience); a credential holding may_act_for is not flagged; doctor `unscoped_multi_user_token` reports the same detection. docs/mcp/ADMIN.md#one-token-several-people' },socket_identity_mismatch: { kind: 'degraded', summary: 'The running serve\'s warm CLI socket refused this CLI call because an identity part (named, never its value) differs from the serve\'s, so the call ran on the slower cold path; doctor `cli_socket_refusals` counts these.' },diff --git a/src/core/facts/writeback-audience.ts b/src/core/facts/writeback-audience.tsindex cddc631e0f..dd3df87073 100644--- a/src/core/facts/writeback-audience.ts+++ b/src/core/facts/writeback-audience.ts@@ -42,6 +42,8 @@ export interface BrainAudienceResult {audience: BrainAudience;/** Human-readable evidence, surfaced verbatim by doctor + the config caution. */reasons: string[];+ /** Set when 'personal' is a fallback because the client-usage read failed, not evidence: callers that widen access read it as not personal. */+ unproven?: true;}export async function classifyBrainAudience(@@ -93,6 +95,6 @@ export async function classifyBrainAudience(// The declaration read above already proved the DB reachable — a failed// usage read here means the multi-client infra isn't there (fresh or// pre-OAuth brain), which is itself personal-shaped evidence.- return { audience: 'personal', reasons: [...reasons, 'no shared declaration; client-usage heuristic unavailable'] };+ return { audience: 'personal', unproven: true, reasons: [...reasons, 'no shared declaration; client-usage heuristic unavailable'] };}}diff --git a/src/core/git-remote.ts b/src/core/git-remote.tsindex 152dfb7470..2fa8995ce2 100644--- a/src/core/git-remote.ts+++ b/src/core/git-remote.ts@@ -17,7 +17,7 @@ import { assertManagedFilesystemWrite } from './persistence/filesystem-guard.ts'*/import { execFileSync } from './spawn.ts';import { lstatSync, existsSync, readdirSync } from 'fs';-import { isAbsolute, join } from 'path';+import { dirname, isAbsolute, join } from 'path';import { isInternalUrl } from './url-safety.ts';import { execFileBounded } from './bounded-child-exec.ts';import { gitChildEnv } from './git-env.ts';@@ -351,6 +351,20 @@ export function validateRepoState(* `addSource` (#2707) to validate `--path` at registration time instead of* deferring the failure to the first sync.*/+/** Whether `dir` or any directory above it has a `.git` entry (read from the filesystem, no Git process). */+export function underGitCheckout(dir: string): boolean {+ for (let current = dir; ; current = dirname(current)) {+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- the second segment is the fixed name '.git'; this only checks for its existence while walking up from a registered source root.+ if (existsSync(join(current, '.git'))) return true;+ if (current === dirname(current)) return false;+ }+}++/** GST-2732: a path counts as a plain folder only when neither Git nor the filesystem places it in a checkout, the test sync applies. */+export function inGitCheckout(path: string): boolean {+ return underGitCheckout(path) || isInsideGitRepo(path);+}+export function isInsideGitRepo(path: string): boolean {try {execFileSync('git', ['-C', path, 'rev-parse', '--show-toplevel'], {diff --git a/src/core/persistence/administration.ts b/src/core/persistence/administration.tsindex 857b8390ca..4677b2e011 100644--- a/src/core/persistence/administration.ts+++ b/src/core/persistence/administration.ts@@ -270,7 +270,7 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatio'Add the source with gbrain sources add, which builds the typed options; a resident-proxy caller sends params.options as a JSON object.');const { managedSourceAddInput } = await import('./managed-sources.ts');const { runManagedSourceLifecycle } = await import('./source-lifecycle.ts');- const options = params.options as import('../sources-ops.ts').AddSourceOpts;+ const options = await (await import('../source-default-search.ts')).withDefaultSearchChoice(engine, params.options as import('../sources-ops.ts').AddSourceOpts);if (options.requestId !== params.request_id || !isWriteRequestId(params.request_id)) throw invalid('Source add request identity must match its options.','Send one UUID as both params.request_id and options.requestId; gbrain sources add sets both from one request id, so run the add through it.');return runManagedSourceLifecycle(engine, { ...managedSourceAddInput(options), dryRun: params.dry_run === true });diff --git a/src/core/persistence/source-lifecycle.ts b/src/core/persistence/source-lifecycle.tsindex c03dc19861..7a506b252e 100644--- a/src/core/persistence/source-lifecycle.ts+++ b/src/core/persistence/source-lifecycle.ts@@ -12,7 +12,7 @@ import { EXPIRED_ARCHIVE_SQL, removedSourceScrubCtes } from '../source-delete.tsimport { parseSourceConfig } from '../sources-load.ts';import { redactSourceConfig } from '../source-config-redact.ts';import { discoverGitRoot } from '../sync-git.ts';-import { isInsideGitRepo, hasTrackedContent } from '../git-remote.ts';+import { inGitCheckout, hasTrackedContent } from '../git-remote.ts';import { containsPath, getWorktreeBinding, humanManifestProgress, type WorktreeBinding, type WorktreeManifest, worktreeManifest } from './ownership.ts';import { manifestDifferences, storedManifestScope, type WorktreeManifestScope } from './worktree-manifest.ts';import { hostIdFor } from './identity.ts';@@ -149,7 +149,8 @@ export async function runManagedSourceLifecycle(engine:BrainEngine,input:SourceLconst prior=await priorTopologyChange(engine,principal,requestId,intent);const replayed=replayTopologyChange(prior);if(replayed) return replayed;- if(input.requireGitContent&&input.path&&(!isInsideGitRepo(input.path)||!hasTrackedContent(input.path)))+ // GST-2732: a plain folder outside any repository registers as one; a repository with nothing committed still refuses (#2707).+ if(input.requireGitContent&&input.path&&(!existsSync(input.path)||inGitCheckout(input.path)&&!hasTrackedContent(input.path)))throw opError('not_a_git_repo','The source path must contain committed Git content. Use --force to register an ordinary directory.',`Commit the content in that directory with git first, or, if '${input.sourceId}' is meant to be a plain directory, rerun the add with --force (sync then imports its files without Git; a file removed from it keeps its page); nothing was registered.`);if(input.operation==='reclone'||input.operation==='add'&&input.remoteUrl){diff --git a/src/core/setup/codex.ts b/src/core/setup/codex.tsindex 77486c7a99..2ce84ffff8 100644--- a/src/core/setup/codex.ts+++ b/src/core/setup/codex.ts@@ -140,12 +140,32 @@ export function readCodexSetupReceipt(receiptPath: string): { setup: CodexSetupRconst writeReceipt = (path: string, receipt: CodexSetupReceipt) => atomicWriteTextFile(path, `${JSON.stringify(receipt, null, 2)}\n`, { forceMode: 0o600 });+/**+ * Provider key and endpoint names Codex forwards from its own environment to+ * serve. Codex starts stdio servers with a scrubbed environment, so a key the+ * user exported never reached serve and search stayed keyword-only. Names+ * only: Codex reads each value from its own environment at launch and skips+ * a name that is unset, so no value is ever written to config.toml. The+ * provider subset of the plugin lane's .codex-plugin/mcp.json env_vars+ * (test/setup-codex-env-vars.test.ts keeps them equal).+ */+export const CODEX_FORWARDED_PROVIDER_ENV: readonly string[] = [+ 'ANTHROPIC_API_KEY', 'ANTHROPIC_BASE_URL', 'AZURE_OPENAI_API_KEY', 'DASHSCOPE_API_KEY', 'DEEPGRAM_API_KEY', 'DEEPSEEK_API_KEY',+ 'GEMINI_API_KEY', 'GOOGLE_GENERATIVE_AI_API_KEY', 'GOOGLE_GENERATIVE_AI_BASE_URL', 'GROQ_API_KEY', 'JEV_TYPESAFE_API_KEY',+ 'LITELLM_API_KEY', 'LITELLM_BASE_URL', 'LLAMA_SERVER_API_KEY', 'LLAMA_SERVER_BASE_URL', 'LLAMA_SERVER_RERANKER_API_KEY',+ 'LLAMA_SERVER_RERANKER_BASE_URL', 'LMSTUDIO_API_KEY', 'LMSTUDIO_BASE_URL', 'MINIMAX_API_KEY', 'MISTRAL_API_KEY', 'MOONSHOT_API_KEY',+ 'NAN_API_KEY', 'NVIDIA_API_KEY', 'OLLAMA_API_KEY', 'OLLAMA_BASE_URL', 'OPENAI_API_KEY', 'OPENAI_BASE_URL', 'OPENROUTER_API_KEY',+ 'OPENROUTER_BASE_URL', 'PARTICLE_API_KEY', 'PERPLEXITY_API_KEY', 'PPLX_API_KEY', 'TOGETHER_API_KEY', 'TYPESAFE_API_KEY',+ 'VOYAGE_API_KEY', 'ZHIPUAI_API_KEY',+];+export function desiredCodexMcpEntry(plan: Pick<CodexSetupPlan, 'launcher' | 'brainHome' | 'surface' | 'advertise' | 'gbrainHomeEnv' | 'sourceId' | 'stdioMember'>): Record<string, CodexTomlValue> {const env: Record<string, string> = {};if (plan.gbrainHomeEnv) env.GBRAIN_HOME = plan.gbrainHomeEnv;if (plan.sourceId) env.GBRAIN_SOURCE = plan.sourceId;// Codex starts stdio servers in the session's directory, so serve starts through the launcher too (#8426).- return { command: hookLauncherPath(plan.brainHome), args: stdioServeArgv(plan.launcher, plan.surface, plan.advertise, plan.stdioMember), ...(Object.keys(env).length ? { env } : {}) };+ return { command: hookLauncherPath(plan.brainHome), args: stdioServeArgv(plan.launcher, plan.surface, plan.advertise, plan.stdioMember), ...(Object.keys(env).length ? { env } : {}),+ env_vars: [...CODEX_FORWARDED_PROVIDER_ENV] };}function desiredGroups(plan: CodexSetupPlan): Partial<Record<CodexSetupEvent, CodexHookGroup>> {diff --git a/src/core/source-default-search.ts b/src/core/source-default-search.tsnew file mode 100644index 0000000000..727a0a865a--- /dev/null+++ b/src/core/source-default-search.ts@@ -0,0 +1,28 @@+/**+ * GST-2732 B (Garry, 2026-11-15: "Do it"): a source added with no federated choice joins default search only on a+ * single-user brain: access.serves reads one, brain.audience classifies personal from a declaration or a successful usage read, and the caller is local (a thin+ * client's add runs on its host as a remote caller). Any other answer, a failed read included, leaves the stored default unset (out of default search),+ * and the add says so (`source_not_in_default_search`). Existing sources are never changed here.+ */+import type { BrainEngine } from './engine.ts';+import type { AddSourceOpts } from './sources-ops.ts';++export async function newSourceJoinsDefaultSearch(engine: BrainEngine): Promise<boolean> {+ try {+ const { brainServes } = await import('./access/serves.ts');+ if ((await brainServes(engine)).serves !== 'one') return false;+ const { classifyBrainAudience } = await import('./facts/writeback-audience.ts');+ const audience = await classifyBrainAudience(engine);+ return audience.audience === 'personal' && !audience.unproven;+ } catch {+ return false;+ }+}++/** Folder and Git sources only: connectors keep their own defaults (GitHub and Google federated, meetings and Slack chats out). */+export async function withDefaultSearchChoice(engine: BrainEngine, opts: AddSourceOpts): Promise<AddSourceOpts> {+ if (opts.federated != null || opts.github || opts.google || opts.meetings || opts.slack || opts.addedByRemoteCaller) return opts;+ const joins = await newSourceJoinsDefaultSearch(engine);+ if (opts.localPath && (await engine.executeRaw('SELECT 1 FROM sources WHERE id = $1 AND local_path IS NULL', [opts.id])).length > 0) return opts;+ return joins ? { ...opts, federated: true } : opts;+}diff --git a/src/core/source-resolver.ts b/src/core/source-resolver.tsindex 2cbdf31d2f..f46d613ee4 100644--- a/src/core/source-resolver.ts+++ b/src/core/source-resolver.ts@@ -376,11 +376,11 @@ async function pickSoleNonDefaultSource(`SELECT 1 AS one FROM pages WHERE source_id = 'default' AND deleted_at IS NULL LIMIT 1`,).then(found => found.length > 0);defaultHasPages.catch(() => {});- let rows: Array<{ id: string }> = request ? request.filter(row => row.local_path !== null && row.id !== 'default' && row.archived === false && parseSourceConfig(row.config).role !== 'storage_manifest') : [];+ let rows: Array<{ id: string; config?: unknown }> = request ? request.filter(row => row.local_path !== null && row.id !== 'default' && row.archived === false && parseSourceConfig(row.config).role !== 'storage_manifest') : [];if (!request) {try {- rows = await engine.executeRaw<{ id: string }>(- `SELECT id FROM sources WHERE local_path IS NOT NULL AND id != 'default' AND archived = false AND config->>'role' IS DISTINCT FROM 'storage_manifest'`,+ rows = await engine.executeRaw<{ id: string; config: unknown }>(+ `SELECT id, config FROM sources WHERE local_path IS NOT NULL AND id != 'default' AND archived = false AND config->>'role' IS DISTINCT FROM 'storage_manifest'`,);} catch {rows = await engine.executeRaw<{ id: string }>(@@ -396,7 +396,9 @@ async function pickSoleNonDefaultSource(// every bare command away from the sole side-source, and the user// hunts for "lost" writes. One stderr line names both sides so the// misroute is diagnosable; same suppression knob as the routing nudge.- if (!opts.quiet && process.env.GBRAIN_NO_SOLE_NON_DEFAULT_NUDGE !== '1') {+ // GST-2732: a federated side source is in default search already, so the routing loses nothing and stays quiet.+ const federated = (parseSourceConfig(rows[0].config) as { federated?: unknown }).federated === true;+ if (!opts.quiet && !federated && process.env.GBRAIN_NO_SOLE_NON_DEFAULT_NUDGE !== '1') {console.error(`[gbrain] sole non-default source '${rows[0].id}' exists, but 'default' is non-empty — routing to 'default' (#3070 emptiness guard). Pass --source ${rows[0].id} or set sources.default to target it.`,);diff --git a/src/core/sources-ops.ts b/src/core/sources-ops.tsindex 10494e0aed..0206bcc870 100644--- a/src/core/sources-ops.ts+++ b/src/core/sources-ops.ts@@ -48,7 +48,7 @@ import {parseRemoteUrl,cloneRepo,validateRepoState,- isInsideGitRepo,+ inGitCheckout,hasTrackedContent,RemoteUrlError,GitOperationError,@@ -461,7 +461,7 @@ export async function addSource(engine: BrainEngine,opts: AddSourceOpts,): Promise<SourceRow> {- if(await managedPersistenceEnabled(engine))return (await import('./persistence/managed-sources.ts')).addManagedSource(engine,opts);+ opts = await (await import('./source-default-search.ts')).withDefaultSearchChoice(engine, opts); if(await managedPersistenceEnabled(engine))return (await import('./persistence/managed-sources.ts')).addManagedSource(engine,opts);await assertUnmanagedCanonicalWriter(engine, 'sources add');validateSourceId(opts.id);@@ -707,8 +707,9 @@ export async function addSource(// report ("plain directory accepted, sync fails later") rather than a// broader "does this path exist" check nobody asked for.//- // Both isInsideGitRepo AND hasTrackedContent must hold. isInsideGitRepo- // alone lets through a `git init`ed-but-never-committed directory (fails+ // GST-2732: a plain folder outside any git repository registers as a plain+ // directory (sync imports its files without Git, #7973). Inside a+ // repository, hasTrackedContent must hold: isInsideGitRepo alone lets through a `git init`ed-but-never-committed directory (fails// sync's "No commits in repo ..."), AND an empty-commit-then-untracked-// files directory (git resolves HEAD fine but the tree is empty — the// exact silent-staleness footgun #2707(c) describes: sync "succeeds"@@ -718,7 +719,8 @@ export async function addSource(opts.localPath &&!opts.force &&existsSync(opts.localPath) &&- (!isInsideGitRepo(opts.localPath) || !hasTrackedContent(opts.localPath))+ inGitCheckout(opts.localPath) &&+ !hasTrackedContent(opts.localPath)) {const q = shellQuote(opts.localPath);throw new SourceOpError(diff --git a/test/e2e/multi-source.test.ts b/test/e2e/multi-source.test.tsindex 4580a707ee..d8eb94a7ff 100644--- a/test/e2e/multi-source.test.ts+++ b/test/e2e/multi-source.test.ts@@ -438,7 +438,7 @@ describeE2E('v0.18.0 multi-source — sources table surface', () => {await teardownDB();});- test('default source is seeded federated=true; new sources default to isolated', async () => {+ test('default source is seeded federated=true; on a shared brain new sources default to isolated, on a personal one they join', async () => {const conn = getConn();const engine = getEngine();@@ -449,11 +449,22 @@ describeE2E('v0.18.0 multi-source — sources table surface', () => {// Defensive cleanup: sources isn't in helpers.ALL_TABLES, so residual// rows from prior test runs can shadow this INSERT via ON CONFLICT// DO NOTHING. Delete first, then create.- await conn.unsafe(`DELETE FROM sources WHERE id = 'isolatedsrc'`);- await runSources(engine as unknown as Parameters<typeof runSources>[0], ['add', 'isolatedsrc']);+ await conn.unsafe(`DELETE FROM sources WHERE id IN ('isolatedsrc', 'personalsrc')`);+ await engine.setConfig('brain.audience', 'shared');+ try {+ await runSources(engine as unknown as Parameters<typeof runSources>[0], ['add', 'isolatedsrc']);+ } finally {+ await engine.setConfig('brain.audience', 'personal');+ }const iso = await conn.unsafe(`SELECT config FROM sources WHERE id = 'isolatedsrc'`);const isoConfig = typeof iso[0].config === 'string' ? JSON.parse(iso[0].config) : iso[0].config;- expect(isoConfig.federated).toBeUndefined(); // omitted → isolated-by-default+ expect(isoConfig.federated).toBeUndefined();++ await runSources(engine as unknown as Parameters<typeof runSources>[0], ['add', 'personalsrc']);+ const personal = await conn.unsafe(`SELECT config FROM sources WHERE id = 'personalsrc'`);+ const personalConfig = typeof personal[0].config === 'string' ? JSON.parse(personal[0].config) : personal[0].config;+ expect(personalConfig.federated).toBe(true);+ await conn.unsafe(`DELETE FROM sources WHERE id = 'personalsrc'`);});test('federate / unfederate flips config.federated on real DB', async () => {diff --git a/test/serve-stdio-bound-explicit-read.test.ts b/test/serve-stdio-bound-explicit-read.test.tsindex f2074ef654..a96d4dd536 100644--- a/test/serve-stdio-bound-explicit-read.test.ts+++ b/test/serve-stdio-bound-explicit-read.test.ts@@ -53,6 +53,8 @@ describe('#5081 — GBRAIN_SOURCE-bound stdio serve, explicit source_id reads',});delete env.GBRAIN_SOURCE;execFixture(['run', 'src/cli.ts', 'init', '--pglite', '--no-embedding', '--non-interactive'], env);+ // GST-2732: a shared brain keeps a new source's federated setting unset, the shape this fixture needs.+ execFixture(['run', 'src/cli.ts', 'config', 'set', 'brain.audience', 'shared'], env);for (const [id, flag] of [['work', null], ['notes', '--federated'], ['private', null]] as const) {const dir = join(home, id);mkdirSync(dir, { recursive: true });diff --git a/test/setup-codex-env-vars.test.ts b/test/setup-codex-env-vars.test.tsnew file mode 100644index 0000000000..d43d9f5237--- /dev/null+++ b/test/setup-codex-env-vars.test.ts@@ -0,0 +1,37 @@+/**+ * `gbrain setup codex` forwards provider key names to serve (GST-2732).+ * Codex starts stdio MCP servers with a scrubbed environment, so a key the+ * user exported reached the CLI but never the MCP child, and Codex sessions+ * stayed keyword-only. The entry lists names only (env_vars), never values.+ */+import { withEnv } from './helpers/with-env.ts';+import { describe, expect, test } from 'bun:test';+import { readFileSync } from 'fs';+import { join } from 'path';+import { CODEX_FORWARDED_PROVIDER_ENV, desiredCodexMcpEntry } from '../src/core/setup/codex.ts';++const ROOT = join(import.meta.dir, '..');+const plan = { launcher: '/usr/local/bin/gbrain', brainHome: '/tmp/gbrain-home-example', surface: 'starter', advertise: 'verbs', gbrainHomeEnv: '/tmp/gbrain-home-example', sourceId: null, stdioMember: null } as const;++describe('setup codex env_vars', () => {+ test('the MCP entry forwards every provider key and endpoint name, sorted', () => {+ const entry = desiredCodexMcpEntry(plan as never) as { env_vars?: string[] };+ expect(entry.env_vars).toEqual([...CODEX_FORWARDED_PROVIDER_ENV]);+ expect(entry.env_vars).toContain('OPENAI_API_KEY');+ expect(entry.env_vars).toContain('VOYAGE_API_KEY');+ expect([...CODEX_FORWARDED_PROVIDER_ENV]).toEqual([...CODEX_FORWARDED_PROVIDER_ENV].sort());+ });++ test('the entry never carries a key value, even when the key is set in setup\'s environment', async () => {+ await withEnv({ OPENAI_API_KEY: 'sk-test-value-never-written' }, () => {+ const rendered = JSON.stringify(desiredCodexMcpEntry(plan as never));+ expect(rendered).not.toContain('sk-test-value-never-written');+ });+ });++ test('the list equals the provider subset of the Codex plugin lane\'s env_vars', () => {+ const plugin = JSON.parse(readFileSync(join(ROOT, '.codex-plugin/mcp.json'), 'utf8'));+ const pluginProviders = (plugin.mcpServers.gbrain.env_vars as string[]).filter(n => /_(API_KEY|BASE_URL)$/.test(n));+ expect([...CODEX_FORWARDED_PROVIDER_ENV]).toEqual(pluginProviders);+ });+});diff --git a/test/setup.test.ts b/test/setup.test.tsindex 76b95c6a66..392aa65b3c 100644--- a/test/setup.test.ts+++ b/test/setup.test.ts@@ -38,6 +38,7 @@ import { hookLauncherFix, hookLauncherProblems } from '../src/commands/doctor/chimport { launcherLaneFindings, setupRerunArgv } from '../src/core/setup/launcher-lanes.ts';import { harnessWiringEntry } from '../src/core/readiness.ts';import { applyClaudeSetup, readSetupReceipt } from '../src/core/setup/claude-code.ts';+import { CODEX_FORWARDED_PROVIDER_ENV } from '../src/core/setup/codex.ts';const CLI = resolve(import.meta.dir, '..', 'src', 'cli.ts');const roots: string[] = [];@@ -565,7 +566,8 @@ describe('gbrain setup codex: install lifecycle', () => {expect(first.doc.consent.capture).toMatchObject({ value: 'declined', source: 'default' });expect(first.doc.notices.find((n: any) => n.code === 'first_run_decisions').user_message).toContain('Report back (Wakeshift): off. gbrain wakeshift enable turns it on.');expect(readJson(join(b.gbrainHome, '.gbrain', 'config.json')).embedding_disabled).toBe(true);- expect(toml(b).mcp_servers.gbrain).toEqual({ command: launcher(b), args: [b.bin, 'serve', '--surface', 'starter', '--advertise', 'verbs'], env: { GBRAIN_HOME: b.gbrainHome } });+ expect(toml(b).mcp_servers.gbrain).toEqual({ command: launcher(b), args: [b.bin, 'serve', '--surface', 'starter', '--advertise', 'verbs'], env: { GBRAIN_HOME: b.gbrainHome },+ env_vars: [...CODEX_FORWARDED_PROVIDER_ENV] });expect(Object.keys(readJson(hooksJson(b)).hooks).sort()).toEqual(['SessionStart', 'UserPromptSubmit']);expect(groups(b, 'UserPromptSubmit')).toEqual([{ hooks: [{ type: 'command', timeout: 15,command: `env GBRAIN_HOOK_LANE=setup GBRAIN_HOME=${b.gbrainHome} ${b.gbrainHome}/.gbrain/hook-launcher/gbrain-hook ${b.bin} hook user-prompt --harness codex` }] }]);@@ -732,7 +734,7 @@ describe('gbrain setup codex: install lifecycle', () => {expect(readFileSync(codexToml(b), 'utf8')).toBe(foreign);expect(existsSync(hooksJson(b))).toBe(false);- const same = `[mcp_servers.gbrain]\ncommand = ${JSON.stringify(launcher(b))}\nargs = [${JSON.stringify(b.bin)}, "serve", "--surface", "starter"]\nenv = { GBRAIN_HOME = ${JSON.stringify(b.gbrainHome)} }\n`;+ const same = `[mcp_servers.gbrain]\ncommand = ${JSON.stringify(launcher(b))}\nargs = [${JSON.stringify(b.bin)}, "serve", "--surface", "starter"]\nenv = { GBRAIN_HOME = ${JSON.stringify(b.gbrainHome)} }\nenv_vars = [${CODEX_FORWARDED_PROVIDER_ENV.map(n => JSON.stringify(n)).join(', ')}]\n`;writeFileSync(codexToml(b), same);expect((await setup(b, ['codex'])).exitCode).toBe(0);expect(readJson(codexReceipt(b)).mcp_adopted).toBe(true);diff --git a/test/source-resolver-sole-non-default.test.ts b/test/source-resolver-sole-non-default.test.tsindex 870b9e5715..032e0bd89f 100644--- a/test/source-resolver-sole-non-default.test.ts+++ b/test/source-resolver-sole-non-default.test.ts@@ -24,7 +24,7 @@ import {} from '../src/core/source-resolver.ts';import { withEnv } from './helpers/with-env.ts';-type StubSource = { id: string; local_path: string | null; archived?: boolean };+type StubSource = { id: string; local_path: string | null; archived?: boolean; config?: Record<string, unknown> };function makeStub(sources: StubSource[],@@ -45,7 +45,7 @@ function makeStub(}if (sql.includes('archived = false')) {return sources.filter(s => s.local_path !== null && s.id !== 'default' && s.archived !== true)- .map(s => ({ id: s.id })) as unknown as T[];+ .map(s => ({ id: s.id, config: s.config ?? {} })) as unknown as T[];}if (sql.includes('local_path IS NOT NULL AND id != \'default\'')) {return sources.filter(s => s.local_path !== null && s.id !== 'default')@@ -238,6 +238,28 @@ describe('#1434 — sole_non_default tier', () => {expect(line).toContain('non-empty');});+ test('#3070 (GST-2732): no flip warning when the side source is federated, since default search already reads it', async () => {+ const engine = makeStub(+ [+ { id: 'default', local_path: null },+ { id: 'company', local_path: '/tmp/company', config: { federated: true } },+ ],+ null,+ { defaultActivePages: 1 },+ );+ const originalError = console.error;+ const errLines: string[] = [];+ console.error = (...args: unknown[]) => { errLines.push(args.join(' ')); };+ try {+ await withEnv({ GBRAIN_NO_SOLE_NON_DEFAULT_NUDGE: undefined }, async () => {+ expect((await resolveSourceWithTier(engine, null, '/tmp')).source_id).toBe('default');+ });+ } finally {+ console.error = originalError;+ }+ expect(errLines.length).toBe(0);+ });+test('#3070: the flip warning is suppressed via GBRAIN_NO_SOLE_NON_DEFAULT_NUDGE=1', async () => {const engine = makeStub([diff --git a/test/sources-add-default-search.test.ts b/test/sources-add-default-search.test.tsnew file mode 100644index 0000000000..74a2fc6e73--- /dev/null+++ b/test/sources-add-default-search.test.ts@@ -0,0 +1,181 @@+/**+ * GST-2732 B (Garry, 2026-11-15: "Do it"): a source added with no --federated choice joins default search on a+ * single-user brain, and stays out with a notice everywhere else.+ *+ * 1. Protects: on a fresh personal brain (access.serves one, brain.audience personal by the heuristic) a plain+ * `sources add` stores federated true, prints how to take it out, and prints no not-in-default-search notice;+ * an explicit --no-federated still wins; a brain declared shared or serving several people keeps the old+ * default and prints the notice; an existing source is not changed by a later add.+ * 2. Fails when: the default flips on a shared or several-people brain, the personal default stays unfederated,+ * an explicit --no-federated is overridden, or an existing source's setting moves.+ * 3. No production seam: the real command on PGLite, console spies only.+ */+import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runSources } from '../src/commands/sources.ts';++let engine: PGLiteEngine;+const dirs: string[] = [];++async function add(args: string[]): Promise<{ stdout: string; stderr: string }> {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-sources-add-default-'));+ dirs.push(dir);+ const out: string[] = [];+ const err: string[] = [];+ const log = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { out.push(a.join(' ')); });+ const warn = spyOn(console, 'error').mockImplementation((...a: unknown[]) => { err.push(a.join(' ')); });+ const raw = spyOn(process.stderr, 'write').mockImplementation(((chunk: unknown) => { err.push(String(chunk)); return true; }) as never);+ try {+ await runSources(engine, ['add', args[0]!, '--path', dir, '--force', ...args.slice(1)]);+ } finally {+ log.mockRestore();+ warn.mockRestore();+ raw.mockRestore();+ }+ return { stdout: out.join('\n'), stderr: err.join('\n') };+}++async function federated(id: string): Promise<unknown> {+ const rows = await engine.executeRaw<{ f: unknown }>(`SELECT config->'federated' AS f FROM sources WHERE id = $1`, [id]);+ return rows[0]?.f ?? null;+}++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({ engine: 'pglite' } as never);+ await engine.initSchema();+}, 60_000);++afterAll(async () => {+ await engine?.disconnect();+ for (const d of dirs) rmSync(d, { recursive: true, force: true });+});++describe('a new source on a single-user brain joins default search', () => {+ test('a plain add stores federated true, says how to take it out, and prints no notice', async () => {+ const { stdout, stderr } = await add(['personal-a']);+ expect(await federated('personal-a')).toBe(true);+ expect(stdout).toContain('federated: true');+ expect(stdout).toContain('gbrain sources unfederate personal-a');+ expect(stderr).not.toContain('source_not_in_default_search');+ });++ test('an explicit --no-federated is the stated choice and stays out', async () => {+ await add(['personal-b', '--no-federated']);+ expect(await federated('personal-b')).toBe(false);+ });++ test('attaching a path to an existing path-less source keeps its stored setting (#3903 attach)', async () => {+ await engine.executeRaw(`INSERT INTO sources (id, name, local_path, config) VALUES ('attach-off', 'attach-off', NULL, '{"federated":false}'::jsonb), ('attach-unset', 'attach-unset', NULL, '{}'::jsonb)`);+ await add(['attach-off']);+ await add(['attach-unset']);+ expect(await federated('attach-off')).toBe(false);+ expect(await federated('attach-unset')).toBeNull();+ });++ test('a retried add of a source that now exists normalizes the same way (idempotent replay)', async () => {+ const { withDefaultSearchChoice } = await import('../src/core/source-default-search.ts');+ await add(['personal-retry']);+ const again = await withDefaultSearchChoice(engine, { id: 'personal-retry', localPath: '/tmp/gbrain-retry-example' } as never);+ expect(again.federated).toBe(true);+ });++ test('--json reports federated true with no notices', async () => {+ const out = JSON.parse((await add(['personal-c', '--json'])).stdout);+ expect(out).toMatchObject({ id: 'personal-c', federated: true });+ expect(out.notices).toBeUndefined();+ });+});++describe('a brain that is shared or serves several people keeps new sources out, with the notice', () => {+ test('brain.audience shared: the add stays unfederated and prints the notice with the shared reason', async () => {+ await engine.setConfig('brain.audience', 'shared');+ try {+ const { stderr } = await add(['shared-a']);+ expect(await federated('shared-a')).not.toBe(true);+ expect(stderr).toContain('source_not_in_default_search');+ expect(stderr).toContain('serves several people or is not marked personal');+ expect(await federated('personal-a')).toBe(true);+ } finally {+ await engine.setConfig('brain.audience', 'personal');+ }+ });++ test('access.serves several: the add stays unfederated even on a brain declared personal', async () => {+ await engine.setConfig('access.serves', 'several');+ try {+ const out = JSON.parse((await add(['several-a', '--json'])).stdout);+ expect(out.federated).toBe(false);+ expect(out.notices?.[0]?.code).toBe('source_not_in_default_search');+ } finally {+ await engine.setConfig('access.serves', 'one');+ }+ });+});++describe('federating a source on a keyless PGLite brain', () => {+ test('says embedding is off instead of telling the user to run gbrain embed --stale', async () => {+ await add(['keyless-a', '--no-federated']);+ await engine.putPage('notes/keyless', { type: 'note', title: 'K', compiled_truth: 'A page with a chunk to embed.', timeline: '' }, { sourceId: 'keyless-a' });+ await engine.upsertChunks('notes/keyless', [{ chunk_index: 0, chunk_text: 'A page with a chunk to embed.', chunk_source: 'compiled_truth' }], { sourceId: 'keyless-a' });+ await engine.setConfig('embedding_disabled', 'true');+ const out: string[] = [];+ const log = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { out.push(a.join(' ')); });+ const err = spyOn(console, 'error').mockImplementation((...a: unknown[]) => { out.push(a.join(' ')); });+ try {+ await runSources(engine, ['federate', 'keyless-a']);+ } finally {+ log.mockRestore();+ err.mockRestore();+ await engine.setConfig('embedding_disabled', 'false');+ }+ const text = out.join('\n');+ expect(text).toContain('embedding is disabled on this brain');+ expect(text).not.toContain('gbrain embed --stale');+ });+});++describe('a brain that cannot be shown to be personal keeps new sources out', () => {+ test('a failed client-usage read on an undeclared brain is not personal: the source stays out, with the notice', async () => {+ const { newSourceJoinsDefaultSearch } = await import('../src/core/source-default-search.ts');+ const declared = await engine.getConfig('brain.audience');+ await engine.unsetConfig('brain.audience');+ const failing = new Proxy(engine, {+ get(target, key, receiver) {+ if (key === 'executeRaw') return (sql: string, params?: unknown[]) => /mcp_request_log/.test(sql)+ ? Promise.reject(new Error('canceling statement due to statement timeout'))+ : target.executeRaw(sql, params as never);+ const value = Reflect.get(target, key, receiver);+ return typeof value === 'function' ? value.bind(target) : value;+ },+ }) as PGLiteEngine;+ try {+ expect(await newSourceJoinsDefaultSearch(engine)).toBe(true);+ expect(await newSourceJoinsDefaultSearch(failing)).toBe(false);+ const notice = (await import('../src/commands/sources-add-next.ts')).notInDefaultSearchNotice('unproven-a', !(await newSourceJoinsDefaultSearch(failing)));+ expect(notice.why).toContain('is not marked personal');+ } finally {+ if (declared != null) await engine.setConfig('brain.audience', declared);+ }+ });+});++describe('an identical retry of a path-less add on a managed brain', () => {+ test('replays the first add instead of failing idempotency_conflict', async () => {+ const { managedBrain } = await import('./helpers/managed-brain.ts');+ const { addSource } = await import('../src/core/sources-ops.ts');+ const { randomUUID } = await import('node:crypto');+ await managedBrain(async ({ engine: managed }) => {+ const requestId = randomUUID();+ const first = await addSource(managed, { id: 'bare-retry', requestId } as never);+ const again = await addSource(managed, { id: 'bare-retry', requestId } as never);+ expect(again.id).toBe(first.id);+ const [row] = await managed.executeRaw<{ f: unknown }>(`SELECT config->'federated' AS f FROM sources WHERE id = 'bare-retry'`);+ expect(row?.f).toBe(true);+ });+ }, 60_000);+});+diff --git a/test/sources-add-federation-warning.test.ts b/test/sources-add-federation-warning.test.tsindex 8e6e25003f..debccabcd7 100644--- a/test/sources-add-federation-warning.test.ts+++ b/test/sources-add-federation-warning.test.ts@@ -23,6 +23,7 @@ import { tmpdir } from 'node:os';import { join } from 'node:path';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { runSources } from '../src/commands/sources.ts';+import { syncOutOfSearchNotice } from '../src/commands/sources-add-next.ts';let engine: PGLiteEngine;const dirs: string[] = [];@@ -34,11 +35,13 @@ async function add(args: string[]): Promise<{ stdout: string; stderr: string }>const err: string[] = [];const log = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { out.push(a.join(' ')); });const warn = spyOn(console, 'error').mockImplementation((...a: unknown[]) => { err.push(a.join(' ')); });+ const raw = spyOn(process.stderr, 'write').mockImplementation(((chunk: unknown) => { err.push(String(chunk)); return true; }) as never);try {await runSources(engine, ['add', args[0]!, '--path', dir, '--force', ...args.slice(1)]);} finally {log.mockRestore();warn.mockRestore();+ raw.mockRestore();}return { stdout: out.join('\n'), stderr: err.join('\n') };}@@ -52,6 +55,8 @@ beforeAll(async () => {engine = new PGLiteEngine();await engine.connect({ engine: 'pglite' } as never);await engine.initSchema();+ // GST-2732 B: a personal brain federates a new source by default (test/sources-add-default-search.test.ts); these cases are the shared brain.+ await engine.setConfig('brain.audience', 'shared');}, 60_000);afterAll(async () => {@@ -67,9 +72,19 @@ describe('sources add federation warning', () => {expect(stderr).toContain('no source grant');expect(stderr).toContain('gbrain sources federate source-a');expect(stderr).toContain('gbrain auth rescope --token <name> --sources source-a');+ expect(stderr).toContain('source_not_in_default_search');+ expect(stderr).toContain('not in default search');expect(await federated('source-a')).not.toBe(true);});+ test('--json carries the not-in-default-search notice with the federate fix, and keeps the existing fields', async () => {+ const { stdout } = await add(['source-n', '--json']);+ const out = JSON.parse(stdout);+ expect(out).toMatchObject({ id: 'source-n', federated: false });+ expect(out.notices).toHaveLength(1);+ expect(out.notices[0]).toMatchObject({ code: 'source_not_in_default_search', kind: 'info', fix: { argv: ['gbrain', 'sources', 'federate', 'source-n'] } });+ });+test('--federated adds without the warning', async () => {const { stderr } = await add(['source-b', '--federated']);expect(stderr).not.toContain('is not federated');@@ -155,3 +170,24 @@ describe('sources add next step when the no-grant floor holds no page', () => {expect(json.next).toBeUndefined();});});++describe('gbrain sync --source names a source that default search leaves out', () => {+ test('a synced source with pages and no federated setting gets the notice; a federated one, the default source and status do not', async () => {+ await add(['source-m']);+ expect(await syncOutOfSearchNotice(engine, ['--source', 'source-m'])).toBeNull();+ await engine.putPage('notes/m', { type: 'note', title: 'M', compiled_truth: 'A page in source-m.', timeline: '' }, { sourceId: 'source-m' });+ const notice = await syncOutOfSearchNotice(engine, ['--source', 'source-m', '--no-pull']);+ expect(notice).toMatchObject({ code: 'source_not_in_default_search', fix: { argv: ['gbrain', 'sources', 'federate', 'source-m'], ask_user: true } });+ expect(await syncOutOfSearchNotice(engine, ['status', '--source', 'source-m'])).toBeNull();+ expect(await syncOutOfSearchNotice(engine, ['--source', 'default'])).toBeNull();+ await engine.executeRaw(`UPDATE sources SET config = config || '{"federated": false}'::jsonb WHERE id = 'source-m'`);+ expect(await syncOutOfSearchNotice(engine, ['--source', 'source-m'])).toBeNull();+ });++ test('a source a remote MCP caller added stays out without a federate step after sync', async () => {+ await add(['source-r']);+ await engine.executeRaw(`UPDATE sources SET config = (config - 'federated') || '{"added_by_remote_caller": true}'::jsonb WHERE id = 'source-r'`);+ await engine.putPage('notes/r', { type: 'note', title: 'R', compiled_truth: 'A page in source-r.', timeline: '' }, { sourceId: 'source-r' });+ expect(await syncOutOfSearchNotice(engine, ['--source', 'source-r'])).toBeNull();+ });+});diff --git a/test/sources-ops.test.ts b/test/sources-ops.test.tsindex b430ead763..c1135ddbfe 100644--- a/test/sources-ops.test.ts+++ b/test/sources-ops.test.ts@@ -840,9 +840,32 @@ describe('addSource --path — #2707 git-repo validation', () => {rmSync(SANDBOX, { recursive: true, force: true });});- test('rejects an existing non-git directory with an actionable error', async () => {+ test('registers an existing plain directory outside any git repository without --force (GST-2732)', async () => {+ const plainDir = join(SANDBOX, 'plain-ok');+ mkdirSync(plainDir, { recursive: true });+ writeFileSync(join(plainDir, 'notes.md'), 'a plain folder');+ const row = await addSource(engine, { id: 'plain-ok-src', localPath: plainDir });+ expect(row.local_path).toBe(plainDir);+ });++ test('a folder with a .git entry that git cannot read is not a plain folder: refused like sync would treat it (GST-2732)', async () => {+ const brokenDir = join(SANDBOX, 'broken-gitlink');+ mkdirSync(brokenDir, { recursive: true });+ writeFileSync(join(brokenDir, '.git'), 'gitdir: /nonexistent/gbrain-gst2732\n');+ writeFileSync(join(brokenDir, 'notes.md'), 'inside a checkout git cannot open');+ let threw: SourceOpError | undefined;+ try {+ await addSource(engine, { id: 'broken-gitlink-src', localPath: brokenDir });+ } catch (e) {+ threw = e as SourceOpError;+ }+ expect(threw?.code).toBe('not_a_git_repo');+ });++ test('rejects a git repository with untracked files only, with an actionable error', async () => {const plainDir = join(SANDBOX, 'plain');mkdirSync(plainDir, { recursive: true });+ execFileSync('git', ['-C', plainDir, 'init', '-q']);writeFileSync(join(plainDir, 'notes.md'), 'not committed anywhere');let threw: SourceOpError | undefined;@@ -1006,6 +1029,7 @@ describe('addSource --path — #2707 git-repo validation', () => {test('quotes a path with a space in the remediation command (codex round 1)', async () => {const spacedDir = join(SANDBOX, 'has space here');mkdirSync(spacedDir, { recursive: true });+ execFileSync('git', ['-C', spacedDir, 'init', '-q']);let threw: SourceOpError | undefined;try {@@ -1143,6 +1167,7 @@ describe('addSource --path — #3903 attach to existing path-less source', () =>);const plainDir = join(SANDBOX, 'plain-attach');mkdirSync(plainDir, { recursive: true });+ execFileSync('git', ['-C', plainDir, 'init', '-q']);let threw: SourceOpError | undefined;try {diff --git a/test/sources.test.ts b/test/sources.test.tsindex 3fd7bd900c..58ab5de59f 100644--- a/test/sources.test.ts+++ b/test/sources.test.ts@@ -9,6 +9,7 @@import { describe, test, expect, beforeEach, afterEach, spyOn } from 'bun:test';import { mkdtempSync, mkdirSync, rmSync } from 'fs';import { tmpdir } from 'os';+import { execFileSync } from 'child_process';import { join } from 'path';import { runSources } from '../src/commands/sources.ts';import type { BrainEngine } from '../src/core/engine.ts';@@ -96,7 +97,7 @@ describe('sources add', () => {await expect(runSources(engine, ['add', long, '--path', '/tmp/x'])).rejects.toThrow(/Invalid source id/);});- test('inserts a valid source with defaults (federated unset → isolated)', async () => {+ test('inserts a valid source with defaults (a single-user brain federates it, GST-2732)', async () => {const { engine, calls } = makeStub({'SELECT id, name, local_path, last_commit, last_sync_at, config, created_at': [{id: 'gstack',@@ -114,7 +115,8 @@ describe('sources add', () => {expect(insert!.params[0]).toBe('gstack');expect(insert!.params[1]).toBe('gstack'); // name defaults to idexpect(insert!.params[2]).toBe('/tmp/gstack');- expect(insert!.params[3]).toBe('{}'); // federated unset → empty config+ // A shared brain keeps the old unset default: test/sources-add-default-search.test.ts.+ expect(insert!.params[3]).toBe('{"federated":true}');});test('--federated sets config.federated = true', async () => {@@ -174,12 +176,14 @@ describe('sources add — #2707 --force flag wiring', () => {beforeEach(() => {plainDir = mkdtempSync(join(tmpdir(), 'gbrain-sources-cli-2707-'));+ // GST-2732: a folder outside any repository registers as plain; the refusal is for a repository with nothing committed.+ execFileSync('git', ['-C', plainDir, 'init', '-q']);});afterEach(() => {rmSync(plainDir, { recursive: true, force: true });});- test('rejects a real non-git --path directory by default', async () => {+ test('rejects a git repository with nothing committed by default', async () => {const { engine } = makeStub();await expect(runSources(engine, ['add', 'cli-plain', '--path', plainDir])).rejects.toThrow(/not a git repository/);diff --git a/test/sync-plain-directory-7973.test.ts b/test/sync-plain-directory-7973.test.tsindex 30b06b6564..1cf3f00ac4 100644--- a/test/sync-plain-directory-7973.test.ts+++ b/test/sync-plain-directory-7973.test.ts@@ -10,6 +10,7 @@ import { afterAll, beforeAll, describe, expect, test } from 'bun:test';import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';+import { execFileSync } from 'node:child_process';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { withEnv } from './helpers/with-env.ts';import { performSync } from '../src/commands/sync.ts';@@ -64,9 +65,19 @@ describe.each(backends.map(url => [engineName(url), url] as const))('plain-direc}), 180_000);});-test('sources add without --force names what sync does with a forced plain directory', () => managedBrain(async ({ engine, root }) => {+test('a plain folder outside any git repository registers without --force (GST-2732)', () => managedBrain(async ({ engine, root }) => {+ const dir = join(root, '..', 'plain-folder');+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, 'note.md'), '# A note\n');+ await runManagedSourceLifecycle(engine, { operation: 'add', sourceId: 'source-b', path: dir, requireGitContent: true });+ const [row] = await engine.executeRaw<{ id: string }>("SELECT id FROM sources WHERE id='source-b'");+ expect(row?.id).toBe('source-b');+}), 120_000);++test('sources add without --force refuses a git repository with nothing committed and names what --force does', () => managedBrain(async ({ engine, root }) => {const dir = join(root, '..', 'plain-notes');mkdirSync(dir, { recursive: true });+ execFileSync('git', ['-C', dir, 'init', '-q']);await expect(runManagedSourceLifecycle(engine, { operation: 'add', sourceId: 'source-a', path: dir, requireGitContent: true })).rejects.toMatchObject({ code: 'not_a_git_repo', suggestion: expect.stringContaining('sync then imports its files without Git') });}), 120_000);