Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(gbra286): page history reads keep master member access and the quote fence
garrytanb036dfc9a1b0
diff --git a/scripts/check-engine-sql-dynamic.ts b/scripts/check-engine-sql-dynamic.tsindex 80b63b798c..284d46d7ef 100644--- a/scripts/check-engine-sql-dynamic.ts+++ b/scripts/check-engine-sql-dynamic.ts@@ -59,7 +59,7 @@ const VETTED_BUILDERS: Record<string, string> = {privateLinkOriginFilterForCaller: 'src/core/search/private-visibility.ts: constant link-origin predicate ORed with isValidSourceId-checked private-readable source ids',privateTimelineEventFilterForCaller: 'src/core/search/private-visibility.ts: constant timeline-event predicate ORed with isValidSourceId-checked private-readable source ids',orPrivateReadableSource: 'src/core/search/private-visibility.ts: wraps a caller predicate with isValidSourceId-checked private-readable source ids quoted as literals',- replacedBecauseSql: 'src/core/engine-sql/pages.ts: constant GBRA-217 reason projection over a caller alias; the boolean picks one of two constant texts',+ 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',currentCodeEdgeFilter: 'src/core/code-intel/read-scope.ts: constant current-edge predicate over a caller alias',diff --git a/src/core/engine-sql/pages.ts b/src/core/engine-sql/pages.tsindex f9f785772e..5d63fbe41f 100644--- a/src/core/engine-sql/pages.ts+++ b/src/core/engine-sql/pages.ts@@ -1006,17 +1006,18 @@ const PAGE_VERSION_SEGMENTED_COLUMNS = trustedSql('pv.body_storage, pv.body_gene* next snapshot of the page, or the live page, which the caller's own page predicate checks) and the successor was not* pruned (`successor_pruned`: its visibility can no longer be checked, so the reason is withheld). The successor is* read over every snapshot of the page, never only the rows the reader may see. Shared by get_versions and get_page as_of.+ * GBRA-286: a successor snapshot that names readers the caller does not meet (GBRA-218 readable_by) withholds it too.*/-/** GBRA-217: each version's parsed valid time (the shared normaliser), so a timeline reads in one get_versions call. */-const VERSION_VALID_TIME_COLUMNS = `${validDateSql("pv.frontmatter->>'valid_from'")} AS valid_from, ${validDateSql("pv.frontmatter->>'valid_until'")} AS valid_until`;-export function replacedBecauseSql(pv: string, excludePrivate: boolean): string {if (!excludePrivate) return `${pv}.change_reason`;return `CASE WHEN ${pv}.change_reason IS NULL OR COALESCE(${pv}.successor_pruned, false) THEN NULL- WHEN COALESCE((SELECT ${privateSnapshotFilterFragment('rb_next')} FROM page_versions rb_next+ WHEN COALESCE((SELECT ${privateSnapshotFilterFragment('rb_next')} AND ${callerReadersAllowedSql('rb_next', 'snapshot')} FROM page_versions rb_nextWHERE rb_next.page_id = ${pv}.page_id AND rb_next.id > ${pv}.id ORDER BY rb_next.id LIMIT 1), true) THEN ${pv}.change_reason END`;}+/** GBRA-217: each version's parsed valid time (the shared normaliser), so a timeline reads in one get_versions call. */+const VERSION_VALID_TIME_COLUMNS = `${validDateSql("pv.frontmatter->>'valid_from'")} AS valid_from, ${validDateSql("pv.frontmatter->>'valid_until'")} AS valid_until`;+/*** Newest first (`pv.id` breaks snapshot_at ties). Scope, privacy and* re-derivation (a page a purge hid) predicates sit in WHERE, so `limit`diff --git a/src/core/ops/admin.ts b/src/core/ops/admin.tsindex b42964705a..cfe6976730 100644--- a/src/core/ops/admin.ts+++ b/src/core/ops/admin.ts@@ -231,7 +231,8 @@ const get_versions: Operation = {const metadata = page(await ctx.engine.getVersions(p.slug as string, { ...opts, includeBody: false })).map(v => { const { compiled_truth: _b, timeline: _t, ...rest } = v as typeof v & { compiled_truth?: unknown; timeline?: unknown }; return rest; });const sized = [];- for (const v of metadata) sized.push({ ...await remoteVersionSize(ctx, v), ...(ctx.remote === false ? {} : remoteReason(v)) });+ const reason = await remoteReasons(ctx, String(p.slug), metadata);+ for (const v of metadata) sized.push({ ...await remoteVersionSize(ctx, v), ...reason(v) });return canReadWriteAttribution(ctx) ? attributeVersions(ctx.engine, sized) : sized;}const plain = page(await ctx.engine.getVersions(p.slug as string, opts));@@ -240,11 +241,12 @@ const get_versions: Operation = {const out = [];const snapshotTiers = ctx.remote === false || versions.length === 0 ? new Map<number, unknown>() : new Map((await ctx.engine.executeRaw<{ id: number | string; trust_tier: string | null }>('SELECT id, trust_tier FROM page_versions WHERE id = ANY($1::bigint[])', [versions.map(v => Number(v.id))])).map(r => [Number(r.id), r.trust_tier] as const));+ const reason = await remoteReasons(ctx, String(p.slug), versions);for (const v of versions) {if (isSegmentedPage(v)) {const sized = await remoteVersionSize(ctx, v);const { compiled_truth: _b, timeline: _t, ...rest } = sized;- out.push({ ...rest, ...(ctx.remote === false ? {} : remoteReason(v)), body_ref: { version_id: v.id, total_bytes: 'total_bytes' in sized ? sized.total_bytes : pageBodyBytes(v) } });+ out.push({ ...rest, ...reason(v), body_ref: { version_id: v.id, total_bytes: 'total_bytes' in sized ? sized.total_bytes : pageBodyBytes(v) } });continue;}if (ctx.remote === false) { out.push(v); continue; }@@ -252,7 +254,7 @@ const get_versions: Operation = {// GST-687: so does one whose snapshot tier is below the owner's (a version with no snapshot reads as unknown).const quote = quotesStored(v.type, snapshotTiers.get(Number(v.id)));const body = (text: string) => { const clean = sanitizeRemoteBody(text); return quote && clean ? fenceTranscriptText(clean, String(p.slug)) : clean; };- out.push({ ...v, compiled_truth: body(v.compiled_truth), ...remoteReason(v),+ out.push({ ...v, compiled_truth: body(v.compiled_truth), ...reason(v),...(typeof v.timeline === 'string' ? { timeline: body(v.timeline) } : {}), ...(quote ? { quoted: 'transcript' } : {}) });}return out;@@ -261,9 +263,26 @@ const get_versions: Operation = {cliHints: { name: 'history', positional: ['slug'] },};-/** GBRA-217: a remote reader's `replaced_because` goes through the same sanitizer as the version bodies. */-function remoteReason(v: { replaced_because?: string | null }): { replaced_because?: string } {- return typeof v.replaced_because === 'string' ? { replaced_because: sanitizeRemoteBody(v.replaced_because) } : {};+/**+ * GBRA-217: a remote reader's `replaced_because` goes through the same sanitizer as the version bodies. GBRA-286+ * (#8042, GST-687): it is quoted when the write that gave it (the next snapshot, or the live page when none) is of a+ * third-party type or below the owner's tier, as that write's text is. A trusted local reader gets it as stored.+ */+async function remoteReasons(ctx: OperationContext, slug: string, versions: ReadonlyArray<{ id: number; replaced_because?: string | null }>):+ Promise<(v: { id: number; replaced_because?: string | null }) => { replaced_because?: string }> {+ const ids = versions.filter(v => typeof v.replaced_because === 'string').map(v => Number(v.id));+ if (ctx.remote === false || ids.length === 0) return () => ({});+ const writers = new Map((await ctx.engine.executeRaw<{ id: number | string; type: string | null; tier: string | null }>(+ `SELECT pv.id, COALESCE(nx.type, p.type) AS type, CASE WHEN nx.id IS NULL THEN p.trust_tier ELSE nx.trust_tier END AS tier+ FROM page_versions pv JOIN pages p ON p.id = pv.page_id+ LEFT JOIN LATERAL (SELECT n.id, n.type, n.trust_tier FROM page_versions n WHERE n.page_id = pv.page_id AND n.id > pv.id ORDER BY n.id LIMIT 1) nx ON true+ WHERE pv.id = ANY($1::bigint[])`, [ids])).map(r => [Number(r.id), r] as const));+ return v => {+ if (typeof v.replaced_because !== 'string') return {};+ const clean = sanitizeRemoteBody(v.replaced_because);+ const writer = writers.get(Number(v.id));+ return { replaced_because: clean && quotesStored(writer?.type, writer?.tier) ? fenceTranscriptText(clean, slug) : clean };+ };}/**diff --git a/src/core/ops/valid-time-read.ts b/src/core/ops/valid-time-read.tsindex 08719b727b..312d7bb703 100644--- a/src/core/ops/valid-time-read.ts+++ b/src/core/ops/valid-time-read.ts@@ -19,7 +19,9 @@ import { inlineBodyBytes } from './get-page-body.ts';import { pageTrustForRead } from './get-page-projection.ts';import { isCalendarDate } from '../link-validity.ts';import { replacedBecauseSql } from '../engine-sql/pages.ts';-import { privateLinkOriginFilterFragment, privatePagesFilterFragment, privateSnapshotFilterFragment, resolveExcludePrivatePages } from '../search/private-visibility.ts';+import { callerReadersAllowedSql, privacyForCaller, privateLinkOriginFilterFragment, privatePagesFilterForCaller, privatePagesFilterFragment, privateSnapshotFilterFragment, resolveExcludePrivatePages } from '../search/private-visibility.ts';+import { fenceTranscriptText, isQuotedPageType, neutralizeToolCalls, quotesStored } from '../search/transcript-quote.ts';+import { quotedPageMeta } from './get-page-projection.ts';import { sanitizeRemoteBody } from '../remote-body.ts';import { serializePageToMarkdown } from '../markdown.ts';import { pageDocument } from '../page-window/document.ts';@@ -47,6 +49,8 @@ interface Identity { id: number; source_id: string; slug: string; source_path: sinterface PickRow {version_id: number | null; ord: number; replaced_at: string | null; valid_from: string; valid_until: string | null; visible: boolean;reason: string | null; successor_pruned: boolean; segmented: boolean; recorded_since: string | null; introduced_because: string | null; chosen: boolean;+ /** GBRA-286 (GST-687): the stored trust tier of this edition and of the write that replaced it (the next row), for the quote fence. */+ tier: string | null; successor_tier: string | null;}interface PickResult { row: PickRow | null; competing: number[]; undated: number; largeVersions: number; segmentedVersions: number; anyFiled: boolean; gapAt: string | null; createdAt: string | null }@@ -88,7 +92,7 @@ async function resolveIdentity(tx: BrainEngine, ctx: OperationContext, slug: strconst rows = await tx.executeRaw<Identity>(`SELECT p.id, p.source_id, p.slug, p.source_path, s.local_path, ${privatePagesFilterFragment('p')} AS worldFROM pages p JOIN sources s ON s.id = p.source_idWHERE p.slug = $1 AND p.deleted_at IS NULL AND ($2::text IS NULL OR p.source_id = $2) AND ($3::text[] IS NULL OR p.source_id = ANY($3::text[]))- ${excludePrivate ? `AND ${privatePagesFilterFragment('p')}` : ''}+ ${excludePrivate ? `AND ${privatePagesFilterForCaller('p')}` : ''}ORDER BY p.source_id LIMIT 6`, [slug, scope.sourceId ?? null, scope.sourceIds ?? null]);if (rows.length > 1) {const sources = rows.map(r => r.source_id);@@ -111,17 +115,18 @@ async function pick(tx: BrainEngine, pageId: number, asOf: string, excludePrivatconst vd = (a: string, key: string) => validDateSql(`${a}.frontmatter->>'${key}'`);const [r] = await tx.executeRaw<Record<string, unknown>>(`WITH rows AS (SELECT pv.id AS version_id, pv.id::bigint AS ord, pv.snapshot_at AS replaced_at, ${vd('pv', 'valid_from')} AS valid_from, ${vd('pv', 'valid_until')} AS valid_until,- ${bodyKey('pv')} AS body_key, ${privateSnapshotFilterFragment('pv')} AS visible, ${replacedBecauseSql('pv', excludePrivate)} AS reason,+ ${bodyKey('pv')} AS body_key, (${callerReadersAllowedSql('pv', 'snapshot')} AND ${privacyForCaller('p', privateSnapshotFilterFragment('pv'))}) AS visible,+ ${replacedBecauseSql('pv', excludePrivate)} AS reason, pv.trust_tier AS tier,COALESCE(pv.successor_pruned, false) AS successor_pruned, COALESCE(pv.body_storage = 'segmented', false) AS segmented,(pv.body_storage IS DISTINCT FROM 'segmented' AND octet_length(COALESCE(pv.compiled_truth, '')) + octet_length(COALESCE(pv.timeline, '')) > $3) AS large,pv.source_path IS NOT NULL AS filed- FROM page_versions pv WHERE pv.page_id = $1+ FROM page_versions pv JOIN pages p ON p.id = pv.page_id WHERE pv.page_id = $1UNION ALL- SELECT NULL, ${CURRENT_ORD}::bigint, NULL, ${vd('p', 'valid_from')}, ${vd('p', 'valid_until')}, ${bodyKey('p')}, ${privatePagesFilterFragment('p')}, NULL,+ SELECT NULL, ${CURRENT_ORD}::bigint, NULL, ${vd('p', 'valid_from')}, ${vd('p', 'valid_until')}, ${bodyKey('p')}, ${privatePagesFilterForCaller('p')}, NULL, p.trust_tier,false, COALESCE(p.body_storage = 'segmented', false), false, p.source_path IS NOT NULLFROM pages p WHERE p.id = $1),seq AS (- SELECT r.*, lag(r.replaced_at) OVER w AS recorded_since, lag(r.reason) OVER w AS introduced_because,+ SELECT r.*, lag(r.replaced_at) OVER w AS recorded_since, lag(r.reason) OVER w AS introduced_because, lead(r.tier) OVER w AS successor_tier,lag(r.ord) OVER w AS prev_ord, lead(r.ord) OVER w AS next_ordFROM rows r WINDOW w AS (ORDER BY r.ord)),pick AS (@@ -131,7 +136,7 @@ async function pick(tx: BrainEngine, pageId: number, asOf: string, excludePrivatCASE WHEN s.valid_from > $2::text THEN s.valid_from END ASC, s.ord DESCLIMIT 1)SELECT k.version_id, k.ord, k.replaced_at, k.valid_from, k.valid_until, k.visible, k.reason, k.successor_pruned, k.segmented,- k.recorded_since, k.introduced_because, k.chosen,+ k.recorded_since, k.introduced_because, k.chosen, k.tier, k.successor_tier,(SELECT array_agg(c.ord ORDER BY c.ord) FROM (SELECT s.ord FROM seq sWHERE s.valid_from IS NOT NULL AND s.ord <> k.ord AND ((s.ord > k.ord AND s.valid_from < k.valid_from)@@ -148,6 +153,7 @@ async function pick(tx: BrainEngine, pageId: number, asOf: string, excludePrivatvalid_until: r.valid_until == null ? null : String(r.valid_until), visible: r.visible === true, reason: (r.reason as string | null) ?? null,successor_pruned: r.successor_pruned === true, segmented: r.segmented === true, recorded_since: iso(r.recorded_since),introduced_because: (r.introduced_because as string | null) ?? null, chosen: r.chosen === true,+ tier: (r.tier as string | null) ?? null, successor_tier: (r.successor_tier as string | null) ?? null,} : null;return { row, competing: ((r?.competing as unknown[] | null) ?? []).map(Number), undated: Number(r?.undated ?? 0),largeVersions: Number(r?.large_versions ?? 0), segmentedVersions: Number(r?.segmented_versions ?? 0), anyFiled: r?.any_filed === true,@@ -241,13 +247,25 @@ async function loadEdition(tx: BrainEngine, identity: Identity, row: PickRow): Psegmented: v.body_storage === 'segmented', ...(v.body_generation != null ? { generation: Number(v.body_generation) } : {}) } };}-/** The edition as the caller may read it: whole, or one window (with the next call pinned to it) when it is large or segmented. */-async function editionView(ctx: OperationContext, identity: Identity, e: Edition, asOf: string, offset: number | null, maxBytes: number): Promise<Record<string, unknown> | 'gone'> {- const clean = (s: string) => ctx.remote === false ? s : sanitizeRemoteBody(s, { includeWithdrawn: true, keepMaterializedMarkers: true });- const meta = { ...(e.versionId === null ? { revision: e.revision } : { version_id: e.versionId }), title: e.title, type: e.type, tags: e.tags, frontmatter: e.frontmatter };+/**+ * The edition as the caller may read it: whole, or one window (with the next call pinned to it) when it is large or segmented.+ * GBRA-286 (#8042, GST-687): with `quote` (a remote reader, and an edition below the owner's tier or of a third-party+ * type) its text and metadata are fenced as quoted source material, a third-party edition's tool-call blocks summarized,+ * as get_page quotes the current page.+ */+async function editionView(ctx: OperationContext, identity: Identity, e: Edition, asOf: string, offset: number | null, maxBytes: number, quote: boolean): Promise<Record<string, unknown> | 'gone'> {+ const neutralize = quote && ctx.thinClient !== true && isQuotedPageType(e.type);+ const clean = (s: string) => {+ if (ctx.remote === false) return s;+ const safe = sanitizeRemoteBody(s, { includeWithdrawn: true, keepMaterializedMarkers: true });+ return neutralize ? neutralizeToolCalls(safe) : safe;+ };+ const fence = (s: string) => quote && s ? fenceTranscriptText(s, identity.slug) : s;+ const { title, frontmatter, tags } = quotedPageMeta({ slug: identity.slug, title: e.title, frontmatter: e.frontmatter }, quote, e.tags);+ const meta = { ...(e.versionId === null ? { revision: e.revision } : { version_id: e.versionId }), title, type: e.type, tags, frontmatter, ...(quote ? { quoted: 'transcript' } : {}) };const truth = e.segmented ? '' : clean(e.compiled_truth), timeline = e.segmented ? '' : clean(e.timeline);const bytes = Buffer.byteLength(truth, 'utf8') + Buffer.byteLength(timeline, 'utf8');- if (!e.segmented && offset === null && (ctx.remote === false || bytes <= await inlineBodyBytes(ctx))) return { ...meta, compiled_truth: truth, timeline };+ if (!e.segmented && offset === null && (ctx.remote === false || bytes <= await inlineBodyBytes(ctx))) return { ...meta, compiled_truth: fence(truth), timeline: fence(timeline) };let total: number, slice: WindowSlice, lines: number | undefined;if (e.segmented) {try {@@ -262,7 +280,7 @@ async function editionView(ctx: OperationContext, identity: Identity, e: Editionslice = windowFrom(doc.bytes, offset ?? 0, maxBytes);}const out: Record<string, unknown> = { ...meta, body: 'window', size: { total_bytes: total, ...(lines !== undefined ? { total_lines: lines } : {}) },- window: slice, truncated: slice.byte_start > 0 || slice.byte_end < total };+ window: quote ? { ...slice, text: fence(slice.text) } : slice, truncated: slice.byte_start > 0 || slice.byte_end < total };if (slice.byte_end < total) {const cursor = encodeCursor({ page_id: identity.id, revision: e.versionId === null ? e.revision : `v:${e.versionId}`, view: 'read', offset: slice.byte_end, max_bytes: maxBytes });out.next_cursor = cursor;@@ -323,15 +341,20 @@ export async function getPageAsOf(ctx: OperationContext, p: Record<string, unknolet { history, uncertain, why } = verdict;let view: Record<string, unknown> | 'gone' | null = null;const requested = typeof p.max_bytes === 'number' && Number.isSafeInteger(p.max_bytes) && p.max_bytes > 0 ? p.max_bytes : pin?.maxBytes ?? DEFAULT_WINDOW_BYTES;- if (!read.pinGone) view = await editionView(ctx, identity, loaded.edition, asOf, pin ? pin.offset : null, ctx.remote === false ? requested : Math.min(requested, MAX_WINDOW_BYTES));+ const quotes = (tier: string | null) => ctx.remote !== false && quotesStored(loaded.edition.type, tier);+ if (!read.pinGone) view = await editionView(ctx, identity, loaded.edition, asOf, pin ? pin.offset : null, ctx.remote === false ? requested : Math.min(requested, MAX_WINDOW_BYTES), quotes(row.tier));if (read.pinGone || view === 'gone') { history = 'incomplete'; uncertain = true; why = 'edition_pruned'; view = null; }- const reason = (s: string | null) => s === null ? null : ctx.remote === false ? s : sanitizeRemoteBody(s);+ const reason = (s: string | null, tier: string | null) => {+ if (s === null || ctx.remote === false) return s;+ const clean = sanitizeRemoteBody(s);+ return quotes(tier) && clean ? fenceTranscriptText(clean, identity.slug) : clean;+ };const chosen = row.chosen;const validTime = {as_of: asOf, status: verdict.status,chosen_version_id: chosen ? row.version_id : null, chosen_is_current: chosen && row.version_id === null,valid_from: chosen ? row.valid_from : null, valid_until: chosen ? row.valid_until : null,- introduced_because: chosen ? reason(row.introduced_because) : null, replaced_because: chosen ? reason(row.reason) : null,+ introduced_because: chosen ? reason(row.introduced_because, row.tier) : null, replaced_because: chosen ? reason(row.reason, row.successor_tier) : null,history, uncertain, why, undated_versions: picked.undated, amendments_not_applied: amendments,recorded_since: chosen ? row.recorded_since ?? (picked.gapAt === null ? picked.createdAt : null) : null,...(why === 'ambiguous_edition_dates' ? { competing_version_ids: picked.competing.map(o => o === CURRENT_ORD ? null : o) } : {}),diff --git a/test/page-change-reason-gbra217.test.ts b/test/page-change-reason-gbra217.test.tsindex ee0e678824..99a66d616a 100644--- a/test/page-change-reason-gbra217.test.ts+++ b/test/page-change-reason-gbra217.test.ts@@ -14,6 +14,7 @@ import type { BrainEngine } from '../src/core/engine.ts';import { operationsByName, OperationError, type OperationContext } from '../src/core/operations.ts';import { canonicalChangeReason, CHANGE_REASON_MAX } from '../src/core/persistence/change-reason.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { unquoteTranscriptText } from '../src/core/search/transcript-quote.ts';import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';@@ -156,7 +157,8 @@ for (const backend of testBackends()) describe(`[${backend}] page change reasonsexpect(JSON.stringify(remote)).not.toContain('private-time reason');await call('put_page', { slug: SLUG, content: page('world three'), expected_revision: await revision(), reason: 'third edition', wait_ms: 30_000 });- expect((await versions(true))[0]!.replaced_because).toBe('third edition');+ // GBRA-286: put_page writes agent_written text, so a remote reader gets the reason quoted (GST-687).+ expect(unquoteTranscriptText(String((await versions(true))[0]!.replaced_because), SLUG)).toBe('third edition');await engine.executeRaw("UPDATE page_versions SET successor_pruned = true WHERE change_reason = 'third edition'");expect((await versions(true))[0]!.replaced_because).toBeNull();expect((await versions(false))[0]!.replaced_because).toBe('third edition');diff --git a/test/page-change-reason-mcp-gbra217.test.ts b/test/page-change-reason-mcp-gbra217.test.tsindex 0e0859fce7..5c5fa7426f 100644--- a/test/page-change-reason-mcp-gbra217.test.ts+++ b/test/page-change-reason-mcp-gbra217.test.ts@@ -17,6 +17,7 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { dispatchToolCall, type ToolResult } from '../src/mcp/dispatch.ts';import { registerLocalWriter, withVerifiedLocalRegistration } from '../src/core/persistence/identity.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { unquoteTranscriptText } from '../src/core/search/transcript-quote.ts';import { withEnv } from './helpers/with-env.ts';let engine: PGLiteEngine;@@ -42,7 +43,8 @@ describe('A-T10: reasons over MCP, remote=true', () => {expect(second.isError).toBeFalsy();expect(JSON.stringify(body(second))).toContain('"no_repository"');const versions = body(await call('get_versions', { slug })) as unknown as Array<Record<string, unknown>>;- expect(versions[0]!.replaced_because).toBe('Client asked for the 30-day window.');+ // GBRA-286: the reason of an agent-written edition reaches a remote reader quoted (GST-687).+ expect(unquoteTranscriptText(String(versions[0]!.replaced_because), slug)).toBe('Client asked for the 30-day window.');const secret = 'ghp_' + 'Z9y8X7w6V5u4T3s2R1q0P9o8N7m6L5k4J3i2';const refused = await call('put_page', { slug, content: page('x'), request_id: randomUUID(), reason: `new token ${secret}` });diff --git a/test/page-history-guards-gbra286.test.ts b/test/page-history-guards-gbra286.test.tsindex 182113bc3d..70b0d50f05 100644--- a/test/page-history-guards-gbra286.test.ts+++ b/test/page-history-guards-gbra286.test.ts@@ -74,12 +74,14 @@ for (const backend of testBackends()) {const unlisted = await versions(slug, true);expect(unlisted).toHaveLength(1);- expect(unlisted[0]!.replaced_because).toBeUndefined();+ expect(unlisted[0]!.replaced_because).toBeNull();expect(JSON.stringify(unlisted)).not.toContain('canaryrbreason');expect(JSON.stringify(await versions(slug, true, { include_body: true }))).not.toContain('canaryrbreason');const member = await asMember(() => versions(slug, true));- expect(member.map(v => v.replaced_because)).toEqual(['opened again', 'restricted-time reason canaryrbreason']);+ expect(member).toHaveLength(2);+ expect(member[0]!.replaced_because).toContain('opened again');+ expect(member[1]!.replaced_because).toContain('restricted-time reason canaryrbreason');});test('as_of: an edition that names readers reads as not found for an unlisted remote reader, and as text for a listed member', async () => {@@ -98,7 +100,7 @@ for (const backend of testBackends()) {const member = await asMember(() => call('get_page', { slug, as_of: '2026-03-01' }, true));expect(member.valid_time.status).toBe('in_force');expect(member.compiled_truth).toContain('canaryasofbody');- expect(member.valid_time.replaced_because).toBe('opened to everyone canaryasofreason');+ expect(member.valid_time.replaced_because).toContain('opened to everyone canaryasofreason');});test('as_of: an unlisted remote reader never sees a reason whose successor edition names readers', async () => {@@ -112,7 +114,7 @@ for (const backend of testBackends()) {expect(old.valid_time.replaced_because).toBeNull();expect(JSON.stringify(old)).not.toContain('canaryasofsuccessor');const member = await asMember(() => call('get_page', { slug, as_of: '2026-03-01' }, true));- expect(member.valid_time.replaced_because).toBe('restricted canaryasofsuccessor');+ expect(member.valid_time.replaced_because).toContain('restricted canaryasofsuccessor');});test('as_of and get_versions quote text below the owner tier for a remote reader', async () => {diff --git a/test/valid-time-gbra217.test.ts b/test/valid-time-gbra217.test.tsindex 10626e59ad..eed224c7b3 100644--- a/test/valid-time-gbra217.test.ts+++ b/test/valid-time-gbra217.test.ts@@ -25,6 +25,7 @@ import { assertValidTimeEcho, currentValidTime, validDate, validDateSql, validTiimport { exitCodeForCode } from '../src/core/error-catalogue.ts';import { asOfExitCode, formatGetPage, validTimeLine } from '../src/cli/page-render.ts';import { utcToday } from '../src/core/link-validity.ts';+import { unquoteTranscriptText } from '../src/core/search/transcript-quote.ts';import { testBackends, requirePostgresTestDatabase } from './helpers/test-backends.ts';import { importSegmented } from './helpers/segmented-privacy-fixture.ts';@@ -213,7 +214,7 @@ for (const backend of testBackends()) {expect(early.valid_time.replaced_because).toBeNull();expect((await read(slug, '2026-03-01')).valid_time.replaced_because).toBe('reason-r2-private-time');const late = await read(slug, '2026-10-01', true);- expect(late.valid_time.introduced_because).toBe('reason-r3-back-to-world');+ expect(unquoteTranscriptText(late.valid_time.introduced_because, slug)).toBe('reason-r3-back-to-world');for (const d of ['2025-01-01', '2026-03-01', '2026-10-01']) expect(JSON.stringify(await read(slug, d, true))).not.toContain('reason-r2');});@@ -326,14 +327,15 @@ for (const backend of testBackends()) {expect(r.valid_time).toMatchObject({ status: 'in_force', chosen_version_id: v1 });expect(r.compiled_truth).toBeUndefined();expect(r.body).toBe('window');- let text = r.window.text;+ // GBRA-286: put_page writes agent_written text, so each remote window comes quoted (GST-687).+ let text = unquoteTranscriptText(r.window.text, slug);let hops = 0;while (r.next) {expect(r.next.arguments).toMatchObject({ slug, source_id: 'default', as_of: '2026-03-01' });if (hops === 1) await put(slug, 'A third edition written mid-read.', ["valid_from: '2026-02-01'"]);r = await call('get_page', r.next.arguments, true);expect(r.version_id).toBe(v1);- text += r.window.text;+ text += unquoteTranscriptText(r.window.text, slug);hops++;}expect(hops).toBeGreaterThan(2);