Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sources): validate --path is a git repo with committed content at registration (#2707) (#2975)

Masa2934c53c1d5a
diff --git a/docs/guides/multi-source-brains.md b/docs/guides/multi-source-brains.md
index 084605598f..da73fea7d6 100644
--- a/docs/guides/multi-source-brains.md
+++ b/docs/guides/multi-source-brains.md
@@ -114,8 +114,11 @@ Flip later with `gbrain sources federate <id>` / `unfederate <id>`.
Full subcommand reference:
```
-gbrain sources add <id> --path <p> [--name <n>] [--federated|--no-federated]
+gbrain sources add <id> --path <p> [--name <n>] [--federated|--no-federated] [--force]
Register a source. id: [a-z0-9](?:[a-z0-9-]{0,30}[a-z0-9])?
+ --path must be a git repo (or a subdirectory of one) — see
+ "The git requirement for --path sources" below. --force
+ skips that check to register before git-init exists.
gbrain sources list [--json] List all sources with page counts + federation state.
gbrain sources remove <id> [--yes] [--dry-run] [--keep-storage]
Cascade-delete a source (pages, chunks, timeline).
@@ -128,6 +131,47 @@ gbrain sources federate <id>
gbrain sources unfederate <id>
```
+## 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
+(or worse, "succeed" while importing nothing) on its first `gbrain sync`.
+Fix it with:
+
+```bash
+git -C <path> init
+git -C <path> add -A
+git -C <path> commit -m "initial import"
+gbrain sources add <id> --path <path>
+```
+
+Two details that are easy to miss:
+
+- **Files must actually be committed, not just present.** The sync walker
+ reads files through git objects, so `git init` alone — even followed by an
+ empty commit (`git commit --allow-empty`) — isn't enough. Registration
+ checks for real tracked content (`git ls-tree HEAD` scoped to the path),
+ not just a resolvable `HEAD`, so this footgun is caught immediately
+ instead of surfacing later as a sync that imports nothing.
+- **`--force` registers the source anyway**, skipping the check. Use this if
+ you're registering a path before an automated pipeline gets around to
+ `git init`-ing it. GBrain never auto-`git init`s a `--path` source for
+ you — it's your directory, not a gbrain-managed clone (same consent
+ boundary as sync-time self-heal, which also never mutates a `--path`
+ source without an explicit ask).
+
+**If sync ever reports a problem with the sync anchor** (`last_commit`) —
+after a force-push, a history rewrite, or a from-scratch `git init` on a
+directory that was synced before — you do not need to reset anything by
+hand. `gbrain sync` detects an unreachable or non-ancestor anchor
+automatically and recovers: either a full reimport (anchor object missing)
+or a direct tree-to-tree diff against the orphaned bookmark (anchor present
+but rewritten), advancing the anchor to the new HEAD when it completes.
+
## Citation format for agents
When agents receive multi-source results they MUST cite pages in
diff --git a/src/commands/sources.ts b/src/commands/sources.ts
index 38e4fe317f..13c52918b1 100644
--- a/src/commands/sources.ts
+++ b/src/commands/sources.ts
@@ -7,7 +7,9 @@
* full story.
*
* Subcommands:
- * gbrain sources add <id> --path <path> [--name <display>] [--federated|--no-federated]
+ * gbrain sources add <id> --path <path> [--name <display>] [--federated|--no-federated] [--force]
+ * --path must be a git-initialized repo (files committed,
+ * not just present) — #2707. --force skips the check.
* gbrain sources list [--json]
* gbrain sources remove <id> [--yes] [--dry-run] [--keep-storage]
* gbrain sources rename <id> <new-name>
@@ -120,7 +122,7 @@ async function runAdd(engine: BrainEngine, args: string[]): Promise<void> {
if (!id) {
console.error(
'Usage: gbrain sources add <id> [--path <path> | --url <https-url>] ' +
- '[--name <display>] [--federated|--no-federated] [--clone-dir <path>]',
+ '[--name <display>] [--federated|--no-federated] [--clone-dir <path>] [--force]',
);
process.exit(2);
}
@@ -132,6 +134,7 @@ async function runAdd(engine: BrainEngine, args: string[]): Promise<void> {
let cloneDir: string | undefined;
let patFile: string | undefined;
let noHarden = false;
+ let force = false;
for (let i = 1; i < args.length; i++) {
const a = args[i];
@@ -143,6 +146,7 @@ async function runAdd(engine: BrainEngine, args: string[]): Promise<void> {
if (a === '--clone-dir') { cloneDir = args[++i]; continue; }
if (a === '--pat-file') { patFile = args[++i]; continue; }
if (a === '--no-harden') { noHarden = true; continue; }
+ if (a === '--force') { force = true; continue; }
console.error(`Unknown flag: ${a}`);
process.exit(2);
}
@@ -162,6 +166,7 @@ async function runAdd(engine: BrainEngine, args: string[]): Promise<void> {
remoteUrl,
federated,
cloneDir,
+ force,
});
// Topology A discovery: if the just-added source carries a brain-resident
@@ -1368,8 +1373,9 @@ function printHelp(): void {
console.log(`gbrain sources — manage multi-source brain configuration (v0.26.5)
Subcommands:
- add <id> --path <p> [--name <n>] [--federated|--no-federated]
- Register a new source.
+ add <id> --path <p> [--name <n>] [--federated|--no-federated] [--force]
+ Register a new source. --path must be a git repo
+ with committed files; --force skips that check.
list [--json] List registered sources with page counts.
remove <id> [--confirm-destructive] [--dry-run]
Permanently delete a source and all its data.
diff --git a/src/core/git-remote.ts b/src/core/git-remote.ts
index d3673c29b1..8bd5df504a 100644
--- a/src/core/git-remote.ts
+++ b/src/core/git-remote.ts
@@ -303,6 +303,83 @@ export function validateRepoState(
return 'healthy';
}
+/**
+ * True if `path` is itself a git repo OR a subdirectory of one, per
+ * `git rev-parse --show-toplevel`. Mirrors the walk-up discovery
+ * `sync.ts:discoverGitRoot` performs at sync time (#753/#774 — subdir-of-git
+ * sources are valid), so a directory that passes this check is guaranteed
+ * not to hit sync's "Not inside a git repository" error later. Used by
+ * `addSource` (#2707) to validate `--path` at registration time instead of
+ * deferring the failure to the first sync.
+ */
+export function isInsideGitRepo(path: string): boolean {
+ try {
+ execFileSync('git', ['-C', path, 'rev-parse', '--show-toplevel'], {
+ stdio: ['ignore', 'pipe', 'pipe'],
+ timeout: 10_000,
+ env: { ...process.env, ...GIT_ENV },
+ });
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * The empty-tree object ID for `path`'s repo, derived (not hardcoded) so
+ * this works for both the default SHA-1 object format and the opt-in
+ * `--object-format=sha256` one (git 2.29+) — each has its own empty-tree
+ * OID. `git hash-object -t tree --stdin < /dev/null` computes the hash of
+ * a zero-entry tree using whatever hash algorithm `path`'s repo is
+ * configured for, without needing to know which one that is. #2707 codex
+ * round 4 (P2): an earlier version hardcoded the well-known SHA-1 constant
+ * (`4b825dc6...`), which silently mismatched — and so let an empty
+ * SHA-256 repo through — on a SHA-256 repo's real (different) empty-tree
+ * OID.
+ */
+function emptyTreeOid(path: string): string {
+ return execFileSync('git', ['-C', path, 'hash-object', '-t', 'tree', '--stdin'], {
+ input: '',
+ stdio: ['pipe', 'pipe', 'pipe'],
+ timeout: 10_000,
+ env: { ...process.env, ...GIT_ENV },
+ }).toString().trim();
+}
+
+/**
+ * True if `path`'s HEAD tree has at least one tracked entry scoped to
+ * `path` itself. `-C path` + the `HEAD:./` revision syntax resolves the
+ * tree object for `path` specifically (not the whole repo root), so this
+ * is correct for both a repo's toplevel AND a subdirectory-of-a-repo
+ * source — then a single OID comparison against that repo's empty-tree
+ * object (see `emptyTreeOid`) tells us whether that tree is empty. #2707
+ * codex round 3 (P2): unlike listing (`ls-tree`), this is O(1) output — no
+ * `maxBuffer` exposure on a repo with a very large number of entries.
+ *
+ * Subsumes "no commits at all" (`HEAD:./` on an unborn repo fails to
+ * resolve — there's no HEAD) AND "has a HEAD commit but it's empty"
+ * (#2707 codex round 2): `git commit --allow-empty` followed by creating
+ * untracked files resolves `HEAD:./` successfully (to the empty-tree OID)
+ * but that tree has zero entries — a directory that would pass a bare
+ * `rev-parse HEAD` check yet still can't sync (or worse, "succeeds"
+ * importing nothing and then never notices the untracked files change —
+ * the silent-staleness class #2707 exists to prevent). A directory
+ * that's `git init`ed but never committed, or where this specific path
+ * was never `git add`ed, fails this check either way.
+ */
+export function hasTrackedContent(path: string): boolean {
+ try {
+ const out = execFileSync('git', ['-C', path, 'rev-parse', '--verify', 'HEAD:./'], {
+ stdio: ['ignore', 'pipe', 'pipe'],
+ timeout: 10_000,
+ env: { ...process.env, ...GIT_ENV },
+ });
+ return out.toString().trim() !== emptyTreeOid(path);
+ } catch {
+ return false;
+ }
+}
+
// ── Durability helpers (v0.42.44) ───────────────────────────────────────────
// Used by the brain-repo durability feature (`gbrain sources harden/pull`) and
// the DB-free pull cron. These are the auth-capable, rebase-aware counterparts
diff --git a/src/core/sources-ops.ts b/src/core/sources-ops.ts
index 9edcfedbe5..98268a8c5d 100644
--- a/src/core/sources-ops.ts
+++ b/src/core/sources-ops.ts
@@ -45,6 +45,8 @@ import {
parseRemoteUrl,
cloneRepo,
validateRepoState,
+ isInsideGitRepo,
+ hasTrackedContent,
RemoteUrlError,
GitOperationError,
type RepoState,
@@ -67,7 +69,8 @@ export type SourceOpErrorCode =
| 'protected_id'
| 'clone_dir_outside_gbrain'
| 'symlink_escape'
- | 'unmanaged_path';
+ | 'unmanaged_path'
+ | 'not_a_git_repo';
export class SourceOpError extends Error {
constructor(
@@ -145,6 +148,13 @@ export interface AddSourceOpts {
* Only honored when remoteUrl is set.
*/
cloneDir?: string;
+ /**
+ * Skip the #2707 git-repo validation on `localPath`. Opt-in escape hatch
+ * for registering a path before it's git-initialized (e.g. an automated
+ * pipeline that populates + `git init`s the directory after `sources add`
+ * runs). Does NOT auto-`git init` anything — see `addSource` docstring.
+ */
+ force?: boolean;
}
export interface RemoveSourceOpts {
@@ -157,6 +167,20 @@ export interface RemoveSourceOpts {
// ── Helpers ─────────────────────────────────────────────────────────────────
+/**
+ * POSIX single-quote `arg` unless it's already shell-safe. #2707 codex round
+ * 1: the `not_a_git_repo` remediation error prints a pasteable `git ...`
+ * command built from the caller-supplied path — spaces, `$()`, backticks,
+ * etc. must be inert literals when pasted, which double-quoting would not
+ * guarantee (command substitution still runs inside "..."). Mirrors
+ * `src/commands/connect.ts:shellQuote` (not imported — that file is a
+ * commands/ caller of core/, not the other way around).
+ */
+function shellQuote(arg: string): string {
+ if (/^[A-Za-z0-9_.:/@-]+$/.test(arg)) return arg;
+ return `'${arg.replace(/'/g, "'\\''")}'`;
+}
+
/**
* Validate via the canonical regex from `source-id.ts` but rethrow as the
* sources-ops-tagged error so `gbrain sources add` keeps its user-facing
@@ -310,6 +334,18 @@ export function unownedHint(
// ── addSource ───────────────────────────────────────────────────────────────
+/**
+ * #2707: `--path` registration used to accept any existing directory with
+ * zero git validation, deferring the failure to the first `gbrain sync`
+ * ("Not inside a git repository: ..."). By the time that surfaces the
+ * source has already been silently stale for however long nobody read the
+ * sync logs. This is registration-time, fail-fast validation ONLY — it
+ * never auto-`git init`s the directory (that would cross the consent
+ * boundary #2967 established for sync-time self-heal: a `--path` source is
+ * the user's own external directory, and gbrain must not mutate it without
+ * explicit ask). Callers who want to register before git-init exists opt in
+ * via `force: true` (CLI: `--force`).
+ */
export async function addSource(
engine: BrainEngine,
opts: AddSourceOpts,
@@ -437,6 +473,37 @@ export async function addSource(
}
} else {
// ── Path B: --path or no path (existing behavior, pre-v0.28) ─────────
+ // #2707: only validate when the path actually exists — a not-yet-created
+ // path is a different (pre-existing, out of scope) failure mode, and
+ // gating on existsSync keeps this a fail-fast check on the exact bug
+ // 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
+ // 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"
+ // importing nothing, then never notices the untracked files change).
+ // hasTrackedContent's `ls-tree HEAD -- .` catches both (codex round 2).
+ if (
+ opts.localPath &&
+ !opts.force &&
+ existsSync(opts.localPath) &&
+ (!isInsideGitRepo(opts.localPath) || !hasTrackedContent(opts.localPath))
+ ) {
+ const q = shellQuote(opts.localPath);
+ throw new SourceOpError(
+ 'not_a_git_repo',
+ `"${opts.localPath}" is not a git repository with committed, tracked files ` +
+ `(or a subdirectory of one). GBrain sync requires every --path source to ` +
+ `be git-initialized, with the files actually committed — an empty commit ` +
+ `is not enough (the walker reads through git objects, so untracked files ` +
+ `stay invisible). Fix: \`git -C ${q} init && git -C ${q} add -A && ` +
+ `git -C ${q} commit -m "initial import"\`, then re-run this command. To ` +
+ `register anyway and git-init later, pass --force.`,
+ );
+ }
const config: Record<string, unknown> = {};
if (opts.federated !== null && opts.federated !== undefined) {
config.federated = opts.federated;
diff --git a/test/sources-ops.test.ts b/test/sources-ops.test.ts
index 1098c52679..0a68f10ae4 100644
--- a/test/sources-ops.test.ts
+++ b/test/sources-ops.test.ts
@@ -15,6 +15,7 @@ import {
} from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
+import { execFileSync } from 'child_process';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import {
addSource,
@@ -358,7 +359,10 @@ describe('removeSource — clone-cleanup', () => {
const userPath = join(GBRAIN_HOME, 'user-managed-fixture');
mkdirSync(userPath, { recursive: true });
writeFileSync(join(userPath, 'file'), 'hi');
- await addSource(engine, { id: 'cleanup-no', localPath: userPath });
+ // #2707: this fixture is intentionally not a git repo (unrelated to
+ // what this test covers — clone-cleanup ownership) — force past the
+ // registration-time git check.
+ await addSource(engine, { id: 'cleanup-no', localPath: userPath, force: true });
const result = await removeSource(engine, {
id: 'cleanup-no',
confirmDestructive: true,
@@ -485,8 +489,10 @@ describe('getSourceStatus', () => {
// path-only source still gets validateRepoState — but with no expected
// URL, it just probes existence + .git. Path exists with no .git → 'no-git'.
// To match contract docstring we'd want 'not-applicable' only when
- // local_path is null. Test the truthful behavior:
- await addSource(engine, { id: 'status-no-url', localPath: userPath });
+ // local_path is null. Test the truthful behavior. #2707: this fixture
+ // is deliberately no-git (that's what's under test for getSourceStatus)
+ // — force past the registration-time git check to construct it.
+ await addSource(engine, { id: 'status-no-url', localPath: userPath, force: true });
const s = await getSourceStatus(engine, 'status-no-url');
// local_path set but no .git: returns 'no-git'
expect(s.clone_state).toBe('no-git');
@@ -814,6 +820,252 @@ describe('addSource --url — writes ownership marker', () => {
});
});
+// ---------------------------------------------------------------------------
+// addSource --path — #2707 git-repo validation at registration time
+//
+// Deliberately does NOT run under withEnv2 (the fake-git harness above):
+// writeFakeGit()'s catch-all `exit 0` would make `rev-parse --show-toplevel`
+// (and therefore isInsideGitRepo) succeed unconditionally for any path,
+// which defeats the point of these tests. Real system git applies here.
+// ---------------------------------------------------------------------------
+
+describe('addSource --path — #2707 git-repo validation', () => {
+ const SANDBOX = join(tmpdir(), `gbrain-2707-git-validate-${process.pid}`);
+
+ beforeEach(() => {
+ rmSync(SANDBOX, { recursive: true, force: true });
+ mkdirSync(SANDBOX, { recursive: true });
+ });
+ afterAll(() => {
+ rmSync(SANDBOX, { recursive: true, force: true });
+ });
+
+ test('rejects an existing non-git directory with an actionable error', async () => {
+ const plainDir = join(SANDBOX, 'plain');
+ mkdirSync(plainDir, { recursive: true });
+ writeFileSync(join(plainDir, 'notes.md'), 'not committed anywhere');
+
+ let threw: SourceOpError | undefined;
+ try {
+ await addSource(engine, { id: 'plain-src', localPath: plainDir });
+ } catch (e) {
+ threw = e as SourceOpError;
+ }
+ expect(threw).toBeInstanceOf(SourceOpError);
+ expect(threw?.code).toBe('not_a_git_repo');
+ expect(threw?.message).toContain(plainDir);
+ expect(threw?.message).toContain('--force');
+ expect(threw?.message).toMatch(/git .*init/);
+
+ // Source was never registered — no partial row left behind.
+ const rows = await engine.executeRaw<{ id: string }>(
+ `SELECT id FROM sources WHERE id = 'plain-src'`,
+ );
+ expect(rows.length).toBe(0);
+ });
+
+ test('rejects a git-initialized directory with zero commits (codex round 1)', async () => {
+ const unbornDir = join(SANDBOX, 'unborn');
+ mkdirSync(unbornDir, { recursive: true });
+ execFileSync('git', ['-C', unbornDir, 'init', '-q']);
+ // No `git add` / `git commit` — isInsideGitRepo alone would pass this.
+
+ let threw: SourceOpError | undefined;
+ try {
+ await addSource(engine, { id: 'unborn-src', localPath: unbornDir });
+ } catch (e) {
+ threw = e as SourceOpError;
+ }
+ expect(threw).toBeInstanceOf(SourceOpError);
+ expect(threw?.code).toBe('not_a_git_repo');
+ });
+
+ test('rejects an empty-commit repo whose files are untracked (codex round 2)', async () => {
+ // git commit --allow-empty gives a resolvable HEAD (so a bare "has a
+ // commit" check would wrongly pass this) but the tree is empty; files
+ // written afterward are untracked and invisible to the sync walker.
+ const emptyCommitDir = join(SANDBOX, 'empty-commit');
+ mkdirSync(emptyCommitDir, { recursive: true });
+ execFileSync('git', ['-C', emptyCommitDir, 'init', '-q']);
+ execFileSync('git', ['-C', emptyCommitDir, 'config', 'user.email', '[email protected]']);
+ execFileSync('git', ['-C', emptyCommitDir, 'config', 'user.name', 'Test']);
+ execFileSync('git', ['-C', emptyCommitDir, 'commit', '--allow-empty', '-q', '-m', 'empty']);
+ writeFileSync(join(emptyCommitDir, 'notes.md'), 'never committed');
+
+ let threw: SourceOpError | undefined;
+ try {
+ await addSource(engine, { id: 'empty-commit-src', localPath: emptyCommitDir });
+ } catch (e) {
+ threw = e as SourceOpError;
+ }
+ expect(threw).toBeInstanceOf(SourceOpError);
+ expect(threw?.code).toBe('not_a_git_repo');
+ });
+
+ test('rejects an untracked subdirectory of an otherwise-real git repo (codex round 2)', async () => {
+ const parent = join(SANDBOX, 'partial-repo');
+ const trackedFile = join(parent, 'README.md');
+ const untrackedSub = join(parent, 'untracked-sub');
+ mkdirSync(untrackedSub, { recursive: true });
+ writeFileSync(trackedFile, '# fixture');
+ execFileSync('git', ['-C', parent, 'init', '-q']);
+ execFileSync('git', ['-C', parent, 'config', 'user.email', '[email protected]']);
+ execFileSync('git', ['-C', parent, 'config', 'user.name', 'Test']);
+ execFileSync('git', ['-C', parent, 'add', 'README.md']);
+ execFileSync('git', ['-C', parent, 'commit', '-q', '-m', 'initial import']);
+ writeFileSync(join(untrackedSub, 'x.md'), 'never git add-ed');
+
+ let threw: SourceOpError | undefined;
+ try {
+ await addSource(engine, { id: 'partial-repo-src', localPath: untrackedSub });
+ } catch (e) {
+ threw = e as SourceOpError;
+ }
+ expect(threw).toBeInstanceOf(SourceOpError);
+ expect(threw?.code).toBe('not_a_git_repo');
+ });
+
+ test('registers a repo with many tracked entries without buffer-size false rejection (codex round 3)', async () => {
+ // Codex round 3 (P2): the earlier `git ls-tree` listing implementation
+ // buffered the whole tree and could exceed execFileSync's default 1 MiB
+ // maxBuffer on a large repo, causing an incorrect rejection. The
+ // rev-parse HEAD:./ + empty-tree-SHA-comparison implementation reads a
+ // fixed ~40-byte SHA regardless of tree size — this locks that in.
+ const bigDir = join(SANDBOX, 'many-entries');
+ mkdirSync(bigDir, { recursive: true });
+ for (let i = 0; i < 300; i++) {
+ writeFileSync(join(bigDir, `file-${i}.md`), `# entry ${i}`);
+ }
+ execFileSync('git', ['-C', bigDir, 'init', '-q']);
+ execFileSync('git', ['-C', bigDir, 'config', 'user.email', '[email protected]']);
+ execFileSync('git', ['-C', bigDir, 'config', 'user.name', 'Test']);
+ execFileSync('git', ['-C', bigDir, 'add', '-A']);
+ execFileSync('git', ['-C', bigDir, 'commit', '-q', '-m', 'many files']);
+
+ const row = await addSource(engine, { id: 'many-entries-src', localPath: bigDir });
+ expect(row.local_path).toBe(bigDir);
+ });
+
+ // Codex round 4 (P2): the empty-tree OID is hash-algorithm-specific — a
+ // hardcoded SHA-1 constant silently mismatched (and so accepted) an empty
+ // SHA-256 repo. --object-format=sha256 needs git 2.29+; skip rather than
+ // hard-fail on an older CI git.
+ const SHA256_SUPPORTED = (() => {
+ try {
+ const probe = join(tmpdir(), `gbrain-2707-sha256-probe-${process.pid}`);
+ mkdirSync(probe, { recursive: true });
+ execFileSync('git', ['-C', probe, 'init', '-q', '--object-format=sha256'], {
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ rmSync(probe, { recursive: true, force: true });
+ return true;
+ } catch {
+ return false;
+ }
+ })();
+
+ test.skipIf(!SHA256_SUPPORTED)(
+ 'rejects an empty-commit SHA-256 repo the same as a SHA-1 one (codex round 4)',
+ async () => {
+ const sha256Dir = join(SANDBOX, 'sha256-empty');
+ mkdirSync(sha256Dir, { recursive: true });
+ execFileSync('git', ['-C', sha256Dir, 'init', '-q', '--object-format=sha256']);
+ execFileSync('git', ['-C', sha256Dir, 'config', 'user.email', '[email protected]']);
+ execFileSync('git', ['-C', sha256Dir, 'config', 'user.name', 'Test']);
+ execFileSync('git', ['-C', sha256Dir, 'commit', '--allow-empty', '-q', '-m', 'empty']);
+ writeFileSync(join(sha256Dir, 'notes.md'), 'never committed');
+
+ let threw: SourceOpError | undefined;
+ try {
+ await addSource(engine, { id: 'sha256-empty-src', localPath: sha256Dir });
+ } catch (e) {
+ threw = e as SourceOpError;
+ }
+ expect(threw).toBeInstanceOf(SourceOpError);
+ expect(threw?.code).toBe('not_a_git_repo');
+ },
+ );
+
+ test.skipIf(!SHA256_SUPPORTED)(
+ 'registers a SHA-256 repo with real committed content (no regression)',
+ async () => {
+ const sha256Dir = join(SANDBOX, 'sha256-real');
+ mkdirSync(sha256Dir, { recursive: true });
+ writeFileSync(join(sha256Dir, 'README.md'), '# fixture');
+ execFileSync('git', ['-C', sha256Dir, 'init', '-q', '--object-format=sha256']);
+ execFileSync('git', ['-C', sha256Dir, 'config', 'user.email', '[email protected]']);
+ execFileSync('git', ['-C', sha256Dir, 'config', 'user.name', 'Test']);
+ execFileSync('git', ['-C', sha256Dir, 'add', '-A']);
+ execFileSync('git', ['-C', sha256Dir, 'commit', '-q', '-m', 'initial import']);
+
+ const row = await addSource(engine, { id: 'sha256-real-src', localPath: sha256Dir });
+ expect(row.local_path).toBe(sha256Dir);
+ },
+ );
+
+ 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 });
+
+ let threw: SourceOpError | undefined;
+ try {
+ await addSource(engine, { id: 'spaced-src', localPath: spacedDir });
+ } catch (e) {
+ threw = e as SourceOpError;
+ }
+ expect(threw?.message).toContain(`'${spacedDir}'`);
+ });
+
+ test('--force bypasses the check and registers the plain directory as-is', async () => {
+ const plainDir = join(SANDBOX, 'plain-forced');
+ mkdirSync(plainDir, { recursive: true });
+
+ const row = await addSource(engine, {
+ id: 'plain-forced-src',
+ localPath: plainDir,
+ force: true,
+ });
+ expect(row.local_path).toBe(plainDir);
+ });
+
+ test('an already git-initialized directory registers unaffected (no regression)', async () => {
+ const gitDir = join(SANDBOX, 'gitrepo');
+ mkdirSync(gitDir, { recursive: true });
+ writeFileSync(join(gitDir, 'README.md'), '# fixture');
+ execFileSync('git', ['-C', gitDir, 'init', '-q']);
+ execFileSync('git', ['-C', gitDir, 'config', 'user.email', '[email protected]']);
+ execFileSync('git', ['-C', gitDir, 'config', 'user.name', 'Test']);
+ execFileSync('git', ['-C', gitDir, 'add', '-A']);
+ execFileSync('git', ['-C', gitDir, 'commit', '-q', '-m', 'initial import']);
+
+ const row = await addSource(engine, { id: 'gitrepo-src', localPath: gitDir });
+ expect(row.local_path).toBe(gitDir);
+ });
+
+ test('a subdirectory of a git repo registers unaffected (#753/#774 parity with sync-time discovery)', async () => {
+ const gitDir = join(SANDBOX, 'gitrepo-parent');
+ const subDir = join(gitDir, 'sub');
+ mkdirSync(subDir, { recursive: true });
+ writeFileSync(join(subDir, 'README.md'), '# fixture');
+ execFileSync('git', ['-C', gitDir, 'init', '-q']);
+ execFileSync('git', ['-C', gitDir, 'config', 'user.email', '[email protected]']);
+ execFileSync('git', ['-C', gitDir, 'config', 'user.name', 'Test']);
+ execFileSync('git', ['-C', gitDir, 'add', '-A']);
+ execFileSync('git', ['-C', gitDir, 'commit', '-q', '-m', 'initial import']);
+
+ const row = await addSource(engine, { id: 'subdir-src', localPath: subDir });
+ expect(row.local_path).toBe(subDir);
+ });
+
+ test('a not-yet-created path is unaffected (pre-existing lenient behavior, out of #2707 scope)', async () => {
+ const missingDir = join(SANDBOX, 'does-not-exist-yet');
+ expect(existsSync(missingDir)).toBe(false);
+
+ const row = await addSource(engine, { id: 'missing-src', localPath: missingDir });
+ expect(row.local_path).toBe(missingDir);
+ });
+});
+
// ---------------------------------------------------------------------------
// isPathContained — symlink-safe confinement helper (exported for reuse)
// ---------------------------------------------------------------------------
diff --git a/test/sources.test.ts b/test/sources.test.ts
index f5122655c1..73a6bfff75 100644
--- a/test/sources.test.ts
+++ b/test/sources.test.ts
@@ -6,7 +6,10 @@
* shape, validation, and flag parsing.
*/
-import { describe, test, expect, beforeEach } from 'bun:test';
+import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
+import { mkdtempSync, mkdirSync, rmSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
import { runSources } from '../src/commands/sources.ts';
import type { BrainEngine } from '../src/core/engine.ts';
@@ -158,6 +161,47 @@ describe('sources add', () => {
});
});
+// ── add — #2707 git-repo validation (CLI wiring) ───────────────
+//
+// Uses a REAL on-disk temp dir (unlike the fake-path tests above) so the
+// core addSource git check actually runs; the stub engine still fakes the
+// DB round-trip. Confirms --force parses through to opsAddSource.
+
+describe('sources add — #2707 --force flag wiring', () => {
+ let plainDir: string;
+
+ beforeEach(() => {
+ plainDir = mkdtempSync(join(tmpdir(), 'gbrain-sources-cli-2707-'));
+ });
+ afterEach(() => {
+ rmSync(plainDir, { recursive: true, force: true });
+ });
+
+ test('rejects a real non-git --path directory by default', async () => {
+ const { engine } = makeStub();
+ await expect(runSources(engine, ['add', 'cli-plain', '--path', plainDir]))
+ .rejects.toThrow(/not a git repository/);
+ });
+
+ test('--force registers the same directory anyway', async () => {
+ const { engine, calls } = makeStub({
+ 'SELECT id, name, local_path, last_commit, last_sync_at, config, created_at': [{
+ id: 'cli-forced',
+ name: 'cli-forced',
+ local_path: plainDir,
+ last_commit: null,
+ last_sync_at: null,
+ config: '{}',
+ created_at: new Date(),
+ }],
+ });
+ await runSources(engine, ['add', 'cli-forced', '--path', plainDir, '--force']);
+ const insert = calls.find(c => c.sql.includes('INSERT INTO sources'));
+ expect(insert).toBeDefined();
+ expect(insert!.params[2]).toBe(plainDir);
+ });
+});
+
// ── list ────────────────────────────────────────────────────
describe('sources list', () => {
diff --git a/test/sync-sole-non-default-routing.test.ts b/test/sync-sole-non-default-routing.test.ts
index 7eaff54ba8..f3b3411b3e 100644
--- a/test/sync-sole-non-default-routing.test.ts
+++ b/test/sync-sole-non-default-routing.test.ts
@@ -164,9 +164,13 @@ describe('#1434 — runSync auto-routes to sole_non_default source', () => {
test('2+ non-default sources: no auto-route, no nudge, falls through to default', async () => {
// Both need local_path to be counted by the sole_non_default helper.
// Pre-existing helper filters local_path IS NOT NULL.
+ // secondRepo is a bare temp dir (no git init) — its content is
+ // irrelevant to what this test verifies (that 2+ non-default sources
+ // disable auto-routing); --force skips #2707's registration-time git
+ // validation, which is orthogonal to this test's assertion.
const secondRepo = mkdtempSync(join(tmpdir(), 'gbrain-snd-routing-second-'));
await runSources(engine, ['add', 'studiovault', '--path', repoPath, '--no-federated']);
- await runSources(engine, ['add', 'second-vault', '--path', secondRepo, '--no-federated']);
+ await runSources(engine, ['add', 'second-vault', '--path', secondRepo, '--no-federated', '--force']);
const { runSync } = await import('../src/commands/sync.ts');
const origWrite = process.stderr.write.bind(process.stderr);