Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(sync): every #6729 downgrade surface names its per-pair rename-identity remedy (#6729)

garrytan2d4344db100b
diff --git a/src/commands/doctor/checks/rename-identity-downgrades.ts b/src/commands/doctor/checks/rename-identity-downgrades.ts
index 7ab5888ee4..2708a7ee14 100644
--- a/src/commands/doctor/checks/rename-identity-downgrades.ts
+++ b/src/commands/doctor/checks/rename-identity-downgrades.ts
@@ -2,13 +2,15 @@
* #6729 `rename_identity_downgrades`: inexact Git renames a sync split into a delete plus an add because their identity
* could not be confirmed (sync-rename-identity.ts). Each old page keeps its facts, links and aliases on its soft-deleted
* slug, and the purge leaves it alone until the pair gets a disposition (restored, remedied or closed without merging);
- * there is no time window. The finding names every open pair until then; its fix restores the first old page (with its
- * facts, links and aliases, beside the new page) once the user asks to keep it.
+ * there is no time window. The finding names every open pair with its remedy; its fix is the first pair's
+ * `gbrain repair rename-identity` apply (preview first, bound to the plan hash, destructive consent, behind ask_user;
+ * `--close` on a managed brain). Restoring the old page is the alternative its text names wherever the source admits a
+ * restore (`restore_available`); details list the sources that do not. With no open record the check is ok.
*/
import type { Check } from '../../doctor.ts';
import { agentFix, checkError } from '../check-fix.ts';
import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
-import { identityDowngradeReasonText, identityRestoreArgv, identityStatusArgv, listIdentityDowngrades } from '../../../core/sync-identity-downgrades.ts';
+import { identityDowngradeReasonText, identityRestoreArgv, identityStatusArgv, listIdentityDowngrades, withIdentityRemedies } from '../../../core/sync-identity-downgrades.ts';
const DOCS = 'docs/guides/live-sync.md#renaming-a-page';
const SAMPLE = 5;
@@ -16,28 +18,43 @@ const SAMPLE = 5;
async function runRenameIdentityDowngrades(ctx: DoctorContext): Promise<Check[]> {
const checks: Check[] = [];
try {
- const open = await listIdentityDowngrades(connectedEngine(ctx));
+ const engine = connectedEngine(ctx);
+ const open = await listIdentityDowngrades(engine);
const bySource = [...new Set(open.map(record => record.source_id))].map(source_id => ({ source_id, count: open.filter(record => record.source_id === source_id).length }));
- const samples = open.slice(0, SAMPLE).map(record => ({ source_id: record.source_id, from: record.from, to: record.to, old_slug: record.old_slug, new_slug: record.new_slug,
- reason: record.reason, facts: record.facts, links: record.links, aliases: record.aliases, recorded_at: record.recorded_at }));
+ const sampled = await withIdentityRemedies(engine, open.slice(0, SAMPLE));
+ const samples = sampled.map(record => ({ source_id: record.source_id, from: record.from, to: record.to, old_slug: record.old_slug, new_slug: record.new_slug,
+ reason: record.reason, facts: record.facts, links: record.links, aliases: record.aliases, recorded_at: record.recorded_at, remedy: record.remedy }));
const details = { count: open.length, by_source: bySource, samples, docs: DOCS };
if (!open.length) {
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]!, restorable = open.find(record => record.restore_available !== false);
+ const first = sampled[0]!;
const unrestorable = [...new Set(open.filter(record => record.restore_available === false).map(record => record.source_id))];
+ const restore = first.restore_available === false ? null : identityRestoreArgv(first).join(' ');
+ const carry = first.remedy.disposition === 'carry';
+ const route = carry
+ ? `To carry an old page's identity onto its new page, preview ${first.remedy.preview_argv.join(' ')} and, after the user agrees, apply it. `
+ : first.remedy.carry_unavailable
+ ? `Carrying identity is unavailable on a managed source (${first.remedy.carry_unavailable}); to release the purge hold without carrying it, preview ${first.remedy.preview_argv.join(' ')} and, after the user agrees, apply it. `
+ : `The new file did not import; to release the purge hold, preview ${first.remedy.preview_argv.join(' ')} and, after the user agrees, apply it. `;
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. `
- + (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.',
- ...(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 ${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?` }) } : {}) });
+ + `first: ${identityDowngradeReasonText(first.reason)}). ${identityStatusArgv(first.source_id).join(' ')} lists every pair with its remedy. ${route}`
+ + (restore ? `To keep the old page as its own page instead: ${restore}. ` : '')
+ + (unrestorable.length ? `A restore is not offered on ${unrestorable.join(', ')} (an unbound Postgres source refuses page writes outside its checkout). ` : '')
+ + `The purge holds each old page until ${first.remedy.hold_releases}.`,
+ fix: agentFix(first.remedy.argv,
+ (carry
+ ? `Carries ${first.old_slug}'s page identity (version history, timeline, links, facts and aliases) onto ${first.new_slug}, applies the new file as an edit and retires the provisional page; the pair settles. Preview first.`
+ : `Closes the pair of ${first.old_slug} without carrying its identity${first.remedy.carry_unavailable ? ` (carrying is unavailable on a managed source: ${first.remedy.carry_unavailable})` : ''}, so the purge no longer waits for it; nothing moves. Preview first.`)
+ + (restore ? ` The alternative is ${restore}.` : ''),
+ 'rename_identity_downgrades', { docs: DOCS, ask_user: true, consent: ['destructive'], preview_argv: first.remedy.preview_argv, plan_hash: first.remedy.plan_hash,
+ user_message: (carry
+ ? `Sync did not keep the identity of ${first.old_slug} when ${first.from} became ${first.to}. Carry its history, ${first.facts} fact(s) and ${first.links} link(s) onto ${first.new_slug}`
+ : `Sync did not keep the identity of ${first.old_slug} when ${first.from} became ${first.to}${first.remedy.carry_unavailable ? ', and carrying it is unavailable on a managed source' : ', and the new file did not import'}. Release the purge hold so ${first.old_slug} is purged`)
+ + (restore ? ` (or restore it as its own page with ${restore})?` : '?') }) });
} 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/persistence/sync-status.ts b/src/core/persistence/sync-status.ts
index 569c17e9e0..acdbc5ab1e 100644
--- a/src/core/persistence/sync-status.ts
+++ b/src/core/persistence/sync-status.ts
@@ -42,7 +42,7 @@ import { classifyRecordedFault, classifyTerminal, type TerminalCategory } from '
import type { PublicCategory } from './public-category.ts';
import { readSyncFile, resolveManagedSyncContext } from './sync-discovery.ts';
import { sha256 } from './digest.ts';
-import { listIdentityDowngrades } from '../sync-identity-downgrades.ts';
+import { listIdentityDowngrades, withIdentityRemedies } from '../sync-identity-downgrades.ts';
export interface SyncStatusHold extends SyncFaultVerdict {
code: string;
@@ -89,8 +89,12 @@ export interface SyncStatus {
rate_pages_per_min: number | null;
eta_seconds: number | null;
holds: SyncStatusHold[];
- /** #6729: renames whose page identity was not kept and whose pair has no disposition yet (old page soft-deleted with its facts and links, held from the purge; `gbrain restore` keeps one). */
- identity_downgrades: import('../sync-identity-downgrades.ts').IdentityDowngrade[];
+ /**
+ * #6729: renames whose page identity was not kept and whose pair has no disposition yet (old page soft-deleted with its
+ * facts and links, held from the purge), each with its remedy: `gbrain repair rename-identity` preview and apply argv,
+ * consent and when the purge hold releases.
+ */
+ identity_downgrades: import('../sync-identity-downgrades.ts').IdentityDowngradeEntry[];
last_error: SyncStatusError | null;
/** Whether anything (a hold or the last error) waits on a person; the first such reason. */
needs_human: boolean;
@@ -300,7 +304,7 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string, opts
const [state, stateReason] = statusState({ human: !!human, oldest, recovery, liveJob: liveJob !== null, unfinished, lastError: !!lastError, actionable: actionable.length > 0, holds: holds.length > 0 });
return { source_id: sourceId, run_id: header?.runId ?? null,
cursor: header ? { index: Number(header.index), total: Number(header.total), pinned_target: header.target ?? null, last_advance_at: p ? new Date(p.lastAt).toISOString() : null, done: !!header.done } : null,
- committed_last_10m: Number(committed?.n ?? 0), ...estimate, live_job_id: liveJob, holds, identity_downgrades: await listIdentityDowngrades(engine, [sourceId]), last_error: lastError, needs_human: !!human, ...(human ? { human_reason: human.human_reason } : {}),
+ committed_last_10m: Number(committed?.n ?? 0), ...estimate, live_job_id: liveJob, holds, identity_downgrades: await withIdentityRemedies(engine, await listIdentityDowngrades(engine, [sourceId])), last_error: lastError, needs_human: !!human, ...(human ? { human_reason: human.human_reason } : {}),
resume_argv: resume, ...blockers, cursors: detail ? await liveCursors(engine, sourceId, source.incarnation, selected?.key ?? null, failures) : [],
terminal_failures: terminal, connector_last_error: connectorLastError, next: next ?? recovery_next ?? (stateReason === 'request_pending' && oldest.status === 'ok' && oldest.request ? { argv: ['gbrain', 'sync', ...resume], consent: [], actor: 'agent', requires_exclusive: false, verify,
why: `Write request ${oldest.request.request_id} of this source is still ${oldest.request.state}${oldest.request.step ? ` (step ${oldest.request.step})` : ''}; a running owner finishes it on its own, and the next sync of this source drains it.` } satisfies Action
diff --git a/src/core/sync-identity-downgrades.ts b/src/core/sync-identity-downgrades.ts
index 8370a433d1..137c70fe3b 100644
--- a/src/core/sync-identity-downgrades.ts
+++ b/src/core/sync-identity-downgrades.ts
@@ -9,11 +9,17 @@
* `completed_keys[0]` holds the record. A record is open while it has no `disposition` (set when the pair is remedied
* or closed without merging) and its old page is still soft-deleted from that sync (`deleted_at` = `old_deleted_at`);
* a restore, a purge or a later delete of the restored page closes it.
+ *
+ * Every surface names the remedy per pair (`identityRemedy`): the preview `gbrain repair rename-identity --source <id>
+ * --slug <new>`, its apply with the plan hash (destructive consent), and what releases the purge hold. On a managed brain
+ * carrying identity is unavailable (`managed_remedy_unavailable`), so the remedy there is `--close`.
*/
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 { readManagedMode } from './persistence/managed-mode.ts';
+import { previewHash } from './persistence/preview-approval.ts';
import { resolveSlugForPath, type DowngradedRename, type RenameDowngradeReason } from './sync.ts';
export const IDENTITY_DOWNGRADE_OP = 'sync-identity-downgrade';
@@ -115,6 +121,84 @@ export async function listIdentityDowngrades(engine: RestoreProbeEngine, sourceI
return records.map(record => ({ ...record, restore_available: restorable.get(record.source_id)! }));
}
+/** What the remedy does with a pair: carry the old page's identity onto the new slug (default), or close the record. */
+export type IdentityRemedyDisposition = 'carry' | 'close';
+export const IDENTITY_HOLD_RELEASE = 'the remedy carries or closes the pair, or the old page is restored or purged';
+/** A carry is a classic-source maintenance transaction; on a managed brain the remedy can only close the pair. */
+export const MANAGED_REMEDY_UNAVAILABLE = 'managed_remedy_unavailable';
+
+/** One page side of a pair as the remedy binds it: id, slug, revision and whether it is soft-deleted. */
+export interface IdentityRemedySide { page_id: number; slug: string; revision: string; deleted: boolean }
+
+/** The per-pair remedy every surface prints (sync report, `sync status --json`, doctor). */
+export interface IdentityRemedy {
+ /** `carry`, or `close` when the new file did not import or carrying is unavailable. */
+ disposition: IdentityRemedyDisposition;
+ /** `managed_remedy_unavailable` on a managed brain (the pair can only be closed there), else null. */
+ carry_unavailable: typeof MANAGED_REMEDY_UNAVAILABLE | null;
+ plan_hash: string; preview_argv: string[]; argv: string[]; consent: ['destructive'];
+ hold_releases: string;
+}
+
+export type IdentityDowngradeEntry = IdentityDowngrade & { remedy: IdentityRemedy };
+
+async function remedySide(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, where: string, value: string | number): Promise<IdentityRemedySide | null> {
+ const [row] = await engine.executeRaw<{ id: number | string; slug: string; revision: string | null; deleted: boolean }>(
+ `SELECT id, slug, knowledge_revision::text AS revision, deleted_at IS NOT NULL AS deleted FROM pages WHERE source_id = $1 AND ${where} = $2 LIMIT 1`, [sourceId, value]);
+ return row ? { page_id: Number(row.id), slug: row.slug, revision: row.revision ?? '', deleted: row.deleted === true } : null;
+}
+
+/**
+ * The state a remedy preview binds: the brain, the pair, both page ids and revisions, and the disposition. The old page
+ * is read by id (it may have moved since), the new page by its live slug. Every surface hashes these same parts, so the
+ * hash a sync report or doctor prints is the one the preview saves.
+ */
+export async function identityRemedyParts(engine: Pick<BrainEngine, 'executeRaw'>, record: IdentityDowngrade, disposition: IdentityRemedyDisposition) {
+ const [brain] = await engine.executeRaw<{ brain_id: string }>('SELECT brain_id FROM persistence_brain WHERE singleton=1').catch(() => []);
+ const old = await remedySide(engine, record.source_id, 'id', record.old_page_id);
+ const fresh = record.new_slug ? await remedySide(engine, record.source_id, 'slug', record.new_slug) : null;
+ return { kind: 'rename-identity-v1', brain_id: brain?.brain_id ?? 'host', source_id: record.source_id, from: record.from, to: record.to,
+ recorded_at: record.recorded_at, disposition, old, new: fresh && !fresh.deleted ? fresh : null };
+}
+export type IdentityRemedyParts = Awaited<ReturnType<typeof identityRemedyParts>>;
+
+/** `gbrain repair rename-identity --source <id> --slug <new>` (`--from <old>` when another open pair shares the new slug). */
+export function renameIdentityPreviewArgv(record: Pick<IdentityDowngrade, 'source_id' | 'new_slug' | 'old_slug'>, opts: { from?: boolean; close?: boolean } = {}): string[] {
+ return ['gbrain', 'repair', 'rename-identity', '--source', record.source_id, ...(record.new_slug ? ['--slug', record.new_slug] : []),
+ ...(opts.from || !record.new_slug ? ['--from', record.old_slug] : []), ...(opts.close ? ['--close'] : [])];
+}
+
+/** The remedy one pair names: its preview, the apply bound to the current plan hash, consent, and the hold release. */
+export async function identityRemedy(engine: Pick<BrainEngine, 'executeRaw'>, record: IdentityDowngrade, opts: { from?: boolean; managed?: boolean } = {}): Promise<IdentityRemedy> {
+ const close = !!opts.managed || !record.new_slug;
+ const plan_hash = previewHash(await identityRemedyParts(engine, record, close ? 'close' : 'carry'));
+ const preview_argv = renameIdentityPreviewArgv(record, { from: opts.from, close });
+ return { disposition: close ? 'close' : 'carry', carry_unavailable: opts.managed && record.new_slug ? MANAGED_REMEDY_UNAVAILABLE : null,
+ plan_hash, preview_argv, argv: [...preview_argv, '--apply', '--expect', plan_hash, '--yes'], consent: ['destructive'], hold_releases: IDENTITY_HOLD_RELEASE };
+}
+
+/** Each record with its remedy; `--from` is named only where two open pairs share a new slug. */
+export async function withIdentityRemedies(engine: Pick<BrainEngine, 'executeRaw'>, records: readonly IdentityDowngrade[]): Promise<IdentityDowngradeEntry[]> {
+ if (!records.length) return [];
+ const managed = await readManagedMode(engine);
+ const shared = (record: IdentityDowngrade) => records.filter(other => other.source_id === record.source_id && other.new_slug === record.new_slug).length > 1;
+ return Promise.all(records.map(async record => ({ ...record, remedy: await identityRemedy(engine, record, { from: shared(record), managed }) })));
+}
+
+/** How the remedy settled a pair: its identity was carried (`remedied`) or its record closed (`closed`). */
+export type IdentityDowngradeSettlement = 'remedied' | 'closed';
+
+/**
+ * Settles one open record (disposition still unset) with `completed_keys[0].disposition = { kind, at }`, so the purge no
+ * longer waits for its old page and no surface lists it. Returns the rows settled (0 when already settled or gone).
+ */
+export async function settleIdentityDowngrade(engine: Pick<BrainEngine, 'executeRaw'>, oldPageId: number, kind: IdentityDowngradeSettlement): Promise<number> {
+ return (await engine.executeRaw(
+ `UPDATE op_checkpoints SET completed_keys = jsonb_set(completed_keys, '{0,disposition}', jsonb_build_object('kind', $3::text, 'at', $4::text))
+ WHERE op = $1 AND fingerprint = $2 AND completed_keys->0->>'disposition' IS NULL RETURNING 1`,
+ [IDENTITY_DOWNGRADE_OP, String(oldPageId), kind, new Date().toISOString()])).length;
+}
+
/** A recorded downgrade (as opposed to a raw pair a sync has not recorded yet). */
export const isRecordedDowngrade = (entry: DowngradedRename): entry is IdentityDowngrade => 'old_page_id' in entry;
@@ -128,9 +212,9 @@ export async function noteIdentityDowngrades<T extends { status: string; identit
const pairs = (result.identityDowngrades ?? []).filter(pair => !isRecordedDowngrade(pair));
if (!pairs.length || !['synced', 'first_sync'].includes(result.status)) return result;
try {
- const records = await recordIdentityDowngrades(engine, sourceId, pairs);
const restore_available = await identityRestoreAvailable(engine, sourceId);
- for (const line of identityDowngradeLines(records.map(record => ({ ...record, restore_available })))) write(line);
+ const records = await withIdentityRemedies(engine, (await recordIdentityDowngrades(engine, sourceId, pairs)).map(record => ({ ...record, restore_available })));
+ for (const line of identityDowngradeLines(records)) 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)}`);
@@ -147,14 +231,23 @@ export const identityRestoreArgv = (record: Pick<IdentityDowngrade, 'source_id'
/** The read-only listing of a source's open records. */
export const identityStatusArgv = (sourceId: string): string[] => ['gbrain', 'sync', 'status', '--source', sourceId, '--json'];
-/** The sync report's lines for the downgraded pairs of one run. */
-export function identityDowngradeLines(records: readonly IdentityDowngrade[]): string[] {
+/** What the remedy of one pair does, for the report line and doctor. */
+export function remedyAction(record: IdentityDowngradeEntry): string {
+ if (record.remedy.disposition === 'carry') return `Carry ${record.old_slug}'s identity onto ${record.new_slug} (asks the user first: destructive)`;
+ if (record.remedy.carry_unavailable) return `Carrying ${record.old_slug}'s identity onto ${record.new_slug} is unavailable on a managed source (${record.remedy.carry_unavailable}); `
+ + 'release the purge hold without carrying it (asks the user first: destructive)';
+ return 'Release the purge hold (asks the user first: destructive)';
+}
+
+/** The sync report's lines for the downgraded pairs of one run, each naming its remedy. */
+export function identityDowngradeLines(records: readonly IdentityDowngradeEntry[]): string[] {
if (!records.length) return [];
return [
- ...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.'}`
- + (record.restore_available === false ? '' : ` To keep the old page, restore it: ${identityRestoreArgv(record).join(' ')}`)),
+ ...records.flatMap(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}; `
+ + `${record.new_slug ? `${record.new_slug} starts fresh.` : 'the new file did not import.'} The purge holds ${record.old_slug} until ${record.remedy.hold_releases}.`,
+ ` ${remedyAction(record)}: preview ${record.remedy.preview_argv.join(' ')}, then apply ${record.remedy.argv.join(' ')}`
+ + (record.restore_available === false ? '' : `; or keep ${record.old_slug} as its own page: ${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.ts
index f1b20dafe7..3d5f5e14bc 100644
--- a/test/sync-inexact-rename-6729.test.ts
+++ b/test/sync-inexact-rename-6729.test.ts
@@ -112,9 +112,10 @@ for (const kind of testBackends()) describe(`inexact Git rename identity (#6729,
expect((await purgeDeletedPagesCoordinated(engine, 0)).slugs.filter(slug => slug.endsWith('-x-com'))).toEqual([]);
expect(await pageRow(s.id, 'people/a-x-com')).toBeDefined();
- // Doctor names them; the fix restores the first old page once the user asks (ask_user), and verify clears it.
+ // Doctor names them; the fix is the first pair's preview-bound remedy (ask_user, destructive) and restoring the old page is
+ // the alternative it names. Take the alternative here (the remedy has its own suite), then verify clears that pair.
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 }>; restore_unavailable_sources?: string[] }; 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 }>; samples: Array<{ old_slug: string; new_slug: string }>; restore_unavailable_sources?: string[] }; fix?: Record<string, unknown> & { argv: string[]; why: string; plan_hash: 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');
@@ -125,7 +126,11 @@ for (const kind of testBackends()) describe(`inexact Git rename identity (#6729,
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();
+ // The doctor fix there is the pair's remedy (a classic carry).
+ const { new_slug: carryOnto } = finding!.details.samples[0]!;
+ const carryPreview = ['gbrain', 'repair', 'rename-identity', '--source', s.id, '--slug', carryOnto];
+ expect(structuredClone(finding!.fix)).toMatchObject({ argv: [...carryPreview, '--apply', '--expect', finding!.fix!.plan_hash, '--yes'], preview_argv: carryPreview, consent: ['destructive'], ask_user: true });
+ expect(finding!.fix!.why).not.toContain('gbrain restore');
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([]);
@@ -134,14 +139,17 @@ for (const kind of testBackends()) describe(`inexact Git rename identity (#6729,
expect((await purgeDeletedPagesCoordinated(engine, 0)).slugs).toContain('people/a-x-com');
return;
}
- const [, , slug, , sourceId] = finding!.fix!.argv;
+ const { old_slug: slug, new_slug: newSlug } = finding!.details.samples[0]!, sourceId = s.id;
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 };
- expect(finding!.fix).toMatchObject({ argv: ['gbrain', 'restore', expect.stringMatching(/^people\/[ab]-x-com$/), '--source-id', s.id, '--force'], consent: [], actor: 'agent', ask_user: true,
- user_message: expect.stringContaining(slug!), verify: { argv: ['gbrain', 'doctor', '--only', 'rename_identity_downgrades', '--json'] } });
+ expect(slug).toMatch(/^people\/[ab]-x-com$/);
+ const preview = ['gbrain', 'repair', 'rename-identity', '--source', s.id, '--slug', newSlug];
+ expect(structuredClone(finding!.fix)).toMatchObject({ argv: [...preview, '--apply', '--expect', finding!.fix!.plan_hash, '--yes'], preview_argv: preview, consent: ['destructive'], actor: 'agent', ask_user: true,
+ user_message: expect.stringContaining(slug), verify: { argv: ['gbrain', 'doctor', '--only', 'rename_identity_downgrades', '--json'] } });
+ expect(finding!.fix!.why).toContain(`gbrain restore ${slug} --source-id ${s.id} --force`);
const { deriveNext } = await import('../src/core/agent-output.ts');
expect(deriveNext(finding!.fix as never, { transport: 'cli', isCallable: () => false, preapproved: () => true })).toBe('ask_user');
- // Run the argv (gbrain restore <slug> --source-id <id> --force) through its operation, then the verify.
+ // Run the alternative (gbrain restore <slug> --source-id <id> --force) through its operation, then the verify.
const { operationsByName } = await import('../src/core/operations.ts');
await operationsByName.restore_page!.handler({ ...repairCtx(engine), sourceId } as never, { slug, source_id: sourceId, force: true });
expect((await pageRow(s.id, slug!))).toMatchObject({ id: restored.id, deleted_at: null });