Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(openclaw): bank compaction checkpoints on 2026.9.x hosts (#6316)

time-attack3aa19349a881
diff --git a/docs/architecture/key-files/ambient-capture.md b/docs/architecture/key-files/ambient-capture.md
index eacf21e0aa..299cbb2924 100644
--- a/docs/architecture/key-files/ambient-capture.md
+++ b/docs/architecture/key-files/ambient-capture.md
@@ -9,3 +9,4 @@ each lane's claim, and a re-check at fact admission. User guide:
Key files:
- `src/core/context/capture-consent.ts` + `src/core/facts/capture-sources.ts` (+ `captureGateDecision` in `src/core/facts/writeback-config.ts`) — `captureGateDecision(cfg, lane)` is the ONE truth table for the ambient capture lanes (`writeback` = `.wb-` Stop-hook turns, `compact` = PreCompact segments + OpenClaw compactions, `session_end` = SessionEnd `<sid>.txt`): explicit `off` retires every lane; unset retires `writeback` and extracts `compact`/`session_end` (the hooks are their opt-in); read error, plane drift, invalid mode, and (compact/session_end) a DB-absent file-mirror `off` (`off_unsynced`) hold. `captureLaneStates`/`captureLaneSummary`/`writebackOffMessage`/`writebackUnsetMessage`/`WRITEBACK_RESTART_AFTER_OFF` render it for `config set|unset|get` (stderr lane line), doctor `memory_writeback` (`details.capture_lanes`, `details.restart_after_off`) and the guide's truth table. `src/core/context/capture-consent.ts`: capture side `recordCaptureIfOff` (the PreCompact `bankCompactSegment` `beforeWrite` callback, the SessionEnd corpus write and the OpenClaw spool write this brain's own `<file>.capture-off.<brain>.json` (`captureOffRecordPath`; brain identity = hash of the resolved config dir, turn hashes via `corpus-turns.ts`) BEFORE the file lands, unioning a pre-wave-12 single `<file>.capture-off.json` that names this brain, so two brains sharing a corpus directory never overwrite each other's off turns; GC (`corpus-segments.ts`, `CAPTURE_OFF_INFIX`) reaps any brain's orphan record only after the seat grace); extraction side `resolveCaptureGate` + `applyCaptureGate` (hold / `retireCorpusFile` / fold this brain's turns, own record plus a matching legacy record, via `retireCorpusTurns`, retiring a file whose every turn was captured under off; foreign-brain records ignored; an unreadable or invalid record holds `capture_record_unreadable` and makes `recordCaptureIfOff` throw, never reads as "no record"), called under the claim before any provider call or receipt republish in `checkpoint-harvest.ts` (`runOne`, `runWritebackTurn`), `context-engine.ts` rung 3 and `sweep.ts` (including the keyless/extraction-disabled early returns). Publication side: `src/core/facts/capture-sources.ts` holds `FACTS_BACKSTOP_SOURCES` (`as const`; `FactsBackstopCtx['source']` derives from it), the ambient subset, `captureGateLaneForSource` and `assertAmbientCaptureAdmissible` (code `ambient_capture_off`), re-checked inside `admitManagedFactsBatch`'s transaction (`facts-maintenance.ts`; sessions and intents carry `captureSource` / `capture_source`, so #6048 follow-up batches are re-checked too) and before the unmanaged fence write in `backstop.ts`; requests admitted before `off` publish. Tests: `test/capture-consent-gate.serial.test.ts`, `test/capture-consent-admission.test.ts` (PGLite + Postgres), `test/capture-consent-inventory.test.ts`. Retired turn hashes also land in `.progress` `retired_turns` (`retireCorpusFile`, `retireCorpusTurns`); `planCorpusWindows` skips them wherever a rewrite places them, and `withoutOffPeriodTurns` (capture-consent.ts) strips them from what `discoverTranscripts` hands dream synthesis.
+- `src/core/context-engine.ts` + `src/openclaw-context-engine.ts` — the deterministic context engine OpenClaw loads on every turn (`assemble()` injects the Live Context block, zero-LLM). `createGBrainContextEngine({workspaceDir, resolveEntities?})` accepts an OPTIONAL host-injected resolver (`ENGINE_API_VERSION` 0.3.0, additive — older hosts work unchanged; the plugin entry maps `ctx.resolveEntities`/`ctx.brainQuery` onto it). Checkpoint compaction: `compact()` runs a time-bounded (8s), fail-open, lazily-imported checkpoint step BEFORE delegating — spools the since-last-boundary window (openclaw tail reader over the exported adapter mapper, 40-turn cap = the no-prior-boundary fallback) as a content-addressed corpus segment + ledger entry, then rung 2 (PGLite: one `bankOnly`+`flushCorpusFile` IPC round trip to serve) or rung 3 (Postgres: inline harvest over the reflex ladder's exported `getDirectPostgresEngine` singleton, under sweep claim fencing + capability/kill-switch gates, abort post-check) — and rides an additive `result.gbrain_checkpoint` bag on the delegate's return (`ownsCompaction` stays false). After the segment is spooled, the Memorable receipt lane runs (gate + stamp via `memorableGateAllowed`, span-filtered redacted tool calls, `recordAndRelayReceipt` with `harness: 'openclaw'` — per-compaction capture, content-hash dedup on retries, fail-open for the checkpoint; the whole block is skipped once the host's compact() deadline has fired; the rendered segment text is re-scanned with highEntropy at receipt time and the relay REFUSED fail-closed on any hit — the segment rendering feeds the ledger hash and cannot change, so the next compaction window re-evaluates; this lane NEVER compacts the receipts file — the hook lane is the ONE compactor, single-rewriter rule — but DOES trim the relay file, since an openclaw-only host has no hook lane and converging newest-keeping trims make concurrent trims safe). `assemble()` consumes `sessionId ?? sessionKey` and splices a deterministic envelope-bearing Compaction-checkpoint block at parts[1] (after Live Context) from the banked manifest via an in-process memo + hash-keyed polls (≤5; stale manifests can't satisfy a poll for the new segment; no manifest ⇒ byte-identical output). `assemble()` runs the Retrieval Reflex after the Live Context block: extracts the current turn's user text, builds prior-context text (every message EXCEPT the current turn — suppression must not see the triggering mention), passes the rolling window (`getWindowTurns`, last 12 user/assistant turns; the reflex slices to its configured `retrieval_reflex_window_turns`), and appends the pointer block. `warmReflex()` fires at construction. Current-host plugin factories may be called with zero arguments. The host workspace takes precedence; ambiguous/unbound legacy fallback warns and reads no source. The canonical slot ID is `gbrain-context-engine`; `gbrain-context` remains a registry alias, not a current-host slot alias. The exclusive context-engine contract and no-write stateless admitted-turn acknowledgement are additive. `assemble` uses an authoritative separate prompt: sqlite transcript-storage metadata fences historic turns, whereas an identical final legacy user message already represents the current turn. Reflex-only synthesis leaves messages intact; absent prompt keeps message extraction. These contracts do not prove model recall. `compact()` records the session's seat sidecar (`context/seat.ts`, harness `openclaw`, seat keyed to the agent directory holding `sessions/`) before spooling the segment; a failure never fails the checkpoint. OpenClaw 2026.9.x calls `compact()` with a `sessionTarget` and no `sessionFile`; `readCompactTail` then reads the transcript through the host's `openclaw/plugin-sdk/session-transcript-runtime` (`readSessionTranscriptEvents`, lazily imported; `__setTranscriptRuntimeLoaderForTests` is the seam) and maps the events with the JSONL mapper (`readOpenclawEventsTail` in `corpus-segments.ts`), keeping the file path for older hosts. Every compaction writes one `openclaw-compact` heartbeat (status and reason codes); doctor `memory_writeback` warns when a week of compactions banked none (`details.openclaw_compactions_7d`). Pinned-host proof: `test/openclaw-context-engine-native.serial.test.ts` (gateway plus `openclaw sessions compact`); fake runtime: `test/openclaw-compact-transcript-runtime.serial.test.ts`.
diff --git a/docs/architecture/key-files/engines-1.md b/docs/architecture/key-files/engines-1.md
index a4d17c1044..46b0d291a6 100644
--- a/docs/architecture/key-files/engines-1.md
+++ b/docs/architecture/key-files/engines-1.md
@@ -7,7 +7,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/connection-manager.ts` — routes ordinary and direct Postgres pools. Supabase-shaped URLs retain automatic derivation; a valid explicit `GBRAIN_DIRECT_DATABASE_URL` or constructor override also enables dual routing for generic Postgres and PgBouncer on custom ports. The kill switch and inherited parent route stay authoritative. `describeMode()` reports the same route used by `ddl()` and `bulk()`. Regression coverage: `test/connection-manager.serial.test.ts` and the real 24-case persistence runtime matrix.
-- `src/core/context-engine.ts` + `src/openclaw-context-engine.ts` — the deterministic context engine OpenClaw loads on every turn (`assemble()` injects the Live Context block, zero-LLM). `createGBrainContextEngine({workspaceDir, resolveEntities?})` accepts an OPTIONAL host-injected resolver (`ENGINE_API_VERSION` 0.3.0, additive — older hosts work unchanged; the plugin entry maps `ctx.resolveEntities`/`ctx.brainQuery` onto it). Checkpoint compaction: `compact()` runs a time-bounded (8s), fail-open, lazily-imported checkpoint step BEFORE delegating — spools the since-last-boundary window (openclaw tail reader over the exported adapter mapper, 40-turn cap = the no-prior-boundary fallback) as a content-addressed corpus segment + ledger entry, then rung 2 (PGLite: one `bankOnly`+`flushCorpusFile` IPC round trip to serve) or rung 3 (Postgres: inline harvest over the reflex ladder's exported `getDirectPostgresEngine` singleton, under sweep claim fencing + capability/kill-switch gates, abort post-check) — and rides an additive `result.gbrain_checkpoint` bag on the delegate's return (`ownsCompaction` stays false). After the segment is spooled, the Memorable receipt lane runs (gate + stamp via `memorableGateAllowed`, span-filtered redacted tool calls, `recordAndRelayReceipt` with `harness: 'openclaw'` — per-compaction capture, content-hash dedup on retries, fail-open for the checkpoint; the whole block is skipped once the host's compact() deadline has fired; the rendered segment text is re-scanned with highEntropy at receipt time and the relay REFUSED fail-closed on any hit — the segment rendering feeds the ledger hash and cannot change, so the next compaction window re-evaluates; this lane NEVER compacts the receipts file — the hook lane is the ONE compactor, single-rewriter rule — but DOES trim the relay file, since an openclaw-only host has no hook lane and converging newest-keeping trims make concurrent trims safe). `assemble()` consumes `sessionId ?? sessionKey` and splices a deterministic envelope-bearing Compaction-checkpoint block at parts[1] (after Live Context) from the banked manifest via an in-process memo + hash-keyed polls (≤5; stale manifests can't satisfy a poll for the new segment; no manifest ⇒ byte-identical output). `assemble()` runs the Retrieval Reflex after the Live Context block: extracts the current turn's user text, builds prior-context text (every message EXCEPT the current turn — suppression must not see the triggering mention), passes the rolling window (`getWindowTurns`, last 12 user/assistant turns; the reflex slices to its configured `retrieval_reflex_window_turns`), and appends the pointer block. `warmReflex()` fires at construction. Current-host plugin factories may be called with zero arguments. The host workspace takes precedence; ambiguous/unbound legacy fallback warns and reads no source. The canonical slot ID is `gbrain-context-engine`; `gbrain-context` remains a registry alias, not a current-host slot alias. The exclusive context-engine contract and no-write stateless admitted-turn acknowledgement are additive. `assemble` uses an authoritative separate prompt: sqlite transcript-storage metadata fences historic turns, whereas an identical final legacy user message already represents the current turn. Reflex-only synthesis leaves messages intact; absent prompt keeps message extraction. These contracts do not prove model recall. `compact()` records the session's seat sidecar (`context/seat.ts`, harness `openclaw`, seat keyed to the agent directory holding `sessions/`) before spooling the segment; a failure never fails the checkpoint.
- `src/core/db-lock.ts` + `lease-schema.ts` — row leases survive transaction-mode PgBouncer. Migration 152 gives every `gbrain_cycle_locks` acquisition a UUID; refresh/release, dead-holder takeover/reaper and manual/age-gated breaks match the observed token exactly. Epoch text is retained for diagnostics and legacy mutation detection, never treated as unique identity. `withRefreshingLock` always passes an aborting work signal, rejects results after ownership loss/TTL expiry, tracks a single actual renewal through timeout cancellation, and drains late completion before release. Renewal deadlines start before the database round trip. `performSync` composes this signal with caller cancellation. `inspectLock`, `listStaleLocks`, `listLiveLocks`, `classifyHolderLiveness` and namespace-scoped `reapDeadHolderLocks` retain their status/recovery contracts. Tests: `test/db-lock-concurrency.test.ts`, `test/e2e/db-lock-acquisition-token.test.ts`, existing fencing/reaper/inspection suites.
diff --git a/src/commands/doctor/checks/memory-writeback.ts b/src/commands/doctor/checks/memory-writeback.ts
index 0973ee500c..1c94a422f1 100644
--- a/src/commands/doctor/checks/memory-writeback.ts
+++ b/src/commands/doctor/checks/memory-writeback.ts
@@ -39,7 +39,7 @@ import { resolveDefaultVisibility } from '../../../core/facts/visibility.ts';
import { classifyBrainAudience } from '../../../core/facts/writeback-audience.ts';
import { readVerbUsage } from '../../../core/verbs/usage-log.ts';
import { readClientOpUsage } from '../../../core/mcp-usage.ts';
-import { readHeartbeatTail } from '../../../core/context/hook-heartbeat.ts';
+import { OPENCLAW_COMPACT_EVENT, readHeartbeatTail } from '../../../core/context/hook-heartbeat.ts';
import { CORPUS_UNINGESTED_RETENTION_FACTOR, corpusBacklog, corpusSpoolDir } from '../../../core/context/corpus-segments.ts';
import { listCorpusSourceHolds } from '../../../core/context/corpus-source.ts';
import { readHarnessReceiptState } from '../../../core/bootstrap/format.ts';
@@ -137,6 +137,27 @@ async function corpusSourceHoldProblem(engine: BrainEngine, fileCfg: ReturnType<
+ 'Ask the user which source they belong to, preview with gbrain sweep --assign-corpus <source>, then add --apply';
}
+/**
+ * #6316: the OpenClaw context engine writes one heartbeat per compaction.
+ * Compactions in the window that never banked a segment mean the lane is
+ * silently dead (a host that passes neither a session file nor a target the
+ * engine can read). Records `details.openclaw_compactions_7d`.
+ */
+async function openclawCompactionProblem(details: Record<string, unknown>): Promise<string | null> {
+ const cutoff = Date.now() - COUNTER_WINDOW_DAYS * DAY_MS;
+ const runs = (await readHeartbeatTail(2000)).filter((e) => e.event === OPENCLAW_COMPACT_EVENT && Date.parse(e.ts) >= cutoff);
+ if (!runs.length) return null;
+ const skipped = runs.filter((e) => e.segment === 'skipped');
+ const reasons: Record<string, number> = {};
+ for (const e of skipped) reasons[e.reason ?? 'unknown'] = (reasons[e.reason ?? 'unknown'] ?? 0) + 1;
+ details.openclaw_compactions_7d = { total: runs.length, banked: runs.length - skipped.length, skipped: reasons };
+ const blind = (reasons.no_session ?? 0) + (reasons.transcript_runtime_unavailable ?? 0) + (reasons.transcript_read_failed ?? 0);
+ if (skipped.length < runs.length || blind === 0) return null;
+ const top = Object.entries(reasons).sort((a, b) => b[1] - a[1])[0]!;
+ return `OpenClaw ran ${runs.length} compaction(s) in ${COUNTER_WINDOW_DAYS}d and the gbrain checkpoint banked none (top skip: ${top[0]} x${top[1]}); `
+ + 'compaction-time facts are not being captured. Upgrade gbrain on the OpenClaw host and restart the gateway, then check again: gbrain doctor --json';
+}
+
async function corpusBacklogProblem(engine: BrainEngine, fileCfg: ReturnType<typeof loadConfig>, details: Record<string, unknown>): Promise<string | null> {
const synth = fileCfg?.dream?.synthesize as Record<string, unknown> | undefined;
const dir = await sessionCorpusDir(engine, fileCfg);
@@ -257,6 +278,8 @@ export async function buildMemoryWritebackCheck(engine: BrainEngine | null): Pro
// Unset (default) off still extracts SessionEnd and compaction files; explicit off retires them.
const offHoldProblem = explicitOff ? null : await corpusSourceHoldProblem(engine, fileCfg, details).catch(() => null);
if (offHoldProblem) offProblems.push(offHoldProblem);
+ const offCompactProblem = explicitOff ? null : await openclawCompactionProblem(details).catch(() => null);
+ if (offCompactProblem) offProblems.push(offCompactProblem);
if (explicitOff) details.restart_after_off = WRITEBACK_RESTART_AFTER_OFF;
return {
name: MEMORY_WRITEBACK_CHECK_NAME,
@@ -275,6 +298,8 @@ export async function buildMemoryWritebackCheck(engine: BrainEngine | null): Pro
if (corpusProblem) problems.push(corpusProblem);
const holdProblem = await corpusSourceHoldProblem(engine, fileCfg, details).catch(() => null);
if (holdProblem) problems.push(holdProblem);
+ const compactProblem = await openclawCompactionProblem(details).catch(() => null);
+ if (compactProblem) problems.push(compactProblem);
if (!wb.ttl_valid) {
problems.push(`memory.auto_writeback_transient_ttl is invalid — using '${wb.transient_ttl}'`);
}
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 0a54256cbf..cb0f7a114c 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -376,6 +376,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
// Fix wave 13 PR3 (GBRA-57). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
{ since: '0.60.152.0', text: 'The dream cycle now reads a schema pack set with `gbrain config set schema_pack` (or `schema_pack.source.<id>`) when it decides whether to run extract_atoms and synthesize_concepts, as `gbrain schema active` already did. A paid phase that only such a database-config pack declares, and that did not run before, is skipped with `consent_required` until you run `gbrain config set cycle.extract_atoms.enabled true` (or `cycle.synthesize_concepts.enabled true`); doctor `extract_atoms_backlog` names the same command.' },
{ since: '0.60.152.0', text: 'On a managed brain, a page or transcript whose atom extraction failed (malformed or cut-off model output) is now retried by the next drain or cycle, inside its per-run budget, up to 3 attempts per content; it was replayed as a failure with no model call and could stop the drain with `provider_failure`. After the third failure it is held (`held_failed`): out of the atom backlog until its content changes, and doctor `extract_atoms_held_failed` lists it with the paid retry command.' },
+ { since: '0.60.152.0', text: 'Captured session files (compaction segments, Stop-hook turns and SessionEnd transcripts) now record the source their session started under and are filed there, in a `sourced/` folder of the corpus directory, instead of under whatever source the sweep runs for. Files written before this upgrade on a brain with more than one source are held until you say where they belong: `gbrain doctor` names them, `gbrain sweep --assign-corpus <source>` previews and `--apply` maps them. A serve asked to file a session under another source refuses instead of rerouting it.' },
+ { since: '0.60.152.0', text: 'On OpenClaw 2026.9.x, which no longer passes a session file to the context engine, compaction now banks a gbrain checkpoint segment again by reading the transcript through the host\'s session-transcript runtime. Each compaction leaves an `openclaw-compact` entry in the hooks heartbeat, and `gbrain doctor` warns when a week of compactions banked nothing.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/context-engine.ts b/src/core/context-engine.ts
index d3128b0000..4976dba859 100644
--- a/src/core/context-engine.ts
+++ b/src/core/context-engine.ts
@@ -13,6 +13,7 @@
* @see https://docs.openclaw.ai/concepts/context-engine
*/
+import type { OpenclawBoundaryTail } from './context/corpus-segments.ts';
import { readFileSync, existsSync, statSync } from 'fs';
import { join } from 'path';
import { buildReflexAddition, warmReflex, type ResolveEntitiesFn as ReflexResolveEntitiesFn } from './context/reflex.ts';
@@ -67,7 +68,9 @@ export interface ContextEngine {
}): Promise<AssembleResult>;
compact(params: {
sessionId: string;
- sessionFile: string;
+ /** Older hosts; OpenClaw 2026.9.x passes `sessionTarget` instead (#6316). */
+ sessionFile?: string;
+ sessionTarget?: { agentId?: string; sessionId: string; sessionKey?: string; storePath?: string; threadId?: string };
tokenBudget?: number;
force?: boolean;
[key: string]: unknown;
@@ -98,6 +101,36 @@ async function ensureSdkLoaded(): Promise<void> {
}
}
+/** #6316: the host SDK surface that reads a transcript by session identity (OpenClaw 2026.9.x). */
+type TranscriptRuntime = { readSessionTranscriptEvents: (target: Record<string, unknown>) => Promise<unknown[]> | unknown[] };
+let _transcriptRuntimeLoader: (() => Promise<unknown>) | undefined;
+
+async function loadTranscriptRuntime(): Promise<TranscriptRuntime | null> {
+ try {
+ // @ts-ignore — resolved at runtime by the OpenClaw host; not a build-time dep.
+ const mod = (await (_transcriptRuntimeLoader ? _transcriptRuntimeLoader() : import('openclaw/plugin-sdk/session-transcript-runtime'))) as Partial<TranscriptRuntime> | null;
+ return typeof mod?.readSessionTranscriptEvents === 'function' ? (mod as TranscriptRuntime) : null;
+ } catch {
+ return null;
+ }
+}
+
+/** Test-only: replace the host transcript-runtime import (undefined restores the real one). */
+export function __setTranscriptRuntimeLoaderForTests(loader: (() => Promise<unknown>) | undefined): void {
+ _transcriptRuntimeLoader = loader;
+}
+
+/** The host's session target, reduced to the identity fields its transcript runtime reads. */
+function hostSessionTarget(raw: unknown): Record<string, string> | null {
+ if (!raw || typeof raw !== 'object') return null;
+ const target: Record<string, string> = {};
+ for (const key of ['agentId', 'sessionId', 'sessionKey', 'storePath', 'threadId']) {
+ const value = (raw as Record<string, unknown>)[key];
+ if (typeof value === 'string' && value) target[key] = value;
+ }
+ return target.sessionId ? target : null;
+}
+
/** Test-only: reset the lazy-load state so a test can re-exercise the load path. */
export function __resetSdkLoadStateForTests(): void {
_sdkLoaded = false;
@@ -781,6 +814,80 @@ export function sanitizeEngineSessionId(raw: unknown): string | null {
return s && !/^\.+$/.test(s) ? s : null;
}
+async function engineCorpusDir(cfg: { dream?: { synthesize?: Record<string, unknown> } } | null): Promise<string> {
+ const configured = cfg?.dream?.synthesize?.session_corpus_dir;
+ const { ensureGbrainHome, resolveGbrainHome } = await import('./gbrain-home.ts');
+ const { mkdirSync } = await import('node:fs');
+ const { isAbsolute, join: joinPath } = await import('node:path');
+ let dir: string;
+ if (typeof configured === 'string' && configured && isAbsolute(configured)) {
+ dir = configured;
+ } else {
+ let home: string;
+ try {
+ home = ensureGbrainHome();
+ } catch {
+ home = resolveGbrainHome();
+ }
+ dir = joinPath(home, 'transcripts', 'corpus');
+ }
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
+ return dir;
+}
+
+/** #6268: the session's frozen corpus source, or undefined while unresolved / unknown. */
+async function sessionSourceFor(cfg: { dream?: { synthesize?: Record<string, unknown> } } | null, sessionId: string): Promise<string | undefined> {
+ const { corpusSpoolDir } = await import('./context/corpus-segments.ts');
+ const { readSessionSource } = await import('./context/corpus-source.ts');
+ return readSessionSource(corpusSpoolDir(await engineCorpusDir(cfg)), sessionId)?.source_id ?? undefined;
+}
+
+/**
+ * #6316: the compaction window's source transcript: the JSONL `sessionFile`
+ * on older hosts, otherwise the host's session-transcript-runtime read by
+ * `sessionTarget`. A typed skip reason when neither yields mapped events.
+ */
+async function readCompactTail(
+ sessionFile: string | null,
+ target: Record<string, string> | null,
+ deadlineHit: () => boolean,
+): Promise<{ tail: OpenclawBoundaryTail } | { skip: string }> {
+ const segs = await import('./context/corpus-segments.ts');
+ let tail: OpenclawBoundaryTail | null = null;
+ if (sessionFile) {
+ tail = segs.readOpenclawBoundaryTail(sessionFile, { maxBytes: 2 * 1024 * 1024 });
+ } else if (target) {
+ const runtime = await loadTranscriptRuntime();
+ if (!runtime) return { skip: 'transcript_runtime_unavailable' };
+ let events: unknown;
+ try {
+ events = await runtime.readSessionTranscriptEvents(target);
+ } catch {
+ return { skip: 'transcript_read_failed' };
+ }
+ if (deadlineHit()) return { skip: 'deadline' };
+ tail = Array.isArray(events) ? segs.readOpenclawEventsTail(events, { maxBytes: 2 * 1024 * 1024 }) : null;
+ }
+ return tail ? { tail } : { skip: 'unparseable' };
+}
+
+/**
+ * #6316: one heartbeat per OpenClaw compaction (status and reason codes only),
+ * so doctor can tell a compaction lane that never banks (`no_session`,
+ * `transcript_runtime_unavailable`) from one that was never called.
+ */
+async function recordOpenclawCompact(checkpoint: Record<string, unknown>, durationMs: number): Promise<void> {
+ try {
+ const { OPENCLAW_COMPACT_EVENT, writeHeartbeat } = await import('./context/hook-heartbeat.ts');
+ const status = typeof checkpoint.status === 'string' ? checkpoint.status : 'unknown';
+ const reason = typeof checkpoint.reason === 'string' ? checkpoint.reason : undefined;
+ await writeHeartbeat({
+ ts: new Date().toISOString(), event: OPENCLAW_COMPACT_EVENT, outcome: status === 'skipped' ? 'degraded' : 'ok',
+ ...(reason ? { reason } : {}), segment: status, duration_ms: durationMs,
+ }, { trim: false });
+ } catch { /* telemetry never fails the compaction */ }
+}
+
/**
* #4618: record the session's seat before its segment is spooled (the hook
* lane's ordering), keyed to the OpenClaw agent dir holding `sessions/`.
@@ -789,7 +896,7 @@ export function sanitizeEngineSessionId(raw: unknown): string | null {
* heartbeat as a degraded `compact` entry with its fixed recovery hint, the
* way the hook lane reports it.
*/
-async function recordOpenclawSeat(dir: string, sessionId: string, sessionFile: string): Promise<void> {
+async function recordOpenclawSeat(dir: string, sessionId: string, sessionFile: string | null): Promise<void> {
try {
const { resolveSeat, writeSeatSidecar } = await import('./context/seat.ts');
let reasons: string[];
@@ -949,7 +1056,7 @@ export function createGBrainContextEngine(ctx: {
/** compact()-side: spool-first checkpoint over the ladder. Never throws. */
async function runCompactCheckpoint(params: {
- sessionId?: unknown; sessionFile?: unknown;
+ sessionId?: unknown; sessionFile?: unknown; sessionTarget?: unknown;
}, deadlineHit: () => boolean = () => false): Promise<Record<string, unknown>> {
// Host-supplied id, sanitized to the hook lane's charset before ANY
// filename/key use (pre-landing review, security: OpenClaw session keys
@@ -963,12 +1070,16 @@ export function createGBrainContextEngine(ctx: {
// equivalent root for OpenClaw's session store. Content is sniffed
// structurally: a non-JSONL/boundary-less file is a typed skip below.
const sessionFile = typeof params.sessionFile === 'string' && params.sessionFile ? params.sessionFile : null;
- if (!sessionId || !sessionFile) return { status: 'skipped', reason: 'no_session' };
+ // #6316: OpenClaw 2026.9.x passes no sessionFile; it passes a sessionTarget
+ // its session-transcript-runtime reads from the host's SQLite store.
+ const target = sessionFile ? null : hostSessionTarget(params.sessionTarget);
+ if (!sessionId || (!sessionFile && !target)) return { status: 'skipped', reason: 'no_session' };
const segs = await import('./context/corpus-segments.ts');
if (deadlineHit()) return { status: 'skipped', reason: 'deadline' };
- const tail = segs.readOpenclawBoundaryTail(sessionFile, { maxBytes: 2 * 1024 * 1024 });
- if (!tail) return { status: 'skipped', reason: 'unparseable' };
+ const read = await readCompactTail(sessionFile, target, deadlineHit);
+ if ('skip' in read) return { status: 'skipped', reason: read.skip };
+ const tail = read.tail;
const windowTurns = segs.sliceBoundaryWindow(tail.turns, tail.boundaryTurnIndexes, {
maxTurns: OPENCLAW_SEGMENT_MAX_TURNS,
});
@@ -981,12 +1092,9 @@ export function createGBrainContextEngine(ctx: {
const { loadConfig } = await import('./config.ts');
const cfg = loadConfig();
// #6268: the session's frozen source rides in the segment NAME, inside the spool.
- const root = await engineCorpusDir(cfg);
- const dir = segs.ensureCorpusSpoolDir(root);
- const { stamp } = await (await import('./context/corpus-source.ts')).openSessionSource(root, sessionId, { cwd: workspaceDir, harness: 'openclaw' });
- const source = stamp !== segs.CORPUS_UNRESOLVED_STAMP ? stamp : undefined;
+ const { root, dir, stamp, source } = await (await import('./context/corpus-source.ts')).openSessionCorpus(await engineCorpusDir(cfg), sessionId, { cwd: workspaceDir, harness: 'openclaw' });
const segName = (hash: string) => segs.segmentFileName(sessionId, hash, stamp);
- await recordOpenclawSeat(dir, sessionId, sessionFile);
+ await recordOpenclawSeat(dir, sessionId, sessionFile ?? target?.storePath ?? null);
(await import('./context/capture-consent.ts')).recordCaptureIfOff(cfg, `${dir}/${segName(segs.segmentHash(rendered.text))}`, rendered.text, source);
const w = segs.writeSegment(dir, sessionId, rendered.text, stamp);
const ordinal = segs.appendSegmentLedger(dir, sessionId, w.hash);
@@ -1163,34 +1271,8 @@ export function createGBrainContextEngine(ctx: {
}
}
- /** #6268: the session's frozen corpus source, or undefined while unresolved / unknown. */
- async function sessionSourceFor(cfg: { dream?: { synthesize?: Record<string, unknown> } } | null, sessionId: string): Promise<string | undefined> {
- const { corpusSpoolDir } = await import('./context/corpus-segments.ts');
- const { readSessionSource } = await import('./context/corpus-source.ts');
- return readSessionSource(corpusSpoolDir(await engineCorpusDir(cfg)), sessionId)?.source_id ?? undefined;
- }
/** Corpus dir from FILE config (hook.ts parity — no engine required). */
- async function engineCorpusDir(cfg: { dream?: { synthesize?: Record<string, unknown> } } | null): Promise<string> {
- const configured = cfg?.dream?.synthesize?.session_corpus_dir;
- const { ensureGbrainHome, resolveGbrainHome } = await import('./gbrain-home.ts');
- const { mkdirSync } = await import('node:fs');
- const { isAbsolute, join: joinPath } = await import('node:path');
- let dir: string;
- if (typeof configured === 'string' && configured && isAbsolute(configured)) {
- dir = configured;
- } else {
- let home: string;
- try {
- home = ensureGbrainHome();
- } catch {
- home = resolveGbrainHome();
- }
- dir = joinPath(home, 'transcripts', 'corpus');
- }
- mkdirSync(dir, { recursive: true, mode: 0o700 });
- return dir;
- }
const engine: ContextEngine = {
info: {
@@ -1309,6 +1391,7 @@ export function createGBrainContextEngine(ctx: {
// delegate; the abort closure stops it at the next step boundary, and
// the timer is cleared when the work wins.
let gbrainCheckpoint: Record<string, unknown>;
+ const checkpointStart = Date.now();
try {
const deadline = new AbortController();
let timer: ReturnType<typeof setTimeout> | undefined;
@@ -1332,6 +1415,7 @@ export function createGBrainContextEngine(ctx: {
} catch {
gbrainCheckpoint = { status: 'skipped', reason: 'error' };
}
+ await recordOpenclawCompact(gbrainCheckpoint, Date.now() - checkpointStart);
// Delegate to legacy runtime compaction UNCHANGED (ownsCompaction stays
// false), then ride the additive bag on the existing untyped `result`.
const delegated =
diff --git a/src/core/context/corpus-segments.ts b/src/core/context/corpus-segments.ts
index 545d0c4775..124e883630 100644
--- a/src/core/context/corpus-segments.ts
+++ b/src/core/context/corpus-segments.ts
@@ -335,7 +335,7 @@ export async function coverageComplete(
export function readOpenclawBoundaryTail(
path: string,
opts: { maxBytes?: number } = {},
-): { turns: WindowTurn[]; boundaryTurnIndexes: number[]; toolCalls: ToolCallRecord[]; toolCallTurnIndexes: number[] } | null {
+): OpenclawBoundaryTail | null {
const maxBytes = Math.max(1, Math.floor(opts.maxBytes ?? 2 * 1024 * 1024));
let raw: string;
try {
@@ -355,6 +355,47 @@ export function readOpenclawBoundaryTail(
} catch {
return null;
}
+ const entries: unknown[] = [];
+ for (const line of raw.split('\n')) {
+ const t = line.trim();
+ if (!t) continue;
+ try {
+ entries.push(JSON.parse(t));
+ } catch {
+ continue; // includes a tail read's partial first line
+ }
+ }
+ return mapOpenclawEntries(entries);
+}
+
+export type OpenclawBoundaryTail = { turns: WindowTurn[]; boundaryTurnIndexes: number[]; toolCalls: ToolCallRecord[]; toolCallTurnIndexes: number[] };
+
+/**
+ * #6316: OpenClaw 2026.9.x keeps transcripts in its SQLite store and passes
+ * compact() a `sessionTarget` instead of a `sessionFile`. The host's
+ * `session-transcript-runtime` returns the same event objects the JSONL file
+ * holds, so this keeps the newest events up to `maxBytes` of serialized JSON
+ * (the file reader's tail bound) and maps them with the same mapper.
+ */
+export function readOpenclawEventsTail(events: unknown[], opts: { maxBytes?: number } = {}): OpenclawBoundaryTail | null {
+ const maxBytes = Math.max(1, Math.floor(opts.maxBytes ?? 2 * 1024 * 1024));
+ let bytes = 0;
+ let start = events.length;
+ while (start > 0) {
+ let size: number;
+ try {
+ size = Buffer.byteLength(JSON.stringify(events[start - 1]) ?? '', 'utf8') + 1;
+ } catch {
+ break;
+ }
+ if (bytes + size > maxBytes) break;
+ bytes += size;
+ start--;
+ }
+ return mapOpenclawEntries(events.slice(start));
+}
+
+function mapOpenclawEntries(entries: unknown[]): OpenclawBoundaryTail | null {
const turns: WindowTurn[] = [];
const boundaryTurnIndexes: number[] = [];
// Memorable integration: tool calls stamped with the turn slot they sit at
@@ -365,15 +406,7 @@ export function readOpenclawBoundaryTail(
const toolCalls: ToolCallRecord[] = [];
const toolCallTurnIndexes: number[] = [];
let mappedAnything = false;
- for (const line of raw.split('\n')) {
- const t = line.trim();
- if (!t) continue;
- let entry: unknown;
- try {
- entry = JSON.parse(t);
- } catch {
- continue; // includes a tail read's partial first line
- }
+ for (const entry of entries) {
const mapped = mapOpenclawLine(entry);
if (mapped.kind === 'message' || mapped.kind === 'skip') {
for (const c of mapped.toolCalls ?? []) {
diff --git a/src/core/context/hook-heartbeat.ts b/src/core/context/hook-heartbeat.ts
index 85e3ac4cb8..63ba7c8b63 100644
--- a/src/core/context/hook-heartbeat.ts
+++ b/src/core/context/hook-heartbeat.ts
@@ -20,6 +20,9 @@ import type { ToolCallRecord } from '../transcripts/claude-code-jsonl.ts';
import { ensureGbrainHome, resolveGbrainHome } from '../gbrain-home.ts';
import { seatReasonHint } from './seat.ts';
+/** #6316: the OpenClaw context engine's per-compaction checkpoint event. */
+export const OPENCLAW_COMPACT_EVENT = 'openclaw-compact';
+
/** Heartbeat file line cap [S3#7]. */
export const HEARTBEAT_MAX_LINES = 5000;
diff --git a/test/doctor-memory-writeback.test.ts b/test/doctor-memory-writeback.test.ts
index 6926fe3ed0..9e215da5d8 100644
--- a/test/doctor-memory-writeback.test.ts
+++ b/test/doctor-memory-writeback.test.ts
@@ -305,3 +305,38 @@ describe('memory_writeback doctor check', () => {
});
}
});
+
+describe('memory_writeback doctor check: capture-lane notices (#6268, #6316)', () => {
+ test('#6268 a held session file (source never resolved) → warn naming --assign-corpus preview then --apply; the default-off path reports it too', async () => {
+ const spool = join(tmp, '.gbrain', 'transcripts', 'corpus', 'sourced');
+ mkdirSync(spool, { recursive: true });
+ writeFileSync(join(spool, 'sess-held.src-_unresolved.txt'), 'USER: hi\n');
+ await withEnv({ GBRAIN_HOME: tmp }, async () => {
+ const off = await buildMemoryWritebackCheck(engine);
+ expect(off.status).toBe('warn');
+ expect(off.details?.corpus_source_holds).toEqual({ legacy_unstamped: 0, unresolved: 1, sessions: 1 });
+ expect(off.message).toContain('gbrain sweep --assign-corpus <source>');
+ expect(off.message).toContain('--apply');
+ await engine.setConfig('memory.auto_writeback', 'off');
+ writeFileMirror(tmp, { auto_writeback: 'off' });
+ expect((await buildMemoryWritebackCheck(engine)).message).not.toContain('--assign-corpus');
+ });
+ });
+
+ test('#6316 OpenClaw compactions that never banked → warn with the top skip; one banked compaction clears it', async () => {
+ await engine.setConfig('memory.auto_writeback', 'salient');
+ writeFileMirror(tmp, { auto_writeback: 'salient' });
+ await withEnv({ GBRAIN_HOME: tmp }, async () => {
+ const ts = new Date().toISOString();
+ for (let i = 0; i < 2; i++) await writeHeartbeat({ ts, event: 'openclaw-compact', outcome: 'degraded', reason: 'no_session', segment: 'skipped', duration_ms: 1 }, { trim: false });
+ const dead = await buildMemoryWritebackCheck(engine);
+ expect(dead.status).toBe('warn');
+ expect(dead.details?.openclaw_compactions_7d).toEqual({ total: 2, banked: 0, skipped: { no_session: 2 } });
+ expect(dead.message).toContain('banked none (top skip: no_session x2)');
+ await writeHeartbeat({ ts, event: 'openclaw-compact', outcome: 'ok', segment: 'banked', duration_ms: 1 }, { trim: false });
+ const live = await buildMemoryWritebackCheck(engine);
+ expect(live.message).not.toContain('banked none');
+ expect(live.details?.openclaw_compactions_7d).toMatchObject({ total: 3, banked: 1 });
+ });
+ });
+});
diff --git a/test/openclaw-compact-transcript-runtime.serial.test.ts b/test/openclaw-compact-transcript-runtime.serial.test.ts
new file mode 100644
index 0000000000..9fbdf690b2
--- /dev/null
+++ b/test/openclaw-compact-transcript-runtime.serial.test.ts
@@ -0,0 +1,111 @@
+/**
+ * #6316 — OpenClaw 2026.9.x calls compact() with a `sessionTarget` and no
+ * `sessionFile`; the checkpoint reads the transcript through the host's
+ * `session-transcript-runtime`, keeps the JSONL path for older hosts, and
+ * writes one heartbeat per compaction. The runtime module is faked here; the
+ * pinned host covers it for real in openclaw-context-engine-native.serial.
+ * SERIAL: mutates GBRAIN_HOME.
+ */
+import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import {
+ __resetSdkLoadStateForTests,
+ __setTranscriptRuntimeLoaderForTests,
+ createGBrainContextEngine,
+} from '../src/core/context-engine.ts';
+import { OPENCLAW_COMPACT_EVENT, readHeartbeatTail } from '../src/core/context/hook-heartbeat.ts';
+
+const event = (type: string, extra: Record<string, unknown> = {}) => ({ type, timestamp: '2026-10-01T10:00:00Z', ...extra });
+const message = (text: string) => event('message', { id: crypto.randomUUID(), message: { role: 'user', content: [{ type: 'text', text }] } });
+const target = { agentId: 'main', sessionId: 'oc-target', sessionKey: 'agent:main:one', storePath: '/x/agents/main/sessions/sessions.json' };
+
+describe('compact() through the host session-transcript-runtime (#6316)', () => {
+ let home: string;
+ let workspace: string;
+ let savedHome: string | undefined;
+
+ beforeEach(() => {
+ __resetSdkLoadStateForTests();
+ savedHome = process.env.GBRAIN_HOME;
+ home = mkdtempSync(join(tmpdir(), 'gb-oc-runtime-'));
+ workspace = join(home, 'ws');
+ mkdirSync(workspace, { recursive: true });
+ process.env.GBRAIN_HOME = home;
+ });
+
+ afterEach(() => {
+ __setTranscriptRuntimeLoaderForTests(undefined);
+ if (savedHome === undefined) delete process.env.GBRAIN_HOME;
+ else process.env.GBRAIN_HOME = savedHome;
+ rmSync(home, { recursive: true, force: true });
+ });
+
+ const spool = () => join(home, '.gbrain', 'transcripts', 'corpus', 'sourced');
+ const segments = () => (existsSync(spool()) ? readdirSync(spool()).filter((n) => n.includes('.seg-') && n.endsWith('.txt')) : []);
+ const checkpoint = (r: { result?: unknown }) => (r.result as { gbrain_checkpoint?: { status: string; reason?: string } }).gbrain_checkpoint;
+ const compactions = async () => (await readHeartbeatTail(100)).filter((e) => e.event === OPENCLAW_COMPACT_EVENT);
+
+ it('banks the since-last-boundary window read by session target, with the target identity only', async () => {
+ const seen: unknown[] = [];
+ __setTranscriptRuntimeLoaderForTests(async () => ({
+ readSessionTranscriptEvents: async (t: unknown) => {
+ seen.push(t);
+ return [event('session', { id: 'oc-target' }), message('PRE-BOUNDARY text'), event('compaction'), message('POST-BOUNDARY window text')];
+ },
+ }));
+ const engine = createGBrainContextEngine({ workspaceDir: workspace });
+ const r = await engine.compact({ sessionId: 'oc-target', sessionTarget: { ...target, expectedWriterRunId: 'run-1' } } as never);
+ expect(checkpoint(r)).toMatchObject({ status: 'banked' });
+ expect(seen).toEqual([target]);
+ const [seg] = segments();
+ expect(seg).toBeDefined();
+ const body = readFileSync(join(spool(), seg!), 'utf8');
+ expect(body).toContain('POST-BOUNDARY');
+ expect(body).not.toContain('PRE-BOUNDARY');
+ expect(await compactions()).toMatchObject([{ outcome: 'ok', segment: 'banked' }]);
+ });
+
+ it('keeps the JSONL sessionFile path for older hosts and never calls the runtime', async () => {
+ let called = false;
+ __setTranscriptRuntimeLoaderForTests(async () => ({ readSessionTranscriptEvents: async () => { called = true; return []; } }));
+ const sessionFile = join(home, 'oc.jsonl');
+ writeFileSync(sessionFile, [event('session', { id: 'oc-file' }), message('FILE window text')].map((e) => JSON.stringify(e)).join('\n') + '\n');
+ const engine = createGBrainContextEngine({ workspaceDir: workspace });
+ const r = await engine.compact({ sessionId: 'oc-file', sessionFile, sessionTarget: target } as never);
+ expect(checkpoint(r)).toMatchObject({ status: 'banked' });
+ expect(called).toBe(false);
+ expect(readFileSync(join(spool(), segments()[0]!), 'utf8')).toContain('FILE window text');
+ });
+
+ it('a host that passes neither a file nor a target is a no_session skip, counted in the heartbeat', async () => {
+ const engine = createGBrainContextEngine({ workspaceDir: workspace });
+ const r = await engine.compact({ sessionId: 'oc-none' } as never);
+ expect(checkpoint(r)).toEqual({ status: 'skipped', reason: 'no_session' });
+ expect(segments()).toEqual([]);
+ expect(await compactions()).toMatchObject([{ outcome: 'degraded', reason: 'no_session', segment: 'skipped' }]);
+ });
+
+ it('a missing runtime module or a runtime without the reader is transcript_runtime_unavailable', async () => {
+ const engine = createGBrainContextEngine({ workspaceDir: workspace });
+ __setTranscriptRuntimeLoaderForTests(async () => { throw new Error('Cannot find module'); });
+ expect(checkpoint(await engine.compact({ sessionId: 'oc-a', sessionTarget: target } as never))).toEqual({ status: 'skipped', reason: 'transcript_runtime_unavailable' });
+ __setTranscriptRuntimeLoaderForTests(async () => ({}));
+ expect(checkpoint(await engine.compact({ sessionId: 'oc-b', sessionTarget: target } as never))).toEqual({ status: 'skipped', reason: 'transcript_runtime_unavailable' });
+ expect(segments()).toEqual([]);
+ });
+
+ it('a reader that throws is transcript_read_failed; a target without a session id is no_session', async () => {
+ __setTranscriptRuntimeLoaderForTests(async () => ({ readSessionTranscriptEvents: async () => { throw new Error('projection_rebuilding'); } }));
+ const engine = createGBrainContextEngine({ workspaceDir: workspace });
+ expect(checkpoint(await engine.compact({ sessionId: 'oc-c', sessionTarget: target } as never))).toEqual({ status: 'skipped', reason: 'transcript_read_failed' });
+ expect(checkpoint(await engine.compact({ sessionId: 'oc-d', sessionTarget: { agentId: 'main' } } as never))).toEqual({ status: 'skipped', reason: 'no_session' });
+ });
+
+ it('events with nothing the mapper knows are unparseable, not an empty bank', async () => {
+ __setTranscriptRuntimeLoaderForTests(async () => ({ readSessionTranscriptEvents: async () => [{ type: 'custom' }, 'x', null] }));
+ const engine = createGBrainContextEngine({ workspaceDir: workspace });
+ expect(checkpoint(await engine.compact({ sessionId: 'oc-e', sessionTarget: target } as never))).toEqual({ status: 'skipped', reason: 'unparseable' });
+ });
+});
diff --git a/test/openclaw-context-engine-native.serial.test.ts b/test/openclaw-context-engine-native.serial.test.ts
index 2156d5c4ba..a17e8733df 100644
--- a/test/openclaw-context-engine-native.serial.test.ts
+++ b/test/openclaw-context-engine-native.serial.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, test } from 'bun:test';
-import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { existsSync, mkdtempSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { createServer } from 'node:http';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
@@ -142,6 +142,38 @@ describe.skipIf(!host)('pinned OpenClaw native context-engine startup', () => {
expect(otherMessages).toContain('people/alice-example');
expect(otherMessages).toContain('other-source-saved-page-canary');
expect(otherMessages).not.toContain('main-source-saved-page-canary');
+
+ // #6316: a real host compaction (2026.9.x passes sessionTarget, no sessionFile) banks a segment.
+ const gatewayPort = 20_000 + Math.floor(Math.random() * 20_000);
+ const config = JSON.parse(readFileSync(configPath, 'utf8'));
+ writeFileSync(configPath, JSON.stringify({ ...config, gateway: { mode: 'local', port: gatewayPort, bind: 'loopback', auth: { mode: 'none' } } }));
+ const gateway = Bun.spawn([host!, 'gateway', 'run'], { env, cwd: otherWorkspace, stdout: 'pipe', stderr: 'pipe' });
+ try {
+ const reader = gateway.stdout.getReader();
+ let gatewayLog = '';
+ const readyBy = Date.now() + 60_000;
+ while (!gatewayLog.includes('[gateway] ready') && Date.now() < readyBy) {
+ const chunk = await Promise.race([reader.read(), Bun.sleep(1_000).then(() => null)]);
+ if (chunk?.done) break;
+ if (chunk?.value) gatewayLog += new TextDecoder().decode(chunk.value);
+ }
+ reader.releaseLock();
+ expect(gatewayLog).toContain('[gateway] ready');
+ const compacted = JSON.parse(await run(['sessions', 'compact', 'agent:main:fresh-conversation-one', '--agent', 'main', '--json', '--timeout', '60000']));
+ expect(compacted).toMatchObject({ ok: true, compacted: true });
+ } finally {
+ gateway.kill();
+ await gateway.exited;
+ }
+ const spool = join(dir, '.gbrain', 'transcripts', 'corpus', 'sourced');
+ const segments = (existsSync(spool) ? readdirSync(spool) : []).filter((name) => name.includes('.seg-') && name.endsWith('.txt'));
+ expect(segments).toHaveLength(1);
+ expect(readFileSync(join(spool, segments[0]!), 'utf8')).toContain('Tell me about Alice Example.');
+ const heartbeat = join(dir, '.gbrain', 'integrations', 'hooks', 'heartbeat.jsonl');
+ const checkpoints = (existsSync(heartbeat) ? readFileSync(heartbeat, 'utf8').trim().split('\n') : [])
+ .map((line) => JSON.parse(line)).filter((entry) => entry.event === 'openclaw-compact');
+ expect(checkpoints).toHaveLength(1);
+ expect(checkpoints[0].segment).not.toBe('skipped');
} finally {
await new Promise<void>((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
rmSync(dir, { recursive: true, force: true });
diff --git a/test/session-seat-capture.serial.test.ts b/test/session-seat-capture.serial.test.ts
index cb29d7be39..df48a33de7 100644
--- a/test/session-seat-capture.serial.test.ts
+++ b/test/session-seat-capture.serial.test.ts
@@ -74,6 +74,11 @@ async function sessionEnd(sid: string, harnessHome: string, transcript: string):
}
const lastHeartbeat = async () => (await readHeartbeatTail(1))[0];
+// #6316: every OpenClaw compaction also appends its own `openclaw-compact` checkpoint entry after the seat entry.
+const openclawHeartbeats = async () => {
+ const tail = await readHeartbeatTail(10);
+ return { lane: tail.filter((e) => e.event !== 'openclaw-compact').at(-1), checkpoint: tail.at(-1) };
+};
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 () => {
@@ -235,16 +240,18 @@ describe('seat sidecar on session capture (#4618)', () => {
mkdirSync(sidecar('oc-fail'), { recursive: true });
await openclawCompact('oc-fail');
expect(readdirSync(corpus()).filter((f) => f.startsWith('oc-fail.seg-'))).toHaveLength(1);
- const hb = await lastHeartbeat();
+ const { lane: hb, checkpoint } = await openclawHeartbeats();
expect(hb).toMatchObject({ event: 'compact', outcome: 'degraded', reason: 'seat_write_failed' });
+ expect(checkpoint).toMatchObject({ event: 'openclaw-compact', segment: 'banked' });
expect(hb?.hint).toContain('make the corpus dir');
});
test('the OpenClaw lane reports an invalid GBRAIN_SEAT like the hook lane does', async () => {
process.env.GBRAIN_SEAT = 'Not A Seat!';
await openclawCompact('oc-bad');
- const hb = await lastHeartbeat();
+ const { lane: hb, checkpoint } = await openclawHeartbeats();
expect(hb).toMatchObject({ event: 'compact', outcome: 'degraded', reason: 'seat_label_invalid' });
+ expect(checkpoint).toMatchObject({ event: 'openclaw-compact', segment: 'banked' });
expect(hb?.hint).toContain('gbrain bootstrap hooks --seat');
});
});