Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Close the guest-note gaps the pre-landing review found (GBRA-504)
garrytan95891ced9c95
diff --git a/docs/guides/guest-notes.md b/docs/guides/guest-notes.mdindex 03acd011b5..1e71f975c6 100644--- a/docs/guides/guest-notes.md+++ b/docs/guides/guest-notes.md@@ -63,8 +63,9 @@ gbrain guests init --writer oauth_client:client-a --yesThe source is called `guests` unless you pass `--source <id>`. Running initagain on a guest source adds the new writers and keeps the old ones. If the-source exists already, it must have no local path; init then marks it as a guest-source.+source exists already, it must have no local path and hold no pages; init then+marks it as a guest source. A source that already holds pages is refused, because+every page in a guest source would then read as a guest's words.## Change who may write@@ -117,8 +118,8 @@ The offsite moved to Friday.A guest note is saved once, as a new page. Saving to a slug that exists isrefused `revision_required`, and `force`, `expected_revision`, `edit_page`,-`append_page`, `add_timeline_entry`, `add_link`, `remember`, `put_pages` and-uploads are refused `guest_page_immutable`; a writer may delete its notes.+`append_page`, `add_timeline_entry`, `add_link`, `remember`, `put_raw_data`,+`put_pages` and uploads are refused `guest_page_immutable`; a writer may delete its notes.gbrain checks the writer list again when the note publishes, so a writer youremove in between is refused `source_writer_restricted`. Every refusal is in[write refusals](write-refusals.md#guest-source-refusals).@@ -194,7 +195,11 @@ The guest note and its mark are not changed. Its reads now show`guest.promoted: true`, and the broker's delete of it is refused`guest_page_promoted`, so a retention sweep can't remove what you kept. You canstill delete it from your own CLI. Promoting the same note to the same page again-writes nothing (`already_promoted`).+writes nothing (`already_promoted`). If a promotion stopped after the new page was+written but before the link was recorded (an interrupted run, or a write that was+still pending), promoting again records the link without writing the page twice.+The note is read through the same read scope as `get_page`, so a connection that+cannot read the guest source cannot promote from it.Agents reach the same step as the MCP tool `promote_guest_note`. Only you mayrun it: your own CLI (not under `GBRAIN_ENFORCED_MEMBER` and not with `--as`), adiff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex 149c9ff01d..6dd5e5ba81 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -210,7 +210,7 @@ test/get-page-federated-scope.test.ts #4275 alias hop scope: archived sources, itest/git-env-guard.test.ts (file-level) 5 readFileSynctest/grant-execution-prerequisites.test.ts execution prerequisite table 1 readFileSynctest/guest-derived-registry.test.ts guest derived-producer registry 2 readFileSync-test/guest-derived-registry.test.ts guest pages feed no derived rows (pglite, repo-less) 3 readFileSync+test/guest-derived-registry.test.ts guest pages feed no derived rows (pglite, repo-less) 4 readFileSynctest/harness-onboarding.test.ts harness identity and private handoff 6 readFileSynctest/hook-command.serial.test.ts user-prompt 18 source-surface-helpertest/hook-push-spawn-env.test.ts spawnDetachedPush env handoff 2 readFileSyncdiff --git a/src/commands/guests.ts b/src/commands/guests.tsindex b1109a432e..673c68da95 100644--- a/src/commands/guests.ts+++ b/src/commands/guests.ts@@ -82,6 +82,13 @@ async function runInit(engine: BrainEngine, rest: string[]): Promise<void> {console.error(`Source "${sourceId}" has a local path (${plan.localPath}). A guest source is database-only, so gbrain will not make this one a guest source. Pick another name with --source.`);process.exit(2);}+ if (plan.exists && !plan.guest) {+ const [held] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM pages WHERE source_id = $1 AND deleted_at IS NULL', [sourceId]);+ if (Number(held?.n ?? 0) > 0) {+ console.error(`Source "${sourceId}" already holds ${held!.n} page(s). Every page in a guest source reads as an outside guest's words and only listed writers can change it, so gbrain will not make this one a guest source. Pick another name with --source.`);+ process.exit(2);+ }+ }const writerLine = (list: readonly string[]) => list.length > 0 ? list.join(', '): `none yet: nobody can save notes there until you add one (gbrain sources writers ${sourceId} --add ${GUEST_WRITER_FORMAT})`;if (!yes) {diff --git a/src/core/cycle/propose-takes.ts b/src/core/cycle/propose-takes.tsindex 13cea215fb..50783092d6 100644--- a/src/core/cycle/propose-takes.ts+++ b/src/core/cycle/propose-takes.ts@@ -63,6 +63,7 @@ import { ProposeTakesFailures, PROPOSE_TAKES_HOLD_RUNS, type FailedPage } from 'import type { OperationContext } from '../operations.ts';import type { BrainEngine } from '../engine.ts';import type { PhaseStatus, CyclePhase } from '../cycle.ts';+import { guestSourceExclusionSql } from '../guests/derived.ts';/*** Bump when the extractor prompt or the JSON output shape changes. Old@@ -316,6 +317,7 @@ async function listCandidatePages("COALESCE(frontmatter->>'dream_generated', '') <> 'true'","COALESCE(frontmatter->>'extracted_by', '') NOT LIKE 'extract_atoms%'","COALESCE(frontmatter->>'synthesized_by', '') NOT LIKE 'synthesize_concepts%'",+ guestSourceExclusionSql('propose_takes', 'pages'),];const params: unknown[] = [];if (scope.sourceIds && scope.sourceIds.length > 0) {diff --git a/src/core/eligibility/activation.ts b/src/core/eligibility/activation.tsindex 800f3b9ab4..c5a670bec9 100644--- a/src/core/eligibility/activation.ts+++ b/src/core/eligibility/activation.ts@@ -18,7 +18,7 @@import type { BrainEngine } from '../engine.ts';import type { Notice } from '../agent-output.ts';import { admitsTrust, minTrust, storedTrustTier, type TrustTier } from '../trust/tier.ts';-import { guestSourceSql, guestView, loadGuestMarks, unattributedGuest, type GuestStamp } from '../guests/marker.ts';+import { guestView, loadGuestMarks, unattributedGuest, withGuestSourceSql, type GuestStamp } from '../guests/marker.ts';import { activationSuppressedSql, type EligibilityTable } from './sql.ts';import type { ReadEligibility } from './policy.ts';@@ -130,11 +130,11 @@ export async function pageActivationVerdicts(engine: Exec, keys: readonly PageKePromise<Map<string, ActivationVerdict & { origin: unknown; guest?: GuestStamp }>> {const out = new Map<string, ActivationVerdict & { origin: unknown; guest?: GuestStamp }>();if (keys.length === 0) return out;- const rows = await engine.executeRaw<{ id: number; source_id: string; slug: string; trust_tier: string; write_origin: unknown; flagged: boolean; guest: boolean }>(+ const rows = await withGuestSourceSql(guestSql => engine.executeRaw<{ id: number; source_id: string; slug: string; trust_tier: string; write_origin: unknown; flagged: boolean; guest: boolean }>(`SELECT a.id, a.source_id, a.slug, a.trust_tier, a.write_origin, ${activationSuppressedSql('pages', 'a')} AS flagged,- ${guestSourceSql('s.config', 'a.source_id')} AS guest FROM pages a LEFT JOIN sources s ON s.id = a.source_id+ ${guestSql('s.config', 'a.source_id')} AS guest FROM pages a LEFT JOIN sources s ON s.id = a.source_idWHERE a.deleted_at IS NULL AND (a.source_id, a.slug) IN (SELECT * FROM unnest($1::text[], $2::text[]))`,- [keys.map(k => k.source_id), keys.map(k => k.slug)]);+ [keys.map(k => k.source_id), keys.map(k => k.slug)]));// GBRA-504: a page in a guest source carries its guest mark (one batched read), or reads unattributed.const marks = rows.some(r => r.guest === true) ? await loadGuestMarks(engine, rows.filter(r => r.guest === true).map(r => Number(r.id))) : null;for (const row of rows) {diff --git a/src/core/eligibility/stamp.ts b/src/core/eligibility/stamp.tsindex 305fdbe43b..a528248c61 100644--- a/src/core/eligibility/stamp.ts+++ b/src/core/eligibility/stamp.ts@@ -12,7 +12,7 @@ import { admitsTrust, compareTrust, minTrust, storedTrustTier, type TrustTier }import { chunkFenceMarker, FENCE_TRUST_ORIGIN, fenceTrustMarker, lowestFenceTrustMarker } from './fence-overlay.ts';import { needsDataEnvelope, parseContested, renderTrustedText, trustFields, type Contested, type TrustFields } from './labels.ts';import { activationSuppressedSql, contestedRefSql } from './sql.ts';-import { GUEST_ORIGIN, guestSourceSql, guestView, loadGuestMarks, unattributedGuest, type GuestStamp } from '../guests/marker.ts';+import { GUEST_ORIGIN, guestView, loadGuestMarks, unattributedGuest, withGuestSourceSql, type GuestStamp } from '../guests/marker.ts';const withFlag = (fields: TrustFields, flagged: unknown): TrustFields => (flagged === true ? { ...fields, unconfirmed: true } : fields);@@ -28,8 +28,8 @@ type Exec = Pick<BrainEngine, 'executeRaw'>;const key = (source: string | null | undefined, slug: string) => `${source ?? 'default'}\u0000${slug}`;type TrustRow = { id: number; source_id: string; slug: string; trust_tier: string; write_origin: unknown; flagged: boolean; guest: boolean };-const TRUST_COLUMNS = `pages.id, pages.source_id, pages.slug, pages.trust_tier, pages.write_origin, ${activationSuppressedSql('pages', 'pages')} AS flagged,- ${guestSourceSql('s.config', 'pages.source_id')} AS guest FROM pages LEFT JOIN sources s ON s.id = pages.source_id`;+const trustColumns = (guestSql: (config: string, id: string) => string) => `pages.id, pages.source_id, pages.slug, pages.trust_tier, pages.write_origin, ${activationSuppressedSql('pages', 'pages')} AS flagged,+ ${guestSql('s.config', 'pages.source_id')} AS guest FROM pages LEFT JOIN sources s ON s.id = pages.source_id`;/*** Trust fields per page id and per (source_id, slug). GBRA-504: a row in a guest source is decided here, per row from@@ -42,15 +42,18 @@ export async function loadPageTrust(engine: Exec, refs: readonly PageRef[], optsconst byKey = new Map<string, TrustFields>();const ids = [...new Set(refs.map(r => r.page_id).filter((n): n is number => typeof n === 'number' && Number.isFinite(n)))];const slugRefs = refs.filter(r => typeof r.page_id !== 'number');- const rows: Array<TrustRow & { byId: boolean }> = [];- if (ids.length) {- for (const row of await engine.executeRaw<TrustRow>(`SELECT ${TRUST_COLUMNS} WHERE pages.id = ANY($1::int[])`, [ids])) rows.push({ ...row, byId: true });- }- if (slugRefs.length) {- for (const row of await engine.executeRaw<TrustRow>(`SELECT ${TRUST_COLUMNS}- WHERE ${opts.includeDeleted ? '' : 'pages.deleted_at IS NULL AND '}(pages.source_id, pages.slug) IN (SELECT * FROM unnest($1::text[], $2::text[]))`,- [slugRefs.map(r => r.source_id ?? 'default'), slugRefs.map(r => r.slug)])) rows.push({ ...row, byId: false });- }+ const rows = await withGuestSourceSql(async guestSql => {+ const found: Array<TrustRow & { byId: boolean }> = [];+ if (ids.length) {+ for (const row of await engine.executeRaw<TrustRow>(`SELECT ${trustColumns(guestSql)} WHERE pages.id = ANY($1::int[])`, [ids])) found.push({ ...row, byId: true });+ }+ if (slugRefs.length) {+ for (const row of await engine.executeRaw<TrustRow>(`SELECT ${trustColumns(guestSql)}+ WHERE ${opts.includeDeleted ? '' : 'pages.deleted_at IS NULL AND '}(pages.source_id, pages.slug) IN (SELECT * FROM unnest($1::text[], $2::text[]))`,+ [slugRefs.map(r => r.source_id ?? 'default'), slugRefs.map(r => r.slug)])) found.push({ ...row, byId: false });+ }+ return found;+ });const marks = rows.some(r => r.guest === true) ? await loadGuestMarks(engine, rows.filter(r => r.guest === true).map(r => Number(r.id))) : null;for (const row of rows) {const base = withFlag(trustFields(row.trust_tier, row.write_origin), row.flagged);diff --git a/src/core/guests/derived.ts b/src/core/guests/derived.tsindex 265afd178c..9ab760f31d 100644--- a/src/core/guests/derived.ts+++ b/src/core/guests/derived.ts@@ -33,7 +33,7 @@ export const GUEST_DERIVED_PRODUCERS = {synthesize_concepts: { guest: 'none', reason: 'Aggregates atom pages, which extract_atoms never derives from a guest page.' },recompute_emotional_weight: { guest: 'none', reason: "Scores a page from its own takes and tags into that page's emotional_weight column; a guest page has no takes." },consolidate: { guest: 'none', reason: NO_ROWS },- propose_takes: { guest: 'skip', sites: [CYCLE] },+ propose_takes: { guest: 'skip', sites: [CYCLE, 'src/core/cycle/propose-takes.ts'] },grade_takes: { guest: 'none', reason: NO_ROWS },calibration_profile: { guest: 'none', reason: NO_ROWS },edge_contradictions: { guest: 'none', reason: NO_ROWS },diff --git a/src/core/guests/marker.ts b/src/core/guests/marker.tsindex d4949cfe12..5f9e146579 100644--- a/src/core/guests/marker.ts+++ b/src/core/guests/marker.ts@@ -10,6 +10,7 @@*/import type { BrainEngine } from '../engine.ts';import type { Operation } from '../ops/contract.ts';+import { isMissingSchemaObject } from '../utils.ts';export const GUEST_ORIGIN = 'guest';/** get_brain_identity lists it: this brain stamps the guest warning on every read, so a guest broker may switch on. */@@ -22,6 +23,17 @@ export const GUEST_MARKER_CAPABILITY = 'guest_marker_v1';export const guestSourceSql = (config: string, id: string) =>`(COALESCE(${config}->>'guest' = 'true', false) OR EXISTS (SELECT 1 FROM guest_sources gs WHERE gs.source_id = ${id}))`;+/**+ * Runs `read` with guestSourceSql. A brain whose schema is behind v312 has no guest_sources table, so the read is+ * retried with the config record alone instead of failing every read that returns a page.+ */+export async function withGuestSourceSql<T>(read: (guestSql: typeof guestSourceSql) => Promise<T>): Promise<T> {+ try { return await read(guestSourceSql); } catch (e) {+ if (!isMissingSchemaObject(e, 'table', 'guest_sources')) throw e;+ return read(config => `COALESCE(${config}->>'guest' = 'true', false)`);+ }+}+/** Whether any source is a guest source, read from the sources themselves on every call; a failed read answers yes. */export async function brainHasGuestSource(engine: Pick<BrainEngine, 'executeRaw'>): Promise<boolean> {try {diff --git a/src/core/guests/promote.ts b/src/core/guests/promote.tsindex dce6d8521c..1315e573d2 100644--- a/src/core/guests/promote.ts+++ b/src/core/guests/promote.ts@@ -11,6 +11,7 @@* (guests/admission.ts refuseRemoteDeleteOfPromoted). The guest page and its mark are never changed.*/import { OperationError, type OperationContext } from '../ops/contract.ts';+import { federatedSearchScope } from '../ops/context.ts';import { serializeMarkdown } from '../markdown.ts';import { currentCallerAccess } from '../search/private-visibility.ts';import type { PageType } from '../types.ts';@@ -40,7 +41,8 @@ async function guestNote(ctx: OperationContext, slug: string, guestSource: strinconst rows = await ctx.engine.executeRaw<{ id: number; source_id: string }>('SELECT p.id, p.source_id FROM pages p JOIN guest_sources g ON g.source_id = p.source_id WHERE p.slug = $1 AND p.deleted_at IS NULL'+ (guestSource ? ' AND p.source_id = $2' : '') + ' ORDER BY p.source_id', guestSource ? [slug, guestSource] : [slug]);- const readable = ctx.remote === false || !ctx.auth ? null : ctx.auth.allowedSources?.length ? ctx.auth.allowedSources : [ctx.auth.sourceId];+ const scope = ctx.remote === false ? null : federatedSearchScope(ctx, guestSource);+ const readable = scope ? scope.sourceIds ?? (scope.sourceId !== undefined ? [scope.sourceId] : null) : null;const found = rows.filter(r => !readable || readable.includes(r.source_id));if (!found.length) {throw new OperationError('page_not_found', 'No live guest note ' + slug + (guestSource ? ' in source ' + guestSource : '') + ' is visible here, so nothing was promoted.',@@ -74,12 +76,20 @@ 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(+ 'INSERT INTO guest_promotions (guest_page_id, target_source_id, target_slug, promoted_by_kind, promoted_by_id, request_id) VALUES ($1, $2, $3, $4, $5, $6)',+ [note.id, targetSource, target, by.kind, by.id, 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);+ return { status: 'promoted', ...result, recovered: true };+ }const params = { slug: target, content, source_id: targetSource, ...(typeof p.request_id === 'string' ? { request_id: p.request_id } : {}) };(await import('../persistence/page-visibility.ts')).assertSubmittedReaders(ctx.remote, target, content);const write = await submitPageMutation(ctx, { operation: 'put_page', params });- const by = await requestPrincipalForContext(ctx);- await ctx.engine.executeRaw(- 'INSERT INTO guest_promotions (guest_page_id, target_source_id, target_slug, promoted_by_kind, promoted_by_id, request_id) VALUES ($1, $2, $3, $4, $5, $6)',- [note.id, targetSource, target, by.kind, by.id, typeof write.request_id === 'string' ? write.request_id : null]);+ await link(write.request_id);return { status: 'promoted', ...result, write };}diff --git a/src/core/ops/raw-data.ts b/src/core/ops/raw-data.tsindex 24d20cbe0d..ea31bdf644 100644--- a/src/core/ops/raw-data.ts+++ b/src/core/ops/raw-data.ts@@ -8,6 +8,8 @@import type { Operation } from './contract.ts';import { readPolicyOpts, requireWritablePage } from './context.ts';import { enforceClientSlugFence } from './context.ts';+import { refuseGuestSourceWrite } from '../guests/admission.ts';+import { requestPrincipalForContext } from '../persistence/page-mutations.ts';// --- Raw Data ---@@ -30,6 +32,7 @@ const put_raw_data: Operation = {const sourceOpts = ctx.sourceId ? { sourceId: ctx.sourceId } : {};// GBRA-218: a remote caller's missing and member-hidden targets get the same page_not_found (no existence oracle).if (ctx.remote !== false) await requireWritablePage(ctx, p.slug as string, 'put_raw_data', 'page');+ await refuseGuestSourceWrite(ctx.engine, ctx.sourceId || 'default', () => requestPrincipalForContext(ctx), 'put_raw_data');await ctx.engine.putRawData(p.slug as string, p.source as string, p.data as object, sourceOpts);return { status: 'ok' };},diff --git a/test/guest-derived-registry.test.ts b/test/guest-derived-registry.test.tsindex 942a5583a5..d0ed9bd436 100644--- a/test/guest-derived-registry.test.ts+++ b/test/guest-derived-registry.test.ts@@ -19,6 +19,7 @@ import { importFromContent } from '../src/core/import-file.ts';import { extractStaleFromDB } from '../src/commands/extract.ts';import { extractTimelineFromDB } from '../src/commands/extract-timeline-db.ts';import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';+import { runPhaseProposeTakes } from '../src/core/cycle/propose-takes.ts';import { withWriteAttribution } from '../src/core/persistence/context.ts';const ROOT = join(import.meta.dir, '..');@@ -91,6 +92,16 @@ describe('guest pages feed no derived rows (pglite, repo-less)', () => {expect(await guestRows()).toEqual({ links: 0, timeline: 0, facts: 0 });}, 120_000);+ test('an unscoped propose_takes run never reads a guest page and proposes nothing from it', async () => {+ const scanned: string[] = [];+ const ctx = { engine, config: {} as never, logger: { info() {}, warn() {}, error() {} } as never, dryRun: false, remote: false, sourceId: undefined };+ await runPhaseProposeTakes(ctx as never, { extractor: async ({ pagePath }) => { scanned.push(pagePath); return []; } });+ expect(scanned).toContain('notes/owner-a');+ expect(scanned.filter(slug => slug === 'notes/guest-a' || slug === 'people/carol-example')).toEqual([]);+ const [proposals] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM take_proposals WHERE source_id = 'guests'");+ expect(proposals!.n).toBe(0);+ }, 120_000);+test('a cycle scoped to the guest source reports the derived phases skipped', async () => {const report = await runCycle(engine, { sourceId: 'guests', phases: ['extract_facts', 'propose_takes', 'orphans'], brainDir: null } as never);const byPhase = Object.fromEntries(report.phases.map(p => [p.phase, (p.details as { reason?: string } | undefined)?.reason]));diff --git a/test/guest-notes-admission.test.ts b/test/guest-notes-admission.test.tsindex 89ccbde19b..9314e2dceb 100644--- a/test/guest-notes-admission.test.ts+++ b/test/guest-notes-admission.test.ts@@ -240,6 +240,17 @@ describe('guest write admission (pglite, repo-less)', () => {expect((await put('broker', slug)).code).toBe('guest_page_immutable');}, 120_000);+ test('raw data cannot be attached to a guest page by its writer, another credential or the owner', async () => {+ const slug = slugOf();+ expect((await put('broker', slug)).isError).toBe(false);+ const data = { note: 'attached later' };+ expect((await call('broker', 'put_raw_data', { slug, source: 'provider-a', data })).code).toBe('guest_page_immutable');+ expect((await call('other', 'put_raw_data', { slug, source: 'provider-a', data })).code).toBe('source_writer_restricted');+ expect((await local('put_raw_data', { slug, source: 'provider-a', data })).code).toBe('source_writer_restricted');+ const [rows] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM raw_data r JOIN pages p ON p.id = r.page_id WHERE p.source_id = $1 AND p.slug = $2', [SRC, slug]);+ expect(rows!.n).toBe(0);+ }, 120_000);+test('the frontmatter allowlist and the sender and group match', async () => {for (const [label, page] of [['extra key', { extra: ['tags: [x]'] }], ['visibility', { extra: ['visibility: private'] }], ['trust key', { extra: ['trust_tier: owner'] }],diff --git a/test/guest-notes-promotion.test.ts b/test/guest-notes-promotion.test.tsindex 04e1182be6..acf749d9b4 100644--- a/test/guest-notes-promotion.test.ts+++ b/test/guest-notes-promotion.test.ts@@ -31,6 +31,7 @@ import { runSources } from '../src/commands/sources.ts';import { operationsByName } from '../src/core/operations.ts';import type { AuthInfo } from '../src/core/ops/contract.ts';import { readsUnscopedOnPurpose } from './helpers/reads-unscoped.ts';+import { explicitReadBinding } from '../src/core/source-resolver.ts';const SRC = 'guests';const PLAIN = 'source-a';@@ -145,11 +146,47 @@ describe('promote_guest_note (pglite, repo-less)', () => {const third = slugOf();await saveGuest(third);const stdio = await dispatchToolCall(engine, 'promote_guest_note', { slug: third, to: 'notes/kept-' + third.slice(-8) }, {- remote: true, transport: 'stdio', stdioMember: OWNER, sourceId: PLAIN, takesHoldersAllowList: ['world'] });+ remote: true, transport: 'stdio', stdioMember: OWNER, sourceId: PLAIN, localFederatedSourceIds: [PLAIN, SRC], takesHoldersAllowList: ['world'] });expect({ isError: stdio.isError === true, text: stdio.isError ? stdio.content[0]!.text : '' }).toEqual({ isError: false, text: '' });expect((await promotions(third))[0]?.promoted_by_kind).toBe('local_stdio');}, 120_000);+ test('a stdio connection bound to a source that cannot read the guest source cannot promote from it', async () => {+ const slug = slugOf();+ await saveGuest(slug);+ const isolated = 'source-isolated';+ await engine.executeRaw(`INSERT INTO sources (id, name, config) VALUES ($1, $1, '{"federated": false}'::jsonb) ON CONFLICT (id) DO NOTHING`, [isolated]);+ const binding = await explicitReadBinding(engine, isolated, 'env');+ expect(binding?.sourceIds).toEqual([isolated]);+ const opts = { remote: true, transport: 'stdio' as const, stdioMember: OWNER, sourceId: isolated, explicitReadBinding: binding, takesHoldersAllowList: ['world'] };+ const read = parse((await dispatchToolCall(engine, 'get_page', { slug, source_id: SRC }, opts)).content[0]!.text);+ expect(read.code ?? read.error).toBeDefined();+ const out = await dispatchToolCall(engine, 'promote_guest_note', { slug, to: 'notes/bound-' + slug.slice(-8) }, opts);+ expect(out.isError).toBe(true);+ expect(await promotions(slug)).toEqual([]);+ expect(await engine.getPage('notes/bound-' + slug.slice(-8), { sourceId: isolated })).toBeNull();+ }, 120_000);++ test('a promotion whose link was lost is finished by promoting again, with no second write', async () => {+ const slug = slugOf();+ const target = 'notes/recover-' + slug.slice(-8);+ await saveGuest(slug);+ expect((await local('promote_guest_note', { slug, to: target })).isError).toBe(false);+ await engine.executeRaw('DELETE FROM guest_promotions WHERE target_source_id = $1 AND target_slug = $2', [PLAIN, target]);+ const before = (await engine.readPageSnapshot(target, { sourceId: PLAIN }))!.revision;+ const again = await local('promote_guest_note', { slug, to: target });+ expect({ isError: again.isError, text: again.isError ? again.text : '', status: again.json.status }).toEqual({ isError: false, text: '', status: 'promoted' });+ expect(await promotions(slug)).toEqual([{ target_source_id: PLAIN, target_slug: target, promoted_by_kind: 'local_cli' }]);+ expect((await engine.readPageSnapshot(target, { sourceId: PLAIN }))!.revision).toBe(before);+ }, 120_000);++ test('a target page that was not promoted from this note is not linked', async () => {+ const slug = slugOf();+ await saveGuest(slug);+ expect((await local('promote_guest_note', { slug, to: 'notes/owner-page' })).isError).toBe(true);+ expect(await promotions(slug)).toEqual([]);+ }, 120_000);+test('everyone else is guest_promotion_owner_only and nothing is written', async () => {const slug = slugOf();await saveGuest(slug);diff --git a/test/guest-notes-shortcut.test.ts b/test/guest-notes-shortcut.test.tsindex 7df3cc833e..9cb869a199 100644--- a/test/guest-notes-shortcut.test.ts+++ b/test/guest-notes-shortcut.test.ts@@ -77,3 +77,36 @@ describe('a guest source the guests command never set up', () => {expect(out.isError || out.json?.origin === 'guest').toBe(true);}, 60_000);});++describe('a brain whose schema is behind v312', () => {+ test('reads still work without the guest tables, and a config-marked guest source is still marked', async () => {+ const old = new PGLiteEngine();+ await old.connect({});+ await old.initSchema();+ try {+ await addMember(old, OWNER);+ await setOwner(old, OWNER);+ for (const id of [EDITED, LISTED]) {+ await old.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [id]);+ await importFromContent(old, SLUG, '---\ntype: note\ntitle: Visitor note\n---\n# Visitor note\n\nA visitor wrote this in ' + id + '.\n', { sourceId: id });+ }+ await old.executeRaw(`UPDATE sources SET config = config || '{"guest": true}'::jsonb WHERE id = $1`, [EDITED]);+ await old.executeRaw('DROP TABLE guest_promotions, guest_marks, guest_sources CASCADE');+ const read = async (op: string, params: Record<string, unknown>, sourceId: string) => {+ const out = await dispatchToolCall(old, op, params, { remote: true, transport: 'stdio', stdioMember: OWNER, sourceId, takesHoldersAllowList: ['world'] });+ const text = out.content[0]!.text;+ let json: any = null;+ try { json = JSON.parse(text); } catch { /* an error text */ }+ return { isError: out.isError === true, text, json };+ };+ const plain = await read('get_page', { slug: SLUG }, LISTED);+ expect({ isError: plain.isError, text: plain.isError ? plain.text : '', origin: plain.json?.origin === 'guest' }).toEqual({ isError: false, text: '', origin: false });+ const listed = await read('list_pages', {}, EDITED);+ const row = (Array.isArray(listed.json) ? listed.json : listed.json?.pages ?? []).find((r: any) => r.slug === SLUG);+ expect({ isError: listed.isError, origin: row?.origin, tier: row?.trust_tier }).toEqual({ isError: false, origin: 'guest', tier: 'external_untrusted' });+ } finally {+ await disposePersistenceConsumer(old);+ await old.disconnect();+ }+ }, 120_000);+});diff --git a/test/guests-cli.test.ts b/test/guests-cli.test.tsindex 96ad5c221c..952ca627bd 100644--- a/test/guests-cli.test.ts+++ b/test/guests-cli.test.ts@@ -63,6 +63,18 @@ const guestRow = async (id: string) => (await engine.executeRaw<{ writers: strinconst configOf = (config: unknown) => (typeof config === 'string' ? JSON.parse(config) : config) as Record<string, unknown>;describe('gbrain guests init', () => {+ test('refuses an existing source that already holds pages, in the preview and with --yes', async () => {+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', ['source-a']);+ await engine.putPage('notes/owner-a', { title: 'Owner', type: 'note' as never, compiled_truth: 'Mine.', frontmatter: {}, timeline: '' }, { sourceId: 'source-a' } as never);+ for (const args of [['init', '--source', 'source-a'], ['init', '--source', 'source-a', '--yes']]) {+ exitCode = null; err = [];+ await run(() => runGuests(engine, args));+ expect({ args, exitCode, said: err.join('\n').includes('already holds 1 page') }).toEqual({ args, exitCode: 2, said: true });+ }+ expect(await guestRow('source-a')).toBeUndefined();+ expect(configOf((await sourceRow('source-a'))!.config).guest).toBeUndefined();+ });+test('previews by default and writes nothing', async () => {await run(() => runGuests(engine, ['init', '--writer', 'oauth_client:client-a']));expect(exitCode).toBeNull();diff --git a/test/operations-coverage-ledger.test.ts b/test/operations-coverage-ledger.test.tsindex 37e2501290..aa60b0f837 100644--- a/test/operations-coverage-ledger.test.ts+++ b/test/operations-coverage-ledger.test.ts@@ -50,6 +50,7 @@ const LEDGER: Record<string, string> = {restore_page: 'test/pages-source-scoping-4329.test.ts',purge_deleted_pages: 'test/operations-trust-boundary.test.ts',purge_fact: 'test/purge-fact.test.ts',+ promote_guest_note: 'test/guest-notes-promotion.test.ts',confirm_memory: 'test/trust-owner-actions.test.ts',list_page_purges: 'test/page-purge.test.ts',unpurge_page: 'test/page-purge.test.ts',