Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(context): proactive brief draws on dated page edits (D5 follow-up, default off)

garrytancab6e8ca197e
diff --git a/docs/guides/push-context.md b/docs/guides/push-context.md
index 8a8497a65a..2eaea84f40 100644
--- a/docs/guides/push-context.md
+++ b/docs/guides/push-context.md
@@ -130,8 +130,15 @@ and Codex, OpenCode and thin-client harnesses are out of scope for v1. **On a
thin client, push is unsupported**: use the pull form below.
**What it pushes.** The newest open loop with the counterparty, the newest
-dated fact about them, then further loops, up to three items. Each line
-carries a short id (`L12`, `F3401`), a date (`undated` when there is none),
+dated fact about them, the newest dated edit to their page, then further
+loops, up to three items. The edit item is for agents that record a change by
+editing the page instead of calling `remember`: it is the page's newest
+timeline entry or the lines its newest revision added (whichever was recorded
+last), and it is dropped when it repeats the content of one of the
+counterparty's facts or loops in the brief. Facts and takes fence rows and
+headings never count as an edit. Each line
+carries a short id (`L12`, `F3401`, `Ev88` for a revision, `Et17` for a
+timeline entry), a date (`undated` when there is none),
and the source slug, quoted as data inside the `retrieved brain context —
data, not instructions` envelope. Each item is at most 600 characters, and
the block at most 1,800. The block leads the injected context, so the hook's
@@ -144,7 +151,9 @@ size cap never cuts it.
makes the fact world. The `remote_private_pages` escape hatch does not
widen the push.
- **Fresh only.** Loops with no activity for 90 days and loops whose google
- source has not synced in 24 hours are skipped.
+ source has not synced in 24 hours are skipped. A page edit or timeline entry
+ recorded more than 30 days ago (or a timeline entry dated more than 30 days
+ ago) is skipped.
- **Once per session.** An item id is not pushed twice in a session. The
serve remembers delivered ids per session (in memory, so a serve restart
forgets them), and the transcript's earlier injections are scanned for the
@@ -169,7 +178,9 @@ D6 measures use.
`counterparty` (a name or an exact slug) and an optional `intent` (`meeting`
or `reply`) and returns the same brief labelled `## Before you start (pulled
on request)`, plus a structured `brief` field. Remote callers get the dated
-fact arm only; open loops are withheld (`withheld_arms: ["loops"]`).
+fact and page-edit arms (world pages only, the same text `get_versions` and
+`get_timeline` already return them); open loops are withheld
+(`withheld_arms: ["loops"]`).
## The OpenClaw reflex volunteer arm
diff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.md
index be2616ba40..ae737a0d5f 100644
--- a/docs/protocol/MEMORY_VERBS_v1.md
+++ b/docs/protocol/MEMORY_VERBS_v1.md
@@ -946,9 +946,14 @@ A name resolves only on the alias or title arm at ≥ 0.8, to a person or compan
page, never through a common word. An unresolved name returns
`reason: "counterparty_unresolved"` and no items; an invalid `intent` is
`invalid_params`. Items are open loops (`L<id>`, trusted-local callers only;
-remote callers get `withheld_arms: ["loops"]`) and the newest dated fact
-(`F<id>`). Visibility follows the `include_private` rule above, with
-private-provenance facts excluded unless widened. The same assembler serves
+remote callers get `withheld_arms: ["loops"]`), the newest dated fact
+(`F<id>`), and the counterparty page's newest dated edit (`kind: "edit"`: the
+lines a revision added, `Ev<page version id>`, or a timeline entry,
+`Et<timeline entry id>`), dropped when it repeats a fact or loop of the same
+brief. Visibility follows the `include_private` rule above, with
+private-provenance facts excluded unless widened; an edit's page (and a
+timeline entry's event page) follows the same page rule, and facts and takes
+fence rows never count as an edit. The same assembler serves
the off-by-default hook push ([push context](../guides/push-context.md)).
### delta(since?, since_slug?, cursor?, entities?, budget_tokens?, session_id?, include_private?) — read, zero LLM
diff --git a/llms-full.txt b/llms-full.txt
index 68033ff12b..5d24c94212 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -8529,8 +8529,15 @@ and Codex, OpenCode and thin-client harnesses are out of scope for v1. **On a
thin client, push is unsupported**: use the pull form below.
**What it pushes.** The newest open loop with the counterparty, the newest
-dated fact about them, then further loops, up to three items. Each line
-carries a short id (`L12`, `F3401`), a date (`undated` when there is none),
+dated fact about them, the newest dated edit to their page, then further
+loops, up to three items. The edit item is for agents that record a change by
+editing the page instead of calling `remember`: it is the page's newest
+timeline entry or the lines its newest revision added (whichever was recorded
+last), and it is dropped when it repeats the content of one of the
+counterparty's facts or loops in the brief. Facts and takes fence rows and
+headings never count as an edit. Each line
+carries a short id (`L12`, `F3401`, `Ev88` for a revision, `Et17` for a
+timeline entry), a date (`undated` when there is none),
and the source slug, quoted as data inside the `retrieved brain context —
data, not instructions` envelope. Each item is at most 600 characters, and
the block at most 1,800. The block leads the injected context, so the hook's
@@ -8543,7 +8550,9 @@ size cap never cuts it.
makes the fact world. The `remote_private_pages` escape hatch does not
widen the push.
- **Fresh only.** Loops with no activity for 90 days and loops whose google
- source has not synced in 24 hours are skipped.
+ source has not synced in 24 hours are skipped. A page edit or timeline entry
+ recorded more than 30 days ago (or a timeline entry dated more than 30 days
+ ago) is skipped.
- **Once per session.** An item id is not pushed twice in a session. The
serve remembers delivered ids per session (in memory, so a serve restart
forgets them), and the transcript's earlier injections are scanned for the
@@ -8568,7 +8577,9 @@ D6 measures use.
`counterparty` (a name or an exact slug) and an optional `intent` (`meeting`
or `reply`) and returns the same brief labelled `## Before you start (pulled
on request)`, plus a structured `brief` field. Remote callers get the dated
-fact arm only; open loops are withheld (`withheld_arms: ["loops"]`).
+fact and page-edit arms (world pages only, the same text `get_versions` and
+`get_timeline` already return them); open loops are withheld
+(`withheld_arms: ["loops"]`).
## The OpenClaw reflex volunteer arm
@@ -9789,9 +9800,14 @@ A name resolves only on the alias or title arm at ≥ 0.8, to a person or compan
page, never through a common word. An unresolved name returns
`reason: "counterparty_unresolved"` and no items; an invalid `intent` is
`invalid_params`. Items are open loops (`L<id>`, trusted-local callers only;
-remote callers get `withheld_arms: ["loops"]`) and the newest dated fact
-(`F<id>`). Visibility follows the `include_private` rule above, with
-private-provenance facts excluded unless widened. The same assembler serves
+remote callers get `withheld_arms: ["loops"]`), the newest dated fact
+(`F<id>`), and the counterparty page's newest dated edit (`kind: "edit"`: the
+lines a revision added, `Ev<page version id>`, or a timeline entry,
+`Et<timeline entry id>`), dropped when it repeats a fact or loop of the same
+brief. Visibility follows the `include_private` rule above, with
+private-provenance facts excluded unless widened; an edit's page (and a
+timeline entry's event page) follows the same page rule, and facts and takes
+fence rows never count as an edit. The same assembler serves
the off-by-default hook push ([push context](../guides/push-context.md)).
### delta(since?, since_slug?, cursor?, entities?, budget_tokens?, session_id?, include_private?) — read, zero LLM
diff --git a/src/core/context/proactive-brief.ts b/src/core/context/proactive-brief.ts
index 726802f588..94364c5500 100644
--- a/src/core/context/proactive-brief.ts
+++ b/src/core/context/proactive-brief.ts
@@ -19,11 +19,15 @@ import { isConfigTruthy } from '../config.ts';
import { HALFLIFE_DAYS } from '../facts/decay.ts';
import { listOpenLoops, type OpenLoopRow } from '../loops/loops-store.ts';
import { normalizeAlias } from '../search/alias-normalize.ts';
-import { privatePagesFilterFragment, privateProvenanceFilterFragment } from '../search/private-visibility.ts';
+import { privatePagesFilterFragment, privateProvenanceFilterFragment, privateTimelineEventFilterFragment } from '../search/private-visibility.ts';
import { pageEligibleSql, projectionEligibleSql } from '../eligibility/sql.ts';
import type { ReadEligibility } from '../eligibility/policy.ts';
import { renderTrustedInline, trustFields } from '../eligibility/labels.ts';
import { redactFindings } from '../secret-scan.ts';
+import { FACTS_FENCE_BEGIN, FACTS_FENCE_END } from '../facts-fence.ts';
+import { TAKES_FENCE_BEGIN, TAKES_FENCE_END } from '../takes-fence.ts';
+import { protectedRegions } from '../fence-scan.ts';
+import { stripMaterializedMarkers } from '../timeline-marker.ts';
import { MIN_ALIAS_LENGTH, isCommonAliasWord } from '../mentions/aliases.ts';
import { extractCandidatesFromWindow, isCommonCapitalizedWord, isStopword } from './entity-salience.ts';
import { resolveEntitiesToPointers, type ReflexPointer } from './retrieval-reflex.ts';
@@ -39,6 +43,8 @@ export const BRIEF_CALENDAR_WINDOW_HOURS = 12;
export const BRIEF_MIN_CONFIDENCE = 0.8;
export const BRIEF_MAX_COUNTERPARTIES = 2;
export const BRIEF_SOURCE_STALE_MS = 24 * 60 * 60 * 1000;
+/** A page edit or timeline entry older than this (recorded, or dated) is not a recent change. */
+export const BRIEF_EDIT_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
export const BRIEF_HEADER = '## Before you start';
export const BRIEF_PULL_HEADER = '## Before you start (pulled on request)';
/** Brief work stops this long into a turn_context request (of its 400ms server budget; the legacy block runs first). */
@@ -52,10 +58,15 @@ const ENTITY_PREFIXES = ['people/', 'companies/'];
const DAY_MS = 24 * 60 * 60 * 1000;
const ENABLED_TTL_MS = 5_000;
const ENABLED_READ_TIMEOUT_MS = 50;
+/** The edit arm diffs entity-sized pages only: a revision over this many bytes ends the walk. */
+const EDIT_MAX_PAGE_BYTES = 64 * 1024;
+const EDIT_MAX_VERSIONS = 4;
+/** An edit whose words are this much contained in a fact or loop of the same brief repeats it. */
+const SAME_CONTENT_RATIO = 0.8;
/** How the brief was triggered; `brief-<trigger>` is its telemetry match_arm. */
export type BriefTrigger = 'calendar' | 'lexicon' | 'session' | 'pull';
-export type BriefItemKind = 'loop' | 'change';
+export type BriefItemKind = 'loop' | 'change' | 'edit';
export type BriefIntent = 'meeting' | 'reply';
export const BRIEF_INTENTS: readonly BriefIntent[] = ['meeting', 'reply'];
@@ -67,7 +78,7 @@ export interface BriefCounterparty {
}
export interface BriefItem {
- /** Short id: L<loop id> or F<fact id>. */
+ /** Short id: L<loop id>, F<fact id>, Ev<page version id> (a page edit) or Et<timeline entry id>. */
id: string;
kind: BriefItemKind;
/** YYYY-MM-DD, or null when the item has no date (rendered `undated`). */
@@ -453,6 +464,104 @@ async function changeItem(engine: BrainEngine, cp: BriefCounterparty, skipFactId
};
}
+/**
+ * The counterparty page's newest dated change, for brains that record a
+ * change by editing the page instead of saving a fact: its newest timeline
+ * entry or its newest revision, whichever was recorded last (a tie goes to
+ * the timeline entry). A revision renders the narrative lines it added that
+ * the page still has; facts and takes fences are dropped from both sides
+ * whole (their rows reach the brief only through the fact arm), as are
+ * headings. The page passes the same world-only and eligibility filters as
+ * the other arms (a timeline entry's event page too); the walk reads at most
+ * EDIT_MAX_VERSIONS revisions of an entity-sized page and skips anything
+ * recorded or dated more than BRIEF_EDIT_MAX_AGE_MS ago.
+ */
+async function editItem(engine: BrainEngine, cp: BriefCounterparty, clock: BriefClock, opts: ArmOpts): Promise<BriefItem | null> {
+ const [pg] = await engine.executeRaw<{ id: number; compiled_truth: string | null; timeline: string | null; trust_tier: unknown; write_origin: unknown }>(
+ `SELECT p.id, CASE WHEN octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) <= $3 THEN p.compiled_truth END AS compiled_truth,
+ p.timeline, p.trust_tier, p.write_origin
+ FROM pages p
+ WHERE p.source_id = $1 AND p.slug = $2 AND p.deleted_at IS NULL
+ AND ${opts.includePrivate ? 'TRUE' : privatePagesFilterFragment('p')}
+ AND ${pageEligibleSql('p', opts.eligibility)}`,
+ [cp.source_id, cp.slug, EDIT_MAX_PAGE_BYTES],
+ );
+ if (!pg || !live(clock)) return null;
+ const since = new Date(clock.now - BRIEF_EDIT_MAX_AGE_MS).toISOString();
+ const [entries, versions] = await Promise.all([
+ engine.executeRaw<{ id: number; date: string; summary: string; detail: string; created_at: string | Date }>(
+ `SELECT te.id, te.date::text AS date, te.summary, te.detail, te.created_at FROM timeline_entries te
+ WHERE te.page_id = $1 AND te.created_at >= $2::timestamptz AND te.date >= $2::timestamptz::date
+ AND ${opts.includePrivate ? 'TRUE' : privateTimelineEventFilterFragment('te')}
+ AND ${projectionEligibleSql('timeline_entries', 'te', opts.eligibility)}
+ ORDER BY te.created_at DESC, te.date DESC, te.id DESC LIMIT 1`,
+ [pg.id, since],
+ ),
+ pg.compiled_truth === null ? Promise.resolve([]) : engine.executeRaw<{ id: number; compiled_truth: string | null; timeline: string | null; snapshot_at: string | Date; is_deleted: boolean }>(
+ `SELECT v.id, CASE WHEN octet_length(v.compiled_truth) + octet_length(COALESCE(v.timeline, '')) <= $3 THEN v.compiled_truth END AS compiled_truth,
+ v.timeline, v.snapshot_at, v.is_deleted
+ FROM page_versions v WHERE v.page_id = $1 AND v.snapshot_at >= $2::timestamptz
+ ORDER BY v.id DESC LIMIT ${EDIT_MAX_VERSIONS}`,
+ [pg.id, since, EDIT_MAX_PAGE_BYTES],
+ ),
+ ]);
+ const current = pg.compiled_truth === null ? [] : narrativeLines(pg.compiled_truth, pg.timeline);
+ const still = new Set(current);
+ let revision: { id: string; at: number; added: string[] } | null = null;
+ let newer = current;
+ for (const v of versions) {
+ if (v.compiled_truth === null || v.is_deleted) break;
+ const older = narrativeLines(v.compiled_truth, v.timeline);
+ const pool = new Map<string, number>();
+ for (const l of older) pool.set(l, (pool.get(l) ?? 0) + 1);
+ const added = newer.filter((l) => {
+ const n = pool.get(l) ?? 0;
+ if (n > 0) { pool.set(l, n - 1); return false; }
+ return still.has(l);
+ });
+ if (added.length) { revision = { id: `Ev${Number(v.id)}`, at: new Date(v.snapshot_at).getTime(), added }; break; }
+ newer = older;
+ }
+ const entry = entries[0];
+ const entryAt = entry ? new Date(entry.created_at).getTime() : Number.NEGATIVE_INFINITY;
+ const base = { kind: 'edit' as const, slug: cp.slug, source_id: cp.source_id, counterparty: cp.slug, confidence: cp.confidence };
+ if (entry && (!revision || entryAt >= revision.at)) {
+ const body = entry.detail ? `${entry.summary} — ${entry.detail}` : entry.summary;
+ return { ...base, id: `Et${Number(entry.id)}`, date: ymd(entry.date), text: `timeline: ${renderStored(body, pg.trust_tier, pg.write_origin)}` };
+ }
+ if (!revision) return null;
+ return { ...base, id: revision.id, date: ymd(new Date(revision.at)), text: `edit: ${renderStored(revision.added.join(' '), pg.trust_tier, pg.write_origin)}` };
+}
+
+const FENCE_PAIRS = [{ begin: FACTS_FENCE_BEGIN, end: FACTS_FENCE_END }, { begin: TAKES_FENCE_BEGIN, end: TAKES_FENCE_END }] as const;
+
+/** A page's narrative lines: protected fences (and an unterminated tail) dropped whole, materialized markers and headings dropped, trimmed, non-empty. */
+function narrativeLines(compiled: string, timeline: string | null): string[] {
+ return [compiled, timeline ?? ''].flatMap((part) => {
+ const { regions, truncatedAt } = protectedRegions(part, FENCE_PAIRS);
+ let kept = '';
+ let cursor = 0;
+ for (const r of regions) { kept += part.slice(cursor, r.start); cursor = r.end; }
+ kept += truncatedAt === -1 ? part.slice(cursor) : part.slice(cursor, truncatedAt);
+ return stripMaterializedMarkers(kept).split('\n').map((l) => l.trim()).filter((l) => l && !/^#{1,6}\s/.test(l));
+ });
+}
+
+/** Two items carry the same content when the smaller one's words are SAME_CONTENT_RATIO contained in the other's (quoted body only). */
+function sameContent(a: BriefItem, b: BriefItem): boolean {
+ const words = (i: BriefItem) => {
+ const t = i.text.slice(i.text.indexOf('“') + 1, i.text.lastIndexOf('”'));
+ return new Set(t.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter((w) => w.length > 1 && !isStopword(w)));
+ };
+ const [x, y] = [words(a), words(b)];
+ const small = x.size <= y.size ? x : y;
+ const large = small === x ? y : x;
+ if (!small.size) return false;
+ let shared = 0;
+ for (const w of small) if (large.has(w)) shared++;
+ return shared / small.size >= SAME_CONTENT_RATIO;
+}
+
/**
* Stored text as data: secret-redacted BEFORE collapsing and clipping (so a
* cut can't split a credential past the scanner), one line, no comment or
@@ -487,8 +596,9 @@ export interface AssembleBriefOpts {
}
/**
- * Rank and cap: per counterparty the top loop, the newest change, then
- * further loops; at most BRIEF_MAX_ITEMS in total, each line <=
+ * Rank and cap: per counterparty the top loop, the newest change, the newest
+ * page edit (dropped when it repeats the content of one of the counterparty's
+ * facts or loops), then further loops; at most BRIEF_MAX_ITEMS in total, each line <=
* BRIEF_ITEM_MAX_CHARS, the block <= BRIEF_MAX_CHARS and BRIEF_MAX_BYTES.
* Stops issuing queries once the clock passes. Null when nothing survives.
*/
@@ -501,8 +611,10 @@ export async function assembleBrief(engine: BrainEngine, opts: AssembleBriefOpts
const loops = opts.local ? await loopItems(engine, cp, opts.clock, arm).catch(() => []) : [];
const loopFacts = new Set(loops.map((l) => l.factId).filter((n): n is number => n !== null));
const change = live(opts.clock) ? await changeItem(engine, cp, loopFacts, arm).catch(() => null) : null;
+ const found = await (live(opts.clock) ? editItem(engine, cp, opts.clock, arm).catch(() => null) : null);
+ const edit = found && ![change, ...loops].some((x) => x && sameContent(found, x)) ? found : null;
const fresh = loops.filter((l) => !seen(l.id)).map(({ factId, ...item }) => { void factId; return item; });
- for (const i of [fresh[0], change, ...fresh.slice(1)]) {
+ for (const i of [fresh[0], change, edit, ...fresh.slice(1)]) {
if (!i || seen(i.id) || items.some((x) => x.id === i.id)) continue;
if (items.length >= BRIEF_MAX_ITEMS) break;
items.push(i);
diff --git a/test/proactive-brief.test.ts b/test/proactive-brief.test.ts
index 4f7091c452..b83c4c3776 100644
--- a/test/proactive-brief.test.ts
+++ b/test/proactive-brief.test.ts
@@ -12,6 +12,7 @@ import { upsertOpenLoop } from '../src/core/loops/loops-store.ts';
import {
__resetBriefStateForTests,
BRIEF_CALENDAR_WINDOW_HOURS,
+ BRIEF_EDIT_MAX_AGE_MS,
BRIEF_HEADER,
BRIEF_INTENTS,
BRIEF_ITEM_MAX_CHARS,
@@ -38,6 +39,8 @@ import { operationsByName, type OperationContext } from '../src/core/operations.
import { BRIEF_INTENTS as OP_BRIEF_INTENTS } from '../src/core/ops/facts.ts';
import { dispatchToolCall } from '../src/mcp/dispatch.ts';
import { __resetHotMemoryCacheForTests } from '../src/core/facts/meta-hook.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { FACTS_FENCE_BEGIN, FACTS_FENCE_END } from '../src/core/facts-fence.ts';
import type { GBrainConfig } from '../src/core/config.ts';
let engine: PGLiteEngine;
@@ -97,6 +100,14 @@ async function loop(summary: string, opts: { factId?: number | null; dueAt?: str
return Number(id);
}
+/** Rewrite a page through the import write path: the preimage becomes a page_versions row, as an agent's put_page or edit_page leaves it. */
+async function rewrite(slug: string, title: string, body: string, opts: { type?: string; frontmatter?: Record<string, unknown>; timeline?: string } = {}) {
+ const fm = Object.entries({ type: opts.type ?? 'person', title, ...opts.frontmatter }).map(([k, v]) => `${k}: ${JSON.stringify(v)}`).join('\n');
+ const md = `---\n${fm}\n---\n\n# ${title}\n\n${body}\n${opts.timeline ? `\n## Timeline\n\n${opts.timeline}\n` : ''}`;
+ const r = await importFromContent(engine, slug, md, { noEmbed: true });
+ expect(r.status).toBe('imported');
+}
+
async function seedAlice() {
await page('people/alice-example', 'person', 'Alice Example');
await engine.setPageAliases('people/alice-example', 'default', [normalizeAlias('Alice Example'), normalizeAlias('[email protected]')]);
@@ -259,6 +270,139 @@ describe('items, ranking and limits', () => {
});
});
+describe('page edits (brains that record a change by editing pages)', () => {
+ const BEFORE = '- Next meeting: pricing review on Friday, October 16 (2026-10-16) at 13:30.';
+ const AFTER = '- Next meeting: pricing review on Tuesday, October 20 (2026-10-20) at 13:30 (moved from Friday, October 16).';
+
+ test('a brain whose only record of the change is a page edit gets a dated edit item', async () => {
+ await rewrite('people/alice-example', 'Alice Example', `Alice Example is DevOps Manager.\n\n## Current\n\n${BEFORE}`);
+ await rewrite('people/alice-example', 'Alice Example', `Alice Example is DevOps Manager.\n\n## Current\n\n${AFTER}`);
+ const [{ id }] = await engine.executeRaw<{ id: number }>(`SELECT max(id) AS id FROM page_versions`);
+ const brief = await prompt('Prep for my meeting with Alice Example');
+ expect(brief!.items.map((i) => [i.id, i.kind])).toEqual([[`Ev${id}`, 'edit']]);
+ expect(brief!.text).toContain(`- [Ev${id}] ${new Date().toISOString().slice(0, 10)} · edit: [unverified origin · legacy] “${AFTER}” → \`people/alice-example\``);
+ });
+
+ test('a change recorded only in the Timeline section, or as a timeline entry, gets an item', async () => {
+ await rewrite('people/alice-example', 'Alice Example', 'Alice Example is DevOps Manager.');
+ const line = '- **2026-10-14** | Call: pricing review moved to 2026-10-20';
+ await rewrite('people/alice-example', 'Alice Example', 'Alice Example is DevOps Manager.', { timeline: line });
+ const viaSection = await prompt('Draft a reply to Alice Example', 'te1');
+ expect(viaSection!.items).toHaveLength(1);
+ expect(viaSection!.items[0]!.text).toContain(line);
+ const day = new Date().toISOString().slice(0, 10);
+ expect(await engine.addTimelineEntry('people/alice-example', { date: day, source: 'test', summary: 'Pricing review moved to Tuesday', detail: 'same time' } as never, { sourceId: 'default' })).toBe(true);
+ const [{ id }] = await engine.executeRaw<{ id: number }>(`SELECT max(id) AS id FROM timeline_entries`);
+ const viaEntry = await prompt('Draft a reply to Alice Example', 'te2');
+ expect(viaEntry!.items.map((i) => i.id)).toEqual([`Et${id}`]);
+ expect(viaEntry!.text).toContain(`- [Et${id}] ${day} · timeline: [unverified origin · legacy] “Pricing review moved to Tuesday — same time” → \`people/alice-example\``);
+ });
+
+ test('an edit and a fact with the same content dedupe to the fact; different content keeps both', async () => {
+ await rewrite('people/alice-example', 'Alice Example', BEFORE);
+ await rewrite('people/alice-example', 'Alice Example', AFTER);
+ const same = await fact('Next meeting: pricing review moved to Tuesday, October 20 (2026-10-20) at 13:30, from Friday, October 16.', 'people/alice-example');
+ expect((await prompt('Prep for my meeting with Alice Example', 'd1'))!.items.map((i) => i.id)).toEqual([`F${same}`]);
+ await rewrite('people/alice-example', 'Alice Example', `${AFTER}\n- Champion for the security review.`);
+ const items = (await prompt('Prep for my meeting with Alice Example', 'd2'))!.items;
+ expect(items.map((i) => i.kind)).toEqual(['change', 'edit']);
+ expect(items[1]!.text).toContain('Champion for the security review.');
+ expect(items[1]!.text).not.toContain('October 20');
+ });
+
+ test('fence rows, headings and removed lines are not an edit; an edit is delivered once per session', async () => {
+ await rewrite('people/alice-example', 'Alice Example', 'Alice Example.\n- Old line.');
+ await rewrite('people/alice-example', 'Alice Example', `Alice Example.\n\n## Facts\n\n${FACTS_FENCE_BEGIN}\n| 1 | Some fact | fact | 1.0 | world |\n${FACTS_FENCE_END}`);
+ expect(await prompt('Draft a reply to Alice Example', 'f1')).toBeNull();
+ await rewrite('people/alice-example', 'Alice Example', `Alice Example.\n- New line.\n\n## Facts\n\n${FACTS_FENCE_BEGIN}\n| 1 | Some fact | fact | 1.0 | world |\n${FACTS_FENCE_END}`);
+ const brief = await prompt('Draft a reply to Alice Example', 'f2');
+ expect(brief!.items.map((i) => i.text)).toEqual(['edit: [unverified origin · legacy] “- New line.”']);
+ recordBriefDelivered('default', 'f2', brief!.items.map((i) => i.id));
+ expect(await prompt('Draft another reply to Alice Example', 'f2')).toBeNull();
+ });
+
+ test('edits recorded or dated past the window are skipped', async () => {
+ await rewrite('people/alice-example', 'Alice Example', BEFORE);
+ await rewrite('people/alice-example', 'Alice Example', AFTER);
+ await engine.executeRaw(`UPDATE page_versions SET snapshot_at = $1`, [new Date(Date.now() - BRIEF_EDIT_MAX_AGE_MS - DAY).toISOString()]);
+ expect(await prompt('Draft a reply to Alice Example', 'w1')).toBeNull();
+ const old = new Date(Date.now() - BRIEF_EDIT_MAX_AGE_MS - DAY).toISOString().slice(0, 10);
+ await engine.addTimelineEntry('people/alice-example', { date: old, source: 'test', summary: 'Long ago' } as never, { sourceId: 'default' });
+ expect(await prompt('Draft a reply to Alice Example', 'w2')).toBeNull();
+ });
+
+ test('a delivered edit logs its own rationale kind', async () => {
+ await rewrite('people/alice-example', 'Alice Example', BEFORE);
+ await rewrite('people/alice-example', 'Alice Example', AFTER);
+ const [{ id }] = await engine.executeRaw<{ id: number }>(`SELECT max(id) AS id FROM page_versions`);
+ const base = await turnContextWithBrief(engine, 'default', { kind: 'turn_context', protocol: 2, secret: 'x', sessionId: 'se', window: [{ role: 'user', text: 'Draft a reply to Alice Example' }] });
+ briefDelivered(engine, 'default', base, 'se');
+ await awaitPendingVolunteerEventWrites();
+ const rows = await engine.executeRaw<{ match_arm: string; rationale: string }>(`SELECT match_arm, rationale FROM context_volunteer_events WHERE channel = 'brief'`);
+ expect(rows).toEqual([{ match_arm: 'brief-lexicon', rationale: `edit:Ev${id}` }]);
+ });
+
+ test('the remote pull carries a world page edit (world-only, like the fact arm)', async () => {
+ await rewrite('people/alice-example', 'Alice Example', BEFORE);
+ await rewrite('people/alice-example', 'Alice Example', AFTER);
+ const res = await dispatchToolCall(engine as never, 'context_pack', { counterparty: 'Alice Example', intent: 'meeting' }, { remote: true, transport: 'stdio', sourceId: 'default' });
+ const body = JSON.parse((res.content[0] as { text: string }).text) as { brief: { items: Array<{ kind: string; text: string }> } };
+ expect(body.brief.items.map((i) => i.kind)).toEqual(['edit']);
+ expect(body.brief.items[0]!.text).toContain('Tuesday, October 20');
+ });
+
+ test('canary fuzz: an edit on a private page, in a fence, or on a private event never surfaces', async () => {
+ let seed = 0x5eed;
+ const rnd = () => { seed = (seed * 1103515245 + 12345) & 0x7fffffff; return seed; };
+ const canary = (n: number) => `EDITCANARY${n}x${rnd().toString(36)}`;
+ const canaries: string[] = [];
+ const shapes: Array<(c: string, n: number) => Promise<void>> = [
+ async (c, n) => { // explicitly private counterparty page
+ const slug = `people/secret-${n}`;
+ await rewrite(slug, `Secret ${n} Example`, 'Secret person.', { frontmatter: { visibility: 'private' } });
+ await engine.setPageAliases(slug, 'default', [normalizeAlias(`Secret ${n} Example`)]);
+ await rewrite(slug, `Secret ${n} Example`, `Secret person.\n- ${c} moved the call.`, { frontmatter: { visibility: 'private' }, timeline: `- **2026-10-14** | ${c} timeline` });
+ await engine.addTimelineEntry(slug, { date: new Date().toISOString().slice(0, 10), source: 'test', summary: `${c} entry` } as never, { sourceId: 'default' });
+ },
+ async (c) => { // a private fact row added inside the facts fence of the world page
+ const rows = `| 1 | ${c} salary | fact | 1.0 | private |`;
+ await rewrite('people/alice-example', 'Alice Example', `Alice Example.\n\n## Facts\n\n${FACTS_FENCE_BEGIN}\n${rows}\n${FACTS_FENCE_END}`);
+ },
+ async (c) => { // an unterminated fence tail
+ await rewrite('people/alice-example', 'Alice Example', `Alice Example.\n\n${FACTS_FENCE_BEGIN}\n| 2 | ${c} tail | fact | 1.0 | private |`);
+ },
+ async (c, n) => { // a world-looking page derived from a private one
+ await page(`notes/private-src-${n}`, 'note', 'Private source', { frontmatter: { visibility: 'private' } });
+ const slug = `people/derived-${n}`;
+ await rewrite(slug, `Derived ${n} Example`, 'Derived.', { frontmatter: { derived_from: `notes/private-src-${n}` } });
+ await engine.setPageAliases(slug, 'default', [normalizeAlias(`Derived ${n} Example`)]);
+ await rewrite(slug, `Derived ${n} Example`, `Derived.\n- ${c} derived edit.`, { frontmatter: { derived_from: `notes/private-src-${n}` } });
+ },
+ async (c, n) => { // a timeline entry projected from a private event page onto the world page
+ await page(`events/private-${n}`, 'event', 'Private event', { frontmatter: { visibility: 'private' } });
+ const [{ id: pid }] = await engine.executeRaw<{ id: number }>(`SELECT id FROM pages WHERE slug = 'people/alice-example'`);
+ const [{ id: eid }] = await engine.executeRaw<{ id: number }>(`SELECT id FROM pages WHERE slug = $1`, [`events/private-${n}`]);
+ await engine.executeRaw(`INSERT INTO timeline_entries (page_id, date, source, summary, event_page_id) VALUES ($1, CURRENT_DATE, 'test', $2, $3)`, [pid, `${c} private event`, eid]);
+ },
+ ];
+ for (let round = 0; round < 3; round++) {
+ for (const [n, shape] of shapes.entries()) {
+ const c = canary(round * 10 + n);
+ canaries.push(c);
+ await shape(c, round * 10 + n);
+ }
+ const texts: string[] = [];
+ for (const who of ['Alice Example', `Secret ${round * 10} Example`, `Derived ${round * 10 + 3} Example`]) {
+ texts.push((await prompt(`Prep for my meeting with ${who}`, `cz-${round}-${who}`))?.text ?? '');
+ texts.push(JSON.stringify(await operationsByName.context_pack!.handler(localCtx(), { counterparty: who })));
+ const res = await dispatchToolCall(engine as never, 'context_pack', { counterparty: who }, { remote: true, transport: 'stdio', sourceId: 'default' });
+ texts.push(res.content.map((x) => (x as { text?: string }).text ?? '').join('\n'));
+ }
+ for (const t of texts) for (const c of canaries) expect(t).not.toContain(c);
+ }
+ });
+});
+
describe('privacy: private material is never pushed', () => {
const CANARY = ['PRIVCANARY', 'Zq9'].join('');
@@ -389,6 +533,21 @@ describe('default off', () => {
}
});
+ test('with the key unset, a brain holding a page edit answers byte-identically to the legacy assembly', async () => {
+ await rewrite('people/alice-example', 'Alice Example', '- Next meeting: Friday, October 16.');
+ await rewrite('people/alice-example', 'Alice Example', '- Next meeting: Tuesday, October 20 (moved from Friday, October 16).');
+ await engine.unsetConfig(PROACTIVE_BRIEF_KEY);
+ __resetBriefStateForTests();
+ __resetHotMemoryCacheForTests();
+ const legacy = await assembleTurnContext(engine, { sourceId: 'default', window, sessionId: 'd3', lexicalArms: true });
+ __resetHotMemoryCacheForTests();
+ const served = await turnContextWithBrief(engine, 'default', { kind: 'turn_context', protocol: 2, secret: 'x', sessionId: 'd3', window });
+ expect(JSON.stringify(served)).toBe(JSON.stringify(legacy));
+ const pack = await makeContextPackIpcHandler(engine, 'default')({ kind: 'context_pack', protocol: 2, secret: 'x', sessionId: 'd3', trigger: 'session-start:startup' });
+ expect(pack?.brief).toBeUndefined();
+ expect(served.text).not.toContain(BRIEF_HEADER);
+ });
+
test('with the key unset, SessionStart and context_pack carry no brief', async () => {
await fact('Moved to Acme Example as CFO.', 'people/alice-example');
await meeting('calendar/2026/10/sync-a', 2 * HOUR, ['[email protected]']);