Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Revert "perf(sync): non-blocking git-aware file walk, reused by full sync only when safe (#5947)"
time-attack3bdefd9a558c
diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsvindex 47c145196f..701053e820 100644--- a/scripts/function-size-baseline.tsv+++ b/scripts/function-size-baseline.tsv@@ -19,7 +19,7 @@ src/commands/eval-longmemeval.ts runEvalLongMemEval 740 seed: W5 baseline, refacsrc/commands/extract-conversation-facts.ts processPage 320 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 #5918: one read of the page's conversation_segment_gap_minutes shared by both splitIntoSegments calls (validation lives in pageSegmentGapMinutes); +12 fix wave 9 lane P (#5025, D-N2): not-extractable skip call (decision in facts/conversation-skip.ts) and the email-thread segment gapsrc/commands/extract-conversation-facts.ts runExtractConversationFactsCore 378 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 #5757: managed flag threaded into ExtractCoreState; +4 #5823: shared default-cap wiring and structured budget reason/model; decision logic is in facts/conversation-budget.ts; +2 #5330: strict-eligibility read and the enumeration filter through the shared predicate (rule lives in facts/conversation-types.ts)src/commands/extract.ts runExtract 398 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)-src/commands/import.ts runImport 975 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +4 GBRA-40 F4b: planner-stats refresh every import.analyze_every_pages files (logic in planner-stats.ts); +6 #5988: onFileResult hook so full sync holds content refusals (logic in commands/sync/holds.ts); +3 #5988: heldPaths skip so a full sync never imports a rename destination it held this run (logic in commands/sync/holds.ts); +3 #5947: onCollected hands runImport's completed walk to performFullSync (reuse rule in core/sync-walk.ts)+src/commands/import.ts runImport 972 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +4 GBRA-40 F4b: planner-stats refresh every import.analyze_every_pages files (logic in planner-stats.ts); +6 #5988: onFileResult hook so full sync holds content refusals (logic in commands/sync/holds.ts); +3 #5988: heldPaths skip so a full sync never imports a rename destination it held this run (logic in commands/sync/holds.ts)src/commands/mcp-expose.ts runPublish 443 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/commands/migrate-engine.ts runMigrateEngine 405 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/commands/serve.ts installStdioLifecycle 323 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +7 GBRA-40 Lane D: facts drain install call and its shutdown stop (logic in installFactsDrain); +1 engine graduation (GBRA-50 G3): onShutdownReady hook for the graduation hand-off (logic in installGraduationHandoff)diff --git a/src/commands/import.ts b/src/commands/import.tsindex 1239743f80..577d986ac4 100644--- a/src/commands/import.ts+++ b/src/commands/import.ts@@ -41,7 +41,6 @@ import { importManagedFile } from '../core/persistence/import-mutations.ts';import { acceptedPendingReceipt } from '../core/persistence/accepted-pending.ts';import { estimateCostFromChars, lookupEmbeddingPrice } from '../core/embedding-pricing.ts';import { getEmbeddingModel } from '../core/ai/gateway.ts';-import { GIT_CHECK_IGNORE_ARGS, GIT_LS_FILES_ARGS, GIT_LS_FILES_MAX_BUFFER, gitListCandidates, gitListSyncableFilesAsync, walkOptions, type CollectedWalk } from '../core/sync-walk.ts';import { managedRootMarkerFor } from '../core/persistence/root-registry.ts';/** Return a refusal when an import target lies outside every admitted root. */@@ -256,8 +255,6 @@ export async function runImport(heldPaths?: ReadonlySet<string>;/** #5988: each file's outcome (a throw arrives as `{ status: 'error', error }`); `'held'` = the caller held it, not a failure. */onFileResult?: (path: string, filePath: string, result: Pick<ImportResult, 'status' | 'error' | 'refusal' | 'frontmatter_recovery'>) => Promise<'held' | undefined>;- /** #5947: runImport's completed walk (root-relative, before `exclude`), so a full sync can reuse it. */- onCollected?: (walk: CollectedWalk) => void;/*** #753/#774: glob patterns to exclude from the import (same semantics as* `isSyncable`'s `exclude` — matched against the dir-relative path).@@ -563,12 +560,11 @@ export async function runImport(const malformedExcluded: string[] = [];const company = currentCompanyBrainSync(sourceId);let allFiles = company ? company.plan.manifest.filter(entry => entry.disposition === 'included').map(entry => join(dir, entry.path))- : singleFile ? [dir] : await collectSyncableFilesAsync(dir, {+ : singleFile ? [dir] : collectSyncableFiles(dir, {strategy, includeGitignored,includeHidden: opts.includeHidden,onExcluded: (rel) => { malformedExcluded.push(rel); },});- if (!company && !singleFile && !opts.signal?.aborted) opts.onCollected?.({ complete: true, root: dir, options: walkOptions({ strategy, includeGitignored, includeHidden: opts.includeHidden, exclude: opts.exclude }), files: allFiles.map(abs => relative(dir, abs)) });console.error(`[gbrain phase] import.collect_files done ${Date.now() - _walkT0}ms files=${allFiles.length}`,);@@ -1315,7 +1311,7 @@ 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, ...GIT_CHECK_IGNORE_ARGS], { stdio: 'ignore' });+ execFileSync('git', ['-C', dir, 'check-ignore', '-q', '.'], { stdio: 'ignore' });return true;} catch {return false;@@ -1344,7 +1340,11 @@ function gitListSyncableFiles(): string[] | null {let stdout: string;try {- stdout = execFileSync('git', ['-C', dir, ...GIT_LS_FILES_ARGS], { encoding: 'utf8', maxBuffer: GIT_LS_FILES_MAX_BUFFER, stdio: ['ignore', 'pipe', 'ignore'] });+ stdout = execFileSync(+ 'git',+ ['-C', dir, 'ls-files', '--cached', '--others', '--exclude-standard', '-z'],+ { encoding: 'utf8', maxBuffer: 512 * 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore'] },+ );} catch {return null; // not a git work tree, or git not on PATH → FS-walk fallback}@@ -1352,7 +1352,14 @@ function gitListSyncableFiles(// 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 full of gitListCandidates(dir, stdout, rel => isCollectibleForWalker(rel, strategy, multimodalOn, includeHidden), onExcluded)) {+ for (const rel of stdout.split('\0')) {+ if (!rel) continue;+ // Malformed check FIRST (separately from the collectible gate) so the+ // exclusion is reportable — other filters (strategy, prune, metafile)+ // are silent by design; this one hides renameable content.+ if (hasMalformedPathSegment(rel)) { onExcluded?.(rel); continue; }+ if (!isCollectibleForWalker(rel, strategy, multimodalOn, includeHidden)) continue;+ const full = join(dir, rel);let st;try {st = lstatSync(full);@@ -1468,22 +1475,6 @@ export function collectSyncableFiles(dir: string, opts: CollectOpts = {}): strinreturn files.sort();}-/**- * `collectSyncableFiles` for long-running async callers (import, full sync):- * the git fast path yields the event loop instead of holding it. Same output;- * the FS walk (`--include-gitignored`, non-git and git-ignored dirs) is the- * synchronous one.- */-export async function collectSyncableFilesAsync(dir: string, opts: CollectOpts = {}): Promise<string[]> {- if (!opts.includeGitignored) {- const multimodalOn = process.env.GBRAIN_EMBEDDING_MULTIMODAL === 'true';- const gitFiles = await gitListSyncableFilesAsync(dir,- rel => isCollectibleForWalker(rel, opts.strategy ?? 'markdown', multimodalOn, opts.includeHidden), opts.onExcluded);- if (gitFiles) return gitFiles;- }- return collectSyncableFiles(dir, { ...opts, includeGitignored: true });-}-/*** @deprecated v0.31.2: kept as a thin wrapper so legacy callers keep* compiling. Prefer `collectSyncableFiles(dir, { strategy: 'markdown' })`.diff --git a/src/commands/sync/full.ts b/src/commands/sync/full.tsindex 4ddf95b89a..3a683357f2 100644--- a/src/commands/sync/full.ts+++ b/src/commands/sync/full.ts@@ -2,11 +2,10 @@import { assertSourceFilesystemActive } from '../../core/minions/source-filesystem.ts';import { currentJobSignal } from '../../core/minions/submission-authority.ts';import { currentCompanyBrainSync, softDeleteSyncPages } from '../../core/company-brain/profile.ts';-import { join, relative } from 'path';+import { relative } from 'path';import type { BrainEngine } from '../../core/engine.ts';import { DELETE_BATCH_SIZE } from '../../core/engine-constants.ts';-import { collectSyncableFilesAsync } from '../import.ts';-import { reusableWalk, walkOptions, type CollectedWalk } from '../../core/sync-walk.ts';+import { collectSyncableFiles } from '../import.ts';import {isSyncable,isPoisonedPath,@@ -102,7 +101,6 @@ export async function performFullSync(opts.onProgress?.({ phase: 'full_import' });await moveHeldRenames(engine, holds, holdRoot);let result: import('../import.ts').RunImportResult;- let importWalk: CollectedWalk | undefined;try {result = await runImport(engine, importArgs, {signal: opts.signal,@@ -123,7 +121,6 @@ export async function performFullSync(noteScreenedImport(holds, path, fileResult);return await holdRefusedImport(engine, holds, path, filePath, fileResult) ? 'held' : undefined;},- onCollected: (walk) => { importWalk = walk; },});if (opts.signal?.aborted) throw new ImportAbortError('interrupted', 1, result);} catch (error) {@@ -150,7 +147,8 @@ export async function performFullSync(const fullSourceId = opts.sourceId ?? DEFAULT_SOURCE_ID;const fullFailureSet = new Set(result.failures.map(f => f.path));if (holds?.existing.size || holds?.retryPaths.size) {- const walked = new Set((await fullSyncScopeFiles(syncScopeRoot, opts, importWalk)).files.map(abs => relative(holdRoot, abs)));+ const walked = new Set(collectSyncableFiles(syncScopeRoot, { strategy: opts.strategy ?? 'markdown', includeGitignored: opts.includeGitignored,+ includeHidden: opts.includeHidden }).map(abs => relative(holdRoot, abs)));await settleFullSyncHolds(engine, holds, { root: holdRoot, walked, failed: fullFailureSet });}const fullSucceeded = loadSyncFailures()@@ -192,7 +190,7 @@ export async function performFullSync();}- const reconciledDeletes = await reconcileFullSyncDeletes(engine, opts, { company, gitContextRoot, syncScopeRoot, slugRoot, importWalk });+ const reconciledDeletes = await reconcileFullSyncDeletes(engine, opts, { company, gitContextRoot, syncScopeRoot, slugRoot });// #3479 blocker 2 — the post-gate sweep above ran BEFORE this reconcile,// so a `<rename:…>` sentinel whose stale row the reconcile just removed@@ -244,7 +242,7 @@ export async function performFullSync(async function fullSyncDryRun(engine: BrainEngine, syncScopeRoot: string, headCommit: string, opts: SyncOpts,hold: { holds: LegacyHolds | null; holdRoot: string }): Promise<SyncResult> {const dryRunMalformed: string[] = [];- let allFiles = await collectSyncableFilesAsync(syncScopeRoot, {+ let allFiles = collectSyncableFiles(syncScopeRoot, {strategy: opts.strategy ?? 'markdown',includeGitignored: opts.includeGitignored,onExcluded: (rel) => { dryRunMalformed.push(rel); },@@ -347,18 +345,6 @@ async function reportBlockedFullSync(};}-/**- * The scope's syncable files as absolute paths. runImport's walk stands in for- * a fresh one only when it completed for this root with identical options- * (`reused`); otherwise the tree is walked again with the same options.- */-async function fullSyncScopeFiles(syncScopeRoot: string, opts: SyncOpts, walk: CollectedWalk | undefined): Promise<{ files: string[]; reused: boolean }> {- // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- rel is the walker's own output under syncScopeRoot; the join rebuilds the in-memory path string the callers compare, no fs operation- if (reusableWalk(walk, syncScopeRoot, walkOptions(opts))) return { files: walk.files.map(rel => join(syncScopeRoot, rel)), reused: true };- return { files: await collectSyncableFilesAsync(syncScopeRoot, { strategy: opts.strategy ?? 'markdown', includeGitignored: opts.includeGitignored,- includeHidden: opts.includeHidden }), reused: false };-}-/*** Soft-delete file-backed pages whose source file is gone (advancing full* syncs only). Returns the number of pages that transitioned.@@ -366,9 +352,9 @@ async function fullSyncScopeFiles(syncScopeRoot: string, opts: SyncOpts, walk: Casync function reconcileFullSyncDeletes(engine: BrainEngine,opts: SyncOpts,- input: { company: ReturnType<typeof currentCompanyBrainSync>; gitContextRoot: string; syncScopeRoot: string; slugRoot: string | undefined; importWalk?: CollectedWalk },+ input: { company: ReturnType<typeof currentCompanyBrainSync>; gitContextRoot: string; syncScopeRoot: string; slugRoot: string | undefined },): Promise<number> {- const { company, gitContextRoot, syncScopeRoot, slugRoot, importWalk } = input;+ const { company, gitContextRoot, syncScopeRoot, slugRoot } = input;// #1970 (F-A): runImport is import-only — it never purges pages whose backing// file was deleted since the last sync. A full re-import is authoritative for// the whole tree, so reconcile deletes here too (this is what makes the@@ -409,9 +395,12 @@ async function reconcileFullSyncDeletes(// --include-hidden full sync just imported would look "gone" on the// very next reconcile pass (its file was never in this collection) and// the mass-delete valve would remove it.- const scope = company ? null : await fullSyncScopeFiles(syncScopeRoot, opts, importWalk);- const currentFiles = company ? company.plan.manifest.filter(entry => entry.disposition === 'included').map(entry => entry.path)- : scope!.files.map(abs => relative(slugRoot ?? syncScopeRoot, abs));+ const currentFiles = company ? company.plan.manifest.filter(entry => entry.disposition === 'included').map(entry => entry.path) : collectSyncableFiles(syncScopeRoot, {+ strategy: opts.strategy ?? 'markdown',+ includeGitignored: opts.includeGitignored,+ includeHidden: opts.includeHidden,+ })+ .map(abs => relative(slugRoot ?? syncScopeRoot, abs));// #5988 (E13): the old page of a held rename keeps its origin until the// renamed file imports; its file being gone does not make it stale.const heldOrigins = await heldRenameOrigins(engine, sid);@@ -437,14 +426,11 @@ async function reconcileFullSyncDeletes(// from pre-gate releases survive reconcile (their file still exists —// deleting the row would be silent data loss; cross-model finding).(unsyncableReason(p, reconcileSyncOpts) === 'malformed-path' && isPoisonedPath(p));- const inScope = (p: string) => (scopePrefix === '' || p.startsWith(scopePrefix)) && reconcileEligible(p);- let plan = planReconcileDeletes(rows, currentFiles, inScope);- // #5947: the reused walk predates the import, so a file restored or created since then- // is missing from it. It may prove nothing is stale; a deletion is decided on a fresh walk.- if (scope?.reused && plan.staleSlugs.length > 0) {- const fresh = await fullSyncScopeFiles(syncScopeRoot, opts, undefined);- plan = planReconcileDeletes(rows, fresh.files.map(abs => relative(slugRoot ?? syncScopeRoot, abs)), inScope);- }+ const plan = planReconcileDeletes(+ rows,+ currentFiles,+ p => (scopePrefix === '' || p.startsWith(scopePrefix)) && reconcileEligible(p),+ );if (plan.staleSlugs.length > 0 && plan.massDelete && !massReconcileAllowed()) {// #2828 mass-delete safety valve: a reconcile that would sweep more than// half of the pages this strategy manages, on a source with a non-trivialdiff --git a/src/core/sync-walk.ts b/src/core/sync-walk.tsdeleted file mode 100644index 75d74afa57..0000000000--- a/src/core/sync-walk.ts+++ /dev/null@@ -1,97 +0,0 @@-/**- * Git-aware file enumeration shared by the synchronous import walker- * (`collectSyncableFiles` in commands/import.ts) and its non-blocking twin- * (`collectSyncableFilesAsync`), plus the token that lets a full sync reuse- * runImport's walk.- *- * Both walkers list a tree with `git ls-files` and feed every entry through- * `gitListCandidates`, so their filters cannot drift. The async walker runs- * `git ls-files` and the ignored-directory probe as awaited children and the- * per-file lstat through a bounded pool, so a large tree on a slow filesystem- * no longer holds the event loop (other sources' database handshakes, lock- * heartbeats and timers keep running). This module imports nothing from- * commands/, so commands/import.ts can depend on it without a cycle.- */-import { execFile } from 'child_process';-import { lstat } from 'fs/promises';-import { join } from 'path';-import { promisify } from 'util';-import { hasMalformedPathSegment } from './sync.ts';-import { runWithLimit } from './worker-pool.ts';-import type { SyncStrategy } from './sync.ts';--export const GIT_LS_FILES_ARGS = ['ls-files', '--cached', '--others', '--exclude-standard', '-z'] as const;-export const GIT_CHECK_IGNORE_ARGS = ['check-ignore', '-q', '.'] as const;-export const GIT_LS_FILES_MAX_BUFFER = 512 * 1024 * 1024;-/** lstat calls in flight per async walk; the runtime's I/O pool bounds real parallelism. */-const WALK_LSTAT_CONCURRENCY = 32;-const execFileAsync = promisify(execFile);--/**- * The `git ls-files -z` entries that pass the walker filters, as absolute- * paths in listing order. The malformed-name check runs first and is- * reported through `onExcluded`, because it hides renameable content; the- * other filters (`accept`: strategy, prune, metafile) are silent by design.- */-export function gitListCandidates(dir: string, stdout: string, accept: (relPath: string) => boolean,- onExcluded?: (relPath: string) => void): string[] {- const candidates: string[] = [];- for (const rel of stdout.split('\0')) {- if (!rel) continue;- if (hasMalformedPathSegment(rel)) { onExcluded?.(rel); continue; }- if (accept(rel)) candidates.push(join(dir, rel));- }- return candidates;-}--/**- * The git fast path without blocking the event loop: same filters, same- * no-symlink rule (submodule gitlinks drop out as non-regular entries), same- * sorted output, and the same `null` signal into the FS-walk fallback for a- * non-git directory or one the enclosing repository ignores.- */-export async function gitListSyncableFilesAsync(dir: string, accept: (relPath: string) => boolean,- onExcluded?: (relPath: string) => void): Promise<string[] | null> {- let stdout: string;- try {- ({ stdout } = await execFileAsync('git', ['-C', dir, ...GIT_LS_FILES_ARGS], { encoding: 'utf8', maxBuffer: GIT_LS_FILES_MAX_BUFFER }));- } catch {- return null;- }- if (stdout === '' && await execFileAsync('git', ['-C', dir, ...GIT_CHECK_IGNORE_ARGS]).then(() => true, () => false)) return null;- const candidates = gitListCandidates(dir, stdout, accept, onExcluded);- // A rejected lstat (ls-files raced a deletion, or unreadable) drops the file, like the synchronous loop.- const regular = await runWithLimit({- items: candidates,- limit: WALK_LSTAT_CONCURRENCY,- fn: async (full: string) => {- const st = await lstat(full);- return !st.isSymbolicLink() && st.isFile();- },- });- return candidates.filter((_, i) => regular[i].ok && regular[i].value).sort();-}--/** The options that decide what a walk lists. */-export interface WalkOptions { strategy: SyncStrategy; includeGitignored: boolean; includeHidden: string[]; exclude: string[] }--/**- * runImport's walk handed to a full sync. `complete` is set only when the walk- * returned and the run was not aborted; `files` are root-relative, taken- * before `--exclude` (the same set the full sync's own walk would list).- */-export interface CollectedWalk { complete: true; root: string; options: WalkOptions; files: string[] }--export function walkOptions(opts: { strategy?: SyncStrategy; includeGitignored?: boolean; includeHidden?: string[]; exclude?: string[] }): WalkOptions {- return { strategy: opts.strategy ?? 'markdown', includeGitignored: opts.includeGitignored ?? false,- includeHidden: [...(opts.includeHidden ?? [])], exclude: [...(opts.exclude ?? [])] };-}--/** A walk may stand in for a fresh one only when it completed for the same root with identical options. */-export function reusableWalk(walk: CollectedWalk | undefined, root: string, options: WalkOptions): walk is CollectedWalk {- if (walk?.complete !== true || walk.root !== root) return false;- const a = walk.options;- const same = (x: string[], y: string[]) => x.length === y.length && x.every((value, i) => value === y[i]);- return a.strategy === options.strategy && a.includeGitignored === options.includeGitignored- && same(a.includeHidden, options.includeHidden) && same(a.exclude, options.exclude);-}diff --git a/test/import-cancellation.serial.test.ts b/test/import-cancellation.serial.test.tsindex da21eaf1b8..8c82350cc5 100644--- a/test/import-cancellation.serial.test.ts+++ b/test/import-cancellation.serial.test.ts@@ -123,15 +123,11 @@ for (const mode of ['caller', 'job', 'log-ingest', 'lease', 'caller-and-lease']const originalLog = engine.logIngest.bind(engine);const originalLock = locks.withRefreshingLock;let calls = 0;- let leaseLost!: () => void;- const lostLease = new Promise<void>(resolve => { leaseLost = resolve; });const importSpy = spyOn(importFiles, 'importFile').mockImplementation(async (...args) => {const result = await originalImport(...args); calls++;if (mode === 'lease' || mode === 'caller-and-lease') {if (mode === 'caller-and-lease') controller.abort();- // The file walk yields, so a lease shorter than the run up to the- // first import could expire before it; hold this file until it does.- await lostLease;+ await new Promise(resolve => setTimeout(resolve, 80));} else if (mode !== 'log-ingest') controller.abort();return result;});@@ -141,10 +137,7 @@ for (const mode of ['caller', 'job', 'log-ingest', 'lease', 'caller-and-lease']return result;});const lockSpy = spyOn(locks, 'withRefreshingLock').mockImplementation((eng, key, fn, opts) =>- originalLock(eng, key, fn, key.startsWith('gbrain-fs:') && mode.includes('lease') ? {- ...opts, ttlMinutes: 0.02,- onLockLost: (reason) => { opts?.onLockLost?.(reason); leaseLost(); },- } : opts));+ originalLock(eng, key, fn, key.startsWith('gbrain-fs:') && mode.includes('lease') ? { ...opts, ttlMinutes: 0.0005 } : opts));const sync = () => performSync(engine, { repoPath: root, sourceId: 'default', noPull: true, noEmbed: true, noExtract: true, concurrency: 1, signal: controller.signal });try {if (mode === 'job') {diff --git a/test/import-walker-async.test.ts b/test/import-walker-async.test.tsdeleted file mode 100644index 6fb68fc8bd..0000000000--- a/test/import-walker-async.test.ts+++ /dev/null@@ -1,179 +0,0 @@-/**- * `collectSyncableFilesAsync` — the non-blocking variant of the git-aware- * walker that `runImport` and `performFullSync` use.- *- * Contract: the same output as `collectSyncableFiles` for every input (sorted- * absolute paths, strategy filter, prune/metafile/malformed gates, no- * symlinks, `onExcluded`, `includeHidden`, `includeGitignored`, multimodal- * admission, the FS-walk fallback for non-git and git-ignored directories),- * but `git ls-files` and the per-file lstat are awaited, so timers and- * in-flight I/O keep running during the walk.- * The synchronous walk held the thread for the whole lstat loop, which on a- * large tree over a network filesystem starved every other source's database- * handshakes in the same `sync --all` process.- *- * No PGLite needed: the walker is pure filesystem + git.- */--import { describe, test, expect, beforeAll, afterAll } from 'bun:test';-import { mkdtempSync, writeFileSync, rmSync, mkdirSync, symlinkSync } from 'fs';-import { execSync } from 'child_process';-import { tmpdir } from 'os';-import { join, relative } from 'path';-// Namespace import: the async walker is looked up at call time, so these-// cases run (and fail) against a tree that predates it.-import * as walker from '../src/commands/import.ts';-import { withEnv } from './helpers/with-env.ts';-import { writeLargeWorktree } from './helpers/large-worktree.ts';-import type { CollectedWalk, WalkOptions } from '../src/core/sync-walk.ts';-// Loaded at run time so these cases fail (rather than the file failing to load) on a tree without the module.-const walkRule = await import('../src/core/sync-walk.ts').catch(() => null);-const walkOptions = (opts: Parameters<NonNullable<typeof walkRule>['walkOptions']>[0]): WalkOptions => walkRule!.walkOptions(opts);-const reusableWalk = (walk: CollectedWalk | undefined, root: string, options: WalkOptions): boolean => walkRule!.reusableWalk(walk, root, options);--const PAGE = '---\ntitle: Page\n---\nbody\n';-let repo: string;-let plain: string;--function sh(cwd: string, cmd: string): void {- execSync(cmd, { cwd, stdio: 'pipe' });-}--function gitInit(dir: string): void {- sh(dir, 'git init -q');- sh(dir, 'git config user.email "[email protected]"');- sh(dir, 'git config user.name "T"');-}--function write(root: string, rel: string, body = PAGE): void {- mkdirSync(join(root, rel, '..'), { recursive: true });- writeFileSync(join(root, rel), body);-}--beforeAll(() => {- repo = mkdtempSync(join(tmpdir(), 'gbrain-walk-async-'));- gitInit(repo);- write(repo, '.gitignore', 'ignored/\n*.secret.md\n');- write(repo, 'notes/a.md');- write(repo, 'notes/b.md');- write(repo, 'code/x.ts', 'export const x = 1;\n');- write(repo, 'img/pic.png', 'not really a png');- write(repo, 'README.md', '# metafile\n');- write(repo, '.dira/hidden.md');- write(repo, 'node_modules/dep/notes.md');- write(repo, 'notes/bad[1].md');- write(repo, 'gone.md');- write(repo, 'ignored/i.md');- write(repo, 'notes/x.secret.md');- symlinkSync('notes/a.md', join(repo, 'link.md'));- symlinkSync('notes', join(repo, 'linkdir'));- sh(repo, 'git add -A && git commit -q -m fixture');- // Still in the index but gone from disk: listed by --cached, dropped by lstat.- rmSync(join(repo, 'gone.md'));- // Untracked and not ignored: listed by --others.- write(repo, 'notes/untracked.md');- write(repo, 'ignored/j.md');-- // Not a git work tree: both variants take the FS walk.- plain = mkdtempSync(join(tmpdir(), 'gbrain-walk-async-plain-'));- write(plain, 'a.md');- write(plain, 'sub/b.md');- write(plain, 'sub/c.ts', 'export const c = 1;\n');- write(plain, '.hidden/d.md');- symlinkSync('a.md', join(plain, 'link.md'));-});--afterAll(() => {- rmSync(repo, { recursive: true, force: true });- rmSync(plain, { recursive: true, force: true });-});--const STRATEGIES = ['markdown', 'code', 'auto'] as const;-const VARIANTS = [{}, { includeHidden: ['.dira/**'] }, { includeGitignored: true }];--async function expectSameAsSync(dir: string, opts: { strategy: (typeof STRATEGIES)[number]; includeHidden?: string[]; includeGitignored?: boolean }): Promise<string[]> {- const syncExcluded: string[] = [];- const asyncExcluded: string[] = [];- const expected = walker.collectSyncableFiles(dir, { ...opts, onExcluded: (rel) => { syncExcluded.push(rel); } });- const actual = await walker.collectSyncableFilesAsync(dir, { ...opts, onExcluded: (rel) => { asyncExcluded.push(rel); } });- expect(actual).toEqual(expected);- expect(asyncExcluded).toEqual(syncExcluded);- return actual;-}--describe('collectSyncableFilesAsync matches collectSyncableFiles', () => {- test('git work tree: every strategy x hidden/gitignored variant', async () => {- for (const strategy of STRATEGIES) {- for (const variant of VARIANTS) await expectSameAsSync(repo, { strategy, ...variant });- }- });-- test('non-git directory: the FS-walk fallback', async () => {- for (const strategy of STRATEGIES) await expectSameAsSync(plain, { strategy });- });-- test('a directory the repository ignores: the same FS-walk fallback', async () => {- const ignored = join(repo, 'ignored');- for (const strategy of STRATEGIES) await expectSameAsSync(ignored, { strategy });- const files = await walker.collectSyncableFilesAsync(ignored, { strategy: 'markdown' });- expect(files.map((f) => relative(ignored, f))).toEqual(['i.md', 'j.md']);- });-- test('multimodal admission applies to both', async () => {- await withEnv({ GBRAIN_EMBEDDING_MULTIMODAL: 'true' }, async () => {- for (const strategy of ['markdown', 'auto'] as const) {- const files = await expectSameAsSync(repo, { strategy });- expect(files).toContain(join(repo, 'img/pic.png'));- }- });- });-- test('the git fast path keeps its filters: tracked + untracked, no ignored, pruned, metafile, malformed, symlinked or index-only paths', async () => {- const excluded: string[] = [];- const files = await walker.collectSyncableFilesAsync(repo, { strategy: 'markdown', onExcluded: (rel) => { excluded.push(rel); } });- expect(files.map((f) => relative(repo, f))).toEqual(['notes/a.md', 'notes/b.md', 'notes/untracked.md']);- expect(excluded).toEqual(['notes/bad[1].md']);- });-});--describe('collectSyncableFilesAsync does not hold the event loop', () => {- test('a timer queued before the walk fires before the walk resolves', async () => {- const big = mkdtempSync(join(tmpdir(), 'gbrain-walk-async-big-'));- try {- gitInit(big);- writeLargeWorktree(big, 2000);- let fired = false;- setTimeout(() => { fired = true; }, 0);- const files = await walker.collectSyncableFilesAsync(big, { strategy: 'markdown' });- expect(files.length).toBe(2000);- // A walk that runs to completion without yielding (the synchronous- // ls-files + lstat loop) resolves before any timer can run.- expect(fired).toBe(true);- } finally {- rmSync(big, { recursive: true, force: true });- }- });-});--describe('reusableWalk: a full sync reuses the import walk only when it is complete and option-identical', () => {- const options: WalkOptions = { strategy: 'markdown', includeGitignored: false, includeHidden: ['.dira/**'], exclude: ['notes/b.md'] };- const walk: CollectedWalk = { complete: true, root: '/brain', options, files: ['notes/a.md'] };-- test('the same root and options reuse it', () => {- expect(reusableWalk(walk, '/brain', walkOptions({ strategy: 'markdown', includeHidden: ['.dira/**'], exclude: ['notes/b.md'] }))).toBe(true);- });-- test('an incomplete or missing walk is walked again', () => {- expect(reusableWalk({ ...walk, complete: false } as unknown as CollectedWalk, '/brain', options)).toBe(false);- expect(reusableWalk(undefined, '/brain', options)).toBe(false);- });-- test('a different root, strategy, gitignore mode, --include-hidden or --exclude is walked again', () => {- expect(reusableWalk(walk, '/brain/sub', options)).toBe(false);- expect(reusableWalk(walk, '/brain', { ...options, strategy: 'auto' })).toBe(false);- expect(reusableWalk(walk, '/brain', { ...options, includeGitignored: true })).toBe(false);- expect(reusableWalk(walk, '/brain', { ...options, includeHidden: [] })).toBe(false);- expect(reusableWalk(walk, '/brain', { ...options, exclude: ['notes/c.md'] })).toBe(false);- expect(reusableWalk(walk, '/brain', { ...options, exclude: [] })).toBe(false);- });-});diff --git a/test/sync-full-walk-once.test.ts b/test/sync-full-walk-once.test.tsdeleted file mode 100644index 2584d9bd74..0000000000--- a/test/sync-full-walk-once.test.ts+++ /dev/null@@ -1,177 +0,0 @@-/**- * `sync --full` file walk: it runs without holding the event loop, a full sync- * with nothing to delete walks the tree once, and a deletion is never decided- * on runImport's walk alone.- *- * runImport walks the tree with `collectSyncableFilesAsync` and hands the- * completed walk to performFullSync (`onCollected`). The hold settle and the- * delete reconcile reuse it only when it completed for the same root with the- * same options. The walk predates the import, so a file restored after it is- * missing from it: when the reused walk names any page stale, the reconcile- * walks the tree again and decides on that fresh listing.- *- * The git shim counts `git ls-files` listings and, on request, restores a file- * right after the first listing is taken (between the import walk and the- * reconcile).- */--import { describe, test, expect, beforeAll, afterAll, beforeEach, afterEach } from 'bun:test';-import { mkdtempSync, writeFileSync, rmSync, mkdirSync, readFileSync, existsSync } from 'fs';-import { execFileSync, execSync } from 'child_process';-import { tmpdir } from 'os';-import { join } from 'path';-import { PGLiteEngine } from '../src/core/pglite-engine.ts';-import { runSources } from '../src/commands/sources.ts';-import { performSync } from '../src/commands/sync.ts';-import { runImport } from '../src/commands/import.ts';-import { resetPgliteState } from './helpers/reset-pglite.ts';-import { withEnv } from './helpers/with-env.ts';--const SOURCE = 'walk-once';-let engine: PGLiteEngine;-let repo: string;-let shimDir: string;--beforeAll(async () => {- engine = new PGLiteEngine();- await engine.connect({});- await engine.initSchema();-});--afterAll(async () => {- await engine.disconnect();-});--beforeEach(async () => {- await resetPgliteState(engine);- const rows = await engine.executeRaw<{ id: string }>(`SELECT id FROM sources WHERE id = $1`, [SOURCE]);- if (rows.length === 0) await runSources(engine, ['add', SOURCE, '--no-federated']);- repo = mkdtempSync(join(tmpdir(), 'gbrain-walk-once-'));- execSync('git init -q && git config user.email "[email protected]" && git config user.name "T"', { cwd: repo, stdio: 'pipe' });- mkdirSync(join(repo, 'notes'), { recursive: true });- for (const name of ['a', 'b', 'c', 'd']) {- writeFileSync(join(repo, `notes/${name}.md`), note(name));- }- execSync('git add -A && git commit -q -m fixture', { cwd: repo, stdio: 'pipe' });- shimDir = mkdtempSync(join(tmpdir(), 'gbrain-walk-once-shim-'));-});--afterEach(() => {- rmSync(repo, { recursive: true, force: true });- rmSync(shimDir, { recursive: true, force: true });-});--function note(name: string): string {- return `---\ntype: note\ntitle: Note ${name}\n---\n\nBody of ${name}.\n`;-}--function commit(message: string): void {- execSync(`git add -A && git commit -q -m "${message}"`, { cwd: repo, stdio: 'pipe' });-}--function fullSync(opts: { exclude?: string[] } = {}) {- return performSync(engine, { repoPath: repo, full: true, sourceId: SOURCE, noPull: true, noEmbed: true, ...opts });-}--/**- * Runs `fn` with a git on PATH that records every syncable-file listing and returns- * how many it saw. With `restoreAfterFirst`, the first listing is taken before that- * file is written back, so only later listings can include it.- */-async function countListings(fn: () => Promise<unknown>, restoreAfterFirst?: { rel: string; body: string }): Promise<number> {- const realGit = execFileSync('sh', ['-c', 'command -v git'], { encoding: 'utf8' }).trim();- const log = join(shimDir, 'listings.log');- rmSync(log, { force: true });- const restore = restoreAfterFirst ? join(shimDir, 'restore.md') : '';- if (restoreAfterFirst) writeFileSync(restore, restoreAfterFirst.body);- const target = restoreAfterFirst ? join(repo, restoreAfterFirst.rel) : '';- writeFileSync(join(shimDir, 'git'), `#!/bin/sh-case " $* " in- *" ls-files --cached --others --exclude-standard "*)- echo listing >> "${log}"- out=$("${realGit}" "$@" | tr '\\0' '\\n'); rc=$?- if [ -n "${restore}" ] && [ -f "${restore}" ]; then mv "${restore}" "${target}"; fi- printf '%s\\n' "$out" | tr '\\n' '\\0'- exit $rc ;;-esac-exec "${realGit}" "$@"-`, { mode: 0o755 });- await withEnv({ PATH: `${shimDir}:${process.env.PATH}` }, fn);- return existsSync(log) ? readFileSync(log, 'utf8').split('\n').filter(Boolean).length : 0;-}--async function liveSlugs(): Promise<string[]> {- const rows = await engine.executeRaw<{ slug: string }>(- `SELECT slug FROM pages WHERE source_id = $1 AND deleted_at IS NULL ORDER BY slug`, [SOURCE],- );- return rows.map((r) => r.slug);-}--describe('sync --full file walk', () => {- test('the import walk lets timers run while it lists and stats the tree', async () => {- let fired = false;- let firedBeforeWalkDone = null as boolean | null;- const original = console.error;- console.error = (...args: unknown[]) => {- const line = String(args[0] ?? '');- if (line.includes('[gbrain phase] import.collect_files start')) setTimeout(() => { fired = true; }, 0);- else if (line.includes('[gbrain phase] import.collect_files done')) firedBeforeWalkDone = fired;- };- try {- await fullSync();- } finally {- console.error = original;- }- // Between the phase's start and done lines a synchronous walk never yields.- expect(firedBeforeWalkDone).toBe(true);- expect(await liveSlugs()).toEqual(['notes/a', 'notes/b', 'notes/c', 'notes/d']);- });-- test('a full sync with nothing to delete walks once, and the hold settle reuses the import walk', async () => {- // #5988: a file whose frontmatter needs interpretation is held, not failed.- writeFileSync(join(repo, 'notes/held.md'), '---\ntitle: first line\nsecond line\n---\nBody.\n');- commit('add a held file');- expect(await fullSync()).toMatchObject({ holds_outstanding: 1 });-- let second: unknown;- expect(await countListings(async () => { second = await fullSync({ exclude: ['notes/b.md'] }); })).toBe(1);- // The held file is still on disk, so its hold stays; the excluded b keeps its page.- expect(second).toMatchObject({ holds_outstanding: 1 });- expect(await liveSlugs()).toEqual(['notes/a', 'notes/b', 'notes/c', 'notes/d']);- });-- test('a deletion is decided on a fresh walk: a file restored after the import walk keeps its page', async () => {- await fullSync();- expect(await liveSlugs()).toEqual(['notes/a', 'notes/b', 'notes/c', 'notes/d']);-- rmSync(join(repo, 'notes/c.md'));- rmSync(join(repo, 'notes/d.md'));- commit('remove c and d');-- // d is written back after the import walk listed the tree, before the reconcile.- const listings = await countListings(() => fullSync({ exclude: ['notes/b.md'] }), { rel: 'notes/d.md', body: note('d') });- // c is gone from the tree → soft-deleted. d is back on disk → kept. b is excluded but on disk → kept.- expect(await liveSlugs()).toEqual(['notes/a', 'notes/b', 'notes/d']);- expect(listings).toBe(2);- });-- test('runImport hands over its walk only when the walk completed unaborted', async () => {- const handed: unknown[] = [];- await runImport(engine, [repo, '--no-embed'], { sourceId: SOURCE, onCollected: (walk) => { handed.push(walk); } });- expect(handed).toEqual([expect.objectContaining({ complete: true, root: repo, files: ['notes/a.md', 'notes/b.md', 'notes/c.md', 'notes/d.md'] })]);-- handed.length = 0;- const controller = new AbortController();- const original = console.error;- console.error = (...args: unknown[]) => {- if (String(args[0] ?? '').includes('[gbrain phase] import.collect_files start')) controller.abort();- };- try {- await runImport(engine, [repo, '--no-embed'], { sourceId: SOURCE, signal: controller.signal, onCollected: (walk) => { handed.push(walk); } }).catch(() => undefined);- } finally {- console.error = original;- }- expect(controller.signal.aborted).toBe(true);- expect(handed).toEqual([]);- });-});