Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): classic rename identity never blocks on unreadable values (S-51); classifier keys connection scope on codes, reconcile holds unexpected errors (S-65/S-67/S-70) (GBRA-133 PR 1)

garrytan187d44159e8f
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index a58e5da57e..09381ff09c 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -3100,6 +3100,22 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c
Reasons: `rename_source_changed`.
+### rename_identity_unreadable
+
+<a id="rename_identity_unreadable"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A renamed file is held because the database refused to compare its title or frontmatter id (SQLSTATE 22021/22P05), so sync could not tell whether it is the page it replaces. | Which page a file is cannot be decided without comparing its identity; the old page keeps its id, links, facts and timeline and the rest of the source keeps syncing. | Remove the NUL byte or broken Unicode character from the file title and id, commit, and sync again; the pair is decided again when the file changes. | agent | `repeat the read that failed` | 1 | no |
+
+### rename_reconcile_failed
+
+<a id="rename_reconcile_failed"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A renamed file imported, but removing the page of its old name failed unexpectedly, so that page was kept and may be a duplicate. | An unexpected error is deterministic, so a blocking marker would stop the source on every run; the rename is held instead and the rest of the source keeps syncing. | Ask the user before a full sync of the source (gbrain sync --source <source> --full --no-pull), which removes pages whose file is gone, or remove the old page with gbrain delete. | agent | `repeat the read that failed` | 1 | no |
+
### request_already_submitted
<a id="request_already_submitted"></a>
diff --git a/docs/guides/sync-unblock-runbook.md b/docs/guides/sync-unblock-runbook.md
index 7c94d6619c..3122cbad41 100644
--- a/docs/guides/sync-unblock-runbook.md
+++ b/docs/guides/sync-unblock-runbook.md
@@ -124,6 +124,8 @@ Every hold and error has three fields, from one table
| `write_gate_rejected` | page | none | yes | always: write_gate.external_mode=reject is the user's setting |
| `legacy_slug_conflict` | page | none | yes | always: only a person decides which legacy page the file takes over |
| `origin_conflict` | page | repair | no | the hold carries a reason (the pages differ, ids conflict or none is the page the path names), or the heal is off |
+| `rename_identity_unreadable` | page | none | yes | always: the file title or id holds characters the database cannot compare |
+| `rename_reconcile_failed` | page | none | yes | always: the old page may be a duplicate |
| `origin_conflict_decision` | page | none | yes | always: the pages differ, their ids conflict or none is the page the path names |
| `revision_conflict` | page | retry | no | the same path fails again after a rerun |
| `page_identity_changed` | page | retry | no | the same path fails again after a rerun |
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 030dd7d05e..bd6e295479 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -206,6 +206,8 @@ with each file and fix the ones that need no guessing."*
| <a id="legacy_slug_conflict"></a><a id="legacy_slug_conflict-explicit_id_conflict"></a>`legacy_slug_conflict` (`explicit_id_conflict`) | The file has no page at its slug, and several live pages an older gbrain imported before the current slug fold (a space, an emoji, an accent or a trailing dash in the slug; no recorded file) fold to that slug (#6727). Exactly one such page is taken over by the file: the next sync imports into it (same page id, links, timeline and aliases) and records the file as its origin, instead of creating a second page. With several, sync cannot tell which page is the file's, so it holds the file and the rest of the source syncs. It holds the file the same way when the one match has a slug sync cannot write as it stands (capital letters, from a gbrain that predates lowercase slugs; the importer lowercases), rather than creating a second page beside it. With reason `explicit_id_conflict` (#6729), the one match carries an explicit frontmatter `id` that differs from the file's, so it is a different document and is not taken over. With `sync.holds=fail` the run stops with `page_identity_changed`. Twins an older sync already created are not merged by this. | Ask the user which page is the file's (`gbrain sync status --source <source> --json` names every candidate slug). Remove each other one with `gbrain delete --source <source> -- '<slug>'` (soft delete, recoverable for 72 h), or rename the file if none of them is its page; with one match under a slug with capitals, which no command can address yet, keep the file held or rename it to a name that folds to another slug (it then imports as a new page beside the old one, which keeps its links). For `explicit_id_conflict`: give the file the page's `id` if it is the same document; otherwise rename the file or delete the old page. Then `gbrain sync --source <source> --no-pull`. The hold re-screens on every sync. |
| <a id="origin_conflict"></a><a id="origin_conflict-no_canonical_claimant"></a><a id="origin_conflict-content_differs"></a><a id="origin_conflict-file_unreadable"></a><a id="origin_conflict-explicit_id_conflict"></a><a id="origin_conflict-visibility_differs"></a><a id="origin_conflict-trust_tier_differs"></a><a id="origin_conflict-twin_has_withdrawals"></a><a id="origin_conflict-twin_slug_path_occupied"></a><a id="origin_conflict-twin_evidence_conflicts"></a>`origin_conflict` (`no_canonical_claimant`, `content_differs`, `file_unreadable`, `explicit_id_conflict`, `visibility_differs`, `trust_tier_differs`, `twin_has_withdrawals`, `twin_slug_path_occupied`, `twin_evidence_conflicts`) | Several live pages of the source record this file as their origin (duplicate-origin twins, #6948). Sync used to stop the whole source with `page_identity_changed`; now only this file is held and the rest of the source syncs. With no reason the pages are verified duplicates: the page the path names (`meta.canonical_slug`), one inline body, a readable file, no conflicting frontmatter ids, one visibility and trust tier, no slug-keyed fact withdrawals or purges, no file at a twin's own slug path and no link, relationship date, timeline entry or raw payload the merge would lose. Right after that managed sync, the heal merges each other page into the canonical one (links, relationship dates, timeline, raw data, user tags, aliases and facts move; its slug becomes an alias; it is soft-deleted without touching the file, restorable for 72 h) and the next sync imports the file. A reason means a person decides: `no_canonical_claimant` (no page, or not exactly one, is the page the path names), `content_differs` (the bodies differ, or one cannot be read), `file_unreadable`, `explicit_id_conflict` (different frontmatter `id`s), `visibility_differs`, `trust_tier_differs` (a merge never raises or lowers a tier), `twin_has_withdrawals`, `twin_slug_path_occupied`, `twin_evidence_conflicts`. With `sync.holds=fail` the run stops with `page_identity_changed`. | `gbrain repair origin-twins --source <source>` (read-only) lists every group with its pages, revisions and verdict. Verified groups: let the next sync heal them, or apply the preview now. A decision: read each page (`gbrain get --source <source> -- '<slug>'`), then either `gbrain repair origin-twins --source <source> --slug '<kept-slug>'` (the others forget the file and stay live; nothing is deleted) or soft-delete the others with `gbrain delete`. Then `gbrain sync --source <source> --no-pull`. The heal's kill switch is `gbrain config set sync.origin_twins.auto_resolve false`. The hold re-screens on every sync. Guide: [origin twins](repair.md#origin-twins). |
| <a id="rename_held"></a><a id="rename_held-rename_source_changed"></a>`rename_held` (`rename_source_changed`) | A renamed file's hold cleared, but the page it was renamed from changed after the rename was recorded, so the page did not move. | `gbrain repair frontmatter --source <source> --include-ambiguous` proposes re-binding the rename to the old page's current revision; apply after the user agrees. Or restore the old file name. |
+| <a id="rename_identity_unreadable"></a>`rename_identity_unreadable` | Classic sync (GBRA-133 S-51): a file added in the same sync that removed or renamed another has a title or frontmatter `id` the database refused to compare (SQLSTATE 22021 or 22P05), so sync could not tell whether it is that page renamed. The new file is held and the old page keeps its id, links, facts and timeline; the rest of the source keeps syncing. A NUL byte or an unpaired surrogate in a title or id never reaches the database: sync treats such a value as absent and the pair takes the ordinary unconfirmed-rename path. | Remove the characters the database cannot store from the file title and `id`, commit, then `gbrain sync --source <source> --no-pull`. The pair is decided again when the file changes or on `gbrain sources retry-held <source>`. |
+| <a id="rename_reconcile_failed"></a>`rename_reconcile_failed` | Classic sync (GBRA-133 S-67): a rename fell back to importing the new file, and removing the page of the old name then failed with an unexpected error (the hold records its class and code, never its message). The old page was kept and may duplicate the new one; the rest of the source keeps syncing. A transient database error and the reconcile's own "staleness unprovable" verdict still record the `<rename:…>` marker, which a later run converges. | Ask the user before `gbrain sync --source <source> --full --no-pull`: the full walk removes pages whose file is gone after checking each one (it re-reads the whole source). Or remove the old page with `gbrain delete --source <source> -- <slug>` (recoverable for 72 h). |
| <a id="concurrent_write"></a>`concurrent_write` | Managed sync was importing a newer Git version of the file while a database-only write (write-through off, a sandboxed or derived write) committed a different version of the same page, so the two diverge (#6194). The proof is the page's revision itself: it was written by a committed non-sync request for that page. Neither version was overwritten: the page keeps the database version, the file is held and the rest of the source syncs. Since #6340 a page that moved with no such request to name is held the same way (the hold records `page_revision` and `expected_revision` instead of a competing request), and so is a page that changed, was deleted or was re-bound in the database between the manifest freeze and the entry's turn; a page that still holds exactly what the file would import is re-bound to its new revision and passed. | `gbrain sources status <source>` names the page and the competing request. Preview with `gbrain sources reconcile <source> <slug> --preview`, decide with the user which content wins, apply the resolved preview, then `gbrain sources retry-held <source>` and `gbrain sync --source <source> --no-pull` re-screen the file. A new commit of the file re-screens it too. |
| <a id="file_drift"></a>`file_drift` | Managed sync would have imported a file over a database version of its page that sync never saw (#6712). Every import records its provenance (the bytes left on disk, the page revision it wrote, the parser); a page that moved since that record (a database-only write, write-through off) while its file did not change, or, in a tree walk (first sync, `--full`, an unreachable checkpoint), a page whose file and revision both moved or that has no usable record (an upgraded brain: none, a pre-PR 0 record, a partial one), is imported only when the import changes nothing, a sync request wrote its current revision, or its writer's write-through wrote that revision to the file. Otherwise the file is held, the page keeps the database version and the rest of the source syncs. The hold names `sides` (`database`, `both`, `unknown`) and the database request that wrote the page when there was one. Pages under `storage.keep_db` prefixes are never held: the entry is skipped and the keep_db worker reconciles the page from the database. Holds of this code never escalate; with `sync.holds=fail` the run stops with `file_drift` instead of holding. | `gbrain sources status <source>` names the page. Preview `gbrain repair file-drift --source <source> --slug <slug> --prefer database` (keep the database copy, rewrite the file) or `--prefer file` (import the file), decide with the user, apply it with the plan hash, then `gbrain sync --source <source> --no-pull`. A changed file or page revision re-screens the hold by itself. |
| <a id="parser_regression"></a>`parser_regression` | With `GBRAIN_SYNC_PARSER_REGRESSION=hold`, a file whose exact bytes imported under an earlier gbrain is now refused. This is a gbrain bug. | Report it with the gbrain version, the file and the code; upgrade or pin the last good version. After a fixed gbrain is installed, `gbrain sources retry-held <source>` and then `gbrain sync --source <source> --no-pull` re-screen it. |
diff --git a/src/commands/sync/holds.ts b/src/commands/sync/holds.ts
index 12f3d2299d..f1e13cd999 100644
--- a/src/commands/sync/holds.ts
+++ b/src/commands/sync/holds.ts
@@ -290,6 +290,58 @@ export function applyHoldsToManifest(holds: LegacyHolds | null, filtered: { adde
}
}
+/** GBRA-133 S-51: the hold code of a rename pair whose identity the database refused to read. */
+const UNREADABLE_RENAME = 'rename_identity_unreadable';
+
+/**
+ * GBRA-133 S-51: holds each pair the identity confirmation could not read (SQLSTATE 22021/22P05). `to` is not
+ * imported and the page at `from` keeps its id, links, facts and timeline; the hold records that page, so the pair
+ * moves with its id if a later decision confirms it.
+ */
+export async function holdUnreadableRenames(engine: BrainEngine, holds: LegacyHolds, root: string, pairs: Array<{ from: string; to: string; cause: unknown }>): Promise<void> {
+ for (const pair of pairs) {
+ const [page] = await engine.executeRaw<{ id: number | string; slug: string; revision: string }>(
+ `SELECT id, slug, knowledge_revision::text AS revision FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND (source_path=$2 OR slug=$3)
+ ORDER BY (source_path=$2) DESC LIMIT 1`, [holds.sourceId, pair.from, resolveSlugForPath(pair.from) || '']);
+ const filePath = fileUnderRoot(root, pair.to);
+ const state = (pair.cause as { code?: unknown } | null)?.code;
+ await recordLegacyHold(engine, holds, {
+ path: pair.to, upstreamVersion: filePath ? currentVersion(filePath) ?? null : null,
+ renameFrom: page ? { sourcePath: pair.from, slug: page.slug, pageId: Number(page.id), revision: page.revision } : undefined,
+ refusal: { code: UNREADABLE_RENAME, message: `${pair.to} replaces ${pair.from} in this sync, but the database refused to compare its title or id`
+ + `${typeof state === 'string' ? ` (SQLSTATE ${state})` : ''}, so sync could not tell whether it is the same page; it held ${pair.to} and kept the old page.` },
+ });
+ }
+}
+
+/**
+ * GBRA-133 S-51: a held pair whose file this run imports or re-screens is decided again before the hold replay turns
+ * it into a rename. Confirmed: the replay moves the page with its id. Downgraded: the old page is deleted and the file
+ * imports as a new page, as for any unconfirmed pair. Still unreadable: it stays held and is not imported.
+ */
+export async function redecideUnreadableRenames(engine: BrainEngine, holds: LegacyHolds, root: string, filtered: { added: string[]; modified: string[]; deleted: string[] },
+ decide: (pair: { from: string; to: string; pageId: number }) => Promise<'confirmed' | 'downgraded' | 'held'>): Promise<void> {
+ if (!holds.active) return;
+ const existing = holds.existing as Map<string, GitHoldRecord>;
+ for (const [path, record] of existing) {
+ const origin = record.meta.rename_from;
+ const lists = [filtered.added, filtered.modified, holds.rescreen];
+ if (record.code !== UNREADABLE_RENAME || !origin || !lists.some(list => list.includes(path))) continue;
+ const verdict = await decide({ from: origin.sourcePath, to: path, pageId: origin.pageId });
+ if (verdict === 'confirmed') continue;
+ if (verdict === 'downgraded') {
+ const { rename_from: _settled, ...meta } = record.meta;
+ existing.set(path, { ...record, meta });
+ if (!filtered.deleted.includes(origin.sourcePath)) filtered.deleted.push(origin.sourcePath);
+ continue;
+ }
+ for (const list of lists) { const at = list.indexOf(path); if (at >= 0) list.splice(at, 1); }
+ const filePath = fileUnderRoot(root, path);
+ await recordLegacyHold(engine, holds, { path, upstreamVersion: filePath ? currentVersion(filePath) ?? null : null, renameFrom: origin,
+ refusal: { code: UNREADABLE_RENAME, message: record.message } });
+ }
+}
+
/** The rename a hold on `to` (or on an earlier destination of the same origin) still owes. */
function pendingRename(holds: LegacyHolds, from: string, to: string): SyncRename | undefined {
return holds.existing.get(to)?.meta.rename_from
diff --git a/src/commands/sync/preflight.ts b/src/commands/sync/preflight.ts
index 7a52cafe58..5e6bcfaa08 100644
--- a/src/commands/sync/preflight.ts
+++ b/src/commands/sync/preflight.ts
@@ -22,7 +22,7 @@ import {
} from '../../core/sync-anchor.ts';
import type { SlugRootMode } from '../../core/sync-anchor.ts';
import { buildDetachedWorkingTreeManifest, mergeSyncManifests } from '../../core/sync-delta.ts';
-import { confirmedSyncDelta, confirmRenameIdentities } from '../../core/sync-rename-identity.ts';
+import { confirmedSyncDelta, confirmRenameIdentities, redecideHeldRename, type ConfirmedManifest } from '../../core/sync-rename-identity.ts';
import {
git,
isWithinRoot,
@@ -49,7 +49,7 @@ import type { SyncResult, SyncOpts } from '../sync.ts';
import { syncCheckpointKeys, resolveSyncCheckpointEvery } from './checkpoint.ts';
import { runConnectorSync } from './connector.ts';
import { performFullSync } from './full.ts';
-import { applyHoldsToManifest, planHoldRescreen, wouldHoldFields, type LegacyHolds } from './holds.ts';
+import { applyHoldsToManifest, holdUnreadableRenames, planHoldRescreen, redecideUnreadableRenames, wouldHoldFields, type LegacyHolds } from './holds.ts';
import { sweepOrphanedRenameSentinels } from './rename-reconcile.ts';
import type { SyncPlan, SyncActivePack } from './sync-run.ts';
import { formatUrlClonePullBlock, urlClonePullBlock } from '../../core/url-clone.ts';
@@ -133,7 +133,7 @@ export async function preflightIncrementalSync(engine: BrainEngine, opts: SyncOp
const {
storedVersion, currentVersion, versionMismatch, versionNeverSet, importWorkingTree, workingTreeManifest,
hasWorkingTreeChanges, uncommittedDrift, inScope, scopeRel, isSelectedForRun, excluded, syncOpts,
- } = await resolveWorkingTreeScope(engine, opts, { company, gitContextRoot, detachedHead, scoped, syncScopeRelPath });
+ } = await resolveWorkingTreeScope(engine, opts, { company, gitContextRoot, detachedHead, scoped, syncScopeRelPath, holdUnreadable: !!holds?.active });
// #5988: held files re-screen even when Git did not touch them; a run with
// nothing else to do still re-screens them, and clears holds of gone files.
@@ -226,10 +226,17 @@ export async function preflightIncrementalSync(engine: BrainEngine, opts: SyncOp
workingTreeManifest, detachedHead, scoped, slugRootMode, inScope, scopeRel, excluded, isSelectedForRun, syncOpts, holds,
});
if ('done' in delta) return delta;
- const { manifest, filtered, malformedSkipped, syncImportRoot, modePath } = delta;
+ const { manifest, filtered, malformedSkipped, syncImportRoot, modePath, heldRenames } = delta;
if (holds) {
const touched = new Set([...filtered.added, ...filtered.modified, ...filtered.deleted, ...filtered.renamed.flatMap(r => [r.from, r.to])]);
for (let i = holds.rescreen.length - 1; i >= 0; i--) if (touched.has(holds.rescreen[i]!)) holds.rescreen.splice(i, 1);
+ // GBRA-133 S-51: a pair whose identity the database refused waits as a hold; one held earlier is decided again
+ // once its file changes or a retry asks for it, before the hold replay turns it into a rename.
+ if (!opts.dryRun) {
+ await holdUnreadableRenames(engine, holds, syncImportRoot, heldRenames);
+ await redecideUnreadableRenames(engine, holds, syncImportRoot, filtered, pair => redecideHeldRename(engine, gitContextRoot, pin,
+ { ...pair, gitTo: sourceRootMode ? `${syncScopeRelPath}/${pair.to}` : pair.to }, { sourceId: holds.sourceId, sourcePathOf: scopeRel }));
+ }
applyHoldsToManifest(holds, filtered);
}
const totalChanges = filtered.added.length + filtered.modified.length + filtered.deleted.length + filtered.renamed.length + (holds?.rescreen.length ?? 0);
@@ -831,9 +838,11 @@ async function resolveWorkingTreeScope(
detachedHead: boolean;
scoped: boolean;
syncScopeRelPath: string;
+ /** GBRA-133 S-51: the run can hold a rename pair whose identity the database refused to read. */
+ holdUnreadable: boolean;
},
) {
- const { company, gitContextRoot, detachedHead, scoped, syncScopeRelPath } = input;
+ const { company, gitContextRoot, detachedHead, scoped, syncScopeRelPath, holdUnreadable } = input;
// v0.20.0 Cathedral II Layer 12 (codex SP-1 fix): before returning
// 'up_to_date' on git-HEAD equality, check the chunker version gate.
// If sources.chunker_version mismatches CURRENT_CHUNKER_VERSION, force
@@ -871,7 +880,7 @@ async function resolveWorkingTreeScope(
// counting degrades to empty with a stderr note; an EXPLICIT working-tree
// import request fails closed with the reason (importing without the
// manifest would silently skip the very files the caller asked for).
- let workingTreeManifest: SyncManifest;
+ let workingTreeManifest: ConfirmedManifest;
try {
workingTreeManifest = company ? { added: [], modified: [], deleted: [], renamed: [] } : buildDetachedWorkingTreeManifest(gitContextRoot);
} catch (e) {
@@ -900,7 +909,7 @@ async function resolveWorkingTreeScope(
// #6729: an imported dirty tree's inexact renames are confirmed (base HEAD, target the working tree) before any
// filter reads them; a manifest only counted as drift decomposes its renames anyway.
if (importWorkingTree) workingTreeManifest = await confirmRenameIdentities(engine, gitContextRoot, 'HEAD', null, workingTreeManifest,
- { sourceId: opts.sourceId ?? DEFAULT_SOURCE_ID, sourcePathOf: scopeRel });
+ { sourceId: opts.sourceId ?? DEFAULT_SOURCE_ID, sourcePathOf: scopeRel, holdUnreadable });
const includedPaths = company ? new Set(company.plan.manifest.filter(entry => entry.disposition === 'included').map(entry => entry.path)) : null;
const storedPaths = company ? new Set((await engine.executeRaw<{ source_path: string }>('SELECT source_path FROM pages WHERE source_id=$1 AND source_path IS NOT NULL', [opts.sourceId!])).map(page => page.source_path)) : null;
const isSelectedForRun = (path: string, options?: Parameters<typeof isSyncable>[1]): boolean => company
@@ -963,7 +972,7 @@ async function computeFilteredDelta(
pin: string;
fullSyncRoots: { gitContextRoot: string; syncScopeRoot: string; anchorPath: string; slugRootMode: SlugRootMode };
importWorkingTree: boolean;
- workingTreeManifest: SyncManifest;
+ workingTreeManifest: ConfirmedManifest;
detachedHead: boolean;
scoped: boolean;
slugRootMode: SlugRootMode;
@@ -976,7 +985,8 @@ async function computeFilteredDelta(
},
): Promise<
| { done: SyncResult }
- | { manifest: SyncManifest; filtered: SyncManifest; malformedSkipped: string[]; syncImportRoot: string; modePath: (p: string) => string; totalChanges: number }
+ | { manifest: SyncManifest; filtered: SyncManifest; malformedSkipped: string[]; syncImportRoot: string; modePath: (p: string) => string; totalChanges: number;
+ heldRenames: Array<{ from: string; to: string; gitTo: string; cause: unknown }> }
> {
const {
company, gitContextRoot, syncScopeRoot, lastCommit, headCommit, pin, fullSyncRoots, importWorkingTree,
@@ -1000,7 +1010,7 @@ async function computeFilteredDelta(
// throwing — a slow correct reconcile beats a hard error or a silent walk.
// #6729: inexact renames keep their page identity only when confirmed, before the company fold, the unsyncable fold
// and the hold replay read the manifest; the already-confirmed working-tree manifest merges after.
- const delta = await confirmedSyncDelta(engine, gitContextRoot, lastCommit, pin, { sourceId: opts.sourceId ?? DEFAULT_SOURCE_ID, sourcePathOf: scopeRel });
+ const delta = await confirmedSyncDelta(engine, gitContextRoot, lastCommit, pin, { sourceId: opts.sourceId ?? DEFAULT_SOURCE_ID, sourcePathOf: scopeRel, holdUnreadable: !!holds?.active });
if (delta.status === 'unavailable') {
serr(
`[sync] delta ${lastCommit.slice(0, 8)}..${pin.slice(0, 8)} unavailable ` +
@@ -1126,7 +1136,11 @@ async function computeFilteredDelta(
const totalChanges = filtered.added.length + filtered.modified.length +
filtered.deleted.length + filtered.renamed.length;
- return { manifest, filtered, malformedSkipped, syncImportRoot, modePath, totalChanges };
+ // GBRA-133 S-51: pairs the identity confirmation could not read, in this run's scope, by the mode's page paths.
+ const heldRenames = [...(delta.manifest.heldRenames ?? []), ...(importWorkingTree ? workingTreeManifest.heldRenames ?? [] : [])]
+ .filter(pair => inScope(pair.to) && !excluded(pair.to) && isSelectedForRun(pair.to, syncOpts))
+ .map(pair => ({ from: modePath(pair.from), to: modePath(pair.to), gitTo: pair.to, cause: pair.cause }));
+ return { manifest, filtered, malformedSkipped, syncImportRoot, modePath, totalChanges, heldRenames };
}
function dryRunResult(input: {
diff --git a/src/commands/sync/renames.ts b/src/commands/sync/renames.ts
index 71bd912904..ea7e06922b 100644
--- a/src/commands/sync/renames.ts
+++ b/src/commands/sync/renames.ts
@@ -31,7 +31,8 @@ import {
import type { SyncResult } from '../sync.ts';
import { trackedSlugIndex, activeSlugsBySourcePath } from './rename-reconcile.ts';
import type { TrackedSlugIndex } from './rename-reconcile.ts';
-import { clearLegacyHold, holdRefusedImport, holdRenameDestination, noteScreenedImport } from './holds.ts';
+import { clearLegacyHold, holdRefusedImport, holdRenameDestination, noteScreenedImport, recordLegacyHold, type LegacyHolds } from './holds.ts';
+import { classifyItemFailure } from '../../core/item-failure.ts';
import { partial, noteTypeWarning, markCompleted } from './sync-run.ts';
import type { SyncPlan, SyncRun, SyncProgress } from './sync-run.ts';
import { recordFallbackRename } from '../../core/belief/identity.ts';
@@ -380,6 +381,30 @@ export async function carryRenameIdentity(engine: BrainEngine, sourceId: string,
if (publication) await markBeliefCommits(engine, [publication]).catch(() => undefined);
}
+/** The reconcile's own "cannot prove the old row stale" verdict: the one throw that keeps the `<rename:…>` sentinel by design. */
+class RenameStalenessUnprovable extends Error {}
+
+/**
+ * GBRA-133 S-67: holds `to` as `rename_reconcile_failed` when finding the stale rows threw something other than the
+ * unprovable verdict or a transient database error (a connection, a timeout, a lock), which a later run retries. The hold records
+ * the cause's class and code only, never its message (it can quote content). False when it does not apply.
+ */
+async function holdUnexpectedReconcileFailure(engine: BrainEngine, holds: LegacyHolds | null, input: { from: string; to: string; error: unknown }): Promise<boolean> {
+ if (!holds?.active || input.error instanceof RenameStalenessUnprovable) return false;
+ const classified = classifyItemFailure(input.error);
+ if (classified.scope === 'run' || classified.code === 'statement_timeout' || classified.code === 'lock_timeout') return false;
+ const name = input.error instanceof Error ? input.error.name : typeof input.error;
+ const code = (input.error as { code?: unknown } | null)?.code;
+ const cause = `${name}${typeof code === 'string' && /^[\w.-]{1,40}$/.test(code) ? ` ${code}` : ''}`;
+ try {
+ await recordLegacyHold(engine, holds, { path: input.to, upstreamVersion: null, refusal: { code: 'rename_reconcile_failed',
+ message: `${input.to} was renamed from ${input.from} and imported, but removing the old page failed unexpectedly (${cause}), so the old page was kept and may be a duplicate.` } });
+ return true;
+ } catch {
+ return false;
+ }
+}
+
/**
* #3056: when the cheap rename did not apply, the rename fell back to add
* semantics; remove the stale old row once the destination materialized.
@@ -388,7 +413,7 @@ export async function carryRenameIdentity(engine: BrainEngine, sourceId: string,
*/
async function reconcileRenameFallback(
run: SyncRun,
- plan: Pick<SyncPlan, 'opts'>,
+ plan: Pick<SyncPlan, 'opts' | 'holds'>,
ctx: Pick<RenameContext, 'slugLiveness' | 'renameOldSlugs' | 'renameSentinelAlreadyOpen'>,
from: string,
to: string,
@@ -445,6 +470,7 @@ async function reconcileRenameFallback(
// review) — so `staleSlug` below (and the sentinel/remedy text it
// feeds) can only ever name a genuinely-stale row.
let staleSlug: string | undefined;
+ let deleting = false;
try {
const active = await activeSlugsBySourcePath(
engine, [from], opts.sourceId ?? DEFAULT_SOURCE_ID,
@@ -504,6 +530,7 @@ async function reconcileRenameFallback(
}
}
if (staleSlugs.length > 0) {
+ deleting = true;
// Delete every genuinely-stale active row still carrying the
// old path — with a non-unique source_path there can be more
// than one, and the rename is checkpointed after this loop, so
@@ -561,7 +588,7 @@ async function reconcileRenameFallback(
// actionable slug an earlier failure had recorded. `undefined`
// renders as `?`, which is the truth: not known.
staleSlug = undefined;
- throw new Error(
+ throw new RenameStalenessUnprovable(
`staleness unprovable for ${unprovable.length} row(s) ` +
`(${unprovable.join(', ')}): the tracked-file slug index is ` +
`incomplete, so no index miss proves a row stale, and this ` +
@@ -570,6 +597,10 @@ async function reconcileRenameFallback(
);
}
} catch (e: unknown) {
+ // GBRA-133 S-67: a failed delete keeps the sentinel (#3056/#3479: it converges, or `gbrain delete` is its exit), as do
+ // the unprovable verdict and a transient database error; any other throw while finding the stale rows is
+ // deterministic, so this rename is held and the rest of the source syncs.
+ if (!deleting && await holdUnexpectedReconcileFailure(engine, plan.holds, { from, to, error: e })) return false;
reconcileFailed = true;
failedFiles.push({
path: renameSentinelPath(to),
diff --git a/src/core/classic-rename-holds.ts b/src/core/classic-rename-holds.ts
new file mode 100644
index 0000000000..8915892f63
--- /dev/null
+++ b/src/core/classic-rename-holds.ts
@@ -0,0 +1,35 @@
+/**
+ * GBRA-133 PR 1: the fixes of the classic (unmanaged) sync rename holds. gitHoldFix (persistence/sync-holds.ts)
+ * dispatches these codes here; the holds are written by src/commands/sync/holds.ts and renames.ts.
+ *
+ * rename_identity_unreadable (S-51) the database refused to compare a renamed file's title or id, so the pair
+ * waits and the old page stays whole;
+ * rename_reconcile_failed (S-67) a rename fell back to an add and removing the old page threw unexpectedly,
+ * so the old page was kept and may be a duplicate.
+ */
+import type { Action } from './agent-output.ts';
+
+export const CLASSIC_RENAME_HOLD_CODES = ['rename_identity_unreadable', 'rename_reconcile_failed'] as const;
+export type ClassicRenameHoldCode = typeof CLASSIC_RENAME_HOLD_CODES[number];
+
+export function classicRenameHoldFix(record: { source_id: string; path: string; code: string; slug?: string | null }): Action {
+ const source = record.source_id;
+ const verify = { argv: ['gbrain', 'sources', 'status', source, '--json'] };
+ const sync: Action = { argv: ['gbrain', 'sync', '--source', source, '--no-pull'], consent: [], actor: 'agent', requires_exclusive: false, verify,
+ why: `Re-screens ${record.path} after the file is fixed; the rest of the source keeps syncing either way.` };
+ if (record.code === 'rename_reconcile_failed') {
+ return { argv: ['gbrain', 'sync', '--source', source, '--full', '--no-pull'], consent: [], actor: 'user', requires_exclusive: false,
+ docs: 'docs/guides/write-refusals.md#rename_reconcile_failed',
+ user_message: `${record.path} was imported as the new name of a renamed file, but removing the page of the old name failed unexpectedly, so sync kept that page (it may now duplicate ${record.slug ?? 'the new page'}) and the rest of source ${source} kept syncing. `
+ + `A full sync of the source (gbrain sync --source ${source} --full --no-pull) re-reads every file and removes pages whose file is gone after checking each one; it can take a while on a large source. `
+ + 'Or find the old page with gbrain sources status and remove it with gbrain delete (recoverable for 72 h).',
+ why: 'Whether to remove a page is the user\'s call; the hold records only the failure\'s class and code, never its message.',
+ verify };
+ }
+ return { argv: verify.argv, consent: [], actor: 'user', requires_exclusive: false, docs: 'docs/guides/write-refusals.md#rename_identity_unreadable',
+ user_message: `${record.path} replaces a file removed in the same sync, but the database refused to compare its title or frontmatter id, so sync could not tell whether it is the same page. `
+ + `It held ${record.path} and kept the old page (same id, links, facts and timeline); the rest of source ${source} keeps syncing. `
+ + `Remove the characters the database cannot store (a NUL byte or a broken Unicode character) from the file's title and id, commit, then run gbrain sync --source ${source} --no-pull: the next sync decides again whether it is the old page.`,
+ why: 'Which page a file is cannot be decided without comparing its identity, and sync never guesses; the hold is decided again when the file changes or on gbrain sources retry-held.',
+ then: sync, verify };
+}
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 5a5436d9dc..8ae869b7ca 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -532,6 +532,8 @@ export const CODES = {
relay_session_expired: { class: 'caller', summary: "Google connect credential error: relay session expired.", docs: 'docs/guides/google-connect.md#troubleshooting' },
relay_unreachable: { class: 'retryable', summary: "Google connect credential error: relay unreachable.", docs: 'docs/guides/google-connect.md#troubleshooting' },
rename_held: { class: 'caller', summary: "A renamed file is held because the page it was renamed from changed after the rename was recorded.", reasons: ['rename_source_changed'], why: "Moving the page now could carry the newer edit to the wrong file, so the rename waits for an explicit re-bind.", suggestion: 'Preview the frontmatter repair with --include-ambiguous to re-bind the rename to the current page, and approve it.' },
+ rename_identity_unreadable: { class: 'caller', summary: "A renamed file is held because the database refused to compare its title or frontmatter id (SQLSTATE 22021/22P05), so sync could not tell whether it is the page it replaces.", why: "Which page a file is cannot be decided without comparing its identity; the old page keeps its id, links, facts and timeline and the rest of the source keeps syncing.", suggestion: 'Remove the NUL byte or broken Unicode character from the file title and id, commit, and sync again; the pair is decided again when the file changes.' },
+ rename_reconcile_failed: { class: 'caller', summary: "A renamed file imported, but removing the page of its old name failed unexpectedly, so that page was kept and may be a duplicate.", why: "An unexpected error is deterministic, so a blocking marker would stop the source on every run; the rename is held instead and the rest of the source keeps syncing.", suggestion: 'Ask the user before a full sync of the source (gbrain sync --source <source> --full --no-pull), which removes pages whose file is gone, or remove the old page with gbrain delete.' },
request_already_submitted: { class: 'caller', summary: "This optimizer publication request has already been submitted." },
request_too_large: { class: 'caller', summary: "The request exceeds a configured capacity; narrow it." },
requirements_changed: { class: 'caller', summary: "The runtime requirements exceed the owner-approved publication policy." },
diff --git a/src/core/item-failure.ts b/src/core/item-failure.ts
index 747b6e24d5..1a4dff618d 100644
--- a/src/core/item-failure.ts
+++ b/src/core/item-failure.ts
@@ -25,6 +25,7 @@ import { OperationError, opError } from './ops/contract.ts';
import { CODES } from './error-registry.ts';
import { acceptedPendingReceipt } from './persistence/accepted-pending.ts';
import { providerItemRefusal } from './ai/errors.ts';
+import { quotesPath } from './retry-matcher.ts';
/** Every per-item loop that isolates its items, with the inventory row it fixes (reports/GBRA-130-inventory.md). */
export const ISOLATE_SITES = {
@@ -101,6 +102,8 @@ function sqlstateFailure(state: string): { code: string; scope: 'run' | 'item';
}
const RUN_ERRNOS = new Set(['ENOSPC', 'EMFILE', 'ENFILE', 'EROFS', 'EDQUOT']);
+/** A database socket or driver connection that went away (the codes the connection text below names); a child process's ETIMEDOUT or EPIPE stays the item's. */
+const ITEM_CONNECTION_CODES = new Set(['ECONNRESET', 'ECONNREFUSED', 'CONNECTION_CLOSED', 'CONNECTION_ENDED', 'CONNECTION_DESTROYED']);
const ITEM_ERRNOS = new Set(['EACCES', 'EPERM', 'ENOENT', 'ELOOP', 'EISDIR', 'ENOTDIR', 'ENAMETOOLONG', 'EILSEQ']);
const RUN_ERROR_NAMES: Record<string, string> = { AbortError: 'aborted', LockStolenError: 'lock_stolen', BudgetExhausted: 'budget_exhausted' };
/** A model or embedding provider's own failure (the gateway's error classes, an HTTP fetch that failed): never the database connection; a provider outage trips the breaker. */
@@ -130,13 +133,15 @@ function classifyOne(error: unknown): ClassifiedItemFailure | null {
if (sql) return { ...sql, message, requestId: null };
}
if (typeof raw === 'string' && RUN_ERRNOS.has(raw)) return { code: 'disk_full', scope: 'run', class: 'transient', message, requestId: null };
+ if (typeof raw === 'string' && ITEM_CONNECTION_CODES.has(raw)) return { code: 'connection_lost', scope: 'run', class: 'transient', message, requestId: null };
if (typeof raw === 'string' && ITEM_ERRNOS.has(raw)) return { code: 'unreadable_item', scope: 'item', class: 'content', message, requestId: null };
const refusal = providerItemRefusal(error);
if (refusal) return { code: refusal, scope: 'item', class: 'content', message, requestId: null };
if ((typeof name === 'string' && AI_ERROR_NAMES.has(name)) || /^fetch failed\b/i.test(message)) {
return { code: 'provider_error', scope: 'item', class: 'transient', message, requestId: null };
}
- if (/ECONNRESET|ECONNREFUSED|connection (terminated|ended|closed)|Connection terminated|socket hang up/i.test(message)) {
+ // GBRA-133 S-65/S-70: connection text is read only from an uncoded error naming no path; a coded error was decided above.
+ if (raw === undefined && !quotesPath(message) && /ECONNRESET|ECONNREFUSED|connection (terminated|ended|closed)|Connection terminated|socket hang up/i.test(message)) {
return { code: 'connection_lost', scope: 'run', class: 'transient', message, requestId: null };
}
return null;
diff --git a/src/core/persistence/public-category.ts b/src/core/persistence/public-category.ts
index 8861db7c99..55641342ff 100644
--- a/src/core/persistence/public-category.ts
+++ b/src/core/persistence/public-category.ts
@@ -36,6 +36,7 @@ export const PUBLIC_BY_CODE: Readonly<Record<string, PublicCategory>> = {
worktree_dirty: 'drift', file_drift: 'drift', source_changed: 'drift', pinned_git_worktree_conflict: 'drift',
concurrent_write: 'conflict', revision_conflict: 'conflict', page_identity_changed: 'conflict', legacy_slug_conflict: 'conflict', origin_conflict: 'conflict', origin_conflict_decision: 'conflict',
invalid_fence: 'content_refused', invalid_frontmatter: 'content_refused', frontmatter_slug_conflict: 'content_refused', rename_held: 'content_refused',
+ rename_identity_unreadable: 'content_refused', rename_reconcile_failed: 'conflict',
file_too_large: 'content_refused', content_rejected: 'content_refused', managed_image_sync_unsupported: 'content_refused',
purged_content: 'content_refused', write_gate_rejected: 'content_refused',
file_database_drift: 'drift', raw_file_changed: 'drift', pending_import: 'transient',
diff --git a/src/core/persistence/sync-fault-class.ts b/src/core/persistence/sync-fault-class.ts
index 9f96b34a9b..4ca55a55c4 100644
--- a/src/core/persistence/sync-fault-class.ts
+++ b/src/core/persistence/sync-fault-class.ts
@@ -84,6 +84,11 @@ export const SYNC_FAULT_TABLE: ReadonlyArray<SyncFaultRule> = [
{ 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.' },
// #6948: an `origin_conflict` hold whose verdict carries a reason (sync-status.ts holdVerdict): nothing resolves it without a person.
+ // GBRA-133 PR 1: classic rename holds (src/core/classic-rename-holds.ts); only a person changes the file or removes the page.
+ { code: 'rename_identity_unreadable', class: 'page', safe_actions: ['none'], needs_human: true, escalate: 'always: the file title or id holds characters the database cannot compare',
+ human_reason: 'The database refused to compare this renamed file title or frontmatter id; a person removes the NUL byte or broken Unicode character from the file and commits, then syncs.' },
+ { code: 'rename_reconcile_failed', class: 'page', safe_actions: ['none'], needs_human: true, escalate: 'always: the old page may be a duplicate',
+ human_reason: 'A rename imported but the old page could not be removed; a person runs a full sync of the source (it removes pages whose file is gone) or removes the old page with gbrain delete.' },
{ code: 'origin_conflict_decision', class: 'page', safe_actions: ['none'], needs_human: true, escalate: 'always: the pages differ, their ids conflict or none is the page the path names',
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.' },
// Older releases recorded these as run failures; a rerun on this release holds the page instead.
diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.ts
index eeaeb11c1e..e308389202 100644
--- a/src/core/persistence/sync-holds.ts
+++ b/src/core/persistence/sync-holds.ts
@@ -42,6 +42,7 @@ import type { FenceReason, FenceTier, GateLetter } from '../fence-repair/types.t
import { FENCE_VERSION } from '../fence-repair/refusal.ts';
import { fenceHoldFix, fenceHoldLocation, fencePreviewArgv, readFenceAutoRepair, type FenceAutoRepair, type FenceHoldLocation } from '../fence-repair/hold-fix.ts';
import { contentHoldDocs, contentHoldFix } from '../content-repair/hold-fix.ts';
+import { classicRenameHoldFix } from '../classic-rename-holds.ts';
import { STRUCTURED_WRITE_ADVICE, type FencesNormalized } from '../fence-repair/report.ts';
import type { SyncDiscovery, SyncRename } from './sync-discovery.ts';
import { isCodeFilePath, isImageFilePath, isMultimodalEnabled } from '../sync.ts';
@@ -70,7 +71,9 @@ export const GIT_HOLD_ESCALATE_MIN_SCREENED = 40;
type Exec = Pick<BrainEngine, 'executeRaw'>;
export type GitHoldCode = ContentRefusal['code'] | 'rename_held' | 'parser_regression' | 'managed_image_sync_unsupported' | 'concurrent_write' | 'preparation_stalled' | 'worktree_dirty' | 'file_drift'
- | 'legacy_slug_conflict' | 'write_interrupted' | 'origin_conflict';
+ | 'legacy_slug_conflict' | 'write_interrupted' | 'origin_conflict'
+ /** GBRA-133 PR 1 (classic sync): src/core/classic-rename-holds.ts. */
+ | 'rename_identity_unreadable' | 'rename_reconcile_failed';
/**
* Flip lane C: the holds of a write that ran out of attempts, its preparation never settling (`preparation_stalled`)
* or its statements ended by the database every time (`write_interrupted`). The file is not the problem: they route to
@@ -738,6 +741,8 @@ export function gitHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'c
+ (soft.length ? `, for example: ${soft.join('; ')}` : '') + `; then run gbrain sync --source ${source} --no-pull. gbrain repair origin-twins --source ${source} lists the group and its commands.`,
why: 'Which page owns a file cannot be decided when the pages differ, carry different frontmatter ids, or none is the page the path names; sync never deletes a page it cannot prove is a duplicate.', then, verify };
}
+ case 'rename_identity_unreadable': case 'rename_reconcile_failed':
+ return classicRenameHoldFix(record);
case 'rename_held':
return repair(true, `The page that ${record.path} renames changed after the rename was recorded, so it was not moved; the preview proposes re-binding the rename to the current page for approval.`);
case 'frontmatter_slug_conflict':
diff --git a/src/core/retry-matcher.ts b/src/core/retry-matcher.ts
index d4703dedf9..05d198d509 100644
--- a/src/core/retry-matcher.ts
+++ b/src/core/retry-matcher.ts
@@ -76,6 +76,23 @@ export function getCode(err: unknown): string | undefined {
return undefined;
}
+/** Socket errnos and postgres.js library codes that mean an open connection went away: decided by the code, never the message. */
+const CONNECTION_CODES: ReadonlySet<string> = new Set(['ECONNRESET', 'ECONNABORTED', 'ETIMEDOUT', 'EPIPE', 'CONNECTION_CLOSED', 'CONNECTION_ENDED', 'CONNECTION_DESTROYED']);
+
+/** True for a socket errno or a postgres.js connection code. */
+export function isConnectionCode(code: string | undefined): boolean {
+ return code !== undefined && CONNECTION_CODES.has(code);
+}
+
+/**
+ * GBRA-133 S-70: does this message name a path? Connection text is only read from a message that names none, so an
+ * unexpected error quoting a file such as `notes/connection closed.md` is never taken for a dropped connection.
+ * URLs (a connection string, an endpoint) are not paths.
+ */
+export function quotesPath(message: string): boolean {
+ return /[\\/]/.test(message.replace(/[a-z][a-z0-9+.-]*:\/\/\S*/gi, ''));
+}
+
export function getMessage(err: unknown): string {
if (err instanceof Error) return err.message;
if (err && typeof err === 'object') {
@@ -133,6 +150,7 @@ export function isRetryableConnError(err: unknown): boolean {
// The message form is already caught by /connection.*closed/i below; match
// the code too for wrappers that rethrow with the code but a new message.
if (code === 'CONNECTION_CLOSED') return true;
+ if (isConnectionCode(code)) return true;
// v0.42.x (#1794): SQLSTATE 53300 too_many_connections — pool/pooler
// exhaustion. Starts with 53 not 08, so the /^08/ test above misses it.
// Transient: the spike clears as in-flight queries release connections.
@@ -147,7 +165,7 @@ export function isRetryableConnError(err: unknown): boolean {
return true;
}
const msg = getMessage(err);
- return CONN_PATTERNS.some(p => p.test(msg));
+ return !quotesPath(msg) && CONN_PATTERNS.some(p => p.test(msg));
}
/**
@@ -159,8 +177,9 @@ export function isRetryableConnError(err: unknown): boolean {
*/
export function isConnectionLoss(err: unknown): boolean {
const code = getCode(err);
- if (code && (/^08/.test(code) || ['CONNECTION_CLOSED', 'CONNECTION_ENDED', 'CONNECTION_DESTROYED', '57P01', '57P02', '57P03'].includes(code))) return true;
- return /\b(ECONNRESET|ECONNABORTED|ETIMEDOUT|EPIPE)\b|Connection terminated unexpectedly|server closed the connection|connection.*closed|terminating connection due to administrator command/i.test(getMessage(err));
+ if (code && (/^08/.test(code) || isConnectionCode(code) || ['57P01', '57P02', '57P03'].includes(code))) return true;
+ const msg = getMessage(err);
+ return !quotesPath(msg) && /\b(ECONNRESET|ECONNABORTED|ETIMEDOUT|EPIPE)\b|Connection terminated unexpectedly|server closed the connection|connection.*closed|terminating connection due to administrator command/i.test(msg);
}
/**
diff --git a/src/core/sync-rename-identity.ts b/src/core/sync-rename-identity.ts
index 4f572b5260..6c7c0a2410 100644
--- a/src/core/sync-rename-identity.ts
+++ b/src/core/sync-rename-identity.ts
@@ -41,6 +41,20 @@ import { computeSyncDelta, type SyncDeltaResult } from './sync-delta.ts';
const HEAD_BYTES = 64 * 1024;
+/** GBRA-133 S-51: text Postgres cannot store or compare (SQLSTATE 22021/22P05): U+0000 or a lone UTF-16 surrogate. */
+const UNQUERYABLE_TEXT = /\u0000|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
+/** An identity value the database cannot compare is absent (never normalized into another value). */
+const queryable = (value: string | null): string | null => value !== null && UNQUERYABLE_TEXT.test(value) ? null : value;
+/** The SQLSTATEs a parameter the database cannot encode raises: an invalid byte sequence, an untranslatable character. */
+const UNREADABLE_IDENTITY_STATES: ReadonlySet<string> = new Set(['22021', '22P05']);
+const unreadableIdentity = (error: unknown): boolean => {
+ for (let current = error, depth = 0; current && depth < 5; depth++, current = (current as { cause?: unknown }).cause) {
+ const code = (current as { code?: unknown }).code;
+ if (typeof code === 'string' && UNREADABLE_IDENTITY_STATES.has(code)) return true;
+ }
+ return false;
+};
+
/** `digest`: sha256 of the whole file when it fit in the head read (null for a longer file), the content-continuity signal. */
export interface FrontmatterIdentity { id: string | null; slug: string | null; title: string | null; digest: string | null }
const NO_IDENTITY: FrontmatterIdentity = { id: null, slug: null, title: null, digest: null };
@@ -54,7 +68,7 @@ export function frontmatterIdentity(head: Buffer | string | null): FrontmatterId
if (head === null) return NO_IDENTITY;
const text = (typeof head === 'string' ? head : head.toString('utf8')).replace(/^\uFEFF/, '');
let title: string | null;
- try { title = explicitMarkdownTitle(text) || null; } catch { title = null; }
+ try { title = queryable(explicitMarkdownTitle(text) || null); } catch { title = null; }
const digest = Buffer.byteLength(head) < HEAD_BYTES ? createHash('sha256').update(head).digest('hex') : null;
const block = /^---\r?\n([\s\S]*?)\r?\n(?:---|\.\.\.)[ \t]*(?:\r?\n|$)/.exec(text);
if (!block) return { ...NO_IDENTITY, title, digest };
@@ -64,7 +78,7 @@ export function frontmatterIdentity(head: Buffer | string | null): FrontmatterId
const field = (key: string, numeric = false): string | null => {
const value = (data as Record<string, unknown>)[key];
const text = typeof value === 'string' ? value.trim() : numeric && typeof value === 'number' && Number.isFinite(value) ? String(value) : '';
- return text === '' ? null : text;
+ return text === '' ? null : queryable(text);
};
return { id: field('id', true), slug: field('slug'), title, digest };
}
@@ -249,7 +263,18 @@ export function decideRenameIdentities(manifest: SyncManifest, inputs: RenameIde
};
}
-export interface ConfirmRenameOpts { sourceId: string; /** See `RenameIdentityInputs.sourcePathOf`. */ sourcePathOf?: (gitPath: string) => string }
+/** GBRA-133 S-51: an inexact pair whose identity the database refused to read (`cause`, SQLSTATE 22021/22P05); neither side is in the manifest. */
+export interface HeldIdentityRename { from: string; to: string; similarity: number; cause: unknown }
+/** A confirmed manifest; `heldRenames` lists the pairs the caller must hold instead of applying. */
+export interface ConfirmedManifest extends SyncManifest { heldRenames?: HeldIdentityRename[] }
+
+export interface ConfirmRenameOpts {
+ sourceId: string;
+ /** See `RenameIdentityInputs.sourcePathOf`. */
+ sourcePathOf?: (gitPath: string) => string;
+ /** The caller holds `heldRenames`; without it a pair the database refused to read still throws its error. */
+ holdUnreadable?: boolean;
+}
/**
* Reads both sides' frontmatter and the live pages sharing their ids and titles, then applies
@@ -257,7 +282,7 @@ export interface ConfirmRenameOpts { sourceId: string; /** See `RenameIdentityIn
* whose base is HEAD).
*/
export async function confirmRenameIdentities(engine: Pick<BrainEngine, 'executeRaw'>, repo: string, base: string, target: string | null,
- manifest: SyncManifest, opts: ConfirmRenameOpts): Promise<SyncManifest> {
+ manifest: SyncManifest, opts: ConfirmRenameOpts): Promise<ConfirmedManifest> {
if (!needsRenameConfirmation(manifest)) return manifest;
const readable = (path: string) => isMarkdownFilePath(path) && !path.includes('\n');
const basePaths = [...new Set([...manifest.deleted, ...manifest.renamed.map(rename => rename.from)].filter(readable))];
@@ -270,26 +295,56 @@ export async function confirmRenameIdentities(engine: Pick<BrainEngine, 'execute
// The old side's title is the one its page row stores: a page whose title changed in the brain is compared as it is now.
const titled = basePaths.filter(path => baseIdentity.get(path)!.title);
const sourcePathOf = opts.sourcePathOf ?? ((path: string) => path);
- const stored = titled.length ? await engine.executeRaw<{ slug: string; source_path: string | null; title: string | null }>(
+ // GBRA-133 S-51: both reads batch every path; a value the database cannot encode (22021/22P05) is found by retrying
+ // path by path, and only the pairs carrying it are held. Every other error propagates (a lost connection is the run's).
+ const unreadable = new Map<string, unknown>();
+ const perPath = async <T>(paths: string[], read: (paths: string[]) => Promise<T[]>): Promise<T[]> => {
+ if (paths.length === 0) return [];
+ try { return await read(paths); } catch (error) {
+ if (!unreadableIdentity(error)) throw error;
+ const rows: T[] = [];
+ for (const path of paths) {
+ try { rows.push(...await read([path])); } catch (one) {
+ if (!unreadableIdentity(one)) throw one;
+ unreadable.set(path, one);
+ }
+ }
+ return rows;
+ }
+ };
+ const stored = await perPath(titled, paths => engine.executeRaw<{ slug: string; source_path: string | null; title: string | null }>(
`SELECT slug, source_path, title FROM pages WHERE source_id = $1 AND deleted_at IS NULL AND (source_path = ANY($2::text[]) OR slug = ANY($3::text[]))`,
- [opts.sourceId, [...new Set(titled.flatMap(path => [path, sourcePathOf(path)]))], titled.map(path => resolveSlugForPath(sourcePathOf(path)))]) : [];
+ [opts.sourceId, [...new Set(paths.flatMap(path => [path, sourcePathOf(path)]))], paths.map(path => resolveSlugForPath(sourcePathOf(path)))]));
for (const path of titled) {
const row = stored.find(page => page.source_path === path || page.source_path === sourcePathOf(path))
?? stored.find(page => page.source_path === null && page.slug === resolveSlugForPath(sourcePathOf(path)));
if (row) baseIdentity.set(path, { ...baseIdentity.get(path)!, title: row.title?.trim() || null });
}
- const identities = [...baseIdentity.values(), ...targetIdentity.values()];
- const ids = [...new Set(identities.flatMap(identity => identity.id ? [identity.id] : []))];
- const titles = [...new Set(identities.flatMap(identity => identity.title ? [identity.title] : []))];
- const live = ids.length || titles.length ? await engine.executeRaw<LiveIdentityHolder>(
- `SELECT slug, source_path, frontmatter->>'id' AS fm_id, title FROM pages
- WHERE source_id = $1 AND deleted_at IS NULL AND (frontmatter->>'id' = ANY($2::text[]) OR title = ANY($3::text[]))`,
- [opts.sourceId, ids, titles]) : [];
- const decided = decideRenameIdentities(manifest, {
+ const identityOf = (path: string) => [baseIdentity.get(path), targetIdentity.get(path)].filter((identity): identity is FrontmatterIdentity => !!identity);
+ const valued = [...new Set([...basePaths, ...targetPaths])].filter(path => identityOf(path).some(identity => identity.id || identity.title));
+ const live = await perPath(valued, paths => {
+ const identities = paths.flatMap(identityOf);
+ return engine.executeRaw<LiveIdentityHolder>(
+ `SELECT slug, source_path, frontmatter->>'id' AS fm_id, title FROM pages
+ WHERE source_id = $1 AND deleted_at IS NULL AND (frontmatter->>'id' = ANY($2::text[]) OR title = ANY($3::text[]))`,
+ [opts.sourceId, [...new Set(identities.flatMap(identity => identity.id ? [identity.id] : []))], [...new Set(identities.flatMap(identity => identity.title ? [identity.title] : []))]]);
+ });
+ // A path whose identity the database refused: an inexact pair carrying it is held (the old page stays whole); on an
+ // unpaired add or delete its identity is absent, which today's rules already treat as a plain add or delete.
+ const held: HeldIdentityRename[] = [];
+ for (const path of unreadable.keys()) { baseIdentity.delete(path); targetIdentity.delete(path); }
+ const pairs = manifest.renamed.filter(rename => {
+ const cause = rename.similarity !== undefined && rename.similarity < 100 ? unreadable.get(rename.from) ?? unreadable.get(rename.to) : undefined;
+ if (cause !== undefined) held.push({ from: rename.from, to: rename.to, similarity: rename.similarity!, cause });
+ return cause === undefined;
+ });
+ const decided: ConfirmedManifest = decideRenameIdentities({ ...manifest, renamed: pairs }, {
base: path => baseIdentity.get(path) ?? NO_IDENTITY,
target: path => targetIdentity.get(path) ?? NO_IDENTITY,
live, sourcePathOf: opts.sourcePathOf, targetSource: target === null ? 'working_tree' : 'commit',
});
+ if (held.length && !opts.holdUnreadable) throw held[0]!.cause;
+ if (held.length) decided.heldRenames = held;
if (target !== null) return decided;
// A dirty-tree verdict holds only for the bytes it read: each kept rename carries their digest, and the identity move
// re-checks it against the bytes it imports (classic applyRename, managed readSyncContent).
@@ -300,8 +355,37 @@ export async function confirmRenameIdentities(engine: Pick<BrainEngine, 'execute
return { ...decided, renamed: decided.renamed.map(stamp) };
}
+/**
+ * GBRA-133 S-51: decides a held pair again (its file changed, or a retry asked): the base side is the page the hold
+ * kept (its stored id and title), the target the file at `target`. `held` when the database still refuses a value.
+ */
+export async function redecideHeldRename(engine: Pick<BrainEngine, 'executeRaw'>, repo: string, target: string,
+ pair: { from: string; to: string; gitTo: string; pageId: number }, opts: ConfirmRenameOpts): Promise<'confirmed' | 'downgraded' | 'held'> {
+ const [page] = await engine.executeRaw<{ fm_id: string | null; title: string | null }>(
+ `SELECT frontmatter->>'id' AS fm_id, title FROM pages WHERE id = $1 AND deleted_at IS NULL`, [pair.pageId]);
+ if (!page) return 'downgraded';
+ const before: FrontmatterIdentity = { ...NO_IDENTITY, id: queryable(page.fm_id?.trim() || null), title: queryable(page.title?.trim() || null) };
+ const [head] = pair.gitTo.includes('\n') ? [null] : await catFileHeads(repo, [`${target}:${pair.gitTo}`]);
+ const after = frontmatterIdentity(head ?? null);
+ const ids = [...new Set([before.id, after.id].filter((value): value is string => !!value))];
+ const titles = [...new Set([before.title, after.title].filter((value): value is string => !!value))];
+ let live: LiveIdentityHolder[];
+ try {
+ live = ids.length || titles.length ? await engine.executeRaw<LiveIdentityHolder>(
+ `SELECT slug, source_path, frontmatter->>'id' AS fm_id, title FROM pages
+ WHERE source_id = $1 AND deleted_at IS NULL AND (frontmatter->>'id' = ANY($2::text[]) OR title = ANY($3::text[]))`, [opts.sourceId, ids, titles]) : [];
+ } catch (error) {
+ if (unreadableIdentity(error)) return 'held';
+ throw error;
+ }
+ const decided = decideRenameIdentities({ added: [], modified: [], deleted: [], renamed: [{ from: pair.from, to: pair.to, similarity: 0 }] }, {
+ base: path => path === pair.from ? before : NO_IDENTITY, target: path => path === pair.to ? after : NO_IDENTITY, live,
+ });
+ return decided.renamed.length ? 'confirmed' : 'downgraded';
+}
+
/** `computeSyncDelta` of a commit range with its renames confirmed (the commit-range half of every incremental sync). */
-export async function confirmedSyncDelta(engine: Pick<BrainEngine, 'executeRaw'>, repo: string, from: string, to: string, opts: ConfirmRenameOpts): Promise<SyncDeltaResult> {
+export async function confirmedSyncDelta(engine: Pick<BrainEngine, 'executeRaw'>, repo: string, from: string, to: string, opts: ConfirmRenameOpts): Promise<Exclude<SyncDeltaResult, { status: 'ok' }> | { status: 'ok'; manifest: ConfirmedManifest }> {
const delta = computeSyncDelta(repo, from, to);
return delta.status === 'ok' ? { status: 'ok', manifest: await confirmRenameIdentities(engine, repo, from, to, delta.manifest, opts) } : delta;
}
diff --git a/test/e2e/s-51-rename-identity-unreadable-postgres.test.ts b/test/e2e/s-51-rename-identity-unreadable-postgres.test.ts
new file mode 100644
index 0000000000..f4b21feec7
--- /dev/null
+++ b/test/e2e/s-51-rename-identity-unreadable-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../pathological/s-51-rename-identity-unreadable.test.ts'));
diff --git a/test/e2e/s-70-classifier-origin-postgres.test.ts b/test/e2e/s-70-classifier-origin-postgres.test.ts
new file mode 100644
index 0000000000..ff8f5b47ec
--- /dev/null
+++ b/test/e2e/s-70-classifier-origin-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../pathological/s-70-classifier-origin.test.ts'));
diff --git a/test/pathological/s-51-rename-identity-unreadable.test.ts b/test/pathological/s-51-rename-identity-unreadable.test.ts
new file mode 100644
index 0000000000..c10f0ea64e
--- /dev/null
+++ b/test/pathological/s-51-rename-identity-unreadable.test.ts
@@ -0,0 +1,141 @@
+/**
+ * GBRA-133 S-51 (PR 1 item 1): a NUL or a lone surrogate in a title or frontmatter id used to reach
+ * confirmRenameIdentities' text[] parameters, so every classic incremental run of the source failed with SQLSTATE
+ * 22021 and no ledger row (only --full escaped). Such values are now absent before any SQL (the pair takes today's
+ * unconfirmed-rename rules, never a normalized value), and a value the database still refuses (22021/22P05) holds only
+ * the pair carrying it as rename_identity_unreadable, keeping the old page whole; any other error stays the run's.
+ * Classic sync on PGLite, and on Postgres through test/e2e/s-51-rename-identity-unreadable-postgres.test.ts.
+ */
+import { describe, expect, test } from 'bun:test';
+import { unlinkSync } from 'node:fs';
+import { join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { performSync } from '../../src/commands/sync/perform.ts';
+import { readGitSourceHolds, gitHoldItem } from '../../src/core/persistence/sync-holds.ts';
+import { frontmatterIdentity } from '../../src/core/sync-rename-identity.ts';
+import { loadSyncFailures } from '../../src/core/sync-failure-ledger.ts';
+import { expectUnitNotAborted, pathologicalArms } from './harness.ts';
+import { md, withProbeEngine, withProbeRepo, type ProbeRepo } from './s-blockers-fixture.ts';
+
+const body = (title: string, extra = '') => `---\ntitle: ${title}\ntype: note\n---\n${Array.from({ length: 12 }, (_, i) => `Line ${i} of the ${title} note, long enough that git pairs an edited move.`).join('\n')}\n${extra}`;
+const page = async (engine: BrainEngine, sourceId: string, slug: string) =>
+ (await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [sourceId, slug]))[0]?.id ?? null;
+const holdsOf = async (engine: BrainEngine, sourceId: string) => ((await readGitSourceHolds(engine, { sourceIds: [sourceId] }))[0]?.holds ?? []);
+const syncWith = (r: ProbeRepo, engine: BrainEngine) => performSync(engine, { repoPath: r.root, sourceId: r.sourceId, noPull: true, noEmbed: true, noExtract: true, concurrency: 1 });
+
+/** The engine whose identity-confirmation reads (the stored-title and live-identity queries) throw `error` when `when` matches their params. */
+function failingIdentityReads(engine: BrainEngine, error: () => unknown, when: (params: unknown[]) => boolean): BrainEngine {
+ return new Proxy(engine, { get(target, prop) {
+ const value = Reflect.get(target, prop);
+ if (prop === 'executeRaw' && typeof value === 'function') {
+ return (sql: string, params: unknown[] = []) => /\btitle FROM pages\b/.test(sql) && /= ANY\([$][23]::text\[\]\)/.test(sql) && when(params)
+ ? Promise.reject(error()) : (value as Function).call(target, sql, params);
+ }
+ return typeof value === 'function' ? value.bind(target) : value;
+ } }) as BrainEngine;
+}
+const naming = (needle: string) => (params: unknown[]) => JSON.stringify(params).includes(needle);
+
+describe('S-51 identity values the database cannot compare are absent', () => {
+ test('a NUL or a lone surrogate in a title, id or slug reads as no value; other values are kept as written', () => {
+ expect(frontmatterIdentity('# Meeting notes\u0000\u0000')).toMatchObject({ title: null });
+ expect(frontmatterIdentity('---\ntitle: "a\\0b"\nid: "x\\0y"\nslug: "s\\0"\n---\nbody')).toMatchObject({ title: null, id: null, slug: null });
+ expect(frontmatterIdentity('---\ntitle: "a\\uD800b"\nid: "\\uDC00"\n---\nbody')).toMatchObject({ title: null, id: null });
+ expect(frontmatterIdentity('---\ntitle: "Caf\\u00e9 \\U0001F600"\nid: note-7\n---\nbody')).toMatchObject({ title: 'Café 😀', id: 'note-7' });
+ });
+});
+
+for (const { backend, databaseUrl } of pathologicalArms()) {
+ describe(`S-51 classic sync: rename identity the database refuses (${backend})`, () => {
+ test('S-51 a NUL-padded title committed with a markdown delete syncs; later commits keep syncing', () => withProbeEngine(databaseUrl, (engine, home) => withProbeRepo(engine, 'classic', home, async r => {
+ r.write('notes/old.md', md('old')); r.commitAll('old');
+ expect((await r.sync()).status).toBe('first_sync');
+ unlinkSync(join(r.root, 'notes/old.md'));
+ r.write('notes/nul-title.md', '# Meeting notes\u0000\u0000\u0000');
+ r.write('ok/healthy-1.md', md('healthy one'));
+ r.commitAll('odd');
+ await expectUnitNotAborted(() => r.sync());
+ expect({ cursor: await r.lastCommit() === r.head(), healthy: await page(engine, r.sourceId, 'ok/healthy-1') !== null, old: await page(engine, r.sourceId, 'notes/old') })
+ .toEqual({ cursor: true, healthy: true, old: null });
+ r.write('ok/healthy-2.md', md('healthy two')); r.commitAll('healthy two');
+ await expectUnitNotAborted(() => r.sync());
+ expect({ cursor: await r.lastCommit() === r.head(), healthy: await page(engine, r.sourceId, 'ok/healthy-2') !== null }).toEqual({ cursor: true, healthy: true });
+ })), 180_000);
+
+ test('S-51 a NUL title in an edited move takes the unconfirmed-rename path (never a normalized value); a page with the colliding plain title keeps its id, links and timeline', () => withProbeEngine(databaseUrl, (engine, home) => withProbeRepo(engine, 'classic', home, async r => {
+ r.write('notes/keep.md', '---\ntitle: Meeting notes\ntype: note\n---\nSee [[seed]].\n');
+ r.write('notes/move.md', body('Moved note'));
+ r.write('notes/gone.md', md('Gone'));
+ r.commitAll('base');
+ expect((await r.sync()).status).toBe('first_sync');
+ const keep = await page(engine, r.sourceId, 'notes/keep');
+ await engine.executeRaw("INSERT INTO timeline_entries(page_id, date, summary) VALUES($1, '2026-01-02', 'kept entry')", [keep]);
+ await engine.addLink('notes/keep', 'seed', 'kept link', undefined, undefined, undefined, undefined, { fromSourceId: r.sourceId, toSourceId: r.sourceId });
+ const kept = async () => (await engine.executeRaw<{ links: number; timeline: number; deleted: string | null }>(`SELECT
+ (SELECT count(*)::int FROM links WHERE from_page_id=p.id) AS links, (SELECT count(*)::int FROM timeline_entries WHERE page_id=p.id) AS timeline,
+ p.deleted_at::text AS deleted FROM pages p WHERE p.id=$1`, [keep]))[0];
+ const before = await kept();
+ unlinkSync(join(r.root, 'notes/move.md'));
+ r.write('notes/moved.md', body('Moved note').replace(/^---[\s\S]*?---\n/, '# Moved note\u0000\n'));
+ unlinkSync(join(r.root, 'notes/gone.md'));
+ r.write('notes/nul.md', '# Meeting notes\u0000\u0000\nAnother note.\n');
+ r.write('ok/healthy-1.md', md('healthy one'));
+ r.commitAll('odd');
+ expect(r.git('diff', '--name-status', '-M', 'HEAD~1', 'HEAD')).toMatch(/^R\d+\tnotes\/move\.md\tnotes\/moved\.md$/m);
+ await expectUnitNotAborted(() => r.sync());
+ expect({ cursor: await r.lastCommit() === r.head(), healthy: await page(engine, r.sourceId, 'ok/healthy-1') !== null,
+ keepId: await page(engine, r.sourceId, 'notes/keep'), kept: await kept(), moveOld: await page(engine, r.sourceId, 'notes/move') })
+ .toEqual({ cursor: true, healthy: true, keepId: keep, kept: before, moveOld: null });
+ expect(before).toEqual({ links: 1, timeline: 1, deleted: null });
+ })), 180_000);
+
+ test('S-51 a value the database still refuses (22021) holds only its pair: the old page stays whole, the other pair renames, and a later edit renames it with its id', () => withProbeEngine(databaseUrl, (engine, home) => withProbeRepo(engine, 'classic', home, async r => {
+ r.write('notes/a.md', body('Poison title')); r.write('notes/c.md', body('Fine title'));
+ r.commitAll('base');
+ expect((await r.sync()).status).toBe('first_sync');
+ const a = await page(engine, r.sourceId, 'notes/a'), c = await page(engine, r.sourceId, 'notes/c');
+ unlinkSync(join(r.root, 'notes/a.md')); r.write('notes/b.md', body('Poison title', 'An edit.\n'));
+ unlinkSync(join(r.root, 'notes/c.md')); r.write('notes/d.md', body('Fine title', 'An edit.\n'));
+ r.write('ok/healthy-1.md', md('healthy one'));
+ r.commitAll('moves');
+ const refused = failingIdentityReads(engine, () => Object.assign(new Error('invalid byte sequence for encoding "UTF8": 0x00'), { code: '22021' }), naming('Poison title'));
+ await expectUnitNotAborted(() => syncWith(r, refused));
+ const held = (await holdsOf(engine, r.sourceId)).find(h => h.path === 'notes/b.md');
+ expect({ cursor: await r.lastCommit() === r.head(), healthy: await page(engine, r.sourceId, 'ok/healthy-1') !== null,
+ a: await page(engine, r.sourceId, 'notes/a'), b: await page(engine, r.sourceId, 'notes/b'), d: await page(engine, r.sourceId, 'notes/d'), c: await page(engine, r.sourceId, 'notes/c'),
+ hold: held && { code: held.code, origin: held.meta.rename_from?.pageId }, ledger: loadSyncFailures().filter(f => f.source_id === r.sourceId).length })
+ .toEqual({ cursor: true, healthy: true, a, b: null, d: c, c: null, hold: { code: 'rename_identity_unreadable', origin: a }, ledger: 0 });
+ const fix = gitHoldItem(held!).fix;
+ expect({ actor: fix.actor, argv: fix.argv, then: fix.then?.argv }).toEqual({ actor: 'user', argv: ['gbrain', 'sources', 'status', r.sourceId, '--json'],
+ then: ['gbrain', 'sync', '--source', r.sourceId, '--no-pull'] });
+ expect(fix.user_message).toContain('notes/b.md');
+ // Untouched, the hold waits (no re-decision, nothing imported).
+ r.write('ok/healthy-2.md', md('healthy two')); r.commitAll('healthy two');
+ await expectUnitNotAborted(() => r.sync());
+ expect({ a: await page(engine, r.sourceId, 'notes/a'), b: await page(engine, r.sourceId, 'notes/b'), held: (await holdsOf(engine, r.sourceId)).map(h => h.path) })
+ .toEqual({ a, b: null, held: ['notes/b.md'] });
+ // The file changes and the database reads it: the pair is decided again and the page moves with its id.
+ r.write('notes/b.md', body('Poison title', 'An edit.\nA fix.\n')); r.commitAll('fix b');
+ await expectUnitNotAborted(() => r.sync());
+ expect({ cursor: await r.lastCommit() === r.head(), a: await page(engine, r.sourceId, 'notes/a'), b: await page(engine, r.sourceId, 'notes/b'), held: (await holdsOf(engine, r.sourceId)).length })
+ .toEqual({ cursor: true, a: null, b: a, held: 0 });
+ })), 180_000);
+
+ test('S-51 run: a lost connection during identity confirmation stops the run with nothing deleted or added, and the next run renames', () => withProbeEngine(databaseUrl, (engine, home) => withProbeRepo(engine, 'classic', home, async r => {
+ r.write('notes/a.md', body('Some title'));
+ r.commitAll('base');
+ expect((await r.sync()).status).toBe('first_sync');
+ const a = await page(engine, r.sourceId, 'notes/a');
+ const before = await r.lastCommit();
+ unlinkSync(join(r.root, 'notes/a.md')); r.write('notes/b.md', body('Some title', 'An edit.\n'));
+ r.commitAll('move');
+ const lost = failingIdentityReads(engine, () => Object.assign(new Error('Connection terminated unexpectedly'), { code: '08006' }), () => true);
+ await expect(syncWith(r, lost)).rejects.toThrow('Connection terminated unexpectedly');
+ expect({ cursor: await r.lastCommit(), a: await page(engine, r.sourceId, 'notes/a'), b: await page(engine, r.sourceId, 'notes/b'), held: (await holdsOf(engine, r.sourceId)).length })
+ .toEqual({ cursor: before, a, b: null, held: 0 });
+ await expectUnitNotAborted(() => r.sync());
+ expect({ cursor: await r.lastCommit() === r.head(), a: await page(engine, r.sourceId, 'notes/a'), b: await page(engine, r.sourceId, 'notes/b') })
+ .toEqual({ cursor: true, a: null, b: a });
+ })), 180_000);
+ });
+}
diff --git a/test/pathological/s-70-classifier-origin.test.ts b/test/pathological/s-70-classifier-origin.test.ts
new file mode 100644
index 0000000000..c1c3185c5c
--- /dev/null
+++ b/test/pathological/s-70-classifier-origin.test.ts
@@ -0,0 +1,135 @@
+/**
+ * GBRA-133 PR 1 item 4 (classifier hardening), classic sync.
+ *
+ * S-65/S-70: the item classifier and the retry matchers read "connection closed", "ECONNRESET" and friends from any
+ * error's message, so an unexpected per-file error whose message quotes a path such as notes/connection closed.md was
+ * a lost connection: the run stopped with no ledger row on every rerun. The run scope now comes from the error's code
+ * (SQLSTATE class 08, socket errnos, the driver's connection codes) and connection text is read only from an uncoded
+ * message naming no path.
+ *
+ * S-67: the rename reconcile turned any throw into a hard-blocking `<rename:…>` marker that --skip-failed cannot pass.
+ * Its own "staleness unprovable" verdict and transient database errors keep the marker (a later run converges); any
+ * other throw holds the rename as rename_reconcile_failed with its class and code, and the source keeps syncing.
+ *
+ * PGLite here; Postgres through test/e2e/s-70-classifier-origin-postgres.test.ts.
+ */
+import { describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { performSync } from '../../src/commands/sync/perform.ts';
+import { classifyItemFailure } from '../../src/core/item-failure.ts';
+import { isConnectionLoss, isRetryableConnError } from '../../src/core/retry-matcher.ts';
+import { gitHoldItem, readGitSourceHolds } from '../../src/core/persistence/sync-holds.ts';
+import { loadSyncFailures } from '../../src/core/sync-failure-ledger.ts';
+import { expectUnitNotAborted, pathologicalArms } from './harness.ts';
+import { md, withProbeEngine, withProbeRepo, type ProbeRepo } from './s-blockers-fixture.ts';
+
+const coded = (code: string, message: string) => Object.assign(new Error(message), { code });
+
+describe('S-70 connection scope comes from the error, never a quoted path', () => {
+ test('an uncoded error quoting a path is the item\'s; driver errors and coded errors still stop the run', () => {
+ expect(classifyItemFailure(new Error('import failed for notes/connection closed.md')).scope).toBe('item');
+ expect(classifyItemFailure(new TypeError("Cannot read properties of undefined (reading 'x') in notes/econnreset.md")).scope).toBe('item');
+ expect(classifyItemFailure(new Error('read ECONNRESET')).scope).toBe('run');
+ expect(classifyItemFailure(coded('ECONNRESET', 'read failed on /var/run/socket')).scope).toBe('run');
+ expect(classifyItemFailure(coded('CONNECTION_CLOSED', 'write CONNECTION_CLOSED db.example.invalid:5432')).scope).toBe('run');
+ expect(classifyItemFailure(coded('08006', 'Connection terminated unexpectedly')).scope).toBe('run');
+ expect(classifyItemFailure(coded('ETIMEDOUT', 'spawnSync git ETIMEDOUT')).scope).toBe('item');
+ });
+
+ test('the retry matchers ignore a quoted path but keep driver text, connection strings and connection codes', () => {
+ for (const fn of [isRetryableConnError, isConnectionLoss]) {
+ expect(fn(new Error('cannot import notes/connection closed.md'))).toBe(false);
+ expect(fn(new Error('cannot import notes\\ECONNRESET.md'))).toBe(false);
+ expect(fn(new Error('Connection terminated unexpectedly'))).toBe(true);
+ expect(fn(new Error('connection closed by postgresql://db.example.invalid:5432/brain'))).toBe(true);
+ expect(fn(coded('ECONNRESET', 'read failed on /var/run/socket'))).toBe(true);
+ }
+ });
+});
+
+/** The engine whose page reads inside a file's import throw `error` for `slug` (no production seam). */
+function failingImport(engine: BrainEngine, slug: string, 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') && args[0] === slug ? Promise.reject(error()) : (value as Function).apply(target, args);
+ }
+ return typeof value === 'function' ? value.bind(target) : value;
+ } }) as BrainEngine;
+}
+
+/** The engine whose old-row lookup inside the rename reconcile throws `error`. */
+function failingReconcile(engine: BrainEngine, error: () => unknown): BrainEngine {
+ return new Proxy(engine, { get(target, prop) {
+ const value = Reflect.get(target, prop);
+ if (prop === 'executeRaw' && typeof value === 'function') {
+ return (sql: string, params?: unknown[]) => /SELECT slug, source_path FROM pages/.test(sql) && new Error().stack?.includes('reconcileRenameFallback')
+ ? Promise.reject(error()) : (value as Function).call(target, sql, params);
+ }
+ return typeof value === 'function' ? value.bind(target) : value;
+ } }) as BrainEngine;
+}
+
+const syncWith = (r: ProbeRepo, engine: BrainEngine) => performSync(engine, { repoPath: r.root, sourceId: r.sourceId, noPull: true, noEmbed: true, noExtract: true, concurrency: 1 });
+const live = async (r: ProbeRepo, slug: string) => (await r.engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [r.sourceId, slug]))[0]?.id ?? null;
+const ledger = (r: ProbeRepo) => loadSyncFailures().filter(f => f.source_id === r.sourceId).map(f => ({ path: f.path, state: f.state }));
+
+for (const { backend, databaseUrl } of pathologicalArms()) {
+ describe(`S-70/S-67 classic sync (${backend})`, () => {
+ test('S-70 item: an unexpected import error quoting notes/connection closed.md is a ledger row, the siblings import, and it auto-skips on run 3', () => withProbeEngine(databaseUrl, (engine, home) => withProbeRepo(engine, 'classic', home, async r => {
+ expect((await r.sync()).status).toBe('first_sync');
+ r.write('notes/connection closed.md', md('odd')); r.write('ok/healthy-1.md', md('healthy one')); r.commitAll('odd');
+ const failing = failingImport(engine, 'notes/connection-closed', () => new Error('unexpected failure while importing notes/connection closed.md'));
+ const runs = [];
+ for (let i = 0; i < 3; i++) runs.push((await expectUnitNotAborted(() => syncWith(r, failing))).status);
+ expect({ runs, ledger: ledger(r), healthy: await live(r, 'ok/healthy-1') !== null, cursor: await r.lastCommit() === r.head() })
+ .toEqual({ runs: ['blocked_by_failures', 'blocked_by_failures', 'synced'], ledger: [{ path: 'notes/connection closed.md', state: 'auto_skipped' }], healthy: true, cursor: true });
+ })), 180_000);
+
+ test('S-70 run: a coded lost connection while importing still stops the run with no ledger row', () => withProbeEngine(databaseUrl, (engine, home) => withProbeRepo(engine, 'classic', home, async r => {
+ expect((await r.sync()).status).toBe('first_sync');
+ const before = await r.lastCommit();
+ r.write('notes/plain.md', md('plain')); r.commitAll('plain');
+ // Postgres reconnects and retries a lost connection on a fresh pool (outside this proxy), so the run may also recover;
+ // either way the lost connection is never charged to the file.
+ let thrown: string | null = null;
+ try { await syncWith(r, failingImport(engine, 'notes/plain', () => coded('08006', 'Connection terminated unexpectedly'))); } catch (error) { thrown = (error as Error).message; }
+ const cursor = await r.lastCommit();
+ expect({ ledger: ledger(r), outcome: thrown === null ? { recovered: cursor === r.head() } : { thrown, cursorKept: cursor === before } })
+ .toEqual({ ledger: [], outcome: thrown === null ? { recovered: true } : { thrown: 'Connection terminated unexpectedly', cursorKept: true } });
+ if (backend === 'pglite') expect(thrown).toBe('Connection terminated unexpectedly');
+ })), 180_000);
+
+ const renameOntoLivePage = async (r: ProbeRepo) => {
+ r.write('people/carol.md', md('Carol')); r.commitAll('carol');
+ expect((await r.sync()).status).toBe('first_sync');
+ await r.engine.putPage('people/dana', { type: 'person', title: 'Dana (stale)', compiled_truth: 'occupies the destination slug' }, { sourceId: r.sourceId });
+ r.git('mv', 'people/carol.md', 'people/dana.md'); r.write('ok/healthy-1.md', md('healthy one')); r.commitAll('rename');
+ };
+
+ test('S-67 item: an unexpected throw in the rename reconcile holds the rename (class and code only) instead of a blocking marker', () => withProbeEngine(databaseUrl, (engine, home) => withProbeRepo(engine, 'classic', home, async r => {
+ await renameOntoLivePage(r);
+ const result = await expectUnitNotAborted(() => syncWith(r, failingReconcile(engine, () => new TypeError("Cannot read properties of undefined (reading 'slug') for people/carol.md"))));
+ const hold = ((await readGitSourceHolds(engine, { sourceIds: [r.sourceId] }))[0]?.holds ?? []).find(h => h.path === 'people/dana.md');
+ expect({ status: result.status, cursor: await r.lastCommit() === r.head(), ledger: ledger(r), code: hold?.code, healthy: await live(r, 'ok/healthy-1') !== null, carol: await live(r, 'people/carol') !== null })
+ .toEqual({ status: 'synced', cursor: true, ledger: [], code: 'rename_reconcile_failed', healthy: true, carol: true });
+ expect(hold!.message).toContain('(TypeError)');
+ expect(hold!.message).not.toContain('Cannot read');
+ const fix = gitHoldItem(hold!).fix;
+ expect({ actor: fix.actor, argv: fix.argv }).toEqual({ actor: 'user', argv: ['gbrain', 'sync', '--source', r.sourceId, '--full', '--no-pull'] });
+ r.write('ok/healthy-2.md', md('healthy two')); r.commitAll('later');
+ await expectUnitNotAborted(() => r.sync());
+ expect({ cursor: await r.lastCommit() === r.head(), healthy: await live(r, 'ok/healthy-2') !== null }).toEqual({ cursor: true, healthy: true });
+ })), 180_000);
+
+ test('S-67 run: a transient database error in the reconcile keeps the <rename:…> marker, and the next run converges', () => withProbeEngine(databaseUrl, (engine, home) => withProbeRepo(engine, 'classic', home, async r => {
+ await renameOntoLivePage(r);
+ const result = await expectUnitNotAborted(() => syncWith(r, failingReconcile(engine, () => coded('57014', 'canceling statement due to statement timeout'))));
+ expect({ status: result.status, marker: ledger(r).some(row => row.path.startsWith('<rename:')) }).toEqual({ status: 'blocked_by_failures', marker: true });
+ await expectUnitNotAborted(() => r.sync());
+ expect({ cursor: await r.lastCommit() === r.head(), carol: await live(r, 'people/carol'), markers: ledger(r).filter(row => row.path.startsWith('<rename:') && row.state === 'open') })
+ .toEqual({ cursor: true, carol: null, markers: [] });
+ })), 180_000);
+ });
+}
+