Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Bring guest notes inside the repo's code ratchets (GBRA-504)

garrytanbdc98816a9dd
diff --git a/docs/contracts/qm-memory-provider/v2.json b/docs/contracts/qm-memory-provider/v2.json
index 1dad8d23eb..8d5dd9cf9d 100644
--- a/docs/contracts/qm-memory-provider/v2.json
+++ b/docs/contracts/qm-memory-provider/v2.json
@@ -42,6 +42,7 @@
"loops_mute",
"loops_unmute",
"ontology_propose",
+ "promote_guest_note",
"put_page",
"put_pages",
"put_raw_data",
diff --git a/docs/contracts/qm-memory-provider/v3.json b/docs/contracts/qm-memory-provider/v3.json
index d8b9d8f2d7..292180bd32 100644
--- a/docs/contracts/qm-memory-provider/v3.json
+++ b/docs/contracts/qm-memory-provider/v3.json
@@ -42,6 +42,7 @@
"loops_mute",
"loops_unmute",
"ontology_propose",
+ "promote_guest_note",
"put_page",
"put_pages",
"put_raw_data",
diff --git a/docs/contracts/qm-memory-provider/v4.json b/docs/contracts/qm-memory-provider/v4.json
index 6e4f25180f..9e90eadeda 100644
--- a/docs/contracts/qm-memory-provider/v4.json
+++ b/docs/contracts/qm-memory-provider/v4.json
@@ -42,6 +42,7 @@
"loops_mute",
"loops_unmute",
"ontology_propose",
+ "promote_guest_note",
"put_page",
"put_pages",
"put_raw_data",
diff --git a/docs/contracts/qm-memory-provider/v5.json b/docs/contracts/qm-memory-provider/v5.json
index 12264cfd0c..d49ce542a4 100644
--- a/docs/contracts/qm-memory-provider/v5.json
+++ b/docs/contracts/qm-memory-provider/v5.json
@@ -42,6 +42,7 @@
"loops_mute",
"loops_unmute",
"ontology_propose",
+ "promote_guest_note",
"put_page",
"put_pages",
"put_raw_data",
diff --git a/scripts/check-engine-sql-dynamic.ts b/scripts/check-engine-sql-dynamic.ts
index 8509e32b4d..9770f8e4a4 100644
--- a/scripts/check-engine-sql-dynamic.ts
+++ b/scripts/check-engine-sql-dynamic.ts
@@ -63,6 +63,7 @@ const VETTED_BUILDERS: Record<string, string> = {
replacedBecauseSql: 'src/core/engine-sql/pages.ts: constant GBRA-217 reason projection over a caller alias, with callerReadersAllowedSql on the successor (identities checked by validIdentity before they are quoted in); the boolean picks one of two constant texts',
validDateSql: 'src/core/valid-time.ts: constant GBRA-217 date normaliser over a caller column expression; engine-sql passes only constant pv.frontmatter keys',
quarantineFilterFragment: 'src/core/quarantine.ts: constant quarantine predicate over a caller alias',
+ guestSourceExclusionSql: 'src/core/guests/derived.ts: GBRA-504 constant guest-source NOT EXISTS predicate (guests/note.ts guestSourceSql) over a caller alias, or TRUE for a producer that takes guest input; the producer key is a typed union member; no values',
currentCodeEdgeFilter: 'src/core/code-intel/read-scope.ts: constant current-edge predicate over a caller alias',
buildCJKKeywordSql: 'src/core/search/cjk-keyword-sql.ts: binds the query as params; shared by both engines',
currentTextProjectionFilter: 'src/core/search/safe-chunks.ts: constant projection predicate over a caller alias',
diff --git a/src/cli/command-table.ts b/src/cli/command-table.ts
index 859f914d6c..79678c15c5 100644
--- a/src/cli/command-table.ts
+++ b/src/cli/command-table.ts
@@ -424,7 +424,8 @@ export const CLI_COMMANDS: readonly CliCommandRecord[] = [ // Pre-connect: disp
// #5575: memory trust. Observational startup: `trust backfill --dry-run` runs with no migrations and no writes.
// W1 belief ledger coverage: enable, disable, status, reconcile, backfill (docs/designs/BELIEF_LEDGER.md section 7).
{ name: 'beliefs', phase: 'post-connect', thinClient: 'route-then-refuse', selfHelp: true, json: 'document', routes_source: true, load: () => import('./commands/beliefs.ts') },
- // CLI_ONLY: guest notes (GBRA-504): sets up a database-only guest source; trusted local CLI only.
+ // CLI_ONLY: guest notes (GBRA-504): sets up a database-only guest source; trusted local CLI only. selfHelp: a router
+ // (init, promote, grant-owner-clients); its usage prints before any engine is opened.
{ name: 'guests', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/guests.ts') },
{ name: 'trust', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, json: 'document', skipStartupHooks: true, startup: 'observational', load: () => import('./commands/trust.ts') },
// selfHelp: v0.43 (#2095): watch ships WATCH_HELP (flags + the stdin-turn protocol).
diff --git a/src/cli/page-render.ts b/src/cli/page-render.ts
index b17b1a60da..4926e07dde 100644
--- a/src/cli/page-render.ts
+++ b/src/cli/page-render.ts
@@ -132,15 +132,12 @@ export function asOfExitCode(r: GetPageResult | null | undefined): number {
return r.compiled_truth === undefined && !r.window ? 1 : 0;
}
-/** stdout text for one get_page result; partial responses add a stderr note. */
-/** GBRA-504: a guest page's human output starts with its warning line, rendered from the stamped guest fields. */
+/** stdout text for one get_page result; partial responses add a stderr note. A guest page's text starts with its warning line (GBRA-504). */
export function formatGetPage(r: GetPageResult): string {
- const text = formatPage(r);
- return r.guest && text ? `${guestWarningLine(r.guest)}
-${text}` : text;
-}
-
-function formatPage(r: GetPageResult): string {
+ if (r.guest) {
+ const text = formatGetPage({ ...r, guest: undefined });
+ return text && `${guestWarningLine(r.guest)}\n${text}`;
+ }
if (r.valid_time) process.stderr.write(validTimeLine(r.valid_time) + '\n');
if (asOfNotInForce(r)) return `status: ${r.valid_time.status}\nwhy: ${r.valid_time.why ?? 'none'}\n`;
if (r.valid_time?.history !== undefined && r.compiled_truth === undefined && !r.window) return '';
diff --git a/src/cli/router-help.ts b/src/cli/router-help.ts
index d5b5746a60..47afd34e02 100644
--- a/src/cli/router-help.ts
+++ b/src/cli/router-help.ts
@@ -24,6 +24,7 @@ export const ROUTER_MODULES: Readonly<Record<string, () => Promise<RouterModule>
quarantine: () => import('../commands/quarantine.ts'),
core: () => import('../commands/core.ts'),
loops: () => import('../commands/loops.ts'),
+ guests: () => import('../commands/guests.ts'),
};
/**
diff --git a/src/cli/subcommands.ts b/src/cli/subcommands.ts
index a19c8cf848..525f898ca9 100644
--- a/src/cli/subcommands.ts
+++ b/src/cli/subcommands.ts
@@ -28,6 +28,7 @@ export const CONFIG_SUBCOMMANDS = ['show', 'get', 'set', 'unset'] as const;
export const QUARANTINE_SUBCOMMANDS = ['list', 'clear', 'scan', 'release', 'drop'] as const;
export const CORE_SUBCOMMANDS = ['list', 'show', 'status', 'add', 'remove', 'diff', 'ack', 'init', 'suggest'] as const;
export const LOOPS_SUBCOMMANDS = ['list', 'show', 'done', 'drop', 'mute', 'unmute'] as const;
+export const GUESTS_SUBCOMMANDS = ['init', 'promote', 'grant-owner-clients'] as const;
export const SCHEMA_SUBCOMMANDS = [
'active', 'list', 'show', 'validate', 'use', 'detect', 'suggest', 'review-candidates', 'init', 'fork', 'edit',
'diff', 'graph', 'lint', 'explain', 'review-orphans', 'downgrade', 'usage', 'stats', 'cardinality-preview',
@@ -60,6 +61,7 @@ export const ROUTERS: Readonly<Record<string, RouterInventory>> = {
// so `core list --help` ran `list` against a null engine and `loops show --help` exited 2 "needs a loop id".
core: { subcommands: CORE_SUBCOMMANDS, bareHelpFirst: true },
loops: { subcommands: LOOPS_SUBCOMMANDS, bareHelpFirst: true },
+ guests: { subcommands: GUESTS_SUBCOMMANDS, bareHelpFirst: true },
};
/** `--help` / `-h` before any `--` terminator. */
diff --git a/src/commands/doctor/checks/guest-source.ts b/src/commands/doctor/checks/guest-source.ts
index 564b19c159..4e705c0e04 100644
--- a/src/commands/doctor/checks/guest-source.ts
+++ b/src/commands/doctor/checks/guest-source.ts
@@ -19,6 +19,8 @@ import { authSourcesFromGrant, grantFromClient, grantFromRow, grantFromTokenRow
import { guestSourceSql } from '../../../core/guests/marker.ts';
import { GUEST_TRUST_CEILING } from '../../../core/guests/sources.ts';
import { ownerCredentials } from '../../../core/guests/owner-credentials.ts';
+import { GUEST_NOTES_MIGRATION } from '../../../core/guests/migration.ts';
+import { isMissingSchemaObject } from '../../../core/utils.ts';
const name = 'guest_source';
type Finding = { level: 'fail' | 'warn'; text: string; fix?: string[] };
@@ -70,6 +72,14 @@ async function sourceFindings(engine: BrainEngine, s: GuestSourceRow): Promise<F
return out;
}
+/** A schema behind the guest-notes migration has no guest_sources table: only a config can mark a guest source, and nothing enforces it. */
+async function behindGuestMigration(engine: BrainEngine): Promise<Check> {
+ const marked = await engine.executeRaw<{ id: string }>("SELECT id FROM sources WHERE COALESCE(config->>'guest' = 'true', false) ORDER BY id");
+ const behind = `this brain's schema is behind the guest-notes migration (v${GUEST_NOTES_MIGRATION}); gbrain apply-migrations --yes brings it up to date`;
+ if (!marked.length) return infoCheck(name, `Not applicable: ${behind}.`, 'not_applicable');
+ return { name, status: 'warn', message: `Source(s) ${marked.map(s => s.id).join(', ')} say guest: true in their config, but ${behind}; until then nothing enforces their writer list or trust ceiling.` };
+}
+
export async function guestSourceCheck(engine: BrainEngine): Promise<Check> {
try {
const sources = await engine.executeRaw<GuestSourceRow>(
@@ -89,6 +99,7 @@ export async function guestSourceCheck(engine: BrainEngine): Promise<Check> {
? "Read-only preview of the owner credentials that cannot read the guest source; adding it with --yes is the owner's decision."
: 'Changes how the guest source is set up or who may write it; ask the brain owner first.', name, preview ? {} : { ask_user: true }) } : {}) };
} catch (error) {
+ if (isMissingSchemaObject(error, 'table', 'guest_sources')) return behindGuestMigration(engine).catch(e => checkError(name, 'check the guest sources', e));
return checkError(name, 'check the guest sources', error);
}
}
diff --git a/src/commands/guests.ts b/src/commands/guests.ts
index e1f5dcaa63..c2ad034d24 100644
--- a/src/commands/guests.ts
+++ b/src/commands/guests.ts
@@ -30,6 +30,9 @@ export const GUESTS_USAGE = `Usage: gbrain guests init [--source <id>] [--writer
the guest source (--source, default "guests"), and with --yes adds it to their read
lists, keeping every source they already read.`;
+export { GUESTS_SUBCOMMANDS as SUBCOMMANDS } from '../cli/subcommands.ts';
+export function printUsage(): void { console.log(GUESTS_USAGE); }
+
function usageError(message: string): never {
console.error(message);
console.error(GUESTS_USAGE);
@@ -151,5 +154,5 @@ async function runGrantOwnerClients(engine: BrainEngine, rest: string[]): Promis
console.log(` ${o.kind} ${o.name} (${o.id}): ${o.outcome === 'granted' ? `now reads "${sourceId}"` : o.outcome === 'conflict'
? 'not changed: its grant changed since this preview; run the command again' : `not changed: ${o.detail}`}`);
}
- if (outcomes.some(o => o.outcome === 'conflict')) setCliExitVerdict(1);
+ if (outcomes.some(o => o.outcome === 'conflict' || o.outcome === 'failed')) setCliExitVerdict(1);
}
diff --git a/src/commands/import-source-refusal.ts b/src/commands/import-source-refusal.ts
new file mode 100644
index 0000000000..f898a2f565
--- /dev/null
+++ b/src/commands/import-source-refusal.ts
@@ -0,0 +1,22 @@
+/**
+ * The sources an ordinary `gbrain import` refuses before it reads a file: a guest source (GBRA-504: only its listed
+ * writers save pages there, through put_page) and a company-brain source outside its approved sync. runImport throws
+ * ImportAbortError with the returned reason; the CLI prints nothing more, so the reason and next step print here.
+ */
+import type { BrainEngine } from '../core/engine.ts';
+import { currentCompanyBrainSync, getCompanyBrainProfile } from '../core/company-brain/profile.ts';
+import { readGuestSource } from '../core/guests/sources.ts';
+
+/** The abort reason for a source this import may not write, after printing why; null when it may. */
+export async function importSourceRefusal(engine: BrainEngine, sourceId: string | undefined): Promise<string | null> {
+ const id = sourceId ?? 'default';
+ if (await readGuestSource(engine, id)) {
+ console.error(`source_writer_restricted: source ${id} is a guest source; only its listed writers save pages there, through put_page. Import into another source.`);
+ return 'source_writer_restricted: guest sources take no import';
+ }
+ if (!currentCompanyBrainSync(sourceId) && await getCompanyBrainProfile(engine, id)) {
+ console.error('This source accepts only its approved committed company-brain manifest. Use sources resume or sync; ordinary import cannot write back to this read-only repository.');
+ return 'company-brain sources require approved committed ingestion';
+ }
+ return null;
+}
diff --git a/src/commands/import.ts b/src/commands/import.ts
index 3c92345a33..1943780ffb 100644
--- a/src/commands/import.ts
+++ b/src/commands/import.ts
@@ -14,7 +14,7 @@ import { OperationError } from '../core/ops/contract.ts';
import { importFile, importImageFile, isImageFilePath, type ImportResult } from '../core/import-file.ts';
import { gitFirstCommitDates } from '../core/git-first-commit.ts';
import { gitLsFiles } from '../core/git-visible-files.ts';
-import { currentCompanyBrainSync, getCompanyBrainProfile, importCompanyBrainFile } from '../core/company-brain/profile.ts';
+import { currentCompanyBrainSync, importCompanyBrainFile } from '../core/company-brain/profile.ts';
import { loadConfig, gbrainPath } from '../core/config.ts';
import { createProgress } from '../core/progress.ts';
import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';
@@ -51,7 +51,7 @@ import { getEmbeddingModel } from '../core/ai/gateway.ts';
import { managedRootMarkerFor } from '../core/persistence/root-registry.ts';
import { readManagedMode } from '../core/persistence/ownership.ts';
import { readPageBodyPolicy } from '../core/page-body/limits.ts';
-import { readGuestSource } from '../core/guests/sources.ts';
+import { importSourceRefusal } from './import-source-refusal.ts';
/** Return a refusal when an import target lies outside every admitted root. */
export function configuredRootImportError(dir: string, configuredRoots: string[]): string | null {
@@ -468,14 +468,8 @@ export async function runImport(
}
}
}
- if (await readGuestSource(engine, sourceId ?? 'default')) {
- console.error(`source_writer_restricted: source ${sourceId ?? 'default'} is a guest source; only its listed writers save pages there, through put_page. Import into another source.`);
- throw new ImportAbortError('source_writer_restricted: guest sources take no import');
- }
- if (!currentCompanyBrainSync(sourceId) && await getCompanyBrainProfile(engine, sourceId ?? 'default')) {
- console.error('This source accepts only its approved committed company-brain manifest. Use sources resume or sync; ordinary import cannot write back to this read-only repository.');
- throw new ImportAbortError('company-brain sources require approved committed ingestion');
- }
+ const refusedSource = await importSourceRefusal(engine, sourceId);
+ if (refusedSource) throw new ImportAbortError(refusedSource);
let importActivePack: { page_types: ReadonlyArray<{ name: string; path_prefixes: ReadonlyArray<string>; aliases?: ReadonlyArray<string> }> } | undefined;
try {
const { loadActivePackForEngine } = await import('../core/schema-pack/engine-resolution.ts');
diff --git a/src/core/access/actor-model.ts b/src/core/access/actor-model.ts
index 4d845714fc..54c1dfd517 100644
--- a/src/core/access/actor-model.ts
+++ b/src/core/access/actor-model.ts
@@ -30,7 +30,7 @@ export const SCOPE_ATTEST_OPS: ReadonlySet<string> = new Set(['forget', 'forget_
*/
export const ACTOR_DEFERRED_OPS: ReadonlySet<string> = new Set([
'list_write_conflicts',
- 'capture', 'extract_facts', 'ontology_propose', 'confirm_memory', 'loops_close',
+ 'capture', 'extract_facts', 'ontology_propose', 'confirm_memory', 'promote_guest_note', 'loops_close',
'takes_add', 'takes_update', 'takes_resolve', 'takes_supersede',
'add_timeline_entry', 'add_link', 'remove_link', 'add_tag', 'remove_tag',
'put_page', 'put_pages', 'edit_page', 'append_page', 'delete_page', 'restore_page', 'revert_version',
diff --git a/src/core/cycle.ts b/src/core/cycle.ts
index a29ecfd647..9012621910 100644
--- a/src/core/cycle.ts
+++ b/src/core/cycle.ts
@@ -1915,6 +1915,15 @@ export async function runCycle(
/** #7241: tell `opts.onPhaseStart` a selected phase is starting; a hook error is logged, never fatal. */
const notifyPhaseStart = (opts: CycleOpts, phase: CyclePhase, phases: readonly CyclePhase[]): Promise<void> => Promise.resolve().then(() => opts.onPhaseStart?.(phase, phases.indexOf(phase), phases.length)).then(() => undefined, (e: unknown) => { console.warn(`[cycle] onPhaseStart hook error (non-fatal): ${e instanceof Error ? e.message : String(e)}`); });
+/** GBRA-504: a cycle scoped to a guest source skips every phase that would derive rows from guest pages (guests/derived.ts); each is reported skipped. */
+async function withoutGuestPhases(engine: BrainEngine | null, sourceId: string | undefined, phases: CyclePhase[], phaseResults: PhaseResult[]): Promise<CyclePhase[]> {
+ if (!engine || !sourceId || !await (await import('./guests/note.ts')).isGuestSource(engine, sourceId)) return phases;
+ const guestSkipped = new Set((await import('./guests/derived.ts')).guestSkippedPhases());
+ for (const phase of phases.filter(p => guestSkipped.has(p))) phaseResults.push({ phase, status: 'skipped', duration_ms: 0,
+ summary: 'skipped on a guest source: guest notes feed no derived rows', details: { reason: 'guest_source', source_id: sourceId } });
+ return phases.filter(p => !guestSkipped.has(p));
+}
+
async function runCycleUnscoped(
engine: BrainEngine | null,
opts: CycleOpts,
@@ -1942,14 +1951,7 @@ async function runCycleUnscoped(
phase_scope: PHASE_SCOPE[phase],
},
}));
- // GBRA-504: a cycle scoped to a guest source skips every phase that would derive rows from guest pages (guests/derived.ts).
- if (engine && opts.sourceId && await (await import('./guests/note.ts')).isGuestSource(engine, opts.sourceId)) {
- const guestSkipped = new Set((await import('./guests/derived.ts')).guestSkippedPhases());
- for (const phase of phases.filter(p => guestSkipped.has(p))) phaseResults.push({ phase, status: 'skipped', duration_ms: 0,
- summary: 'skipped on a guest source: guest notes feed no derived rows', details: { reason: 'guest_source', source_id: opts.sourceId } });
- phases = phases.filter(p => !guestSkipped.has(p));
- }
-
+ phases = await withoutGuestPhases(engine, opts.sourceId, phases, phaseResults);
// Capture as a const so it narrows to `string` inside the `else` branches of
// the per-phase `if (brainDir === null)` guards, even within async closures
// (const bindings narrow across closures; property accesses don't).
diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.ts
index 8cb4559ee3..46e5c68b04 100644
--- a/src/core/cycle/extract-facts.ts
+++ b/src/core/cycle/extract-facts.ts
@@ -809,19 +809,9 @@ const FACTS_WALK_YIELD_EVERY = 50;
* an ExtractFactsResult envelope; status mapping (ok / warn / fail)
* happens in the cycle.ts caller.
*/
-export async function runExtractFacts(
- engine: BrainEngine,
- opts: ExtractFactsOpts = {},
-): Promise<ExtractFactsResult> {
- const sourceId = opts.sourceId ?? 'default';
- // Managed brains reconcile the same way, but each page's writes publish as
- // a receipted database-only maintenance request. The authority is
- // preflighted on the first page that needs a write, so a run with nothing
- // to change never needs one; an unacceptable caller still refuses first.
- const managed = await maintenanceCallerPreflight(engine, sourceId);
- let authority: Promise<MaintenanceAuthority | null> | undefined;
- const managedAuthority = () => managed ? authority ??= maintenancePreflight(engine, sourceId) : Promise.resolve(null);
- const result: ExtractFactsResult = {
+/** A run's counters before it scans anything; a guest source's run returns them unchanged. */
+function emptyExtractFactsResult(): ExtractFactsResult {
+ return {
pagesScanned: 0,
pagesWithFacts: 0,
factsInserted: 0,
@@ -842,6 +832,21 @@ export async function runExtractFacts(
phantomsLockBusy: false,
phantomsMorePending: false,
};
+}
+
+export async function runExtractFacts(
+ engine: BrainEngine,
+ opts: ExtractFactsOpts = {},
+): Promise<ExtractFactsResult> {
+ const sourceId = opts.sourceId ?? 'default';
+ // Managed brains reconcile the same way, but each page's writes publish as
+ // a receipted database-only maintenance request. The authority is
+ // preflighted on the first page that needs a write, so a run with nothing
+ // to change never needs one; an unacceptable caller still refuses first.
+ const managed = await maintenanceCallerPreflight(engine, sourceId);
+ let authority: Promise<MaintenanceAuthority | null> | undefined;
+ const managedAuthority = () => managed ? authority ??= maintenancePreflight(engine, sourceId) : Promise.resolve(null);
+ const result = emptyExtractFactsResult();
if (await (await import('../guests/derived.ts')).skipsGuestSource(engine, 'extract_facts', sourceId)) return result;
// ── Fence unfenced rows (#5299) ─────────────────────────────────
diff --git a/src/core/eligibility/stamp.ts b/src/core/eligibility/stamp.ts
index a528248c61..56e514b460 100644
--- a/src/core/eligibility/stamp.ts
+++ b/src/core/eligibility/stamp.ts
@@ -28,7 +28,7 @@ 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 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,
+const trustColumns = (guestSql: (config: string, id: string) => string) => `pages.id, pages.source_id, pages.slug, trust_tier, 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`;
/**
diff --git a/src/core/guests/admission.ts b/src/core/guests/admission.ts
index 0fabcd2da6..435f6d3817 100644
--- a/src/core/guests/admission.ts
+++ b/src/core/guests/admission.ts
@@ -166,23 +166,16 @@ export async function assertGuestReaders(engine: Pick<BrainEngine, 'getConfig'>,
return audience[0]!;
}
-/** Publication's recheck: the source is still a guest source and the request's principal is still a listed writer. */
-export async function assertGuestWriterAtPublication(tx: Pick<BrainEngine, 'executeRaw'>, row: { source_id: string; principal_kind: string; principal_id: string }): Promise<void> {
- const [guest] = await tx.executeRaw<{ writers: string[] }>('SELECT writers FROM guest_sources WHERE source_id = $1 FOR SHARE', [row.source_id]);
- if (!guest || !guest.writers.includes(`${row.principal_kind}:${row.principal_id}`)) throw sourceWriterRestricted(row.source_id);
-}
-
/**
- * Publication's check for a write that carries no guest note (it was admitted before its source became a guest
- * source): a listed writer's put_page is guest_attribution_missing, any other listed writer's write is
- * guest_page_immutable, and anyone else is source_writer_restricted. Nothing publishes.
+ * Publication's recheck: the source is still a guest source and the request's principal is still a listed writer. The
+ * same statement sets gbrain.guest_note to the request's id (the gbrain.write_request it publishes as), which the guest-source trigger (trust/schema.ts GUEST_GUARD)
+ * requires of a listed writer's page write; any other write to a guest source, such as one admitted before its source
+ * became a guest source, is refused there (source_writer_restricted or guest_attribution_missing) with no read here.
*/
-export async function assertNoGuestSourceAtPublication(tx: Pick<BrainEngine, 'executeRaw'>, row: { source_id: string; operation: string; principal_kind: string; principal_id: string }): Promise<void> {
- const [guest] = await tx.executeRaw<{ writers: string[] }>('SELECT writers FROM guest_sources WHERE source_id = $1 FOR SHARE', [row.source_id]);
- if (!guest) return;
- if (!guest.writers.includes(`${row.principal_kind}:${row.principal_id}`)) throw sourceWriterRestricted(row.source_id);
- if (row.operation === 'put_page') throw guestAttributionMissing('the source became a guest source after this write was submitted');
- throw guestPageImmutable(`${row.operation} on a source that became a guest source after this write was submitted`);
+export async function assertGuestWriterAtPublication(tx: Pick<BrainEngine, 'executeRaw'>, row: { source_id: string; principal_kind: string; principal_id: string; id: string }): Promise<void> {
+ const [guest] = await tx.executeRaw<{ writers: string[] }>(
+ "SELECT writers, set_config('gbrain.guest_note', $2, true) AS guest_note FROM guest_sources WHERE source_id = $1 FOR SHARE", [row.source_id, row.id]);
+ if (!guest || !guest.writers.includes(`${row.principal_kind}:${row.principal_id}`)) throw sourceWriterRestricted(row.source_id);
}
/** The guest mark, written in the publication transaction right after the page row. */
diff --git a/src/core/guests/marker.ts b/src/core/guests/marker.ts
index 0af43f7c5f..4be4a83975 100644
--- a/src/core/guests/marker.ts
+++ b/src/core/guests/marker.ts
@@ -29,10 +29,13 @@ export async function withGuestSourceSql<T>(read: (guestSql: typeof guestSourceS
}
}
-/** Whether any source is a guest source, read from the sources themselves on every call; a failed read answers yes. */
+/**
+ * Whether any source is a guest source, read from the sources themselves on every call; a failed read answers yes. Like
+ * search's read policy (search/read-policy-sql.ts), it reads sources as `read_source`: a live read check, not a listing.
+ */
export async function brainHasGuestSource(engine: Pick<BrainEngine, 'executeRaw'>): Promise<boolean> {
try {
- const [row] = await engine.executeRaw<{ present: boolean }>(`SELECT EXISTS (SELECT 1 FROM sources s WHERE ${guestSourceSql('s.config', 's.id')}) AS present`);
+ const [row] = await engine.executeRaw<{ present: boolean }>(`SELECT EXISTS (SELECT 1 FROM sources read_source WHERE ${guestSourceSql('read_source.config', 'read_source.id')}) AS present`);
return row?.present !== false;
} catch { return true; }
}
@@ -83,6 +86,17 @@ export function guestAnswerLine(slugs: readonly string[]): string {
return `Uses outside-guest notes: ${[...new Set(slugs)].join(', ')} (${NOT_OWNER}).`;
}
+/**
+ * think's result fields for the pages it gathered: `result` as given, or, when a guest note reached the prompt, its answer
+ * ending with guestAnswerLine and `guest_evidence` naming each such note.
+ */
+export function withGuestAnswer<T extends { answer?: string }>(pages: ReadonlyArray<{ source_id?: string | null; slug: string; guest?: GuestStamp }>, result: T):
+ T & { guest_evidence?: Array<{ source_id: string; slug: string; guest: GuestStamp }> } {
+ const evidence = pages.flatMap(pg => pg.guest ? [{ source_id: pg.source_id ?? 'default', slug: pg.slug, guest: pg.guest }] : []);
+ if (!evidence.length) return result;
+ return { ...result, answer: `${(result.answer ?? '').trimEnd()}\n\n${guestAnswerLine(evidence.map(g => g.slug))}`, guest_evidence: evidence };
+}
+
/** The guest object a caller sees: the writer only for an owner caller. */
export function guestView(stamp: GuestStamp, owner: boolean): GuestStamp {
const { writer, ...rest } = stamp;
diff --git a/src/core/guests/owner-credentials.ts b/src/core/guests/owner-credentials.ts
index c2489326d1..e094d18d18 100644
--- a/src/core/guests/owner-credentials.ts
+++ b/src/core/guests/owner-credentials.ts
@@ -77,12 +77,13 @@ export async function ownerCredentials(engine: BrainEngine, guestSourceId: strin
}) };
}
-export interface GrantOutcome { kind: 'client' | 'token'; id: string; name: string; outcome: 'granted' | 'conflict' | 'skipped'; detail?: string }
+export interface GrantOutcome { kind: 'client' | 'token'; id: string; name: string; outcome: 'granted' | 'conflict' | 'skipped' | 'failed'; detail?: string }
/**
* Adds guestSourceId to the read list of each previewed credential that lacks it, at the revision the preview read.
* A grant changed since (another edit, a rescope) is a conflict and stays as it is; each result is read back and must
- * equal the previewed list plus the guest source.
+ * equal the previewed list plus the guest source. Any other failure is that credential's outcome (failed, with the
+ * error), so one credential never stops the others.
*/
export async function grantOwnerCredentials(engine: BrainEngine, guestSourceId: string, plan: readonly OwnerCredential[]): Promise<GrantOutcome[]> {
const out: GrantOutcome[] = [];
@@ -103,8 +104,8 @@ export async function grantOwnerCredentials(engine: BrainEngine, guestSourceId:
}
out.push({ ...base, outcome: 'granted' });
} catch (e) {
- if (e instanceof GrantError && e.code === 'grant_conflict') { out.push({ ...base, outcome: 'conflict', detail: e.message }); continue; }
- throw e;
+ const conflict = e instanceof GrantError && e.code === 'grant_conflict';
+ out.push({ ...base, outcome: conflict ? 'conflict' : 'failed', detail: e instanceof Error ? e.message : String(e) });
}
}
return out;
diff --git a/src/core/guests/promote.ts b/src/core/guests/promote.ts
index 36f25f7df1..d7ebb9aa41 100644
--- a/src/core/guests/promote.ts
+++ b/src/core/guests/promote.ts
@@ -13,20 +13,25 @@
import { OperationError, type OperationContext } from '../ops/contract.ts';
import { federatedSearchScope } from '../ops/context.ts';
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';
const DOCS = 'docs/guides/write-refusals.md#guest_promotion_owner_only';
-export function guestPromotionOwnerOnly(): OperationError {
+export function guestPromotionOwnerOnly(slug: unknown): OperationError {
+ const command = typeof slug === 'string' && slug.trim() ? 'gbrain guests promote ' + slug.trim().toLowerCase() : 'gbrain guests promote with the note\'s slug';
return new OperationError('guest_promotion_owner_only', 'Only the brain owner can keep a guest note as an owner page, so nothing was read or written.',
- 'Do not retry. Ask the brain owner; if they want to keep the note, they run gbrain guests promote <slug> on the brain host.', DOCS);
+ 'Do not retry. Ask the brain owner; if they want to keep the note, they run ' + command + ' on the brain host.', DOCS);
}
-/** The owner, and only the owner, may promote (see the module comment). */
+/**
+ * The owner, and only the owner, may promote (see the module comment). Enforced-member mode never reaches here as a
+ * trusted local caller: its gate (cli/enforced-member-classes.ts) refuses gbrain guests and promote_guest_note.
+ */
export function isGuestPromotionOwner(ctx: Pick<OperationContext, 'remote' | 'viaSubagent' | 'accessIdentity' | 'applyRemoteReadPolicy'>): boolean {
if (ctx.viaSubagent) return false;
- if (ctx.remote === false) return process.env.GBRAIN_ENFORCED_MEMBER === undefined && !ctx.applyRemoteReadPolicy && !ctx.accessIdentity?.length;
+ if (ctx.remote === false) return !ctx.applyRemoteReadPolicy && !ctx.accessIdentity?.length;
const access = currentCallerAccess();
return access.owner === true && !access.actor;
}
@@ -56,7 +61,7 @@ async function guestNote(ctx: OperationContext, slug: string, guestSource: strin
}
export async function promoteGuestNote(ctx: OperationContext, p: Record<string, unknown>): Promise<Record<string, unknown>> {
- if (!isGuestPromotionOwner(ctx)) throw guestPromotionOwnerOnly();
+ if (!isGuestPromotionOwner(ctx)) throw guestPromotionOwnerOnly(p.slug);
const slug = text(p.slug, 'slug', true)!.toLowerCase();
const note = await guestNote(ctx, slug, text(p.guest_source, 'guest_source'));
const { pageMutationSource, submitPageMutation, requestPrincipalForContext } = await import('../persistence/page-mutations.ts');
@@ -72,6 +77,7 @@ export async function promoteGuestNote(ctx: OperationContext, p: Record<string,
if (kept) return { status: 'already_promoted', ...result };
const page = await ctx.engine.getPage(slug, { sourceId: note.source_id });
if (!page) throw new OperationError('page_not_found', 'Guest note ' + slug + ' was deleted while it was promoted; nothing was written.', 'Ask the brain owner to restore it, then promote it again.');
+ assertInlineBody(page, 'promote_guest_note');
const readers = page.frontmatter?.readable_by;
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: [] });
diff --git a/src/core/guests/publication.ts b/src/core/guests/publication.ts
new file mode 100644
index 0000000000..7222c0999a
--- /dev/null
+++ b/src/core/guests/publication.ts
@@ -0,0 +1,33 @@
+/**
+ * Guest notes (GBRA-504): what page preparation needs for a guest write, kept beside admission so page-prepare.ts
+ * only calls it. prepareGuestWrite reads it once per write (before the snapshot); page-prepare.ts guardGuestPublication
+ * adds the publication-time checks.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { parseMarkdownHead } from '../markdown.ts';
+import type { WriteRequest } from '../persistence/model.ts';
+import { assertGuestReaders } from './admission.ts';
+import { isGuestWrite } from './derived.ts';
+import { storedGuestNote, type GuestAttribution } from './note.ts';
+
+export interface GuestWrite {
+ /** A guest write for the publication-time producers (derived.ts isGuestWrite): a guest note, or any write to a guest source. */
+ write: boolean;
+ note: GuestAttribution | null;
+ /** The note's one audience principal, checked against its readers; null without a note. */
+ audience: string | null;
+}
+
+export const NOT_A_GUEST_WRITE: GuestWrite = { write: false, note: null, audience: null };
+
+/**
+ * The guest reads of one page write. A note's readers are checked here, at preparation, as they were at submission.
+ * Throws when the guest-source lookup fails, so the write refuses instead of publishing derived rows.
+ */
+export async function prepareGuestWrite(engine: BrainEngine, row: WriteRequest, content: unknown): Promise<GuestWrite> {
+ const note = storedGuestNote(row.intent);
+ const write = await isGuestWrite(engine, row.source_id, row.intent);
+ if (!note) return { write, note, audience: null };
+ const frontmatter = typeof content === 'string' ? parseMarkdownHead(content).frontmatter : {};
+ return { write, note, audience: await assertGuestReaders(engine, frontmatter, Array.isArray(row.authority.actingFor) ? row.authority.actingFor : null) };
+}
diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.ts
index 27da9fb221..ee8a6df07e 100644
--- a/src/core/persistence/page-mutations.ts
+++ b/src/core/persistence/page-mutations.ts
@@ -46,13 +46,13 @@ import { colonSlugWindowsRefusal, isWindowsColonTarget } from './native-file-tar
import { CALLER_CONTENT_OPERATIONS, publishesDatabaseOnly } from './page-prepare.ts';
import { isSegmentedPage } from '../page-body/page-shape.ts';
import { liveSearchable } from './searchable.ts';
-import { cachedPreadmitBrain, dropPreadmitCache, preadmitReads, preadmitRecheckFailed } from './preadmit-cache.ts';
+import { ADMISSION_SOURCE_SQL, cachedPreadmitBrain, dropPreadmitCache, preadmitReads, preadmitRecheckFailed } from './preadmit-cache.ts';
import { pipelined } from '../page-state/transactions.ts';
import { holdsSummarizedToolCalls, isQuotedPageType, quotesTier, unquoteTranscriptText } from '../search/transcript-quote.ts';
import { readStoredBody } from '../facts/file-body-guard.ts';
import { isMirrorOnlyPage, sourceMirrorReadOnly } from './mirror-read-only.ts';
import { perCallWriteSource } from '../access/attest-sources.ts';
-import { readGuestSource, type GuestSource } from '../guests/sources.ts';
+import type { GuestSource } from '../guests/sources.ts';
import { admitGuestOperation, assertGuestFrontmatter, assertGuestReaders, GUEST_NOTE_INTENT_KEY, guestPageImmutable, refuseRemoteGuestDelete } from '../guests/admission.ts';
import { currentCallerAccess } from '../search/private-visibility.ts';
import { assertStorageSourceWriter } from '../storage-manifest/door.ts';
@@ -79,11 +79,11 @@ const flatSql = (sql: string) => sql.replace(/\s+/g, ' ').trim();
* import's source-root and company-profile checks. All of them are rechecked
* under lock by the admission transaction or by publication.
*/
+type AdmissionSource = { incarnation: string; archived: boolean; local_path: string | null; kind: string | null; role: string | null; guest_writers: string[] | null; guest_trust_ceiling: string | null };
const BATCH_SHARED_READS = new Set([
- "SELECT incarnation,archived,local_path,config->>'kind' AS kind,config->>'role' AS role FROM sources WHERE id=$1",
+ ADMISSION_SOURCE_SQL,
'SELECT s.source_id,s.source_incarnation,s.worktree_id,s.relative_path, s.topology_generation::text AS topology_generation,w.owner_host_id,w.owner_epoch::text AS owner_epoch,w.state, h.local_path,h.coordination_path FROM persistence_source_bindings s JOIN persistence_worktrees w ON w.id=s.worktree_id LEFT JOIN persistence_host_bindings h ON h.worktree_id=w.id AND h.host_id=$2::uuid WHERE s.source_id=$1',
'SELECT lane,revoked_at,grant_ceiling FROM persistence_local_writers WHERE id=$1::uuid',
- 'SELECT source_id, writers, trust_ceiling FROM guest_sources WHERE source_id = $1',
'SELECT local_path FROM sources WHERE id=$1 AND incarnation=$2::uuid',
'SELECT brain_id FROM persistence_brain WHERE singleton=1',
'SELECT value FROM config WHERE key=$1',
@@ -410,11 +410,12 @@ export async function preparePageAdmission(ctx: OperationContext,
const captureSlug = input.operation === 'capture' ? await resolveCaptureFile(ctx, sourceId, p) : null;
const principal = await requestPrincipalForContext(ctx);
// Independent reads go out together on Postgres; the first refusal in this order is the one reported.
- const [, prior, guest] = await pipelined(ctx.engine, [
+ const [, prior, [source]] = await pipelined(ctx.engine, [
() => assertPageRequestIdentity(ctx.engine, principal, requestId),
() => getWriteRequest(ctx.engine, principal, requestId),
- () => readGuestSource(ctx.engine, sourceId),
- ]) as [unknown, WriteRequest | null, GuestSource | null];
+ () => ctx.engine.executeRaw<AdmissionSource>(ADMISSION_SOURCE_SQL, [sourceId]),
+ ]) as [unknown, WriteRequest | null, AdmissionSource[]];
+ const guest: GuestSource | null = source?.guest_writers ? { source_id: sourceId, writers: source.guest_writers, trust_ceiling: source.guest_trust_ceiling! } : null;
// GBRA-504: a guest source admits only its listed writers' plain put_page, carrying the guest attribution, which joins
// the intent (and so the replay identity) here; every other write to it is refused before anything is journaled.
const guestNote = guest ? admitGuestOperation(guest, { principal, operation: input.operation, remote: ctx.remote !== false,
@@ -436,8 +437,6 @@ export async function preparePageAdmission(ctx: OperationContext,
}
if (input.operation === 'delete_page') assertPurgeParams(p, ctx.remote);
if (guest && input.operation === 'delete_page' && ctx.remote !== false && typeof p.slug === 'string') await refuseRemoteGuestDelete(ctx.engine, sourceId, p.slug.toLowerCase(), principal);
- const [source] = await ctx.engine.executeRaw<{ incarnation: string; archived: boolean; local_path: string | null; kind: string | null; role: string | null }>(
- "SELECT incarnation,archived,local_path,config->>'kind' AS kind,config->>'role' AS role FROM sources WHERE id=$1", [sourceId]);
if (!source || source.archived) {
throw new OperationError('source_changed', 'The write source is not active.',
`Source ${sourceId} is archived or not registered, so nothing was written. Write to an active source (sources_list shows them).`);
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index 32bbe68f7b..0cb49b60d1 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -107,9 +107,9 @@ import { gateField, gateInput } from '../trust/gate-outcomes.ts';
import { PUSH_SCAN_MAX_FILE_BYTES } from '../page-size-policy.ts';
import { fileContentHash, FileBytes, isStreamedContent, LARGE_FILE_MIN_BYTES, StreamedFileContent } from './large-file.ts';
import { bindOrigin } from './origin-guard.ts';
-import { assertGuestReaders, assertGuestWriterAtPublication, assertNoGuestSourceAtPublication, insertGuestMark, refuseRemoteGuestDelete } from '../guests/admission.ts';
-import { readGuestSourceIds, storedGuestNote } from '../guests/note.ts';
-import { isGuestWrite, skipsGuestNote } from '../guests/derived.ts';
+import { assertGuestWriterAtPublication, insertGuestMark, refuseRemoteGuestDelete } from '../guests/admission.ts';
+import { skipsGuestNote } from '../guests/derived.ts';
+import { NOT_A_GUEST_WRITE, prepareGuestWrite, type GuestWrite } from '../guests/publication.ts';
const ownerStatusFix = (sourceId: string): Action => readFix(`Shows source ${sourceId}'s canonical owner with its pending, failed and recovering requests, read-only.`,
@@ -995,7 +995,8 @@ export async function preparePageMutation(unbounded: BrainEngine, row: WriteRequ
signal?.throwIfAborted();
return prepareStagedUpload(unbounded, row, staged => preparePageMutation(unbounded, staged, _config, preparedIntent, signal, options));
}
- return prepareInlineOrSegmentedMutation(unbounded, row, _config, preparedIntent, signal, options);
+ return prepareInlineOrSegmentedMutation(unbounded, row, _config, preparedIntent, signal, options,
+ row.operation === 'delete_page' ? NOT_A_GUEST_WRITE : await prepareGuestWrite(unbounded, row, preparedIntent?.content ?? row.intent?.content));
}
/** A remote caller's refusal names the line, never a key: keys can be private, and the receipt keeps the message. */
@@ -1028,7 +1029,7 @@ function remoteCoreMarkingKept(row: WriteRequest, snapshot: PageSnapshot | null,
async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: WriteRequest, _config: Parameters<typeof preparePageMutation>[2],
preparedIntent: Parameters<typeof preparePageMutation>[3], signal: AbortSignal | undefined,
- options: NonNullable<Parameters<typeof preparePageMutation>[5]>): Promise<PreparedMutation> {
+ options: NonNullable<Parameters<typeof preparePageMutation>[5]>, guest: GuestWrite): Promise<PreparedMutation> {
signal?.throwIfAborted();
const clock = options.clock;
const engine = boundedReads(unbounded, clock);
@@ -1083,8 +1084,7 @@ async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: Wri
if (!snapshot) throw pageRefusal('page_not_found', 'Page not found.', row,
`Page ${row.slug} does not exist in source ${row.source_id} (it was purged or never written), so nothing was ${row.operation === 'restore_page' ? 'restored' : 'reverted'}. Check the slug and the source.`,
pageFix(row.source_id, row.slug));
- if (row.operation === 'restore_page' && bodyUnread(snapshot.page)) return prepareUnreadRestore(engine, row, snapshot, { activePack, clock, allowMissingFile: options.allowMissingFile });
- if (row.operation === 'restore_page' && (await readGuestSourceIds(engine, [row.source_id])).has(row.source_id)) return prepareGuestRestore(engine, row, snapshot);
+ if (row.operation === 'restore_page' && (guest.write || bodyUnread(snapshot.page))) return guest.write ? prepareGuestRestore(engine, row, snapshot) : prepareUnreadRestore(engine, row, snapshot, { activePack, clock, allowMissingFile: options.allowMissingFile });
let page = snapshot.page;
let tags = snapshot.tags;
if (row.operation === 'revert_version') {
@@ -1111,9 +1111,7 @@ async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: Wri
...(snapshot?.page??{id:0,source_id:row.source_id,created_at:new Date(),updated_at:new Date()}),...parsed,compiled_truth,timeline},parsed.tags);
}
content = remoteCoreMarkingKept(row, snapshot, content, activePack);
- const guestNote = storedGuestNote(p);
- const guestWrite = await isGuestWrite(engine, row.source_id, p);
- const projected = !skipsGuestNote('publication_projections', guestWrite) && !(options.unprojected || row.operation === 'remember' || row.operation.startsWith('takes_') || (row.operation === 'extract_facts' && p.kind === 'managed_facts_entity'));
+ const projected = !skipsGuestNote('publication_projections', guest.write) && !(options.unprojected || row.operation === 'remember' || row.operation.startsWith('takes_') || (row.operation === 'extract_facts' && p.kind === 'managed_facts_entity'));
const writer = replacesTombstone || ((row.operation === 'put_page' || row.operation === 'edit_page') && p.kind !== 'managed_maintenance_page'
&& (preparedIntent !== undefined || typeof p.expected_revision === 'string')) ? 'editing' : 'preserving';
// #5969 (D3): only an ordinary put_page intent carries a timeline section; every other writer keeps the shared policy.
@@ -1149,7 +1147,6 @@ async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: Wri
// #5575: the page's tier, computed once before import so the write gate sees exactly it (ENG-18).
const incoming = typeof content === 'string' && !isFenceEditWrite(row) ? parseMarkdown(content, row.slug, { activePack }).frontmatter : null;
const trust = provenanceWriteTrust(row, incoming, snapshot?.page.frontmatter);
- const guestAudience = guestNote ? await assertGuestReaders(engine, incoming ?? {}, Array.isArray(row.authority.actingFor) ? row.authority.actingFor : null) : null;
const gateTrust = pageGateTrust(row, trust, storedTier);
// GST-2518: a lower-tier local write keeps the page's privacy labels it would widen (GST-2521: and the owner as a reader); its proposal carries the request.
const labelGuard = await privacyLabelGuard(engine, row, trust, snapshot?.page ?? null, storedTier, incoming);
@@ -1232,7 +1229,7 @@ async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: Wri
const [project, advisories, links, target, core] = await pipelined(together, [
async () => projected ? prepareCanonicalProjections(engine,ready.parsedPage,row.slug,row.source_id,snapshot,writer,timelinePolicy) : undefined,
async () => noop || targetDeleted ? pageNoopAdvisories(row) : !ordinaryPage ? remoteLinkHint(row) : preparePageAdvisories(engine,row,ready.parsedPage,snapshot),
- async () => !skipsGuestNote('auto_links', guestWrite) && !noop && !targetDeleted && autoLinkedPage && (row.authority.autoLinkTrusted ?? !row.authority.remote) && await isAutoLinkEnabled(engine)
+ async () => !skipsGuestNote('auto_links', guest.write) && !noop && !targetDeleted && autoLinkedPage && (row.authority.autoLinkTrusted ?? !row.authority.remote) && await isAutoLinkEnabled(engine)
? prepareAutomaticLinks(engine,row.slug,ready.parsedPage,row.source_id,options.coordinated === true) : undefined,
() => prepareFileTarget(engine, row, snapshot, targetDeleted ? null : rendered, undefined, { capture, allowMissing: options.allowMissingFile, activePack, remote: row.authority.remote, newPageIgnoredDatabaseOnly: true, clock, labelEdit: row.operation === 'submit_job' && p.kind === 'managed_maintenance_page' ? readLabelEdit(p.label_edit) : undefined }),
// Always-loaded core tier: owner-only marking, brain-wide budget, remote-edit policy (core-guard.ts).
@@ -1332,20 +1329,7 @@ async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: Wri
// DX-1: a guarded supersession reports contested (the first proposal; every one when the write contested several rows).
...(contested.length ? { contested: { proposal_ref: contested[0], ...(contested.length > 1 ? { proposal_refs: contested } : {}) } } : {}) };
} };
- if (guestNote && guestAudience) {
- const { validate, apply } = publication;
- publication.validate = async tx => { await validate?.(tx); await assertGuestWriterAtPublication(tx, row); };
- publication.apply = async (tx, preimage) => {
- const out = await apply(tx, preimage);
- if (!noop) await insertGuestMark(tx, row, guestNote, guestAudience);
- return out;
- };
- } else {
- // A write admitted before its source became a guest source carries no guest note: it never publishes there.
- const { validate } = publication;
- publication.validate = async tx => { await validate?.(tx); await assertNoGuestSourceAtPublication(tx, row); };
- }
- return publication;
+ return guardGuestPublication(publication, row, guest, noop);
}
/** What a page's projections report back: removed timeline rows and the contested proposal refs (#5575 guarded supersession). */
@@ -1359,3 +1343,21 @@ function editLockedPage(row: WriteRequest, snapshot: PageSnapshot | null) {
pageFix(row.source_id, row.slug));
return applyPageEdits(snapshot.page, snapshot.tags, row.authority.remote, parsePageEdits(row.intent?.edits), parseEditWithin(row.intent?.within));
}
+
+/**
+ * A guest note's publication with the guest checks of guests/admission.ts added to its validate and apply. Any other
+ * write is returned as it is: the guest-source trigger refuses it in a source that became a guest source after it was
+ * admitted, so it publishes no extra statement.
+ */
+function guardGuestPublication(publication: PreparedMutation, row: WriteRequest, guest: GuestWrite, noop: boolean): PreparedMutation {
+ const { validate, apply } = publication;
+ const { note, audience } = guest;
+ if (!note || !audience) return publication;
+ publication.validate = async tx => { await validate?.(tx); await assertGuestWriterAtPublication(tx, row); };
+ publication.apply = async (tx, preimage) => {
+ const out = await apply(tx, preimage);
+ if (!noop) await insertGuestMark(tx, row, note, audience);
+ return out;
+ };
+ return publication;
+}
diff --git a/src/core/persistence/preadmit-cache.ts b/src/core/persistence/preadmit-cache.ts
index d9e79e9dac..b7d3b6a723 100644
--- a/src/core/persistence/preadmit-cache.ts
+++ b/src/core/persistence/preadmit-cache.ts
@@ -23,7 +23,11 @@ import { registerEngineView, writeSwitchOn } from './switches.ts';
export const PREADMIT_TTL_MS = 30_000;
const BRAIN_SQL = 'SELECT brain_id FROM persistence_brain WHERE singleton=1';
-const SOURCE_SQL = "SELECT incarnation,archived,local_path,config->>'kind' AS kind,config->>'role' AS role FROM sources WHERE id=$1";
+/**
+ * Page admission's source row and, in the same statement, its guest_sources row (GBRA-504). A row worth caching has a
+ * local path, and a source with one is never a guest source (the database refuses it: guest_source_database_only).
+ */
+export const ADMISSION_SOURCE_SQL = "SELECT s.incarnation,s.archived,s.local_path,s.config->>'kind' AS kind,s.config->>'role' AS role,g.writers AS guest_writers,g.trust_ceiling AS guest_trust_ceiling FROM sources s LEFT JOIN guest_sources g ON g.source_id=s.id WHERE s.id=$1";
const BINDING_SQL = 'SELECT s.source_id,s.source_incarnation,s.worktree_id,s.relative_path, s.topology_generation::text AS topology_generation,w.owner_host_id,w.owner_epoch::text AS owner_epoch,w.state, h.local_path,h.coordination_path FROM persistence_source_bindings s JOIN persistence_worktrees w ON w.id=s.worktree_id LEFT JOIN persistence_host_bindings h ON h.worktree_id=w.id AND h.host_id=$2::uuid WHERE s.source_id=$1';
const WRITER_SQL = new Set([
'SELECT revoked_at,credential_hash,lane FROM persistence_local_writers WHERE id=$1::uuid',
@@ -35,7 +39,7 @@ function present(sql: string, rows: Array<Record<string, unknown>>): boolean {
const row = rows[0];
if (rows.length !== 1 || !row) return false;
if (sql === BRAIN_SQL) return typeof row.brain_id === 'string';
- if (sql === SOURCE_SQL) return row.archived === false && typeof row.local_path === 'string' && row.local_path !== '';
+ if (sql === ADMISSION_SOURCE_SQL) return row.archived === false && typeof row.local_path === 'string' && row.local_path !== '';
if (sql === BINDING_SQL) return typeof row.local_path === 'string' && row.local_path !== '' && row.state === 'active';
return WRITER_SQL.has(sql) && row.revoked_at == null;
}
@@ -82,7 +86,7 @@ export async function preadmitReads(engine: BrainEngine, now: () => number = Dat
return registerEngineView(new Proxy(engine, { get(target, key) {
if (key === 'executeRaw') return (sql: string, params?: unknown[], opts?: { signal?: AbortSignal }) => {
const text = flat(sql);
- return text === BRAIN_SQL || text === SOURCE_SQL || text === BINDING_SQL || WRITER_SQL.has(text) ? read(text, params, opts) : target.executeRaw(sql, params, opts);
+ return text === BRAIN_SQL || text === ADMISSION_SOURCE_SQL || text === BINDING_SQL || WRITER_SQL.has(text) ? read(text, params, opts) : target.executeRaw(sql, params, opts);
};
const value = Reflect.get(target, key, target);
return typeof value === 'function' ? value.bind(target) : value;
diff --git a/src/core/persistence/publication-failure.ts b/src/core/persistence/publication-failure.ts
index 75bfa82921..6afd0b96ca 100644
--- a/src/core/persistence/publication-failure.ts
+++ b/src/core/persistence/publication-failure.ts
@@ -123,6 +123,7 @@ const PURGED_PREFIX = 'purged_content:';
const GUEST_GUARD_TEXT: Record<string, string> = {
source_writer_restricted: 'only the listed writers of a guest source may create or change its pages',
guest_page_immutable: 'a guest source holds no facts, takes or timeline entries, and its pages are never changed',
+ guest_attribution_missing: 'a listed writer creates or changes a guest page only as a guest note carrying its attribution',
guest_mark_immutable: 'a guest mark is never changed',
guest_source_database_only: 'a guest source is database-only and takes no local path or repository',
};
diff --git a/src/core/think/index.ts b/src/core/think/index.ts
index b3dcd05f77..4d61888a1e 100644
--- a/src/core/think/index.ts
+++ b/src/core/think/index.ts
@@ -43,7 +43,7 @@ import { evidenceTitlesEnabled } from '../search/evidence-date.ts';
import { startThinkDecide, thinkAbstainResult, type ThinkAbstention } from './decide.ts';
import { classifyIntent } from './intent.ts';
import { deriveTrust, type TaintRef } from '../trust/taint.ts';
-import { guestAnswerLine, type GuestStamp } from '../guests/marker.ts';
+import { withGuestAnswer, type GuestStamp } from '../guests/marker.ts';
import { publishSinglePage, THINK_SYNTHESIS_KIND } from '../generations/adapters/single-page.ts';
/** Anthropic Messages client interface — same shape used by subagent.ts so test stubs can be shared. */
@@ -686,10 +686,6 @@ export async function runThink(
if (gather.diagnostics.window?.dropped) warnings.push(`WINDOW_EXCLUDED_${gather.diagnostics.window.dropped}_PAGES`);
// #5575 A6: every page and take reaches the prompt with its trust tier.
await stampPageTrust(engine, gather.pages);
- // GBRA-504: the guest notes among them; the answer names them in a line gbrain appends after synthesis.
- const guestEvidence = gather.pages.flatMap(pg => pg.guest ? [{ source_id: pg.source_id ?? 'default', slug: pg.slug, guest: pg.guest }] : []);
- const guestAnswer = (answer: string) => guestEvidence.length
- ? { answer: `${answer.trimEnd()}\n\n${guestAnswerLine(guestEvidence.map(g => g.slug))}`, guest_evidence: guestEvidence } : { answer };
gather.takes = await stampRowTrust(engine, 'takes', gather.takes, t => ('take_id' in t ? t.take_id : (t as { id: number }).id));
// Render evidence blocks for the prompt. #4510: the per-page excerpt is
@@ -900,9 +896,9 @@ export async function runThink(
// Degrade gracefully: return the gather without synthesis. Better than throwing.
return {
question: opts.question,
- ...guestAnswer(modelProblem
+ ...withGuestAnswer(gather.pages, { answer: modelProblem
? `(model "${modelUsed}" not usable — ${detail}${fix})`
- : '(no LLM available — set ANTHROPIC_API_KEY or pass `client`)'),
+ : '(no LLM available — set ANTHROPIC_API_KEY or pass `client`)' }),
citations: [],
gaps: [
modelProblem
@@ -1039,11 +1035,10 @@ export async function runThink(
const extractive = synthesisStatus !== 'ok'
? composeExtractiveFallback(gather.pages, opts.question, opts.remote !== false)
: null;
- const grounded: Partial<ThinkResult> = synthesisStatus === 'ok' ? await groundThinkAnswer(engine, response.answer, [opts.question, pagesBlock, takesBlock, graphBlock ?? '', trajectoryBlock], warnings) : {};
return {
question: opts.question,
- ...grounded, ...guestAnswer(grounded.answer ?? response.answer),
+ ...withGuestAnswer(gather.pages, { answer: response.answer, ...(synthesisStatus === 'ok' ? await groundThinkAnswer(engine, response.answer, [opts.question, pagesBlock, takesBlock, graphBlock ?? '', trajectoryBlock], warnings) : {}) }),
citations: resolved.citations,
gaps: response.gaps,
pagesGathered: gather.pages.length,
diff --git a/src/core/trust/schema.ts b/src/core/trust/schema.ts
index 1554c0e1b0..a4254e32ad 100644
--- a/src/core/trust/schema.ts
+++ b/src/core/trust/schema.ts
@@ -124,9 +124,13 @@ const CHANGED_CHAIN = `${TRUST_TABLES.map((table, index) => `${index === 0 ? 'IF
* source (guest_sources, one primary-key probe) may be inserted, or have a
* content column other than deleted_at changed (moves in or out included), only
* by a principal on the source's writer list, read from the attribution
- * settings. A fact, take or timeline row in a guest source is refused on INSERT
- * and on a content change; lifecycle updates and deletes pass. Other tables skip
- * the probe while guest_sources is empty.
+ * settings, and only by a guest note: its publication sets gbrain.guest_note to
+ * its gbrain.write_request (guests/admission.ts assertGuestWriterAtPublication), so a
+ * listed writer's plain write admitted before the source became a guest source
+ * is refused here (guest_attribution_missing) without a read of its own. A
+ * fact, take or timeline row in a guest source is refused on INSERT and on a
+ * content change; lifecycle updates and deletes pass. Other tables skip the
+ * probe while guest_sources is empty.
*/
const GUEST_GUARD = `
IF TG_OP = 'UPDATE' THEN
@@ -146,6 +150,9 @@ const GUEST_GUARD = `
ELSIF ${contentChanged('pages', GUEST_PAGE_CONTENT_COLUMNS)} THEN
${guestRefuse('source_writer_restricted', 'only the listed writers of a guest source may change its pages')};
END IF;
+ ELSIF guest AND (TG_OP = 'INSERT' OR ${contentChanged('pages', GUEST_PAGE_CONTENT_COLUMNS)}) AND NOT COALESCE(
+ NULLIF(current_setting('gbrain.guest_note', true), '') = current_setting('gbrain.write_request', true), false) THEN
+ ${guestRefuse('guest_attribution_missing', 'a listed writer creates or changes a guest page only as a guest note')};
END IF;
ELSIF (TG_OP = 'INSERT' OR changed) AND EXISTS (SELECT 1 FROM guest_sources) THEN
IF TG_TABLE_NAME = 'facts' THEN
diff --git a/test/access-qm-actor.test.ts b/test/access-qm-actor.test.ts
index 5fed1a2ec3..f53dfb37b9 100644
--- a/test/access-qm-actor.test.ts
+++ b/test/access-qm-actor.test.ts
@@ -514,7 +514,7 @@ for (const kind of testBackends()) {
['commit_page_upload', { upload_id: 'x' }], ['abort_page_upload', { upload_id: 'x' }],
['put_raw_data', { slug: PAGES.alice.slug, source: 'crm-example', data: {} }],
['extract_entities', { text: 'Alice met Bob.' }], ['ontology_propose', { subject: PAGES.alice.slug, fact: 'x' }],
- ['confirm_memory', { ref: 'p:' + SRC + '/' + PAGES.alice.slug }], ['loops_close', { id: 1 }],
+ ['confirm_memory', { ref: 'p:' + SRC + '/' + PAGES.alice.slug }], ['promote_guest_note', { slug: PAGES.alice.slug }], ['loops_close', { id: 1 }],
['questions_pin', { question: 'x?' }], ['questions_refresh', { id: 1 }], ['questions_unpin', { id: 1 }],
// Shared rows with no page: answer feedback, the ingest log and loop suppression.
['rate_answer', { answer_id: 'x', rating: 'up' }], ['log_ingest', { source_type: 'note', source_ref: 'x', pages_updated: [], summary: 'x' }],
diff --git a/test/doctor-guest-source.test.ts b/test/doctor-guest-source.test.ts
index 73cfae7fa6..f4360e3be2 100644
--- a/test/doctor-guest-source.test.ts
+++ b/test/doctor-guest-source.test.ts
@@ -7,7 +7,8 @@
* guest with no guest_sources row), when a writer names a removed client, or when a writer's grant reaches another
* source; warn, with
* the exact grant command, when an owner credential cannot read the guest source, and when its min_trust floor hides
- * guest notes (F9). The check reads only: no grant changes. PGLite in-memory, no repository.
+ * guest notes (F9). On a schema behind the guest-notes migration it names that migration: not applicable, or warn
+ * when a config still marks a guest source. The check reads only: no grant changes. PGLite in-memory, no repository.
*/
import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
@@ -20,6 +21,7 @@ import { initGuestSource } from '../src/core/guests/sources.ts';
import { guestSourceCheck } from '../src/commands/doctor/checks/guest-source.ts';
import { categorizeCheck } from '../src/core/doctor-categories.ts';
import { setMinTrust } from '../src/core/trust/min-trust.ts';
+import { GUEST_NOTES_MIGRATION } from '../src/core/guests/migration.ts';
const SRC = 'guests';
const PLAIN = 'source-a';
@@ -116,3 +118,23 @@ describe('guest_source doctor check', () => {
expect(check.message).toContain('gbrain auth set-min-trust ' + ownerClient + ' external_untrusted');
}, 60_000);
});
+
+describe('guest_source doctor check on a schema behind the guest-notes migration', () => {
+ let old: PGLiteEngine;
+ beforeAll(async () => {
+ old = new PGLiteEngine();
+ await old.connect({});
+ await old.initSchema();
+ await old.executeRaw('DROP TABLE guest_promotions, guest_marks, guest_sources CASCADE');
+ }, 60_000);
+ afterAll(async () => { await old.disconnect(); }, 60_000);
+
+ test('names the migration: not applicable without a config-marked source, warn with one', async () => {
+ const bare = await guestSourceCheck(old);
+ expect({ status: bare.status, state: bare.readiness_state, names: bare.message.includes('v' + GUEST_NOTES_MIGRATION) }).toEqual({ status: 'ok', state: 'not_applicable', names: true });
+ await old.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [SRC]);
+ await old.executeRaw(`UPDATE sources SET config = config || '{"guest": true}'::jsonb WHERE id = $1`, [SRC]);
+ const marked = await guestSourceCheck(old);
+ expect({ status: marked.status, names: marked.message.includes('v' + GUEST_NOTES_MIGRATION), source: marked.message.includes(SRC) }).toEqual({ status: 'warn', names: true, source: true });
+ }, 60_000);
+});
diff --git a/test/e2e/single-write-fast-path-postgres.test.ts b/test/e2e/single-write-fast-path-postgres.test.ts
index 2cd1fb29f3..3b9cadd3b4 100644
--- a/test/e2e/single-write-fast-path-postgres.test.ts
+++ b/test/e2e/single-write-fast-path-postgres.test.ts
@@ -16,6 +16,7 @@ import { submitPageMutation } from '../../src/core/persistence/page-mutations.ts
import { persistenceHome, revokeLocalWriter } from '../../src/core/persistence/identity.ts';
import { installFaultHook } from '../../src/core/persistence/fault-points.ts';
import { resetWriteSwitches } from '../../src/core/persistence/switches.ts';
+import { ADMISSION_SOURCE_SQL } from '../../src/core/persistence/preadmit-cache.ts';
import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
import { getWorktreeBinding } from '../../src/core/persistence/ownership.ts';
import { tryAcquireNativeLock, type NativeLockHandle } from '../../src/core/persistence/native-lock.ts';
@@ -39,7 +40,7 @@ function countStatements(engine: BrainEngine, fragment: string): { count: () =>
return { count: () => n, restore: () => { proto.executeRaw = original; } };
}
const GROUP_COMPLETION = "UPDATE persistence_requests r SET state='committed'";
-const SOURCE_READ = "SELECT incarnation,archived,local_path,config->>'kind' AS kind,config->>'role' AS role FROM sources WHERE id=$1";
+const SOURCE_READ = ADMISSION_SOURCE_SQL;
afterEach(() => { installFaultHook(undefined); resetWriteSwitches(); });
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
index 1a8e2d79de..c44c3b9460 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
@@ -655,7 +655,7 @@
"gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058",
"gbrain_snapshot_version_trust()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=a0aa697992ad1777eaba4a1f4d2325dc4f2a98f3ebf9e81325d1b068406ce1cb",
"gbrain_stamp_revision_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=d446ed1145d8bb9c93cb0ca4aa076a5dc7a5fe07b3e79518adaf1b17b0a51216",
- "gbrain_stamp_trust_tier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=8dd3e1a4575fe8d2844a4430d0e66ceb122265ef161f9cecefa3a3edf06a6e5b",
+ "gbrain_stamp_trust_tier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=3034ff087fc72989b8d7a1cbd8895a26ef6433d0fa830fc6ace23d5a79ff33e2",
"gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=1f8fcf3492a9276c52541f6d353d6c709a123b6db4c84bb9a60d77a82fa1672f",
"gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=e2dbafe65571fedcadc0441415f58fb5b5209b4c9cefa50e4855f58f0452327c",
"gbrain_try_jsonb(input text)": "RETURNS jsonb kind=f lang=plpgsql volatility=i secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=11b96a0400158fcb3dbd84255985cd11e473688c53fff64ebf92602fceccbedf",
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
index 109611df86..d8ef0b83b4 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
@@ -655,7 +655,7 @@
"gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058",
"gbrain_snapshot_version_trust()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=a0aa697992ad1777eaba4a1f4d2325dc4f2a98f3ebf9e81325d1b068406ce1cb",
"gbrain_stamp_revision_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=d446ed1145d8bb9c93cb0ca4aa076a5dc7a5fe07b3e79518adaf1b17b0a51216",
- "gbrain_stamp_trust_tier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=8dd3e1a4575fe8d2844a4430d0e66ceb122265ef161f9cecefa3a3edf06a6e5b",
+ "gbrain_stamp_trust_tier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=3034ff087fc72989b8d7a1cbd8895a26ef6433d0fa830fc6ace23d5a79ff33e2",
"gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=1f8fcf3492a9276c52541f6d353d6c709a123b6db4c84bb9a60d77a82fa1672f",
"gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=e2dbafe65571fedcadc0441415f58fb5b5209b4c9cefa50e4855f58f0452327c",
"gbrain_try_jsonb(input text)": "RETURNS jsonb kind=f lang=plpgsql volatility=i secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=11b96a0400158fcb3dbd84255985cd11e473688c53fff64ebf92602fceccbedf",
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
index d9a808af5b..ebd551114e 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
@@ -655,7 +655,7 @@
"gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058",
"gbrain_snapshot_version_trust()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=a0aa697992ad1777eaba4a1f4d2325dc4f2a98f3ebf9e81325d1b068406ce1cb",
"gbrain_stamp_revision_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=d446ed1145d8bb9c93cb0ca4aa076a5dc7a5fe07b3e79518adaf1b17b0a51216",
- "gbrain_stamp_trust_tier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=8dd3e1a4575fe8d2844a4430d0e66ceb122265ef161f9cecefa3a3edf06a6e5b",
+ "gbrain_stamp_trust_tier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=3034ff087fc72989b8d7a1cbd8895a26ef6433d0fa830fc6ace23d5a79ff33e2",
"gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=1f8fcf3492a9276c52541f6d353d6c709a123b6db4c84bb9a60d77a82fa1672f",
"gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=e2dbafe65571fedcadc0441415f58fb5b5209b4c9cefa50e4855f58f0452327c",
"gbrain_try_jsonb(input text)": "RETURNS jsonb kind=f lang=plpgsql volatility=i secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=11b96a0400158fcb3dbd84255985cd11e473688c53fff64ebf92602fceccbedf",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
index 14aecef6be..c2d68d280e 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
@@ -658,7 +658,7 @@
"gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058",
"gbrain_snapshot_version_trust()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=a0aa697992ad1777eaba4a1f4d2325dc4f2a98f3ebf9e81325d1b068406ce1cb",
"gbrain_stamp_revision_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=d446ed1145d8bb9c93cb0ca4aa076a5dc7a5fe07b3e79518adaf1b17b0a51216",
- "gbrain_stamp_trust_tier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=8dd3e1a4575fe8d2844a4430d0e66ceb122265ef161f9cecefa3a3edf06a6e5b",
+ "gbrain_stamp_trust_tier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=3034ff087fc72989b8d7a1cbd8895a26ef6433d0fa830fc6ace23d5a79ff33e2",
"gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=1f8fcf3492a9276c52541f6d353d6c709a123b6db4c84bb9a60d77a82fa1672f",
"gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=e2dbafe65571fedcadc0441415f58fb5b5209b4c9cefa50e4855f58f0452327c",
"gbrain_try_jsonb(input text)": "RETURNS jsonb kind=f lang=plpgsql volatility=i secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=11b96a0400158fcb3dbd84255985cd11e473688c53fff64ebf92602fceccbedf",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
index d49435592f..6b8fb7ddb6 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
@@ -658,7 +658,7 @@
"gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058",
"gbrain_snapshot_version_trust()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=a0aa697992ad1777eaba4a1f4d2325dc4f2a98f3ebf9e81325d1b068406ce1cb",
"gbrain_stamp_revision_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=d446ed1145d8bb9c93cb0ca4aa076a5dc7a5fe07b3e79518adaf1b17b0a51216",
- "gbrain_stamp_trust_tier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=8dd3e1a4575fe8d2844a4430d0e66ceb122265ef161f9cecefa3a3edf06a6e5b",
+ "gbrain_stamp_trust_tier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=3034ff087fc72989b8d7a1cbd8895a26ef6433d0fa830fc6ace23d5a79ff33e2",
"gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=1f8fcf3492a9276c52541f6d353d6c709a123b6db4c84bb9a60d77a82fa1672f",
"gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=e2dbafe65571fedcadc0441415f58fb5b5209b4c9cefa50e4855f58f0452327c",
"gbrain_try_jsonb(input text)": "RETURNS jsonb kind=f lang=plpgsql volatility=i secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=11b96a0400158fcb3dbd84255985cd11e473688c53fff64ebf92602fceccbedf",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
index f1bd09d68a..601e08bf13 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
@@ -658,7 +658,7 @@
"gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058",
"gbrain_snapshot_version_trust()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=a0aa697992ad1777eaba4a1f4d2325dc4f2a98f3ebf9e81325d1b068406ce1cb",
"gbrain_stamp_revision_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=d446ed1145d8bb9c93cb0ca4aa076a5dc7a5fe07b3e79518adaf1b17b0a51216",
- "gbrain_stamp_trust_tier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=8dd3e1a4575fe8d2844a4430d0e66ceb122265ef161f9cecefa3a3edf06a6e5b",
+ "gbrain_stamp_trust_tier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=3034ff087fc72989b8d7a1cbd8895a26ef6433d0fa830fc6ace23d5a79ff33e2",
"gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=1f8fcf3492a9276c52541f6d353d6c709a123b6db4c84bb9a60d77a82fa1672f",
"gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=e2dbafe65571fedcadc0441415f58fb5b5209b4c9cefa50e4855f58f0452327c",
"gbrain_try_jsonb(input text)": "RETURNS jsonb kind=f lang=plpgsql volatility=i secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=11b96a0400158fcb3dbd84255985cd11e473688c53fff64ebf92602fceccbedf",
diff --git a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
index 0897ddd950..5d9b8e3b7b 100644
--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
@@ -655,7 +655,7 @@
"gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058",
"gbrain_snapshot_version_trust()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=a0aa697992ad1777eaba4a1f4d2325dc4f2a98f3ebf9e81325d1b068406ce1cb",
"gbrain_stamp_revision_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=d446ed1145d8bb9c93cb0ca4aa076a5dc7a5fe07b3e79518adaf1b17b0a51216",
- "gbrain_stamp_trust_tier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=8dd3e1a4575fe8d2844a4430d0e66ceb122265ef161f9cecefa3a3edf06a6e5b",
+ "gbrain_stamp_trust_tier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=3034ff087fc72989b8d7a1cbd8895a26ef6433d0fa830fc6ace23d5a79ff33e2",
"gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=1f8fcf3492a9276c52541f6d353d6c709a123b6db4c84bb9a60d77a82fa1672f",
"gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=e2dbafe65571fedcadc0441415f58fb5b5209b4c9cefa50e4855f58f0452327c",
"gbrain_try_jsonb(input text)": "RETURNS jsonb kind=f lang=plpgsql volatility=i secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=11b96a0400158fcb3dbd84255985cd11e473688c53fff64ebf92602fceccbedf",
diff --git a/test/get-brain-identity.test.ts b/test/get-brain-identity.test.ts
index 33f21716fa..1dcc274c98 100644
--- a/test/get-brain-identity.test.ts
+++ b/test/get-brain-identity.test.ts
@@ -115,7 +115,7 @@ describe('get_brain_identity op', () => {
'update_available',
'version',
]);
- expect(result.capabilities).toEqual(['large_pages_v1']);
+ expect(result.capabilities).toEqual(['large_pages_v1', 'guest_marker_v1']);
});
test('last_sync_iso is null in v0.31.1 (deferred to v0.31.x — see plan)', async () => {
diff --git a/test/guest-derived-registry.test.ts b/test/guest-derived-registry.test.ts
index 184c0d48de..f68ee25182 100644
--- a/test/guest-derived-registry.test.ts
+++ b/test/guest-derived-registry.test.ts
@@ -7,6 +7,7 @@
* that links and dates things, stale link extraction, the timeline walk and fact extraction derive nothing from it and
* report nothing for it, while an owner page beside it still gets its link.
*/
+import { randomUUID } from 'node:crypto';
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
@@ -61,8 +62,12 @@ describe('guest pages feed no derived rows (pglite, repo-less)', () => {
await engine.connect({});
await engine.initSchema();
await initGuestSource(engine, 'guests', [`${writer.kind}:${writer.id}`]);
- const asWriter = <T>(fn: (tx: PGLiteEngine) => Promise<T>) => engine.transaction(tx => withWriteAttribution(tx, { requestId: null, principal: writer,
- trust: { tier: 'external_untrusted', origin: { channel: 'test' } } }, () => fn(tx as PGLiteEngine)));
+ const request = randomUUID();
+ const asWriter = <T>(fn: (tx: PGLiteEngine) => Promise<T>) => engine.transaction(tx => withWriteAttribution(tx, { requestId: request, principal: writer,
+ trust: { tier: 'external_untrusted', origin: { channel: 'test' } } }, async () => {
+ await tx.executeRaw("SELECT set_config('gbrain.guest_note', $1, true)", [request]);
+ return fn(tx as PGLiteEngine);
+ }));
await asWriter(tx => importFromContent(tx, 'people/carol-example', '---\ntype: note\ntitle: Carol\n---\n# Carol\n\nA guest page.', { sourceId: 'guests', noEmbed: true } as never));
await asWriter(tx => importFromContent(tx, 'notes/guest-a', '---\ntype: note\ntitle: Guest\n---\n# Guest\n\nMet [[people/carol-example]] about the ledger.\n\n## Facts\n\n| fact | entity |\n|---|---|\n| Carol likes tea | people/carol-example |\n',
{ sourceId: 'guests', noEmbed: true } as never));
diff --git a/test/guest-notes-promotion.test.ts b/test/guest-notes-promotion.test.ts
index acf749d9b4..30cf43667d 100644
--- a/test/guest-notes-promotion.test.ts
+++ b/test/guest-notes-promotion.test.ts
@@ -6,7 +6,8 @@
* 'promoted_from: <guest source>:<slug>' and the guest note's readers, records the link in guest_promotions, and leaves
* the guest page and its mark unchanged; the guest row then reads 'guest.promoted: true'. Promoting again to the same
* page writes nothing. Everyone else (the broker, a member, the owner's credential speaking for a group, an enforced
- * member) is refused guest_promotion_owner_only before anything is written. The broker's remote delete of a promoted
+ * member's stdio server) is refused guest_promotion_owner_only before anything is written, and an enforced member CLI's
+ * gate refuses gbrain guests promote and the operation. The broker's remote delete of a promoted
* guest page is refused guest_page_promoted; of an unpromoted one it still works. 'gbrain guests promote' runs the same
* op. All on a repo-less PGLite brain; one case promotes into a source with a git repository.
*/
@@ -32,6 +33,7 @@ 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';
+import { enforcedClassOf } from '../src/cli/enforced-member-classes.ts';
const SRC = 'guests';
const PLAIN = 'source-a';
@@ -199,10 +201,8 @@ describe('promote_guest_note (pglite, repo-less)', () => {
};
expect(refusals).toEqual({ broker: 'guest_promotion_owner_only', member: 'guest_promotion_owner_only',
owner_for_group: 'guest_promotion_owner_only', enforced_member: 'guest_promotion_owner_only' });
- const prior = process.env.GBRAIN_ENFORCED_MEMBER;
- process.env.GBRAIN_ENFORCED_MEMBER = OWNER;
- try { expect((await local('promote_guest_note', { slug })).code).toBe('guest_promotion_owner_only'); }
- finally { if (prior === undefined) delete process.env.GBRAIN_ENFORCED_MEMBER; else process.env.GBRAIN_ENFORCED_MEMBER = prior; }
+ expect({ command: enforcedClassOf('guests', ['promote', slug], undefined), op: enforcedClassOf('promote_guest_note', [], 'promote_guest_note') })
+ .toEqual({ command: 'refused', op: 'refused' });
expect(await promotions(slug)).toEqual([]);
expect(await engine.getPage(slug, { sourceId: PLAIN })).toBeNull();
}, 120_000);
diff --git a/test/guest-notes-schema.test.ts b/test/guest-notes-schema.test.ts
index 8ee1a5bc79..3609f8594a 100644
--- a/test/guest-notes-schema.test.ts
+++ b/test/guest-notes-schema.test.ts
@@ -7,8 +7,9 @@
* rewrite, the backfill INSERT and the promotion UPDATE branches); facts,
* takes and timeline rows refused in a guest source; the writer backstop (a
* page INSERT or content UPDATE in a guest source needs a principal on the
- * source's writer list, while soft delete, restore, purge and non-content
- * updates pass); a guest source refusing a local_path; and pages outside a
+ * source's writer list, and from a listed writer a guest note (gbrain.guest_note
+ * set to its request, else guest_attribution_missing), while soft delete,
+ * restore, purge and non-content updates pass); a guest source refusing a local_path; and pages outside a
* guest source keeping their behavior. Runs on PGLite, and on Postgres (direct
* and transaction-mode PgBouncer) through test/e2e/guest-notes-postgres.test.ts.
*/
@@ -42,10 +43,16 @@ afterAll(async () => { for (const b of backends) await b.close(); });
const BROKER: Principal = { kind: 'oauth_client', id: 'client-a' };
const OTHER: Principal = { kind: 'oauth_client', id: 'client-b' };
const OWNER_CLI: Principal = { kind: 'local_cli', id: 'cli-a' };
+const REQUEST = randomUUID();
const as = (principal: Principal, tier?: TrustTier): WriteAttribution =>
- ({ requestId: null, principal, ...(tier ? { trust: { tier, origin: { channel: 'test' } } } : {}) });
+ ({ requestId: REQUEST, principal, ...(tier ? { trust: { tier, origin: { channel: 'test' } } } : {}) });
+/** What a guest note's publication sets (guests/admission.ts assertGuestWriterAtPublication): gbrain.guest_note = its request. */
+const asGuestNote = <T>(tx: BrainEngine, fn: () => Promise<T>) =>
+ tx.executeRaw("SELECT set_config('gbrain.guest_note', $1, true)", [REQUEST]).then(fn);
const writeAs = <T>(engine: BrainEngine, principal: Principal, tier: TrustTier | undefined, fn: (tx: BrainEngine) => Promise<T>) =>
- engine.transaction(tx => withWriteAttribution(tx, as(principal, tier), () => fn(tx)));
+ engine.transaction(tx => withWriteAttribution(tx, as(principal, tier), () => asGuestNote(tx, () => fn(tx))));
+const writeAsPlain = <T>(engine: BrainEngine, principal: Principal, fn: (tx: BrainEngine) => Promise<T>) =>
+ engine.transaction(tx => withWriteAttribution(tx, as(principal, 'agent_written'), () => fn(tx)));
async function guestSource(engine: BrainEngine, writers: Principal[] = [BROKER]): Promise<string> {
const id = `guests-${randomUUID().slice(0, 8)}`;
@@ -114,8 +121,8 @@ for (const backendName of testBackends()) {
test('the ceiling holds on the backfill INSERT and promotion UPDATE branches', async () => {
const engine = engineOf();
const source = await guestSource(engine);
- const copied = await engine.transaction(tx => withWriteAttribution(tx, as(BROKER), () =>
- withTrustBackfill(tx, () => insertPage(tx, source, undefined, 'operator_curated'))));
+ const copied = await engine.transaction(tx => withWriteAttribution(tx, as(BROKER), () => asGuestNote(tx, () =>
+ withTrustBackfill(tx, () => insertPage(tx, source, undefined, 'operator_curated')))));
expect(copied.trust_tier).toBe('external_untrusted');
await engine.transaction(tx => withTrustPromotion(tx, 'operator_curated', () =>
tx.executeRaw(`UPDATE pages SET trust_tier='operator_curated' WHERE id=$1`, [copied.id])));
@@ -147,7 +154,10 @@ for (const backendName of testBackends()) {
expect(await failure(insertPage(engine, source))).toMatch(/source_writer_restricted/);
expect(await failure(writeAs(engine, OTHER, 'agent_written', tx => insertPage(tx, source)))).toMatch(/source_writer_restricted/);
expect(await failure(writeAs(engine, OWNER_CLI, 'operator_curated', tx => insertPage(tx, source)))).toMatch(/source_writer_restricted/);
+ expect(await failure(writeAsPlain(engine, BROKER, tx => insertPage(tx, source)))).toMatch(/guest_attribution_missing/);
const page = await writeAs(engine, BROKER, 'agent_written', tx => insertPage(tx, source));
+ expect(await failure(writeAsPlain(engine, BROKER, tx =>
+ tx.executeRaw(`UPDATE pages SET compiled_truth='plain rewrite' WHERE id=$1`, [page.id])))).toMatch(/guest_attribution_missing/);
expect(await failure(writeAs(engine, OWNER_CLI, 'operator_curated', tx =>
tx.executeRaw(`UPDATE pages SET compiled_truth='owner rewrite' WHERE id=$1`, [page.id])))).toMatch(/source_writer_restricted/);
expect(await failure(engine.executeRaw(`UPDATE pages SET frontmatter='{"trust_tier":"user_confirmed"}'::jsonb WHERE id=$1`, [page.id]))).toMatch(/source_writer_restricted/);
diff --git a/test/helpers/segmented-write-sweep.ts b/test/helpers/segmented-write-sweep.ts
index 2d9f99c640..ba4e98886d 100644
--- a/test/helpers/segmented-write-sweep.ts
+++ b/test/helpers/segmented-write-sweep.ts
@@ -121,6 +121,7 @@ export const PAGE_OPS: Record<string, Case> = {
takes_remove: { who: LOCAL, skipOver: NO_FENCE_ROW, run: async (f, slug, who) => f.call(who, 'takes_remove', { slug, row_num: await f.localTake(slug) }) },
takes_rebuild: { who: LOCAL, run: op('takes_rebuild', (_f, slug) => ({ slug })) },
confirm_memory: { who: REMOTE, run: op('confirm_memory', (_f, slug) => ({ ref: 'p:' + SRC + '/' + slug })) },
+ promote_guest_note: { who: REMOTE, run: op('promote_guest_note', (_f, slug) => ({ slug, to: slug })) },
extraction_review: { who: LOCAL, run: op('extraction_review', (_f, slug) => ({ action: 'distinct', slugs: [slug], of: OTHER })) },
entity_identity_link: { who: LOCAL, run: op('entity_identity_link', (_f, slug) => ({ entity_id: 'acme-example', slug, source_id: SRC })) },
delete_page: { who: REMOTE, replaces: true, run: op('delete_page', async (f, slug) => ({ slug, expected_revision: await f.revision(slug) })) },
diff --git a/test/large-pages/segmented-write-sweep.test.ts b/test/large-pages/segmented-write-sweep.test.ts
index bf4378dd29..b58faf18d9 100644
--- a/test/large-pages/segmented-write-sweep.test.ts
+++ b/test/large-pages/segmented-write-sweep.test.ts
@@ -24,6 +24,7 @@ const SWEEP_MS = 900_000;
/** Ops whose every binding is refused for a reason of their own. */
const NOT_REACHED: Record<string, string> = {
revert_version: 'refuses every segmented page by design (page_body_segmented, reason segmented_revert)',
+ promote_guest_note: 'loads only a guest note and the sweep brain has no guest source, so the owner is refused page_not_found and anyone else guest_promotion_owner_only before a page loads; a guest note stored in segments is refused page_body_segmented (promote.ts assertInlineBody)',
};
describe('the sweep classifies every mutating op in the registry', () => {
diff --git a/test/serve-http-mcp-dispatch-context.serial.test.ts b/test/serve-http-mcp-dispatch-context.serial.test.ts
index 8e4b5cd5f8..c76a81758c 100644
--- a/test/serve-http-mcp-dispatch-context.serial.test.ts
+++ b/test/serve-http-mcp-dispatch-context.serial.test.ts
@@ -95,7 +95,7 @@ async function rpc(base: string, token: string, method: string, params?: unknown
return JSON.parse(dataLine ? dataLine.slice('data:'.length) : text).result;
}
-const FULL_SURFACE_KEYS = ['actor', 'admissionOrigin', 'auth', 'config', 'inboundFrameBytes', 'isListed', 'logger', 'mcpCaller', 'metaHook', 'noticeLedger', 'onBehalfOf', 'remote', 'resultRows', 'room', 'sourceId', 'surface', 'surfaceCeiling', 'takesHoldersAllowList', 'transport'];
+const FULL_SURFACE_KEYS = ['actor', 'admissionOrigin', 'auth', 'config', 'guest', 'inboundFrameBytes', 'isListed', 'logger', 'mcpCaller', 'metaHook', 'noticeLedger', 'onBehalfOf', 'remote', 'resultRows', 'room', 'sourceId', 'surface', 'surfaceCeiling', 'takesHoldersAllowList', 'transport'];
describe('POST /mcp dispatch context', () => {
test('full surface: remote http dispatch with the verified auth and token source scope', async () => {