Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(reconcile): page the same-file census and index it, so a common file name no longer refuses reconciliation (#6222, #6254)
time-attack5529ea8e852a
diff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.mdindex 8ff74a295a..8b1ce8578e 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`, `git status --porcelain -z -- <file>` in the source root) 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`.+- `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`, `git status --porcelain -z -- <file>` in the source root) 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) pages the "no other page claims this file" census 100 rows at a time below the source's highest page id, so a common file name no longer refuses; realpath still decides each candidate. 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`.- `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.diff --git a/src/commands/source-reconcile.ts b/src/commands/source-reconcile.tsindex 0e1f0c075a..0c9693378e 100644--- a/src/commands/source-reconcile.ts+++ b/src/commands/source-reconcile.ts@@ -42,8 +42,9 @@ before applying. Apply preserves both originals and uses the current canonicalowner without changing ownership, activation, roots, or sync checkpoints.The caller must already have a trusted CLI registration whose original andcurrent grants permit put_page for this source and exact slug.-get_write_request needs its own operation grant; identical apply replay is-available without that receipt helper. Inspect the private artifact's .conflicts+Read a pending apply's receipt with gbrain write-request --brain <id> -- <request-id>+(MCP: get_write_request), which needs its own operation grant; identical apply+replay is available without that receipt helper. Inspect the private artifact's .conflictsand .result locally before applying; stdout contains only a summary.Use the same request ID and arguments after a lost response or pending receipt.After a terminal conflict, make a new preview and use a new request ID.@@ -55,6 +56,9 @@ timeline lines are suggested, not decided, because an added line can stillcontradict an old one; read them in the private preview, then rerun with--accept-suggested. Anything else (changed or removed text, policy, privacy,title, type, tags, fences) keeps the preview unready for a person to decide.+Writes to one source publish one at a time on its canonical owner, so running+many applies at once only queues them (commits coalesce); reconcile a large set+from one client, one or two at a time.Audit is bounded and read-only; its cursor is not a sync checkpoint. --classifyadds each drifted page's structural classification and counts, never values.Backups persist until explicitly removed. Removal deletes that private history,diff --git a/src/core/persistence/reconcile-state.ts b/src/core/persistence/reconcile-state.tsindex 8fa27ebd95..807e1f9ce0 100644--- a/src/core/persistence/reconcile-state.ts+++ b/src/core/persistence/reconcile-state.ts@@ -72,6 +72,61 @@ function recordedReconcilePath(root: string, page: { slug: string; source_path?:const recorded = recordedPathFromFileUri(page.source_uri, root);return recorded ? join(root, recorded) : null;}+/**+ * The paged census query of {@link assertSoleFileClaim}: $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.+ */+export function fileClaimCandidatesSql(platform: NodeJS.Platform = process.platform): string {+ 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 (+ (${pathMatch}) OR (source_uri LIKE 'file:%' AND regexp_replace(source_uri, '^.*/', '')=ANY($7::text[])))+ ORDER BY id LIMIT 100`;+}+/**+ * Refuses when another page of the source records the reconciled file as its own.+ *+ * #6222/#6254: every page whose recorded path or file URI shares the file's+ * name is a candidate, and realpath decides each one. The census is paged+ * (100 rows per batch, keyset on id) below the source's highest page id read+ * once, so a common name like `2015-09.md` no longer refuses, and concurrent+ * imports cannot make it endless; preparation re-reads this state inside the+ * coordinated write. Both name predicates match the expression indexes of+ * migration v219 (`pages_source_path_name_idx`, `pages_file_uri_name_idx`):+ * the path index normalizes backslashes, so on POSIX the slash-only basename+ * is rechecked on the rows it finds.+ */+async function assertSoleFileClaim(engine: BrainEngine, target: { sourceId: string; slug: string; pageId: number; root: string;+ mode: 'git-root' | 'source-root'; path: string; canonicalPath: string; recordedUri: string | null }): Promise<void> {+ 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);+ for (let afterId = 0; ;) {+ 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]);+ for (const candidate of candidates) {+ const candidatePath = recordedReconcilePath(root, candidate, mode);+ if (!candidatePath || !isWriteTargetContained(candidatePath, root)) continue;+ let canonicalCandidate: string;+ try { canonicalCandidate = realpathSync(candidatePath); }+ catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue;+ throw opError('source_changed', 'A candidate canonical file origin could not be verified.',+ `Nothing changed. Page ${candidate.slug} in '${sourceId}' records a file that could not be resolved; check that the source checkout is readable, then preview ${slug} again.`);+ }+ if (canonicalCandidate === canonicalPath) throw opError('source_changed', 'Several pages claim the recorded canonical file.',+ `Nothing changed. Pages ${slug} and ${candidate.slug} in '${sourceId}' both record the same file, so reconcile cannot tell which owns it; decide with the user which page owns the file before reconciling either.`);+ }+ if (candidates.length < 100) return;+ afterId = Number(candidates[candidates.length - 1]!.id);+ }+}export async function readReconcileState(engine: BrainEngine, sourceId: string, slug: string, assessmentAt = new Date().toISOString()): Promise<ReconcileState> {const binding = await getWorktreeBinding(engine, sourceId);if (!binding?.local_path || binding.owner_host_id !== localHostId() || binding.state !== 'active') {@@ -111,29 +166,9 @@ export async function readReconcileState(engine: BrainEngine, sourceId: string,throw opError('request_too_large', 'The canonical file exceeds reconciliation capacity.',`Nothing changed. The canonical file of ${slug} in '${sourceId}' is larger than the journal's request and recovery limits; tell the user the page needs a manual edit of that file.`);}- const fileName = basename(path), uriName = pathToFileURL(path).pathname.split('/').pop()!;- const candidates = await engine.executeRaw<{ slug: string; source_path: string | null; source_uri: string | null }>(- `SELECT slug,source_path,source_uri FROM pages WHERE source_id=$1 AND id<>$2 AND (- regexp_replace(CASE WHEN $7::boolean THEN replace(btrim(source_path),chr(92),'/') ELSE btrim(source_path) END,'^.*/','')=$3- OR source_uri LIKE 'file:%' AND (right(source_uri,length($4::text))=$4 OR right(source_uri,length($5::text))=$5)- OR source_uri=$6) ORDER BY id LIMIT 101`,- [sourceId, snapshot.page.id, fileName, `/${fileName}`, `/${uriName}`, recorded ? snapshot.page.source_uri : null, process.platform === 'win32']);- if (candidates.length > 100) throw new OperationError('source_changed', 'Too many candidate page origins to verify this exact file safely.',- 'Review the recorded source paths before retrying this exact-page reconciliation.');const canonicalPath = realpathSync(path);- for (const candidate of candidates) {- const candidatePath = recordedReconcilePath(root, candidate, mode);- if (!candidatePath || !isWriteTargetContained(candidatePath, root)) continue;- let canonicalCandidate: string;- try { canonicalCandidate = realpathSync(candidatePath); }- catch (error) {- if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue;- throw opError('source_changed', 'A candidate canonical file origin could not be verified.',- `Nothing changed. Page ${candidate.slug} in '${sourceId}' records a file that could not be resolved; check that the source checkout is readable, then preview ${slug} again.`);- }- if (canonicalCandidate === canonicalPath) throw opError('source_changed', 'Several pages claim the recorded canonical file.',- `Nothing changed. Pages ${slug} and ${candidate.slug} in '${sourceId}' both record the same file, so reconcile cannot tell which owns it; decide with the user which page owns the file before reconciling either.`);- }+ await assertSoleFileClaim(engine, { sourceId, slug, pageId: snapshot.page.id, root, mode, path, canonicalPath,+ recordedUri: recorded ? snapshot.page.source_uri ?? null : null });const raw = readFileSync(path), text = raw.toString('utf8');if (!Buffer.from(text).equals(raw)) throw opError('invalid_params', 'The canonical file must contain valid UTF-8.',`Nothing changed. Re-save the canonical file of ${slug} in '${sourceId}' as UTF-8, then preview the page again.`);diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex cfca332ad7..54cf78e271 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -219,6 +219,7 @@ import { v215 } from './v215-facts-attributed-to.ts';import { v216 } from './v216-chronicle-campaign-stamps.ts';import { v217 } from './v217-persistence-request-claim-phase.ts';import { v218 } from './v218-purge-legacy-worktree-manifest-files.ts';+import { v219 } from './v219-pages-reconcile-name-indexes.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -436,4 +437,5 @@ export const MIGRATIONS: Migration[] = [v216,v217,v218,+ v219,];diff --git a/src/core/schema-migrations/v219-pages-reconcile-name-indexes.ts b/src/core/schema-migrations/v219-pages-reconcile-name-indexes.tsnew file mode 100644index 0000000000..663c9be204--- /dev/null+++ b/src/core/schema-migrations/v219-pages-reconcile-name-indexes.ts@@ -0,0 +1,35 @@+import type { Migration } from './types.ts';+import { buildIndexOnline, migrationNotice } from './helpers.ts';++/**+ * #6222/#6254: index the reconcile "no other page claims this file" census+ * (`assertSoleFileClaim`, persistence/reconcile-state.ts). It looked up every+ * page whose recorded path or file URI shares the file's name with a regexp+ * over the whole source, about five times per reconciled page (458 ms per call+ * at 490k pages). The expressions here are byte-identical to the census+ * predicates. Postgres builds each index CONCURRENTLY, one statement per call,+ * after dropping an INVALID leftover; PGLite builds them inline.+ */+export const PAGES_RECONCILE_NAME_INDEXES = [+ { name: 'pages_source_path_name_idx', table: 'pages',+ sql: `CREATE INDEX IF NOT EXISTS pages_source_path_name_idx+ ON pages (source_id, (regexp_replace(replace(btrim(source_path), chr(92), '/'), '^.*/', '')))+ WHERE source_path IS NOT NULL` },+ { name: 'pages_file_uri_name_idx', table: 'pages',+ sql: `CREATE INDEX IF NOT EXISTS pages_file_uri_name_idx+ ON pages (source_id, (regexp_replace(source_uri, '^.*/', '')))+ WHERE source_uri LIKE 'file:%'` },+] as const;++export const v219: Migration = {+ version: 219,+ name: 'pages_reconcile_name_indexes',+ idempotent: true,+ transaction: false,+ sql: '',+ handler: async engine => {+ for (const index of PAGES_RECONCILE_NAME_INDEXES) {+ await buildIndexOnline(engine, 219, index, { notice: migrationNotice });+ }+ },+};diff --git a/test/e2e/pages-reconcile-name-indexes-postgres.test.ts b/test/e2e/pages-reconcile-name-indexes-postgres.test.tsnew file mode 100644index 0000000000..6cb12c54c7--- /dev/null+++ b/test/e2e/pages-reconcile-name-indexes-postgres.test.ts@@ -0,0 +1,96 @@+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import postgres from '#postgres';+import { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { PAGES_RECONCILE_NAME_INDEXES, v219 } from '../../src/core/schema-migrations/v219-pages-reconcile-name-indexes.ts';+import { requirePostgresTestDatabase } from '../helpers/test-backends.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';++// #6222/#6254 (fix wave 12, W1.3): v219 builds the reconcile file-claim name+// indexes CONCURRENTLY on Postgres, one statement per call (a multi-statement+// call runs in an implicit transaction, which CONCURRENTLY refuses), drops an+// INVALID leftover and rebuilds it, resumes after a failed second build, and+// runs through a transaction-mode PgBouncer when the CI fixture provides one.++const NAMES = PAGES_RECONCILE_NAME_INDEXES.map(index => index.name);+let engine: PostgresEngine;+let close: () => Promise<void>;++beforeAll(async () => {+ const pg = await isolatedPersistencePostgres(requirePostgresTestDatabase());+ engine = pg.engine; close = pg.close;+}, 120_000);+afterAll(async () => { await close?.(); });++const states = async () => (await engine.executeRaw<{ name: string; state: string }>(+ `SELECT n.name, CASE WHEN i.indexrelid IS NULL THEN 'missing' WHEN i.indisvalid THEN 'valid' ELSE 'invalid' END AS state+ FROM unnest($1::text[]) WITH ORDINALITY AS n(name, ord) LEFT JOIN pg_index i ON i.indexrelid = to_regclass(n.name) ORDER BY n.ord`, [NAMES]))+ .map(row => row.state);++/** Runs v219 with every reserved-connection statement recorded; `fail` throws instead of running the matching statement. */+async function runV219(fail?: (sql: string) => boolean): Promise<string[]> {+ const statements: string[] = [];+ const reserve = engine.withReservedConnection.bind(engine);+ engine.withReservedConnection = (async (fn: Parameters<PostgresEngine['withReservedConnection']>[0]) => reserve(conn => fn({+ executeRaw: async (sql: string, params?: unknown[]) => {+ statements.push(sql);+ if (fail?.(sql)) throw new Error('synthetic interrupted index build');+ return conn.executeRaw(sql, params);+ },+ }))) as PostgresEngine['withReservedConnection'];+ try { await v219.handler!(engine); } finally { engine.withReservedConnection = reserve; }+ return statements;+}++test('initSchema leaves both name indexes valid', async () => {+ expect(await states()).toEqual(['valid', 'valid']);+});++test('v219 builds each index CONCURRENTLY in its own call, with no session SET', async () => {+ for (const name of NAMES) await engine.executeRaw(`DROP INDEX IF EXISTS ${name}`);+ const statements = await runV219();+ expect(statements.map(sql => sql.trim().split(/\s+/).slice(0, 8).join(' '))).toEqual(+ NAMES.map(name => `CREATE INDEX CONCURRENTLY IF NOT EXISTS ${name} ON`));+ expect(statements.filter(sql => /^(SET|RESET)\b/i.test(sql.trim()))).toEqual([]);+ expect(await states()).toEqual(['valid', 'valid']);+});++test('an INVALID leftover is dropped and rebuilt; a valid index is left alone', async () => {+ await engine.executeRaw(`UPDATE pg_index SET indisvalid=false WHERE indexrelid='${NAMES[1]}'::regclass`);+ expect(await states()).toEqual(['valid', 'invalid']);+ const statements = await runV219();+ expect(statements.map(sql => sql.trim().split(/\s+/)[6])).toEqual([NAMES[1]]);+ expect(await states()).toEqual(['valid', 'valid']);+});++test('a failed second build leaves the first index valid, and a rerun finishes the second', async () => {+ for (const name of NAMES) await engine.executeRaw(`DROP INDEX IF EXISTS ${name}`);+ await expect(runV219(sql => sql.includes(NAMES[1]!))).rejects.toThrow('synthetic interrupted index build');+ expect(await states()).toEqual(['valid', 'missing']);+ await runV219();+ expect(await states()).toEqual(['valid', 'valid']);+});++const pooled = process.env.GBRAIN_PGBOUNCER_URL;+const pooledAdmin = process.env.GBRAIN_PGBOUNCER_DIRECT_URL;+if (process.env.GBRAIN_CI_REQUIRE_PGBOUNCER === '1' && !(pooled && pooledAdmin)) throw new Error('v219 pooler coverage requires the configured CI PgBouncer fixture.');+test.skipIf(!pooled || !pooledAdmin)('a fresh schema through a transaction-mode PgBouncer builds both indexes valid', async () => {+ assertSafeE2eDatabaseUrl(pooledAdmin!);+ const name = `gbrain_test_v219_pool_${randomUUID().replaceAll('-', '')}`;+ const admin = postgres(pooledAdmin!, { max: 1, prepare: false });+ await admin.unsafe(`CREATE DATABASE ${name}`);+ const url = new URL(pooled!); url.pathname = `/${name}`;+ const viaPool = new PostgresEngine();+ try {+ await viaPool.connect({ database_url: url.toString(), poolSize: 2 });+ await viaPool.initSchema();+ for (const index of NAMES) await viaPool.executeRaw(`DROP INDEX IF EXISTS ${index}`);+ await v219.handler!(viaPool);+ const rows = await viaPool.executeRaw<{ valid: boolean }>('SELECT indisvalid AS valid FROM pg_index WHERE indexrelid = ANY(ARRAY[to_regclass($1), to_regclass($2)])', NAMES);+ expect(rows.map(row => row.valid)).toEqual([true, true]);+ } finally {+ await viaPool.disconnect();+ await admin.unsafe(`DROP DATABASE IF EXISTS ${name} WITH (FORCE)`); await admin.end();+ }+}, 180_000);diff --git a/test/persistence-reconcile.test.ts b/test/persistence-reconcile.test.tsindex aec769b39e..d3fbb66d0d 100644--- a/test/persistence-reconcile.test.ts+++ b/test/persistence-reconcile.test.ts@@ -12,6 +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 { 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';@@ -631,19 +632,75 @@ test('genuine shared-file origins through explicit paths or URI fallback still r}}), 120_000);-test('candidate-origin fanout stops at a bounded verification limit rather than scanning the source', async () => isolated(async engine => {- const f = await fixture(engine), uri = pathToFileURL(f.file).href;+// #6222 (fix wave 12, W1.3): the census was capped at 100 candidates, so a common file name+// (date-named archives such as channels/<name>/2015-09.md) refused every page that had it.+// It now pages through every same-name candidate and realpath still decides ownership.+test('same-name pages in other directories and a shared provenance URI no longer refuse reconciliation', async () => isolated(async engine => {+ const f = await fixture(engine, true), uri = pathToFileURL(f.file).href;await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], async () => {await tx.executeRaw('UPDATE pages SET source_uri=$3 WHERE source_id=$1 AND slug=$2', [f.id, f.slug, uri]);await tx.executeRaw(`INSERT INTO pages(source_id,slug,type,title,compiled_truth,frontmatter,source_path,source_uri)- SELECT $1,'other/candidate-'||n,'note','Independent origin','Independent candidate '||n,'{}'::jsonb,'other/candidate-'||n||'.md',$2- FROM generate_series(1,101) n`, [f.id, uri]);+ SELECT $1,'channels/c'||n||'/example','note','Channel '||n,'Independent channel '||n,'{}'::jsonb,'channels/c'||n||'/example.md',+ CASE WHEN n % 2 = 0 THEN $2 END FROM generate_series(1,205) n`, [f.id, uri]);}, TEST_WRITE_ATTRIBUTION));+ for (let n = 1; n <= 205; n++) {+ mkdirSync(join(f.root, 'channels', `c${n}`), { recursive: true });+ writeFileSync(join(f.root, 'channels', `c${n}`, 'example.md'), `Independent channel ${n}\n`);+ }+ const neighbours = () => engine.executeRaw('SELECT slug,source_path,knowledge_revision FROM pages WHERE source_id=$1 AND slug<>$2 ORDER BY id', [f.id, f.slug]);+ const before = await neighbours();await local(engine, f.registration, async () => {- await expect(runReconcilePreview(engine, { source_id: f.id, slug: f.slug })).rejects.toMatchObject({- code: 'source_changed', message: 'Too many candidate page origins to verify this exact file safely.' });+ const result = await runReconcilePreview(engine, { source_id: f.id, slug: f.slug });+ expect(result).toMatchObject({ status: 'ready', relative_path: 'notes/example.md' });expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [f.id])).toHaveLength(0);+ expect((await runReconcileApply(engine, { source_id: f.id, slug: f.slug, preview: result.preview, request_id: randomUUID() })).state).toBe('committed');});+ expect(await neighbours()).toEqual(before);+ for (const n of [1, 102, 205]) expect(readFileSync(join(f.root, 'channels', `c${n}`, 'example.md'), 'utf8')).toBe(`Independent channel ${n}\n`);+}), 180_000);++test.each(['path', 'uri'])('a real second claimant behind 200 same-name pages still refuses, in preview and on a stale-preview apply (%s)', async origin => isolated(async engine => {+ const f = await fixture(engine, true), raw = readFileSync(f.file);+ await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], async () => {+ await tx.executeRaw(`INSERT INTO pages(source_id,slug,type,title,compiled_truth,frontmatter,source_path)+ SELECT $1,'channels/c'||n||'/example','note','Channel '||n,'Independent channel '||n,'{}'::jsonb,'channels/c'||n||'/example.md'+ FROM generate_series(1,200) n`, [f.id]);+ }, TEST_WRITE_ATTRIBUTION));+ await local(engine, f.registration, async () => {+ const { preview } = await runReconcilePreview(engine, { source_id: f.id, slug: f.slug });+ await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], () => tx.putPage('other/late-claimant', {+ type: 'note', title: 'Late claimant', compiled_truth: 'Another page claiming the same file.', frontmatter: {},+ source_path: origin === 'path' ? './notes//example.md' : null, source_uri: origin === 'uri' ? pathToFileURL(f.file).href : null,+ }, { sourceId: f.id }), TEST_WRITE_ATTRIBUTION));+ const snapshot = await engine.readPageSnapshot(f.slug, { sourceId: f.id });+ const collision = { code: 'source_changed', message: 'Several pages claim the recorded canonical file.' };+ await expect(runReconcilePreview(engine, { source_id: f.id, slug: f.slug })).rejects.toMatchObject(collision);+ await expect(runReconcileApply(engine, { source_id: f.id, slug: f.slug, preview, request_id: randomUUID() })).rejects.toMatchObject(collision);+ expect(await engine.readPageSnapshot(f.slug, { sourceId: f.id })).toEqual(snapshot);+ expect(readFileSync(f.file)).toEqual(raw);+ expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [f.id])).toHaveLength(0);+ });+}), 180_000);++test('a fresh PGLite schema builds the v219 name indexes inline', async () => {+ const engine = engines[0]!;+ const rows = await engine.executeRaw<{ present: boolean }>("SELECT to_regclass('pages_source_path_name_idx') IS NOT NULL AS present UNION ALL SELECT to_regclass('pages_file_uri_name_idx') IS NOT NULL");+ expect(rows.map(row => row.present)).toEqual([true, true]);+});++// #6254: the census runs about five times per reconciled page; on Postgres it must use the+// v219 expression indexes instead of evaluating a regexp over every page of the source.+test('the file-claim census is served by the v219 name indexes on Postgres', async () => isolated(async engine => {+ if (engine.kind !== 'postgres') return;+ 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)+ 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']]))+ .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);// The parser must not normalize an already-resolved identity a second time.