Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(import): walk an explicitly named directory that the enclosing git repo ignores; scale harness validates a reused corpus

garrytanc3770114f738
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4071b3a741..8642e139b6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -71,6 +71,7 @@ The CI scale tier now runs this harness at 10k pages on every change that touche
- **`gbrain embed --stale` stopped by its 30-minute budget with chunks left exits 11** (was 0) and prints `remaining_stale` and the resume command; failures still exit 1. Doctor `embeddings` reports the backlog with `gbrain embed --stale --catch-up`, and reports "not applicable" on a keyless brain.
- **A sync that keeps making progress is no longer stopped by its default or environment deadline.** It stops only after `GBRAIN_SYNC_STALL_ABORT_SECONDS` (900) without progress, with `code=sync_deadline_stop` and the resume command. `--hard-deadline` and `--timeout` stay strict.
- **`gbrain serve`'s boot deadline counts time without progress,** so a large brain's slow but advancing boot (or a serve already answering tool calls) is not killed. `GBRAIN_SERVE_BOOT_TIMEOUT_SECONDS=0` still disables it.
+- **`gbrain import <dir>` imports a directory its enclosing git repository ignores** (a scratch folder inside a checkout) instead of reporting success with zero files. Importing a repository itself still honors its `.gitignore`.
- **Writes to a checkout that `gbrain sources refresh` is draining or merging are refused** with `worktree_refreshing` (retry the same request id after about a second); database-only memory writes are not affected.
### Itemized changes
diff --git a/docs/architecture/key-files/commands-4.md b/docs/architecture/key-files/commands-4.md
index 26f38a5820..558d38c829 100644
--- a/docs/architecture/key-files/commands-4.md
+++ b/docs/architecture/key-files/commands-4.md
@@ -5,7 +5,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/graph-query.ts` — `gbrain graph-query <slug> [--type T] [--depth N] [--direction in|out|both] [--source <id>] [--include-foreign]`: typed-edge relationship traversal (renders indented tree). The local walk is scoped to the resolved source (`--source` / `GBRAIN_SOURCE` / `.gbrain-source` / path match / brain default via `resolveSourceId`, the same scalar scope the `traverse_graph` op gets from `sourceScopeOpts`); an explicit `--source` that fails to resolve throws. `--include-foreign` (or `--source __all__`) drops the scope so the walk spans every source. The foreign-edge footer (`N edges to foreign-source pages hidden; pass --include-foreign`) prints only when the walk was actually scoped, so cross-source edges never disappear silently and the footer never describes a filter that did not apply. The local path uses `engine.traversePathsDetailed` and prints a stderr note when the walk hit `TRAVERSE_PATH_ROW_CAP` (shallowest edges kept; lower `--depth` or narrow with `--type`/`--direction`); the thin-client path goes through the `traverse_graph` op, which has no `source_id` param (the server scopes the walk to the caller's grant): an explicit `--source` there is rejected with exit 1 (same policy + wording as `applyThinClientSourceScope`, never silently dropped) and `--include-foreign` prints a stderr note that it is not forwarded. Pinned by `test/graph-query.test.ts` (local) + `test/graph-query-thin-client-source-flag.serial.test.ts` (thin client; mocks `isThinClient` + `callRemoteTool`).
-- `src/commands/import.ts` — `gbrain import <path> [--source-id <id> | --source <id>]`: page import with ordinary-import progress checkpoints and content-hash revalidation; company-brain ingestion resumes an approved committed manifest. `runImport` contains NO `process.exit`: all five preflight/argv failure sites (deferred-setup embedding sentinel, missing embedding credentials, invalid `--workers`, missing dir arg, unreadable target) throw the exported typed `ImportAbortError` (carries `exitCode`; the user-facing message is printed at the throw site), so in-process callers — the `sync_brain` MCP op, autopilot, the Minions `import` handler — survive a failed preflight as a normal tool/job error instead of the whole serving process dying mid-call. The CLI's `import` case catches it and exits `e.exitCode`. Pinned by `test/import-abort-error.test.ts`. Human-only output (the `info()` lines and the end-of-run `Import complete` summary) goes through `slog()` from `console-prefix.ts` — identical to `console.log` outside a wrap, but an in-process caller in its own `--json` mode (`sync --json` → `performFullSync` → `runImport`, wrapped in `withHumanLogsToStderr`) keeps stdout pure JSON; `import --json` itself sends them to stderr directly. Pinned by `test/sync-json-stdout-clean.test.ts` (first-sync case) + `test/import-json-stdout.serial.test.ts`. The `--json` payload also carries `source_id`, the effective destination the pages were written to (`sourceId ?? 'default'`, identical to the ingest_log row and to the import-file write) — NOT the resolver's tier answer, since `runImport` adopts only flag/env/sole_non_default resolutions and lets dotfile/local_path/brain_default fall through to `default`; pinned by the `--json payload names …` cases in `test/import-source-id.test.ts`. `--source-id <id>` (alias `--source <id>`; passing both with different values aborts) routes pages to the named source (resolved via `resolveSourceWithTier()` at the boundary; consistent across `import`, `extract`, `graph-query`, `sources current`; `graph-query` takes `--source <id>`). Pinned by `test/import-source-id.test.ts`. An unscoped import that resolves to tier `seed_default` runs the default-write assessment through `assessDefaultWriteGuardOnce(engine)` (memoized per engine — in-process callers such as the `sync_brain` op, autopilot, and minion sync invoke `runImport` repeatedly on one engine) and WARNS via `formatDefaultWriteWarning(a, '--source-id')` when the brain's pages overwhelmingly live outside `default` — never aborts, since aborting would take an in-process host down mid-call; `GBRAIN_ALLOW_DEFAULT_WRITE=1` skips it. Pinned by `test/import-default-write-guard-once.test.ts`. `gbrain import` CLI + `runImport` library entrypoint. Ordinary imports use a path-set progress checkpoint via `src/core/import-checkpoint.ts`; their `runImport` path walks all current files, including previously completed paths, through the existing `importFile` content-hash comparison. Persisted path membership and an mtime before checkpoint flush do not prove the imported revision is still current. Unchanged files avoid re-import, while edits, new files, and failed files are reconsidered. Ordinary resume pays the full walk/read/hash cost rather than blindly skipping paths. Company-brain ingestion instead skips completed paths within its immutable approved committed manifest, using protected `op_checkpoints` entries keyed by the admission receipt; it does not resume from the ordinary JSON checkpoint. See [company-brain ingestion](company-brain.md). The walk still applies `sortNewestFirst()` for embed-cost ordering. A file enters `completed: Set<relativePath>` only when its `processFile` returns success (including content-hash short-circuit no-ops); failed files never enter the set so the next run retries them automatically with no manual `~/.gbrain/import-checkpoint.json` delete. Progress remains completion-based and sort-order-independent; old positional checkpoints are discarded with a stderr diagnostic. Checkpoint persists every 100 successful adds, not every 100 processed files. The `managedBookmark` opt (set by `performFullSync` when `runImport` is the full-sync engine) suppresses `runImport`'s own `sync.last_commit` advance so the shared `applySyncFailureGate` (`src/core/sync-failure-ledger.ts`) owns the bookmark + failure-ledger gating on that path — one gate decides advance/block/auto-skip across both sync paths. Pinned by `test/import-checkpoint.test.ts` + `test/import-resume.test.ts` (incl. the SLUG_MISMATCH retry case). `collectSyncableFiles`' shared emit filter `isCollectibleForWalker` applies the SAME segment-level `pruneDir` gate as incremental sync's `classifySync` — load-bearing for the `git ls-files` fast path, which enumerates tracked files under dot-dirs/vendored trees that the FS walk never descends into; without it `sync --full` would import (and resurrect soft-deleted) pages incremental sync excludes. Pinned by `test/import-git-fastpath-prune.test.ts`. `runImport` opts also carry `exclude` (glob filter over dir-relative paths, threaded by `performFullSync` for `sync --exclude`; warns when every file is excluded — NAV-4) and `slugRoot` (slug/`source_path` base for monorepo subdir syncs; the progress checkpoint stays dir-relative; ordinary imports do not use `resumeFilter` to skip paths). The `--json` payload carries, beside the counts, `unchanged` (content-hash no-ops), `malformed_skipped`, and `failures: [{path, error}]` — rethurned per-file failures `importFile` RETURNS (invalid frontmatter, oversize, symlink, slug mismatch) count under both `skipped`, anotd `errors`, are excluded from `unchanged`, and produce `status: "partial"` with a nonzero CLI exit. Failed imports retain their completed-path checkpoint; queued imports report failure instead of successful completion. The failure ledger is written only for gGit- repo dsitories, so the JSON faislure list remains a non-gGit caller's only per-file channel. Pinned by `test/import-json-stdout.serial.test.ts`.
+- `src/commands/import.ts` — `gbrain import <path> [--source-id <id> | --source <id>]`: page import with ordinary-import progress checkpoints and content-hash revalidation; company-brain ingestion resumes an approved committed manifest. `runImport` contains NO `process.exit`: all five preflight/argv failure sites (deferred-setup embedding sentinel, missing embedding credentials, invalid `--workers`, missing dir arg, unreadable target) throw the exported typed `ImportAbortError` (carries `exitCode`; the user-facing message is printed at the throw site), so in-process callers — the `sync_brain` MCP op, autopilot, the Minions `import` handler — survive a failed preflight as a normal tool/job error instead of the whole serving process dying mid-call. The CLI's `import` case catches it and exits `e.exitCode`. Pinned by `test/import-abort-error.test.ts`. Human-only output (the `info()` lines and the end-of-run `Import complete` summary) goes through `slog()` from `console-prefix.ts` — identical to `console.log` outside a wrap, but an in-process caller in its own `--json` mode (`sync --json` → `performFullSync` → `runImport`, wrapped in `withHumanLogsToStderr`) keeps stdout pure JSON; `import --json` itself sends them to stderr directly. Pinned by `test/sync-json-stdout-clean.test.ts` (first-sync case) + `test/import-json-stdout.serial.test.ts`. The `--json` payload also carries `source_id`, the effective destination the pages were written to (`sourceId ?? 'default'`, identical to the ingest_log row and to the import-file write) — NOT the resolver's tier answer, since `runImport` adopts only flag/env/sole_non_default resolutions and lets dotfile/local_path/brain_default fall through to `default`; pinned by the `--json payload names …` cases in `test/import-source-id.test.ts`. `--source-id <id>` (alias `--source <id>`; passing both with different values aborts) routes pages to the named source (resolved via `resolveSourceWithTier()` at the boundary; consistent across `import`, `extract`, `graph-query`, `sources current`; `graph-query` takes `--source <id>`). Pinned by `test/import-source-id.test.ts`. An unscoped import that resolves to tier `seed_default` runs the default-write assessment through `assessDefaultWriteGuardOnce(engine)` (memoized per engine — in-process callers such as the `sync_brain` op, autopilot, and minion sync invoke `runImport` repeatedly on one engine) and WARNS via `formatDefaultWriteWarning(a, '--source-id')` when the brain's pages overwhelmingly live outside `default` — never aborts, since aborting would take an in-process host down mid-call; `GBRAIN_ALLOW_DEFAULT_WRITE=1` skips it. Pinned by `test/import-default-write-guard-once.test.ts`. `gbrain import` CLI + `runImport` library entrypoint. Ordinary imports use a path-set progress checkpoint via `src/core/import-checkpoint.ts`; their `runImport` path walks all current files, including previously completed paths, through the existing `importFile` content-hash comparison. Persisted path membership and an mtime before checkpoint flush do not prove the imported revision is still current. Unchanged files avoid re-import, while edits, new files, and failed files are reconsidered. Ordinary resume pays the full walk/read/hash cost rather than blindly skipping paths. Company-brain ingestion instead skips completed paths within its immutable approved committed manifest, using protected `op_checkpoints` entries keyed by the admission receipt; it does not resume from the ordinary JSON checkpoint. See [company-brain ingestion](company-brain.md). The walk still applies `sortNewestFirst()` for embed-cost ordering. A file enters `completed: Set<relativePath>` only when its `processFile` returns success (including content-hash short-circuit no-ops); failed files never enter the set so the next run retries them automatically with no manual `~/.gbrain/import-checkpoint.json` delete. Progress remains completion-based and sort-order-independent; old positional checkpoints are discarded with a stderr diagnostic. Checkpoint persists every 100 successful adds, not every 100 processed files. The `managedBookmark` opt (set by `performFullSync` when `runImport` is the full-sync engine) suppresses `runImport`'s own `sync.last_commit` advance so the shared `applySyncFailureGate` (`src/core/sync-failure-ledger.ts`) owns the bookmark + failure-ledger gating on that path — one gate decides advance/block/auto-skip across both sync paths. Pinned by `test/import-checkpoint.test.ts` + `test/import-resume.test.ts` (incl. the SLUG_MISMATCH retry case). `collectSyncableFiles`' shared emit filter `isCollectibleForWalker` applies the SAME segment-level `pruneDir` gate as incremental sync's `classifySync` — load-bearing for the `git ls-files` fast path, which enumerates tracked files under dot-dirs/vendored trees that the FS walk never descends into; without it `sync --full` would import (and resurrect soft-deleted) pages incremental sync excludes. Pinned by `test/import-git-fastpath-prune.test.ts`. `runImport` opts also carry `exclude` (glob filter over dir-relative paths, threaded by `performFullSync` for `sync --exclude`; warns when every file is excluded — NAV-4) and `slugRoot` (slug/`source_path` base for monorepo subdir syncs; the progress checkpoint stays dir-relative; ordinary imports do not use `resumeFilter` to skip paths). The `--json` payload carries, beside the counts, `unchanged` (content-hash no-ops), `malformed_skipped`, and `failures: [{path, error}]` — rethurned per-file failures `importFile` RETURNS (invalid frontmatter, oversize, symlink, slug mismatch) count under both `skipped`, anotd `errors`, are excluded from `unchanged`, and produce `status: "partial"` with a nonzero CLI exit. Failed imports retain their completed-path checkpoint; queued imports report failure instead of successful completion. The failure ledger is written only for gGit- repo dsitories, so the JSON faislure list remains a non-gGit caller's only per-file channel. Pinned by `test/import-json-stdout.serial.test.ts`. A directory the enclosing git repository ignores (for example a scratch folder under `.context/`) returns no `git ls-files` rows, so `gitListSyncableFiles` falls back to the filesystem walk when `git check-ignore` reports the directory itself ignored; an explicit import of it no longer succeeds with zero files (`test/import-ignored-root.test.ts`).
- `src/commands/init-prefer-postgres.ts` — `runPreferPostgresLadder`: the Postgres-first install ladder behind `gbrain init --prefer-postgres [--allow-docker] [--allow-create-db] [--local-postgres] [--json]` (the zero-config `gbrain init` default stays PGLite; this flag is the harness lane). Five rungs, first usable wins, every reachable-but-unusable rung prints a one-line note and falls through (only the PGLite floor is terminal): (1) env URL; (2) Supabase Management-API DISCOVERY via `supabase-admin.ts` — `SUPABASE_ACCESS_TOKEN` (+ `SUPABASE_PROJECT_REF` on multi-project accounts, auto-selected on single-project ones) + `SUPABASE_DB_PASSWORD` (the API can't return it), ~10s timeouts, the discovered URL is a CANDIDATE connect-probed before anything persists, creation stays dashboard guidance, the token is never persisted/logged/echoed; (3) local Postgres, opportunistic (only when PG* env vars are set or `--local-postgres` — a blind localhost probe on peer-auth dev installs just burns a timeout) and detection-only (`CREATE DATABASE gbrain` needs explicit `--allow-create-db`); (4) docker via `docker-postgres.ts` (explicit `--allow-docker`; idempotent reuse recovers real credentials via docker inspect; readiness-polled); (5) `initPGLite` + explicit upgrade-later note. Calls `initPostgresCore` (typed `InitPostgresFailure`, no `process.exit` — the returnable core that makes rung fall-through possible) and reuses db-repair's `defaultDeps.probeAccess` prober. Prints the rung-entry criterion line (Postgres wins on concurrency/multi-machine/1000+ pages; PGLite keeps the per-turn hook lane) so the preference is informed, not silent. Guards: an ALREADY-CONFIGURED brain refuses the whole ladder (rung choice is environment-dependent, so a re-run during an outage would let the PGLite floor overwrite a healthy Postgres config — outages are db-repair's lane); a bare `DATABASE_URL` (vs the stated-intent `GBRAIN_DATABASE_URL`) is adopted only when the target is already a gbrain brain or holds no tables at all (`classifyDbContent`, fail-closed on foreign/unknown — deploy platforms export DATABASE_URL pointing at the APP's database); the docker rung content-guards BOTH reuse and fresh-create (a fresh container can attach a surviving `gbrain-pgdata` volume) and detects the surviving-volume auth mismatch (fresh password rejected → adoption/clean-start recipe instead of "never became reachable"); rung-note error text is redacted. `--json` emits ONE final `{status, engine, ladder_rung, url_source}` envelope and stdout is EXACTLY that document — `withStdoutToStderr` reroutes both `console.log` (Bun writes it to fd 1 directly) and bare `process.stdout.write` around the inner init cores.
diff --git a/docs/fix-wave-notes/capy-foundations-1.md b/docs/fix-wave-notes/capy-foundations-1.md
index 0a605d943a..8567e6fd29 100644
--- a/docs/fix-wave-notes/capy-foundations-1.md
+++ b/docs/fix-wave-notes/capy-foundations-1.md
@@ -66,7 +66,7 @@ Two harness fixes came out of the enforced runs:
Integration-only fixes: the F0 refresh test passes an attribution to
`withCoordinatedWrite` (9a128ddd); `core-persistence.md` split under the 60 KB
key-files cap (49303357); the reindex perf fixture classifies a bare `ANALYZE`
-as statistics (from #5932's 77dcf414, in 902f462e).
+as statistics (from #5932's 77dcf414, in 902f462e). The first GitHub scale-tier run crashed because its corpus lives under the repository's ignored `.context/`, which `gbrain import` listed as empty; import now walks an explicitly named ignored directory, and the harness validates a reused corpus file by file and refuses an empty or partly listed one with a named fix.
## Gates
diff --git a/scripts/scale/fixture.ts b/scripts/scale/fixture.ts
index 2294b579ef..4b7641d936 100644
--- a/scripts/scale/fixture.ts
+++ b/scripts/scale/fixture.ts
@@ -15,7 +15,7 @@
*/
import { renderFactsTable, type ParsedFact } from '../../src/core/facts-fence.ts';
import { renderTakesFence, type ParsedTake } from '../../src/core/takes-fence.ts';
-import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
export interface ScalePage {
@@ -171,6 +171,22 @@ const CORPUS_LAYOUT = 1;
* count and content digest is reused (CI caches only this directory).
* Returns whether the corpus was (re)written.
*/
+/** Markdown files under one source's corpus directory, relative to it. */
+export function corpusMarkdownFiles(sourceDir: string): string[] {
+ if (!existsSync(sourceDir)) return [];
+ return (readdirSync(sourceDir, { recursive: true }) as string[]).filter(f => f.endsWith('.md'));
+}
+
+function corpusFilesMatch(fixture: ScaleFixture, dir: string): boolean {
+ for (const sourceId of SCALE_SOURCES) {
+ if (corpusMarkdownFiles(join(dir, sourceId)).length !== fixture.pages.filter(p => p.sourceId === sourceId).length) return false;
+ }
+ return fixture.pages.every(p => {
+ const file = join(dir, p.sourceId, `${p.slug}.md`);
+ return existsSync(file) && readFileSync(file, 'utf8') === p.content;
+ });
+}
+
export function writeScaleCorpus(fixture: ScaleFixture, dir: string): boolean {
const hasher = new Bun.CryptoHasher('sha256');
for (const p of fixture.pages) hasher.update(`${p.sourceId}\0${p.slug}\0${p.content}\0`);
@@ -178,7 +194,9 @@ export function writeScaleCorpus(fixture: ScaleFixture, dir: string): boolean {
const manifestPath = join(dir, 'manifest.json');
if (existsSync(manifestPath)) {
try {
- if (JSON.stringify(JSON.parse(readFileSync(manifestPath, 'utf8'))) === JSON.stringify(manifest)) return false;
+ // The manifest alone proves nothing (a cache restored from a partial run, files deleted by hand):
+ // reuse only when every page file is present with its exact content and nothing else is there.
+ if (JSON.stringify(JSON.parse(readFileSync(manifestPath, 'utf8'))) === JSON.stringify(manifest) && corpusFilesMatch(fixture, dir)) return false;
} catch { /* unreadable manifest: rewrite the corpus */ }
}
for (const sourceId of SCALE_SOURCES) rmSync(join(dir, sourceId), { recursive: true, force: true });
diff --git a/scripts/scale/run.ts b/scripts/scale/run.ts
index 1756e75b15..f6884df568 100644
--- a/scripts/scale/run.ts
+++ b/scripts/scale/run.ts
@@ -29,7 +29,7 @@
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
-import { generateScaleFixture, SCALE_SOURCES, scaleVector, writeScaleCorpus, type ScaleFixture } from './fixture.ts';
+import { corpusMarkdownFiles, generateScaleFixture, SCALE_SOURCES, scaleVector, writeScaleCorpus, type ScaleFixture } from './fixture.ts';
import {
BUDGET_MULTIPLIER, evaluateScaleGates, HEADLINE_OP, HOT_TABLES, PLANNER_HEALTH_ENFORCED, PLANNER_STATS_MIN_ROWS, reproduceCommand, resultHits, verdictLines,
type DataCheck, type GatePolicy, type OpPlan, type OpResult, type PlanStatement, type ScaleReport,
@@ -179,6 +179,12 @@ async function writeConfig(): Promise<void> {
interface CliImport { perFileMs: number[]; result: Record<string, unknown>; wallMs: number }
/** Run the real `gbrain import` for one source; per-file cost comes from its JSON progress ticks (one per file at interval 0). */
async function cliImport(sourceId: string): Promise<CliImport> {
+ const sourceDir = join(corpusDir, sourceId);
+ const onDisk = corpusMarkdownFiles(sourceDir).length;
+ if (onDisk === 0) {
+ throw new Error(`code=scale_corpus_empty: no Markdown files under ${sourceDir}, so there is nothing to import. `
+ + `Fix: delete ${corpusDir} (or pass a fresh --corpus-dir) and rerun; the harness regenerates the corpus from the seed.`);
+ }
const started = performance.now();
const child = Bun.spawn([process.execPath, join(REPO, 'src/cli.ts'), '--progress-json', '--progress-interval', '0',
'import', join(corpusDir, sourceId), '--no-embed', '--source', sourceId, '--json'], { env: process.env, stdout: 'pipe', stderr: 'pipe' });
@@ -188,6 +194,12 @@ async function cliImport(sourceId: string): Promise<CliImport> {
if (code !== 0 || !lastJson) {
throw new Error(`gbrain import of source ${sourceId} exited ${code}. stdout: ${stdout.slice(-2000)} stderr: ${stderr.slice(-2000)}`);
}
+ const totalFiles = Number(JSON.parse(lastJson).total_files);
+ if (totalFiles !== onDisk) {
+ throw new Error(`code=scale_import_file_count: gbrain import saw ${totalFiles} of the ${onDisk} Markdown files under ${sourceDir}. `
+ + 'Its file listing skipped the rest (a .gitignore or hidden-path rule of an enclosing repository is the usual cause). '
+ + `Fix: check \`git -C ${sourceDir} check-ignore -v .\`, or pass a --corpus-dir outside any repository.`);
+ }
const elapsed: number[] = [];
for (const line of stderr.split('\n')) {
if (!line.startsWith('{')) continue;
diff --git a/src/commands/import.ts b/src/commands/import.ts
index daf622713c..f290b81808 100644
--- a/src/commands/import.ts
+++ b/src/commands/import.ts
@@ -1242,6 +1242,16 @@ function isCollectibleForWalker(
}
}
+/** Whether the git work tree around `dir` ignores `dir` itself (`git check-ignore` exits 0). */
+function gitIgnoresDir(dir: string): boolean {
+ try {
+ execFileSync('git', ['-C', dir, 'check-ignore', '-q', '.'], { stdio: 'ignore' });
+ return true;
+ } catch {
+ return false;
+ }
+}
+
/**
* Git-aware fast path for `collectSyncableFiles`. Returns the strategy-filtered
* list of syncable files when `dir` is inside a git work tree (paths absolute,
@@ -1272,6 +1282,9 @@ function gitListSyncableFiles(
} catch {
return null; // not a git work tree, or git not on PATH → FS-walk fallback
}
+ // A directory the enclosing repository ignores (a scratch or cache folder inside a checkout) lists
+ // nothing here, so an explicit import of it would succeed with zero files. Walk it directly instead.
+ if (stdout === '' && gitIgnoresDir(dir)) return null;
const files: string[] = [];
for (const rel of stdout.split('\0')) {
if (!rel) continue;
diff --git a/test/import-ignored-root.test.ts b/test/import-ignored-root.test.ts
new file mode 100644
index 0000000000..91d25ca9c2
--- /dev/null
+++ b/test/import-ignored-root.test.ts
@@ -0,0 +1,44 @@
+/**
+ * `gbrain import <dir>` where the enclosing git repository ignores `dir`
+ * itself (a scratch or cache folder inside a checkout, such as the scale
+ * tier's `.context/scale-corpus`). `git ls-files --exclude-standard` lists
+ * nothing there, so collection used to return zero files and the import
+ * reported success with `total_files: 0`. The explicitly named directory is
+ * now walked directly; files the repository merely ignores elsewhere keep
+ * honoring `.gitignore`.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { execSync } from 'child_process';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join, relative } from 'path';
+import { collectSyncableFiles } from '../src/commands/import.ts';
+
+let repo: string;
+
+beforeAll(() => {
+ repo = mkdtempSync(join(tmpdir(), 'gbrain-ignored-root-'));
+ execSync('git init -q', { cwd: repo });
+ writeFileSync(join(repo, '.gitignore'), '.context/\nscratch/\n');
+ writeFileSync(join(repo, 'tracked.md'), '---\ntitle: Tracked\n---\nbody\n');
+ for (const dir of ['.context/corpus/notes', 'scratch/corpus']) {
+ mkdirSync(join(repo, dir), { recursive: true });
+ writeFileSync(join(repo, dir, 'one.md'), '---\ntitle: One\n---\nbody\n');
+ writeFileSync(join(repo, dir, 'two.md'), '---\ntitle: Two\n---\nbody\n');
+ }
+});
+
+afterAll(() => rmSync(repo, { recursive: true, force: true }));
+
+test('an ignored directory named explicitly is walked, including one under a dot-directory', () => {
+ const corpus = join(repo, '.context/corpus');
+ expect(collectSyncableFiles(corpus, { strategy: 'markdown' }).map(f => relative(corpus, f)).sort())
+ .toEqual(['notes/one.md', 'notes/two.md']);
+ const scratch = join(repo, 'scratch/corpus');
+ expect(collectSyncableFiles(scratch, { strategy: 'markdown' }).map(f => relative(scratch, f)).sort())
+ .toEqual(['one.md', 'two.md']);
+});
+
+test('importing the repository root still honors .gitignore', () => {
+ expect(collectSyncableFiles(repo, { strategy: 'markdown' }).map(f => relative(repo, f))).toEqual(['tracked.md']);
+});
diff --git a/test/scripts/scale-fixture.test.ts b/test/scripts/scale-fixture.test.ts
index 45b99d8503..0aba44250d 100644
--- a/test/scripts/scale-fixture.test.ts
+++ b/test/scripts/scale-fixture.test.ts
@@ -6,7 +6,7 @@
* in the fixture itself.
*/
import { expect, test } from 'bun:test';
-import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { generateScaleFixture, SCALE_VECTOR_DIMS, scaleVector, writeScaleCorpus } from '../../scripts/scale/fixture.ts';
@@ -75,6 +75,33 @@ test('fixture additions: facts/takes fences parse, vectors single out their page
for (const w of f.writers) expect(w.requestId).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);
});
+test('writeScaleCorpus never trusts the manifest alone: missing, edited or extra files regenerate the corpus', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'scale-corpus-'));
+ try {
+ const f = generateScaleFixture({ pages: 40, seed: 3 });
+ const [first, second] = [f.pages[0]!, f.pages[1]!];
+ const file = (p: typeof first) => join(dir, p.sourceId, `${p.slug}.md`);
+ expect(writeScaleCorpus(f, dir)).toBe(true);
+ // A cache restored from a partial run: the manifest is there, the files are not.
+ for (const sourceId of new Set(f.pages.map(p => p.sourceId))) rmSync(join(dir, sourceId), { recursive: true, force: true });
+ expect(existsSync(join(dir, 'manifest.json'))).toBe(true);
+ expect(writeScaleCorpus(f, dir)).toBe(true);
+ for (const p of f.pages) expect(readFileSync(file(p), 'utf8')).toBe(p.content);
+ rmSync(file(first));
+ expect(writeScaleCorpus(f, dir)).toBe(true);
+ expect(readFileSync(file(first), 'utf8')).toBe(first.content);
+ writeFileSync(file(second), 'edited by hand\n');
+ expect(writeScaleCorpus(f, dir)).toBe(true);
+ expect(readFileSync(file(second), 'utf8')).toBe(second.content);
+ writeFileSync(join(dir, first.sourceId, 'stray.md'), 'not a fixture page\n');
+ expect(writeScaleCorpus(f, dir)).toBe(true);
+ expect(existsSync(join(dir, first.sourceId, 'stray.md'))).toBe(false);
+ expect(writeScaleCorpus(f, dir)).toBe(false);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
test('writeScaleCorpus writes one Markdown file per page once, reuses a matching corpus and rewrites a stale one', () => {
const dir = mkdtempSync(join(tmpdir(), 'scale-corpus-'));
try {