Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Guest notes feed nothing derived, whichever record marks the source (GBRA-504)

garrytand3521689a11e
diff --git a/changelog.d/gbra504-guest-notes-4-promotion.md b/changelog.d/gbra504-guest-notes-4-promotion.md
index a9c80ce31e..14e0a9ddbc 100644
--- a/changelog.d/gbra504-guest-notes-4-promotion.md
+++ b/changelog.d/gbra504-guest-notes-4-promotion.md
@@ -15,11 +15,11 @@ You keep a note as your own page with `gbrain guests promote <slug>` (MCP `promo
- Guide: docs/guides/guest-notes.md.
### Itemized changes
-- Migration v312 (`src/core/schema-migrations/v312-guest-notes.ts`): the `guest_sources`, `guest_marks` and `guest_promotions` tables under row-level security, the per-source trust ceiling in the trust trigger, and the writer backstop trigger.
+- The guest-notes schema migration (`src/core/schema-migrations/v<NNN>-guest-notes.ts`; `GUEST_NOTES_MIGRATION` in `src/core/guests/migration.ts` names its number): the `guest_sources`, `guest_marks` and `guest_promotions` tables under row-level security, the per-source trust ceiling in the trust trigger, and the writer backstop trigger.
- `src/core/guests/`: admission (writer list, new-page-only, allowed frontmatter and readers), the mark and its warning, derived-row refusals, promotion, owner credentials and source setup.
- Read paths (`src/cli/page-render.ts`, `src/cli/search-row-format.ts`, `src/cli/guest-lines.ts`, `src/core/access/page-items.ts`, `src/core/think/index.ts`, `src/core/search/transcript-quote.ts`) carry the guest mark and warning.
- Stale extraction, `propose_takes` (scoped or not) and the cycle's fact, atom and enrichment phases leave guest pages out.
-- Reads on a brain whose schema is still behind v312 keep working, because the guest check falls back to the source config when the `guest_sources` table is missing.
+- Reads on a brain whose schema is still behind that migration keep working, because the guest check falls back to the source config when the `guest_sources` table is missing.
- Goldens regenerated: `test/fixtures/goldens/sql-text/pages.json` (stale-extraction query excludes guest pages), `test/fixtures/goldens/exports/types.json` (guest types and error codes), the doctor goldens (the `guest_source` row and the three new tables under row-level security) and `test/fixtures/goldens/cli/tools-json.json` (the new operation).
<!-- behavior-change: guest_notes_gbra504 -->
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.md
index 3bf09ab7f0..332ffa7f1b 100644
--- a/docs/architecture/key-files/core-services-2.md
+++ b/docs/architecture/key-files/core-services-2.md
@@ -34,7 +34,7 @@ Fact and page purge modules (`src/core/facts/purge*.ts`, `deletion-inventory.ts`
- `src/core/ops/trust.ts` — `confirm_memory` (#5575 A4, CEO-9, DX-20): the one MCP-visible owner action. Raises a fact, take or page to `user_confirmed` through `trust/owner-actions.ts` after `requireOwnerConfirmation` (a `memory_confirm` connection, or the local CLI's typed-token TTY prompt); agent tokens get `insufficient_scope` with a `tell_user_to_run` fix naming `gbrain trust confirm <ref>`. Trust proposals and holds are not reachable here; the other owner actions are CLI or resident-owner administration only (`trust/owner-ipc.ts`). It also holds `promote_guest_note` (GBRA-504), whose logic is `guests/promote.ts`.
- `src/core/guests/{promote,owner-credentials}.ts`, `src/commands/doctor/checks/guest-source.ts` — GBRA-504 slice 4. `promote.ts` is `promote_guest_note` (CLI `gbrain guests promote`): `isGuestPromotionOwner` admits the trusted local CLI (not under `GBRAIN_ENFORCED_MEMBER`, not `--as`) and a remote or stdio caller whose `CallerAccess.owner` is set with no attested actor, anyone else is `guest_promotion_owner_only`; it writes the owner page with `submitPageMutation` put_page (git first where the target has a repo), carrying the note's type, title, body and `readable_by` plus `promoted_from: <guest source>:<slug>`, then inserts `guest_promotions`, which `marker.ts` `loadGuestMarks` reads as `guest.promoted` and `admission.ts` `refuseRemoteDeleteOfPromoted` reads to refuse a remote delete `guest_page_promoted` (at submission in `page-mutations.ts`, again in the delete's publication in `page-prepare.ts`). `owner-credentials.ts` lists tokens and OAuth clients bound to `access.owner_member` with their read lists, the exact `gbrain auth rescope ... --if-version` command and whether `min_trust` hides guest notes; `grantOwnerCredentials` (`gbrain guests grant-owner-clients --yes`) adds the guest source as a compare-and-set on the grant revision. The doctor check `guest_source` reads both and changes nothing. Tests: `test/guest-notes-promotion.test.ts`, `test/doctor-guest-source.test.ts`, `test/guests-grant-owner-clients.test.ts`.
-- `src/core/guests/{schema,sources}.ts` — GBRA-504 guest sources. `schema.ts` is migration v312's DDL: `guest_sources` (the authority for which sources are guest sources, their writer list of `<kind>:<id>` attribution principals and their tier ceiling), `guest_marks` (immutable: `gbrain_guard_guest_records` refuses UPDATE; rows leave only with their page) and `guest_promotions`, RLS on, and the guard that keeps a guest source database-only (no `local_path`). The trust trigger (`trust/schema.ts` `GUEST_AWARE_STAMP_TIER_FUNCTION`, installed by v312; v226 keeps its own body) clamps a guest page to the ceiling on every exit, refuses a page INSERT or content change (any content column but `deleted_at`) unless `gbrain.write_principal_kind`:`gbrain.write_principal_id` is on the writer list, and refuses facts, takes and timeline rows there. `sources.ts` holds the reads and writes behind `gbrain guests init` and `gbrain sources writers`.
+- `src/core/guests/{schema,sources}.ts` — GBRA-504 guest sources. `schema.ts` is the guest-notes migration's DDL (number: `guests/migration.ts`): `guest_sources` (the authority for which sources are guest sources, their writer list of `<kind>:<id>` attribution principals and their tier ceiling), `guest_marks` (immutable: `gbrain_guard_guest_records` refuses UPDATE; rows leave only with their page) and `guest_promotions`, RLS on, and the guard that keeps a guest source database-only (no `local_path`). The trust trigger (`trust/schema.ts` `GUEST_AWARE_STAMP_TIER_FUNCTION`, installed by that migration; v226 keeps its own body) clamps a guest page to the ceiling on every exit, refuses a page INSERT or content change (any content column but `deleted_at`) unless `gbrain.write_principal_kind`:`gbrain.write_principal_id` is on the writer list, and refuses facts, takes and timeline rows there. `sources.ts` holds the reads and writes behind `gbrain guests init` and `gbrain sources writers`.
- `src/core/guests/{marker,stamp}.ts`, `src/core/access/page-items.ts`, `src/cli/guest-lines.ts` — GBRA-504 slice 3: the guest warning on every read. `marker.ts` holds the `GuestStamp` object (`sender`, from `guest_marks.sender_label`; `group`, `audience_member`, `saved_at` day, `promoted`, `writer` for owner callers only, `unattributed`), the warning line, the quote-fence label, think's fixed `Uses outside-guest notes:` line, `loadGuestMarks` (one batched `guest_marks` read; a failed read leaves rows unattributed, never bare) and `withGuestMarks`, which `operation-load.ts` `finalizeOperation` wraps around every op whose `outputRedaction` is not `no_stored_text`. `stamp.ts` `stampGuestNotes` finds page items with `page-items.ts` `collectPageItems` (the walker shared with `access/room.ts`; it also reads `fetch` rows by their `gbrain://page/` url), skips the trust load only when `marker.ts` `brainHasGuestSource` (one read of `sources` and `guest_sources`, yes when it fails) finds no guest source, reads guest rows through `eligibility/stamp.ts` `loadPageTrust` (a source is a guest source when its config says so or `guest_sources` lists it, `guestSourceSql`), and stamps a copy with `origin: guest`, `external_untrusted` and the `guest` object; a failed load fails the read. `eligibility/labels.ts` prints the warning line before the `origin="guest"` envelope, `eligibility/activation.ts` and `context/turn-context.ts` carry the stamp on `delta`, and the CLI prints it through `search-row-format.ts`, `page-render.ts` and `guest-lines.ts`. Publication refuses a plain write that lands after its source became a guest source (`guests/admission.ts` `assertNoGuestSourceAtPublication`). Servers list capability `guest_marker_v1`. Tests: `test/guest-notes-warning.test.ts`, `test/guest-notes-contract.test.ts` (every op that returns stored text, as owner over HTTP and stdio and as the audience member), `test/guest-notes-shortcut.test.ts` (a source marked guest without `gbrain guests init` is still marked).
- `src/core/health-memo.ts` — in-process memo for the `get_health` op only (O-ENG-13). An entry is reused when engine object, scope key (`all`, `scalar:<id>`, `set:<sorted unique ids>`, `empty` for an empty or no-sources grant; derived from the exact scope handed to `engine.getHealth`, so no scope reads another's entry), config generation (hash of the orphan exclusions, embedding column registry keys and schema pack setting), page clock (`page_generation_clock_seq.last_value` plus the `persistence_brain` id) and TTL all match. TTL: `GBRAIN_HEALTH_CACHE_TTL_MS`, else config `health.cache_ttl_ms`, else 30000 ms; 0 disables. The TTL bounds staleness from writes that do not touch `pages` (links, timeline rows, chunks). A failed clock/config read computes uncached. `engine.getHealth` stays uncached, so doctor, remediation, maintain, embedding migration and repair verification always read fresh numbers; `gbrain repair --apply` and `gbrain doctor --remediate` call `clearHealthMemo`. Pinned by `test/health-memo.test.ts`.
diff --git a/docs/guides/guest-notes.md b/docs/guides/guest-notes.md
index 1e71f975c6..3e871a8138 100644
--- a/docs/guides/guest-notes.md
+++ b/docs/guides/guest-notes.md
@@ -119,7 +119,8 @@ The offsite moved to Friday.
A guest note is saved once, as a new page. Saving to a slug that exists is
refused `revision_required`, and `force`, `expected_revision`, `edit_page`,
`append_page`, `add_timeline_entry`, `add_link`, `remember`, `put_raw_data`,
-`put_pages` and uploads are refused `guest_page_immutable`; a writer may delete its notes.
+`put_pages` and uploads are refused `guest_page_immutable`; a writer may delete the notes
+it saved, and deleting another writer's note is refused `permission_denied`.
gbrain checks the writer list again when the note publishes, so a writer you
remove in between is refused `source_writer_restricted`. Every refusal is in
[write refusals](write-refusals.md#guest-source-refusals).
diff --git a/llms.txt b/llms.txt
index 9901c7a68a..f1f141556b 100644
--- a/llms.txt
+++ b/llms.txt
@@ -11,6 +11,7 @@ Repo: https://github.com/garrytan/gbrain
- [Muse personal agent](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/muse.md): Verify durable storage first; connect Muse to your published brain (`gbrain mcp expose --funnel` + thin CLI) or add local explicit memory with provenance alongside Muse's native memory; distinguish Muse Code and unverified native MCP.
- [Inside an existing agent](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/in-agent-setup.md): Isolated setup, absolute launcher, receipts, keyless maintenance, complete private backup and safe restoration.
- [Owner turns in a shared room](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/rooms.md): Declare the group chat an answer goes into (X-Gbrain-Room, _meta.room, a room argument): the owner's read is unchanged and every page and fact is marked room_access with whether the room could have read it; reasons, notices, who may ask, and keeping raw results out of the group transcript.
+- [Guest notes](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/guest-notes.md): Keep what outside guests in a group chat say apart from your own pages: a database-only guest source (`gbrain guests init`), the writer list, how the broker saves a note with its sender and group, the warning every read shows, `gbrain guests promote`, `gbrain guests grant-owner-clients` and the guest_source doctor check.
- [Memory boundaries](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/memory-boundaries.md): Durable shared preferences versus harness state; remote graph maintenance, provider text disclosure, authorization and full-backup limits; large pages (segmented storage up to 256 MiB on Postgres, append_page / gbrain append, upload sessions, windowed reads, limits per entry point).
- [Page history](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/page-history.md): Why a page changed: an optional reason on page writes, replaced_because in get_versions, the gbrain-reason commit trailer, remote visibility and repo-less brains.
- [Brain versus session memory](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/brain-vs-memory.md): Route durable facts and preferences to shared memory, configuration to the harness, and temporary work to session state.
diff --git a/scripts/llms-config.ts b/scripts/llms-config.ts
index 25843bd3e6..058341a126 100644
--- a/scripts/llms-config.ts
+++ b/scripts/llms-config.ts
@@ -46,6 +46,7 @@ export const SECTIONS: DocSection[] = [
{ title: "Muse personal agent", path: "docs/guides/muse.md", description: "Verify durable storage first; connect Muse to your published brain (`gbrain mcp expose --funnel` + thin CLI) or add local explicit memory with provenance alongside Muse's native memory; distinguish Muse Code and unverified native MCP.", includeInFull: false },
{ title: "Inside an existing agent", path: "docs/guides/in-agent-setup.md", description: "Isolated setup, absolute launcher, receipts, keyless maintenance, complete private backup and safe restoration.", includeInFull: false },
{ title: "Owner turns in a shared room", path: "docs/guides/rooms.md", description: "Declare the group chat an answer goes into (X-Gbrain-Room, _meta.room, a room argument): the owner's read is unchanged and every page and fact is marked room_access with whether the room could have read it; reasons, notices, who may ask, and keeping raw results out of the group transcript.", includeInFull: false },
+ { title: "Guest notes", path: "docs/guides/guest-notes.md", description: "Keep what outside guests in a group chat say apart from your own pages: a database-only guest source (`gbrain guests init`), the writer list, how the broker saves a note with its sender and group, the warning every read shows, `gbrain guests promote`, `gbrain guests grant-owner-clients` and the guest_source doctor check.", includeInFull: false },
{ title: "Memory boundaries", path: "docs/guides/memory-boundaries.md", description: "Durable shared preferences versus harness state; remote graph maintenance, provider text disclosure, authorization and full-backup limits; large pages (segmented storage up to 256 MiB on Postgres, append_page / gbrain append, upload sessions, windowed reads, limits per entry point).", includeInFull: false },
{ title: "Page history", path: "docs/guides/page-history.md", description: "Why a page changed: an optional reason on page writes, replaced_because in get_versions, the gbrain-reason commit trailer, remote visibility and repo-less brains.", includeInFull: false },
{ title: "Brain versus session memory", path: "docs/guides/brain-vs-memory.md", description: "Route durable facts and preferences to shared memory, configuration to the harness, and temporary work to session state.", includeInFull: false },
diff --git a/src/core/engine-sql/pages.ts b/src/core/engine-sql/pages.ts
index a2deaf52a7..5a3ae6c29c 100644
--- a/src/core/engine-sql/pages.ts
+++ b/src/core/engine-sql/pages.ts
@@ -825,7 +825,7 @@ function stalePagesWhere(opts?: StaleOpts) {
: opts?.attendance === 'blocked' ? sqlFragment` AND links_attendance_blocked_revision = knowledge_revision` : sqlFragment``;
const held = opts?.held === 'exclude' ? sqlFragment` AND NOT ${linkExtractionHeld(opts.versionTs)}`
: opts?.held === 'only' ? sqlFragment` AND ${linkExtractionHeld(opts.versionTs)}` : sqlFragment``;
- // GBRA-504: a guest page is never extracted (guests/derived.ts), so it is never stale; `guests: false` is the pre-v312 shape.
+ // GBRA-504: a guest page is never extracted (guests/derived.ts), so it is never stale; `guests: false` is the shape before the guest-notes migration.
const guests = opts?.guests === false ? sqlFragment`` : sqlFragment` AND ${trustedSql(guestSourceExclusionSql('extract', 'pages'))}`;
// A quarantined page is hidden from search; it is neither re-extracted nor counted as stale.
return sqlFragment`deleted_at IS NULL AND ${trustedSql(quarantineFilterFragment('pages'))} AND ${version}${source}${attendance}${held}${guests}`;
diff --git a/src/core/extraction-lag.ts b/src/core/extraction-lag.ts
index 479516c10a..1a786ed88e 100644
--- a/src/core/extraction-lag.ts
+++ b/src/core/extraction-lag.ts
@@ -76,7 +76,7 @@ async function readLagRow(engine: BrainEngine, opts: { sourceId?: string; timeou
throw e;
}
};
- // GBRA-504: guest pages are never extracted, so they are not lag; a brain before v312 has no guest_sources table.
+ // GBRA-504: guest pages are never extracted, so they are not lag; a brain behind the guest-notes migration has no guest_sources table.
try { return await readShape(true); } catch (e) {
if (!isMissingSchemaObject(e, 'table', 'guest_sources')) throw e;
return readShape(false);
diff --git a/src/core/guests/admission.ts b/src/core/guests/admission.ts
index c00d1f0e1c..0fabcd2da6 100644
--- a/src/core/guests/admission.ts
+++ b/src/core/guests/admission.ts
@@ -82,10 +82,22 @@ export function guestPagePromoted(slug: string): OperationError {
'Do not retry. Treat the note as kept; only the brain owner removes it, on the brain host.', DOCS('guest_page_promoted'));
}
-/** A remote delete of a guest page the owner promoted (guest_promotions) is refused; checked at submission and in publication. */
-export async function refuseRemoteDeleteOfPromoted(exec: Pick<BrainEngine, 'executeRaw'>, sourceId: string, slug: string): Promise<void> {
- const kept = await exec.executeRaw('SELECT 1 FROM guest_promotions g JOIN pages p ON p.id = g.guest_page_id WHERE p.source_id = $1 AND p.slug = $2 LIMIT 1', [sourceId, slug]);
- if (kept.length) throw guestPagePromoted(slug);
+export function guestNoteNotYours(slug: string): OperationError {
+ return new OperationError('permission_denied', `Guest note ${slug} was saved by another writer, so this credential cannot delete it. Nothing was deleted.`,
+ 'Delete only the guest notes this credential saved; the brain owner deletes any guest note on the brain host (gbrain delete).', 'docs/guides/guest-notes.md#save-a-guest-note-for-the-writer');
+}
+
+/**
+ * A remote delete of a page in a guest source: refused when the owner promoted it (guest_promotions) and when its guest
+ * mark names another writer than `principal` (a writer deletes only what it saved). Checked at submission and in publication.
+ */
+export async function refuseRemoteGuestDelete(exec: Pick<BrainEngine, 'executeRaw'>, sourceId: string, slug: string, principal: Principal): Promise<void> {
+ const [page] = await exec.executeRaw<{ guest: boolean; kept: boolean; writer: string | null }>(
+ `SELECT EXISTS (SELECT 1 FROM guest_sources g WHERE g.source_id = p.source_id) AS guest, EXISTS (SELECT 1 FROM guest_promotions g WHERE g.guest_page_id = p.id) AS kept,
+ (SELECT m.writer_kind || ':' || m.writer_id FROM guest_marks m WHERE m.page_id = p.id) AS writer FROM pages p WHERE p.source_id = $1 AND p.slug = $2 LIMIT 1`, [sourceId, slug]);
+ if (!page?.guest && !page?.kept) return;
+ if (page.kept) throw guestPagePromoted(slug);
+ if (page.writer !== principalKey(principal)) throw guestNoteNotYours(slug);
}
const principalKey = (principal: Principal) => `${principal.kind}:${principal.id}`;
diff --git a/src/core/guests/derived.ts b/src/core/guests/derived.ts
index 9ab760f31d..197b2e1ee9 100644
--- a/src/core/guests/derived.ts
+++ b/src/core/guests/derived.ts
@@ -8,7 +8,7 @@
*/
import type { BrainEngine } from '../engine.ts';
import type { CyclePhase } from '../cycle.ts';
-import { isGuestSource, storedGuestNote } from './note.ts';
+import { guestSourceSql, isGuestSource, readGuestSourceIds, storedGuestNote } from './note.ts';
export type GuestDerivedProducer = CyclePhase | 'publication_projections' | 'auto_links' | 'remote_links_effect' | 'facts_backstop' | 'think_writeback';
type GuestDerivedEntry = { guest: 'skip'; sites: readonly string[] } | { guest: 'none'; reason: string };
@@ -68,24 +68,36 @@ export function guestSkippedPhases(): CyclePhase[] {
.filter((key): key is CyclePhase & GuestSkipProducer => GUEST_DERIVED_PRODUCERS[key].guest === 'skip' && (GUEST_DERIVED_PRODUCERS[key] as { sites: readonly string[] }).sites.includes(CYCLE));
}
-/** True when `producer` skips `sourceId` because it is a guest source. */
+// Every helper below decides "guest source" with note.ts guestSourceSql, the test reads use: the source's config says
+// guest or guest_sources lists it. A lookup that fails counts as guest (the producer skips) or refuses (it throws).
+
+/** True when `producer` skips `sourceId` because it is a guest source, or because the lookup failed. */
export async function skipsGuestSource(engine: Pick<BrainEngine, 'executeRaw'>, producer: GuestSkipProducer, sourceId: string): Promise<boolean> {
return skips(producer) && isGuestSource(engine, sourceId);
}
-/** True when `producer` skips a write whose stored intent carries a guest note (publication-time producers; no read). */
-export function skipsGuestNote(producer: GuestSkipProducer, intent: Record<string, unknown> | null | undefined): boolean {
- return skips(producer) && storedGuestNote(intent) !== null;
+/**
+ * Whether a write is a guest write for the publication-time producers: its stored intent carries a guest note, or it
+ * lands in a guest source. Throws when the lookup fails, so the write refuses instead of publishing derived rows.
+ */
+export async function isGuestWrite(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, intent: Record<string, unknown> | null | undefined): Promise<boolean> {
+ return storedGuestNote(intent) !== null || (await readGuestSourceIds(engine, [sourceId])).has(sourceId);
+}
+
+/** True when `producer` skips a write isGuestWrite classified as a guest write. */
+export function skipsGuestNote(producer: GuestSkipProducer, guestWrite: boolean): boolean {
+ return skips(producer) && guestWrite;
}
-/** `items` without those in a guest source, for a producer that walks several sources. */
+/** `items` without those in a guest source, for a producer that walks several sources; none when the lookup fails. */
export async function withoutGuestSources<T>(engine: Pick<BrainEngine, 'executeRaw'>, producer: GuestSkipProducer, items: readonly T[], sourceOf: (item: T) => string): Promise<T[]> {
if (!skips(producer) || items.length === 0) return [...items];
- const guests = new Set((await engine.executeRaw<{ source_id: string }>('SELECT source_id FROM guest_sources')).map(row => row.source_id));
- return guests.size ? items.filter(item => !guests.has(sourceOf(item))) : [...items];
+ let guests: Set<string>;
+ try { guests = await readGuestSourceIds(engine, items.map(sourceOf)); } catch { return []; }
+ return items.filter(item => !guests.has(sourceOf(item)));
}
-/** A SQL predicate keeping rows of `alias` (a pages alias or table name) outside guest sources. */
+/** A SQL predicate keeping rows of `alias` (a pages alias or table name) outside guest sources; it errors (the read refuses) without the guest tables. */
export function guestSourceExclusionSql(producer: GuestSkipProducer, alias: string): string {
- return skips(producer) ? `NOT EXISTS (SELECT 1 FROM guest_sources guest_src WHERE guest_src.source_id = ${alias}.source_id)` : 'TRUE';
+ return skips(producer) ? `NOT EXISTS (SELECT 1 FROM sources guest_src WHERE guest_src.id = ${alias}.source_id AND ${guestSourceSql('guest_src.config', 'guest_src.id')})` : 'TRUE';
}
diff --git a/src/core/guests/marker.ts b/src/core/guests/marker.ts
index 5f9e146579..0af43f7c5f 100644
--- a/src/core/guests/marker.ts
+++ b/src/core/guests/marker.ts
@@ -11,20 +11,15 @@
import type { BrainEngine } from '../engine.ts';
import type { Operation } from '../ops/contract.ts';
import { isMissingSchemaObject } from '../utils.ts';
+import { guestSourceSql } from './note.ts';
export const GUEST_ORIGIN = 'guest';
/** get_brain_identity lists it: this brain stamps the guest warning on every read, so a guest broker may switch on. */
export const GUEST_MARKER_CAPABILITY = 'guest_marker_v1';
-/**
- * SQL true when a source is a guest source: its config says `guest: true` or guest_sources lists it. Either record is
- * enough, so a source that lost one of them (a config edit, a restored database) still reads as a guest source.
- * `config` and `id` are the SQL expressions for the source's config and id.
- */
-export const guestSourceSql = (config: string, id: string) =>
- `(COALESCE(${config}->>'guest' = 'true', false) OR EXISTS (SELECT 1 FROM guest_sources gs WHERE gs.source_id = ${id}))`;
+export { guestSourceSql };
/**
- * Runs `read` with guestSourceSql. A brain whose schema is behind v312 has no guest_sources table, so the read is
+ * Runs `read` with guestSourceSql. A brain whose schema is behind the guest-notes migration (guests/migration.ts) has no guest_sources table, so the read is
* retried with the config record alone instead of failing every read that returns a page.
*/
export async function withGuestSourceSql<T>(read: (guestSql: typeof guestSourceSql) => Promise<T>): Promise<T> {
diff --git a/src/core/guests/migration.ts b/src/core/guests/migration.ts
new file mode 100644
index 0000000000..def5d8bf5f
--- /dev/null
+++ b/src/core/guests/migration.ts
@@ -0,0 +1,14 @@
+/**
+ * The guest-notes schema migration's number, read from the migration registry by the migration's name, so
+ * `bun run migrations:renumber` (which rewrites only the migration's filename, export name and version literal, then
+ * regenerates the registry) moves every comparison with it. Compare against this, never a literal.
+ */
+import { MIGRATIONS } from '../schema-migrations/registry.generated.ts';
+
+export const GUEST_NOTES_MIGRATION_NAME = 'guest_notes';
+
+export const GUEST_NOTES_MIGRATION: number = (() => {
+ const found = MIGRATIONS.find(m => m.name === GUEST_NOTES_MIGRATION_NAME);
+ if (!found) throw new Error('guests/migration.ts: no schema migration named ' + GUEST_NOTES_MIGRATION_NAME);
+ return found.version;
+})();
diff --git a/src/core/guests/note.ts b/src/core/guests/note.ts
index e215fada45..d23bf2c5e6 100644
--- a/src/core/guests/note.ts
+++ b/src/core/guests/note.ts
@@ -15,6 +15,23 @@ export function storedGuestNote(intent: Record<string, unknown> | null | undefin
? { sender_label: note.sender_label, group: note.group } : null;
}
+/**
+ * SQL true when a source is a guest source: its config says `guest: true` or guest_sources lists it. Either record is
+ * enough, so a source that lost one of them (a config edit, a restored database) still counts as a guest source. Reads
+ * (guests/marker.ts) and every derived producer (guests/derived.ts) use this one test. `config` and `id` are the SQL
+ * expressions for the source's config and id.
+ */
+export const guestSourceSql = (config: string, id: string) =>
+ `(COALESCE(${config}->>'guest' = 'true', false) OR EXISTS (SELECT 1 FROM guest_sources gs WHERE gs.source_id = ${id}))`;
+
+/** The guest sources among `sourceIds`, by guestSourceSql. Throws when the lookup fails (a schema behind the guest-notes migration included). */
+export async function readGuestSourceIds(engine: Pick<BrainEngine, 'executeRaw'>, sourceIds: readonly string[]): Promise<Set<string>> {
+ if (sourceIds.length === 0) return new Set();
+ const rows = await engine.executeRaw<{ id: string }>(`SELECT s.id FROM sources s WHERE s.id = ANY($1::text[]) AND ${guestSourceSql('s.config', 's.id')}`, [[...new Set(sourceIds)]]);
+ return new Set(rows.map(row => row.id));
+}
+
+/** For a derived producer: true when `sourceId` is a guest source, or when that cannot be told (the lookup failed). */
export async function isGuestSource(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string): Promise<boolean> {
- return (await engine.executeRaw('SELECT 1 FROM guest_sources WHERE source_id = $1', [sourceId])).length > 0;
+ try { return (await readGuestSourceIds(engine, [sourceId])).has(sourceId); } catch { return true; }
}
diff --git a/src/core/guests/promote.ts b/src/core/guests/promote.ts
index 1315e573d2..36f25f7df1 100644
--- a/src/core/guests/promote.ts
+++ b/src/core/guests/promote.ts
@@ -8,7 +8,7 @@
* source has a repository, database-only where it has none), carrying the guest note's type, title, body and readers
* plus 'promoted_from: <guest source>:<slug>' for people reading it. The link itself lives in guest_promotions, which
* guest rows read as guest.promoted (guests/marker.ts), and which refuses the broker's delete of the note
- * (guests/admission.ts refuseRemoteDeleteOfPromoted). The guest page and its mark are never changed.
+ * (guests/admission.ts refuseRemoteGuestDelete). The guest page and its mark are never changed.
*/
import { OperationError, type OperationContext } from '../ops/contract.ts';
import { federatedSearchScope } from '../ops/context.ts';
diff --git a/src/core/guests/schema.ts b/src/core/guests/schema.ts
index 45b1c73225..7ab310469c 100644
--- a/src/core/guests/schema.ts
+++ b/src/core/guests/schema.ts
@@ -1,6 +1,6 @@
/**
* Guest notes (GBRA-504): the database records behind a guest source. Applied by
- * migration v312 only (like the trust DDL it is not in the schema blob; a fresh
+ * the guest-notes migration only (number: guests/migration.ts; like the trust DDL it is not in the schema blob; a fresh
* install replays every migration).
*
* - guest_sources: which sources are guest sources, who may write them
diff --git a/src/core/persistence/effect-facts.ts b/src/core/persistence/effect-facts.ts
index 7c79c13e1f..d4831f105d 100644
--- a/src/core/persistence/effect-facts.ts
+++ b/src/core/persistence/effect-facts.ts
@@ -14,7 +14,7 @@ import { authorizeStoredRequest, authorizeWrite } from './authority.ts';
import { completeEffect } from './effect-journal.ts';
import { guardEffectSource } from './effect-recovery.ts';
import { derivedExtractionSkip } from './derived-extraction-gate.ts';
-import { skipsGuestNote } from '../guests/derived.ts';
+import { isGuestWrite, skipsGuestNote } from '../guests/derived.ts';
import { bodyUnread, isSegmentedPage } from '../page-body/page-shape.ts';
import type { PersistenceEffect } from './effect-model.ts';
import type { WriteRequest } from './model.ts';
@@ -95,7 +95,7 @@ async function bodyAlreadyOffered(engine: BrainEngine, slug: string, page: Parse
export async function prepareFactsBackstop(engine: BrainEngine, row: WriteRequest, page: ParsedPage, before: PageSnapshot | null = null): Promise<FactsBackstopStatus> {
const confined = derivedExtractionSkip(row.authority);
if (confined) return { skipped: confined };
- if (skipsGuestNote('facts_backstop', row.intent)) return { skipped: 'guest_source' };
+ if (skipsGuestNote('facts_backstop', await isGuestWrite(engine, row.source_id, row.intent))) return { skipped: 'guest_source' };
if (!(await isFactsExtractionEnabled(engine))) return { skipped: 'extraction_disabled' };
const eligible = isFactsBackstopEligible(row.slug, page);
if (!eligible.ok) return { skipped: eligible.reason };
diff --git a/src/core/persistence/effect-links.ts b/src/core/persistence/effect-links.ts
index 8eb40cf477..978fc38958 100644
--- a/src/core/persistence/effect-links.ts
+++ b/src/core/persistence/effect-links.ts
@@ -20,7 +20,7 @@ import { extractSegmentedPageLinks } from '../page-body/segment-links.ts';
import { inlineRegions } from '../page-body/tail-digest.ts';
import { validateSlug } from '../utils.ts';
import { isRemoteWantedPagesEnabled, replaceWantedLinks } from '../wanted-links.ts';
-import { skipsGuestNote } from '../guests/derived.ts';
+import { isGuestWrite, skipsGuestNote } from '../guests/derived.ts';
/** `mcp.remote_auto_links`: unset is on; false/0/no/off (any case) turns the remote `links` effect off. */
export async function isRemoteAutoLinksEnabled(engine: Pick<BrainEngine, 'getConfig'>): Promise<boolean> {
@@ -109,7 +109,7 @@ export async function runLinksEffect(engine: BrainEngine, effect: PersistenceEff
const skip = (tx: SqlEngine, reason: string) => completeEffect(tx, effect, { links: 'skipped', reason });
const [row] = await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE id=$1::uuid', [effect.request_id]);
if (!row || row.state !== 'committed' || !effect.data.slug) return skip(engine, 'invalid_write_request');
- if (skipsGuestNote('remote_links_effect', row.intent)) return skip(engine, 'guest_source');
+ if (skipsGuestNote('remote_links_effect', await isGuestWrite(engine, row.source_id, row.intent))) return skip(engine, 'guest_source');
if (effect.data.range) return runAppendLinksEffect(engine, effect, row, effect.data.range, hostId);
const sourceId = effect.source_id;
const snapshot = await engine.readPageSnapshot(effect.data.slug, { sourceId });
diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.ts
index c757781422..27da9fb221 100644
--- a/src/core/persistence/page-mutations.ts
+++ b/src/core/persistence/page-mutations.ts
@@ -53,7 +53,7 @@ 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 { admitGuestOperation, assertGuestFrontmatter, assertGuestReaders, GUEST_NOTE_INTENT_KEY, guestPageImmutable, refuseRemoteDeleteOfPromoted } from '../guests/admission.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';
@@ -435,7 +435,7 @@ export async function preparePageAdmission(ctx: OperationContext,
return { prior };
}
if (input.operation === 'delete_page') assertPurgeParams(p, ctx.remote);
- if (guest && input.operation === 'delete_page' && ctx.remote !== false && typeof p.slug === 'string') await refuseRemoteDeleteOfPromoted(ctx.engine, sourceId, p.slug.toLowerCase());
+ 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) {
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index d81de7a962..32bbe68f7b 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -45,7 +45,7 @@ import { replaceableFile } from '../facts/file-body-guard.ts';
import { getWorktreeBinding } from './ownership.ts';
import type { PreparedContentImport } from './prepared-import.ts';
import type { PreparedMutation } from './coordinator.ts';
-import type { SqlEngine, WriteRequest } from './model.ts';
+import { requestPrincipal, type SqlEngine, type WriteRequest } from './model.ts';
import { isUnboundSourcePage } from './unbound-source.ts';
import { slugPathFile } from './unbound-pages.ts';
import { isOriginTwinPage } from './origin-twins.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, refuseRemoteDeleteOfPromoted } from '../guests/admission.ts';
-import { isGuestSource, storedGuestNote } from '../guests/note.ts';
-import { skipsGuestNote } from '../guests/derived.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';
const ownerStatusFix = (sourceId: string): Action => readFix(`Shows source ${sourceId}'s canonical owner with its pending, failed and recovering requests, read-only.`,
@@ -815,7 +815,7 @@ async function prepareDeletePageMutation(engine: BrainEngine, row: WriteRequest,
`Page ${row.slug}'s file is committed in source ${row.source_id}'s checkout.`, pageFix(row.source_id, row.slug));
} } : {}),
apply: async tx => {
- if (row.authority.remote) await refuseRemoteDeleteOfPromoted(tx, row.source_id, row.slug);
+ if (row.authority.remote) await refuseRemoteGuestDelete(tx, row.source_id, row.slug, requestPrincipal(row));
if (purge && excludedPath !== null) await assertStillSyncExcluded(tx, row, excludedPath);
// #7311: the tombstone forgets the survivor's file, as an origin_twin page has, so its purge writes no deletion marker for it.
if (preparedPurge && sharedRetention) return purgePageInTransaction(tx, row, { ...snapshot, page: { ...(bodyUnread(snapshot.page) ? withoutBody(snapshot.page) : snapshot.page), source_path: null, source_uri: null } as Page }, preparedPurge);
@@ -1084,7 +1084,7 @@ async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: Wri
`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 isGuestSource(engine, row.source_id)) return prepareGuestRestore(engine, row, snapshot);
+ if (row.operation === 'restore_page' && (await readGuestSourceIds(engine, [row.source_id])).has(row.source_id)) return prepareGuestRestore(engine, row, snapshot);
let page = snapshot.page;
let tags = snapshot.tags;
if (row.operation === 'revert_version') {
@@ -1112,7 +1112,8 @@ async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: Wri
}
content = remoteCoreMarkingKept(row, snapshot, content, activePack);
const guestNote = storedGuestNote(p);
- const projected = !skipsGuestNote('publication_projections', p) && !(options.unprojected || row.operation === 'remember' || row.operation.startsWith('takes_') || (row.operation === 'extract_facts' && p.kind === 'managed_facts_entity'));
+ 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 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.
@@ -1231,7 +1232,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', p) && !noop && !targetDeleted && autoLinkedPage && (row.authority.autoLinkTrusted ?? !row.authority.remote) && await isAutoLinkEnabled(engine)
+ async () => !skipsGuestNote('auto_links', guestWrite) && !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).
diff --git a/src/core/trust/schema.ts b/src/core/trust/schema.ts
index 29d114acfa..1554c0e1b0 100644
--- a/src/core/trust/schema.ts
+++ b/src/core/trust/schema.ts
@@ -32,7 +32,7 @@
* user_confirmed. Inside a writer scope it is otherwise clamped back; with
* no writer scope it raises `trust_raise_refused`. Lowering is always allowed.
* - A writer tier above operator_curated needs a covering promotion ceiling.
- * - Guest sources (GBRA-504, v312): a pages row in a source listed in
+ * - Guest sources (GBRA-504, guest-notes migration): a pages row in a source listed in
* guest_sources never ends above that source's trust_ceiling, on every exit;
* creating it or changing its content needs the principal of
* gbrain.write_principal_kind/_id on the source's writer list; facts, takes
@@ -163,8 +163,8 @@ const GUEST_CEILING_RETURN = `IF guest_ceiling IS NOT NULL AND ${rank('NEW.trust
/**
* The tier trigger function. `guestSources: false` is the v226 body, kept
* byte-identical (the migration golden pins it, and migrations between v226 and
- * v312 run before guest_sources exists). `true` adds the guest-source rules
- * (GUEST_GUARD) and the per-source ceiling on every RETURN NEW; v312 installs
+ * the guest-notes migration run before guest_sources exists). `true` adds the guest-source rules
+ * (GUEST_GUARD) and the per-source ceiling on every RETURN NEW; the guest-notes migration installs
* it, and any later migration that re-creates this function uses it.
*/
const stampTierFunction = (guestSources: boolean) => {
@@ -208,7 +208,7 @@ BEGIN${SETTINGS}${guestSources ? GUEST_GUARD : ''}
END $fn$`;
};
const STAMP_TIER_FUNCTION = stampTierFunction(false);
-/** The current tier trigger function, guest-source rules included (v312). */
+/** The current tier trigger function, guest-source rules included (the guest-notes migration). */
export const GUEST_AWARE_STAMP_TIER_FUNCTION = stampTierFunction(true);
/**
diff --git a/test/guest-derived-predicate.test.ts b/test/guest-derived-predicate.test.ts
new file mode 100644
index 0000000000..b74119c1e0
--- /dev/null
+++ b/test/guest-derived-predicate.test.ts
@@ -0,0 +1,124 @@
+/**
+ * Guest notes (GBRA-504): every derived producer decides "guest source" with the read side's test (guestSourceSql): a
+ * source is a guest source when its config says guest or guest_sources lists it, so losing one record never lets a
+ * guest page feed derived rows. A lookup that fails, or a schema behind the guest-notes migration, counts as guest.
+ *
+ * Protects: (a) a source flagged guest in its config but missing from guest_sources gets no links, timeline rows,
+ * facts or take proposals from the stale walk, the timeline walk, fact extraction, propose_takes or a scoped cycle,
+ * while an owner page beside it still gets its link; (b) on a brain whose schema is behind the guest-notes migration
+ * (the guest tables dropped) the skip holds or refuses, and never derives from the guest page. PGLite, repo-less.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runCycle } from '../src/core/cycle.ts';
+import { skipsGuestSource, withoutGuestSources } from '../src/core/guests/derived.ts';
+import { GUEST_NOTES_MIGRATION } from '../src/core/guests/migration.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { extractStaleFromDB } from '../src/commands/extract.ts';
+import { extractTimelineFromDB } from '../src/commands/extract-timeline-db.ts';
+import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';
+import { runPhaseProposeTakes } from '../src/core/cycle/propose-takes.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+
+const FLAGGED = 'source-a';
+const GUEST_PAGE = 'notes/flagged-a';
+const page = (title: string, body: string) => '---\ntype: note\ntitle: ' + title + '\n---\n# ' + title + '\n\n' + body + '\n';
+
+async function seed(engine: PGLiteEngine): Promise<void> {
+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [FLAGGED]);
+ await importFromContent(engine, 'people/erin-example', page('Erin', 'A person.'), { sourceId: FLAGGED, noEmbed: true } as never);
+ await importFromContent(engine, GUEST_PAGE, page('Visitor', 'Met [[people/erin-example]] about the ledger.\n\n## Timeline\n\n- **2026-11-01** | Met Erin'),
+ { sourceId: FLAGGED, noEmbed: true } as never);
+ await importFromContent(engine, 'people/dan-example', '---\ntype: person\ntitle: Dan\n---\n# Dan\n', { noEmbed: true } as never);
+ await importFromContent(engine, 'notes/owner-a', page('Owner', 'Met [[people/dan-example]].'), { noEmbed: true } as never);
+}
+
+const flag = (engine: PGLiteEngine) => engine.executeRaw("UPDATE sources SET config = config || '{\"guest\": true}'::jsonb WHERE id = $1", [FLAGGED]);
+
+async function flaggedRows(engine: PGLiteEngine) {
+ return (await engine.executeRaw<{ links: number; timeline: number; facts: number; proposals: number }>(
+ 'SELECT (SELECT count(*)::int FROM links l JOIN pages p ON p.id = l.from_page_id WHERE p.source_id = $1) AS links, '
+ + '(SELECT count(*)::int FROM timeline_entries t JOIN pages p ON p.id = t.page_id WHERE p.source_id = $1) AS timeline, '
+ + '(SELECT count(*)::int FROM facts f WHERE f.source_id = $1) AS facts, '
+ + '(SELECT count(*)::int FROM take_proposals k WHERE k.source_id = $1) AS proposals', [FLAGGED]))[0]!;
+}
+
+const proposeCtx = (engine: PGLiteEngine) => ({ engine, config: {} as never, logger: { info() {}, warn() {}, error() {} } as never, dryRun: false, remote: false, sourceId: undefined });
+
+/** Runs a producer; a refusal (thrown error) is an acceptable outcome, deriving from the guest page is not. */
+async function holdsOrRefuses(run: () => Promise<unknown>): Promise<void> {
+ try { await run(); } catch { /* refused: nothing derived */ }
+}
+
+describe('a source flagged guest in its config but missing from guest_sources (pglite, repo-less)', () => {
+ let engine: PGLiteEngine;
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await seed(engine);
+ expect(await engine.countStalePagesForExtraction({ sourceId: FLAGGED })).toBeGreaterThan(0);
+ await flag(engine);
+ expect((await engine.executeRaw('SELECT 1 FROM guest_sources WHERE source_id = $1', [FLAGGED])).length).toBe(0);
+ }, 180_000);
+ afterAll(async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); }, 60_000);
+
+ test('every skip helper treats it as a guest source', async () => {
+ expect(await skipsGuestSource(engine, 'extract_facts', FLAGGED)).toBe(true);
+ expect(await skipsGuestSource(engine, 'extract_atoms', FLAGGED)).toBe(true);
+ expect(await withoutGuestSources(engine, 'chronicle', [FLAGGED, 'default'], id => id)).toEqual(['default']);
+ expect(await engine.countStalePagesForExtraction({ sourceId: FLAGGED })).toBe(0);
+ }, 60_000);
+
+ test('the stale walk, the timeline walk and fact extraction derive nothing from it; the owner page still links', async () => {
+ await extractStaleFromDB(engine, { dryRun: false, jsonMode: true, quiet: true, catchUp: false });
+ await extractTimelineFromDB(engine, { dryRun: false, jsonMode: true, quiet: true });
+ const facts = await runExtractFacts(engine, { sourceId: FLAGGED });
+ expect({ scanned: facts.pagesScanned, failed: facts.pagesFailed }).toEqual({ scanned: 0, failed: 0 });
+ expect(await flaggedRows(engine)).toEqual({ links: 0, timeline: 0, facts: 0, proposals: 0 });
+ const [owner] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM links l JOIN pages p ON p.id = l.from_page_id WHERE p.slug = 'notes/owner-a'");
+ expect(owner!.n).toBeGreaterThan(0);
+ }, 120_000);
+
+ test('an unscoped propose_takes run never reads its pages', async () => {
+ const scanned: string[] = [];
+ await runPhaseProposeTakes(proposeCtx(engine) as never, { extractor: async ({ pagePath }) => { scanned.push(pagePath); return []; } });
+ expect(scanned).toContain('notes/owner-a');
+ expect(scanned.filter(slug => slug === GUEST_PAGE || slug === 'people/erin-example')).toEqual([]);
+ }, 120_000);
+
+ test('a cycle scoped to it skips the derived phases', async () => {
+ const report = await runCycle(engine, { sourceId: FLAGGED, phases: ['extract_facts', 'propose_takes', 'orphans'], brainDir: null } as never);
+ const byPhase = Object.fromEntries(report.phases.map(p => [p.phase, (p.details as { reason?: string } | undefined)?.reason]));
+ expect({ extract_facts: byPhase.extract_facts, propose_takes: byPhase.propose_takes }).toEqual({ extract_facts: 'guest_source', propose_takes: 'guest_source' });
+ }, 120_000);
+});
+
+describe('a brain whose schema is behind the guest-notes migration (v' + GUEST_NOTES_MIGRATION + ')', () => {
+ let engine: PGLiteEngine;
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await seed(engine);
+ await flag(engine);
+ await engine.executeRaw('DROP TABLE guest_promotions, guest_marks, guest_sources CASCADE');
+ }, 180_000);
+ afterAll(async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); }, 60_000);
+
+ test('the skip helpers count the source as guest instead of failing', async () => {
+ expect(await skipsGuestSource(engine, 'extract_facts', FLAGGED)).toBe(true);
+ expect(await withoutGuestSources(engine, 'chronicle', [FLAGGED, 'default'], id => id)).not.toContain(FLAGGED);
+ }, 60_000);
+
+ test('every producer holds or refuses, and none derives from the guest page', async () => {
+ const scanned: string[] = [];
+ await holdsOrRefuses(() => extractStaleFromDB(engine, { dryRun: false, jsonMode: true, quiet: true, catchUp: false }));
+ await holdsOrRefuses(() => extractTimelineFromDB(engine, { dryRun: false, jsonMode: true, quiet: true }));
+ await holdsOrRefuses(() => runExtractFacts(engine, { sourceId: FLAGGED }));
+ await holdsOrRefuses(() => runPhaseProposeTakes(proposeCtx(engine) as never, { extractor: async ({ pagePath }) => { scanned.push(pagePath); return []; } }));
+ await holdsOrRefuses(() => runCycle(engine, { sourceId: FLAGGED, phases: ['extract_facts', 'propose_takes'], brainDir: null } as never));
+ expect(scanned.filter(slug => slug === GUEST_PAGE || slug === 'people/erin-example')).toEqual([]);
+ expect(await flaggedRows(engine)).toEqual({ links: 0, timeline: 0, facts: 0, proposals: 0 });
+ }, 180_000);
+});
diff --git a/test/guest-notes-delete-rights.test.ts b/test/guest-notes-delete-rights.test.ts
new file mode 100644
index 0000000000..c49498447f
--- /dev/null
+++ b/test/guest-notes-delete-rights.test.ts
@@ -0,0 +1,99 @@
+/**
+ * Guest notes (GBRA-504): a guest writer deletes only what it wrote.
+ *
+ * Protects: a credential on a guest source's writer list may delete a guest note it saved, but not one another listed
+ * writer saved (permission_denied, the page stays live), and not any page outside the guest source, through its own
+ * context or by naming another source; the brain owner on the local CLI still deletes any guest note. Real seams:
+ * legacy tokens granted only the guest source, dispatched through MCP dispatch on a repo-less PGLite brain.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';
+import { sqlQueryForEngine } from '../src/core/sql-query.ts';
+import { mintLegacyToken } from '../src/core/token-mint.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { addMember, bindCredential } from '../src/core/access/members.ts';
+import { setOwner } from '../src/core/access/owner.ts';
+import { changeGuestWriters, initGuestSource } from '../src/core/guests/sources.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import type { AuthInfo } from '../src/core/ops/contract.ts';
+import { readsUnscopedOnPurpose } from './helpers/reads-unscoped.ts';
+
+const SRC = 'guests';
+const PLAIN = 'source-a';
+const OWNER = 'alice-example';
+const META = { sender_label: 'Bob Example', group: 'team-a' };
+
+let engine: PGLiteEngine;
+const tokens: Record<string, { id: string; token: string }> = {};
+const provider = () => new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
+const parse = (text: string) => { try { return JSON.parse(text) as Record<string, unknown>; } catch { return {} as Record<string, unknown>; } };
+const note = () => ['---', 'type: note', 'title: A note from Bob', 'readable_by: [' + OWNER + ', bob-example]', 'guest_group: team-a',
+ 'guest_sender: Bob Example', 'saved_at: 2026-11-13T10:00:00Z', '---', '# A note from Bob', '', 'Bob says hello.'].join('\n');
+
+async function call(who: string, op: string, params: Record<string, unknown>, sourceId = SRC) {
+ const auth = await provider().verifyAccessToken(tokens[who]!.token) as unknown as AuthInfo;
+ const out = await dispatchToolCall(engine, op, { ...params }, { remote: true, transport: 'http', auth, sourceId, takesHoldersAllowList: ['world'],
+ onBehalfOf: { header: 'bob-example' }, guest: { requestMeta: { guest: META } } });
+ const json = parse(out.content.map(c => c.text).join('\n'));
+ return { isError: out.isError === true, code: (json.code ?? json.error) as string | undefined };
+}
+async function local(op: string, params: Record<string, unknown>, sourceId = SRC) {
+ const out = await dispatchToolCall(engine, op, { ...params }, { remote: false, sourceId });
+ const json = parse(out.content.map(c => c.text).join('\n'));
+ return { isError: out.isError === true, code: (json.code ?? json.error) as string | undefined };
+}
+const revisionOf = async (slug: string, sourceId = SRC) => (await engine.readPageSnapshot(slug, { sourceId, includeDeleted: true }))!.revision;
+const deleted = async (slug: string, sourceId = SRC) => (await engine.executeRaw<{ d: boolean }>(
+ 'SELECT deleted_at IS NOT NULL AS d FROM pages WHERE source_id = $1 AND slug = $2', [sourceId, slug]))[0]?.d;
+const slugOf = () => 'notes/guest-' + randomUUID().slice(0, 8);
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ for (const id of [OWNER, 'bob-example']) await addMember(engine, id);
+ await setOwner(engine, OWNER);
+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [PLAIN]);
+ await initGuestSource(engine, SRC, []);
+ for (const name of ['broker-a', 'broker-b']) {
+ const minted = await mintLegacyToken(engine, { name, scopes: ['read', 'write'], takesHolders: ['world'], sourceGrant: [SRC] });
+ tokens[name] = { id: minted.id, token: minted.token };
+ await bindCredential(engine, { kind: 'token', id: minted.id }, { mayActFor: ['member:bob-example', 'guest'] });
+ await readsUnscopedOnPurpose(engine, minted.id);
+ await changeGuestWriters(engine, SRC, { add: ['legacy_token:' + minted.id] });
+ }
+ const owned = await local('put_page', { slug: 'notes/owner-plan', content: '---\ntype: note\ntitle: Plan\n---\n# Plan\n\nThe owner plan.' }, PLAIN);
+ expect(owned.isError).toBe(false);
+}, 240_000);
+afterAll(async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); }, 60_000);
+
+describe('guest writer delete rights (pglite, repo-less)', () => {
+ test('a writer deletes its own guest note', async () => {
+ const slug = slugOf();
+ expect((await call('broker-a', 'put_page', { slug, content: note() })).isError).toBe(false);
+ const del = await call('broker-a', 'delete_page', { slug, expected_revision: await revisionOf(slug) });
+ expect({ isError: del.isError, code: del.code }).toEqual({ isError: false, code: undefined });
+ expect(await deleted(slug)).toBe(true);
+ }, 60_000);
+
+ test("a writer cannot delete a guest note another writer saved; the owner still can", async () => {
+ const slug = slugOf();
+ expect((await call('broker-a', 'put_page', { slug, content: note() })).isError).toBe(false);
+ const del = await call('broker-b', 'delete_page', { slug, expected_revision: await revisionOf(slug) });
+ expect({ isError: del.isError, code: del.code }).toEqual({ isError: true, code: 'permission_denied' });
+ expect(await deleted(slug)).toBe(false);
+ const owner = await local('delete_page', { slug, expected_revision: await revisionOf(slug) });
+ expect({ isError: owner.isError, code: owner.code }).toEqual({ isError: false, code: undefined });
+ expect(await deleted(slug)).toBe(true);
+ }, 60_000);
+
+ test('a writer cannot delete a page outside the guest source', async () => {
+ const viaContext = await call('broker-a', 'delete_page', { slug: 'notes/owner-plan', expected_revision: await revisionOf('notes/owner-plan', PLAIN) }, PLAIN);
+ expect(viaContext.isError).toBe(true);
+ const viaParam = await call('broker-a', 'delete_page', { slug: 'notes/owner-plan', source_id: PLAIN, expected_revision: await revisionOf('notes/owner-plan', PLAIN) });
+ expect(viaParam.isError).toBe(true);
+ expect(await deleted('notes/owner-plan', PLAIN)).toBe(false);
+ }, 60_000);
+});
diff --git a/test/guest-notes-schema.test.ts b/test/guest-notes-schema.test.ts
index 8bc1525183..8ee1a5bc79 100644
--- a/test/guest-notes-schema.test.ts
+++ b/test/guest-notes-schema.test.ts
@@ -1,7 +1,7 @@
/**
* Guest notes, slice 1 (GBRA-504): the database records and source rules.
*
- * Protects: migration v312's guest_sources, guest_marks and guest_promotions
+ * Protects: the guest-notes migration's guest_sources, guest_marks and guest_promotions
* tables (RLS on); guest_marks rows refuse UPDATE and leave with their page;
* the trust trigger's per-source ceiling on pages (INSERT, owner-tier content
* rewrite, the backfill INSERT and the promotion UPDATE branches); facts,
@@ -22,6 +22,7 @@ import { withTrustBackfill, withTrustPromotion, withWriteAttribution } from '../
import type { WriteAttribution } from '../src/core/persistence/attribution.ts';
import type { Principal } from '../src/core/persistence/model.ts';
import type { TrustTier } from '../src/core/trust/tier.ts';
+import { GUEST_NOTES_MIGRATION } from '../src/core/guests/migration.ts';
interface Backend { name: string; engine: BrainEngine; close: () => Promise<void> }
const backends: Backend[] = [];
@@ -64,7 +65,7 @@ for (const backendName of testBackends()) {
const engineOf = () => backends.find(b => b.name === backendName)!.engine;
describe(`guest notes schema (${backendName})`, () => {
- test('v312 creates the three tables with row-level security on', async () => {
+ test('migration v' + GUEST_NOTES_MIGRATION + ' creates the three tables with row-level security on', async () => {
const rows = await engineOf().executeRaw<{ relname: string; relrowsecurity: boolean }>(
`SELECT relname, relrowsecurity FROM pg_class WHERE relname = ANY($1::text[]) AND relkind = 'r' ORDER BY relname`,
[['guest_marks', 'guest_promotions', 'guest_sources']]);
diff --git a/test/guest-notes-shortcut.test.ts b/test/guest-notes-shortcut.test.ts
index 9cb869a199..a20871a1b0 100644
--- a/test/guest-notes-shortcut.test.ts
+++ b/test/guest-notes-shortcut.test.ts
@@ -15,6 +15,7 @@ import { dispatchToolCall } from '../src/mcp/dispatch.ts';
import { addMember } from '../src/core/access/members.ts';
import { setOwner } from '../src/core/access/owner.ts';
import { importFromContent } from '../src/core/import-file.ts';
+import { GUEST_NOTES_MIGRATION } from '../src/core/guests/migration.ts';
import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
const OWNER = 'alice-example';
@@ -78,7 +79,7 @@ describe('a guest source the guests command never set up', () => {
}, 60_000);
});
-describe('a brain whose schema is behind v312', () => {
+describe('a brain whose schema is behind migration v' + GUEST_NOTES_MIGRATION, () => {
test('reads still work without the guest tables, and a config-marked guest source is still marked', async () => {
const old = new PGLiteEngine();
await old.connect({});
diff --git a/test/guests-cli.test.ts b/test/guests-cli.test.ts
index 952ca627bd..dfbf1b588f 100644
--- a/test/guests-cli.test.ts
+++ b/test/guests-cli.test.ts
@@ -69,7 +69,7 @@ describe('gbrain guests init', () => {
for (const args of [['init', '--source', 'source-a'], ['init', '--source', 'source-a', '--yes']]) {
exitCode = null; err = [];
await run(() => runGuests(engine, args));
- expect({ args, exitCode, said: err.join('\n').includes('already holds 1 page') }).toEqual({ args, exitCode: 2, said: true });
+ expect({ args, exitCode: exitCode as number | null, said: err.join('\n').includes('already holds 1 page') }).toEqual({ args, exitCode: 2, said: true });
}
expect(await guestRow('source-a')).toBeUndefined();
expect(configOf((await sourceRow('source-a'))!.config).guest).toBeUndefined();