Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix: Step 11 review fixes (#8377: paged fence names the host slug; whole-markdown round trip keeps quoted metadata; iterative backtick run; takes writes and add_timeline_entry unfence copied text)
garrytanf6bdc33448e7
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2f78c9953b..e22d6ceffa 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -23,7 +23,7 @@ Before, #8367 left `chronicle_day`, `chronicle_since`, `chronicle_on_this_day`,- A thin client's paged `gbrain get` of a quoted page (above the inline limit) prints the page, and its `--json` content, inside one quote fence after verifying size and sha256.- The per-turn push hook and the pushed context pack quote hot and entity facts below the owner's tier; a fact injected before this change is not injected again.- `context_pack` counts the entity facts it withholds when the quote lookup fails (`suppressed`) instead of dropping them silently.-- Remote `remember` stores a fact copied out of a quoted read without the fence, and remote `add_timeline_entry` stores an entry copied out of `get_timeline` without it, so the replay key matches and the entry is not duplicated.+- Remote `remember` stores a fact copied out of a quoted read without the fence, and remote `add_timeline_entry` stores an entry copied out of `get_timeline` without it, so the replay key matches and the entry is not duplicated. `takes_add`, `takes_update` and `takes_supersede` do the same for a claim or source copied out of a quoted takes read.- The `put_page` tool-call guard counts only summaries outside the content's own tool-call blocks, and admits a new turn that quotes a summary while every stored call stays; its refusal names `edit_page` first.- Tests: `test/search-transcript-quote-followups.test.ts` (every item, red on master for the changed reads and writes) and `test/trust-keep-maintenance-reimport-8352.test.ts` (maintenance re-imports keep an owner note's tier), both on PGLite and Postgres.diff --git a/docs/mcp/README.md b/docs/mcp/README.mdindex 8f6e0529cc..d3e9348bba 100644--- a/docs/mcp/README.md+++ b/docs/mcp/README.md@@ -140,7 +140,8 @@ answer, `context_pack`, hot memory and write receipts. The context gbrain'shooks inject (the per-turn hook and the pushed context pack) quotes facts belowthe owner's tier the same way, so hook output can hold quote fences. A fact ortimeline entry an agent copies back from a quoted read into `remember` or-`add_timeline_entry` is stored without the fence. A note saved before gbrain+`add_timeline_entry`, or a claim or source copied into `takes_add`, `takes_update` or+`takes_supersede`, is stored without the fence. A note saved before gbraintracked trust reads as unverified, so it is quoted until the owner runs`gbrain trust claim-sources` or `gbrain trust backfill` (`gbrain doctor` names howmany pages that is). Page titles are quoted on `get_page` and `fetch` only:diff --git a/src/cli/page-render.ts b/src/cli/page-render.tsindex 9730f5a54c..8e3a068e4d 100644--- a/src/cli/page-render.ts+++ b/src/cli/page-render.ts@@ -184,7 +184,7 @@ async function spoolWholePage(call: PagedCall, params: Record<string, unknown>,if (bytes !== size.total_bytes || hash.digest('hex') !== size.sha256) {throw new Error(`The paged copy of ${String(params.slug)} does not match the size and sha256 the host reported; the page was not printed.`);}- return { lengths, revision, fence: quoted ? transcriptFence(String(params.slug), longest) : null };+ return { lengths, revision, fence: quoted ? transcriptFence(String(r.slug), longest) : null };}throw new Error(`${String(params.slug)} kept changing while it was being read (${MAX_RESTARTS + 1} attempts); the page was not printed. Try again.`);}diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex a18c831000..0ba304ba8d 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1393,7 +1393,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;// GST-687 (GBRA-269) quote fence by trust tier. since stamped at the merge slot.{ since: '0.60.536.0', id: 'remote_quotes_unverified_text_gst687', text: 'Agents connected over MCP now get text quoted as source material (a line naming its page or fact, then a code fence) when its stored trust tier is below "your notes": text written by an agent, tool data, external text and text of unverified origin. This covers search, query, recall, assemble_evidence, get_page, fetch, get_timeline, get_chunks, search_exact, think\'s extractive answer, get_versions and known_as_of reads, context_pack, delta, hot memory and write receipts; chronicle, takes and page title reads are not quoted yet. A note saved before gbrain tracked trust reads as unverified origin, so it is quoted until the owner claims its source (`gbrain trust claim-sources`) or `gbrain trust backfill` classifies it; `gbrain doctor` names how many pages that is. Conversation pages also come back with tool-call blocks summarized on get_page, fetch, search_exact, get_chunks and think; `get_page` with `include_content` and the markdown view keep the stored text. Local reads, stored text and trust tiers are unchanged.' },// #8377 (GBRA-269) quote fence follow-ups. since stamped at the merge slot.- { since: '0.60.537.0', id: 'remote_quotes_followups_8377', text: 'Agents connected over MCP now also get text below "your notes" quoted on the chronicle reads (chronicle_day, chronicle_since, chronicle_on_this_day, volunteer_chronicle), takes_list and takes_search (claim and source), and a quoted page\'s title and frontmatter (put_page of that read stores them unfenced); get_page include_content and fetch text fence the whole markdown, frontmatter included. The context gbrain\'s hooks inject (the per-turn hook and the pushed context pack) quotes facts below the owner\'s tier too, so hook output can hold quote fences. A thin client\'s paged `gbrain get` of a quoted page prints it inside the fence. remember and add_timeline_entry store text copied out of a quoted read without the fence, and put_page admits a conversation round trip whose stored tool call holds a summary in its arguments. Local reads are unchanged.' },+ { since: '0.60.537.0', id: 'remote_quotes_followups_8377', text: 'Agents connected over MCP now also get text below "your notes" quoted on the chronicle reads (chronicle_day, chronicle_since, chronicle_on_this_day, volunteer_chronicle), takes_list and takes_search (claim and source), and a quoted page\'s title and frontmatter (put_page of that read stores them unfenced); get_page include_content and fetch text fence the whole markdown, frontmatter included. The context gbrain\'s hooks inject (the per-turn hook and the pushed context pack) quotes facts below the owner\'s tier too, so hook output can hold quote fences. A thin client\'s paged `gbrain get` of a quoted page prints it inside the fence. remember, add_timeline_entry and the takes writes store text copied out of a quoted read without the fence, and put_page admits a conversation round trip whose stored tool call holds a summary in its arguments. Local reads are unchanged.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/ops/takes.ts b/src/core/ops/takes.tsindex fd74169296..6e127c6fe4 100644--- a/src/core/ops/takes.ts+++ b/src/core/ops/takes.ts@@ -11,7 +11,7 @@ import { MERGE_PRECONDITION_PARAMS, WRITE_REQUEST_PARAM } from '../persistence/pimport { opError, type Operation, type OperationContext } from './contract.ts';import { MIN_TRUST_PARAM, resolveReadEligibility } from '../eligibility/policy.ts';import { stampRowTrust } from '../eligibility/stamp.ts';-import { fenceTranscriptText, quotesTier } from '../search/transcript-quote.ts';+import { fenceTranscriptText, quotesTier, unquoteTranscriptText } from '../search/transcript-quote.ts';import { opTransport, paramUse } from './op-fix.ts';import {readPolicyOpts,@@ -70,6 +70,14 @@ function quoteTakes<T extends { claim: string; page_slug: string; trust_tier: st});}+/** #8377: a claim or source an agent copied out of a quoted takes read is written without the fence. */+function unquotedTakeParams(ctx: OperationContext, p: Record<string, unknown>): Record<string, unknown> {+ if (ctx.remote === false) return p;+ const slug = String(p.slug).toLowerCase();+ const unquote = (key: string) => typeof p[key] === 'string' ? { [key]: unquoteTranscriptText(p[key] as string, slug) } : {};+ return { ...p, ...unquote('claim'), ...unquote('source') };+}+// --- v0.28: Takes ---const takes_list: Operation = {@@ -478,7 +486,7 @@ const takes_add: Operation = {enforceClientSlugFence(ctx, slug, 'takes_add');validatePageSlug(slug); // defense-in-depth, matching put_pageif (ctx.dryRun) return { dry_run: true, action: 'takes_add', slug };- return submitPageMutation(ctx, { operation: 'takes_add', params: p });+ return submitPageMutation(ctx, { operation: 'takes_add', params: unquotedTakeParams(ctx, p) });},};@@ -509,7 +517,7 @@ const takes_update: Operation = {enforceClientSlugFence(ctx, slug, 'takes_update');validatePageSlug(slug); // defense-in-depth, matching put_pageif (ctx.dryRun) return { dry_run: true, action: 'takes_update', slug, row_num: p.row_num };- return submitPageMutation(ctx, { operation: 'takes_update', params: p });+ return submitPageMutation(ctx, { operation: 'takes_update', params: unquotedTakeParams(ctx, p) });},};@@ -543,7 +551,7 @@ const takes_supersede: Operation = {enforceClientSlugFence(ctx, slug, 'takes_supersede');validatePageSlug(slug); // defense-in-depth, matching put_pageif (ctx.dryRun) return { dry_run: true, action: 'takes_supersede', slug, row_num: p.row_num };- const out = await submitPageMutation(ctx, { operation: 'takes_supersede', params: p });+ const out = await submitPageMutation(ctx, { operation: 'takes_supersede', params: unquotedTakeParams(ctx, p) });recordFunnelEvent('correction');return out;},diff --git a/src/core/ops/timeline.ts b/src/core/ops/timeline.tsindex 5d8c1281db..c28ecc7459 100644--- a/src/core/ops/timeline.ts+++ b/src/core/ops/timeline.ts@@ -66,7 +66,7 @@ const add_timeline_entry: Operation = {throw badDate(`Invalid calendar date "${date}"`);}// #8377: an entry an agent copied out of a quoted read (get_timeline, chronicle) is stored without the fence, so its replay key matches.- const unquote = (v: unknown) => typeof v === 'string' && ctx.remote !== false ? unquoteTranscriptText(v, String(p.slug)) : v;+ const unquote = (v: unknown) => typeof v === 'string' && ctx.remote !== false ? unquoteTranscriptText(v, String(p.slug).toLowerCase()) : v;return submitPageMutation(ctx, { operation: 'add_timeline_entry', params: { ...p, summary: unquote(p.summary), ...(p.detail !== undefined ? { detail: unquote(p.detail) } : {}) } });},cliHints: { name: 'timeline-add', positional: ['slug', 'date', 'summary'] },diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.tsindex f95d655836..8544fec592 100644--- a/src/core/persistence/page-mutations.ts+++ b/src/core/persistence/page-mutations.ts@@ -263,20 +263,33 @@ export async function submitPageMutation(ctx: OperationContext,* GST-687: content carrying a tool-call summary that only the neutralized read of the stored chat page holds (get_page's* reading shape, fetch) is refused, so a read-then-write never replaces a stored tool call with its summary.*/-/** #8377: a quoted read fences the title and each frontmatter string as `slug`'s; YAML indents those fences, so the body's unquote misses them. */-function unquotedFrontmatter(content: string, slug: string): string {+/**+ * #8377: a quoted read's reading shape fences the title and each frontmatter string as `slug`'s (a whole-markdown read is+ * fenced once instead, and its metadata is the page's own). YAML indents those fences, so the body's unquote misses them:+ * each key that held one is rewritten unfenced, and every other frontmatter line is kept byte for byte.+ */+function unquotedFrontmatter(sent: string, content: string, slug: string): string {const offset = frontmatterBodyOffset(content);- if (!offset || !content.slice(0, offset).includes('```text')) return content;- const { frontmatter } = parseMarkdownHead(content);+ if (!offset || !frontmatterBodyOffset(sent) || !content.slice(0, offset).includes('```text')) return content;const unquote = (v: unknown): unknown => typeof v === 'string' ? unquoteTranscriptText(v, slug): Array.isArray(v) ? v.map(unquote): v && typeof v === 'object' && !(v instanceof Date) ? Object.fromEntries(Object.entries(v).map(([k, x]) => [k, unquote(x)])) : v;- const data = unquote(frontmatter) as Record<string, unknown>;- return JSON.stringify(data) === JSON.stringify(frontmatter) ? content : dataFrontmatter.stringify('', data) + content.slice(offset);+ const lines = content.slice(0, offset).split('\n');+ for (const [key, value] of Object.entries(parseMarkdownHead(content).frontmatter)) {+ const plain = unquote(value);+ if (JSON.stringify(plain) === JSON.stringify(value)) continue;+ const at = lines.findIndex((l, i) => i > 0 && l.startsWith(`${key}:`));+ if (at < 0) return content;+ let end = at + 1;+ while (end < lines.length && lines[end] !== '---' && (lines[end] === '' || /^\s/.test(lines[end]) || lines[end].startsWith('-'))) end++;+ const dumped = dataFrontmatter.stringify('', { [key]: plain }).split('\n');+ lines.splice(at, end - at, ...dumped.slice(1, dumped.lastIndexOf('---')));+ }+ return lines.join('\n') + content.slice(offset);}async function unquotedPutContent(engine: BrainEngine, sourceId: string, slug: string, content: string): Promise<string> {- const unquoted = unquotedFrontmatter(unquoteTranscriptText(content, slug), slug);+ const unquoted = unquotedFrontmatter(content, unquoteTranscriptText(content, slug), slug);const summarized = /, arguments omitted\]/.test(unquoted);const quotedType = isQuotedPageType(String(parseMarkdownHead(unquoted).frontmatter.type ?? ''));if (!summarized && (unquoted === content || quotedType)) return unquoted;diff --git a/src/core/search/transcript-quote.ts b/src/core/search/transcript-quote.tsindex e2d7625a66..91a968c8f6 100644--- a/src/core/search/transcript-quote.ts+++ b/src/core/search/transcript-quote.ts@@ -477,7 +477,9 @@ export function neutralizeToolCalls(text: string, header = false): string {export function fenceTranscriptText(text: string, slug: string, header = false): string {const head = headerLine(text, header);const body = text.slice(head.length);- const { open, close } = transcriptFence(slug, Math.max(0, ...(body.match(/`+/g) ?? []).map(run => run.length)));+ let longest = 0;+ for (const run of body.matchAll(/`+/g)) longest = Math.max(longest, run[0].length);+ const { open, close } = transcriptFence(slug, longest);return `${head}${open}${body}${close}`;}diff --git a/test/search-transcript-quote-followups.test.ts b/test/search-transcript-quote-followups.test.tsindex b98fc7a1de..d268682372 100644--- a/test/search-transcript-quote-followups.test.ts+++ b/test/search-transcript-quote-followups.test.ts@@ -256,6 +256,42 @@ for (const backend of testBackends()) {expect((await engine.getPage(CHAT_SLUG))!.compiled_truth).toContain('[tool call: lookup, arguments omitted] there.');expect((await engine.getPage(CHAT_SLUG))!.compiled_truth).toContain('"name":"put_page"');}, 120_000);++ test('item 3: a whole-markdown round trip keeps a frontmatter value that quotes the page itself', async () => {+ const slug = 'notes/quote-example';+ const example = fenceTranscriptText('a quoted sample', slug);+ await engine.putPage(slug, { type: 'note', title: 'Quote example', compiled_truth: 'Body.', timeline: '', frontmatter: { example } });+ const read = await ok('get_page', { slug, include_content: true, content_only: true });+ expect(read.content).toContain(MARKER);+ await ok('put_page', { slug, content: read.content, expected_revision: read.revision });+ expect((await engine.getPage(slug))!.frontmatter.example).toBe(example);+ }, 120_000);++ test('item 3: a fenced title pasted into hand-written frontmatter is stored unfenced, every other value unchanged', async () => {+ const head = (title: string) => `---\ntype: note\ntitle: ${title}\nwhen: 2024-06-01\ncode: 0123\n---\n\nPasted body.\n`;+ for (const slug of ['notes/pasted-plain', 'notes/pasted-fenced']) await ok('put_page', { slug, content: head('Pasted') });+ const fenced = fenceTranscriptText('Pasted', 'notes/pasted-fenced').split('\n').map(l => ` ${l}`).join('\n');+ const { revision } = await ok('get_page', { slug: 'notes/pasted-fenced' });+ await ok('put_page', { slug: 'notes/pasted-fenced', expected_revision: revision, content: head(`|-\n${fenced}`) });+ const [plain, unfenced] = [await engine.getPage('notes/pasted-plain'), await engine.getPage('notes/pasted-fenced')];+ expect([unfenced!.title, unfenced!.frontmatter, unfenced!.compiled_truth]).toEqual([plain!.title, plain!.frontmatter, plain!.compiled_truth]);+ }, 120_000);++ test('item 8: add_timeline_entry unquotes by the page slug however the caller cased it', async () => {+ const text = `Cased entry ${CODE.timeline}-cased`;+ await ok('add_timeline_entry', { slug: AGENT_SLUG.toUpperCase(), date: '2026-10-03', summary: fenceTranscriptText(text, AGENT_SLUG) });+ expect(await engine.executeRaw<{ summary: string }>('SELECT summary FROM timeline_entries WHERE summary LIKE $1', ['%-cased%'])).toEqual([{ summary: text }]);+ }, 120_000);++ test('item 2: a claim and source copied out of a quoted takes read are written unfenced', async () => {+ const take = (await ok('takes_list', { page_slug: AGENT_SLUG }) as Array<{ claim: string; source: string; row_num: number }>).find(t => t.claim.includes(CODE.take))!;+ expect([take.claim, take.source]).toEqual([expect.stringContaining(MARKER), expect.stringContaining(MARKER)]);+ const rows = () => engine.executeRaw<{ claim: string; source: string | null }>('SELECT t.claim, t.source FROM takes t JOIN pages p ON p.id = t.page_id WHERE p.slug = $1 ORDER BY t.row_num', [AGENT_SLUG]);+ await ok('takes_update', { slug: AGENT_SLUG, row_num: take.row_num, source: take.source });+ expect((await rows())[0]!.source).toBe(`Probe source ${CODE.takeSource}`);+ await ok('takes_supersede', { slug: AGENT_SLUG, row_num: take.row_num, claim: take.claim });+ expect((await rows()).map(r => r.claim)).toEqual([`Probe claim ${CODE.take}`, `Probe claim ${CODE.take}`]);+ }, 120_000);});}@@ -278,4 +314,13 @@ describe('item 6: the thin client\'s paged read of a quoted page prints it insidexpect(JSON.parse(json).content).toBe(fenceTranscriptText(total, slug));expect((await readWholePageMarkdown(host, { slug })).markdown).toBe(total);});++ test('a read through an alias prints the fence naming the page the host returned', async () => {+ let out = '';+ await printPagedPage(host, { slug: 'notes/old-name-alias' }, async text => { out += text; });+ expect(out).toBe(fenceTranscriptText(total, slug));+ });+ test('a text with a million backtick runs is fenced without overflowing the stack', () => {+ expect(fenceTranscriptText('`x'.repeat(1_000_000), slug).endsWith('\n```')).toBe(true);+ });});