Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

get_page content_only keeps source_id; put_page names the source a stale revision came from (W-B2)

garrytanb29428444a6e
diff --git a/src/core/ops/get-page-projection.ts b/src/core/ops/get-page-projection.ts
index 076a7c05d2..2960c7ca2f 100644
--- a/src/core/ops/get-page-projection.ts
+++ b/src/core/ops/get-page-projection.ts
@@ -22,7 +22,8 @@ export interface GetPageProjectionOpts {
* #2225: `content` is the canonical serialized markdown (frontmatter +
* compiled_truth + `<!-- timeline -->` sentinel + timeline), built from the
* visible body so the privacy-fence strip applies to untrusted readers too.
- * content_only returns just what a get→edit→put_page round trip needs, without
+ * content_only returns just what a get→edit→put_page round trip needs (source_id
+ * and revision included, so the write goes back to the page that was read), without
* the duplicate compiled_truth / timeline / frontmatter the full shape carries
* next to `content` (a 30 KB page otherwise comes back as ~62 KB).
*/
@@ -37,6 +38,7 @@ export function projectGetPage(visibleBody: Page, o: GetPageProjectionOpts) {
const deletedAt = visibleBody.deleted_at;
return {
slug: visibleBody.slug,
+ source_id: visibleBody.source_id,
type: visibleBody.type,
title: visibleBody.title,
revision,
diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.ts
index a1b28aa4b0..eaf19b6f6d 100644
--- a/src/core/ops/pages.ts
+++ b/src/core/ops/pages.ts
@@ -25,7 +25,7 @@ import { resolveExcludePrivatePages, isPrivatePage, findPrivateOnlySlugs } from
import { LIST_PAGES_DESCRIPTION, CAPTURE_DESCRIPTION } from '../operations-descriptions.ts';
import { listPagesPagination, listingTruncatedNotice } from './list-pages-pagination.ts';
import { OperationError, opError, type Operation, type OperationContext } from './contract.ts';
-import { invalidParam } from './op-fix.ts';
+import { invalidParam, readFix } from './op-fix.ts';
import {
assertExplicitSourceLive,
enforceSubagentSlugFence,
@@ -308,7 +308,7 @@ const put_page: Operation = {
mutating: true,
scope: 'write',
handler: async (ctx, p) => {
- pageMutationSource(ctx, p, 'put_page');
+ const sourceId = pageMutationSource(ctx, p, 'put_page');
if (ctx.dryRun) {
if (typeof p.slug === 'string') {
validatePageSlug(p.slug);
@@ -317,11 +317,48 @@ const put_page: Operation = {
}
return { dry_run: true, action: 'put_page', slug: p.slug };
}
- return submitPageMutation(ctx, { operation: 'put_page', params: p });
+ try {
+ return await submitPageMutation(ctx, { operation: 'put_page', params: p });
+ } catch (error) {
+ if (error instanceof OperationError && error.code === 'revision_conflict') await nameRevisionSource(ctx, sourceId, p, error);
+ throw error;
+ }
},
cliHints: { name: 'put', positional: ['slug'], stdin: 'content' },
};
+/**
+ * A put_page refused as revision_conflict whose expected_revision is the
+ * current revision of the same slug in another source was almost certainly
+ * read there and written back without its source_id. The refusal then names
+ * that source, and its fix re-reads the page there. Only a source and page
+ * the caller may read are named (grant and page visibility, as get_page
+ * applies them); otherwise the refusal is left exactly as it was.
+ */
+async function nameRevisionSource(ctx: OperationContext, writeSource: string, p: Record<string, unknown>, error: OperationError): Promise<void> {
+ if (typeof p.slug !== 'string' || typeof p.expected_revision !== 'string') return;
+ const slug = p.slug.toLowerCase();
+ const expected = p.expected_revision.toLowerCase();
+ try {
+ const candidates = await ctx.engine.executeRaw<{ source_id: string }>(
+ `SELECT p.source_id FROM pages p JOIN sources s ON s.id = p.source_id
+ WHERE p.slug = $1 AND p.source_id <> $2 AND p.deleted_at IS NULL AND s.archived IS NOT TRUE ORDER BY p.source_id`, [slug, writeSource]);
+ const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote);
+ for (const { source_id: other } of candidates) {
+ try { federatedSearchScope(ctx, other); } catch { continue; }
+ const snapshot = await ctx.engine.readPageSnapshot(slug, { sourceId: other, excludePrivate });
+ if (!snapshot || snapshot.revision !== expected || (excludePrivate && isPrivatePage(snapshot.page))) continue;
+ error.suggestion = `Page ${slug} is at exactly this expected_revision in source ${other}, so it was probably read there; this write went to source ${writeSource}. `
+ + `Re-read it with source_id ${other}; a write to that page must carry source_id ${other} and the revision get_page returns.`;
+ error.fix = readFix(`Reads page ${slug} from source ${other}, where its revision matches the one this write sent.`,
+ { argv: ['gbrain', 'get', '--source', other, '--', slug], mcp: { tool: 'get_page', arguments: { slug, source_id: other, include_content: true } } });
+ return;
+ }
+ } catch {
+ // The hint is advisory: a failed lookup leaves the refusal unchanged.
+ }
+}
+
// v0.31.2: isFactsBackstopEligible moved to src/core/facts/eligibility.ts
// so sync.ts, file_upload, code_import, and runFactsBackstop all share one
// predicate. Imported above.
diff --git a/test/get-page-content-roundtrip-2225.test.ts b/test/get-page-content-roundtrip-2225.test.ts
index 9df3c294f7..2ac3feeec0 100644
--- a/test/get-page-content-roundtrip-2225.test.ts
+++ b/test/get-page-content-roundtrip-2225.test.ts
@@ -21,6 +21,8 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { configureGateway } from '../src/core/ai/gateway.ts';
import { operations, type OperationContext } from '../src/core/operations.ts';
import type { GBrainConfig } from '../src/core/config.ts';
+import { OperationError } from '../src/core/ops/contract.ts';
+import { registerLocalWriter } from '../src/core/persistence/identity.ts';
let engine: PGLiteEngine;
const noopLogger = { info: () => {}, warn: () => {}, error: () => {} };
@@ -28,14 +30,14 @@ const noopLogger = { info: () => {}, warn: () => {}, error: () => {} };
const getPage = operations.find((o) => o.name === 'get_page')!;
const putPage = operations.find((o) => o.name === 'put_page')!;
-function localCtx(): OperationContext {
+function localCtx(sourceId = 'default'): OperationContext {
return {
engine,
config: {} as GBrainConfig,
logger: noopLogger,
dryRun: false,
remote: false,
- sourceId: 'default',
+ sourceId,
} as OperationContext;
}
@@ -154,3 +156,100 @@ ${page.timeline as string}
expect(row!.compiled_truth ?? '').not.toContain('Series A closed');
}, 30_000);
});
+
+/**
+ * The lean shape carries source_id, so a get→edit→put_page round trip on a
+ * page outside the caller's default source writes back to that source. A
+ * client that drops it gets a revision_conflict naming the source it read,
+ * but only when the caller may read that source and page.
+ */
+describe('content_only round trip across sources', () => {
+ const CLIENT = 'client-roundtrip-example';
+ const PAGE = (body: string) => `---\ntype: company\ntitle: Acme Example\n---\n\n${body}\n`;
+ const lean = async (slug: string, sourceId: string) => (await getPage.handler(localCtx(), {
+ slug, source_id: sourceId, include_content: true, content_only: true })) as Record<string, string>;
+ const remoteCtx = (readable: string[]): OperationContext => ({ ...localCtx(), remote: true, transport: 'http',
+ auth: { token: 'fixture', clientId: CLIENT, principal: { kind: 'oauth_client', id: CLIENT }, scopes: ['read', 'write'],
+ sourceId: 'default', allowedSources: readable } } as unknown as OperationContext);
+ const refusal = async (ctx: OperationContext, params: Record<string, unknown>): Promise<OperationError> => {
+ try { await putPage.handler(ctx, params); } catch (e) { if (e instanceof OperationError) return e; throw e; }
+ throw new Error('put_page was expected to refuse');
+ };
+ const shape = (e: OperationError) => {
+ const { write_request: _w, ...rest } = e.toJSON() as Record<string, unknown>;
+ return { ...rest, suggestion: String(rest.suggestion).replace(/request_id [0-9a-f-]{36}/, 'request_id <id>') };
+ };
+
+ beforeAll(async () => {
+ await engine.executeRaw("INSERT INTO sources(id,name) VALUES('work','work') ON CONFLICT DO NOTHING");
+ await putPage.handler(localCtx(), { slug: 'companies/warmup-example', content: PAGE('Warm-up.') });
+ await registerLocalWriter(engine, 'cli');
+ await engine.executeRaw(`INSERT INTO oauth_clients(client_id,client_secret_hash,client_name,scope,source_id)
+ VALUES($1,'fixture-hash','example-client','read write','default')`, [CLIENT]);
+ }, 30_000);
+
+ test('lean keys are pinned and include source_id', async () => {
+ await putPage.handler(localCtx('work'), { slug: 'companies/keys-example', content: PAGE('Keys.') });
+ const page = await lean('companies/keys-example', 'work');
+ expect(Object.keys(page).sort()).toEqual(['content', 'revision', 'slug', 'source_id', 'tags', 'title', 'type']);
+ expect(page.source_id).toBe('work');
+ }, 30_000);
+
+ test('passing the returned source_id writes back to the page that was read', async () => {
+ await putPage.handler(localCtx('work'), { slug: 'companies/route-example', content: PAGE('Work copy, 42 employees.') });
+ await putPage.handler(localCtx(), { slug: 'companies/route-example', content: PAGE('Default copy.') });
+ const page = await lean('companies/route-example', 'work');
+ await putPage.handler(localCtx(), { slug: 'companies/route-example', source_id: page.source_id,
+ content: page.content.replace('42 employees', '44 employees'), expected_revision: page.revision });
+ expect((await engine.getPage('companies/route-example', { sourceId: 'work' }))!.compiled_truth).toContain('44 employees');
+ expect((await engine.getPage('companies/route-example', { sourceId: 'default' }))!.compiled_truth).toContain('Default copy.');
+ }, 30_000);
+
+ test('a naive write-back without source_id is refused with a refusal naming work', async () => {
+ await putPage.handler(localCtx('work'), { slug: 'companies/naive-example', content: PAGE('Work only.') });
+ const page = await lean('companies/naive-example', 'work');
+ const error = await refusal(localCtx(), { slug: 'companies/naive-example', content: page.content.replace('only', 'edited'), expected_revision: page.revision });
+ expect(error.code).toBe('revision_conflict');
+ expect(error.suggestion).toContain('source work');
+ expect(error.fix?.argv).toEqual(['gbrain', 'get', '--source', 'work', '--', 'companies/naive-example']);
+ expect(error.fix?.mcp).toEqual({ tool: 'get_page', arguments: { slug: 'companies/naive-example', source_id: 'work', include_content: true } });
+ expect(await engine.getPage('companies/naive-example', { sourceId: 'default' })).toBeNull();
+ expect((await engine.getPage('companies/naive-example', { sourceId: 'work' }))!.compiled_truth).toContain('Work only.');
+ }, 30_000);
+
+ test('a remote caller that cannot read work gets the unchanged refusal: same shape, no hint', async () => {
+ await putPage.handler(localCtx('work'), { slug: 'companies/unreadable-example', content: PAGE('Work only.') });
+ const page = await lean('companies/unreadable-example', 'work');
+ const hidden = await refusal(remoteCtx(['default']), { slug: 'companies/unreadable-example', content: page.content, expected_revision: page.revision });
+ const control = await refusal(remoteCtx(['default']), { slug: 'companies/nowhere-example', content: page.content, expected_revision: page.revision });
+ expect(hidden.code).toBe('revision_conflict');
+ expect(hidden.fix).toBeUndefined();
+ expect(JSON.stringify(hidden.toJSON())).not.toContain('work');
+ expect(shape(hidden)).toEqual(shape(control));
+ // The same caller granted work is told where the page lives.
+ const granted = await refusal(remoteCtx(['default', 'work']), { slug: 'companies/unreadable-example', content: page.content, expected_revision: page.revision });
+ expect(granted.suggestion).toContain('source work');
+ }, 30_000);
+
+ test('a private page in a readable source is not named to a remote caller', async () => {
+ await putPage.handler(localCtx('work'), { slug: 'companies/private-example', content: `---\ntype: company\ntitle: Acme Example\nvisibility: private\n---\n\nPrivate.\n` });
+ const page = await lean('companies/private-example', 'work');
+ const error = await refusal(remoteCtx(['default', 'work']), { slug: 'companies/private-example', content: page.content, expected_revision: page.revision });
+ expect(error.code).toBe('revision_conflict');
+ expect(error.fix).toBeUndefined();
+ expect(JSON.stringify(error.toJSON())).not.toContain('work');
+ // A trusted local caller reads private pages, so it is told.
+ expect((await refusal(localCtx(), { slug: 'companies/private-example', content: page.content, expected_revision: page.revision })).suggestion).toContain('source work');
+ }, 30_000);
+
+ test('an ordinary same-source conflict next to a namesake names no other source', async () => {
+ await putPage.handler(localCtx('work'), { slug: 'companies/stale-example', content: PAGE('Work copy.') });
+ await putPage.handler(localCtx(), { slug: 'companies/stale-example', content: PAGE('Default v1.') });
+ const stale = await lean('companies/stale-example', 'default');
+ await putPage.handler(localCtx(), { slug: 'companies/stale-example', content: PAGE('Default v2.'), expected_revision: stale.revision });
+ const error = await refusal(localCtx(), { slug: 'companies/stale-example', content: PAGE('Default v3.'), expected_revision: stale.revision });
+ expect(error.code).toBe('revision_conflict');
+ expect(error.fix).toBeUndefined();
+ expect(String(error.suggestion)).not.toContain('work');
+ }, 30_000);
+});