Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sync): #6729 the report and doctor offer the restore only where the source admits it (not on an unbound Postgres source); Postgres fixture for the hold
garrytan71cfb9c678f8
diff --git a/.wave18-fragments/lane2-s1.md b/.wave18-fragments/lane2-s1.mdindex e3d6cc56c0..17587982d7 100644--- a/.wave18-fragments/lane2-s1.md+++ b/.wave18-fragments/lane2-s1.md@@ -29,7 +29,7 @@ The remedy repair kind is not in S1: it lands in its own commit after the S1 SHA### KEY_FILES (`docs/architecture/key-files/files-and-sync-*.md`, `commands-*.md`)- `src/core/sync-rename-identity.ts`: the one confirmation stage for inexact Git renames (#6729). `confirmRenameIdentities` reads committed sides through one `git cat-file --batch` stream (64 KiB heads) and the dirty tree's working side from disk, with id and `slug:` from the frontmatter and the title by parseMarkdown precedence (frontmatter, then the first H1, no filename fallback; `markdown.ts` `explicitMarkdownTitle`), the old side taking the title its page row stores; it keeps an R<100 pair on a same-slug respelling, a unique shared `id`, or with no id on either side a unique `slug:` line or title (titles also unique among live pages). `explicitIdVeto` is the one explicit-id veto the managed takeovers consult. An add whose id uniquely matches a delete in the range becomes a rename only with continuity (same file name, title or bytes; `digest` is the sha256 of a file that fits the head read), as decideImportIdentity asks of a move. Downgraded pairs record `read.from` / `read.to`. A dirty-tree verdict is bound to the bytes it read: each kept rename carries `identityHead` (sha256 of the first 64 KiB), classic `applyRename` re-checks it before the identity moves and managed `readSyncContent` refuses `source_changed` on frozen bytes that differ.-- `src/core/sync-identity-downgrades.ts`: durable records of downgraded pairs (`op_checkpoints` op `sync-identity-downgrade`, fingerprint = old page id, open until a disposition is set or the old page is restored or purged; no time window; the checkpoint sweep keeps open records), the purge-hold SQL predicate, the live list (new slug read live), the report lines and the restore argv.+- `src/core/sync-identity-downgrades.ts`: durable records of downgraded pairs (`op_checkpoints` op `sync-identity-downgrade`, fingerprint = old page id, open until a disposition is set or the old page is restored or purged; no time window; the checkpoint sweep keeps open records), the purge-hold SQL predicate, the live list (new slug read live), the report lines and the restore argv; `identityRestoreAvailable` (the decideUnboundWrite rule) keeps the restore off the report and doctor on an unbound Postgres source with a checkout, where it would refuse `owner_unavailable`.- `src/commands/doctor/checks/rename-identity-downgrades.ts`: doctor `rename_identity_downgrades` (warn while a record is open; fix = restore the first old page, behind ask_user).### Tests that changed for the intended behaviourdiff --git a/docs/guides/live-sync.md b/docs/guides/live-sync.mdindex 874bdfed79..ca0bbf3f37 100644--- a/docs/guides/live-sync.md+++ b/docs/guides/live-sync.md@@ -356,7 +356,8 @@ until the pair gets a disposition; there is no time limit, so a pair can stillbe repaired later. Restoring the old page settles it: run`gbrain restore <old-slug> --source-id <id> --force` (it then lives beside thenew page; where the old file cannot be re-created the restore names-`--detach`). To move and rewrite a page so it keeps its identity, give it a+`--detach`). An unbound classic source on Postgres refuses page writes outside+its checkout, so the report and doctor do not offer the restore there. To move and rewrite a page so it keeps its identity, give it astable id or move, commit and sync first, then edit:```yamldiff --git a/src/commands/doctor/checks/rename-identity-downgrades.ts b/src/commands/doctor/checks/rename-identity-downgrades.tsindex bb500b285e..7ab5888ee4 100644--- a/src/commands/doctor/checks/rename-identity-downgrades.ts+++ b/src/commands/doctor/checks/rename-identity-downgrades.ts@@ -25,16 +25,19 @@ async function runRenameIdentityDowngrades(ctx: DoctorContext): Promise<Check[]>checks.push({ name: 'rename_identity_downgrades', status: 'ok', details, message: 'No rename that lost its page identity is waiting for a disposition.' });return checks;}- const first = open[0]!;- checks.push({ name: 'rename_identity_downgrades', status: 'warn', details,+ const first = open[0]!, restorable = open.find(record => record.restore_available !== false);+ const unrestorable = [...new Set(open.filter(record => record.restore_available === false).map(record => record.source_id))];+ checks.push({ name: 'rename_identity_downgrades', status: 'warn', details: { ...details, restore_unavailable_sources: unrestorable },message: `${open.length} rename(s) did not keep their page identity, so each old page's facts, links and aliases stay on its soft-deleted slug, held from the purge until the pair is settled `+ `(e.g. ${samples.map(record => `${record.source_id}:${record.from} -> ${record.to}, ${record.facts} fact(s) and ${record.links} link(s) on ${record.old_slug}`).join('; ')}; `- + `first: ${identityDowngradeReasonText(first.reason)}). ${identityStatusArgv(first.source_id).join(' ')} lists every pair. To keep an old page, restore it; `+ + `first: ${identityDowngradeReasonText(first.reason)}). ${identityStatusArgv(first.source_id).join(' ')} lists every pair. `+ + (restorable ? 'To keep an old page, restore it; ' : '')+ + (unrestorable.length ? `A restore is not offered on ${unrestorable.join(', ')} (an unbound Postgres source refuses page writes outside its checkout); those pairs wait for a disposition. ` : '')+ 'until a pair is restored or settled, its old page stays and this check names it.',- fix: agentFix(identityRestoreArgv(first),- `Restores ${first.old_slug} with its facts, links and aliases, beside ${first.new_slug ?? 'the new file'}; the record closes and the purge no longer waits for it.`,+ ...(restorable ? { fix: agentFix(identityRestoreArgv(restorable),+ `Restores ${restorable.old_slug} with its facts, links and aliases, beside ${restorable.new_slug ?? 'the new file'}; the record closes and the purge no longer waits for it.`,'rename_identity_downgrades', { docs: DOCS, ask_user: true,- user_message: `Sync did not keep the identity of ${first.old_slug} when ${first.from} became ${first.to}. Restore ${first.old_slug} as its own page so its ${first.facts} fact(s) and ${first.links} link(s) stay live?` }) });+ user_message: `Sync did not keep the identity of ${restorable.old_slug} when ${restorable.from} became ${restorable.to}. Restore ${restorable.old_slug} as its own page so its ${restorable.facts} fact(s) and ${restorable.links} link(s) stay live?` }) } : {}) });} catch (error) {checks.push(checkError('rename_identity_downgrades', 'read the renames whose identity was not kept', error, { details: { count: 'unknown', docs: DOCS } }));}diff --git a/src/core/sync-identity-downgrades.ts b/src/core/sync-identity-downgrades.tsindex 2240a7999d..8370a433d1 100644--- a/src/core/sync-identity-downgrades.ts+++ b/src/core/sync-identity-downgrades.ts@@ -11,6 +11,9 @@* a restore, a purge or a later delete of the restored page closes it.*/import type { BrainEngine } from './engine.ts';+import { isConnectorSourceKind } from './persistence/connector-identity.ts';+import { getWorktreeBinding } from './persistence/ownership.ts';+import { readDatabaseOnlyActivatedSources } from './persistence/unbound-source.ts';import { resolveSlugForPath, type DowngradedRename, type RenameDowngradeReason } from './sync.ts';export const IDENTITY_DOWNGRADE_OP = 'sync-identity-downgrade';@@ -25,6 +28,23 @@ export interface IdentityDowngrade extends DowngradedRename {recorded_at: string; old_deleted_at: string;/** Set when the pair is remedied or closed without merging; the record is then closed. */disposition?: { kind: 'remedied' | 'closed'; at: string };+ /** Read live: whether `gbrain restore` can write the old page back on this source (see `identityRestoreAvailable`). */+ restore_available?: boolean;+}++type RestoreProbeEngine = Pick<BrainEngine, 'executeRaw' | 'getConfig' | 'kind'>;++/**+ * Whether a restore of a page that came from a canonical file can be admitted on this source, by the rule page writes+ * follow (decideUnboundWrite): a bound source, a connector source, a source with no checkout, or a PGLite source not+ * activated database-only can; an unbound Postgres source with a checkout refuses `owner_unavailable`, so no surface+ * offers the restore there.+ */+export async function identityRestoreAvailable(engine: RestoreProbeEngine, sourceId: string): Promise<boolean> {+ const [source] = await engine.executeRaw<{ local_path: string | null; kind: string | null }>("SELECT local_path, config->>'kind' AS kind FROM sources WHERE id = $1", [sourceId]);+ if (!source?.local_path || isConnectorSourceKind(source.kind)) return true;+ if (await getWorktreeBinding(engine as never, sourceId, null)) return true;+ return engine.kind === 'pglite' && !(await readDatabaseOnlyActivatedSources(engine)).includes(sourceId);}/** SQL: the downgrade record `dg` is open for the page aliased `alias` (no disposition, old page still soft-deleted by that sync). */@@ -82,14 +102,17 @@ export async function recordIdentityDowngrades(engine: BrainEngine, sourceId: st* Open records (no disposition, old page still soft-deleted by that sync), oldest first; every source when `sourceIds` is omitted.* `new_slug` is read live: the live page at the new path now (a held new file that was fixed later counts once it imports).*/-export async function listIdentityDowngrades(engine: Pick<BrainEngine, 'executeRaw'>, sourceIds?: readonly string[]): Promise<IdentityDowngrade[]> {+export async function listIdentityDowngrades(engine: RestoreProbeEngine, sourceIds?: readonly string[]): Promise<IdentityDowngrade[]> {const rows = await engine.executeRaw<{ record: IdentityDowngrade | string; new_slug: string | null }>(`SELECT dg.completed_keys->0 AS record, np.slug AS new_slug FROM op_checkpoints dg JOIN pages p ON p.id::text = dg.fingerprintLEFT JOIN LATERAL (SELECT slug FROM pages WHERE source_id = p.source_id AND deleted_at IS NULL AND source_path = dg.completed_keys->0->>'to' LIMIT 1) np ON trueWHERE dg.op = $1 AND p.deleted_at IS NOT NULL AND ${identityDowngradeOpen('p')}AND p.source_id = dg.completed_keys->0->>'source_id' AND ($2::text[] IS NULL OR p.source_id = ANY($2::text[]))ORDER BY dg.completed_keys->0->>'recorded_at', dg.fingerprint`, [IDENTITY_DOWNGRADE_OP, sourceIds ? [...sourceIds] : null]);- return rows.map(row => ({ ...(typeof row.record === 'string' ? JSON.parse(row.record) as IdentityDowngrade : row.record), new_slug: row.new_slug }));+ const records = rows.map(row => ({ ...(typeof row.record === 'string' ? JSON.parse(row.record) as IdentityDowngrade : row.record), new_slug: row.new_slug }));+ const restorable = new Map<string, boolean>();+ for (const sourceId of new Set(records.map(record => record.source_id))) restorable.set(sourceId, await identityRestoreAvailable(engine, sourceId));+ return records.map(record => ({ ...record, restore_available: restorable.get(record.source_id)! }));}/** A recorded downgrade (as opposed to a raw pair a sync has not recorded yet). */@@ -106,7 +129,8 @@ export async function noteIdentityDowngrades<T extends { status: string; identitif (!pairs.length || !['synced', 'first_sync'].includes(result.status)) return result;try {const records = await recordIdentityDowngrades(engine, sourceId, pairs);- for (const line of identityDowngradeLines(records)) write(line);+ const restore_available = await identityRestoreAvailable(engine, sourceId);+ for (const line of identityDowngradeLines(records.map(record => ({ ...record, restore_available })))) write(line);return { ...result, identityDowngrades: records };} catch (error) {write(` Could not record ${pairs.length} rename(s) whose identity was not kept: ${error instanceof Error ? error.message : String(error)}`);@@ -129,7 +153,8 @@ export function identityDowngradeLines(records: readonly IdentityDowngrade[]): sreturn [...records.map(record => ` Identity not kept: ${record.from} -> ${record.to} (git similarity ${record.similarity}%; ${REASON_TEXT[record.reason]}). `+ `${record.facts} fact(s), ${record.links} link(s) and ${record.aliases} alias(es) stay on the soft-deleted ${record.old_slug}, which the purge keeps until the pair is settled; `- + `${record.new_slug ? `${record.new_slug} starts fresh.` : 'the new file did not import.'} To keep the old page, restore it: ${identityRestoreArgv(record).join(' ')}`),+ + `${record.new_slug ? `${record.new_slug} starts fresh.` : 'the new file did not import.'}`+ + (record.restore_available === false ? '' : ` To keep the old page, restore it: ${identityRestoreArgv(record).join(' ')}`)),' A move keeps its page when the files share a frontmatter id: (or a unique slug: line or title); to move and rewrite a page, move, commit and sync, then edit.',];}diff --git a/test/sync-inexact-rename-6729.test.ts b/test/sync-inexact-rename-6729.test.tsindex cbc26970d1..f1b20dafe7 100644--- a/test/sync-inexact-rename-6729.test.ts+++ b/test/sync-inexact-rename-6729.test.ts@@ -114,11 +114,26 @@ for (const kind of testBackends()) describe(`inexact Git rename identity (#6729,// Doctor names them; the fix restores the first old page once the user asks (ask_user), and verify clears it.const { renameIdentityDowngradesEntry } = await import('../src/commands/doctor/checks/rename-identity-downgrades.ts');- const doctor = async () => (await renameIdentityDowngradesEntry.run({ engine } as unknown as DoctorContext)) as unknown as Array<{ status: string; details: { count: number; by_source: Array<{ source_id: string; count: number }> }; fix?: Record<string, unknown> & { argv: string[]; verify: { argv: string[] } } }>;+ const doctor = async () => (await renameIdentityDowngradesEntry.run({ engine } as unknown as DoctorContext)) as unknown as Array<{ status: string; details: { count: number; by_source: Array<{ source_id: string; count: number }>; restore_unavailable_sources?: string[] }; fix?: Record<string, unknown> & { argv: string[]; verify: { argv: string[] } } }>;const mine = (finding: Awaited<ReturnType<typeof doctor>>[number]) => finding.details.by_source.find(entry => entry.source_id === s.id)?.count ?? 0;const [finding] = await doctor();expect(finding!.status).toBe('warn');expect(mine(finding!)).toBe(2);+ const { purgeStaleCheckpoints } = await import('../src/core/op-checkpoint.ts');+ const age = () => engine.executeRaw("UPDATE op_checkpoints SET updated_at = now() - interval '30 days' WHERE op = 'sync-identity-downgrade' AND fingerprint = ANY($1::text[])", [[String(a.id), String(b.id)]]);+ const close = (id: number) => engine.executeRaw("UPDATE op_checkpoints SET completed_keys = jsonb_set(completed_keys, '{0,disposition}', jsonb_build_object('kind', 'closed', 'at', now()::text)) WHERE op = 'sync-identity-downgrade' AND fingerprint = $1", [String(id)]);+ if (kind === 'postgres') {+ // An unbound classic Postgres source refuses page writes outside its checkout, so no surface offers the restore+ // there; the pairs still hold their old pages, with no time window, until a disposition.+ expect(finding!.fix).toBeUndefined();+ expect(finding!.details.restore_unavailable_sources).toContain(s.id);+ await age(); await purgeStaleCheckpoints(engine);+ expect((await purgeDeletedPagesCoordinated(engine, 0)).slugs.filter(slug => slug.endsWith('-x-com'))).toEqual([]);+ await close(a.id);+ expect(mine((await doctor())[0]!)).toBe(1);+ expect((await purgeDeletedPagesCoordinated(engine, 0)).slugs).toContain('people/a-x-com');+ return;+ }const [, , slug, , sourceId] = finding!.fix!.argv;const restored = { 'people/a-x-com': { id: a.id, fact: 'A works on payments', alias: 'ali' }, 'people/b-x-com': { id: b.id, fact: 'B works on search', alias: 'bea' } }[slug!]!;const other = slug === 'people/a-x-com' ? { slug: 'people/b-x-com', id: b.id } : { slug: 'people/a-x-com', id: a.id };@@ -137,15 +152,13 @@ for (const kind of testBackends()) describe(`inexact Git rename identity (#6729,expect((await pageRow(s.id, other.slug))!.deleted_at).not.toBeNull();// No time window: a month-old open record survives the checkpoint sweep and still holds its old page, and doctor// still names it; only a disposition releases it. A restored page deleted again later is not held by its old record.- await engine.executeRaw("UPDATE op_checkpoints SET updated_at = now() - interval '30 days' WHERE op = 'sync-identity-downgrade' AND fingerprint = ANY($1::text[])", [[String(a.id), String(b.id)]]);- const { purgeStaleCheckpoints } = await import('../src/core/op-checkpoint.ts');- await purgeStaleCheckpoints(engine);+ await age(); await purgeStaleCheckpoints(engine);expect((await purgeDeletedPagesCoordinated(engine, 0)).slugs).not.toContain(other.slug);expect(mine((await doctor())[0]!)).toBe(1);await engine.softDeletePage(slug!, { sourceId: s.id });expect((await purgeDeletedPagesCoordinated(engine, 0)).slugs).toContain(slug);expect((await engine.executeRaw('SELECT fingerprint FROM op_checkpoints WHERE op = $1 AND fingerprint = ANY($2::text[])', ['sync-identity-downgrade', [String(a.id), String(b.id)]])).map(row => (row as { fingerprint: string }).fingerprint)).toEqual([String(other.id)]);- await engine.executeRaw("UPDATE op_checkpoints SET completed_keys = jsonb_set(completed_keys, '{0,disposition}', jsonb_build_object('kind', 'closed', 'at', now()::text)) WHERE op = 'sync-identity-downgrade' AND fingerprint = $1", [String(other.id)]);+ await close(other.id);expect(mine((await doctor())[0]!)).toBe(0);expect((await purgeDeletedPagesCoordinated(engine, 0)).slugs).toContain(other.slug);}), 180_000);