Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(GBRA-130 A-7): a file sync cannot read as a regular file inside its root is held file_unreadable, never a stopped sync

garrytanb213c0e2d171
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 8d0caef12d..c796e548fb 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -98,8 +98,9 @@ of making a duplicate.
| <a id="purge_lookup_timeout"></a>`purge_lookup_timeout` | `purge_lookup_timeout` | A page purge (`gbrain delete <slug> --purge`) ran one of the journal lookups that still execute inside its publication transaction (the lookup of stored intents for the slug, the re-check of requests admitted after its preparation scan or pending at that scan, the locking read of the requests to redact) and that statement hit the transaction's 5-second statement budget on a large `persistence_requests` table. The request failed terminally instead of being released as `database_contention` and claimed again: nothing of the page was removed or tombstoned, nothing in the journal was redacted, and later writes to the source move again. Do not assume the requested content was erased. The substring search for the page's claims no longer runs here: it runs at preparation in bounded keyset chunks under the preparation budget, and a sweep that outruns that budget twice ends [`preparation_stalled`](#preparation_stalled) instead. A committed purge's receipt reports `journal_sweep` (`scanned`, `ceiling`, `tail`, `pending_rechecked`, `complete`); `complete: false` means a cap was hit (the 10,000-match cap or the tail bound) and some requests were not tested. | If the receipt says the slug index `persistence_requests_slug_intent` is missing or INVALID, run `gbrain repair request-indexes --apply` (the `persistence_request_slug_intent_index` migration builds it online; the index serves the slug lookup, not the substring sweep), then submit the purge again with a new `request_id`. Otherwise submit it again with a new `request_id` (a retry with the same id returns this failure); if it times out again, report the request id with the `persistence_request_indexes` and `persistence_request_growth` entries of `gbrain doctor --json`. |
| <a id="purge_mirror_unwritable"></a>`purge_mirror_unwritable` | `purge_mirror_unwritable` | A fact or page purge appends a text-free `intent` line to the purge mirror (`<brain home>/.gbrain/purge-events.jsonl`) and fsyncs it before it commits, so a later restore of an older backup can replay the purge. The mirror could not be written (a directory in its place, a read-only home, a full disk), so the purge was refused: nothing was removed, tombstoned or redacted. Do not assume the requested content was erased. | Make the mirror a writable regular file owned by the brain's user (mode 0600), then run the purge again with a new `request_id`. |
| <a id="preparation_stalled"></a>`preparation_stalled` | `preparation_stalled` | The write's owner could not finish *preparing* it. Every write has a preparation budget (`persistence.sync_preparation_ms` for a managed sync member, `persistence.maintenance_preparation_ms` for every other managed kind, 120 s each; `remember`, `put_page` and `edit_page` keep 30 s), the owner releases the claim at the budget and tries again, and a request cut off `persistence.max_preparation_attempts` times (default 2; a process killed mid-preparation counts too) is finished `failed` with this code instead of being claimed again and holding the rest of its root. The receipt names the last recorded step and what it was waiting on (`git`, `fs`, `db`, `pool` or `unknown`); while the write was still running, `gbrain sources writer status --json` showed the same on `claim.stall` (`preparation_overdue`). The rest of the root keeps publishing. A **managed sync member** (an import, delete or rename of a file) is also **held**: the sync turns the failed receipt into a `preparation_stalled` hold and carries on, so the file is not imported until it is retried. The file is fine; this is the write owner stalling (a database or pool wait, a hung step), never a frontmatter or fence problem, so no repair applies. The hold's `message` names the request and the step; a held deletion keeps its page. A stalled hold re-screens by itself only when the gbrain version changes; a run that stalls many files in a row stops with [`preparation_systemic`](#preparation_systemic) instead of holding them all. A **foreground write** (`put_page`, `edit_page`, `remember`) or a **maintenance write** (fact-fence adoption, maintenance page writes) gets the terminal receipt only. The deadlines sit behind `persistence.preparation_deadlines` (`false` restores the old behaviour, where only `remember`, `put_page` and `edit_page` had a 30 s budget). | Run `gbrain sources writer status --source <source> --json` (read-only: the step, its wait cause, the owner process and its gbrain version), fix what it names (restart or upgrade an owner that predates deadlines, free the pool, let the lock holder finish), then for a sync hold run `gbrain sources retry-held <source>` and the same `gbrain sync` with the same options (the hold's `fix.then.then` and `retry-held` print it, for example `gbrain sync --source <source> --no-pull --no-embed`). When that sync still has a backlog to finish, it finishes it first and re-screens the scheduled files in the same invocation (the drain yields at the checkpoint and discovers again), so one run of the printed command clears the hold. A foreground write needs a new `request_id`; the next maintenance run submits its write again. Runbook: [catch-up stuck / held N files](troubleshooting.md#catch-up-stuck). |
+| <a id="file_unreadable"></a>`file_unreadable` (sync hold) | `file_unreadable` | A managed sync held one file because it is not a readable regular file inside the source root: a symlink (to a file outside the root or inside it), a non-regular file, or a permission or loop error. Sync never reads or follows it. Until GBRA-130 the whole sync stopped at that file on every run and the rest of the source never imported; now only the file waits. A source root that is itself replaced by a symlink still refuses the whole sync. | Make the file a readable regular file in the checkout (replace the symlink with the file, fix its permissions) or exclude it with `sync.exclude`, and commit. A commit that changes it re-screens the hold on the next sync; after a permission fix run `gbrain sources retry-held <source>`, then the same sync. |
| <a id="page_write_failed"></a>`page_write_failed` (sync hold) | `page_write_failed` | A managed sync held one file because its write failed the same way three times (the same code, origin, error class and SQLSTATE in this source), with an error gbrain cannot classify: an owner exception (for example Postgres 54000 when a frontmatter tag is too long for its index), or a refusal the receipt does not explain. A write that ended [`publication_timeout`](#publication_timeout) is held on its first receipt. Until GBRA-130 every sync stopped `blocked_by_failures` at that file and the rest of the source never imported; now the file is held and the rest of the source syncs. The first two failures still stop the run, so a one-off defect never holds a file. | Read the receipt the hold names (`gbrain write-request <request_id>`, read-only). Fix the file when the error names its content (shorten the tag, split the page), or report the receipt with the gbrain version. Then `gbrain sources retry-held <source>` and the same sync. An upgrade re-tests the file on its own. |
-| <a id="publication_timeout"></a>`publication_timeout` | `publication_timeout` | The write's publication transaction (which runs under a 5-second local statement timeout) hit its statement timeout (57014) or lock timeout (55P03) on every attempt, `persistence.max_preparation_attempts` times (default 2). Each timeout counts one attempt; before GBRA-130 it was released as `database_contention` without being counted and claimed again forever, holding every later write on its root. Nothing was committed; a worktree-backed page's file is restored by its recovery record. The receipt's detail names the SQLSTATE, the attempts and the intent size. | Report the request id, its size and `gbrain sources writer status --source <id> --json`. A smaller write (split the page or the batch) needs a new `request_id`; a retry with the same id returns this failure. |
+| <a id="publication_timeout"></a>`publication_timeout` | `publication_timeout` | The write's publication transaction (which runs under a 5-second local statement timeout) hit its statement timeout (57014) on every attempt, `persistence.max_preparation_attempts` times (default 2). A lock timeout (55P03) waits on another holder and stays transient `database_contention`, uncounted. Each timeout counts one attempt; before GBRA-130 it was released as `database_contention` without being counted and claimed again forever, holding every later write on its root. Nothing was committed; a worktree-backed page's file is restored by its recovery record. The receipt's detail names the SQLSTATE, the attempts and the intent size. | Report the request id, its size and `gbrain sources writer status --source <id> --json`. A smaller write (split the page or the batch) needs a new `request_id`; a retry with the same id returns this failure. |
| <a id="write_outcome_unknown"></a>`write_outcome_unknown` | `write_outcome_unknown` | The database session dropped while the write was being admitted (a pooler reap, a failover, `pg_terminate_backend`), and it kept dropping through the re-reads, so whether the write was accepted is unknown (#6355). A single drop never reaches you: the admission attempt is re-run after 100, 300 and 900 ms, and every attempt begins by reading the retained `request_id`, so a re-run replays an admitted row instead of admitting again. Before this code existed the raw socket error (`write CONNECTION_CLOSED …`, `57P01`) reached the caller while the write went on to commit, and a receipt oracle took it for a refusal. | Read the request first: `gbrain write-request -- <request_id>` or `get_write_request { request_id }` (the error's `fix` names it). A committed or pending row means the write was accepted: replay the same `request_id` to wait for it. No row means it was not: submit it again with the same `request_id`. Never resubmit under a new `request_id` without that read. |
| <a id="page_body_segmented"></a>`page_body_segmented` | `page_body_segmented` (a memory verb: `invalid_params` with `write_error: page_body_segmented`) | The target page stores its body in segments (a page over 1 MiB written while `pages.segmented_storage` was on), and this write needs the whole body as one string: `remember` against an entity page over 24 MiB (named, or inferred from the fact), and the other whole-body writers listed under [page_body_segmented](windowed-reads.md#page_body_segmented). It refused before changing anything and is not retryable. | For `remember`, save the claim without an entity (`infer_entity: false`); remembering it with `entity` once that page accepts fact rows replaces that copy. Otherwise edit the page's file and sync it, or read it with `get_page` `body: "auto"`. |
| <a id="fence_unrenderable"></a>`fence_unrenderable` | `fence_unrenderable` | A legacy fact row (an active `facts` row with no fence row number) was not adopted into its page's `## Facts` fence because the fence codec reads the rendered row back as something other than the stored fact: a whitespace-only claim comes back empty, `~~x~~` comes back struck, a literal `<br>` comes back as a line break, or another column changes. Surrounding whitespace and CRLF line endings are the one accepted difference: such a row is adopted and `facts.fact` takes the fence's text. A second legacy row whose normalized claim, source and visibility the page already carries is left too (`duplicate_claim`; a private and a world row with one text are two facts and both adopt). The cycle and the v0.32.2 migration print `FACTS_FENCE_FAILED: <slug> (fence_unrenderable: N row(s), <class>)`; doctor `fence_integrity` lists the pages, fact ids and reason classes under `unrenderable_legacy_facts` (never the claim text). The same code refuses a planned adoption whose rendered fence does not read back as its facts; that is a gbrain planning defect, not caller input. The planner runs the publisher's own read-back check on the whole rendered fence first, so such a page is reported as unadoptable (class `whole_fence`) instead of being submitted. A managed adoption refused in the last day is not resubmitted: the cycle reports it as class `prior_refusal` with the refused request id (`gbrain write-request -- <id>` reads it), and a direct `submitFactFenceAdoption` call refuses with `The same fact-fence adoption was already refused.`. It is retried a day after the refusal, or at once by a build whose adoption planner revision changed. Unadopted rows hold only their own page: the phantom-redirect pass skips a phantom that owns one and redirects the others. Before v0.60.218.0 the planner could reuse a leftover fence row (one with no database owner) whose visibility differed from the legacy fact's. On a managed brain the publisher refused that page here every cycle, so no private fact was published as world. An unmanaged brain had no such check: it fenced the fact into the leftover row, and the same cycle's reconcile copied that row's visibility into the fact, so a private fact could become world. The current planner never reuses a leftover row for a fact with a different visibility unless the fact is private, and re-renders a reused row from the fact. To count what an older build left in the writer table, run the read-only `scripts/diagnose/fence-adoption-census.sql` on the brain host against the brain's Postgres database (its header shows the `psql` command). | Nothing to fix in the page: the rows stay active and searchable, nothing is lost, and their pages skip destructive fact reconciliation until the rows are adopted. Report the pages and reason classes with the gbrain version. Never `forget_fact` a row to clear the count. |
diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.ts
index b01c0b3d29..fb2cf8f2b6 100644
--- a/src/core/persistence/sync-discovery.ts
+++ b/src/core/persistence/sync-discovery.ts
@@ -121,23 +121,26 @@ export function syncFilePath(root: string, path: string, maxBytes = SYNC_READ_BO
if (realpathSync(root) !== resolve(root)) throw syncTargetRefusal('source_changed', 'The registered source root was replaced by a symlink.',
`The registered root holding ${path} is now a symlink.`);
const absolute = resolve(root, path);
- if (!isWriteTargetContained(absolute, root)) throw syncTargetRefusal('source_changed', 'Sync file escaped its registered root.',
- `${path} resolves outside its registered source root.`);
+ if (!isWriteTargetContained(absolute, root)) throw unreadableSyncFile(syncTargetRefusal('source_changed', 'Sync file escaped its registered root.',
+ `${path} resolves outside its registered source root.`));
try {
// Reject symlink components, including ones targeting another path inside the root.
let current = root;
for (const part of relative(root, absolute).split(sep)) {
current = join(current, part);
- if (lstatSync(current).isSymbolicLink()) throw syncTargetRefusal('source_changed', 'Sync cannot publish through a symlink.',
- `A component of ${path} is a symlink; sync reads and publishes only real files inside the root.`);
+ if (lstatSync(current).isSymbolicLink()) throw unreadableSyncFile(syncTargetRefusal('source_changed', 'Sync cannot publish through a symlink.',
+ `A component of ${path} is a symlink; sync reads and publishes only real files inside the root.`));
}
- if (!lstatSync(absolute).isFile()) throw syncTargetRefusal('source_changed', 'Sync target is not a regular file.',
- `${path} is not a regular file.`);
+ if (!lstatSync(absolute).isFile()) throw unreadableSyncFile(syncTargetRefusal('source_changed', 'Sync target is not a regular file.',
+ `${path} is not a regular file.`));
if (lstatSync(absolute).size > maxBytes) throw opError('request_too_large', 'Sync file exceeds the bounded import size.',
`${path} is larger than the ${SYNC_READ_BOUND}-byte (24 MiB) page ceiling, so nothing was imported from it. Pages up to that size are chunked and searchable; above it, add the file to the sync.exclude config (or keep it outside the brain repo), then sync its source again. See docs/guides/memory-boundaries.md#large-pages.`);
return absolute;
} catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null; throw error; }
}
+/** GBRA-130 A-7: the per-file refusals of a path that is not a readable regular file inside its root (the freeze holds that file `file_unreadable`). */
+export const UNREADABLE_SYNC_FILE = 'unreadable_sync_file';
+const unreadableSyncFile = (error: OperationError): OperationError => Object.assign(error, { detail: UNREADABLE_SYNC_FILE });
export function readSyncFile(root: string, path: string): Buffer | null {
const absolute = syncFilePath(root, path);
try { return absolute === null ? null : readFileSync(absolute); } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null; throw error; }
diff --git a/src/core/persistence/sync-fault-class.ts b/src/core/persistence/sync-fault-class.ts
index b797db2d5c..e158a08c70 100644
--- a/src/core/persistence/sync-fault-class.ts
+++ b/src/core/persistence/sync-fault-class.ts
@@ -81,6 +81,9 @@ export const SYNC_FAULT_TABLE: ReadonlyArray<SyncFaultRule> = [
// GBRA-130 A-6: one path's write failed the same unclassifiable way on repeated attempts; held so the rest of the source moves.
{ code: 'page_write_failed', class: 'page', safe_actions: ['upgrade'], needs_human: true, escalate: 'always: the writer cannot place the failure',
human_reason: 'The write of this file keeps failing with an error gbrain cannot classify (an owner exception or an unplaced refusal); read its receipt (gbrain write-request <request_id>), report it with the gbrain version or fix the file when the error names its content, then run gbrain sources retry-held <source>.' },
+ // GBRA-130 A-7: the file is not a readable regular file inside the source root (a symlink, a non-regular file, a permission error).
+ { code: 'file_unreadable', class: 'page', safe_actions: ['none'], needs_human: true, escalate: 'always: only a change to the checkout makes the file readable',
+ human_reason: 'Sync cannot read this file as a regular file inside the source root (a symlink, a non-regular file or a permission error) and never follows it; make it a readable regular file in the checkout (or exclude it with sync.exclude) and commit, then run gbrain sources retry-held <source>.' },
// #6948: several live pages record the file as their origin; the sync-time heal resolves verified duplicates, a person decides the rest.
{ code: 'origin_conflict', class: 'page', safe_actions: ['repair'], needs_human: false, escalate: 'the hold carries a reason (the pages differ, ids conflict or none is the page the path names), or the heal is off',
human_reason: 'Several live pages record this file as their origin and sync cannot prove they are one document; a person keeps the page that is the file\'s and soft-deletes the others (gbrain repair origin-twins --source <source> lists them with the commands), then syncs.' },
diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.ts
index 7891fa2df1..50de34b594 100644
--- a/src/core/persistence/sync-holds.ts
+++ b/src/core/persistence/sync-holds.ts
@@ -74,7 +74,9 @@ export type GitHoldCode = ContentRefusal['code'] | 'rename_held' | 'parser_regre
/** #6712 PR 4b (design v3.2 §3.1): a path a live pass settled in three consecutive passes at one level that never classified settled. */
| 'settle_mismatch'
/** GBRA-130 A-6: the path's write failed the same unclassifiable way (an owner exception, an unplaced refusal) on repeated attempts. */
- | 'page_write_failed';
+ | 'page_write_failed'
+ /** GBRA-130 A-7: a file sync cannot read as a regular file inside its root (a symlink, a non-regular file, a permission error). */
+ | 'file_unreadable';
/** GBRA-130 A-6: the fault a `page_write_failed` hold stands for (identifiers and classes only, never content). */
export interface PageWriteFailureMeta { code: string; origin: string | null; error_class: string | null; errno: string | null; request_id: string; attempts: number; gbrain_version: string }
/** #6278: what the owner recorded about a preparation it gave up on (step names and vocabulary only, never content). */
@@ -675,6 +677,13 @@ export function gitHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'c
why: `Schedules ${record.path} for a re-screen on the next sync once the cause is fixed.` },
verify };
}
+ case 'file_unreadable': {
+ const verify = { argv: ['gbrain', 'sources', 'status', source, '--json'] };
+ return { argv: ['gbrain', 'sources', 'retry-held', source], consent: [], actor: 'user', requires_exclusive: false, docs: 'docs/guides/write-refusals.md#file_unreadable',
+ why: `${record.path} is not a readable regular file inside the source root (a symlink, a non-regular file or a permission error), so sync held it without reading or following it and the rest of the source kept syncing. `
+ + 'Make it a readable regular file in the checkout (or exclude it with sync.exclude) and commit; a commit that changes it re-screens the hold on its own, and this schedules the re-screen for a permission fix.',
+ verify };
+ }
case 'worktree_dirty': {
const verify = { argv: ['gbrain', 'sources', 'status', source, '--json'] };
return { argv: ['gbrain', 'sync', 'unblock', '--source', source, '--apply', '--json'], consent: [], actor: 'agent', requires_exclusive: false, docs: 'docs/guides/write-refusals.md#worktree_dirty',
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index c04506e9d1..3d0b24c68b 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -46,7 +46,7 @@ import { managedSyncResumeArgs } from '../sync-reconcile.ts';
import { laneApplyMsPerMember, lanePolicy, openLanes } from './sync-lanes.ts';
import { isRetryableConnError, isStatementTimeoutError } from '../retry-matcher.ts';
import { SYNC_READ_BOUND, type TreeBlob } from './sync-blobs.ts';
-import { driftBaselineContent, dryRunScreen, heldImageEntry, isSyncReadBound, loadSyncScreenRun, originConflictHold, oversizeHold, pinnedBlob, pinnedContent, pinnedImageBytes, preparationStalledHold, prepareTimeFenceHold, screenFrozenImport, streamedRefusalHold, type HeldEntry, type SyncScreenRun } from './sync-screen.ts';
+import { driftBaselineContent, dryRunScreen, heldImageEntry, isSyncReadBound, loadSyncScreenRun, originConflictHold, oversizeHold, pinnedBlob, pinnedContent, pinnedImageBytes, preparationStalledHold, prepareTimeFenceHold, screenFrozenImport, streamedRefusalHold, unreadableFileHold, type HeldEntry, type SyncScreenRun } from './sync-screen.ts';
import { frozenImageIntent, sameImageBytes } from './sync-image.ts';
import { fenceReceiptLocation } from '../fence-repair/refusal.ts';
import { managedSyncWriteDiagnostic, writeWaitOf } from './sync-write-diagnostic.ts';
@@ -366,7 +366,7 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, ass
let bytes: Buffer | null = null;
try { bytes = readSyncFile(cursor.root, entry.path); }
catch (error) {
- if (!isSyncReadBound(error)) throw error;
+ if (!isSyncReadBound(error)) { const held = holdsOn ? unreadableFileHold(entry, entry.slug!, entry.pageId ?? null, error, () => pinnedBlob(cursor, entry.path)) : null; if (held) return { hold: held }; throw error; } // GBRA-130 A-7
// Wave B: with segmented storage on, a Markdown file over the read bound is frozen by reference and streamed by its owner.
if (entry.action === 'import' && !cursor.companyPlan && !image) {
bodyRef = await streamedSyncBodyRef(engine, { root: cursor.root, path: entry.path, target: cursor.target, working: entry.working,
diff --git a/src/core/persistence/sync-screen.ts b/src/core/persistence/sync-screen.ts
index 099702684b..43a106e7fc 100644
--- a/src/core/persistence/sync-screen.ts
+++ b/src/core/persistence/sync-screen.ts
@@ -30,7 +30,7 @@ import { sha256 } from './digest.ts';
import { readPageBodyPolicy, type PageBodyPolicy } from '../page-body/limits.ts';
import { readPagePurgeTombstones } from './page-purge.ts';
import { listTrustAllowRules } from '../trust/allow-rules.ts';
-import { readSyncContent, readSyncFile, syncGitPath, type SyncDiscovery, type SyncEntry } from './sync-discovery.ts';
+import { readSyncContent, readSyncFile, syncGitPath, UNREADABLE_SYNC_FILE, type SyncDiscovery, type SyncEntry } from './sync-discovery.ts';
import { pinnedWindowBlock, readBlobBytes, readBlobContents, readPinnedBlob, readPinnedBytes, readPinnedContent, readTreeBlobs, SYNC_READ_BOUND, type TreeBlob } from './sync-blobs.ts';
import { screenSyncImport, type SyncImportScreenInput } from './sync-prepare.ts';
import type { SyncProcessingOptions } from './sync-authority.ts';
@@ -215,6 +215,23 @@ export function oversizeHold(entry: Pick<SyncEntry, 'path' | 'sourcePath' | 'wor
message: `File too large (${size ?? `over ${SYNC_READ_BOUND}`} bytes; the sync read bound is the ${SYNC_READ_BOUND}-byte (24 MiB) page ceiling). Pages up to the ceiling are chunked and searchable; leave this file out of the source (sync.exclude) or keep it outside the brain repo. See docs/guides/memory-boundaries.md#large-pages.` }, null, blob);
}
+/** File-system errors that make one path unreadable while the rest of its source reads (GBRA-130 A-7). */
+const UNREADABLE_ERRNO = new Set(['EACCES', 'EPERM', 'ELOOP', 'EISDIR', 'ENOTDIR']);
+/**
+ * GBRA-130 A-7: the hold of a file sync cannot read as a regular file inside its root (a symlink component, a non-regular
+ * file, a permission or loop error); null for any other error. Its content is never read or followed, and the root-level
+ * refusals (the root itself replaced or escaped) are not per-file and stay run-level.
+ */
+export function unreadableFileHold(entry: Pick<SyncEntry, 'path' | 'sourcePath' | 'working' | 'renameFrom' | 'renameHeld'>, slug: string, pageId: number | null, error: unknown,
+ blob: () => TreeBlob | null | undefined): HeldEntry | null {
+ const errno = (error as NodeJS.ErrnoException | null)?.code;
+ const refused = error instanceof OperationError && error.detail === UNREADABLE_SYNC_FILE;
+ if (!refused && !(typeof errno === 'string' && UNREADABLE_ERRNO.has(errno))) return null;
+ const why = refused ? (error as OperationError).message : `it cannot be read (${errno})`;
+ return heldEntry(entry, slug, pageId, { code: 'file_unreadable',
+ message: `Sync did not read ${entry.path}: ${why} Sync reads only regular files inside the source root and never follows a symlink. Make it a readable regular file there (or exclude it with sync.exclude) and commit, then run gbrain sources retry-held to re-test it.` }, null, blob());
+}
+
const purgeTombstonesByRun = new WeakMap<SyncScreenRun, Promise<Map<string, string>>>();
/** #5575: one tombstone read per sync run; a run screens one source. */
function runPurgeTombstones(engine: BrainEngine, run: SyncScreenRun, sourceId: string): Promise<Map<string, string>> {
diff --git a/test/sync-unreadable-file-gbra130.test.ts b/test/sync-unreadable-file-gbra130.test.ts
new file mode 100644
index 0000000000..75e1ede7ec
--- /dev/null
+++ b/test/sync-unreadable-file-gbra130.test.ts
@@ -0,0 +1,54 @@
+/**
+ * GBRA-130 A-7 (#6712 PR 4b): one committed file sync cannot read as a regular file inside its root (a symlink, to a
+ * file outside the root or inside it, or a mode-000 file) stopped the whole managed sync at its freeze
+ * (`readSyncFile` threw `source_changed` / `EACCES` out of freezeEntry), and every later sync stopped at the same file,
+ * so the rest of the source never imported.
+ *
+ * Protects (red before: the first sync rejects at notes/b.md and notes/a.md, notes/c.md never import): the file is held
+ * `file_unreadable` (its content is never read or followed), the other files import, and a later sync is not stopped
+ * by it. The root-level checks (a root replaced by a symlink) stay run-level. Runs on PGLite and, with DATABASE_URL,
+ * on Postgres.
+ */
+import { describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { chmodSync, mkdirSync, symlinkSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { readGitHold } from '../src/core/persistence/sync-holds.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const commit = (root: string, message: string) => { git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); };
+const note = (title: string) => `---\ntype: concept\ntitle: ${title}\n---\n\nThe body of ${title}.\n`;
+const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };
+const setup = ({ root }: { root: string }) => {
+ mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');
+ writeFileSync(join(root, 'notes/seed.md'), note('notes/seed'));
+ commit(root, 'seed');
+};
+const live = async (engine: BrainEngine) => (await engine.executeRaw<{ slug: string }>("SELECT slug FROM pages WHERE source_id='default' AND deleted_at IS NULL ORDER BY slug")).map(row => row.slug);
+
+for (const backend of testBackends()) describe(`[${backend}] GBRA-130 A-7: one unreadable file`, () => {
+ const databaseUrl = backend === 'postgres' ? process.env.DATABASE_URL : undefined;
+ for (const kind of ['symlink outside the root', 'symlink inside the root', 'mode-000'] as const) test(`${kind}: held file_unreadable, the other files import, a later sync is not stopped`, () => managedBrain(async ({ engine, root }) => {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ writeFileSync(join(root, 'notes/a.md'), note('notes/a'));
+ writeFileSync(join(root, 'notes/c.md'), note('notes/c'));
+ if (kind === 'symlink outside the root') { writeFileSync(join(root, '..', 'outside.md'), note('outside')); symlinkSync('../../outside.md', join(root, 'notes/b.md')); }
+ if (kind === 'symlink inside the root') symlinkSync('seed.md', join(root, 'notes/b.md'));
+ if (kind === 'mode-000') writeFileSync(join(root, 'notes/b.md'), note('notes/b'));
+ commit(root, 'a b c');
+ if (kind === 'mode-000') chmodSync(join(root, 'notes/b.md'), 0o000);
+ try {
+ const first = await performManagedSync(engine, OPTS);
+ expect(first.status).toBe('synced');
+ expect(first.held?.map(hold => [hold.path, hold.code])).toEqual([['notes/b.md', 'file_unreadable']]);
+ expect(await live(engine)).toEqual(['notes/a', 'notes/c', 'notes/seed']);
+ const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id='default'");
+ expect(await readGitHold(engine, 'default', incarnation, 'notes/b.md')).toMatchObject({ code: 'file_unreadable' });
+ expect((await performManagedSync(engine, OPTS)).status).not.toBe('blocked_by_failures');
+ } finally { if (kind === 'mode-000') chmodSync(join(root, 'notes/b.md'), 0o644); }
+ }, { databaseUrl, setup }), 240_000);
+});