Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(import): every import abort prints its reason and next command (#5268, #5487)
time-attack072751ee3ec3
diff --git a/docs/architecture/key-files/commands-4.md b/docs/architecture/key-files/commands-4.mdindex 951e7b0523..bb21888c7e 100644--- a/docs/architecture/key-files/commands-4.md+++ b/docs/architecture/key-files/commands-4.md@@ -7,7 +7,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. `--hop <link_type>:<object|subject>` (repeatable, 1-3) runs a typed chain through `runRelationalChain` locally or `traverse_graph` `hops` on a thin client; it is refused with `--type`/`--depth`/`--direction`, a malformed hop names the fix, and a host that ignored `hops` (older gbrain, detected via `ignoredRemoteParams` or a non-chain response) is refused with the upgrade message. 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.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.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/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`: every preflight/argv failure site (deferred-setup embedding sentinel, missing embedding credentials, invalid `--workers`, missing dir arg, unreadable target, symlinked input root in a managed brain, refused source-filesystem lock admission, configured-root refusals) prints its reason and next command to stderr, then throws the exported typed `ImportAbortError` (carries `exitCode` and, for a refused lock admission, the underlying error as `cause`), 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.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.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/src/commands/import.ts b/src/commands/import.tsindex de014316d7..7af63264a0 100644--- a/src/commands/import.ts+++ b/src/commands/import.ts@@ -6,6 +6,7 @@ import { execFileSync } from 'child_process';import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'path';import { cpus, totalmem } from 'os';import type { BrainEngine } from '../core/engine.ts';+import { OperationError } from '../core/ops/contract.ts';import { importFile, importImageFile, isImageFilePath, type ImportResult } from '../core/import-file.ts';import { gitFirstCommitDates } from '../core/git-first-commit.ts';import { currentCompanyBrainSync, getCompanyBrainProfile, importCompanyBrainFile } from '../core/company-brain/profile.ts';@@ -40,6 +41,7 @@ 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 { managedRootMarkerFor } from '../core/persistence/root-registry.ts';/** Return a refusal when an import target lies outside every admitted root. */export function configuredRootImportError(dir: string, configuredRoots: string[]): string | null {@@ -139,14 +141,43 @@ export class ImportAbortError extends Error {readonly partialResult?: RunImportResult;/** True: the user-facing message was already printed at the throw site. */readonly alreadyReported = true;- constructor(reason: string, exitCode = 1, partialResult?: RunImportResult) {- super(`import aborted: ${reason}`);+ /** `cause` keeps the underlying error (and its stack) for in-process callers. */+ constructor(reason: string, exitCode = 1, partialResult?: RunImportResult, cause?: unknown) {+ super(`import aborted: ${reason}`, cause === undefined ? undefined : { cause });this.name = 'ImportAbortError';this.exitCode = exitCode;this.partialResult = partialResult;}}+// The CLI dispatch (src/cli/commands/import.ts) exits on any ImportAbortError+// without printing, so each refusal below prints its reason and the next+// command to stderr before the caller throws the returned abort.++/** A managed import of a symlinked input root: name the path, its target and the command that works. */+function symlinkedRootAbort(dirArg: string, dir: string): ImportAbortError {+ console.error(`Managed import refuses a symlinked input root: ${dirArg} resolves to ${dir}.`);+ console.error(`Fix: gbrain import ${dir}`);+ return new ImportAbortError('managed import refuses a symlinked input root');+}++/** A refused source filesystem lock admission: print its code, message and fix, and keep it as the cause. */+function lockAdmissionAbort(dirArg: string, dir: string, error: unknown): ImportAbortError {+ const message = error instanceof Error ? error.message : String(error);+ console.error(`Cannot import ${dirArg}: source filesystem lock admission failed.`);+ if (error instanceof OperationError) {+ console.error(`Error [${error.code}]: ${message}`);+ if (error.suggestion) console.error(`Fix: ${error.suggestion}`);+ const marker = error.code === 'writer_coordinator_required' ? managedRootMarkerFor(dir)?.marker : undefined;+ if (marker) console.error(`Marker: ${marker}`);+ } else {+ console.error(`Error: ${message}`);+ console.error('Fix: gbrain doctor --json');+ }+ const reason = error instanceof OperationError ? `${error.code}: ${message}` : message;+ return new ImportAbortError(`source filesystem lock admission failed (${reason})`, 1, undefined, error);+}+/*** #3969 — a poll that changed nothing is not an ingest event. Cron-driven* `import`/`sync` against a mostly-static tree was writing an ingest_log row@@ -471,7 +502,7 @@ export async function runImport(const [persistence] = await engine.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1');const managedImport = persistence?.enabled === true;- if (managedImport && dir !== resolve(dirArg)) throw new ImportAbortError('managed import refuses a symlinked input root');+ if (managedImport && dir !== resolve(dirArg)) throw symlinkedRootAbort(dirArg, dir);const singleFile = managedImport && lstatSync(dir).isFile();const importRoot = singleFile ? dirname(dir) : dir;@@ -486,7 +517,7 @@ export async function runImport(// Root discovery is part of admission. Preserve the CLI/library's typed// preflight error contract without changing errors from an import in flight.if (entered || signal?.aborted) throw error;- throw new ImportAbortError('source filesystem lock admission failed');+ throw lockAdmissionAbort(dirArg, dir, error);}}diff --git a/src/core/persistence/filesystem-guard.ts b/src/core/persistence/filesystem-guard.tsindex f947fdc9df..d5cfc69333 100644--- a/src/core/persistence/filesystem-guard.ts+++ b/src/core/persistence/filesystem-guard.ts@@ -63,7 +63,7 @@ export function assertManagedFilesystemWrite(path: string): void {if (!managed || hasFilesystemPublication(path)) return;// #5279: name the root, its source and the evidence, so a stray ownership file is findable.const error = new OperationError('writer_coordinator_required',- `This file belongs to the managed canonical worktree ${managed.root}${managed.sourceId ? ` (source ${managed.sourceId})` : ''}.`,+ `This path belongs to the managed canonical worktree ${managed.root}${managed.sourceId ? ` (source ${managed.sourceId})` : ''}.`,'Submit the change through the persistence coordinator; check the root with gbrain sources writer status.');error.detail = `root=${managed.root} source=${managed.sourceId ?? 'unknown'} evidence=${managed.evidence}`;throw error;diff --git a/src/core/source-resolver.ts b/src/core/source-resolver.tsindex 6e71037018..b3b5c2a880 100644--- a/src/core/source-resolver.ts+++ b/src/core/source-resolver.ts@@ -586,7 +586,8 @@ export function formatDefaultWriteWarning(a: DefaultWriteAssessment, sourceFlag?return (`[gbrain] WARNING: writing to source 'default' on a multi-source brain ` +`(${a.nonDefaultSources} non-default source(s), ${a.nonDefaultPages} pages). ` +- `${escape} to scope writes and avoid cross-source duplicate slugs.`+ `${escape} to scope writes and avoid cross-source duplicate slugs.` ++ (sourceFlag ? ` GBRAIN_SOURCE=<id> works too; GBRAIN_ALLOW_DEFAULT_WRITE=1 keeps 'default' on purpose.` : ''));}diff --git a/test/import-abort-error.test.ts b/test/import-abort-error.test.tsindex 88d2232d05..f8a698386f 100644--- a/test/import-abort-error.test.ts+++ b/test/import-abort-error.test.ts@@ -9,7 +9,10 @@* site maps the typed error back to exit(1), keeping CLI behavior identical.*/-import { test, expect } from 'bun:test';+import { test, expect, spyOn } from 'bun:test';+import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';import { runImport, ImportAbortError } from '../src/commands/import.ts';import type { BrainEngine } from '../src/core/engine.ts';@@ -22,18 +25,33 @@ const engineStub = {getConfig: async () => null,} as unknown as BrainEngine;-async function expectAbort(args: string[], reasonFragment: string): Promise<void> {+// The CLI dispatch (src/cli/commands/import.ts) exits on any ImportAbortError+// without printing, so every abort must write its reason to stderr first.+async function expectAbort(+ args: string[],+ reasonFragment: string,+ stderrFragments: string[] = [],+ engine: BrainEngine = engineStub,+): Promise<ImportAbortError> {+ const stderr = spyOn(console, 'error').mockImplementation(() => {});let thrown: unknown;+ let printed = '';try {- await runImport(engineStub, args);+ await runImport(engine, args);} catch (e) {thrown = e;+ } finally {+ printed = stderr.mock.calls.map(call => call.join(' ')).join('\n');+ stderr.mockRestore();}expect(thrown).toBeInstanceOf(ImportAbortError);const err = thrown as ImportAbortError;expect(err.exitCode).toBe(1);expect(err.alreadyReported).toBe(true);expect(err.message).toContain(reasonFragment);+ expect(printed).not.toBe('');+ for (const fragment of stderrFragments) expect(printed).toContain(fragment);+ return err;}test('missing dir arg → typed abort, not process death', async () => {@@ -48,8 +66,76 @@ test('unreadable import target → typed abort', async () => {await expectAbort(['--no-embed', '/definitely/not/a/real/dir-w0-test'], 'not readable');});+// Sites that refuse a real directory: each case builds its fixture under a+// canonical temp root and names what the user must see on stderr.+const answering = (match: string, rows: unknown[] | Error): BrainEngine => ({+ ...engineStub,+ executeRaw: async (sql: string) => {+ if (!sql.includes(match)) return [];+ if (rows instanceof Error) throw rows;+ return rows;+ },+}) as unknown as BrainEngine;++const directoryCases: Array<{+ name: string;+ setup: (root: string) => string;+ engine?: BrainEngine;+ reason: string;+ stderr: (root: string) => string[];+ cause?: string;+}> = [+ {+ name: 'lock admission refused by a managed-worktree marker (#5487)',+ setup: root => {+ writeFileSync(join(root, '.gbrain-managed'), '');+ return join(root, 'notes');+ },+ reason: 'writer_coordinator_required',+ stderr: root => [+ 'source filesystem lock admission failed.',+ `Error [writer_coordinator_required]: This path belongs to the managed canonical worktree ${root}.`,+ 'Fix: Submit the change through the persistence coordinator; check the root with gbrain sources writer status.',+ `Marker: ${join(root, '.gbrain-managed')}`,+ ],+ },+ {+ name: 'lock admission fails on a non-operation error',+ setup: root => join(root, 'notes'),+ engine: answering("local_path <> ''", new Error('synthetic sources lookup failure')),+ reason: 'synthetic sources lookup failure',+ stderr: () => ['Error: synthetic sources lookup failure', 'Fix: gbrain doctor --json'],+ cause: 'synthetic sources lookup failure',+ },+ {+ name: 'managed brain refuses a symlinked input root',+ setup: root => {+ symlinkSync(join(root, 'notes'), join(root, 'notes-link'));+ return join(root, 'notes-link');+ },+ engine: answering('FROM persistence_brain', [{ enabled: true }]),+ reason: 'symlinked input root',+ stderr: root => [`Managed import refuses a symlinked input root: ${join(root, 'notes-link')} resolves to ${join(root, 'notes')}.`,+ `Fix: gbrain import ${join(root, 'notes')}`],+ },+];++for (const c of directoryCases) {+ test(`${c.name} → typed abort that prints the reason`, async () => {+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'import-abort-')));+ try {+ mkdirSync(join(root, 'notes'));+ writeFileSync(join(root, 'notes', 'alpha-example.md'), '# Alpha example\n');+ const err = await expectAbort(['--no-embed', c.setup(root)], c.reason, c.stderr(root), c.engine);+ if (c.cause) expect((err.cause as Error).message).toBe(c.cause);+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ });+}+test('the calling process survives the abort (the actual Tier-1 bug)', async () => {- // Trivially true if we got here after three aborts above, but assert it+ // Trivially true if we got here after the aborts above, but assert it// explicitly: the process is alive and can keep dispatching.expect(process.pid).toBeGreaterThan(0);});diff --git a/test/import-default-write-warning-5268.test.ts b/test/import-default-write-warning-5268.test.tsnew file mode 100644index 0000000000..19fe119fb2--- /dev/null+++ b/test/import-default-write-warning-5268.test.ts@@ -0,0 +1,46 @@+/**+ * #5268: an unscoped import on a multi-source brain stays advisory (rc 0,+ * the page is imported) and the warning names the commands that scope or+ * confirm the destination. Authoring gate: (1) protects the warning text and+ * the import result; (2) fails when the warning drops the scoping commands+ * or turns into a refusal; (3) import-default-write-warn-destination pins+ * only the destination; (4) no production seam.+ */+import { afterAll, beforeAll, expect, spyOn, test } from 'bun:test';+import { mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { runImport } from '../src/commands/import.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { withEnv } from './helpers/with-env.ts';++let engine: PGLiteEngine;+beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await engine.executeRaw("INSERT INTO sources (id, name) VALUES ('alpha', 'alpha') ON CONFLICT DO NOTHING");+ await engine.putPage('notes/default-example', { type: 'note', title: 'Default example', compiled_truth: 'Default.' });+ for (const slug of ['notes/alpha-one', 'notes/alpha-two', 'notes/alpha-three']) {+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: 'Alpha.' }, { sourceId: 'alpha' });+ }+}, 60_000);+afterAll(async () => { await engine.disconnect(); });++test('an unscoped import on a multi-source brain warns, names the scoping commands, and still imports', async () => {+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'import-default-warning-')));+ const stderr = spyOn(console, 'error').mockImplementation(() => {});+ try {+ writeFileSync(join(root, 'beta-example.md'), '# Beta example\n');+ const result = await withEnv({ GBRAIN_SOURCE: undefined, GBRAIN_ALLOW_DEFAULT_WRITE: undefined }, () => runImport(engine, ['--no-embed', root]));+ expect(result.errors).toBe(0);+ const printed = stderr.mock.calls.map(call => call.join(' ')).join('\n');+ expect(printed).toContain("WARNING: writing to source 'default' on a multi-source brain");+ expect(printed).toContain('Pass --source-id <id>');+ expect(printed).toContain('GBRAIN_SOURCE=<id> works too');+ expect(printed).toContain('GBRAIN_ALLOW_DEFAULT_WRITE=1');+ } finally {+ stderr.mockRestore();+ rmSync(root, { recursive: true, force: true });+ }+}, 60_000);