Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(hooks): record the capturing seat beside each session corpus (#4618)
garrytand9d97e8d4891
diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsvindex 4329af93bc..818c24d3ba 100644--- a/scripts/function-size-baseline.tsv+++ b/scripts/function-size-baseline.tsv@@ -31,7 +31,7 @@ src/core/bootstrap/harness.ts applyHarness 1167 seed: W5 baseline, refactor wavesrc/core/brainstorm/orchestrator.ts _runBrainstormInner 413 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 #5890 close-set spreads INTERNAL_BREADTH_SEARCH_OPTSsrc/core/check-resolvable.ts checkResolvable 419 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/config.ts loadConfigWithEngine 362 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 #5824: search.vector_legacy_guard DB-plane merge-src/core/context-engine.ts createGBrainContextEngine 519 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)+src/core/context-engine.ts createGBrainContextEngine 520 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 #4618: seat sidecar call before the segment spool (helper recordOpenclawSeat)src/core/context/retrieval-reflex.ts resolveEntitiesToPointers 355 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/cycle.ts runCycle 1237 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +5 #5809: extract_atoms phase gets a real abort signal; +2 #5809: cycle_already_running names the lock holder; +1 #4578: a lock steal during the last selected phase reports lock_stolen (one phase per runCycle call)src/core/cycle/extract-atoms.ts runPhaseExtractAtoms 787 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +12 #5809/#5832: hard/soft stop checks, chat-call signal, abortable pacing, no post-stop writes; +1 #5856: one BudgetTracker per drain attempt (reuse the attempt's tracker)diff --git a/src/commands/hook.ts b/src/commands/hook.tsindex 7c858a1762..5c40da8879 100644--- a/src/commands/hook.ts+++ b/src/commands/hook.ts@@ -74,6 +74,7 @@ import {HARVEST_RECEIPT_SUFFIX,segmentHash,} from '../core/context/corpus-segments.ts';+import { hookLaneLabel, resolveSeat, seatReasonHint, writeSeatSidecar } from '../core/context/seat.ts';import { gateWritebackTurn, WRITEBACK_SKIP_REASONS } from '../core/facts/writeback-gate.ts';import { resolveWritebackConfigFromFile } from '../core/facts/writeback-config.ts';import { memorableGateAllowed, recordAndRelayReceipt, redactedToolCallsJson } from '../core/context/hook-heartbeat.ts';@@ -1303,6 +1304,7 @@ async function hookCompact(io: HookIo): Promise<number> {let reason: string | undefined;let segment: string | undefined;let flushAck: string | undefined;+ let seatReasons: string[] = [];const work = (async () => {const j = await readStdinJson(io, 300);@@ -1312,6 +1314,7 @@ async function hookCompact(io: HookIo): Promise<number> {let turns: WindowTurn[] = [];let boundaryTurnIndexes: number[] = [];let allTurns: WindowTurn[] = [];+ let transcriptPath: string | undefined;if (j.transcript_path !== undefined && j.transcript_path !== null) {const conf = confineTranscriptPath(j.transcript_path, {...(io.transcriptRoot ? { root: io.transcriptRoot } : {}),@@ -1321,6 +1324,7 @@ async function hookCompact(io: HookIo): Promise<number> {allowOversize: true,});if (!conf.ok) { outcome = 'degraded'; reason = `transcript_${conf.reason}`; return; }+ transcriptPath = conf.path;try {const parsed = parseTranscript(conf.path, { maxBytes: USER_PROMPT_TRANSCRIPT_MAX_BYTES });allTurns = parsed.turns;@@ -1347,7 +1351,9 @@ async function hookCompact(io: HookIo): Promise<number> {// any IPC. Written for EVERY engine config (the sweep backstop harvests it// when serve/IPC is unavailable). Per-step deadline degrades — a scan that// can't finish skips the segment ENTIRELY (never write unscanned content).- const banked = await bankCompactSegment(await corpusDir(cfg), sessionId, allTurns, boundaryTurnIndexes, {+ const dir = await corpusDir(cfg);+ seatReasons = captureSeat(io, dir, sessionId, transcriptPath);+ const banked = await bankCompactSegment(dir, sessionId, allTurns, boundaryTurnIndexes, {remainingMs: remaining,minScanMs: SEGMENT_MIN_BUDGET_MS,minWriteMs: SEGMENT_WRITE_MIN_BUDGET_MS,@@ -1396,11 +1402,14 @@ async function hookCompact(io: HookIo): Promise<number> {outcome = 'error';reason = errorCode(e); // fail-open: exit 0}+ if (outcome === 'ok' && seatReasons.length) { outcome = 'degraded'; reason = seatReasons[0]; }+ const hint = seatReasonHint(reason);await writeHeartbeat(io, {ts: new Date().toISOString(),event: 'compact',outcome,...(reason ? { reason } : {}),+ ...(hint ? { hint } : {}),duration_ms: Date.now() - t0,...(segment ? { segment } : {}),...(flushAck ? { flush: flushAck } : {}),@@ -1483,8 +1492,10 @@ async function hookStop(io: HookIo): Promise<number> {if (!lastUser || !lastUser.text) return 'no_user_turn';const gated = gateWritebackTurn(lastUser.text);if (!gated.ok) return gated.reason;+ const dir = await corpusDir(cfg);+ captureSeat(io, dir, sid, conf.path); // #4618: the seat precedes the banked turn fileconst banked = await bankWritebackTurn(- await corpusDir(cfg), sid, gated.normalized, gated.hash24,+ dir, sid, gated.normalized, gated.hash24,// Bank the session's source IN THE NAME so the sweep fallback files// the turn into the same source the IPC lane below would have.process.env.GBRAIN_SOURCE ?? null,@@ -1600,6 +1611,17 @@ function corpusRetentionDays(cfg: GBrainConfig | null): number {return typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : CORPUS_RETENTION_DAYS_DEFAULT;}+/** #4618: record the session's seat sidecar; returns heartbeat reason codes. Never throws. */+function captureSeat(io: HookIo, dir: string, sessionId: string, transcriptPath: string | undefined): string[] {+ const harness = io.harness ?? 'claude-code';+ try {+ const seat = resolveSeat({ env: process.env, harness, transcriptPath });+ return seat ? writeSeatSidecar(dir, sessionId, seat, { harness, hookLane: hookLaneLabel(process.env.GBRAIN_HOOK_LANE) }) : [];+ } catch {+ return ['seat_write_failed'];+ }+}+async function hookSessionEnd(io: HookIo): Promise<number> {const t0 = Date.now();let outcome: HookHeartbeatEntry['outcome'] = 'ok';@@ -1699,6 +1721,9 @@ async function hookSessionEnd(io: HookIo): Promise<number> {}} else if (turnsN > 0) {const dir = await corpusDir(cfg);+ // #4618: the seat is recorded BEFORE any corpus file of this session+ // is renamed into place, so a sweep never sees one without its seat.+ deferredReasons.push(...captureSeat(io, dir, sessionId, conf.path));// Cathedral 5 dedup contract: when EVERY non-empty boundary window's// redacted hash is banked in the segment ledger (exact-set), write// only the post-last-boundary REMAINDER; any mismatch ⇒ full@@ -1853,12 +1878,14 @@ async function hookSessionEnd(io: HookIo): Promise<number> {// Deferred reasons apply LAST — visible when nothing about THIS session// degraded, never masking a current-session reason.for (const r of deferredReasons) degrade(r);+ const hint = seatReasonHint(reason);await writeHeartbeat(io, {ts: new Date().toISOString(),event: 'session-end',outcome,...(reason ? { reason } : {}),+ ...(hint ? { hint } : {}),duration_ms: Date.now() - t0,...(turnsN !== undefined ? { turns: turnsN } : {}),...(bytesN !== undefined ? { bytes: bytesN } : {}),diff --git a/src/core/context-engine.ts b/src/core/context-engine.tsindex 38ed31c24c..08b81b648e 100644--- a/src/core/context-engine.ts+++ b/src/core/context-engine.ts@@ -780,6 +780,19 @@ export function sanitizeEngineSessionId(raw: unknown): string | null {return s && !/^\.+$/.test(s) ? s : null;}+/**+ * #4618: record the session's seat before its segment is spooled (the hook+ * lane's ordering), keyed to the OpenClaw agent dir holding `sessions/`.+ * Additive provenance: a failure never fails the checkpoint.+ */+async function recordOpenclawSeat(dir: string, sessionId: string, sessionFile: string): Promise<void> {+ try {+ const { resolveSeat, writeSeatSidecar } = await import('./context/seat.ts');+ const seat = resolveSeat({ env: process.env, harness: 'openclaw', transcriptPath: sessionFile });+ if (seat) writeSeatSidecar(dir, sessionId, seat, { harness: 'openclaw', hookLane: 'context-engine' });+ } catch { /* best effort */ }+}+// ── Engine Implementation ───────────────────────────────────────────────export function createGBrainContextEngine(ctx: {@@ -952,6 +965,7 @@ export function createGBrainContextEngine(ctx: {const { loadConfig } = await import('./config.ts');const cfg = loadConfig();const dir = await engineCorpusDir(cfg);+ await recordOpenclawSeat(dir, sessionId, sessionFile);const w = segs.writeSegment(dir, sessionId, rendered.text);const ordinal = segs.appendSegmentLedger(dir, sessionId, w.hash);const memo = checkpointMemo.get(sessionId) ?? { links: [], polls: 0, expectSeg: null, settled: false };diff --git a/src/core/context/corpus-segments.ts b/src/core/context/corpus-segments.tsindex a036d8b8f5..c09a029bfd 100644--- a/src/core/context/corpus-segments.ts+++ b/src/core/context/corpus-segments.ts@@ -77,6 +77,19 @@ export function ledgerFileName(sessionId: string): string {return `${safeIdComponent(sessionId)}.ledger.json`;}+/** #4618 per-session seat sidecar (context/seat.ts owns its content). One+ * per SESSION, not per corpus file: the session-end `.txt`, its checkpoint+ * segments and its writeback turns all share it. */+export const SEAT_SIDECAR_SUFFIX = '.seat.json';++export function seatFileName(sessionId: string): string {+ return `${safeIdComponent(sessionId)}${SEAT_SIDECAR_SUFFIX}`;+}++/** A seat sidecar written ahead of its corpus file is never reaped inside+ * this window (the writer renames the corpus file within seconds). */+const SEAT_ORPHAN_GRACE_MS = 10 * 60 * 1000;+/** Receipt sidecar suffix (harvest link candidates persisted before manifest* publish). Lives HERE so the engine-free hook lane can GC orphaned receipts* without importing the engine-typed harvest module. */@@ -475,9 +488,10 @@ export async function decideCorpusMode(/*** GC companion for the corpus dir (extends the hook's `.txt`-only GC): remove- * ledgers past the retention window, and remove ORPHANED sidecars whose base- * `.txt` is gone (previously they lived forever). Best-effort per file; never- * throws.+ * ledgers past the retention window, ORPHANED sidecars whose base `.txt` is+ * gone (previously they lived forever), and a session's seat sidecar once no+ * `.txt` of that session remains (after a grace window, so a sidecar written+ * just ahead of its corpus file survives). Best-effort per file; never throws.*/export function gcCorpusArtifacts(dir: string,@@ -486,9 +500,17 @@ export function gcCorpusArtifacts(): void {try {const cutoff = Date.now() - maxAgeMs;- for (const name of readdirSync(dir)) {+ const names = readdirSync(dir);+ const liveSessions = new Set(names.filter((n) => n.endsWith('.txt')).map(corpusFileSessionId));+ for (const name of names) {const p = join(dir, name);try {+ if (name.endsWith(SEAT_SIDECAR_SUFFIX)) {+ if (!liveSessions.has(name.slice(0, -SEAT_SIDECAR_SUFFIX.length)) && statSync(p).mtimeMs < Date.now() - SEAT_ORPHAN_GRACE_MS) {+ rmSync(p, { force: true });+ }+ continue;+ }if (name.endsWith('.ledger.json')) {if (statSync(p).mtimeMs < cutoff) rmSync(p, { force: true });continue;diff --git a/src/core/context/seat.ts b/src/core/context/seat.tsnew file mode 100644index 0000000000..b8db95cdde--- /dev/null+++ b/src/core/context/seat.ts@@ -0,0 +1,182 @@+/**+ * seat.ts — seat identity for captured sessions (#4618).+ *+ * A seat names the agent seat (harness home) whose conversation a corpus file+ * came from, so dream synthesis can credit synthesized pages to it on a brain+ * several agents feed. ENGINE-FREE: pure fs + crypto, usable from the hook+ * command and the OpenClaw context engine.+ *+ * Label: `GBRAIN_SEAT` (operator-chosen, lowercased, `SEAT_LABEL_RE`). Absent+ * ⇒ `home-<8 hex>`, the first 8 hex chars of sha256 over the harness home's+ * realpath — the raw path never leaves the machine, because the seat lands in+ * page frontmatter that may be committed to git. An invalid label falls back+ * to the home seat and reports `seat_label_invalid`. `GBRAIN_SEAT=off` is the+ * opt-out: no seat is recorded, so synthesized pages carry none.+ *+ * Sidecar: `<sessionId>.seat.json` (0600, tmp+rename) beside the corpus+ * files, written BEFORE a corpus file or segment is renamed into place, so a+ * sweep never sees a corpus file without its seat. The first seat recorded+ * for a session is kept; a later capture under another seat reports+ * `seat_conflict` and leaves the sidecar unchanged.+ */++import { createHash } from 'node:crypto';+import { readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs';+import { homedir } from 'node:os';+import { basename, dirname, join, resolve } from 'node:path';+import { seatFileName } from './corpus-segments.ts';++const SEAT_LABEL_RE = /^[a-z0-9][a-z0-9._-]{0,63}$/;++/** The reserved label that turns seat capture off. */+const SEAT_OFF = 'off';++export type SeatReason = 'seat_label_invalid' | 'seat_conflict' | 'seat_write_failed';++/** Fixed heartbeat recovery hints (constant text, never content). */+const SEAT_REASON_HINTS: Record<SeatReason, string> = {+ seat_label_invalid:+ 'GBRAIN_SEAT is not a valid seat label (1-64 chars of a-z 0-9 . _ -, starting with a letter or digit); ' ++ 'sessions are credited to the harness-home seat until you re-run `gbrain bootstrap hooks --seat <label>` ' ++ 'or `gbrain bootstrap harness --seat <label>` with a valid label',+ seat_conflict:+ 'this session was first captured under a different seat; the first seat is kept for the whole session. ' ++ 'No action needed unless the session was resumed from another agent home on purpose',+ seat_write_failed:+ 'the seat sidecar could not be written beside the session corpus, so pages synthesized from this session ' ++ 'carry no seat; make the corpus dir (dream.synthesize.session_corpus_dir, default ' ++ '~/.gbrain/transcripts/corpus) writable by this user (`ls -ld` it); the next capture of the session records the seat',+};++export function seatReasonHint(reason: string | undefined): string | undefined {+ return reason !== undefined && Object.hasOwn(SEAT_REASON_HINTS, reason)+ ? SEAT_REASON_HINTS[reason as SeatReason]+ : undefined;+}++export interface SeatSidecar {+ version: 1;+ seat: string;+ seat_source: 'env' | 'harness_home';+ hook_lane: string;+ harness: string;+ first_seen: string;+}++export interface ResolvedSeat {+ seat: string;+ seat_source: SeatSidecar['seat_source'];+ reasons: SeatReason[];+}++type Env = Record<string, string | undefined>;++/** Lowercased, validated seat label; null when the value is not a valid label. */+export function normalizeSeatLabel(raw: unknown): string | null {+ if (typeof raw !== 'string') return null;+ const label = raw.trim().toLowerCase();+ return SEAT_LABEL_RE.test(label) ? label : null;+}++function parentOfNearestAncestor(path: string, name: string): string | null {+ let dir = dirname(resolve(path));+ for (;;) {+ if (basename(dir) === name) return dirname(dir);+ const up = dirname(dir);+ if (up === dir) return null;+ dir = up;+ }+}++/**+ * The harness home a session ran under. Claude Code: the directory holding+ * `projects/` in the transcript path, else CLAUDE_CONFIG_DIR, else CODEX_HOME.+ * Codex: CODEX_HOME (its hook is spawned by codex, which owns that env).+ * OpenClaw: the agent directory holding `sessions/`. Each falls back to the+ * harness's default home under $HOME.+ */+function harnessHome(opts: { env: Env; harness?: string; transcriptPath?: string | null }): string {+ const { env, harness, transcriptPath } = opts;+ const home = env.HOME?.trim() || homedir();+ if (harness === 'codex') return env.CODEX_HOME?.trim() || join(home, '.codex');+ if (harness === 'openclaw') {+ return (transcriptPath && parentOfNearestAncestor(transcriptPath, 'sessions')) || join(home, '.openclaw');+ }+ return (transcriptPath && parentOfNearestAncestor(transcriptPath, 'projects'))+ || env.CLAUDE_CONFIG_DIR?.trim()+ || env.CODEX_HOME?.trim()+ || join(home, '.claude');+}++function homeSeat(dir: string): string {+ let real: string;+ try {+ real = realpathSync(dir);+ } catch {+ real = resolve(dir);+ }+ return `home-${createHash('sha256').update(real, 'utf8').digest('hex').slice(0, 8)}`;+}++/** The session's seat; null when `GBRAIN_SEAT=off` turned seat capture off. */+export function resolveSeat(opts: { env: Env; harness?: string; transcriptPath?: string | null }): ResolvedSeat | null {+ const raw = opts.env.GBRAIN_SEAT;+ const reasons: SeatReason[] = [];+ if (raw !== undefined && raw.trim() !== '') {+ const label = normalizeSeatLabel(raw);+ if (label === SEAT_OFF) return null;+ if (label) return { seat: label, seat_source: 'env', reasons };+ reasons.push('seat_label_invalid');+ }+ return { seat: homeSeat(harnessHome(opts)), seat_source: 'harness_home', reasons };+}++/** The recorded sidecar, or null when absent, unreadable or not a valid v1 record. */+export function readSeatSidecar(dir: string, sessionId: string): SeatSidecar | null {+ try {+ const parsed = JSON.parse(readFileSync(join(dir, seatFileName(sessionId)), 'utf8')) as Partial<SeatSidecar>;+ return parsed?.version === 1 && typeof parsed.seat === 'string' && SEAT_LABEL_RE.test(parsed.seat)+ ? (parsed as SeatSidecar)+ : null;+ } catch {+ return null;+ }+}++/**+ * Record the session's seat unless one is already recorded. Returns the+ * heartbeat reasons (resolution reasons plus `seat_conflict`). Throws only on+ * a write failure.+ */+export function writeSeatSidecar(+ dir: string,+ sessionId: string,+ resolved: ResolvedSeat,+ meta: { harness: string; hookLane: string },+): SeatReason[] {+ const reasons = [...resolved.reasons];+ const prior = readSeatSidecar(dir, sessionId);+ if (prior) {+ if (prior.seat !== resolved.seat) reasons.push('seat_conflict');+ return reasons;+ }+ const record: SeatSidecar = {+ version: 1,+ seat: resolved.seat,+ seat_source: resolved.seat_source,+ hook_lane: meta.hookLane,+ harness: meta.harness,+ first_seen: new Date().toISOString(),+ };+ const file = join(dir, seatFileName(sessionId));+ const tmp = `${file}.tmp-${process.pid}`;+ writeFileSync(tmp, JSON.stringify(record) + '\n', { mode: 0o600 });+ renameSync(tmp, file);+ return reasons;+}++/** The hook lane label recorded in the sidecar (charset-bounded; never raw env text). */+export function hookLaneLabel(raw: string | undefined): string {+ if (!raw) return 'workspace';+ return /^[a-z0-9_-]{1,32}$/.test(raw) ? raw : 'other';+}diff --git a/test/hook-command.serial.test.ts b/test/hook-command.serial.test.tsindex 04058f8742..ea62fc0fea 100644--- a/test/hook-command.serial.test.ts+++ b/test/hook-command.serial.test.ts@@ -757,8 +757,9 @@ describe('session-end', () => {transcriptRoot: projRoot,});const corpusDir = join(home(), 'transcripts', 'corpus');- const files = readdirSync(corpusDir).filter((f) => f.startsWith('sess-dup'));- expect(files).toEqual(['sess-dup.txt']);+ const files = readdirSync(corpusDir).filter((f) => f.startsWith('sess-dup')).sort();+ // One corpus file plus the session's one seat sidecar (#4618).+ expect(files).toEqual(['sess-dup.seat.json', 'sess-dup.txt']);expect(readFileSync(join(corpusDir, 'sess-dup.txt'), 'utf8')).toContain('resumed pass content');});diff --git a/test/session-seat-capture.serial.test.ts b/test/session-seat-capture.serial.test.tsnew file mode 100644index 0000000000..05b0faff50--- /dev/null+++ b/test/session-seat-capture.serial.test.ts@@ -0,0 +1,227 @@+/**+ * #4618 seat identity on session capture: `gbrain hook session-end`,+ * `gbrain hook compact` and the OpenClaw context-engine compact record a+ * `<sessionId>.seat.json` sidecar beside the dream corpus, before any corpus+ * file of the session is renamed into place, and the hook GC reaps it with+ * the session's last corpus file.+ *+ * Authoring gate: protects the corpus-side seat contract dream synthesis reads+ * (the sidecar's existence, content, ordering and lifetime). A regression that+ * drops the write, leaks a raw home path, reorders it after the corpus rename,+ * overwrites a session's first seat, or reaps a live session's seat fails here.+ * No existing test covers the sidecar; no production seam is added.+ *+ * SERIAL: mutates GBRAIN_HOME / GBRAIN_SEAT / CLAUDE_CONFIG_DIR / CODEX_HOME+ * (check-test-isolation R1 quarantine).+ */+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';+import { createHash } from 'node:crypto';+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, utimesSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { readHeartbeatTail, runHook } from '../src/commands/hook.ts';+import { __resetSdkLoadStateForTests, createGBrainContextEngine } from '../src/core/context-engine.ts';++const ENV_KEYS = ['GBRAIN_HOME', 'GBRAIN_SEAT', 'GBRAIN_HOOK_LANE', 'GBRAIN_SOURCE', 'GBRAIN_HOOKS', 'CLAUDE_CONFIG_DIR', 'CODEX_HOME', 'GBRAIN_MEMORABLE'] as const;+let tmp: string;+let saved: Record<string, string | undefined>;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), 'gb-seat-'));+ saved = {};+ for (const k of ENV_KEYS) {+ saved[k] = process.env[k];+ delete process.env[k];+ }+ process.env.GBRAIN_HOME = tmp;+ mkdirSync(join(tmp, 'ws'), { recursive: true });+});++afterEach(() => {+ for (const k of ENV_KEYS) {+ if (saved[k] === undefined) delete process.env[k];+ else process.env[k] = saved[k];+ }+ rmSync(tmp, { recursive: true, force: true });+});++const corpus = () => join(tmp, '.gbrain', 'transcripts', 'corpus');+const sidecar = (sid: string) => join(corpus(), `${sid}.seat.json`);+const readSeat = (sid: string) => JSON.parse(readFileSync(sidecar(sid), 'utf8')) as Record<string, unknown>;+const expectedHomeSeat = (dir: string) =>+ `home-${createHash('sha256').update(realpathSync(dir), 'utf8').digest('hex').slice(0, 8)}`;++const userLine = (text: string) => JSON.stringify({ type: 'user', isSidechain: false, message: { role: 'user', content: text } });+const assistantLine = (text: string) =>+ JSON.stringify({ type: 'assistant', isSidechain: false, message: { role: 'assistant', content: [{ type: 'text', text }] } });+const boundaryLine = () => JSON.stringify({ type: 'system', subtype: 'compact_boundary', content: 'conversation compacted' });++/** A Claude Code transcript under `<harnessHome>/projects/p1/`. */+function seedTranscript(harnessHome: string, name: string, lines: string[]): string {+ const dir = join(harnessHome, 'projects', 'p1');+ mkdirSync(dir, { recursive: true });+ const p = join(dir, name);+ writeFileSync(p, lines.join('\n') + '\n');+ return p;+}++async function sessionEnd(sid: string, harnessHome: string, transcript: string): Promise<void> {+ expect(await runHook(['session-end'], {+ stdin: JSON.stringify({ session_id: sid, transcript_path: transcript, cwd: join(tmp, 'ws') }),+ transcriptRoot: join(harnessHome, 'projects'),+ })).toBe(0);+}++const lastHeartbeat = async () => (await readHeartbeatTail(1))[0];++describe('seat sidecar on session capture (#4618)', () => {+ test('1. GBRAIN_SEAT: a 0600 env-sourced sidecar is written before the corpus file is renamed into place', async () => {+ process.env.GBRAIN_SEAT = 'alice-desk';+ const transcript = seedTranscript(tmp, 's.jsonl', [userLine('a question'), assistantLine('an answer')]);+ // A directory squatting on the corpus filename makes the corpus rename+ // fail: whatever exists afterwards was written BEFORE the rename.+ mkdirSync(join(corpus(), 'sess-order.txt'), { recursive: true });+ await sessionEnd('sess-order', tmp, transcript);+ expect(statSync(join(corpus(), 'sess-order.txt')).isDirectory()).toBe(true);+ expect(existsSync(sidecar('sess-order'))).toBe(true);+ expect(statSync(sidecar('sess-order')).mode & 0o777).toBe(0o600);+ expect(readSeat('sess-order')).toMatchObject({+ version: 1, seat: 'alice-desk', seat_source: 'env', hook_lane: 'workspace', harness: 'claude-code',+ });++ // The ordinary path: corpus file and sidecar side by side, label lowercased.+ process.env.GBRAIN_SEAT = 'Alice-Desk';+ await sessionEnd('sess-env', tmp, seedTranscript(tmp, 't.jsonl', [userLine('another question')]));+ expect(existsSync(join(corpus(), 'sess-env.txt'))).toBe(true);+ expect(readSeat('sess-env')).toMatchObject({ seat: 'alice-desk', seat_source: 'env' });+ });++ test('2. no GBRAIN_SEAT: a deterministic home-<8 hex> seat and no path in the sidecar', async () => {+ const homeA = join(tmp, 'claude-home-a');+ await sessionEnd('sess-a1', homeA, seedTranscript(homeA, 'a.jsonl', [userLine('first session')]));+ await sessionEnd('sess-a2', homeA, seedTranscript(homeA, 'b.jsonl', [userLine('second session')]));+ const first = readSeat('sess-a1');+ expect(first.seat).toBe(expectedHomeSeat(homeA));+ expect(first.seat).toMatch(/^home-[0-9a-f]{8}$/);+ expect(first.seat_source).toBe('harness_home');+ expect(readSeat('sess-a2').seat).toBe(first.seat);+ const raw = readFileSync(sidecar('sess-a1'), 'utf8');+ expect(raw).not.toContain(tmp);+ expect(raw).not.toContain('/');+ });++ test('3. an invalid GBRAIN_SEAT falls back to the home seat and reports seat_label_invalid with a recovery hint', async () => {+ process.env.GBRAIN_SEAT = 'Not A Seat!';+ await sessionEnd('sess-bad', tmp, seedTranscript(tmp, 'bad.jsonl', [userLine('hello')]));+ expect(readSeat('sess-bad')).toMatchObject({ seat: expectedHomeSeat(tmp), seat_source: 'harness_home' });+ const hb = await lastHeartbeat();+ expect(hb?.event).toBe('session-end');+ expect(hb?.outcome).toBe('degraded');+ expect(hb?.reason).toBe('seat_label_invalid');+ expect(hb?.hint).toContain('gbrain bootstrap hooks --seat');+ });++ test('GBRAIN_SEAT=off is the opt-out: the corpus is captured with no seat sidecar', async () => {+ process.env.GBRAIN_SEAT = 'off';+ await sessionEnd('sess-off', tmp, seedTranscript(tmp, 'off.jsonl', [userLine('no seat please')]));+ expect(existsSync(join(corpus(), 'sess-off.txt'))).toBe(true);+ expect(existsSync(sidecar('sess-off'))).toBe(false);+ expect((await lastHeartbeat())?.reason ?? '').not.toMatch(/^seat_/);+ });++ test('4. a session resumed from another harness home keeps its first seat and reports seat_conflict', async () => {+ const homeA = join(tmp, 'home-a');+ const homeB = join(tmp, 'home-b');+ await sessionEnd('sess-moved', homeA, seedTranscript(homeA, 'm.jsonl', [userLine('started at desk A')]));+ const before = readFileSync(sidecar('sess-moved'), 'utf8');+ await sessionEnd('sess-moved', homeB, seedTranscript(homeB, 'm.jsonl', [userLine('started at desk A'), assistantLine('resumed at desk B')]));+ expect(readFileSync(sidecar('sess-moved'), 'utf8')).toBe(before);+ expect(readSeat('sess-moved').seat).toBe(expectedHomeSeat(homeA));+ expect(readFileSync(join(corpus(), 'sess-moved.txt'), 'utf8')).toContain('resumed at desk B');+ const hb = await lastHeartbeat();+ expect(hb?.reason).toBe('seat_conflict');+ expect(hb?.hint).toContain('first seat is kept');+ });++ test('5. compaction banks a segment and writes the session sidecar once; session-end reuses it', async () => {+ process.env.GBRAIN_SEAT = 'alice-desk';+ const lines = [userLine('OLD window'), boundaryLine(), userLine('NEW window text'), assistantLine('reply in the new window')];+ const transcript = seedTranscript(tmp, 'c.jsonl', lines);+ const compact = () => runHook(['compact'], {+ stdin: JSON.stringify({ session_id: 'sess-cmp', transcript_path: transcript }),+ transcriptRoot: join(tmp, 'projects'),+ });+ expect(await compact()).toBe(0);+ expect(readdirSync(corpus()).filter((f) => f.startsWith('sess-cmp.seg-'))).toHaveLength(1);+ const bytes = readFileSync(sidecar('sess-cmp'), 'utf8');+ const mtime = statSync(sidecar('sess-cmp')).mtimeMs;+ expect(JSON.parse(bytes)).toMatchObject({ seat: 'alice-desk', seat_source: 'env' });+ await new Promise((r) => setTimeout(r, 20));+ expect(await compact()).toBe(0);+ await sessionEnd('sess-cmp', tmp, transcript);+ expect(readFileSync(sidecar('sess-cmp'), 'utf8')).toBe(bytes);+ expect(statSync(sidecar('sess-cmp')).mtimeMs).toBe(mtime);+ expect(readdirSync(corpus()).filter((f) => f.endsWith('.seat.json'))).toEqual(['sess-cmp.seat.json']);+ expect((await lastHeartbeat())?.reason).not.toBe('seat_conflict');+ });++ test('6. GC removes a seat sidecar with its session\'s last corpus file and keeps live or just-written ones', async () => {+ mkdirSync(corpus(), { recursive: true });+ const old = Date.now() / 1000 - 1000 * 24 * 60 * 60;+ for (const name of ['old.txt', 'old.seat.json', 'oldseg.seg-0123456789abcdef01234567.txt', 'oldseg.seat.json']) {+ writeFileSync(join(corpus(), name), name.endsWith('.json') ? '{"version":1,"seat":"alice-desk"}\n' : 'old corpus\n');+ utimesSync(join(corpus(), name), old, old);+ }+ writeFileSync(join(corpus(), 'live.txt'), 'live corpus\n');+ writeFileSync(join(corpus(), 'live.seat.json'), '{"version":1,"seat":"alice-desk"}\n');+ utimesSync(join(corpus(), 'live.seat.json'), old, old);+ writeFileSync(join(corpus(), 'pending.seat.json'), '{"version":1,"seat":"alice-desk"}\n');+ await sessionEnd('sess-gc', tmp, seedTranscript(tmp, 'g.jsonl', [userLine('triggers the GC')]));+ const left = readdirSync(corpus());+ expect(left).not.toContain('old.txt');+ expect(left).not.toContain('old.seat.json');+ expect(left).not.toContain('oldseg.seat.json');+ expect(left).toContain('live.seat.json');+ expect(left).toContain('pending.seat.json');+ expect(left).toContain('sess-gc.seat.json');+ });++ test('a writeback turn banked by the stop hook gets the session sidecar too', async () => {+ process.env.GBRAIN_SEAT = 'alice-desk';+ mkdirSync(join(tmp, '.gbrain'), { recursive: true });+ writeFileSync(join(tmp, '.gbrain', 'config.json'), JSON.stringify({+ engine: 'pglite', database_path: join(tmp, 'pglite-data'), memory: { auto_writeback: 'salient' },+ }));+ const transcript = seedTranscript(tmp, 'wb.jsonl', [userLine('I prefer dark mode in every editor, please set it up.'), assistantLine('Done.')]);+ expect(await runHook(['stop'], {+ write: () => {}, transcriptRoot: join(tmp, 'projects'),+ stdin: JSON.stringify({ session_id: 'sess-wb', transcript_path: transcript }),+ })).toBe(0);+ expect(readdirSync(corpus()).filter((f) => /^sess-wb\.wb-[0-9a-f]{24}\.txt$/.test(f))).toHaveLength(1);+ expect(readSeat('sess-wb')).toMatchObject({ seat: 'alice-desk', seat_source: 'env' });+ });++ test('the OpenClaw context-engine compaction writes the same sidecar, keyed to the agent directory', async () => {+ __resetSdkLoadStateForTests();+ const ws = join(tmp, 'oc-ws');+ mkdirSync(join(ws, 'memory'), { recursive: true });+ writeFileSync(join(ws, 'memory', 'heartbeat-state.json'), '{}');+ const agentDir = join(tmp, 'openclaw', 'agents', 'agent-a');+ mkdirSync(join(agentDir, 'sessions'), { recursive: true });+ const sessionFile = join(agentDir, 'sessions', 'oc-sess.jsonl');+ const msg = (text: string) =>+ JSON.stringify({ type: 'message', timestamp: '2026-08-01T10:00:01Z', message: { role: 'user', content: [{ type: 'text', text }] } });+ writeFileSync(sessionFile, [+ JSON.stringify({ type: 'session', id: 'oc-sess', cwd: '/w', timestamp: '2026-08-01T10:00:00Z' }),+ msg('PRE-BOUNDARY text'),+ JSON.stringify({ type: 'compaction', timestamp: '2026-08-01T10:00:02Z' }),+ msg('POST-BOUNDARY window text'),+ ].join('\n') + '\n');+ const engine = createGBrainContextEngine({ workspaceDir: ws });+ await engine.compact({ sessionId: 'oc-sess', sessionFile });+ expect(readdirSync(corpus()).filter((f) => f.startsWith('oc-sess.seg-'))).toHaveLength(1);+ expect(readSeat('oc-sess')).toMatchObject({+ seat: expectedHomeSeat(agentDir), seat_source: 'harness_home', harness: 'openclaw', hook_lane: 'context-engine',+ });+ });+});