Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Guest notes: a promotion that races another to the same link succeeds instead of failing on the unique key
garrytan660a8363dc66
diff --git a/src/core/guests/promote.ts b/src/core/guests/promote.tsindex cbbd2f248e..0d940ad5d5 100644--- a/src/core/guests/promote.ts+++ b/src/core/guests/promote.ts@@ -18,6 +18,7 @@ import { serializeMarkdown } from '../markdown.ts';import { assertInlineBody } from '../page-body/page-shape.ts';import { currentCallerAccess } from '../search/private-visibility.ts';import type { PageType } from '../types.ts';+import type { BrainEngine } from '../engine.ts';const DOCS = 'docs/guides/write-refusals.md#guest_promotion_owner_only';@@ -62,6 +63,20 @@ async function guestNote(ctx: OperationContext, slug: string, guestSource: strinreturn { id: Number(found[0]!.id), source_id: found[0]!.source_id };}+/**+ * Records the promotion link: relinks the one row for this guest page and target, else inserts it. A concurrent+ * promotion that inserted the same link first keeps its row (ON CONFLICT on guest_promotions_link_key, v314), so the+ * second call succeeds instead of failing on the unique key after its page was written.+ */+export async function linkGuestPromotion(engine: Pick<BrainEngine, 'executeRaw'>, link: { guestPageId: number; targetSource: string; targetSlug: string;+ by: { kind: string; id: string }; requestId: string | null }): Promise<void> {+ await engine.executeRaw(`WITH relinked AS (UPDATE guest_promotions SET promoted_by_kind = $4, promoted_by_id = $5, promoted_at = now(), request_id = $6+ WHERE guest_page_id = $1 AND target_source_id = $2 AND target_slug = $3 RETURNING id)+ INSERT INTO guest_promotions (guest_page_id, target_source_id, target_slug, promoted_by_kind, promoted_by_id, request_id)+ SELECT $1, $2, $3, $4, $5, $6 WHERE NOT EXISTS (SELECT 1 FROM relinked) ON CONFLICT DO NOTHING`,+ [link.guestPageId, link.targetSource, link.targetSlug, link.by.kind, link.by.id, link.requestId]);+}+export async function promoteGuestNote(ctx: OperationContext, p: Record<string, unknown>): Promise<Record<string, unknown>> {if (!isGuestPromotionOwner(ctx)) throw guestPromotionOwnerOnly(p.slug);const slug = text(p.slug, 'slug', true)!.toLowerCase();@@ -84,14 +99,8 @@ export async function promoteGuestNote(ctx: OperationContext, p: Record<string,const content = serializeMarkdown({ ...(readers !== undefined ? { readable_by: readers } : {}), promoted_from: note.source_id + ':' + slug },page.compiled_truth ?? '', page.timeline ?? '', { type: page.type as PageType, title: page.title, tags: [] });if (ctx.dryRun) return { dry_run: true, status: 'would_promote', ...result };- const link = async (requestId: unknown) => {- const by = await requestPrincipalForContext(ctx);- await ctx.engine.executeRaw(`WITH relinked AS (UPDATE guest_promotions SET promoted_by_kind = $4, promoted_by_id = $5, promoted_at = now(), request_id = $6- WHERE guest_page_id = $1 AND target_source_id = $2 AND target_slug = $3 RETURNING id)- INSERT INTO guest_promotions (guest_page_id, target_source_id, target_slug, promoted_by_kind, promoted_by_id, request_id)- SELECT $1, $2, $3, $4, $5, $6 WHERE NOT EXISTS (SELECT 1 FROM relinked)`,- [note.id, targetSource, target, by.kind, by.id, typeof requestId === 'string' ? requestId : null]);- };+ const link = async (requestId: unknown) => linkGuestPromotion(ctx.engine, { guestPageId: note.id, targetSource, targetSlug: target,+ by: await requestPrincipalForContext(ctx), requestId: typeof requestId === 'string' ? requestId : null });const written = await ctx.engine.getPage(target, { sourceId: targetSource });if (written?.frontmatter?.promoted_from === note.source_id + ':' + slug) {await link(null);diff --git a/test/guest-notes-scoped-role.test.ts b/test/guest-notes-scoped-role.test.tsindex 6c94f93611..416570cf06 100644--- a/test/guest-notes-scoped-role.test.ts+++ b/test/guest-notes-scoped-role.test.ts@@ -15,6 +15,7 @@ import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';import { readGuestSource } from '../src/core/guests/sources.ts';import { refuseGuestSourceWrite, refuseRemoteGuestDelete } from '../src/core/guests/admission.ts';import { ADMISSION_SOURCE_SQL } from '../src/core/persistence/preadmit-cache.ts';+import { linkGuestPromotion } from '../src/core/guests/promote.ts';import type { Principal } from '../src/core/persistence/model.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';import { testBackends } from './helpers/test-backends.ts';@@ -127,4 +128,18 @@ const GUESTS = 'guests-scoped';const admission = await asScoped(OTHER, tx => tx.executeRaw<Record<string, unknown>>(ADMISSION_SOURCE_SQL, [GUESTS]));expect(admission.value?.[0]).toMatchObject({ guest_writers: ['oauth_client:client-a'], guest_sources_hidden: false });});++ test('a promotion link that a concurrent promotion inserts first is not a unique-key error, and one link stays', async () => {+ const link = { guestPageId: guestPage.id, targetSource: 'default', targetSlug: 'notes/raced', by: { kind: 'local_cli', id: 'owner' }, requestId: null };+ let inserted!: () => void; let commit!: () => void;+ const first = new Promise<void>(r => { inserted = r; }); const held = new Promise<void>(r => { commit = r; });+ const winner = engine.transaction(async tx => { await linkGuestPromotion(tx, link); inserted(); await held; });+ await first;+ const loser = linkGuestPromotion(engine, link).then(() => 'linked', (e: Error) => e.message);+ for (let i = 0; i < 100 && !(await engine.executeRaw(`SELECT 1 FROM pg_locks WHERE NOT granted`)).length; i++) await Bun.sleep(50);+ commit();+ await winner;+ expect(await loser).toBe('linked');+ expect((await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM guest_promotions WHERE guest_page_id = $1 AND target_slug = 'notes/raced'`, [guestPage.id]))[0]!.n).toBe(1);+ });});