Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync-holds): resolve no-origin, slug-spelling and agreeing file_drift holds

garrytan5245e8a57242
diff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.md
index ec54e77a8d..2a16e55cd0 100644
--- a/docs/architecture/key-files/canonical-reconciliation.md
+++ b/docs/architecture/key-files/canonical-reconciliation.md
@@ -34,7 +34,7 @@ See [generations](generations.md).
- `src/commands/doctor/checks/managed-sync-convergence.ts` — doctor `managed_sync_convergence` (#6712 PR 4a, `deep` tier): the convergence shadow's counts for each managed source this host owns; always `ok` (informational), read-only. Tests: `test/doctor-managed-sync-convergence.test.ts`.
- `src/core/persistence/file-claims.ts` — the recorded-origin census shared by reconcile and the shared-origin delete (#6517): `fileClaimCandidatesQuery` (the paged same-name query and its binds, built per platform so every bound placeholder is referenced (#6659: an unreferenced bind failed every Windows `delete_page` with 42P18), 100 rows per batch below the source's highest page id, served by the v219 name indexes; `source_path` in any spelling or a `file:` URI; tombstones excluded) and `findLiveFileClaimants`, realpath deciding each candidate. In `page-prepare.ts`, a `delete_page` whose file another live page records (`prepareFileTarget` with `sharedOrigin`, before the byte comparison) owns no file: a soft delete publishes database-only with receipt `write_through.skipped: 'shared_origin'` and a warning ("hidden … does not erase", the `gbrain repair file-drift --source <id> --slug <survivor> --prefer file` that imports the kept file into the survivor; #6712 PR 1: sync holds a survivor that differs from the file `file_drift`, and that hold's fix leads with the same command), `validate` re-runs the census under the publication guards (`validateSharedOrigin`: the file moved or removed, or a different claimant set, refuses `source_changed` and never removes the file), and the surviving slug is named only when `slugDisclosable` (authority.ts: the local owner, or a remote writer whose prefix grant, delegated namespace and visibility cover it). An owner purge of a shared-origin page refuses and names the soft delete (the retention purge for a tombstone). #7311: the retention purge of a shared-origin tombstone is database-only like an `origin_twin` page's (`sharedRetention`: no file target, applied with `source_path`/`source_uri` forgotten, so no deletion marker names the survivor's file); `validate` re-runs the census, and a changed one refuses `revision_conflict` (`sharedTombstoneChanged`, a purge deferral), so the next run takes the normal path. Tests: `test/purge-shared-origin-tombstone-7311.test.ts` (Postgres: `test/e2e/purge-shared-origin-tombstone-7311-postgres.test.ts`), `test/page-prepare-shared-origin-6517.test.ts`, `test/sync-origin-live-wins-6517.test.ts`, `test/e2e/managed-sync-shared-origin-6517.test.ts`.
- `src/core/persistence/drift-conflicts.ts` — the `source_changed` / `file_database_drift` conflict pile (#6643). `auditDriftConflicts` groups conflict receipts by slug over a bounded window of request sequences (default 100,000, at most 1,000,000), paginated by slug with a `complete` flag; it backs `gbrain sources reconcile <source> --audit --conflicts` (`reconcile-audit.ts`) and MCP `list_write_conflicts` (`ops/persistence.ts`). The window ends at the source's own newest request (current incarnation, the `(source_incarnation, sequence)` index; a cursor never reads past it), and a source the caller may not read returns before anything is computed; the MCP op refuses an out-of-grant `source_id` through `resolveRequestedScope`. Remote callers get database-derived fields only, with source grant, slug fence and visibility filtered in the aggregating SQL; `liveFileDrift` (the `prepareFileTarget` comparison; reason `canonical_file_missing` for a live page whose canonical file is gone, `file_missing` for any other `source_changed`) and `driftClass` (the `reconcile-additive.ts` verdict) run only for a trusted local caller on the canonical owner, and such a row carries the compared file `path`. `submitMaintenance` (`prepared-maintenance.ts`, `maintenanceDriftRefusal`) refuses a drifted page before admission, and `synthesize_concepts` skips a drifted concept before spend, recording it in `dream.concepts.drift_skips` (per-entry atomic updates, released when the sides agree). Tests: `test/maintenance-file-drift-6643.test.ts` (PGLite; Postgres via `test/e2e/maintenance-file-drift-6643-postgres.test.ts`).
-- `src/core/repair/file-drift.ts` — `gbrain repair file-drift` (#6643): explicit-only, preview-bound resolution of drifted pages through `reconcileCanonical` with one side preferred (`preferSideDecisions`) inside reconcile's protections; `driftExceptions` lists where the result differs from the preferred side. The preview writes a private artifact under `configDir()/repair-previews/file-drift/<hash>.json` and saves the approved set; apply runs `runReconcileApply` per page under request ids derived from the hash and slug, so an interrupted apply resumes. `--all-drifted` refuses mixed drift classes unless `--class` keeps one. Repeatable `--only`/`--skip` over the source-relative canonical file path (`src/core/repair/path-glob.ts` `matchesRepairPath`: a value without `*` is an exact path, as every kind's `--only`; with `*` it is a glob, file-drift only: `*` within a segment, `**` across) narrow the selection before the class check, the 1,000-page bound and any preview work (`not_selected` residual); they join the selection digest only when given (so earlier hashes are unchanged) and appear in every printed preview and apply command. `prepareDriftPage` builds one page's ready reconcile preview for a preferred side; the plan and the keep_db policy share it. `--keep` is refused at parse in `src/commands/repair.ts` with the same command rewritten to `--prefer database`. `reconcile-prepare.ts` keeps the file bytes when they already parse to the result digest. Doctor `maintenance_write_drift` (`src/commands/doctor/checks/maintenance-drift.ts`) counts what remains and, on the owner host, echoes each declared `storage.keep_db` policy as `keep_db_policy` (prefixes, matched drifted pages among those checked live, `unchecked`, receipt cost from `keepDbReceiptCost`). #6712 wave: a selected page whose `liveFileDrift` reason is `canonical_file_missing` goes through `fileGonePage` (`ghostPageNow` for the path, revision and owner; `canonicalDeletionState` for the route): still committed at HEAD is listed `deletion_uncommitted`, gone from HEAD becomes a `prepareDriftPage(..., { fileGone: true })` recreate (`file_gone`, details `action: 'recreate_file'`; a warning when `gitDurabilityPolicy` is not durable, since an uncommitted recreated file loses to the committed deletion on the next sync) or a `SoftDeletePage` applied through `retireGhost` (exported from `repair/ghost-pages.ts`, under the file-drift request id) with the ghost-pages mass valve; `--all-drifted` never selects missing files. `--held [--side both|unknown|deleted [--state tombstone_edited|purged_differs|file_gone]]` (#6712 PR 4b) selects the source's held `file_drift` pages of one Decision (`selectHeld`, side from `fileDriftSide`): several sides or states without `--side` refuse `file_drift_mixed_selection`, a deleted side without `--state` refuses `file_drift_state_required`, and holds with no side (`sides: database`) list `legacy_side`. Both/unknown and `file_gone` pages take the paths above; `tombstone_edited` and `purged_differs` go through `deletedPage` over `readDeletedDriftTarget`: `--prefer database` is a `RemoveFilePage` applied as the `managed_maintenance_file_drift_remove` intent (`prepareDriftFileRemoval`, dispatched from `prepared-maintenance.ts`: a page file target with no bytes bound to the previewed hash, the tombstone revision or marker value re-checked under the publication guard, the hold cleared in the publishing transaction, the page row untouched), `--prefer file` an `ImportFilePage` applied through `submitManagedFileRepair` with the file's own bytes (restores the tombstone, or creates the page; the deletion marker stays for sync to retire). Each `details.pages` entry carries `verb` (`fileDriftActionVerb`), printed by `render`. The Decision is the hold's `meta.side` / `meta.state` (`sync-holds.ts`: `fileDriftSide` reads older holds' `sides`; `gitHoldItem` lists both; a deleted hold's fix previews `heldDriftPreviewArgv` for its path and names each option's verb). Test: `test/repair-file-drift-held-6712.test.ts`.
+- `src/core/repair/file-drift.ts` — `gbrain repair file-drift` (#6643): explicit-only, preview-bound resolution of drifted pages through `reconcileCanonical` with one side preferred (`preferSideDecisions`) inside reconcile's protections; `driftExceptions` lists where the result differs from the preferred side. The preview writes a private artifact under `configDir()/repair-previews/file-drift/<hash>.json` and saves the approved set; apply runs `runReconcileApply` per page under request ids derived from the hash and slug, so an interrupted apply resumes. `--all-drifted` refuses mixed drift classes unless `--class` keeps one. Repeatable `--only`/`--skip` over the source-relative canonical file path (`src/core/repair/path-glob.ts` `matchesRepairPath`: a value without `*` is an exact path, as every kind's `--only`; with `*` it is a glob, file-drift only: `*` within a segment, `**` across) narrow the selection before the class check, the 1,000-page bound and any preview work (`not_selected` residual); they join the selection digest only when given (so earlier hashes are unchanged) and appear in every printed preview and apply command. `prepareDriftPage` builds one page's ready reconcile preview for a preferred side; the plan and the keep_db policy share it. `--keep` is refused at parse in `src/commands/repair.ts` with the same command rewritten to `--prefer database`. `reconcile-prepare.ts` keeps the file bytes when they already parse to the result digest. Doctor `maintenance_write_drift` (`src/commands/doctor/checks/maintenance-drift.ts`) counts what remains and, on the owner host, echoes each declared `storage.keep_db` policy as `keep_db_policy` (prefixes, matched drifted pages among those checked live, `unchecked`, receipt cost from `keepDbReceiptCost`). #6712 wave: a selected page whose `liveFileDrift` reason is `canonical_file_missing` goes through `fileGonePage` (`ghostPageNow` for the path, revision and owner; `canonicalDeletionState` for the route): still committed at HEAD is listed `deletion_uncommitted`, gone from HEAD becomes a `prepareDriftPage(..., { fileGone: true })` recreate (`file_gone`, details `action: 'recreate_file'`; a warning when `gitDurabilityPolicy` is not durable, since an uncommitted recreated file loses to the committed deletion on the next sync) or a `SoftDeletePage` applied through `retireGhost` (exported from `repair/ghost-pages.ts`, under the file-drift request id) with the ghost-pages mass valve; `--all-drifted` never selects missing files. `--held [--side both|unknown|deleted [--state tombstone_edited|purged_differs|file_gone]]` (#6712 PR 4b) selects the source's held `file_drift` pages of one Decision (`selectHeld`, side from `fileDriftSide`): several sides or states without `--side` refuse `file_drift_mixed_selection`, a deleted side without `--state` refuses `file_drift_state_required`, and holds with no side (`sides: database`) list `legacy_side`. Both/unknown and `file_gone` pages take the paths above; `tombstone_edited` and `purged_differs` go through `deletedPage` over `readDeletedDriftTarget`: `--prefer database` is a `RemoveFilePage` applied as the `managed_maintenance_file_drift_remove` intent (`prepareDriftFileRemoval`, dispatched from `prepared-maintenance.ts`: a page file target with no bytes bound to the previewed hash, the tombstone revision or marker value re-checked under the publication guard, the hold cleared in the publishing transaction, the page row untouched), `--prefer file` an `ImportFilePage` applied through `submitManagedFileRepair` with the file's own bytes (restores the tombstone, or creates the page; the deletion marker stays for sync to retire). Each `details.pages` entry carries `verb` (`fileDriftActionVerb`), printed by `render`. The Decision is the hold's `meta.side` / `meta.state` (`sync-holds.ts`: `fileDriftSide` reads older holds' `sides`; `gitHoldItem` lists both; a deleted hold's fix previews `heldDriftPreviewArgv` for its path and names each option's verb). Test: `test/repair-file-drift-held-6712.test.ts`. A held page whose page and file agree (`liveFileDrift` reason `agrees`) is a `ReleasePage` (`release_hold`): its apply re-checks the pinned page revision and file hash, then schedules a re-screen of that one held path (`requestGitHoldRetry`, as `sources retry-held` does), and the next sync releases it. A page with no file origin (`recordsNoFileOrigin` in `unbound-pages.ts`: no source path and no `file:` source URI) adopts its slug-path file, which `slugPathFile` resolves to the spelling sync imports as the slug (`README.md` for `readme`), as `prepareFileTarget` and `liveFileDrift` do. Test: `test/sync-holds-wave-gbra133.test.ts`.
- `src/core/ghost-pages.ts` — #6696 B5, the one ghost-page classifier: a ghost is a live page for which `liveFileDrift` returns reason `canonical_file_missing` on the source's canonical owner host (`prepareFileTarget` tags that refusal `detail: 'canonical_file_missing'`). `scanGhostSource` reads a source's live pages in id order (at most `GHOST_SCAN_LIMIT`), resolves each recorded canonical path exactly as `prepareFileTarget` does and stats it, skips `publishesDatabaseOnly` and legacy slugs, and runs the full check on at most `candidateLimit` candidates; it returns the ghosts, `inspected`, `file_backed` (the mass-delete valve's population), `truncated` and the owner it ran under (host, worktree, owner epoch, incarnation). Off the owner host a source is `not_applicable` (`not_owner_host`, or `not_applicable` with no binding); a missing root is `unknown` (`storage_unavailable`), a stat error, invalid gbrain.yml or inconclusive check `unknown` (`ambiguous_storage`). `ghostPageNow` re-checks one page (the repair's recheck); `readGhostPages(engine, { sourceIds?, sampleLimit? })` is the counts-and-samples summary for doctor and the read-scope health op. Tests: `test/ghost-pages-6696.test.ts`.
- `src/core/repair/ghost-pages.ts` — `gbrain repair ghost-pages --source <id>` (#6696 B5): explicit-only, preview-bound, destructive consent (`GHOST_CONSENT_TEXT`: the 72 h purge fuse, the per-slug `gbrain restore <slug> --force` undo, and the keep path of restoring the file and syncing). The preview binds the ghost set to the owner and each page's revision and path; the apply refuses `not_owner_host`, `ghost_storage_unknown`, `preview_changed` on an owner change, and `ghost_mass_delete_refused` (`massGhosts`: the sync valve, `MASS_RECONCILE_RATIO` over more than `MASS_RECONCILE_MIN_PAGES` file-backed pages, unless `massReconcileAllowed()`). Each page re-checks with `ghostPageNow`, then a managed brain submits one `managed_maintenance_retire_ghost_page` request (`prepareGhostPageRetirement`, dispatched from `prepared-maintenance.ts`: re-check, `delete_page` with `allowMissingFile`, refusal unless the prepared file target is the approved path with no bytes, so filesystem publication refuses a file that appeared later); an unmanaged brain soft-deletes in one transaction after the same check. Outcomes `soft_deleted`, `file_restored` (asks for a new preview), `changed_since_preview`. Doctor `ghost_pages` (`src/commands/doctor/checks/ghost-pages.ts`, BRAIN, after `fence_integrity`) reports the count, samples and coverage with the preview as its fix, `ok` + info off the owner host, unknown on an unreadable checkout; `gbrain pages ghosts` (`src/commands/pages-ghosts.ts`) lists them read-only.
- `src/core/repair/legacy-twins.ts` — `gbrain repair legacy-twins --source <id>` (#6885): explicit-only, preview-bound, destructive consent (`LEGACY_TWINS_CONSENT_TEXT`). `scanLegacyTwins` reads a source's live pages with no recorded origin and no `database_only_reason` in id batches (at most `LEGACY_TWINS_SCAN_LIMIT`), keeps those whose slug `slugifyPath` folds differently, and pairs each with the live page at the folded slug that records a file (at most `LEGACY_TWINS_LIMIT` pairs and decisions). `pairVerdict` lists a pair as a decision (never merged) for differing `content_hash`, several legacy candidates, a twin file `liveFileDrift` does not call `agrees`, a file at the twin's own slug path, twin withdrawals, a legacy `file:` URI or a twin slug outside the op grammar. The preview binds pairs to the owner (host, worktree, owner epoch, incarnation) and both pages' ids, slugs and revisions; the apply refuses `not_owner_host`, `legacy_twins_storage_unknown`, `preview_changed` and `legacy_twin_mass_merge_refused` (`massTwins`, the sync valve). Each pair re-checks with `pairNow`, then a managed brain submits one `managed_maintenance_merge_legacy_twin` request on the twin (`prepareLegacyTwinMerge`, dispatched from `prepared-maintenance.ts`: no file target, `databaseOnlyReason: 'shared_origin'`, the legacy key in `additionalPageKeys`, `pairLocked` under the publication locks); an unmanaged brain merges in `maintenanceTransaction` under both page locks. `applyTwinMerge` records the twin's `source_path` on the legacy page, clears the twin's origin (so its tombstone's retention purge is database-only, never a `shared_origin` refusal), moves links (deduplicated; pair links stay), timeline rows, raw data, attachments, page aliases and facts about the twin, records the twin slug as a `slug_aliases` row, versions and soft-deletes the twin, and moves the twin's `sync-import-provenance` record to the legacy page at its post-write revision. Outcomes `merged`, `changed_since_preview`. Tests: `test/repair-legacy-twins-6885.test.ts` (Postgres: `test/e2e/repair-legacy-twins-6885-postgres.test.ts`).
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 291aac9748..b82138ca89 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -2450,6 +2450,15 @@ the two `--prefer` values do opposite things in each state.
| `purged_differs` | Removes the file. | Imports the file as a new page. |
| `file_gone` | Recreates the file from the page. | Soft-deletes the page (the mass-delete valve applies). |
+A held page whose page and file agree now is listed `release_hold` under
+either `--prefer`: its apply writes nothing to the page or the file, and only
+asks the next sync to re-screen the file, which releases the hold. A page with
+no recorded file origin (no source path, and a source URI that is not a
+`file:` URI) is compared with, and adopts, the file at its slug path, spelled
+as sync imports it (`README.md` for slug `readme`); the apply records that
+path. A sync re-screens a held page that changed since it was held even when
+Git did not move.
+
A held preview covers one window of the selected holds, in held-path order:
at most 200 pages, and it starts no page after 60 seconds of work (each page
reads the database a few dozen times, so a large held set against a remote
diff --git a/src/core/persistence/drift-conflicts.ts b/src/core/persistence/drift-conflicts.ts
index 9fbeba4b52..256422ea5c 100644
--- a/src/core/persistence/drift-conflicts.ts
+++ b/src/core/persistence/drift-conflicts.ts
@@ -39,6 +39,7 @@ import { prepareFileTarget } from './page-prepare.ts';
import { readReconcileState } from './reconcile-state.ts';
import { reconcileCanonical } from './reconcile-merge.ts';
import { classifyDrift } from './reconcile-additive.ts';
+import { recordsNoFileOrigin, slugPathFile } from './unbound-pages.ts';
/** The refusal message `prepareFileTarget` stores on a drift conflict receipt (the detail is not kept on the row). */
export const FILE_DRIFT_MESSAGE = 'The canonical file contains an uncoordinated local edit.';
@@ -105,7 +106,7 @@ export async function liveFileDrift(engine: BrainEngine, sourceId: string, slug:
async function canonicalFilePath(engine: BrainEngine, sourceId: string, root: string, snapshot: PageSnapshot, slug: string): Promise<string> {
const mode = snapshot.page.source_path ? await scannerSlugRootMode(engine, sourceId, root) : undefined;
const captured = recordedPathFromFileUri(snapshot.page.source_uri, root);
- return resolveSourceLocalFilePath(root, snapshot.page.source_path, slug, mode) ?? (captured ? join(root, captured) : join(root, `${slug}.md`));
+ return resolveSourceLocalFilePath(root, snapshot.page.source_path, slug, mode) ?? (captured ? join(root, captured) : slugPathFile(root, slug));
}
/** Whether Git tracks the canonical file and whether its bytes equal the last commit (null: Git cannot say). */
@@ -279,7 +280,7 @@ export async function auditDriftConflicts(engine: BrainEngine, sourceId: string,
if (live.path) { result.path = live.path; result.git = gitState(root, live.path); }
if (live.still_present) {
report.totals.still_present++;
- result.class = await driftClass(engine, sourceId, row.slug, !page?.source_path && !page?.source_uri);
+ result.class = await driftClass(engine, sourceId, row.slug, !!page && recordsNoFileOrigin(page));
}
}
}
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index c63a70de7d..21eb4f296c 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -45,6 +45,7 @@ import type { PreparedContentImport } from './prepared-import.ts';
import type { PreparedMutation } from './coordinator.ts';
import type { SqlEngine, WriteRequest } from './model.ts';
import { isUnboundSourcePage } from './unbound-source.ts';
+import { slugPathFile } from './unbound-pages.ts';
import { isOriginTwinPage } from './origin-twins.ts';
import { sealImportedPage, sealPageTextProjection } from '../page-state/projections.ts';
import { materializedSnapshot, sealSegmentedPage } from './segmented-apply.ts';
@@ -288,7 +289,7 @@ export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequ
const recordedPath = snapshot?.page.source_path || snapshot?.page.withheld_source_path || null;
const mode = recordedPath ? await scannerSlugRootMode(engine, row.source_id, root) : undefined;
const candidate = resolveSourceLocalFilePath(root, recordedPath, row.slug, mode)
- ?? (capturedPath ? join(root, capturedPath) : join(root, `${row.slug}.md`));
+ ?? (capturedPath ? join(root, capturedPath) : snapshot ? slugPathFile(root, row.slug) : join(root, `${row.slug}.md`));
if (isWindowsColonTarget(relative(root, candidate))) {
if (!options.allowMissing && publishesDatabaseOnly(root, row.slug, snapshot)) return undefined;
throw colonSlugWindowsRefusal(row.slug, row.source_id);
diff --git a/src/core/persistence/reconcile-state.ts b/src/core/persistence/reconcile-state.ts
index 80776ef521..2b9b12e4ac 100644
--- a/src/core/persistence/reconcile-state.ts
+++ b/src/core/persistence/reconcile-state.ts
@@ -17,7 +17,7 @@ import { sharedOriginExit } from './sync-origin.ts';
import { originTwinsPreviewArgv } from './origin-twins.ts';
export { fileClaimCandidatesQuery } from './file-claims.ts';
import { localHostId } from './identity.ts';
-import { isDatabaseOnlyPage, slugDerivedOrigin } from './unbound-pages.ts';
+import { isDatabaseOnlyPage, recordsNoFileOrigin, slugDerivedOrigin } from './unbound-pages.ts';
import { isUnboundSourcePage } from './unbound-source.ts';
import { getWorktreeBinding, type WorktreeBinding } from './ownership.ts';
import { digest, gitBlobOid, requireUuid, sha256, stableJson } from './digest.ts';
@@ -238,13 +238,13 @@ export async function readReconcileState(engine: BrainEngine, sourceId: string,
const recordedPath = recordedReconcilePath(root, snapshot.page, mode);
const marked = !recordedPath && isDatabaseOnlyPage({ ...snapshot.page,
database_only_reason: await isUnboundSourcePage(engine, sourceId, slug) ? 'unbound_source' : null });
- const adoptable = !recordedPath && !marked && opts.adoptSlugPath === true && !snapshot.page.source_uri
+ const adoptable = !recordedPath && !marked && opts.adoptSlugPath === true && recordsNoFileOrigin(snapshot.page)
&& !publishesDatabaseOnly(root, slug, snapshot) && !await isMirrorOnlyPage(engine, sourceId, slug);
const derived = marked || adoptable ? slugDerivedOrigin(root, slug, mode) : null;
const origin = derived ? 'slug_derived' : 'recorded';
const path = recordedPath ?? derived?.path ?? null;
if (!path || !isWriteTargetContained(path, root)) throw opError('source_changed', 'The page has no unambiguous confined recorded Markdown origin.',
- `Page ${slug} in '${sourceId}' records no Markdown file inside the source checkout, so there is nothing to reconcile it against; nothing changed. ${!recordedPath && !marked && !snapshot.page.source_uri && opts.adoptSlugPath !== true
+ `Page ${slug} in '${sourceId}' records no Markdown file inside the source checkout, so there is nothing to reconcile it against; nothing changed. ${!recordedPath && !marked && recordsNoFileOrigin(snapshot.page) && opts.adoptSlugPath !== true
? `If the file at its slug path is this page's canonical file, preview again with --adopt-slug-path (gbrain sources reconcile ${sourceId} ${slug} --preview --adopt-slug-path) to adopt it; otherwise check its recorded source path with the command in fix.` : 'Check its recorded source path with the command in fix.'}`,
{ fix: readFix('Shows the page and its recorded source path.', { argv: ['gbrain', 'get', '--source', sourceId, '--', slug] }) });
let size: number;
@@ -312,7 +312,7 @@ async function reconcilePins(engine: BrainEngine, input: { brain_id: string; sou
/** #6394: a preview made with --adopt-slug-path recorded a page with no origin; apply and publication adopt the same pinned file. */
export function reconcilePreviewAdopts(artifact: Pick<ReconcileArtifact, 'preimages'>): boolean {
const stored = (artifact.preimages as { stored_page?: { source_path?: unknown; source_uri?: unknown } | null } | null)?.stored_page;
- return stored != null && stored.source_path == null && stored.source_uri == null;
+ return stored != null && stored.source_path == null && recordsNoFileOrigin({ source_uri: typeof stored.source_uri === 'string' ? stored.source_uri : null });
}
export function assertReconcilePins(expected: ReconcilePins, actual: ReconcilePins): void {
for (const key of Object.keys(expected) as Array<keyof ReconcilePins>) if (expected[key] !== actual[key]) staleReconcile(key);
diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.ts
index 1bbfcd8d3a..59ce7f8cd6 100644
--- a/src/core/persistence/sync-pass-run.ts
+++ b/src/core/persistence/sync-pass-run.ts
@@ -42,6 +42,7 @@ import { assertDrainLease, currentDrainLease } from './sync-lease.ts';
import { idleClear, readIdleFacts } from './sync-idle-skips.ts';
import { digest } from './digest.ts';
import { readSyncTail } from './sync-tail-record.ts';
+import { movedDriftHolds } from './sync-prescreen.ts';
import { clearGitHold, clearGitHoldRetryPaths, holdRescreenDue, readGitHoldRetryPaths, readSyncHoldPolicy, readGitSourceHolds, readSyncImportProvenances, settledDeletionHolds, syncImportParserFor } from './sync-holds.ts';
import { loadActivePackForEngine } from '../schema-pack/engine-resolution.ts';
import { loadConfig } from '../config.ts';
@@ -425,6 +426,8 @@ async function pinPass(engine: BrainEngine, input: SyncPassInput, lease: NonNull
const converged = obligations.converged;
const probe = converged ? rowProbe : null;
const holds = (sourceHolds[0]?.holds ?? []).filter(hold => hold.incarnation === incarnation);
+ // GBRA-133: a file_drift hold whose page moved since it was held is re-screened even when Git did not move.
+ const driftMoved = (await movedDriftHolds(engine, sourceId, holds)).size > 0;
// Working mode (design §2.2): the stat cache this process kept from the round its last stamp used; a cold process has none.
const cacheKey = passFingerprint(sourceId, incarnation);
const kindStarted = Date.now();
@@ -437,7 +440,7 @@ async function pinPass(engine: BrainEngine, input: SyncPassInput, lease: NonNull
head, parserFp, pack, selectionFp, now: started, openEpisode: !!episode, owedTail: tail !== null, retryRow: retry.length > 0,
notConvergedStreak: obligations.not_converged_streak, mismatchStreak: Object.keys(obligations.mismatch).length,
requestNewer: probe?.newer === true, openAtStampFinished: !!converged && (converged.open_at_stamp === null || (probe?.stillOpen ?? 0) < converged.open_at_stamp.length),
- writebackOpen: probe?.writebackOpen === true, workingChange: working.changed, rescreenDueHold: holds.some(hold => holdRescreenDue(hold, retry.includes(hold.path))), full: opts.full === true, fullRound: opts.fullRound === true });
+ writebackOpen: probe?.writebackOpen === true, workingChange: working.changed, rescreenDueHold: driftMoved || holds.some(hold => holdRescreenDue(hold, retry.includes(hold.path))), full: opts.full === true, fullRound: opts.fullRound === true });
// Design §2.6: a withheld mass delete is applied by a full round once the owner host's env valve allows it.
const valveOpen = !remote && !!obligations.deletes_withheld && massReconcileAllowed();
// Design §4: keep_db writes the previous pass deferred (`keep_db_pending`: its cap, or write capacity) are owed to this pass, so it is
diff --git a/src/core/persistence/unbound-pages.ts b/src/core/persistence/unbound-pages.ts
index 61f5b19166..71bbde104e 100644
--- a/src/core/persistence/unbound-pages.ts
+++ b/src/core/persistence/unbound-pages.ts
@@ -11,7 +11,7 @@
* stamped in the publication transaction), so an ordinary page that merely
* lacks a recorded origin is never matched to a slug-derived file.
*/
-import { readdirSync, type Dirent } from 'node:fs';
+import { existsSync, readdirSync, type Dirent } from 'node:fs';
import { basename, isAbsolute, join, relative, resolve, sep } from 'node:path';
import { resolveSourceLocalFilePath } from '../markdown.ts';
import { opError } from '../ops/contract.ts';
@@ -66,6 +66,22 @@ export function slugDerivedOrigin(root: string, slug: string, mode: 'git-root' |
return matches[0] ?? { path, sourcePath };
}
+/** GBRA-133: whether a page records no file origin: no source path and no `file:` source URI (a URL or a capture label names no file). */
+export function recordsNoFileOrigin(page: { source_path?: string | null; source_uri?: string | null }): boolean {
+ return !page.source_path && !/^file:/i.test(page.source_uri?.trim() ?? '');
+}
+
+/**
+ * GBRA-133: the file at a page's slug path (source-root relative). When `<slug>.md` is absent, the one file whose path
+ * imports as the slug in another spelling (`README.md` for slug `readme`) is that file, as discovery names it.
+ */
+export function slugPathFile(root: string, slug: string): string {
+ const exact = join(root, `${slug}.md`);
+ if (existsSync(exact)) return exact;
+ const derived = slugDerivedOrigin(root, slug, 'source-root');
+ return derived && existsSync(derived.path) ? derived.path : exact;
+}
+
function entries(dir: string): Dirent[] {
try { return readdirSync(dir, { withFileTypes: true }); } catch { return []; }
}
diff --git a/src/core/repair/file-drift.ts b/src/core/repair/file-drift.ts
index 7b5fc1749e..13b4e6d1ef 100644
--- a/src/core/repair/file-drift.ts
+++ b/src/core/repair/file-drift.ts
@@ -72,7 +72,7 @@ import { canonicalFilesystemPath } from '../persistence/root-registry.ts';
import { auditDriftConflicts, DRIFT_CLASSES, driftClass, liveFileDrift, type DriftClass } from '../persistence/drift-conflicts.ts';
import { protectedReconcileKey, reconcileCanonical, RECONCILE_SCAN_KEYS, type ReconcileDecision } from '../persistence/reconcile-merge.ts';
import { ABSENT_FILE_HASH, canonicalDeletionState, missingFileRoute, readDeletedDriftTarget, readReconcileState, type DeletedDriftChange, type DeletedDriftTarget, type ReconcileArtifact } from '../persistence/reconcile-state.ts';
-import { clearGitHold, fileDriftActionVerb, fileDriftSide, FILE_DRIFT_DELETED_STATES, FILE_DRIFT_SIDES, GIT_HOLD_OP, heldDriftPreviewArgv, type FileDriftDeletedState, type FileDriftSide, type GitHoldRecord } from '../persistence/sync-holds.ts';
+import { clearGitHold, fileDriftActionVerb, fileDriftSide, FILE_DRIFT_DELETED_STATES, FILE_DRIFT_SIDES, GIT_HOLD_OP, heldDriftPreviewArgv, requestGitHoldRetry, type FileDriftDeletedState, type FileDriftSide, type GitHoldRecord } from '../persistence/sync-holds.ts';
import { prepareRepairPublication, repairScreenConfig, submitManagedFileRepair } from '../persistence/file-repair.ts';
import { maintenancePreflight, submitDatabaseMaintenanceIntent, submitMaintenanceIntent } from '../persistence/prepared-maintenance.ts';
import type { PreparedMutation } from '../persistence/coordinator.ts';
@@ -90,6 +90,7 @@ import { canonicalOriginPage, originConflictMessage, originTwinsFix } from '../p
import { assertReconcileOutputPath, assertReconcileSize } from '../persistence/reconcile-backup.ts';
import { authorizeReconcile, runReconcileApply } from '../persistence/reconcile.ts';
import { acceptedPendingReceipt } from '../persistence/accepted-pending.ts';
+import { recordsNoFileOrigin } from '../persistence/unbound-pages.ts';
import { afterCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairPlanOptions, type RepairScope } from './core.ts';
export type DriftSide = 'file' | 'database';
@@ -120,7 +121,10 @@ export interface ImportFilePage { slug: string; prefer: 'file'; exceptions: Drif
*/
export interface DetachPin { path: string; page_id: number; revision: string; observed_at: string }
export interface DetachPage { slug: string; prefer: 'database'; exceptions: DriftException[]; detach_page: DetachPin }
-type PlannedPage = ArtifactPage | SoftDeletePage | RemoveFilePage | ImportFilePage | DetachPage;
+/** GBRA-133: a held page whose page and file agree now; the apply asks the next sync to re-screen (and so release) its hold. */
+export interface ReleasePin { path: string; incarnation: string; revision: string; file_hash: string | null }
+export interface ReleasePage { slug: string; prefer: DriftSide; exceptions: DriftException[]; release_hold: ReleasePin }
+type PlannedPage = ArtifactPage | SoftDeletePage | RemoveFilePage | ImportFilePage | DetachPage | ReleasePage;
/** #6712 PR 4b: one held `file_drift` page a `--held` selection resolves. */
interface HeldTarget { hold: GitHoldRecord; side: FileDriftSide; state?: FileDriftDeletedState; provenance?: DeletionProvenance }
@@ -482,7 +486,7 @@ export async function prepareDriftPage(engine: BrainEngine, sourceId: string, sl
opts: { fileGone?: boolean } = {}): Promise<ArtifactPage> {
const snapshotRow = await engine.readPageSnapshot(slug, { sourceId });
if (snapshotRow?.page.source_path) await refuseForeignOrigin(engine, sourceId, slug, snapshotRow.page.source_path);
- const adopt = !opts.fileGone && !!snapshotRow && !snapshotRow.page.source_path && !snapshotRow.page.source_uri;
+ const adopt = !opts.fileGone && !!snapshotRow && recordsNoFileOrigin(snapshotRow.page);
const state = await readReconcileState(engine, sourceId, slug, assessmentAt, { adoptSlugPath: adopt, ...(opts.fileGone ? { fileGone: true } : {}) });
if (opts.fileGone && state.pins.raw_file_hash !== ABSENT_FILE_HASH) throw opError('source_changed', 'The canonical file reappeared during the preview.',
`Nothing was written. The canonical file of ${slug} in '${sourceId}' exists again; preview the page again.`);
@@ -663,6 +667,17 @@ async function applyDeletedSide(ctx: OperationContext, page: ApprovedPage, artif
}
}
+/** GBRA-133: re-checks a held page whose page and file agreed at the preview and schedules its re-screen (`sources retry-held` for one path). */
+async function releaseAgreedHold(engine: BrainEngine, page: ApprovedPage, pin: ReleasePin, requestId: string): Promise<RepairItemOutcome> {
+ const live = await liveFileDrift(engine, page.source_id, page.slug);
+ if (live.reason !== 'agrees' || live.db_revision !== pin.revision || (live.file_hash ?? null) !== pin.file_hash) {
+ return { applied: false, outcome: 'changed_since_preview', reason: 'revision_conflict',
+ detail: { request_id: requestId, action: 'release_hold', message: `The page or ${pin.path} changed since the preview (${live.reason}); preview it again.` } };
+ }
+ await requestGitHoldRetry(engine, page.source_id, pin.incarnation, [pin.path]);
+ return { applied: true, outcome: 'repaired', detail: { request_id: requestId, action: 'release_hold', path: pin.path } };
+}
+
/** GBRA-133: one held gone file's provenance, as the preview lists it. */
function provenanceText(found: DeletionProvenance): string {
if (found.kind === 'deleted_by_commit') return `deleted by commit ${found.commit.slice(0, 12)} (${found.date}, ${found.author}: ${found.subject})`;
@@ -764,6 +779,11 @@ export const fileDriftRepair: RepairHandler = {
continue;
}
if (!opts.allDrifted && !opts.held && !selectedByGlobs(live.path, opts)) { count('not_selected'); continue; }
+ if (target && live.reason === 'agrees' && live.db_revision) {
+ pages.push({ slug, prefer: opts.prefer, exceptions: [], release_hold: { path: target.hold.path, incarnation: target.hold.incarnation, revision: live.db_revision, file_hash: live.file_hash ?? null } });
+ listing.push({ item: `${sourceId}:${slug}`, class: 'release_hold', detail: 'the page and its file agree now; the apply asks the next sync to re-screen the file, which releases the hold' });
+ continue;
+ }
if (live.still_present !== true) {
count(live.still_present === false ? 'no_drift' : `unknown_${live.reason}`);
listing.push({ item: `${sourceId}:${slug}`, class: live.still_present === false ? 'no_drift' : 'unknown', detail: live.reason });
@@ -787,7 +807,8 @@ export const fileDriftRepair: RepairHandler = {
const nextCommand = nextCursor ? previewCommand(sourceId, { ...opts, cursor: nextCursor }) : undefined;
if (remaining > 0) residuals.after_window = remaining;
const hash = previewHash({ kind: 'file-drift-v1', brain_id: scope.brain_id, source_id: sourceId, selection,
- pages: pages.map(page => 'soft_delete' in page ? [page.slug, page.soft_delete.ghost.revision, ABSENT_FILE_HASH, 'soft_delete']
+ pages: pages.map(page => 'release_hold' in page ? [page.slug, page.release_hold.revision, page.release_hold.file_hash, 'release_hold', page.release_hold.path]
+ : 'soft_delete' in page ? [page.slug, page.soft_delete.ghost.revision, ABSENT_FILE_HASH, 'soft_delete']
: 'detach_page' in page ? [page.slug, page.detach_page.revision, ABSENT_FILE_HASH, 'detach_page', page.detach_page.page_id, page.detach_page.observed_at]
: 'remove_file' in page ? [page.slug, page.remove_file.revision, page.remove_file.raw_file_hash, 'remove_file', page.remove_file.state, page.remove_file.marker_digest]
: 'import_file' in page ? [page.slug, page.import_file.revision, page.import_file.raw_file_hash, page.import_file.result_digest, page.import_file.state, page.import_file.marker_digest]
@@ -798,6 +819,8 @@ export const fileDriftRepair: RepairHandler = {
const removed = pages.flatMap(page => 'remove_file' in page ? [page.remove_file.path] : []);
let warnings: string[] = nextCommand ? [`This preview covered ${previewed} of the ${held!.targets.length} selected held pages${opts.cursor ? ' after its cursor' : ''} (one window stops at ${HELD_WINDOW_PAGES} pages or ${HELD_WINDOW_BUDGET_MS / 1000} s); its hash and apply command cover only these. `
+ `After applying this window (or deciding not to), preview the next one: ${nextCommand}`] : [];
+ const releases = pages.filter(page => 'release_hold' in page).length;
+ if (releases) warnings.push(`The apply only schedules a re-screen of ${releases} held file(s) whose page and file agree; the next sync (gbrain sync --source ${sourceId}) releases each that still agrees.`);
let undoneBySync: { recreated: number; removed: number } | null = null;
if (recreated.length || removed.length) {
const binding = await getWorktreeBinding(engine, sourceId);
@@ -826,7 +849,8 @@ export const fileDriftRepair: RepairHandler = {
...(undoneBySync ? { undone_by_next_sync_unless_committed: undoneBySync } : {}),
...(held ? { window: { previewed, remaining, complete: remaining === 0, ...(nextCursor ? { next_cursor: nextCursor, next_command: nextCommand } : {}) } } : {}),
...(held?.provenance ? { provenance: held.provenance } : {}),
- pages: pages.map(page => ({ ...('soft_delete' in page ? { slug: page.slug, action: 'soft_delete', path: page.soft_delete.ghost.path, verb: fileDriftActionVerb('deleted', 'file_gone', 'file'), exceptions: page.exceptions }
+ pages: pages.map(page => ({ ...('release_hold' in page ? { slug: page.slug, action: 'release_hold', path: page.release_hold.path, verb: 're-screen the held file (the page and the file agree)', exceptions: page.exceptions }
+ : 'soft_delete' in page ? { slug: page.slug, action: 'soft_delete', path: page.soft_delete.ghost.path, verb: fileDriftActionVerb('deleted', 'file_gone', 'file'), exceptions: page.exceptions }
: 'detach_page' in page ? { slug: page.slug, action: 'detach_page', path: page.detach_page.path, verb: 'keep the page database-only (no file)', exceptions: page.exceptions }
: 'remove_file' in page ? { slug: page.slug, action: 'remove_file', state: page.remove_file.state, path: page.remove_file.path, verb: fileDriftActionVerb('deleted', page.remove_file.state, 'database'), exceptions: page.exceptions }
: 'import_file' in page ? { slug: page.slug, action: 'import_file', state: page.import_file.state, path: page.import_file.path, verb: fileDriftActionVerb('deleted', page.import_file.state, 'file'), exceptions: page.exceptions, result_digest: page.import_file.result_digest }
@@ -843,7 +867,8 @@ export const fileDriftRepair: RepairHandler = {
if (!artifact || digest(artifact) !== page.artifact_digest) throw previewChangedError(opts?.expect ?? hash, command);
const requestId = requestIdFor(hash, page);
let outcome: RepairItemOutcome;
- if ('remove_file' in artifact || 'import_file' in artifact || 'detach_page' in artifact) outcome = await applyDeletedSide(ctx, page, artifact, requestId, opts?.embed !== false);
+ if ('release_hold' in artifact) outcome = await releaseAgreedHold(ctx.engine, page, artifact.release_hold, requestId);
+ else if ('remove_file' in artifact || 'import_file' in artifact || 'detach_page' in artifact) outcome = await applyDeletedSide(ctx, page, artifact, requestId, opts?.embed !== false);
else if ('soft_delete' in artifact) {
const retired = await retireGhost(ctx, artifact.soft_delete.ghost, artifact.soft_delete.owner, async () => requestId);
outcome = retired.applied ? { applied: true, outcome: 'repaired', detail: { request_id: requestId, prefer: 'file', action: 'soft_delete' } }
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 3ddc103718..3d4268cb2f 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -477,6 +477,7 @@ test/sync-full-untracked-import-5459.test.ts
test/sync-group-member-order.test.ts
test/sync-handler-drain-6706.test.ts
test/sync-holds-only-converge-7327.test.ts
+test/sync-holds-wave-gbra133.test.ts
test/sync-import-provenance-disk.test.ts
test/sync-inexact-rename-6729.test.ts
test/sync-landing-gaps.test.ts
diff --git a/test/sync-holds-wave-gbra133.test.ts b/test/sync-holds-wave-gbra133.test.ts
new file mode 100644
index 0000000000..1cb1b9c39a
--- /dev/null
+++ b/test/sync-holds-wave-gbra133.test.ts
@@ -0,0 +1,141 @@
+/**
+ * GBRA-133 sync-holds wave: three `file_drift` hold shapes no command could resolve.
+ *
+ * 1. A page with no file origin (no source path; its source URI is a URL, not a `file:` URI) whose file appeared at its
+ * slug path: both previews refused (no recorded origin), because a source URI of any kind blocked adopting the slug path.
+ * File wins now adopts the file and records its path, and the next sync releases the hold.
+ * 2. A page with no recorded origin whose slug-path file is spelled differently (`README.md` for slug `projects/readme`): the
+ * previews looked for `projects/readme.md`, called the file gone, and a write would have created that second spelling.
+ * The slug path now resolves to the file discovery imports as the slug.
+ * 3. A hold whose page and file agree now stayed held: a sync with no new commit did not re-screen a hold whose page moved,
+ * and nothing re-screened one whose page did not move. Such a sync re-screens it now, and the `--held` preview lists an
+ * agreeing hold as `release_hold`, whose apply schedules its re-screen. A hold that still differs stays held.
+ *
+ * Holds exist only where sync imports a Git checkout, so there is no repo-less arm.
+ */
+import { expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, readdirSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
+import { registerLocalWriter, withVerifiedLocalRegistration } from '../src/core/persistence/identity.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { resolveRepairScope } from '../src/core/repair/core.ts';
+import { repairRunner } from '../src/core/repair/registry.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
+
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, '-c', 'user.name=Example', '-c', '[email protected]',
+ '-c', 'commit.gpgsign=false', ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const note = (slug: string, body: string) => `---\ntype: concept\ntitle: ${slug}\n---\n\n${body}\n`;
+const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };
+const logger = { info() {}, warn() {}, error() {} };
+
+const coordinated = (engine: BrainEngine, sql: string, params: unknown[] = []) =>
+ engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw(sql, params), TEST_WRITE_ATTRIBUTION));
+const holds = async (engine: BrainEngine) => (await engine.executeRaw<{ r: { path: string; code: string; meta: { side?: string } } }>(
+ "SELECT completed_keys->0 AS r FROM op_checkpoints WHERE op='sync-hold' ORDER BY fingerprint")).map(({ r }) => `${r.path} ${r.code} ${r.meta.side ?? ''}`.trim());
+const origin = async (engine: BrainEngine, slug: string) => (await engine.executeRaw<{ source_path: string | null; source_uri: string | null }>(
+ "SELECT source_path, source_uri FROM pages WHERE source_id='default' AND slug=$1", [slug]))[0];
+const commitAll = (root: string, message: string) => { git(root, 'add', '-A'); git(root, 'commit', '-qm', message); };
+
+async function heldPreview(engine: BrainEngine, prefer: 'file' | 'database', expectHash?: string) {
+ return withVerifiedLocalRegistration(engine, await registerLocalWriter(engine, 'cli'), async () =>
+ (await repairRunner(engine, { apply: expectHash !== undefined, logger })).run('file-drift', await resolveRepairScope(engine, 'default'),
+ { explicit: true, sourceFlag: 'default', held: true, side: 'unknown', prefer, ...(expectHash ? { expect: expectHash } : {}) }));
+}
+const listing = (plan: Awaited<ReturnType<typeof heldPreview>>) => (plan as { listing?: Array<{ item: string; class: string }> }).listing?.map(row => `${row.item} ${row.class}`);
+
+/** A page written straight to the database at a slug no file holds yet: no source path, an optional non-file source URI. */
+async function stubPage(engine: BrainEngine, slug: string, sourceUri: string | null): Promise<void> {
+ await coordinated(engine, `INSERT INTO pages(source_id, slug, type, title, compiled_truth, timeline, frontmatter, source_uri)
+ VALUES('default', $1, 'concept', $1, 'A stub.', '', '{}'::jsonb, $2)`, [slug, sourceUri]);
+}
+
+/** notes/n0 as an older gbrain left it (imported, then its origin and write request forgotten), with a stub body, then a commit edits its file. */
+async function heldUnknownPage(engine: BrainEngine, root: string): Promise<void> {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ await coordinated(engine, `DELETE FROM op_checkpoints WHERE op='sync-import-provenance'
+ AND completed_keys->0->>'page_id' IN (SELECT id::text FROM pages WHERE source_id='default' AND slug='notes/n0')`);
+ await coordinated(engine, `UPDATE pages SET source_path=NULL, compiled_truth='A stub.', knowledge_revision=$1::uuid, revision_write_request_id=NULL
+ WHERE source_id='default' AND slug='notes/n0'`, [randomUUID()]);
+ writeFileSync(join(root, 'notes/n0.md'), note('notes/n0', 'The edited body of notes/n0.')); commitAll(root, 'edit n0');
+ await performManagedSync(engine, OPTS);
+ expect(await holds(engine)).toEqual(['notes/n0.md file_drift unknown']);
+}
+
+for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+ const setup = ({ root }: { root: string }) => {
+ mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');
+ for (const slug of ['notes/n0', 'notes/n1']) writeFileSync(join(root, `${slug}.md`), note(slug, `The committed body of ${slug}.`));
+ commitAll(root, 'notes');
+ };
+
+ test(`GBRA-133 [${backend}]: file wins adopts the slug-path file of a page whose source URI names no file, records its path, and the next sync releases the hold`, () => managedBrain(async ({ engine, root }) => {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ await stubPage(engine, 'people/alice-example', 'https://example.invalid/post/1');
+ mkdirSync(join(root, 'people'), { recursive: true });
+ writeFileSync(join(root, 'people/alice-example.md'), note('people/alice-example', 'The full page of people/alice-example.')); commitAll(root, 'add alice');
+ await performManagedSync(engine, OPTS);
+ expect(await holds(engine)).toEqual(['people/alice-example.md file_drift unknown']);
+ expect(listing(await heldPreview(engine, 'database'))).toEqual(['default:people/alice-example prefer_database']);
+ const preview = await heldPreview(engine, 'file');
+ expect(listing(preview)).toEqual(['default:people/alice-example prefer_file']);
+ expect(preview.details!.pages).toEqual([expect.objectContaining({ slug: 'people/alice-example', adopt_slug_path: true })]);
+ expect((await heldPreview(engine, 'file', preview.preview_hash!)).outcomes).toEqual({ repaired: 1 });
+ expect(await origin(engine, 'people/alice-example')).toEqual({ source_path: 'people/alice-example.md', source_uri: 'https://example.invalid/post/1' });
+ await performManagedSync(engine, OPTS);
+ expect(await holds(engine)).toEqual([]);
+ }, { databaseUrl, setup }), 180_000);
+
+ test(`GBRA-133 [${backend}]: a no-origin page's slug path resolves to the file spelled README.md, so file wins adopts it and writes no second spelling`, () => managedBrain(async ({ engine, root }) => {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ await stubPage(engine, 'projects/readme', null);
+ mkdirSync(join(root, 'projects'), { recursive: true });
+ writeFileSync(join(root, 'projects/README.md'), note('Projects', 'The projects index.')); commitAll(root, 'add readme');
+ await performManagedSync(engine, OPTS);
+ expect(await holds(engine)).toEqual(['projects/README.md file_drift unknown']);
+ expect(listing(await heldPreview(engine, 'database'))).toEqual(['default:projects/readme prefer_database']);
+ const preview = await heldPreview(engine, 'file');
+ expect(listing(preview)).toEqual(['default:projects/readme prefer_file']);
+ expect((await heldPreview(engine, 'file', preview.preview_hash!)).outcomes).toEqual({ repaired: 1 });
+ expect((await origin(engine, 'projects/readme'))?.source_path).toBe('projects/README.md');
+ expect(readdirSync(join(root, 'projects'))).toEqual(['README.md']);
+ await performManagedSync(engine, OPTS);
+ expect(await holds(engine)).toEqual([]);
+ }, { databaseUrl, setup }), 180_000);
+
+ test(`GBRA-133 [${backend}]: a sync with no new commit re-screens a held page that moved: one that agrees now is released, one that still differs stays held`, () => managedBrain(async ({ engine, root }) => {
+ await heldUnknownPage(engine, root);
+ await coordinated(engine, "UPDATE pages SET compiled_truth='Another database edit.' WHERE source_id='default' AND slug='notes/n0'");
+ await performManagedSync(engine, OPTS);
+ expect(await holds(engine)).toEqual(['notes/n0.md file_drift unknown']);
+ expect(listing(await heldPreview(engine, 'file'))).toEqual(['default:notes/n0 prefer_file']);
+ await coordinated(engine, "UPDATE pages SET compiled_truth='The edited body of notes/n0.' WHERE source_id='default' AND slug='notes/n0'");
+ await performManagedSync(engine, OPTS);
+ expect(await holds(engine)).toEqual([]);
+ expect((await origin(engine, 'notes/n0'))?.source_path).toBe('notes/n0.md');
+ }, { databaseUrl, setup }), 180_000);
+
+ test(`GBRA-133 [${backend}]: the --held preview lists a hold whose page and file agree as release_hold, and its apply makes the next sync release it`, () => managedBrain(async ({ engine, root }) => {
+ await heldUnknownPage(engine, root);
+ await coordinated(engine, "UPDATE pages SET compiled_truth='The edited body of notes/n0.' WHERE source_id='default' AND slug='notes/n0'");
+ // The hold as a screen that recorded the page at its current revision left it: nothing moved since, so no sync re-screens it.
+ const [{ revision }] = await engine.executeRaw<{ revision: string }>("SELECT knowledge_revision::text AS revision FROM pages WHERE source_id='default' AND slug='notes/n0'");
+ await engine.executeRaw("UPDATE op_checkpoints SET completed_keys=jsonb_set(completed_keys, '{0,meta,page_revision}', to_jsonb($1::text)) WHERE op='sync-hold'", [revision]);
+ await performManagedSync(engine, OPTS);
+ expect(await holds(engine)).toEqual(['notes/n0.md file_drift unknown']);
+ const preview = await heldPreview(engine, 'file');
+ expect(listing(preview)).toEqual(['default:notes/n0 release_hold']);
+ expect(preview.details!.pages).toEqual([expect.objectContaining({ slug: 'notes/n0', action: 'release_hold', path: 'notes/n0.md' })]);
+ expect((await heldPreview(engine, 'file', preview.preview_hash!)).outcomes).toEqual({ repaired: 1 });
+ expect(await holds(engine)).toEqual(['notes/n0.md file_drift unknown']);
+ await performManagedSync(engine, OPTS);
+ expect(await holds(engine)).toEqual([]);
+ expect((await origin(engine, 'notes/n0'))?.source_path).toBe('notes/n0.md');
+ }, { databaseUrl, setup }), 180_000);
+}