Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(hooks): stop surfacing another session's text at session start (#5558)
garrytan4ede8936058c
diff --git a/src/commands/hook.ts b/src/commands/hook.tsindex 0322e08634..c16ac329f8 100644--- a/src/commands/hook.ts+++ b/src/commands/hook.ts@@ -34,7 +34,6 @@*/import {- appendFileSync,chmodSync,existsSync,mkdirSync,@@ -226,16 +225,18 @@ export interface HookIo {// ── Entry point ─────────────────────────────────────────────────────────────+export const HOOK_EVENTS = ['session-start', 'user-prompt', 'stop', 'session-end', 'compact'] as const;+const USAGE = `Usage: gbrain hook <event>Events (wired into .claude/settings.local.json by gbrain bootstrap):- session-start print the greeting digest (MEMORY.md sections, last session,- push status, hook health) to stdout+ session-start print the greeting digest (MEMORY.md sections, push status,+ hook health) to stdoutuser-prompt read hook JSON on stdin, request per-turn context from arunning 'gbrain serve' over IPC, print additionalContext JSON(--harness <claude-code|codex|opencode> sets the feedback-loopchannel; default claude-code, unknown values fall back to the default)- stop append to the per-session live buffer+ stop bank the writeback backstop and spawn the workspace pushsession-end ingest the session transcript into the dream corpus(secret-scanned), prune old corpus files, push the workspacecompact (PreCompact) bank the window's standing entities into the@@ -261,7 +262,7 @@ export async function runHook(args: string[], io: HookIo = {}): Promise<number>const v = args[harnessIdx + 1];if (v === 'claude-code' || v === 'codex' || v === 'opencode') io = { ...io, harness: v };}- if (!event || !['session-start', 'user-prompt', 'stop', 'session-end', 'compact'].includes(event)) {+ if (!event || !(HOOK_EVENTS as readonly string[]).includes(event)) {process.stderr.write(USAGE + '\n');return 1;}@@ -423,7 +424,7 @@ function ensureDir0700(dir: string): string {return dir;}-function sanitizeSessionId(id: unknown): string {+export function sanitizeSessionId(id: unknown): string {// Leading dashes are stripped so the id can never be parsed as a FLAG by a// downstream argv consumer (the detached memorable spawn passes it as a// positional value) — hook stdin is untrusted input.@@ -487,10 +488,6 @@ async function hookSessionStart(io: HookIo): Promise<number> {const digest = memoryDigest(join(ws, 'MEMORY.md'));if (digest) out.push(digest);- // 2. Last-session line from the stop-buffer dir [G15 consumer].- const last = await lastSessionLine();- if (last) out.push(last);-// 3. Push staleness [B4].const pushNote = await pushStatusNote();if (pushNote) out.push(pushNote);@@ -637,32 +634,6 @@ async function liveBufferDir(): Promise<string> {return ensureDir0700(join(home, 'transcripts', 'live'));}-async function lastSessionLine(): Promise<string | null> {- try {- const dir = await liveBufferDir();- let newest: { path: string; mtime: number } | null = null;- for (const name of readdirSync(dir)) {- if (!name.endsWith('.txt')) continue;- const p = join(dir, name);- const st = statSync(p);- if (!newest || st.mtimeMs > newest.mtime) newest = { path: p, mtime: st.mtimeMs };- }- if (!newest) return null;- const lines = readFileSync(newest.path, 'utf8').split('\n').filter((l) => l.trim());- const last = lines[lines.length - 1];- if (!last) return null;- try {- const e = JSON.parse(last) as { ts?: string; exchange?: string };- const snippet = typeof e.exchange === 'string' ? ` — ${e.exchange.slice(0, 200)}` : '';- return `Last session activity: ${e.ts ?? 'unknown time'}${snippet}`;- } catch {- return `Last session activity: ${last.slice(0, 200)}`;- }- } catch {- return null;- }-}-async function pushStatusNote(): Promise<string | null> {try {// One reader + one aggregation for every status surface [D8]; per-root@@ -1444,16 +1415,9 @@ async function hookStop(io: HookIo): Promise<number> {let j: Record<string, unknown> | null = null;try {j = await readStdinJson(io, 300);- const sessionId = sanitizeSessionId(j?.session_id);- const dir = await liveBufferDir();- const exchange = firstString(j, ['last_assistant_message', 'lastAssistantMessage', 'prompt']);- const entry = {- ts: new Date().toISOString(),- session_id: sessionId,- ...(exchange ? { exchange: exchange.slice(0, 400) } : {}),- };- appendFileSync(join(dir, `${sessionId}.txt`), JSON.stringify(entry) + '\n', { mode: 0o600 });- gcOldFiles(dir, STOP_BUFFER_RETENTION_MS);+ // #5558: stop no longer buffers assistant text; GC drains any buffers+ // older binaries left behind.+ gcOldFiles(await liveBufferDir(), STOP_BUFFER_RETENTION_MS);} catch (e) {outcome = 'error';reason = errorCode(e);@@ -1594,15 +1558,6 @@ async function hookStop(io: HookIo): Promise<number> {return 0;}-function firstString(j: Record<string, unknown> | null, keys: string[]): string | null {- if (!j) return null;- for (const k of keys) {- const v = j[k];- if (typeof v === 'string' && v.trim()) return v;- }- return null;-}-function gcOldFiles(dir: string, maxAgeMs: number): void {try {const cutoff = Date.now() - maxAgeMs;diff --git a/test/context-engine-checkpoint.serial.test.ts b/test/context-engine-checkpoint.serial.test.tsindex 83ee215f40..2f9b12bec6 100644--- a/test/context-engine-checkpoint.serial.test.ts+++ b/test/context-engine-checkpoint.serial.test.ts@@ -340,67 +340,35 @@ describe('checkpoint compaction (cathedral 5)', () => {});it('F5/CK9 drift guard: hook.ts sanitizeSessionId, corpus-segments safeIdComponent, and sanitizeEngineSessionId map an identical probe set to IDENTICAL keys', async () => {- const { runHook } = await import('../src/commands/hook.ts');+ const { sanitizeSessionId } = await import('../src/commands/hook.ts');const { segmentFileName, parseSegmentFileName } = await import('../src/core/context/corpus-segments.ts');- // hook.ts's copy is module-private; its stop lane names the live-buffer- // file `${sanitizeSessionId(id)}.txt` — the filename IS the mapping seam- // (same seam test/hook-command.serial.test.ts already pins for one id).- const savedEnv: Record<string, string | undefined> = {};- for (const k of ['GBRAIN_HOOKS', 'GBRAIN_HOOK_LANE', 'GBRAIN_STOP_PUSH']) savedEnv[k] = process.env[k];- delete process.env.GBRAIN_HOOKS;- delete process.env.GBRAIN_HOOK_LANE;- process.env.GBRAIN_STOP_PUSH = '0'; // stop-push arm skips instantly- const ws = mkdtempSync(join(tmpdir(), 'gb-ckpt-drift-ws-'));- try {- let probeN = 0;- const hookKey = async (probe: unknown): Promise<string> => {- const marker = `drift-probe-${++probeN}-marker`;- const code = await runHook(['stop'], {- stdin: JSON.stringify({ session_id: probe, last_assistant_message: marker }),- cwd: ws, // non-bootstrap workspace: no push machinery runs- spawnPush: () => { /* never spawns */ },- disableTelemetry: true,- });- expect(code).toBe(0);- const liveDir = join(home!, '.gbrain', 'transcripts', 'live');- const hit = readdirSync(liveDir).filter(- (f) => f.endsWith('.txt') && readFileSync(join(liveDir, f), 'utf8').includes(marker),- );- expect(hit).toHaveLength(1);- return hit[0].slice(0, -'.txt'.length);- };- // Third copy (corpus-segments safeIdComponent) read back through its- // exported filename builder + parser.- const segKey = (probe: string): string => {- const parsed = parseSegmentFileName(segmentFileName(probe, 'a'.repeat(24)));- expect(parsed).not.toBeNull();- return parsed!.sessionId;- };-- const probes = ['oc:sess/2026-08', 'a b', '../x', 'UPPER', 'L'.repeat(300)];- for (const probe of probes) {- const engineKey = sanitizeEngineSessionId(probe);- expect(engineKey).not.toBeNull(); // every probe keeps a safe residue- expect(await hookKey(probe)).toBe(engineKey!);- expect(segKey(probe)).toBe(engineKey!);- }-- // Deliberate divergence, pinned so it can only change LOUDLY: degenerate- // ids map to hook.ts's 'unknown' sentinel but to engine null — compact()- // treats a shared-'unknown' bucket as ABSENT (cross-session pollution),- // per the hook.ts compact lane's own sentinel check.- expect(sanitizeEngineSessionId('...')).toBeNull();- expect(await hookKey('...')).toBe('unknown');- expect(sanitizeEngineSessionId(1234)).toBeNull();- expect(await hookKey(1234)).toBe('unknown');- } finally {- rmSync(ws, { recursive: true, force: true });- for (const [k, v] of Object.entries(savedEnv)) {- if (v === undefined) delete process.env[k];- else process.env[k] = v;- }+ // hook.ts's copy is exported for this guard (#5558 removed the stop-lane+ // live-buffer file that used to expose the mapping).+ // Third copy (corpus-segments safeIdComponent) read back through its+ // exported filename builder + parser.+ const segKey = (probe: string): string => {+ const parsed = parseSegmentFileName(segmentFileName(probe, 'a'.repeat(24)));+ expect(parsed).not.toBeNull();+ return parsed!.sessionId;+ };++ const probes = ['oc:sess/2026-08', 'a b', '../x', 'UPPER', 'L'.repeat(300)];+ for (const probe of probes) {+ const engineKey = sanitizeEngineSessionId(probe);+ expect(engineKey).not.toBeNull(); // every probe keeps a safe residue+ expect(sanitizeSessionId(probe)).toBe(engineKey!);+ expect(segKey(probe)).toBe(engineKey!);}++ // Deliberate divergence, pinned so it can only change LOUDLY: degenerate+ // ids map to hook.ts's 'unknown' sentinel but to engine null — compact()+ // treats a shared-'unknown' bucket as ABSENT (cross-session pollution),+ // per the hook.ts compact lane's own sentinel check.+ expect(sanitizeEngineSessionId('...')).toBeNull();+ expect(sanitizeSessionId('...')).toBe('unknown');+ expect(sanitizeEngineSessionId(1234)).toBeNull();+ expect(sanitizeSessionId(1234)).toBe('unknown');});});diff --git a/test/fixtures/goldens/cli/engine-free-db-down.json b/test/fixtures/goldens/cli/engine-free-db-down.jsonindex b0fa02da90..b5e9c0dc05 100644--- a/test/fixtures/goldens/cli/engine-free-db-down.json+++ b/test/fixtures/goldens/cli/engine-free-db-down.json@@ -273,13 +273,13 @@"Usage: gbrain hook <event>","","Events (wired into .claude/settings.local.json by gbrain bootstrap):",- " session-start print the greeting digest (MEMORY.md sections, last session,",- " push status, hook health) to stdout",+ " session-start print the greeting digest (MEMORY.md sections, push status,",+ " hook health) to stdout"," user-prompt read hook JSON on stdin, request per-turn context from a"," running 'gbrain serve' over IPC, print additionalContext JSON"," (--harness <claude-code|codex|opencode> sets the feedback-loop"," channel; default claude-code, unknown values fall back to the default)",- " stop append to the per-session live buffer",+ " stop bank the writeback backstop and spawn the workspace push"," session-end ingest the session transcript into the dream corpus"," (secret-scanned), prune old corpus files, push the workspace"," compact (PreCompact) bank the window's standing entities into the",diff --git a/test/hook-command.serial.test.ts b/test/hook-command.serial.test.tsindex 0ac989ce83..9b73768493 100644--- a/test/hook-command.serial.test.ts+++ b/test/hook-command.serial.test.ts@@ -24,6 +24,7 @@ import {DIGEST_MEMORY_CAP_BYTES,memoryDigest,PUSH_ANNOUNCE_REFIRE_MS,+ HOOK_EVENTS,type HookHeartbeatEntry,} from '../src/commands/hook.ts';import { pushStatusPathForRoot } from '../src/core/workspace-push.ts';@@ -599,7 +600,7 @@ describe('session-start', () => {expect(out.get()).not.toContain('run gbrain doctor');});- test('last-session line + stale push-status surfaced [B4]', async () => {+ test('stale push-status surfaced; no buffered session text at session start [B4, #5558]', async () => {const liveDir = join(home(), 'transcripts', 'live');mkdirSync(liveDir, { recursive: true });writeFileSync(join(liveDir, 'prev.txt'), JSON.stringify({ ts: '2026-08-07T09:00:00Z', session_id: 'prev', exchange: 'wrapped up the acme-example memo' }) + '\n');@@ -609,13 +610,31 @@ describe('session-start', () => {const ws = join(tmp, 'ws');mkdirSync(ws, { recursive: true });const out = collectStdout();- await runHook(['session-start'], { ...out.io, stdin: '', cwd: ws });+ await runHook(['session-start'], { ...out.io, stdin: JSON.stringify({ session_id: 'prev', cwd: ws }), cwd: ws });const text = out.get();- expect(text).toContain('Last session activity');- expect(text).toContain('acme-example memo');+ expect(text).not.toContain('Last session activity');+ expect(text).not.toContain('acme-example memo');expect(text).toContain('>48h ago');});+ test('#5558: no hook event surfaces another session\'s text (every event, every buffer shape)', async () => {+ const liveDir = join(home(), 'transcripts', 'live');+ mkdirSync(liveDir, { recursive: true });+ const secrets = ['private-json-exchange-marker', 'private-raw-line-marker', 'private-own-session-marker'];+ writeFileSync(join(liveDir, 'other-agent.txt'), JSON.stringify({ ts: '2026-09-30T09:00:00Z', session_id: 'other-agent', exchange: secrets[0] }) + '\n');+ writeFileSync(join(liveDir, 'unknown.txt'), secrets[1] + '\n');+ writeFileSync(join(liveDir, 'me.txt'), JSON.stringify({ ts: '2026-09-30T09:01:00Z', session_id: 'me', exchange: secrets[2] }) + '\n');+ const ws = join(tmp, 'ws');+ mkdirSync(ws, { recursive: true });+ for (const event of HOOK_EVENTS) {+ for (const stdin of ['', JSON.stringify({ session_id: 'me', cwd: ws, source: 'compact' })]) {+ const out = collectStdout();+ await runHook([event], { ...out.io, stdin, cwd: ws, spawnPush: () => {}, transcriptRoot: join(tmp, 'projects') });+ for (const secret of secrets) expect(out.get()).not.toContain(secret);+ }+ }+ });+test('parser-drift status file surfaced at session start [G3]', async () => {const statusPath = await hookStatusPath();writeFileSync(statusPath, JSON.stringify({ ts: new Date().toISOString(), error: 'parser_drift', bytes: 1234 }));@@ -630,7 +649,7 @@ describe('session-start', () => {// ── stop [G15] ──────────────────────────────────────────────────────────────describe('stop', () => {- test('appends to the per-session buffer (sanitized id) and GCs stale buffers', async () => {+ test('writes no session buffer and GCs stale buffers left by older binaries [#5558]', async () => {const liveDir = join(home(), 'transcripts', 'live');mkdirSync(liveDir, { recursive: true });const stale = join(liveDir, 'stale.txt');@@ -638,16 +657,14 @@ describe('stop', () => {const old = (Date.now() - 8 * 24 * 3600 * 1000) / 1000;utimesSync(stale, old, old);- expect(- await runHook(['stop'], {- stdin: JSON.stringify({ session_id: 'abc/../def', last_assistant_message: 'the widget-co answer' }),- }),- ).toBe(0);- const files = readdirSync(liveDir);- expect(files).toContain('abc-..-def.txt'); // '/' sanitized, no traversal possible- expect(files).not.toContain('stale.txt');- const body = readFileSync(join(liveDir, 'abc-..-def.txt'), 'utf8');- expect(body).toContain('the widget-co answer');+ for (const session_id of ['abc/../def', undefined]) {+ expect(+ await runHook(['stop'], {+ stdin: JSON.stringify({ session_id, last_assistant_message: 'the widget-co answer' }),+ }),+ ).toBe(0);+ }+ expect(readdirSync(liveDir)).toEqual([]);expect((await lastHeartbeat())?.outcome).toBe('ok');});});@@ -1210,9 +1227,8 @@ describe('stop-hook per-turn push [D3]', () => {await runHook(['stop'], stopIo(repo, spawned));expect(spawned).toEqual([]);expect((await lastHeartbeat())?.reason).toBe('push_clean');- // the live-buffer append still happened (stop's original contract)- const bufDir = join(home(), 'transcripts', 'live');- expect(readdirSync(bufDir).some((n) => n.includes('sess-stop-push'))).toBe(true);+ // #5558: stop no longer writes a live buffer+ expect(existsSync(join(home(), 'transcripts', 'live', 'sess-stop-push.txt'))).toBe(false);});test('corrupt per-root state file is treated as due (fail-open)', async () => {