Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): Windows file-claim census binds only what it references (#6659)
time-attack0ead37abaa49
diff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.mdindex 0734b58aae..38fd5fdf81 100644--- a/docs/architecture/key-files/canonical-reconciliation.md+++ b/docs/architecture/key-files/canonical-reconciliation.md@@ -2,7 +2,7 @@- `src/commands/sync-diagnostics.ts` + `src/core/persistence/{sync-run,verb-errors}.ts` — bounded source/slug/path/reason diagnostics derive from immutable managed-sync receipts, including when the local failure ledger is unavailable. Direct and resident-owner JSON carry the same receipt; human memory errors lead with the specific write reason without widening frozen v1 error codes. Pending requests retain their original UUID, terminal corrections require a new UUID, and neither retry nor line-ending diagnostics bypasses raw-byte or skip guards.-- `src/core/persistence/reconcile*.ts` — trusted-local exact-page reconciliation: loss-preserving semantic preview, explicit JSON Pointer choices, pinned identity/revision/raw-file/policy checks, durable private preimages and same-ID replay through the existing coordinator. Normal overwrite protection stays unchanged. The bounded audit reports source-scoped drift without repair or checkpoint changes; a database-only page (`isDatabaseOnlyPage`, with no file at its slug-derived path) counts as `database_only` with no reconcile suggestion, never as drift, while a legacy row that merely lacks `source_path` is audited as usual. `src/commands/source-reconcile.ts` provides strict CLI parsing, private artifact I/O, brain routing and resident-owner delegation; the operations stay outside public MCP. Operator flow: `docs/guides/concurrent-writes.md`. Tests cover merge choices, both engines, grants, stale previews, read-only audit, and private files. A database-only page (no `source_path`, no `source_uri`; `isDatabaseOnlyPage` in `src/core/persistence/unbound-pages.ts`) is matched to the canonical file at its slug-derived path (`ReconcileState.origin: 'slug_derived'`), and apply records that path as its `source_path` (the #5254 unbound collision; `test/reconcile-unbound-collision.test.ts`). Private fact rows (#6137): `reconcile-prepare.ts` `privateFactViolation` identifies a fact row by (row number, claim), as `restoreHiddenFactRows` does. A stored non-world row carried at its identity must be unchanged; a row at no stored identity may not carry a stored private claim under another visibility, and a world row may not carry (or newly gain) a stored private row's context of 24 or more characters verbatim; sources are not compared. The `permission_denied` refusal names only the row number, with a `gbrain get` read fix. It guards verbatim copies, not reworded text. #6138: an `--auto-additive` preview classified `no_drift` asks Git (`hardened-git.ts` `hardenedPathDirty`: filter-free plumbing, never `git status`, so the checkout's clean/process filters never run; `null` when only repository config could decide) whether the canonical file differs from its last commit and returns `git_dirty`; a dirty file's `next_action` says the content agrees, the difference is only how it is written, reconcile does not commit, and names `git -C <root> diff -- <file>` (committing it is the user's decision; the managed commit path is deferred, D5). The "retry the original write" step is conditional on the preview coming from a refused write. Tests: `test/persistence-reconcile-git-dirty-6138.test.ts`. #6222/#6254: `assertSoleFileClaim` (reconcile-state.ts) refuses on any claimant `findLiveFileClaimants` (file-claims.ts) returns, naming the soft-delete exit (#6517). Its predicates (`fileClaimCandidatesSql`) match the v219 expression indexes `pages_source_path_name_idx` and `pages_file_uri_name_idx` (built online, one statement per call). `sources reconcile` help says writes to one source publish one at a time. Tests: `test/persistence-reconcile.test.ts`, `test/e2e/pages-reconcile-name-indexes-postgres.test.ts`. #6394: `readReconcileState(..., { adoptSlugPath })` lets a live page with no recorded origin and no database-only marker reconcile against the file at its slug path (`slugDerivedOrigin`, mode-aware), never for a declared db_only slug, a never-filed derive-phase page, a page with a `source_uri` or a mirror-only page; the CLI flag is `gbrain sources reconcile … --preview --adopt-slug-path`, and apply and the consumer's prepare adopt only when the preview's stored page recorded no origin (`reconcilePreviewAdopts`), with the pinned relative path and binding digest unchanged. The drift refusal names the flag for such a page.+- `src/core/persistence/reconcile*.ts` — trusted-local exact-page reconciliation: loss-preserving semantic preview, explicit JSON Pointer choices, pinned identity/revision/raw-file/policy checks, durable private preimages and same-ID replay through the existing coordinator. Normal overwrite protection stays unchanged. The bounded audit reports source-scoped drift without repair or checkpoint changes; a database-only page (`isDatabaseOnlyPage`, with no file at its slug-derived path) counts as `database_only` with no reconcile suggestion, never as drift, while a legacy row that merely lacks `source_path` is audited as usual. `src/commands/source-reconcile.ts` provides strict CLI parsing, private artifact I/O, brain routing and resident-owner delegation; the operations stay outside public MCP. Operator flow: `docs/guides/concurrent-writes.md`. Tests cover merge choices, both engines, grants, stale previews, read-only audit, and private files. A database-only page (no `source_path`, no `source_uri`; `isDatabaseOnlyPage` in `src/core/persistence/unbound-pages.ts`) is matched to the canonical file at its slug-derived path (`ReconcileState.origin: 'slug_derived'`), and apply records that path as its `source_path` (the #5254 unbound collision; `test/reconcile-unbound-collision.test.ts`). Private fact rows (#6137): `reconcile-prepare.ts` `privateFactViolation` identifies a fact row by (row number, claim), as `restoreHiddenFactRows` does. A stored non-world row carried at its identity must be unchanged; a row at no stored identity may not carry a stored private claim under another visibility, and a world row may not carry (or newly gain) a stored private row's context of 24 or more characters verbatim; sources are not compared. The `permission_denied` refusal names only the row number, with a `gbrain get` read fix. It guards verbatim copies, not reworded text. #6138: an `--auto-additive` preview classified `no_drift` asks Git (`hardened-git.ts` `hardenedPathDirty`: filter-free plumbing, never `git status`, so the checkout's clean/process filters never run; `null` when only repository config could decide) whether the canonical file differs from its last commit and returns `git_dirty`; a dirty file's `next_action` says the content agrees, the difference is only how it is written, reconcile does not commit, and names `git -C <root> diff -- <file>` (committing it is the user's decision; the managed commit path is deferred, D5). The "retry the original write" step is conditional on the preview coming from a refused write. Tests: `test/persistence-reconcile-git-dirty-6138.test.ts`. #6222/#6254: `assertSoleFileClaim` (reconcile-state.ts) refuses on any claimant `findLiveFileClaimants` (file-claims.ts) returns, naming the soft-delete exit (#6517). Its predicates (`fileClaimCandidatesQuery`) match the v219 expression indexes `pages_source_path_name_idx` and `pages_file_uri_name_idx` (built online, one statement per call). `sources reconcile` help says writes to one source publish one at a time. Tests: `test/persistence-reconcile.test.ts`, `test/e2e/pages-reconcile-name-indexes-postgres.test.ts`. #6394: `readReconcileState(..., { adoptSlugPath })` lets a live page with no recorded origin and no database-only marker reconcile against the file at its slug path (`slugDerivedOrigin`, mode-aware), never for a declared db_only slug, a never-filed derive-phase page, a page with a `source_uri` or a mirror-only page; the CLI flag is `gbrain sources reconcile … --preview --adopt-slug-path`, and apply and the consumer's prepare adopt only when the preview's stored page recorded no origin (`reconcilePreviewAdopts`), with the pinned relative path and binding digest unchanged. The drift refusal names the flag for such a page.- `src/core/persistence/reconcile-additive.ts` (#5974) — pure structural drift classifier over the complete file/database delta: inserted whole lines (two-pointer subsequence, CRLF-normalized; fence, heading and table insertions excluded) are `suggested`; an append-only `contacts` list, an allowlisted activity date moving forward, and one-sided ordinary fields are `auto`; policy/privacy/identity/tag changes and everything else are `review`. `--auto-additive` previews write `take_file` only for `auto` (and `suggested` with `--accept-suggested`), recorded as format-2 `auto_decisions` with an evidence digest that apply and owner preparation recheck. `--audit --classify` reports per-page verdicts and counts, never values; #5966 (W14 P1.7) adds the `slug_rule_mismatch` verdict (a legacy unstamped file of a slug the path cannot derive, fix: `gbrain repair frontmatter`) read from `readReconcileState`'s refusal (`detail: slug_rule_mismatch` once the wave-13 `reconcile-state.ts` hunk lands; until then an `invalid_params` refusal on a non-fixed-point slug).@@ -16,7 +16,7 @@- `src/core/persistence/sync-slices.ts` — #6349 path-sliced staging for a managed target that exceeds the cursor bound with no commit axis to stage on (a first sync, a `--full` tree walk, one commit above the bound). `sliceEntries` cuts the whole resolved manifest in `(phase, code-unit path)` order: every import slice, then bounded deletion slices, the longest prefix the bound admits. The slice cursor `{ phase, after, head, target }` lives in `op_checkpoints` (`managed-sync-slice`, keyed by source, incarnation and the run's cursor options so a resumed invocation with other exclusions starts over), written or cleared by the slice's checkpoint in the same transaction that leaves `last_commit` untouched until the last slice settles; `sync-discovery.ts` resumes an unfinished target pinned at its recorded commit.- **`src/core/persistence/sync-discovery.ts`** + **`sync-origin.ts`** — managed owner-only Git discovery with source-relative exclusions and one-statement page identity/revision/liveness snapshots. #6517: `selectOriginClaimant` (sync-origin.ts) is the one origin rule, applied by the discovery census and by `assertSyncPageOrigin` at preparation and publication: a live page wins over tombstones, several live pages refuse `page_identity_changed` naming the soft-delete exit (`sharedOriginExit`), a single tombstone may be reused, several tombstones stay ambiguous. Reserved skillpack paths (`skills/` at any depth and `skillpack.json`, `src/core/skill-reserved-paths.ts`) never enter discovery: the shared skill publisher owns them and `managedImportContent` refuses them, so a seeded pack cannot block a sync. Nested full discovery filters source scope before slicing paths. Windows separator aliases retain their page identity; ambiguous aliases refuse, while POSIX backslashes/case remain exact. Under `source-root` mode a stored `<scope>/<path>` origin (the Git-root form older write-through minted from the slug, recognized because `<path>` names the page slug) is accepted as `<path>` at discovery, freeze, preparation and the page-origin query, and an import rewrites it in place; when both readings name existing files the stored origin refuses with `detail: ambiguous_source_path`. A genuine origin mismatch refuses with `detail: sync_origin_mismatch` and the filled paths. Deletions must be absent from the pinned Git target or their explicitly selected working tree. Deleting a file that no page records as its origin (for example a skipped slug twin) while its slug's page keeps another origin commits an explicit no-op receipt (`unownedDeletion`, outcome reason `unowned_deleted_path`) that preserves that live page or tombstone; freeze and publication re-prove that no page owns the path and that the file is still absent. Existing cursors reuse their accepted manifests, with unknown old deletion provenance refused rather than rewritten. Active Git holds of the source are re-screened when their blob or working bytes changed, the file left, a `sources retry-held` request names them, the hold predates the current `RECOVERY_VERSION`, or the code is `frontmatter_slug_conflict`, `file_too_large`, `rename_held` or `parser_regression`; holds of now-excluded paths are released at the checkpoint. #6278 (B7): `retryTaken` lists every scheduled path the discovery read (screened as an entry, as a candidate, or no longer eligible); `sync-run.ts` clears them in the transaction that saves the fresh cursor. A held rename destination (or a held path renamed again) carries the hold's `renameFrom` when the old page is unchanged, else `renameHeld` (held as `rename_held` / `rename_source_changed`), and a full walk never deletes an origin a hold's `rename_from` names. Imports whose origin has no page claim their slug together: a live page whose own file is still in the tree keeps the slug, otherwise the file named like the slug (else the first path) wins, and the losers leave the manifest and are reported as `slugCollisions` (the library path's `slug_collision` skip) instead of failing the run. A winner whose slug is held by a page with a vanished or deleted origin takes that page over (`renameFrom`, same slug). A Git-detected rename to an unoccupied slug becomes one import carrying `renameFrom` in place of a delete plus a create. Origins for one slug that differ only by case or separator spelling refuse, except a case-only respelling whose old file the same sync removes. Code files keep exact per-origin identity. On Windows a path containing `:` is reported in `SyncDiscovery.fileRefusals` (code `colon_slug_windows_write_through`, with its filled `gbrain sync --source <id> --no-pull` hint) and kept out of the run and its origin checks, so one such file no longer fails the whole sync (#5032). `resolveManagedSyncContext` refuses `skipFailed` / `includeGitignored` on a managed source with `managed_sync_flag_refused` (`managed-sync-flags.ts`, `detail` = the flag, fix = the same `gbrain sync` argv without it), the one refusal jobs, MCP and the cycle reach; `gbrain sync` raises it at parse, before the legacy ledger acknowledgement and the cost gate, `--all` included (#6696).-- `src/core/persistence/file-claims.ts` — the recorded-origin census shared by reconcile and the shared-origin delete (#6517): `fileClaimCandidatesSql` (the paged same-name query, 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 sync --source <id> --no-pull --full` that imports the kept file into the survivor), `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). A purge of a shared-origin page refuses and names the soft delete. Tests: `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/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 sync --source <id> --no-pull --full` that imports the kept file into the survivor), `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). A purge of a shared-origin page refuses and names the soft delete. Tests: `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`).- `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`.diff --git a/src/core/persistence/file-claims.ts b/src/core/persistence/file-claims.tsindex 06e836074b..1c4118a76c 100644--- a/src/core/persistence/file-claims.ts+++ b/src/core/persistence/file-claims.ts@@ -38,32 +38,49 @@ export function recordedReconcilePath(root: string, page: { slug: string; sourceconst recorded = recordedPathFromFileUri(page.source_uri, root);return recorded ? join(root, recorded) : null;}+export interface FileClaimCandidatesWindow {+ sourceId: string; pageId: number; afterId: number; maxId: number;+ /** The target file's name. */+ fileName: string;+ /** Names a `file:` URI may end with. */+ uriNames: string[];+}/**- * The paged census query: $1 source, $2 the page itself, $3/$4 the id window, $5 the file name, $6 its- * name after the last backslash (POSIX) or the name (Windows), $7 the file-URI names. Exported so the- * Postgres plan test runs the exact text.+ * The paged census query and its binds: $1 source, $2 the page itself, $3/$4 the id window, then the name+ * predicates. The path index normalizes backslashes, so on POSIX the indexed name is the file name after its+ * last backslash and the slash-only basename is rechecked against the file name; on Windows both separators+ * are path separators and the indexed name is the whole check. Every placeholder is referenced on every+ * platform (#6659: an unreferenced untyped bind fails with 42P18). Exported so the Postgres plan test runs+ * the exact text.*/-export function fileClaimCandidatesSql(platform: NodeJS.Platform = process.platform): string {+export function fileClaimCandidatesQuery(window: FileClaimCandidatesWindow, platform: NodeJS.Platform = process.platform): { sql: string; params: unknown[] } {+ const { sourceId, pageId, afterId, maxId, fileName, uriNames } = window;+ const params: unknown[] = [sourceId, pageId, afterId, maxId];+ const bind = (value: unknown) => { params.push(value); return `$${params.length}`; };+ const indexedName = `regexp_replace(replace(btrim(source_path), chr(92), '/'), '^.*/', '')`;const pathMatch = platform === 'win32'- ? `source_path IS NOT NULL AND regexp_replace(replace(btrim(source_path), chr(92), '/'), '^.*/', '')=$6`- : `source_path IS NOT NULL AND regexp_replace(replace(btrim(source_path), chr(92), '/'), '^.*/', '')=$6 AND regexp_replace(btrim(source_path),'^.*/','')=$5`;- return `SELECT id,slug,source_path,source_uri FROM pages WHERE source_id=$1 AND id<>$2 AND id>$3 AND id<=$4 AND deleted_at IS NULL AND (- (${pathMatch}) OR (source_uri LIKE 'file:%' AND regexp_replace(source_uri, '^.*/', '')=ANY($7::text[])))- ORDER BY id LIMIT 100`;+ ? `source_path IS NOT NULL AND ${indexedName}=${bind(fileName)}`+ : `source_path IS NOT NULL AND ${indexedName}=${bind(fileName.replace(/^.*\\/s, ''))} AND regexp_replace(btrim(source_path),'^.*/','')=${bind(fileName)}`;+ const uriMatch = `source_uri LIKE 'file:%' AND regexp_replace(source_uri, '^.*/', '')=ANY(${bind(uriNames)}::text[])`;+ return {+ sql: `SELECT id,slug,source_path,source_uri FROM pages WHERE source_id=$1 AND id<>$2 AND id>$3 AND id<=$4 AND deleted_at IS NULL AND (+ (${pathMatch}) OR (${uriMatch}))+ ORDER BY id LIMIT 100`,+ params,+ };}/** Every other live page of the source whose recorded origin resolves to the target's canonical file, in id order. */export async function findLiveFileClaimants(engine: BrainEngine, target: FileClaimTarget): Promise<FileClaimant[]> {const { sourceId, slug, root, mode, canonicalPath } = target;const fileName = basename(target.path), uriName = pathToFileURL(target.path).pathname.split('/').pop()!;- const indexedName = fileName.replace(/^.*\\/s, '');const uriNames = [...new Set([fileName, uriName, ...(target.recordedUri ? [target.recordedUri.replace(/^.*\//s, '')] : [])])];const [ceiling] = await engine.executeRaw<{ id: number | string | null }>('SELECT max(id) AS id FROM pages WHERE source_id=$1', [sourceId]);const maxId = Number(ceiling?.id ?? 0);const claimants: FileClaimant[] = [];for (let afterId = 0; ;) {+ const query = fileClaimCandidatesQuery({ sourceId, pageId: target.pageId, afterId, maxId, fileName, uriNames });const candidates = await engine.executeRaw<{ id: number | string; slug: string; source_path: string | null; source_uri: string | null }>(- fileClaimCandidatesSql(),- [sourceId, target.pageId, afterId, maxId, fileName, process.platform === 'win32' ? fileName : indexedName, uriNames]);+ query.sql, query.params);for (const candidate of candidates) {const candidatePath = recordedReconcilePath(root, candidate, mode);if (!candidatePath || !isWriteTargetContained(candidatePath, root)) continue;diff --git a/src/core/persistence/reconcile-state.ts b/src/core/persistence/reconcile-state.tsindex 2f5354ff4a..a3f954e58b 100644--- a/src/core/persistence/reconcile-state.ts+++ b/src/core/persistence/reconcile-state.ts@@ -12,7 +12,7 @@ import { isWriteTargetContained } from '../path-confine.ts';import { recordedPathFromFileUri, scannerSlugRootMode } from '../write-through.ts';import { findLiveFileClaimants, recordedReconcilePath, type FileClaimTarget } from './file-claims.ts';import { sharedOriginExit } from './sync-origin.ts';-export { fileClaimCandidatesSql } from './file-claims.ts';+export { fileClaimCandidatesQuery } from './file-claims.ts';import { localHostId } from './identity.ts';import { isDatabaseOnlyPage, slugDerivedOrigin } from './unbound-pages.ts';import { isUnboundSourcePage } from './unbound-source.ts';diff --git a/test/file-claims-win32-6659.serial.test.ts b/test/file-claims-win32-6659.serial.test.tsnew file mode 100644index 0000000000..b59d2381de--- /dev/null+++ b/test/file-claims-win32-6659.serial.test.ts@@ -0,0 +1,55 @@+/**+ * #6659: on a Windows host the file-claim census (every coordinated+ * `delete_page` and reconcile runs it) bound a POSIX-only name its SQL never+ * referenced, and Postgres/PGLite refuse an untyped unreferenced bind with+ * 42P18. This drives the real `findLiveFileClaimants` under `process.platform+ * = 'win32'` (serial: it swaps a process global) and asserts it still finds a+ * page recording the same file.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { findLiveFileClaimants } from '../src/core/persistence/file-claims.ts';++let engine: PGLiteEngine;+let root: string;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ root = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-6659-')));+ mkdirSync(join(root, 'notes'), { recursive: true });+ writeFileSync(join(root, 'notes', 'shared.md'), '---\ntype: note\ntitle: Shared\n---\nShared body.\n');+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES('win-6659','win-6659',$1,'{}')", [root]);+ for (const slug of ['notes/shared', 'notes/shared-twin']) {+ await importFromContent(engine, slug, '---\ntype: note\ntitle: Shared\n---\nShared body.\n',+ { sourceId: 'win-6659', sourcePath: 'notes/shared.md', noEmbed: true });+ }+}, 120_000);++afterAll(async () => {+ await engine?.disconnect();+ rmSync(root, { recursive: true, force: true });+});++for (const platform of ['linux', 'win32'] as const) {+ test(`the file-claim census finds a page recording the same file on ${platform}`, async () => {+ const [target] = await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE source_id='win-6659' AND slug='notes/shared'");+ const path = join(root, 'notes', 'shared.md');+ const descriptor = Object.getOwnPropertyDescriptor(process, 'platform')!;+ try {+ Object.defineProperty(process, 'platform', { ...descriptor, value: platform });+ const claimants = await findLiveFileClaimants(engine, {+ sourceId: 'win-6659', slug: 'notes/shared', pageId: Number(target!.id), root, mode: 'source-root',+ path, canonicalPath: realpathSync(path), recordedUri: null,+ });+ expect(claimants.map(c => c.slug)).toEqual(['notes/shared-twin']);+ } finally {+ Object.defineProperty(process, 'platform', descriptor);+ }+ });+}diff --git a/test/persistence-reconcile.test.ts b/test/persistence-reconcile.test.tsindex 2e7826d1c6..ca05b14d00 100644--- a/test/persistence-reconcile.test.ts+++ b/test/persistence-reconcile.test.ts@@ -12,7 +12,7 @@ import { parseMarkdown, serializePageToMarkdown } from '../src/core/markdown.ts'import { acceptWriterTransfer, acquireWorktree, claimWorktree, getWorktreeBinding, prepareWriterTransfer } from '../src/core/persistence/ownership.ts';import { registerLocalWriter, withVerifiedLocalRegistration, type LocalRegistration } from '../src/core/persistence/identity.ts';import { runReconcileApply, runReconcileBackups, runReconcilePreview, assertReconcileOutputPath } from '../src/core/persistence/reconcile.ts';-import { fileClaimCandidatesSql } from '../src/core/persistence/reconcile-state.ts';+import { fileClaimCandidatesQuery } from '../src/core/persistence/reconcile-state.ts';import { prepareFileTarget } from '../src/core/persistence/page-prepare.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { admitWrite, claimNextWrite, compactWriteReceipts, getWriteRequest } from '../src/core/persistence/journal.ts';@@ -697,13 +697,27 @@ test('the file-claim census is served by the v219 name indexes on Postgres', asyawait engine.transaction(tx => withCoordinatedWrite(tx, [f.id], () => tx.executeRaw(`INSERT INTO pages(source_id,slug,type,title,compiled_truth,frontmatter,source_path)SELECT $1,'bulk/p'||n,'note','Bulk '||n,'Bulk '||n,'{}'::jsonb,'bulk/p'||n||'.md' FROM generate_series(1,3000) n`, [f.id]), TEST_WRITE_ATTRIBUTION));await engine.executeRaw('ANALYZE pages');- const plan = (await engine.executeRaw<{ 'QUERY PLAN': string }>(`EXPLAIN ${fileClaimCandidatesSql('linux')}`,- [f.id, 0, 0, 2147483647, 'example.md', 'example.md', ['example.md']]))+ const census = fileClaimCandidatesQuery({ sourceId: f.id, pageId: 0, afterId: 0, maxId: 2147483647, fileName: 'example.md', uriNames: ['example.md'] }, 'linux');+ const plan = (await engine.executeRaw<{ 'QUERY PLAN': string }>(`EXPLAIN ${census.sql}`, census.params)).map(row => row['QUERY PLAN']).join('\n');expect(plan).toContain('pages_source_path_name_idx');expect(plan).toContain('pages_file_uri_name_idx');}), 120_000);+// #6659: the Windows census bound a POSIX-only name it never referenced; Postgres and PGLite refuse an untyped+// unreferenced bind with 42P18, which failed every coordinated delete_page on a Windows host.+test.each(['win32', 'linux'] as const)('the %s file-claim census runs with its own binds and finds same-name pages', platform =>+ isolated(async engine => {+ const f = await fixture(engine);+ await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], () => tx.executeRaw(`INSERT INTO pages(source_id,slug,type,title,compiled_truth,frontmatter,source_path,source_uri)+ VALUES ($1,'twins/by-path','note','Path twin','x','{}'::jsonb,'other/claimed.md',NULL),+ ($1,'twins/by-uri','note','URI twin','x','{}'::jsonb,NULL,'file:///repo/other/claimed.md'),+ ($1,'twins/unrelated','note','Unrelated','x','{}'::jsonb,'other/unrelated.md',NULL)`, [f.id]), TEST_WRITE_ATTRIBUTION));+ const census = fileClaimCandidatesQuery({ sourceId: f.id, pageId: 0, afterId: 0, maxId: 2147483647, fileName: 'claimed.md', uriNames: ['claimed.md'] }, platform);+ const rows = await engine.executeRaw<{ slug: string }>(census.sql, census.params);+ expect(rows.map(row => row.slug).sort()).toEqual(['twins/by-path', 'twins/by-uri']);+ }), 120_000);+// The parser must not normalize an already-resolved identity a second time.// Existing reconcile cases only covered extension-free page keys.test.each(['notes/example.md', 'notes/example.md.md'])('reconciliation preserves extension-bearing identity %s', async slug =>diff --git a/test/sql-bind-placeholders.test.ts b/test/sql-bind-placeholders.test.tsnew file mode 100644index 0000000000..a5fab232d9--- /dev/null+++ b/test/sql-bind-placeholders.test.ts@@ -0,0 +1,28 @@+/**+ * One guard for the bind-placeholder bug class (#6659):+ * Postgres and PGLite refuse a statement that binds a parameter it never+ * references (42P18 "could not determine data type", or 08P01 "bind message+ * supplies N parameters"). Each exported `{ sql, params }` builder runs over+ * its platform/option matrix, and the `$n` placeholders its SQL references+ * must be exactly `1..params.length`.+ */+import { describe, expect, test } from 'bun:test';+import { fileClaimCandidatesQuery } from '../src/core/persistence/file-claims.ts';++function referenced(sql: string): number[] {+ return [...new Set([...sql.matchAll(/\$(\d+)(?!\d)/g)].map(m => Number(m[1])))].sort((a, b) => a - b);+}+function expectEveryBindReferenced(statement: { sql: string; params: unknown[] } | null): void {+ expect(statement).not.toBeNull();+ expect(referenced(statement!.sql)).toEqual(statement!.params.map((_, i) => i + 1));+}++describe('file-claim census', () => {+ for (const platform of ['linux', 'darwin', 'win32'] as const) {+ test(`${platform}: every bound placeholder is referenced`, () => {+ expectEveryBindReferenced(fileClaimCandidatesQuery({+ sourceId: 'default', pageId: 1, afterId: 0, maxId: 10, fileName: 'example.md', uriNames: ['example.md'],+ }, platform));+ });+ }+});