Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sync): a legacy page whose explicit frontmatter id differs from the file's is not adopted; the file is held legacy_slug_conflict (explicit_id_conflict) (#6729, #6727)
garrytane280d2932df2
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 78f5950931..247ee7e832 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -199,7 +199,7 @@ with each file and fix the ones that need no guessing."*| <a id="content_rejected"></a>`content_rejected` | The content-sanity gate matched junk and the operator set `content_sanity.junk_disposition` to `reject`, so the file is never imported and always visible. | Remove the matched junk from the file, or ask the user whether `junk_disposition` should go back to `quarantine`; that setting is the user's decision. A managed-sync hold re-screens on every sync, so either clears it on the next one. || <a id="purged_content"></a>`purged_content` | The file (or written content) has the content hash of a page the owner purged with `gbrain delete <slug> --purge`, under any slug, or carries a purged claim the database refuses. Purge leaves a text-free tombstone so a stale file, re-sync or revert cannot bring the content back. | Delete or edit the file and commit; an edited file imports normally. Only if the purge was a mistake, the owner lists tombstones with `gbrain pages purges list` and clears one with `gbrain pages unpurge <slug>` on the brain host; a managed-sync hold re-screens on every sync, so the next one imports it. A Google or GitHub connector item refused this way is skipped and the sync continues; `gbrain sources status` lists it ("skipped as purged content"). See [expire versus purge](memory-boundaries.md#purge). || <a id="write_gate_rejected"></a>`write_gate_rejected` | The source is untrusted, the file reads like an instruction to an agent (an override, a standing rule, an exfiltration or credential request), and the operator set `write_gate.external_mode` to `reject`, so the file is never imported and always visible. Managed sync holds it when it freezes the file (#6712 PR 2; before, the refusal came at preparation and blocked the rest of the source); an owner allow rule (`gbrain trust allow`) covering the source and the file's path admits it at freeze exactly as at preparation. The hold is `needs_human`, and every sync re-screens it, so the setting switched or an allow rule added clears it on the next sync. | Tell the user; whether to edit the file or switch `write_gate.external_mode` back to `quarantine` is their decision. |-| <a id="legacy_slug_conflict"></a>`legacy_slug_conflict` | The file has no page at its slug, and several live pages an older gbrain imported before the current slug fold (a space, an emoji, an accent or a trailing dash in the slug; no recorded file) fold to that slug (#6727). Exactly one such page is taken over by the file: the next sync imports into it (same page id, links, timeline and aliases) and records the file as its origin, instead of creating a second page. With several, sync cannot tell which page is the file's, so it holds the file and the rest of the source syncs. It holds the file the same way when the one match has a slug sync cannot write as it stands (capital letters, from a gbrain that predates lowercase slugs; the importer lowercases), rather than creating a second page beside it; with `sync.holds=fail` the run stops with `page_identity_changed`. Twins an older sync already created are not merged by this. | Ask the user which page is the file's (`gbrain sync status --source <source> --json` names every candidate slug). Remove each other one with `gbrain delete --source <source> -- '<slug>'` (soft delete, recoverable for 72 h), or rename the file if none of them is its page; with one match under a slug with capitals, which no command can address yet, keep the file held or rename it to a name that folds to another slug (it then imports as a new page beside the old one, which keeps its links). Then `gbrain sync --source <source> --no-pull`. The hold re-screens on every sync. |+| <a id="legacy_slug_conflict"></a><a id="legacy_slug_conflict-explicit_id_conflict"></a>`legacy_slug_conflict` (`explicit_id_conflict`) | The file has no page at its slug, and several live pages an older gbrain imported before the current slug fold (a space, an emoji, an accent or a trailing dash in the slug; no recorded file) fold to that slug (#6727). Exactly one such page is taken over by the file: the next sync imports into it (same page id, links, timeline and aliases) and records the file as its origin, instead of creating a second page. With several, sync cannot tell which page is the file's, so it holds the file and the rest of the source syncs. It holds the file the same way when the one match has a slug sync cannot write as it stands (capital letters, from a gbrain that predates lowercase slugs; the importer lowercases), rather than creating a second page beside it. With reason `explicit_id_conflict` (#6729), the one match carries an explicit frontmatter `id` that differs from the file's, so it is a different document and is not taken over. With `sync.holds=fail` the run stops with `page_identity_changed`. Twins an older sync already created are not merged by this. | Ask the user which page is the file's (`gbrain sync status --source <source> --json` names every candidate slug). Remove each other one with `gbrain delete --source <source> -- '<slug>'` (soft delete, recoverable for 72 h), or rename the file if none of them is its page; with one match under a slug with capitals, which no command can address yet, keep the file held or rename it to a name that folds to another slug (it then imports as a new page beside the old one, which keeps its links). For `explicit_id_conflict`: give the file the page's `id` if it is the same document; otherwise rename the file or delete the old page. Then `gbrain sync --source <source> --no-pull`. The hold re-screens on every sync. || <a id="rename_held"></a><a id="rename_held-rename_source_changed"></a>`rename_held` (`rename_source_changed`) | A renamed file's hold cleared, but the page it was renamed from changed after the rename was recorded, so the page did not move. | `gbrain repair frontmatter --source <source> --include-ambiguous` proposes re-binding the rename to the old page's current revision; apply after the user agrees. Or restore the old file name. || <a id="concurrent_write"></a>`concurrent_write` | Managed sync was importing a newer Git version of the file while a database-only write (write-through off, a sandboxed or derived write) committed a different version of the same page, so the two diverge (#6194). The proof is the page's revision itself: it was written by a committed non-sync request for that page. Neither version was overwritten: the page keeps the database version, the file is held and the rest of the source syncs. Since #6340 a page that moved with no such request to name is held the same way (the hold records `page_revision` and `expected_revision` instead of a competing request), and so is a page that changed, was deleted or was re-bound in the database between the manifest freeze and the entry's turn; a page that still holds exactly what the file would import is re-bound to its new revision and passed. | `gbrain sources status <source>` names the page and the competing request. Preview with `gbrain sources reconcile <source> <slug> --preview`, decide with the user which content wins, apply the resolved preview, then `gbrain sources retry-held <source>` and `gbrain sync --source <source> --no-pull` re-screen the file. A new commit of the file re-screens it too. || <a id="file_drift"></a>`file_drift` | Managed sync would have imported a file over a database version of its page that sync never saw (#6712). Every import records its provenance (the bytes left on disk, the page revision it wrote, the parser); a page that moved since that record (a database-only write, write-through off) while its file did not change, or, in a tree walk (first sync, `--full`, an unreachable checkpoint), a page whose file and revision both moved or that has no usable record (an upgraded brain: none, a pre-PR 0 record, a partial one), is imported only when the import changes nothing, a sync request wrote its current revision, or its writer's write-through wrote that revision to the file. Otherwise the file is held, the page keeps the database version and the rest of the source syncs. The hold names `sides` (`database`, `both`, `unknown`) and the database request that wrote the page when there was one. Pages under `storage.keep_db` prefixes are never held: the entry is skipped and the keep_db worker reconciles the page from the database. Holds of this code never escalate; with `sync.holds=fail` the run stops with `file_drift` instead of holding. | `gbrain sources status <source>` names the page. Preview `gbrain repair file-drift --source <source> --slug <slug> --prefer database` (keep the database copy, rewrite the file) or `--prefer file` (import the file), decide with the user, apply it with the plan hash, then `gbrain sync --source <source> --no-pull`. A changed file or page revision re-screens the hold by itself. |diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.tsindex f07b20a9ab..e3a26505f6 100644--- a/src/core/persistence/sync-discovery.ts+++ b/src/core/persistence/sync-discovery.ts@@ -47,7 +47,9 @@ export interface SyncEntry { path: string; sourcePath: string; action: 'import'/** #6712 PR 1: the page moved since its last recorded import (or has no record); imported only when the freeze proves it a no-op, else held `file_drift`. */drift?: SyncDriftSide;/** #6727: live pages with no recorded origin whose slugs fold to this file's slug, several or one the importer cannot write; the freeze holds it `legacy_slug_conflict`. */- legacySlugs?: string[]; }+ legacySlugs?: string[];+ /** #6729 x #6727: the one legacy page carries an explicit frontmatter id that differs from the file's, so it is another document; held `legacy_slug_conflict` (`explicit_id_conflict`). */+ legacyIdVeto?: true; }/** Files that map to a slug another origin keeps; they are left out of the manifest until one is renamed. */export interface SyncSlugCollision { slug: string; kept: string; skipped: string[]; }/** #5032: a file sync skipped on this host with a named refusal, without failing the run. */@@ -486,7 +488,7 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, cif (!slug) throw opError('invalid_params', 'The imported file has no usable page slug.',`${entry.sourcePath} in ${sourceId} yields no page slug from its path or frontmatter; nothing was written. Rename the file or set a frontmatter slug and commit, then run gbrain sync --no-pull --source ${sourceId}.`);if (!company && entry.action === 'import' && !origin && !isCodeFilePath(entry.sourcePath)) {- slug = await adoptLegacyPage(engine, identities, bySlug.get(slug), slug, entry);+ slug = await adoptLegacyPage(engine, discovered, identities, bySlug.get(slug), slug, entry);entry.slug = slug;claims.set(slug, [...(claims.get(slug) ?? []), entry]);continue;@@ -572,7 +574,7 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c}return discovered;}-type LegacyIdentity = { id: number; slug: string; source_path: string | null; deleted_at: Date | string | null };+type LegacyIdentity = { id: number; slug: string; source_path: string | null; deleted_at: Date | string | null; fm_id: string | null };/*** #6727: per discovery, its live pages with no recorded origin whose slug the current fold changes, by folded slug. Built on* first need; database-only pages (never imported from a file) are left out by one read over just those candidates, so a@@ -590,15 +592,19 @@ async function foldLegacyPages(engine: BrainEngine, identities: LegacyIdentity[]* #6727: the slug a file with no recorded origin imports as. With no live page at its folded slug, exactly one legacy page* (an older gbrain imported it before the current fold) folding to it is the file's: it imports into that page (same id,* links and history). Several, or one whose slug the importer cannot write as it stands (`validateSlug` lowercases), keep- * the folded slug and are named on the entry, so the freeze holds the file `legacy_slug_conflict`.+ * the folded slug and are named on the entry, so the freeze holds the file `legacy_slug_conflict`. #6729: so does the one+ * page when its explicit frontmatter id differs from the file's (`explicitIdVeto`): it is another document.*/-async function adoptLegacyPage(engine: BrainEngine, identities: LegacyIdentity[], holder: LegacyIdentity | undefined, slug: string, entry: SyncEntry): Promise<string> {+async function adoptLegacyPage(engine: BrainEngine, discovery: SyncDiscovery, identities: LegacyIdentity[], holder: LegacyIdentity | undefined, slug: string, entry: SyncEntry): Promise<string> {if (holder && holder.deleted_at == null) return slug;let folded = legacyByFold.get(identities);if (!folded) legacyByFold.set(identities, folded = foldLegacyPages(engine, identities));const legacy = (await folded).get(slug) ?? [];const writable = () => { try { return validateSlug(legacy[0]!) === legacy[0]; } catch { return false; } };- if (legacy.length === 1 && writable()) return legacy[0]!;+ const legacyId = legacy.length === 1 ? identities.find(page => page.slug === legacy[0] && page.deleted_at == null)?.fm_id ?? null : null;+ const vetoed = legacyId !== null && explicitIdVeto(incomingId(discovery, entry), legacyId);+ if (legacy.length === 1 && writable() && !vetoed) return legacy[0]!;+ if (vetoed) entry.legacyIdVeto = true;if (legacy.length) entry.legacySlugs = [...legacy].sort();return slug;}diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.tsindex 8793d8053e..fe8e42b115 100644--- a/src/core/persistence/sync-holds.ts+++ b/src/core/persistence/sync-holds.ts@@ -82,7 +82,7 @@ export interface PreparationStallMeta {/** The `gbrain sync` arguments that resume the cursor with its stored options (after `sources retry-held`). */sync_argv: string[];}-export type GitHoldReason = InvalidFrontmatterReason | 'rename_source_changed' | FenceReason;+export type GitHoldReason = InvalidFrontmatterReason | 'rename_source_changed' | 'explicit_id_conflict' | FenceReason;export interface GitHoldMeta {reason?: GitHoldReason;@@ -669,8 +669,11 @@ export function gitHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'ccase 'legacy_slug_conflict': {const slugs = record.meta.legacy_slugs ?? [];const verify = { argv: ['gbrain', 'sources', 'status', source, '--json'] };- return { argv: verify.argv, consent: [], actor: 'user', requires_exclusive: false, docs: 'docs/guides/write-refusals.md#legacy_slug_conflict',- user_message: slugs.length > 1+ return { argv: verify.argv, consent: [], actor: 'user', requires_exclusive: false, docs: gitHoldDocs(record.code, record.meta.reason),+ user_message: record.meta.reason === 'explicit_id_conflict'+ ? `${record.path} folds to page ${JSON.stringify(slugs[0] ?? '')}, which an older gbrain imported without recording its file, but the file's frontmatter id differs from that page's, so it is a different document and sync held it rather than give it that page's facts, links and history. `+ + `If it is the same document, give the file the page's id; if not, rename the file to a name that folds to another slug (it imports as a new page), or remove the old page with gbrain delete --source ${source} -- '${slugs[0] ?? '<slug>'}' (recoverable for 72 h); then run gbrain sync --source ${source} --no-pull.`+ : slugs.length > 1? `${record.path} belongs to one of the pages ${slugs.map(slug => JSON.stringify(slug)).join(', ')}, which an older gbrain imported without recording their file, so sync held it rather than guess or create another page. `+ `Pick the page that is this file's and remove each other one with gbrain delete --source ${source} -- '<slug>' (recoverable for 72 h), or rename the file if none of them is its page, then run gbrain sync --source ${source} --no-pull.`: `${record.path} matches page ${JSON.stringify(slugs[0] ?? '')}, which an older gbrain imported without recording its file under a slug with capitals that sync cannot write and no gbrain command can address yet, so sync held the file rather than create a second page. `diff --git a/src/core/persistence/sync-screen.ts b/src/core/persistence/sync-screen.tsindex 13a7c3f237..077e7f3cc1 100644--- a/src/core/persistence/sync-screen.ts+++ b/src/core/persistence/sync-screen.ts@@ -249,6 +249,11 @@ export async function screenFrozenImport(engine: BrainEngine, input: FrozenImporif (entry.renameHeld) {return heldEntry(entry, slug, pageId, { code: 'rename_held', reason: 'rename_source_changed', message: `${entry.path} is a rename of page ${entry.renameHeld.slug}, which changed after the rename was recorded, so the page was not moved.` }, content, blob);}+ if (entry.legacySlugs?.length && entry.legacyIdVeto) {+ const held = heldEntry(entry, slug, pageId, { code: 'legacy_slug_conflict', reason: 'explicit_id_conflict', message: `${entry.path} imports as page ${slug}, but page ${entry.legacySlugs[0]}, which an older gbrain imported from a file of that name `+ + `and records no file, has a frontmatter id that differs from the file's, so it is a different document and sync held the file instead of taking that page over.` }, content, blob);+ return { ...held, meta: { ...held.meta, legacy_slugs: entry.legacySlugs } };+ }if (entry.legacySlugs?.length) {const [only, several] = [entry.legacySlugs[0], entry.legacySlugs.length > 1];const held = heldEntry(entry, slug, pageId, { code: 'legacy_slug_conflict', message: `${entry.path} imports as page ${slug}, but ${several ? `pages ${entry.legacySlugs.join(', ')}` : `page ${only}`}, which an older gbrain imported from a file of that name, `diff --git a/test/sync-legacy-slug-adoption-6727.test.ts b/test/sync-legacy-slug-adoption-6727.test.tsindex 05b807d018..8a31ece871 100644--- a/test/sync-legacy-slug-adoption-6727.test.ts+++ b/test/sync-legacy-slug-adoption-6727.test.ts@@ -152,6 +152,23 @@ test('#6727 a database-only page (never imported from a file) is not taken overexpect((await s.pages()).map(page => [page.slug, page.source_path])).toEqual([['notes/foo bar', null], ['notes/foo-bar', 'notes/Foo Bar.md']]);}), 180_000);+test('#6729 x #6727 a legacy page whose explicit frontmatter id differs from the file\'s is not taken over; the file is held', () => each(async engine => {+ const s = await legacySource(engine, { 'notes/Foo Bar.md': '---\ntitle: Foo Bar\nid: doc-a\n---\nA synthetic observation.\n' });+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw(`UPDATE pages SET frontmatter=frontmatter || '{"id":"doc-b"}'::jsonb WHERE source_id=$1`, [s.id]);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ await s.sync();+ const holds = (await readGitSourceHolds(engine, { sourceIds: [s.id] }))[0]?.holds ?? [];+ expect(holds.map(hold => ({ path: hold.path, code: hold.code, reason: hold.meta.reason, slugs: hold.meta.legacy_slugs })))+ .toEqual([{ path: 'notes/Foo Bar.md', code: 'legacy_slug_conflict', reason: 'explicit_id_conflict', slugs: ['notes/foo bar'] }]);+ expect((await s.pages()).map(page => [page.slug, page.source_path, Number(page.id)])).toEqual([['notes/foo bar', null, s.ids.get('notes/foo bar')!]]);+ writeFileSync(join(s.root, 'notes/Foo Bar.md'), '---\ntitle: Foo Bar\nid: doc-b\n---\nA synthetic observation.\n');+ git(s.root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qam', 'same id');+ await s.sync();+ expect(await s.held()).toEqual([]);+ expect((await s.pages()).map(page => [page.slug, page.source_path, Number(page.id)])).toEqual([['notes/foo bar', 'notes/Foo Bar.md', s.ids.get('notes/foo bar')!]]);+}), 180_000);+test('#6727 with sync.holds=fail the ambiguous file stops the run instead of creating a page', () => each(async engine => {const s = await legacySource(engine, { 'notes/Foo Bar.md': note('Foo Bar') }, ['notes/foo bar']);await engine.setConfig('sync.holds', 'fail');