Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(GBRA-130 A-18): sync ledger classifies errno before text and never reads path text as a provider error; isolated infra failures go chronic; run-scoped errors stop the sync
garrytana051f3655fca
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.mdindex 60cb951966..020f99a055 100644--- a/docs/architecture/KEY_FILES.md+++ b/docs/architecture/KEY_FILES.md@@ -66,8 +66,8 @@ link it here rather than raising the cap.| [Engines (2/2)](key-files/engines-2.md) | `src/core/pglite-resetwal.ts` through `src/core/worker-pool.ts` || [Entrypoints And Docs](key-files/entrypoints-and-docs.md) | `.agents/gbrain-launcher` through `templates/` || [Evaluation](key-files/evaluation.md) | `evals/brainbench/` through `src/eval/shared/judge-runner.ts` |-| [Files And Sync (1/2)](key-files/files-and-sync-1.md) | `src/core/audit-week-file.ts` through `src/core/sync-git.ts:resolveSlugByPathOrSourcePath` |-| [Files And Sync (2/2)](key-files/files-and-sync-2.md) | `src/core/sync-policy.ts` through `src/core/write-through.ts` |+| [Files And Sync (1/2)](key-files/files-and-sync-1.md) | `src/core/audit-week-file.ts` through `src/core/sync-embed-backfill.ts` |+| [Files And Sync (2/2)](key-files/files-and-sync-2.md) | `src/core/sync-failure-ledger.ts` through `src/core/write-through.ts` || [Graph And Facts](key-files/graph-and-facts.md) | `src/core/check-resolvable.ts` through `src/core/trajectory-format.ts` || [Entity recall](key-files/entity-recall.md) | `src/core/mentions/*`, `src/core/ops/backlinks-paged.ts`, `extract mentions --explain`, migration v206 || [Mcp](key-files/mcp.md) | `src/mcp/dispatch.ts` through `src/mcp/validate-params.ts` |diff --git a/docs/architecture/key-files/files-and-sync-1.md b/docs/architecture/key-files/files-and-sync-1.mdindex fdc63fc89f..af46bff805 100644--- a/docs/architecture/key-files/files-and-sync-1.md+++ b/docs/architecture/key-files/files-and-sync-1.md@@ -59,7 +59,3 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/sync-delta.ts` — the single "what changed since last_commit" helper, consumed by BOTH `performSyncInner` (sync executor) and `estimateInlineNewTokens` (cost estimator) so the gate's dollar figure can't drift from what the sync imports. `computeSyncDelta(repoPath, fromCommit, toCommit, {detachedManifest?, detached?})` → `{status:'ok', manifest}` | `{status:'unavailable', reason:'anchor_missing'|'diff_failed'}`. Anchor reachability via `git cat-file -t` (a gc'd bookmark is `anchor_missing`, but a present-but-non-ancestor bookmark is still diffed tree-to-tree), then `git diff --name-status -M from..to` parsed by `buildSyncManifest`; merges the detached working-tree manifest when detached (`buildDetachedWorkingTreeManifest`). NO dirty/untracked probe in the estimator — pricing dirty files would create phantom costs on a busy brain. The executor imports only the commit diff on attached HEADs BY DEFAULT, but counts uncommitted working-tree files (untracked + dirty) as `SyncResult.uncommitted` drift and, with `--working-tree` / config `sync.include_working_tree`, merges the working-tree manifest into the delta so attached repos can import uncommitted state (the estimator does not price that opt-in). `execFileSync` array-args (shell-injection safe), 30s / 100 MiB budget. Test seam `_setGitRunnerForTests`. Pinned by `test/sync-delta.test.ts`.- `src/core/sync-embed-backfill.ts` — Sync command’s engine-aware embedding-delivery seam. It derives separate worker-backed deferral and multi-source fan-out eligibility, keeps automatic-submission policy distinct from capability, invokes the shared cost gate for `--all` and single-source runs, propagates intrinsic large-sync deferral into final delivery outcomes, resolves backfill results through the centralized submitter, formats one truthful human status, and builds the single-source JSON envelope. `syncProducedEmbeddableContent` is the one content gate every automatic submit site (`sync --all`, single-source autodefer, the jobs `sync` handler) applies on top of status: a sweep-only or delete-only run reports `synced` but wrote no chunks, and minting a backfill for it would only arm the per-source cooldown against the next real import (the handler reports `embed_skip_reason: 'no_new_content'`). Keeping these pieces together prevents cost-gate, queue, human, and machine surfaces from drifting while the size-ratcheted `src/commands/sync.ts` façade stays at its committed ceiling.--- `src/core/sync-failure-ledger.ts` — the bounded auto-skip sync failure ledger. A LEAF module (imports only fs/path/crypto/config) so `sync.ts` can re-export it without a circular dependency. State lives in `~/.gbrain/sync-failures.jsonl`, one JSON object per line, keyed by `(source_id, path)` with a per-key `attempts` count and a 3-state machine: `open` (fresh/blocking) → `auto_skipped` (chronic, still doctor-visible) or `acknowledged` (human resolved via `gbrain sync --skip-failed` from either unresolved state). `classifyErrorCode(errorMsg)` regex classifier with 23 named codes (`RENAME_RECONCILE`, `SLUG_MISMATCH`, `DB_DUPLICATE_KEY`, `STATEMENT_TIMEOUT`, `YAML_PARSE`, `YAML_DUPLICATE_KEY`, `MISSING_OPEN`, `MISSING_CLOSE`, `EMPTY_FRONTMATTER`, `NULL_BYTES`, `NESTED_QUOTES`, `INVALID_UTF8`, `FILE_TOO_LARGE`, `SYMLINK_NOT_ALLOWED`, `TAKES_TABLE_MALFORMED`, `TAKES_HOLDER_INVALID`, `EMBEDDING_NO_CREDS`, `EMBEDDING_NO_TOUCHPOINT`, `EMBEDDING_TIMEOUT`, `EMBEDDING_RATE_LIMIT`, `EMBEDDING_QUOTA`, `EMBEDDING_OVERSIZE`, `PAGE_JUNK_PATTERN`) plus `UNKNOWN` (the default fallthrough); `summarizeFailuresByCode(failures)` returns sorted `[{code, count}]`; `MISSING_OPEN`/`EMPTY_FRONTMATTER` regexes match the `markdown.ts` validator strings; `MISSING_CLOSE`'s regex is stale against current `markdown.ts` output — it matches the no-heading-hint case (`No closing --- delimiter found`) but not the heading-hint case (`No closing --- before heading at line N`), which falls through to `UNKNOWN`. `FILE_TOO_LARGE` covers `import-file.ts:395, 1236, 1436` (markdown/text, plain-file, and code-file import paths), `SYMLINK_NOT_ALLOWED` covers `:1231, 2038` (file and image import paths). `EMBEDDING_INFRA_CODES` is the subset (`EMBEDDING_TIMEOUT`/`EMBEDDING_RATE_LIMIT`/`EMBEDDING_QUOTA`) that means the embedding PROVIDER is unhealthy rather than the file being poison — `isEmbeddingInfraCode(code)` is consulted inside `decideGateAction`'s chronic-eligibility loop so these three are never counted toward auto-skip (treated as fresh, forcing `block` instead of `advance_then_autoskip`); an explicit `--skip-failed` still advances past them like any other failure, since that check runs before the loop. All mutations run under `withLedgerLock` (cross-process file lock) with an atomic rename write. The auto-skip threshold resolves via `resolveAutoSkipThreshold()` from `GBRAIN_SYNC_AUTOSKIP_AFTER` (default `DEFAULT_AUTOSKIP_AFTER = 3`; `0` disables the valve = pure fail-closed). Two pure decision functions are the unit-test surface: `decideGateAction({fileFailures, sentinels, attemptsByPath, threshold, skipFailed})` returns `hard_block | block | advance | advance_then_autoskip` (sentinels like `<head>` ALWAYS hard-block, even with `--skip-failed`, so a history rewrite can't auto-skip; any FRESH failure with `attempts < threshold` blocks fail-closed; only when ALL failures are chronic does it `advance_then_autoskip`), and `decideSyncFailureSeverity({entries, nowMs, failHours})` returns the `sync_failures` doctor status (`ok` when zero unresolved; `fail` when ≥10 OPEN-blocking or the oldest OPEN failure's `ts` (last attempt, NOT `first_seen`) is older than `failHours` — a failure retried inside that window keeps refreshing `ts` and never trips this leg even if `first_seen` is much older; otherwise `warn` — `auto_skipped`-only rows stay WARN-visible regardless of count because the bookmark already advanced). `applySyncFailureGate(input)` is the one orchestrator BOTH sync paths (incremental + full/`runImport`) call: it records/clears ledger rows, runs `decideGateAction`, then executes effects in the crash-safe order (advance the bookmark FIRST via the injected `advance()` callback, THEN auto-skip the chronic set) so a crash can never mark a file skipped while leaving sync wedged. `isSkippablePath` rejects `<…>` sentinels. Pinned by `test/sync-failure-ledger.serial.test.ts` + `test/sync-failures.test.ts`.--- `src/core/sync-git.ts:resolveSlugByPathOrSourcePath` — Resolves a slug by `pages.source_path` first (returns the stored slug for frontmatter-fallback pages whose path doesn't derive a slug), then falls back to `resolveSlugForPath(path)`. Three call sites: the un-syncable cleanup (which passes `opts.sourceId`), and the bare no-`sourceId` delete and rename-source paths; when `sourceId` IS set the delete and rename loops batch through `engine.resolveSlugsByPaths` instead. The `source_path` lookup is scoped to the DEFAULT source on the bare path, matching every write that path performs (`updateSlug`, `deletePage`, the rename bookkeeping repair are all default-scoped) — an unscoped lookup could return a row from another source sharing the `source_path`, and the rename loop consumes this value directly as its cheap-move source slug. Without the helper, emoji-only / Thai / Arabic filenames whose slug came from frontmatter would orphan on delete/rename (that path would compute the wrong path-derived slug). Best-effort query — pre-migration brains fall through to the legacy path.diff --git a/docs/architecture/key-files/files-and-sync-2.md b/docs/architecture/key-files/files-and-sync-2.mdindex 2e8a7a4958..6531d1b0a8 100644--- a/docs/architecture/key-files/files-and-sync-2.md+++ b/docs/architecture/key-files/files-and-sync-2.md@@ -3,6 +3,10 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.+- `src/core/sync-failure-ledger.ts` — the bounded auto-skip sync failure ledger. A LEAF module (imports only fs/path/crypto/config) so `sync.ts` can re-export it without a circular dependency. State lives in `~/.gbrain/sync-failures.jsonl`, one JSON object per line, keyed by `(source_id, path)` with a per-key `attempts` count and a 3-state machine: `open` (fresh/blocking) → `auto_skipped` (chronic, still doctor-visible) or `acknowledged` (human resolved via `gbrain sync --skip-failed` from either unresolved state). `classifyErrorCode(errorMsg)` regex classifier with 23 named codes (`RENAME_RECONCILE`, `SLUG_MISMATCH`, `DB_DUPLICATE_KEY`, `STATEMENT_TIMEOUT`, `YAML_PARSE`, `YAML_DUPLICATE_KEY`, `MISSING_OPEN`, `MISSING_CLOSE`, `EMPTY_FRONTMATTER`, `NULL_BYTES`, `NESTED_QUOTES`, `INVALID_UTF8`, `FILE_TOO_LARGE`, `SYMLINK_NOT_ALLOWED`, `TAKES_TABLE_MALFORMED`, `TAKES_HOLDER_INVALID`, `EMBEDDING_NO_CREDS`, `EMBEDDING_NO_TOUCHPOINT`, `EMBEDDING_TIMEOUT`, `EMBEDDING_RATE_LIMIT`, `EMBEDDING_QUOTA`, `EMBEDDING_OVERSIZE`, `PAGE_JUNK_PATTERN`) plus `UNKNOWN` (the default fallthrough); `summarizeFailuresByCode(failures)` returns sorted `[{code, count}]`; `MISSING_OPEN`/`EMPTY_FRONTMATTER` regexes match the `markdown.ts` validator strings; `MISSING_CLOSE`'s regex is stale against current `markdown.ts` output — it matches the no-heading-hint case (`No closing --- delimiter found`) but not the heading-hint case (`No closing --- before heading at line N`), which falls through to `UNKNOWN`. `FILE_TOO_LARGE` covers `import-file.ts:395, 1236, 1436` (markdown/text, plain-file, and code-file import paths), `SYMLINK_NOT_ALLOWED` covers `:1231, 2038` (file and image import paths). `EMBEDDING_INFRA_CODES` is the subset (`EMBEDDING_TIMEOUT`/`EMBEDDING_RATE_LIMIT`/`EMBEDDING_QUOTA`) that means the embedding PROVIDER is unhealthy rather than the file being poison — `isEmbeddingInfraCode(code)` is consulted inside `decideGateAction`'s chronic-eligibility loop so these three are never counted toward auto-skip (treated as fresh, forcing `block` instead of `advance_then_autoskip`); an explicit `--skip-failed` still advances past them like any other failure, since that check runs before the loop. All mutations run under `withLedgerLock` (cross-process file lock) with an atomic rename write. The auto-skip threshold resolves via `resolveAutoSkipThreshold()` from `GBRAIN_SYNC_AUTOSKIP_AFTER` (default `DEFAULT_AUTOSKIP_AFTER = 3`; `0` disables the valve = pure fail-closed). Two pure decision functions are the unit-test surface: `decideGateAction({fileFailures, sentinels, attemptsByPath, threshold, skipFailed})` returns `hard_block | block | advance | advance_then_autoskip` (sentinels like `<head>` ALWAYS hard-block, even with `--skip-failed`, so a history rewrite can't auto-skip; any FRESH failure with `attempts < threshold` blocks fail-closed; only when ALL failures are chronic does it `advance_then_autoskip`), and `decideSyncFailureSeverity({entries, nowMs, failHours})` returns the `sync_failures` doctor status (`ok` when zero unresolved; `fail` when ≥10 OPEN-blocking or the oldest OPEN failure's `ts` (last attempt, NOT `first_seen`) is older than `failHours` — a failure retried inside that window keeps refreshing `ts` and never trips this leg even if `first_seen` is much older; otherwise `warn` — `auto_skipped`-only rows stay WARN-visible regardless of count because the bookmark already advanced). `applySyncFailureGate(input)` is the one orchestrator BOTH sync paths (incremental + full/`runImport`) call: it records/clears ledger rows, runs `decideGateAction`, then executes effects in the crash-safe order (advance the bookmark FIRST via the injected `advance()` callback, THEN auto-skip the chronic set) so a crash can never mark a file skipped while leaving sync wedged. `isSkippablePath` rejects `<…>` sentinels. Pinned by `test/sync-failure-ledger.serial.test.ts` + `test/sync-failures.test.ts`. GBRA-130 A-18: the module imports `BILLING_MESSAGE_RE`/`RATE_MESSAGE_RE` from the import-free `ai/errors.ts` (still a leaf). `classifyErrorCode(msg, path?)` never reads path text as a provider error: errno-led messages map to `PERMISSION_DENIED` (EACCES/EPERM) or `FILE_UNREADABLE` (ENOENT and other file errnos), and the infra regexes run on the message with the embed envelope, the path and its tokens stripped, so `billing/q3.md` or `http-429.md` no longer read as `EMBEDDING_QUOTA`/`EMBEDDING_RATE_LIMIT`. `syncFailureCode(error, path)` takes the structured errno first (the import paths pass `SyncFailedFile.code`). `SyncGateInput` gains `code`, `imported` and `systemic`: a run where files imported records `infra_isolated_runs` on an open infra row, and `decideGateAction` treats an infra row with `infra_isolated_runs >= threshold` as chronic, auto-skipped with code `EMBEDDING_INFRA_ISOLATED`; a run where nothing imported never counts toward it. A systemic run (the `sync.import_files` ItemRun breaker, most files failing) adds no attempt to open rows, starts new rows at 1, blocks, and `finalize.ts` prints a blocked message naming `--skip-failed`. Pinned by `test/pathological/a18-ledger-path-text.test.ts` (both engines).++- `src/core/sync-git.ts:resolveSlugByPathOrSourcePath` — Resolves a slug by `pages.source_path` first (returns the stored slug for frontmatter-fallback pages whose path doesn't derive a slug), then falls back to `resolveSlugForPath(path)`. Three call sites: the un-syncable cleanup (which passes `opts.sourceId`), and the bare no-`sourceId` delete and rename-source paths; when `sourceId` IS set the delete and rename loops batch through `engine.resolveSlugsByPaths` instead. The `source_path` lookup is scoped to the DEFAULT source on the bare path, matching every write that path performs (`updateSlug`, `deletePage`, the rename bookkeeping repair are all default-scoped) — an unscoped lookup could return a row from another source sharing the `source_path`, and the rename loop consumes this value directly as its cheap-move source slug. Without the helper, emoji-only / Thai / Arabic filenames whose slug came from frontmatter would orphan on delete/rename (that path would compute the wrong path-derived slug). Best-effort query — pre-migration brains fall through to the legacy path.+- `src/core/import-chunk-reuse.ts` — `reuseStoredChunkVectors`: A13 vector reuse for one markdown page import, shared by the inline import (before its transaction, to decide which chunks reach the provider) and every import's transaction (under the page lock, `importFromContent` in `import-file.ts`). It copies each stored vector the reuse gate admits onto its matching new chunk and maps the chunk to the stored row id when that row already holds exactly what the chunk would insert, so the import keeps it in place and deletes and writes only the rest; with `keepUnembedded` (the in-transaction pass) an identical never-embedded row stays under a new chunk that carries no vector either. Inline, `--no-embed` and prepared imports all keep rows; a prepared import reuses nothing from a page stored under per-chunk synopsis. Pinned by `test/import-inline-chunk-keep.test.ts` (both engines) and `test/persistence-edit-embedding-reuse.test.ts`. `reuseSegmentChunkVectors` (Wave B) reads only the rows of the retired occurrences with their vectors and applies the same gate and `chunk_source\0chunk_text` plan, so an unchanged chunk inside a rewritten tail keeps its vector.- `src/core/sync-policy.ts` — `isSyncDisabledConfig(config)`: the one predicate for `config.syncEnabled === false` ("excluded from AUTOMATIC/bulk sync"), unwrapping PGLite's JSON-string config scalar via `parseSourceConfig`. Read by the `sync --all` fan-out filter (`src/commands/sync.ts`), autopilot's per-source freshness dispatcher (`src/commands/autopilot.ts`, skip before `queue.add('sync')`) and the full-cycle fan-out (`src/commands/autopilot-fanout.ts`, which drops the `sync` phase + pull from a disabled source's `autopilot-cycle` payload but keeps lint/backlinks/extract and the freshness stamp) and the `sync_enabled` column of `buildSyncStatusReport` (`src/core/sync-status-report.ts`, whose callers pass RAW `SELECT config` rows — a JSON string on PGLite — so a raw cast there contradicted the fan-out filter). Doctor's `checkSyncFreshness` also applies this predicate, including the legacy query fallback: disabled sources contribute neither warnings nor freshness counts; only boolean `false` disables, not the string `'false'`. `checkCycleFreshness` still monitors their maintenance cycles. Pinned by `test/doctor-sync-policy.test.ts` and `test/doctor-cycle-freshness.test.ts`. Deliberately does NOT gate `performSync()`: an explicit `gbrain sync --source <id>` still runs; `sync-cost-gate.ts` keeps its own inline check because it also feeds the explicit single-source cost preview. Pinned by `test/sync-policy.test.ts`, the `#4399` cases in `test/autopilot-fanout-wiring.test.ts` (source-text) and `test/autopilot-fanout.test.ts` (stubbed dispatch).- `src/core/sync-applicability.ts` — agent-first operator wave E4. `syncContentDirectory(engine, {sourceId, repoPath})` resolves the sync root exactly as `performSync` does and returns it when it is a gbrain-owned content directory (under `<GBRAIN_HOME>/.gbrain/content/`, or an owned `--content-root` recorded in the shared-skills setup receipt) with no `.git` at the root; null otherwise (fail-open). `performSync` calls `assertSyncApplicable` first, so such a source refuses with `sync_not_applicable` (reason `content_directory`, fix `gbrain import <dir> [--no-embed] --source <id>`, `git init` named only as an ask-the-user option) before the managed path or the legacy #2964 anchor self-heal could `git init` it. `sync --all` skips these sources with one line; the dream cycle's sync phase reports them `skipped` (`details.reason: sync_not_applicable`). The CLI `sync` record renders fix-carrying OperationErrors through `renderCliError` (`src/cli/commands/sync.ts`). Pinned by `test/sync-applicability.test.ts`.diff --git a/src/commands/sync/finalize.ts b/src/commands/sync/finalize.tsindex e0f652aa27..abed7ab501 100644--- a/src/commands/sync/finalize.ts+++ b/src/commands/sync/finalize.ts@@ -332,6 +332,11 @@ async function applyBookmarkGate(commit: pin,skipFailed: !company && opts.skipFailed === true,...(company ? { threshold: 0 } : {}),+ // GBRA-130 A-18: files imported this run (an infra code on one file while+ // others import goes chronic) and the import breaker's verdict (a run+ // where most files failed counts no attempt and auto-skips nothing).+ imported: run.filesImported,+ systemic: run.itemRun.systemic() !== null,advance,});// #3479 blocker 2 — self-heal for orphaned `<rename:…>` sentinels: a@@ -393,6 +398,15 @@ async function applyBookmarkGate(`${renameDetail || codeBreakdown}\n\n` +renameRemedy,);+ } else if (run.itemRun.systemic()) {+ const fileFailCount = failedFiles.filter(f => isSkippablePath(f.path)).length;+ serr(+ `\nSync blocked: ${fileFailCount} file(s) failed, most of the files this run tried; this looks like ` ++ `a shared cause, so no attempt was counted and nothing auto-skips:\n` ++ `${codeBreakdown}\n${formatFailedFileList(failedFiles)}\n\n` ++ `Fix the shared cause (permissions, the embedding provider, the database) and re-run 'gbrain sync', ` ++ `or acknowledge these files with 'gbrain sync --skip-failed${opts.sourceId ? ` --source ${opts.sourceId}` : ''}'.`,+ );} else {const fileFailCount = failedFiles.filter(f => isSkippablePath(f.path)).length;// #3875: code-aware copy. Provider-infra failures (embed timeout /diff --git a/src/commands/sync/imports.ts b/src/commands/sync/imports.tsindex 23a3103a18..876915435e 100644--- a/src/commands/sync/imports.ts+++ b/src/commands/sync/imports.ts@@ -25,6 +25,7 @@ import {import { isPathSafe } from '../../core/sync-git.ts';import { resolveStallAbortSeconds, composeAbortSignals } from '../../core/sync-reconcile.ts';import { sanitizePathForDisplay } from '../../core/sync.ts';+import { syncFailureCode } from '../../core/sync-failure-ledger.ts';import { isWindowsColonTarget } from '../../core/persistence/native-file-target.ts';import { ERROR_CATALOGUE } from '../../core/error-catalogue.ts';import { enginePoolStats } from '../../core/postgres-engine/pool-stats.ts';@@ -89,6 +90,10 @@ export async function runImportsPhase(// a killed run banks `completed`, the next run skips it (no per-file disk// read or content_hash DB lookup for done files).const importsToDo = resumeFilter(addsAndMods, [...completed]);+ // GBRA-130 A-18: files an earlier run of this drain already banked count as+ // the breaker's successes, so a resumed run that re-attempts only the+ // failing files is not mistaken for a run where most files fail.+ for (let i = importsToDo.length; i < addsAndMods.length; i++) run.itemRun.succeed();const { effectiveConcurrency, runParallel } = await resolveImportConcurrency(engine, opts, importsToDo.length);@@ -351,6 +356,7 @@ async function importOnePath(run: SyncRun, ctx: ImportContext, eng: BrainEngine,// persist. partial() reports this so cron operators see how// much actually landed before --timeout fired.run.filesImported++;+ run.itemRun.succeed();await clearLegacyHold(eng, holds, path);// v0.42.x (#1794): checkpoint this path so a kill banks it.await markCompleted(run, path);@@ -376,12 +382,16 @@ async function importOnePath(run: SyncRun, ctx: ImportContext, eng: BrainEngine,await markCompleted(run, path);}} catch (e: unknown) {+ // GBRA-130 A-18: a run-scoped failure (lost connection, failed+ // transaction, abort, an unavailable writer) stops the sync before the+ // ledger records anything; a file's own failure carries a structured code.+ run.itemRun.record(path, e);const msg = e instanceof Error ? e.message : String(e);if (await holdRefusedImport(eng, holds, path, filePath, { status: 'error', error: msg })) {await markCompleted(run, path);} else {serr(` Warning: skipped ${path}: ${msg}`);- failedFiles.push({ path, error: msg });+ failedFiles.push({ path, error: msg, code: syncFailureCode(e, path) });}} finally {permit.release();diff --git a/src/commands/sync/sync-run.ts b/src/commands/sync/sync-run.tsindex 7501218692..b49ee2e84e 100644--- a/src/commands/sync/sync-run.ts+++ b/src/commands/sync/sync-run.ts@@ -23,6 +23,7 @@ import { appendCompleted, appendCompletedOnce, type OpCheckpointKey } from '../.import { registerCleanup } from '../../core/process-cleanup.ts';import { DB_ACCESS_MARKER_PREFIX, shouldEmitDbAccessMarker } from '../../core/pg-access-classify.ts';import { serr } from '../../core/console-prefix.ts';+import { ItemRun } from '../../core/item-failure.ts';import { buildPartialResult } from '../../core/sync-lock.ts';import type { createProgress } from '../../core/progress.ts';import type { SyncOpts, SyncResult } from '../sync.ts';@@ -30,7 +31,8 @@ import type { LegacyHolds } from './holds.ts';import { resolveSyncCheckpointSeconds, resolveSyncMaxCheckpointFailures, resolveSyncYieldEvery } from './checkpoint.ts';export type SyncActivePack = { page_types: ReadonlyArray<{ name: string; path_prefixes: ReadonlyArray<string>; aliases?: ReadonlyArray<string> }> };-export type SyncFailedFile = { path: string; error: string; line?: number };+/** `code`: the import path's structured ledger code (GBRA-130 A-18); absent, the gate classifies `error`. */+export type SyncFailedFile = { path: string; error: string; line?: number; code?: string };export type SyncOptionsForFilter = Parameters<typeof isSyncable>[1];export type SyncProgress = ReturnType<typeof createProgress>;@@ -97,6 +99,8 @@ export interface SyncRun {readonly succeededPaths: string[];/** Every failure that gates `last_commit` (imports, deletes, renames, `<head>`). */readonly failedFiles: SyncFailedFile[];+ /** GBRA-130 A-18: classifies each thrown import failure (a run-scoped one stops the sync) and trips when most files fail. */+ readonly itemRun: ItemRun;readonly typeWarningCounts: Map<string, TypeWarningCount>;/** @checkpoint Files flushed since the last checkpoint write (count cadence). */sinceFlush: number;@@ -157,6 +161,7 @@ export function createSyncRun(deletedSlugs: new Set<string>(),succeededPaths: [],failedFiles: [],+ itemRun: new ItemRun('sync.import_files'),typeWarningCounts: new Map<string, TypeWarningCount>(),sinceFlush: 0,lastFlushAt: Date.now(),diff --git a/src/core/sync-failure-ledger.ts b/src/core/sync-failure-ledger.tsindex 060a457f20..46e44f6942 100644--- a/src/core/sync-failure-ledger.ts+++ b/src/core/sync-failure-ledger.ts@@ -15,7 +15,8 @@// forever — without ever silently dropping a FRESH failure, and// never auto-skipping an infra sentinel like `<head>`.//-// This module is a LEAF (imports only fs/path/crypto/config) so it can be+// This module is a LEAF (imports only fs/path/crypto/config and the import-free+// ai/errors.ts) so it can be// re-exported from sync.ts without a circular dependency. The state lives// in `~/.gbrain/sync-failures.jsonl`, one JSON object per line.//@@ -54,6 +55,7 @@ import {import { join as _joinPath } from 'path';import { gbrainPath as _gbrainPath } from './config.ts';import { createHash as _createHash } from 'crypto';+import { BILLING_MESSAGE_RE, RATE_MESSAGE_RE } from './ai/errors.ts';export const DEFAULT_SOURCE_ID = 'default';/** Reserved sentinel paths (e.g. `<head>`) start with this; never file paths. */@@ -85,8 +87,10 @@ export interface SyncFailure {first_seen: string;/** ISO — last update. */ts: string;- /** Consecutive failed sync runs for (source_id, path). */+ /** Consecutive failed sync runs for (source_id, path); a systemic run (most files failing) does not count. */attempts: number;+ /** GBRA-130 A-18: consecutive runs this path failed with an embedding-infra code while other files imported. */+ infra_isolated_runs?: number;state: SyncFailureState;resolved_at?: string;// Legacy MIRROR fields, still WRITTEN for one release so any pre-#1939@@ -206,7 +210,44 @@ export function resolveAutoSkipThreshold(): number {* message. Order matters: DB-layer errors are checked BEFORE YAML-layer* ones so Postgres `duplicate key` isn't mislabeled as a YAML duplicate-key.*/-export function classifyErrorCode(errorMsg: string): string {+/** Errno codes of a file the importer could not read: the file's own state, never a provider's. */+const FILE_ERRNO_CODES: Record<string, string> = {+ EACCES: 'PERMISSION_DENIED', EPERM: 'PERMISSION_DENIED',+ ENOENT: 'FILE_UNREADABLE', ELOOP: 'FILE_UNREADABLE', EISDIR: 'FILE_UNREADABLE', ENOTDIR: 'FILE_UNREADABLE',+ ENAMETOOLONG: 'FILE_UNREADABLE', EILSEQ: 'FILE_UNREADABLE',+};++/**+ * GBRA-130 A-18: the part of a failure message a provider wrote. An embed+ * envelope (`[embed(provider:model)] …`) starts it; the failing file's path and+ * every path-like token are removed, so a file named `http-429.md` or living+ * under `billing/` never reads as a rate limit or a quota.+ */+function providerText(errorMsg: string, path?: string): { text: string; enveloped: boolean } {+ const envelope = /\[embed(?:Multimodal)?\([^)]*\)\]/.exec(errorMsg);+ let text = envelope ? errorMsg.slice(envelope.index + envelope[0].length) : errorMsg;+ for (const part of path ? [path, path.split('/').pop()!] : []) if (part) text = text.split(part).join(' ');+ return { text: text.replace(/\S*[\\/]\S*/g, ' '), enveloped: envelope !== null };+}++/**+ * The ledger code of an error raised while importing `path`: an errno is the+ * file's own failure (structured, from the error's `code`); anything else is+ * classified from its message with the path removed.+ */+export function syncFailureCode(error: unknown, path?: string): string {+ const errno = (error as { code?: unknown } | null)?.code;+ if (typeof errno === 'string' && FILE_ERRNO_CODES[errno]) return FILE_ERRNO_CODES[errno]!;+ return classifyErrorCode(error instanceof Error ? error.message : String(error), path);+}++export function classifyErrorCode(errorMsg: string, path?: string): string {+ // GBRA-130 A-18: a Node errno message (`EACCES: permission denied, open+ // '<path>'`) is the file's own failure; its path text must never reach the+ // patterns below.+ const errno = /^(E[A-Z]+): /.exec(errorMsg)?.[1];+ if (errno && FILE_ERRNO_CODES[errno]) return FILE_ERRNO_CODES[errno]!;+// `<rename:…>` sentinel envelope (#3056) — checked FIRST so the code is// stable regardless of the underlying cause: the envelope wraps a raw DB// error whose text would otherwise match a cause-level pattern below@@ -267,14 +308,18 @@ export function classifyErrorCode(errorMsg: string): string {// `[embed(provider:model)] The operation timed out.`). Classified BEFORE the// rate-limit/quota checks and distinct from STATEMENT_TIMEOUT (a DB error) —// this is provider-infra unhealth, not file poison, so the auto-skip valve- // must never eat it.- if (/\[embed(?:Multimodal)?\([^)]*\)\][^\n]*\b(?:timed? ?out|timeout)\b|EMBEDDING_TIMEOUT/i.test(errorMsg)) {+ // must never eat it. GBRA-130 A-18: the infra patterns read only the+ // provider's text (providerText): never the file path, never a bare+ // `billing` or `429` outside an embed envelope.+ const provider = providerText(errorMsg, path);+ if ((provider.enveloped && /\b(?:timed? ?out|timeout)\b/i.test(provider.text.split('\n')[0]!)) || /\bEMBEDDING_TIMEOUT\b/.test(provider.text)) {return 'EMBEDDING_TIMEOUT';}- if (/\brate.?limit|\b429\b|too many requests|rate_limited|RateLimit/i.test(errorMsg)) {+ if (RATE_MESSAGE_RE.test(provider.text) || /\brate_limited\b|RateLimit|\bEMBEDDING_RATE_LIMIT\b/.test(provider.text)+ || (provider.enveloped && /\b429\b/.test(provider.text))) {return 'EMBEDDING_RATE_LIMIT';}- if (/insufficient_quota|quota exceeded|exceeded.*quota|credit balance is too low|billing|EMBEDDING_QUOTA/i.test(errorMsg)) {+ if (BILLING_MESSAGE_RE.test(provider.text) || /\bEMBEDDING_QUOTA\b/.test(provider.text)) {return 'EMBEDDING_QUOTA';}if (/maximum context length|max_tokens|context length|input too long|input length exceeds|tokens? exceed|too many tokens|EMBEDDING_OVERSIZE/i.test(errorMsg)) {@@ -289,11 +334,11 @@ export function classifyErrorCode(errorMsg: string): string {/** Group failures by error code and return a sorted summary. */export function summarizeFailuresByCode(- failures: Array<{ error: string; code?: string }>,+ failures: Array<{ error: string; code?: string; path?: string }>,): Array<{ code: string; count: number }> {const counts: Record<string, number> = {};for (const f of failures) {- const code = f.code ?? classifyErrorCode(f.error);+ const code = f.code ?? classifyErrorCode(f.error, f.path);counts[code] = (counts[code] ?? 0) + 1;}return Object.entries(counts)@@ -336,7 +381,7 @@ export function formatFailedFileList(const cleaned = p.replace(/[\x00-\x1f\x7f]/g, '�');return cleaned.length > 200 ? `${cleaned.slice(0, 197)}...` : cleaned;};- const lines = shown.map(f => ` ${scrub(f.path)} (${f.code ?? classifyErrorCode(f.error)})`);+ const lines = shown.map(f => ` ${scrub(f.path)} (${f.code ?? classifyErrorCode(f.error, f.path)})`);if (files.length > shown.length) {lines.push(` … and ${files.length - shown.length} more (see sync-failures.jsonl)`);}@@ -424,6 +469,7 @@ function _normalizeRow(raw: Record<string, unknown>): SyncFailure {first_seen,ts,attempts,+ ...(typeof raw.infra_isolated_runs === 'number' && raw.infra_isolated_runs > 0 ? { infra_isolated_runs: Math.floor(raw.infra_isolated_runs) } : {}),state,resolved_at:typeof raw.resolved_at === 'string'@@ -568,9 +614,10 @@ function _writeAll(entries: SyncFailure[]): void {function _recordAndClear(sourceId: string,succeededPaths: string[],- failures: Array<{ path: string; error: string; line?: number }>,+ failures: Array<{ path: string; error: string; line?: number; code?: string }>,commit: string,-): Map<string, number> {+ run: { systemic?: boolean; isolatedInfra?: boolean } = {},+): { attempts: Map<string, number>; isolatedInfraRuns: Map<string, number> } {return withLedgerLock(() => {const entries = loadSyncFailures();const byKey = new Map<string, SyncFailure>();@@ -586,9 +633,16 @@ function _recordAndClear(for (const f of failures) {const key = _ledgerKey({ source_id: sourceId, path: f.path });const ex = byKey.get(key);- const code = classifyErrorCode(f.error);+ const code = f.code ?? classifyErrorCode(f.error, f.path);+ // GBRA-130 A-18: a systemic run (most files failing) records its+ // failures but adds no attempt to an open row; an infra code counts+ // isolated runs only while other files import in the same run.+ const counted = run.systemic ? 0 : 1;+ const isolated = isEmbeddingInfraCode(code) && run.isolatedInfra && !run.systemic;if (ex && ex.state === 'open') {- ex.attempts += 1;+ ex.attempts += counted;+ if (isolated) ex.infra_isolated_runs = (ex.infra_isolated_runs ?? 0) + 1;+ else delete ex.infra_isolated_runs;ex.ts = now;ex.commit = commit;ex.error = f.error;@@ -608,6 +662,7 @@ function _recordAndClear(first_seen: now,ts: now,attempts: 1,+ ...(isolated ? { infra_isolated_runs: 1 } : {}),state: 'open',}),);@@ -620,13 +675,13 @@ function _recordAndClear(if (mutated) _writeAll([...byKey.values()]);const attempts = new Map<string, number>();+ const isolatedInfraRuns = new Map<string, number>();for (const f of failures) {- attempts.set(- f.path,- byKey.get(_ledgerKey({ source_id: sourceId, path: f.path }))?.attempts ?? 1,- );+ const row = byKey.get(_ledgerKey({ source_id: sourceId, path: f.path }));+ attempts.set(f.path, row?.attempts ?? 1);+ isolatedInfraRuns.set(f.path, row?.infra_isolated_runs ?? 0);}- return attempts;+ return { attempts, isolatedInfraRuns };});}@@ -728,7 +783,7 @@ export function acknowledgeFailures(sourceId?: string): AcknowledgeResult {* non-sentinel rows transition. Auto-skipped rows stay UNRESOLVED so doctor* keeps warning until the file imports cleanly or a human acknowledges them.*/-export function autoSkipFailures(sourceId: string, paths: string[]): AcknowledgeResult {+export function autoSkipFailures(sourceId: string, paths: string[], codes: ReadonlyMap<string, string> = new Map()): AcknowledgeResult {if (paths.length === 0) return { count: 0, summary: [] };return withLedgerLock(() => {const entries = loadSyncFailures();@@ -742,6 +797,7 @@ export function autoSkipFailures(sourceId: string, paths: string[]): Acknowledgeif (!target.has(_ledgerKey(e))) continue;if (e.state !== 'open') continue;e.state = 'auto_skipped';+ e.code = codes.get(e.path) ?? e.code;e.resolved_at = now;_applyMirror(e);changed++;@@ -816,11 +872,16 @@ export function decideGateAction(args: {attemptsByPath: Map<string, number>;threshold: number;skipFailed: boolean;+ /** A-18: consecutive runs each path failed with an infra code while other files imported. */+ isolatedInfraRunsByPath?: ReadonlyMap<string, number>;+ /** A-18: most of this run's files failed (the ItemRun breaker tripped). */+ systemic?: boolean;}): GateDecision {if (args.sentinels.length > 0) return { action: 'hard_block', autoSkipPaths: [] };if (args.fileFailures.length === 0) return { action: 'advance', autoSkipPaths: [] };if (args.skipFailed) return { action: 'advance', autoSkipPaths: [] };if (args.threshold <= 0) return { action: 'block', autoSkipPaths: [] };+ if (args.systemic) return { action: 'block', autoSkipPaths: [] };const chronic: string[] = [];let fresh = 0;@@ -830,7 +891,8 @@ export function decideGateAction(args: {// file that happened to sync while the provider was unhealthy. Treat them// as fresh so the gate BLOCKS and the operator fixes the provider.if (isEmbeddingInfraCode(f.code)) {- fresh++;+ if ((args.isolatedInfraRunsByPath?.get(f.path) ?? 0) >= args.threshold) chronic.push(f.path);+ else fresh++;continue;}const a = args.attemptsByPath.get(f.path) ?? 1;@@ -893,14 +955,18 @@ export function decideSyncFailureSeverity(args: {export interface SyncGateInput {sourceId: string;- /** All per-file failures this run, including sentinels like `<head>`. */- failedFiles: Array<{ path: string; error: string; line?: number }>;+ /** All per-file failures this run, including sentinels like `<head>`; `code` is the import path's structured code (A-18). */+ failedFiles: Array<{ path: string; error: string; line?: number; code?: string }>;/** File paths that imported successfully this run (clears their rows). */succeededPaths: string[];/** Pin commit the run drained to (stamped on recorded failures). */commit: string;skipFailed: boolean;threshold?: number;+ /** GBRA-130 A-18: files that imported this run; an infra failure while others import counts toward EMBEDDING_INFRA_ISOLATED. */+ imported?: number;+ /** GBRA-130 A-18: most of this run's files failed (ItemRun breaker): record failures, count no attempt, auto-skip nothing. */+ systemic?: boolean;/** Advances the bookmark + clears checkpoints. Awaited BEFORE any ack. */advance: () => Promise<void> | void;}@@ -938,27 +1004,32 @@ export async function applySyncFailureGate(input: SyncGateInput): Promise<SyncGa};}- const attemptsByPath = _recordAndClear(+ const codes = fileFailures.map(f => ({ path: f.path, code: f.code ?? classifyErrorCode(f.error, f.path) }));+ const infraFailures = codes.filter(f => isEmbeddingInfraCode(f.code)).length;+ const { attempts: attemptsByPath, isolatedInfraRuns } = _recordAndClear(input.sourceId,input.succeededPaths,input.failedFiles,input.commit,+ { systemic: input.systemic, isolatedInfra: (input.imported ?? 0) > infraFailures },);const decision = decideGateAction({// #3875: thread the classified error code so provider-infra failures// (embed timeout / rate limit / quota) can never ride the auto-skip valve.- fileFailures: fileFailures.map(f => ({ path: f.path, code: classifyErrorCode(f.error) })),+ fileFailures: codes,sentinels,attemptsByPath,threshold,skipFailed: input.skipFailed,+ isolatedInfraRunsByPath: isolatedInfraRuns,+ systemic: input.systemic,});let fresh = 0;let chronic = 0;for (const f of fileFailures) {- if ((attemptsByPath.get(f.path) ?? 1) >= threshold && threshold > 0) chronic++;+ if ((attemptsByPath.get(f.path) ?? 1) >= threshold && threshold > 0 && !input.systemic) chronic++;else fresh++;}@@ -982,7 +1053,8 @@ export async function applySyncFailureGate(input: SyncGateInput): Promise<SyncGaacknowledged = acknowledgeFailures(input.sourceId).count;} else if (decision.action === 'advance_then_autoskip') {autoSkipped = decision.autoSkipPaths;- autoSkipFailures(input.sourceId, autoSkipped);+ const isolatedInfra = new Map(codes.filter(f => isEmbeddingInfraCode(f.code)).map(f => [f.path, 'EMBEDDING_INFRA_ISOLATED']));+ autoSkipFailures(input.sourceId, autoSkipped, isolatedInfra);}return {diff --git a/test/pathological/a18-ledger-path-text.test.ts b/test/pathological/a18-ledger-path-text.test.tsnew file mode 100644index 0000000000..6e47042ae7--- /dev/null+++ b/test/pathological/a18-ledger-path-text.test.ts@@ -0,0 +1,205 @@+/**+ * GBRA-130 A-18: the legacy sync failure ledger (src/core/sync-failure-ledger.ts)+ * classified a per-file failure by running embedding-infra regexes over the+ * whole error text, path included: `EACCES: permission denied, open+ * '…/billing/q3.md'` became EMBEDDING_QUOTA (bare /billing/), and a file named+ * `http-429.md` or `rate-limit.md` became EMBEDDING_RATE_LIMIT. Infra codes+ * are never chronic, so the gate blocked the source forever (the blocked run+ * keeps its pin, so later commits never imported) and the blocked message said+ * not to use --skip-failed.+ *+ * Authoring gate: (1) protects "a deterministic per-file failure goes chronic+ * and auto-skips; only a recognized provider error is infra": the import path+ * carries a structured code (errno -> PERMISSION_DENIED / FILE_UNREADABLE), the+ * text classifier never reads errno-led messages or path tokens as provider+ * errors, and an infra code on one file while other files import fine goes+ * chronic as EMBEDDING_INFRA_ISOLATED. A run-scoped error during an import+ * stops the sync and records nothing; a run where most files fail counts no+ * attempt and points at --skip-failed. (2) Reverting the classifier or the+ * structured code makes the item case red (4 blocked runs, new.md never+ * imported). (3) test/sync-embedding-infra-gate.test.ts covers the infra codes+ * with provider-shaped messages only, never a path that looks like one. (4)+ * No production seam: the file is made unreadable with chmod; run-scoped+ * errors are injected by wrapping the engine.+ */+import { describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { execFileSync } from 'node:child_process';+import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import type { BrainEngine } from '../../src/core/engine.ts';+import { performSync } from '../../src/commands/sync/perform.ts';+import { applySyncFailureGate, classifyErrorCode, loadSyncFailures } from '../../src/core/sync-failure-ledger.ts';+import { isolatedSharedSkillsEngine } from '../helpers/shared-skills-engine.ts';+import { permsEnforced } from '../helpers/fs-perms.ts';+import { withEnv } from '../helpers/with-env.ts';+import { expectItemFailure, expectOthersUnchanged, expectUnitNotAborted, pathologicalArms, runScopedErrors, snapshotItems } from './harness.ts';++const md = (title: string) => `---\ntitle: ${title}\ntype: note\n---\nThe ${title} note.\n`;+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'] }).trim();+const perms = permsEnforced();++interface Repo { engine: BrainEngine; root: string; sourceId: string; commit(files: Record<string, string>, msg: string): void;+ sync(opts?: { skipFailed?: boolean; engine?: BrainEngine }): ReturnType<typeof performSync>; lastCommit(): Promise<string | null> }++/** A legacy (unmanaged) source on a temp git repo whose first sync imported seed.md; the ledger lives under the temp home.+ * concurrency 1: Postgres import workers connect to the configured database_url, not the isolated test database. */+function legacyRepo(databaseUrl: string | undefined, run: (r: Repo) => Promise<void>): Promise<void> {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-a18-'));+ const root = join(home, 'repo');+ mkdirSync(root);+ return withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, GBRAIN_SYNC_AUTOSKIP_AFTER: '3' }, async () => {+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);+ try {+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ git(root, 'init', '-q'); git(root, 'config', 'user.name', 'Example'); git(root, 'config', 'user.email', '[email protected]');+ const commit = (files: Record<string, string>, msg: string) => {+ for (const [path, body] of Object.entries(files)) { mkdirSync(dirname(join(root, path)), { recursive: true }); writeFileSync(join(root, path), body); }+ git(root, 'add', '--', ...Object.keys(files)); git(root, 'commit', '-qm', msg);+ };+ commit({ 'seed.md': md('seed') }, 'seed');+ const sourceId = `a18${randomUUID().replace(/-/g, '').slice(0, 12)}`;+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [sourceId, root]);+ const sync = (opts: { skipFailed?: boolean; engine?: BrainEngine } = {}) =>+ performSync(opts.engine ?? engine, { repoPath: root, sourceId, noPull: true, noEmbed: true, noExtract: true, concurrency: 1, skipFailed: opts.skipFailed });+ expect((await sync()).status).toBe('first_sync');+ const lastCommit = async () => (await engine.executeRaw<{ c: string | null }>('SELECT last_commit AS c FROM sources WHERE id=$1', [sourceId]))[0]?.c ?? null;+ await run({ engine, root, sourceId, commit, sync, lastCommit });+ } finally {+ await close();+ try { execFileSync('chmod', ['-R', 'u+rwX', home]); } catch { /* best effort */ }+ rmSync(home, { recursive: true, force: true });+ }+ });+}++const row = (sourceId: string, path: string) => loadSyncFailures().find(f => f.source_id === sourceId && f.path === path);++describe('A-18 classifier: errno-led messages and path text are never provider errors', () => {+ test('an EACCES under billing/ and a file named after a status code keep their file codes', () => {+ expect(classifyErrorCode("EACCES: permission denied, open '/r/billing/q3.md'")).toBe('PERMISSION_DENIED');+ expect(classifyErrorCode("ENOENT: no such file or directory, open '/r/notes/rate-limit.md'")).toBe('FILE_UNREADABLE');+ expect(classifyErrorCode('Decode failed for /r/img/http-429.png', 'img/http-429.png')).toBe('UNKNOWN');+ expect(classifyErrorCode('embedMultimodal failed for /r/billing/scan.png: invalid image', 'billing/scan.png')).toBe('UNKNOWN');+ });++ test('provider-shaped messages still classify as infra', () => {+ expect(classifyErrorCode('[embed(openai:text-embedding-3-small)] 429 too many requests', 'notes/http-429.md')).toBe('EMBEDDING_RATE_LIMIT');+ expect(classifyErrorCode('[embed(openai:text-embedding-3-small)] You exceeded your current quota', 'billing/q3.md')).toBe('EMBEDDING_QUOTA');+ });+});++describe('A-18 gate: an infra code on one file while the others import goes chronic with its own code', () => {+ const gate = (sourceId: string, imported: number) => applySyncFailureGate({ sourceId, commit: 'c1', skipFailed: false, advance: () => {},+ failedFiles: [{ path: 'img/huge.png', error: '[embedMultimodal(voyage:voyage-multimodal-3)] The operation timed out.', code: 'EMBEDDING_TIMEOUT' }],+ succeededPaths: imported > 0 ? ['a.md', 'b.md'] : [], imported });++ test('three runs with other files importing auto-skip it as EMBEDDING_INFRA_ISOLATED', () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-a18-gate-'));+ return withEnv({ GBRAIN_SYNC_FAILURES_DIR: home, GBRAIN_SYNC_AUTOSKIP_AFTER: '3' }, async () => {+ try {+ const outcomes = [];+ for (let i = 0; i < 3; i++) outcomes.push(await gate('alpha-example', 2));+ expect(outcomes.map(o => o.advanced)).toEqual([false, false, true]);+ expect(outcomes[2]!.autoSkipped).toEqual(['img/huge.png']);+ expect({ state: row('alpha-example', 'img/huge.png')?.state, code: row('alpha-example', 'img/huge.png')?.code })+ .toEqual({ state: 'auto_skipped', code: 'EMBEDDING_INFRA_ISOLATED' });+ } finally { rmSync(home, { recursive: true, force: true }); }+ });+ });++ test('runs where nothing else imports (the provider is down) never auto-skip it', () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-a18-gate-'));+ return withEnv({ GBRAIN_SYNC_FAILURES_DIR: home, GBRAIN_SYNC_AUTOSKIP_AFTER: '3' }, async () => {+ try {+ for (let i = 0; i < 5; i++) expect((await gate('beta-example', 0)).advanced).toBe(false);+ expect(row('beta-example', 'img/huge.png')?.state).toBe('open');+ } finally { rmSync(home, { recursive: true, force: true }); }+ });+ });+});++/** The engine whose page reads inside a file's import (importOnePath) throw `error`. */+function failingImports(engine: BrainEngine, error: unknown): BrainEngine {+ return new Proxy(engine, { get(target, prop) {+ const value = Reflect.get(target, prop);+ if (prop === 'getPage' && typeof value === 'function') {+ return (...args: unknown[]) => new Error().stack?.includes('importOnePath') ? Promise.reject(error) : (value as Function).apply(target, args);+ }+ return typeof value === 'function' ? value.bind(target) : value;+ } }) as BrainEngine;+}++for (const { backend, databaseUrl } of pathologicalArms()) {+ describe(`A-18 legacy sync: an unreadable file under billing/ goes chronic and auto-skips (${backend})`, () => {+ test.skipIf(!perms)('A-18 item: billing/q3.md (mode 000) is PERMISSION_DENIED, auto-skips on run 3, and a later commit imports on run 4', () => legacyRepo(databaseUrl, async r => {+ r.commit({ 'ok.md': md('ok'), 'billing/q3.md': md('q3') }, 'add');+ chmodSync(join(r.root, 'billing', 'q3.md'), 0o000);+ const first = await expectUnitNotAborted(() => r.sync());+ expect({ status: first.status, codes: first.failureCodes }).toEqual({ status: 'blocked_by_failures', codes: [{ code: 'PERMISSION_DENIED', count: 1 }] });+ const before = await snapshotItems(r.engine, r.sourceId);+ r.commit({ 'new.md': md('new') }, 'later');+ const runs = [];+ for (let i = 0; i < 3; i++) runs.push(await expectUnitNotAborted(() => r.sync()));+ expect(runs.map(x => x.status)).toEqual(['blocked_by_failures', 'synced', 'synced']);+ expect(await r.engine.getPage('new', { sourceId: r.sourceId })).not.toBeNull();+ const failure = row(r.sourceId, 'billing/q3.md');+ expect(failure?.state).toBe('auto_skipped');+ expectItemFailure({ key: failure?.path, code: failure?.code }, { key: 'billing/q3.md', code: 'PERMISSION_DENIED' });+ expectOthersUnchanged(before, await snapshotItems(r.engine, r.sourceId));+ }), 180_000);++ test.skipIf(!perms)('A-18 item: five unreadable files among six readable ones still auto-skip on run 3 (a resumed run counts the banked files)', () => legacyRepo(databaseUrl, async r => {+ const locked = ['l1', 'l2', 'l3', 'l4', 'l5'].map(n => `locked/${n}.md`);+ r.commit(Object.fromEntries([...locked.map(p => [p, md(p)]), ...['o1', 'o2', 'o3', 'o4', 'o5', 'o6'].map(n => [`ok/${n}.md`, md(n)])]), 'mixed');+ for (const path of locked) chmodSync(join(r.root, path), 0o000);+ const runs = [];+ for (let i = 0; i < 3; i++) runs.push(await expectUnitNotAborted(() => r.sync()));+ expect(runs.map(x => x.status)).toEqual(['blocked_by_failures', 'blocked_by_failures', 'synced']);+ expect(loadSyncFailures().filter(f => f.source_id === r.sourceId).map(f => [f.path, f.state]).sort()).toEqual(locked.map(p => [p, 'auto_skipped']));+ }), 180_000);++ test.skipIf(!perms)('A-18 recovery: once the file is readable and edited, the next sync imports it and clears its row', () => legacyRepo(databaseUrl, async r => {+ r.commit({ 'ok.md': md('ok'), 'billing/q3.md': md('q3') }, 'add');+ chmodSync(join(r.root, 'billing', 'q3.md'), 0o000);+ for (let i = 0; i < 3; i++) await r.sync();+ expect(row(r.sourceId, 'billing/q3.md')?.state).toBe('auto_skipped');+ chmodSync(join(r.root, 'billing', 'q3.md'), 0o644);+ r.commit({ 'billing/q3.md': md('q3 revised') }, 'fix');+ const before = await snapshotItems(r.engine, r.sourceId);+ expect((await expectUnitNotAborted(() => r.sync())).status).toBe('synced');+ expect(await r.engine.getPage('billing/q3', { sourceId: r.sourceId })).not.toBeNull();+ expect(row(r.sourceId, 'billing/q3.md')).toBeUndefined();+ expectOthersUnchanged(before, await snapshotItems(r.engine, r.sourceId));+ }), 180_000);++ for (const { name, error } of runScopedErrors()) {+ test(`A-18 run: a run-scoped ${name} while importing a file stops the sync and records no ledger row`, () => legacyRepo(databaseUrl, async r => {+ r.commit({ 'ok.md': md('ok'), 'other.md': md('other') }, 'add');+ const before = await snapshotItems(r.engine, r.sourceId);+ const pinned = await r.lastCommit();+ const injected = error();+ let thrown: unknown;+ const result = await r.sync({ engine: failingImports(r.engine, injected) }).catch(e => { thrown = e; return null; });+ expect({ result: result?.status ?? null, thrown: thrown === injected }).toEqual({ result: null, thrown: true });+ expect(loadSyncFailures().filter(f => f.source_id === r.sourceId)).toEqual([]);+ expect(await r.lastCommit()).toBe(pinned);+ expectOthersUnchanged(before, await snapshotItems(r.engine, r.sourceId));+ }), 180_000);+ }++ test.skipIf(!perms)('A-18 breaker: when most files fail the run counts no attempt, never auto-skips, and --skip-failed is the named exit', () => legacyRepo(databaseUrl, async r => {+ const files = Object.fromEntries(['a', 'b', 'c', 'd', 'e', 'f'].map(n => [`locked/${n}.md`, md(n)]));+ r.commit(files, 'locked');+ for (const path of Object.keys(files)) chmodSync(join(r.root, path), 0o000);+ const runs = [];+ for (let i = 0; i < 4; i++) runs.push(await expectUnitNotAborted(() => r.sync()));+ expect(runs.map(x => x.status)).toEqual(Array(4).fill('blocked_by_failures'));+ expect(loadSyncFailures().filter(f => f.source_id === r.sourceId).map(f => [f.path, f.state, f.attempts]).sort())+ .toEqual(Object.keys(files).map(path => [path, 'open', 1]));+ const acked = await expectUnitNotAborted(() => r.sync({ skipFailed: true }));+ expect(acked.status).toBe('synced');+ }), 240_000);+ });+}