Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(openclaw): compaction checkpoint modules load under Node again

garrytand0b4a0793029
diff --git a/src/core/facts/withdrawal.ts b/src/core/facts/withdrawal.ts
index 25ae9aca79..075e8378fc 100644
--- a/src/core/facts/withdrawal.ts
+++ b/src/core/facts/withdrawal.ts
@@ -6,7 +6,6 @@ import { withdrawnFact, withdrawalFenceBlocks } from './withdrawal-overlay.ts';
import { ambiguousFenceClaims, discoverWithdrawalTargets, withdrawalDiscoveryFailure } from './withdrawal-discovery.ts';
import { dropPurgedFenceRows } from './purge-overlay.ts';
import { privateProvenanceFilterFragment } from '../search/private-visibility.ts';
-import { rewriteLiveSegmentedFences } from '../page-body/segment-rewrite.ts';
import { coverageActive, noteBelief, readLedgerSource, withBeliefBatch } from '../belief/ledger.ts';
import { createPageVersion } from '../page-state/versions.ts';
import { validateSlug } from '../utils.ts';
@@ -111,7 +110,10 @@ export async function recordFactWithdrawal(
// generation whose flip retires only the chunks of the occurrences it rewrote.
const segmented = affected.length ? await tx.executeRaw<{ id: number; slug: string }>(`SELECT id,slug FROM pages
WHERE source_id=$1 AND slug=ANY($2::text[]) AND body_storage='segmented'`, [sourceId, affected.map(page => page.slug)]) : [];
- for (const page of segmented) await rewriteLiveSegmentedFences(tx, Number(page.id), fence => preserveWithdrawnFenceRows(tx, sourceId, fence, page.slug));
+ if (segmented.length) {
+ const { rewriteLiveSegmentedFences } = await import('../page-body/segment-rewrite.ts');
+ for (const page of segmented) await rewriteLiveSegmentedFences(tx, Number(page.id), fence => preserveWithdrawnFenceRows(tx, sourceId, fence, page.slug));
+ }
// Logical revision and projection invalidation commit with the withdrawal.
// The revision trigger queues durable rebuild work even for unmanaged calls.
const inline = affected.length ? await tx.executeRaw<{ id: number; slug: string; knowledge_revision: string }>(
diff --git a/src/core/page-body/ingest.ts b/src/core/page-body/ingest.ts
index 9f2484cbe0..8569a152ad 100644
--- a/src/core/page-body/ingest.ts
+++ b/src/core/page-body/ingest.ts
@@ -25,7 +25,7 @@ import { stepFenceWalk, type FenceWalk } from '../fence-scan.ts';
import { BODY_LEAD_BYTES, BODY_STAGING_HARD_MS, BODY_STAGING_IDLE_MS, SEGMENTED_CREATE_SEAL_MAX_BYTES, STAGE_BATCH_BYTES } from './limits.ts';
import type { BodyRegion, BodyStagingKind, BodyStorage, JsonObject, ManifestRow, ManifestRowInput, SegmentChunkInput,
SegmentedBodyColumns, SegmentTextInput } from './types.ts';
-import { segmentStream, SEGMENTER_VERSION, type StoredRegion } from './segmenter.ts';
+import { regionTrust, segmentStream, SEGMENTER_VERSION, type StoredRegion } from './segmenter.ts';
import { initialEntryState, readEntryState, timelineEntryState, type EntryState } from './entry-state.ts';
import { ContentHashStream } from './content-hash-stream.ts';
import { prepareSegmentChunks } from './segment-chunks.ts';
@@ -150,10 +150,6 @@ export function stringBodyFlags(truth: string, timeline: string): JsonObject {
const hex = (bytes: Uint8Array) => Buffer.from(bytes).toString('hex');
const sameBytes = (a: Uint8Array, b: Uint8Array) => Buffer.from(a).equals(Buffer.from(b));
-/** The whole-region fence trust a region's stored regions are computed under (body_flags). */
-export function regionTrust(flags: JsonObject | null | undefined, region: BodyRegion): 'trusted' | 'void' {
- return (region === 'truth' ? flags?.fence_trust : flags?.timeline_fence_trust) === 'void' ? 'void' : 'trusted';
-}
/** An occurrence is its bytes, entry state and the trust its stored regions were computed under: a trust flip rechunks the region. */
const occurrenceKey = (sha256: Uint8Array, entryState: unknown, trust: 'trusted' | 'void') => `${hex(sha256)}|${stableJson(entryState)}|${trust}`;
diff --git a/src/core/page-body/read-range.ts b/src/core/page-body/read-range.ts
index 14dea92081..fa34818a45 100644
--- a/src/core/page-body/read-range.ts
+++ b/src/core/page-body/read-range.ts
@@ -36,10 +36,9 @@ import { sanitizeRemoteBody } from '../remote-body.ts';
import { credentialSafeProjection } from '../credential-projection.ts';
import { loadFenceChunkOverlay, markFenceChunk, renderFenceLowTier, type FenceChunkOverlay, type FenceLowTierRow } from '../eligibility/fence-overlay.ts';
import { withdrawalFenceBlocks } from '../facts/withdrawal-overlay.ts';
-import { regionTrust } from './ingest.ts';
import { assertRowsTile, generationBodyBytes } from './body-tiling.ts';
import { readBodyLedger, overlaySegmentText, type BodyLedger } from './segment-ledger.ts';
-import { SEGMENTER_VERSION, type FactsSlot, type OutlineHeading, type StoredRegion } from './segmenter.ts';
+import { regionTrust, SEGMENTER_VERSION, type FactsSlot, type OutlineHeading, type StoredRegion } from './segmenter.ts';
import { overlaidPieces, projectionStaleError, projectSegment, type ProjectedPiece, type SegmentProjection } from './segment-projection.ts';
import type { BodyRegion, JsonObject } from './types.ts';
import { opError } from '../ops/contract.ts';
diff --git a/src/core/page-body/segmenter.ts b/src/core/page-body/segmenter.ts
index 98697915c0..dbf75857a8 100644
--- a/src/core/page-body/segmenter.ts
+++ b/src/core/page-body/segmenter.ts
@@ -42,7 +42,7 @@ import { TIMELINE_HEADING_RE } from '../link-extraction.ts';
import { DAY_HEADER_RE, matchAnchorLine } from '../conversation-parser/parse.ts';
import { clip, DATE, FENCE, HEADING, HEADING_MAX_CHARS } from '../page-window/window.ts';
import { SEGMENT_MAX_BYTES, SEGMENT_MIN_BYTES, SEGMENT_RANK4_BYTES, SEGMENT_TARGET_BYTES } from './limits.ts';
-import type { BodyRegion, SegmentCutKind } from './types.ts';
+import type { BodyRegion, JsonObject, SegmentCutKind } from './types.ts';
import { cloneEntryState, type EntryState } from './entry-state.ts';
import {
feedPemScan, findTokens, forcePemCut, initialPemScan, markPemCut, pemExposedFrom, newLineSplit, pemBodyLike, pemResolvedTo, PEM_CONTEXT_CHARS,
@@ -169,6 +169,11 @@ export interface RegionFlags {
observedFenceTrust: 'trusted' | 'void';
}
+/** The whole-region fence trust a region's stored regions are computed under (body_flags). */
+export function regionTrust(flags: JsonObject | null | undefined, region: BodyRegion): 'trusted' | 'void' {
+ return (region === 'truth' ? flags?.fence_trust : flags?.timeline_fence_trust) === 'void' ? 'void' : 'trusted';
+}
+
export function regionFlags(exit: EntryState, fenceTrust: 'trusted' | 'void'): RegionFlags {
const track = fenceTrust === 'trusted' ? exit.trusted : exit.untrusted;
const walk = exit.trusted.walk;
diff --git a/test/openclaw-compact-node-loadable.test.ts b/test/openclaw-compact-node-loadable.test.ts
new file mode 100644
index 0000000000..a701ba6fc7
--- /dev/null
+++ b/test/openclaw-compact-node-loadable.test.ts
@@ -0,0 +1,82 @@
+/**
+ * OpenClaw loads the context engine under Node (jiti), not Bun. Node cannot
+ * load Bun's `with { type: 'file' }` asset imports (tree-sitter wasm, schema
+ * pack yaml), so a module that statically reaches one throws on import, and
+ * compact() turns that throw into `{ status: 'skipped', reason: 'error' }`
+ * after the segment is spooled: the checkpoint never banks. Every module the
+ * compaction checkpoint lazy-loads must keep its static import closure free of
+ * Bun asset imports; segmented-storage code that needs the chunker loads it
+ * lazily on the branch that writes a segmented page.
+ */
+import { describe, expect, test } from 'bun:test';
+import { existsSync, readFileSync, statSync } from 'node:fs';
+import { dirname, join, relative, resolve } from 'node:path';
+
+const root = resolve(import.meta.dir, '..');
+const transpiler = new Bun.Transpiler({ loader: 'ts' });
+
+const COMPACTION_PATH = [
+ 'src/core/config.ts',
+ 'src/core/gbrain-home.ts',
+ 'src/core/secret-scan.ts',
+ 'src/core/source-resolver.ts',
+ 'src/core/sweep.ts',
+ 'src/core/context/capture-consent.ts',
+ 'src/core/context/corpus-segments.ts',
+ 'src/core/context/corpus-source.ts',
+ 'src/core/context/corpus-windows.ts',
+ 'src/core/context/hook-heartbeat.ts',
+ 'src/core/context/reflex.ts',
+ 'src/core/context/resolve-ipc.ts',
+ 'src/core/context/seat.ts',
+ 'src/core/context/session-state.ts',
+ 'src/core/facts/backstop.ts',
+ 'src/core/facts/extract.ts',
+ 'src/core/facts/extraction-availability.ts',
+ 'src/core/persistence/filesystem-guard.ts',
+];
+
+function resolveImport(from: string, spec: string): string {
+ const base = resolve(dirname(from), spec);
+ return [base, `${base}.ts`, join(base, 'index.ts')].find((path) => existsSync(path) && statSync(path).isFile()) ?? base;
+}
+
+/** The import chain from `entry` to a Bun asset import over static edges only, or null. */
+function assetChain(entry: string): string[] | null {
+ const parent = new Map<string, string | null>([[entry, null]]);
+ const queue = [entry];
+ while (queue.length) {
+ const file = queue.shift()!;
+ // test-reads-source-ok[structural]: Node-loadability is a property of the static import graph; Bun loads these assets itself, so no in-process run can reproduce the host's import failure.
+ for (const { path, kind } of transpiler.scanImports(readFileSync(file, 'utf8'))) {
+ if (kind === 'dynamic-import' || !path.startsWith('.')) continue;
+ const target = resolveImport(file, path);
+ if (!/\.(ts|js|mjs|json|node)$/.test(target)) {
+ const chain = [`${relative(root, file)} -> ${path}`];
+ for (let at = parent.get(file); at; at = parent.get(at)!) chain.unshift(relative(root, at));
+ return chain;
+ }
+ if (/\.(ts|js|mjs)$/.test(target) && !parent.has(target)) {
+ parent.set(target, file);
+ queue.push(target);
+ }
+ }
+ }
+ return null;
+}
+
+describe('OpenClaw compaction checkpoint stays loadable under Node', () => {
+ for (const module of COMPACTION_PATH) {
+ test(`${module} reaches no Bun asset import statically`, () => {
+ expect(existsSync(join(root, module))).toBe(true);
+ expect(assetChain(join(root, module))).toBeNull();
+ });
+ }
+
+ test('the guard detects a Bun asset import', () => {
+ expect(assetChain(join(root, 'src/core/markdown-chunks.ts'))).toEqual([
+ 'src/core/markdown-chunks.ts',
+ 'src/core/chunkers/code.ts -> ../../assets/wasm/tree-sitter.wasm',
+ ]);
+ });
+});