惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

量子位
WordPress大学
WordPress大学
小众软件
小众软件
云风的 BLOG
云风的 BLOG
IT之家
IT之家
人人都是产品经理
人人都是产品经理
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Last Week in AI
Last Week in AI
博客园 - 【当耐特】
T
Tailwind CSS Blog
阮一峰的网络日志
阮一峰的网络日志
V
V2EX
宝玉的分享
宝玉的分享
博客园 - Franky
F
Fortinet All Blogs
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
GbyAI
GbyAI
Hugging Face - Blog
Hugging Face - Blog
Jina AI
Jina AI
D
Docker
博客园 - 聂微东
C
Check Point Blog
H
Help Net Security

Recent Commits to openclaw:main

test: merge chat side-result checks · openclaw/openclaw@ddd2c2a test: merge cron history checks · openclaw/openclaw@f7eb746 test: merge responsive navigation shell checks · openclaw/openclaw@c2e4b47 docs(changelog): add codex oauth fixes · openclaw/openclaw@628e6cd test: merge navigation routing cases · openclaw/openclaw@5d8cecb Tests: mock channel registry bundled fallback · openclaw/openclaw@2b08233 Secrets: avoid broad web search discovery for single plugin config · openclaw/openclaw@a464f59 test: merge config view browser checks · openclaw/openclaw@20cf511 fix(status): align oauth health with runtime · openclaw/openclaw@eed7116 feat: add macOS screen snapshots for monitor preview (#67954) thanks … · openclaw/openclaw@f377db1 fix: report shared auth scopes in hello-ok (#67810) thanks @BunsDev · openclaw/openclaw@0b6c39b Auto-reply: avoid eager bundled route fallback · openclaw/openclaw@3ea1bf4 Tests: narrow session binding contract setup · openclaw/openclaw@54e4e16 fix(macOS): enable undo/redo in webchat composer text input (#34962) · openclaw/openclaw@00951dc Tests: speed up channel setup promotion · openclaw/openclaw@82b529a Docs: refresh agent instructions · openclaw/openclaw@5775fe2 fix(auth): serialize OAuth refresh across agents to fix #26322 (#67876) · openclaw/openclaw@8e79080 test: allow ollama public surface boundary test · openclaw/openclaw@7d4f1a6 Docs: add test performance guardrails · openclaw/openclaw@89706d3 Tests: restore context-engine usage proof · openclaw/openclaw@e4c4f95 Tests: slim context engine runtime coverage · openclaw/openclaw@74c198f ci: retry failed custom checkouts · openclaw/openclaw@0ee5baf test: trim duplicate provider auth onboarding cases · openclaw/openclaw@1ffc02e matrix: fix sessions_spawn --thread subagent session spawning (#67643) · openclaw/openclaw@1ce2596 test: reduce auth choice fixture churn · openclaw/openclaw@857b9cd test: mock health status config boundaries · openclaw/openclaw@9d5ab4a test: mock onboard config io boundary · openclaw/openclaw@299694d test: mock legacy state plugin boundaries · openclaw/openclaw@2713089 test: mock channel install boundaries · openclaw/openclaw@b945248 test: mock doctor preview channel boundaries · openclaw/openclaw@b1a3ad4
fix(compaction): ignore stale persisted totalTokens in pr...
yetval · 2026-06-17 · via Recent Commits to openclaw:main
1+

import fs from "node:fs/promises";

2+

import os from "node:os";

3+

import path from "node:path";

4+

import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";

5+

import { testing as cliBackendsTesting } from "../../agents/cli-backends.js";

6+

import type { SessionEntry } from "../../config/sessions.js";

7+

import {

8+

clearMemoryPluginState,

9+

registerMemoryCapability,

10+

type MemoryFlushPlanResolver,

11+

} from "../../plugins/memory-state.js";

12+

import {

13+

runPreflightCompactionIfNeeded,

14+

setAgentRunnerMemoryTestDeps,

15+

} from "./agent-runner-memory.js";

16+

import { createTestFollowupRun, writeTestSessionStore } from "./agent-runner.test-fixtures.js";

17+

import type { ReplyOperation } from "./reply-run-registry.js";

18+19+

const compactEmbeddedAgentSessionMock = vi.fn();

20+21+

function createReplyOperation(): ReplyOperation {

22+

return {

23+

key: "test",

24+

sessionId: "session",

25+

abortSignal: new AbortController().signal,

26+

resetTriggered: false,

27+

phase: "queued",

28+

result: null,

29+

setPhase: vi.fn(),

30+

updateSessionId: vi.fn(),

31+

attachBackend: vi.fn(),

32+

detachBackend: vi.fn(),

33+

retainFailureUntilComplete: vi.fn(),

34+

complete: vi.fn(),

35+

completeThen: vi.fn((afterClear: () => void) => {

36+

afterClear();

37+

}),

38+

completeWithAfterClearBarrier: vi.fn(),

39+

fail: vi.fn(),

40+

abortByUser: vi.fn(),

41+

abortForRestart: vi.fn(),

42+

} as unknown as ReplyOperation;

43+

}

44+45+

function registerMemoryFlushPlanResolverForTest(resolver: MemoryFlushPlanResolver): void {

46+

registerMemoryCapability("memory-core", { flushPlanResolver: resolver });

47+

}

48+49+

describe("runPreflightCompactionIfNeeded stale totalTokens gating", () => {

50+

let rootDir = "";

51+52+

beforeEach(async () => {

53+

rootDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-preflight-stale-"));

54+

registerMemoryFlushPlanResolverForTest(() => ({

55+

softThresholdTokens: 4_000,

56+

forceFlushTranscriptBytes: 1_000_000_000,

57+

reserveTokensFloor: 20_000,

58+

prompt: "Pre-compaction memory flush.\nNO_REPLY",

59+

systemPrompt: "Write memory to memory/YYYY-MM-DD.md.",

60+

relativePath: "memory/2023-11-14.md",

61+

}));

62+

compactEmbeddedAgentSessionMock.mockReset().mockResolvedValue({

63+

ok: true,

64+

compacted: true,

65+

result: { tokensAfter: 42 },

66+

});

67+

setAgentRunnerMemoryTestDeps({

68+

compactEmbeddedAgentSession: compactEmbeddedAgentSessionMock as never,

69+

incrementCompactionCount: vi.fn() as never,

70+

refreshQueuedFollowupSession: vi.fn() as never,

71+

registerAgentRunContext: vi.fn() as never,

72+

emitAgentEvent: vi.fn() as never,

73+

});

74+

});

75+76+

afterEach(async () => {

77+

setAgentRunnerMemoryTestDeps();

78+

cliBackendsTesting.resetDepsForTest();

79+

clearMemoryPluginState();

80+

await fs.rm(rootDir, { recursive: true, force: true });

81+

});

82+83+

async function runWithEntry(sessionEntry: SessionEntry, sessionFile: string) {

84+

return await runPreflightCompactionIfNeeded({

85+

cfg: { agents: { defaults: { compaction: { memoryFlush: {} } } } },

86+

followupRun: createTestFollowupRun({

87+

sessionId: "session",

88+

sessionFile,

89+

sessionKey: "agent:main:main",

90+

}),

91+

defaultModel: "anthropic/claude-opus-4-6",

92+

agentCfgContextTokens: 100_000,

93+

sessionEntry,

94+

sessionStore: { "agent:main:main": sessionEntry },

95+

sessionKey: "agent:main:main",

96+

storePath: path.join(rootDir, "sessions.json"),

97+

isHeartbeat: false,

98+

replyOperation: createReplyOperation(),

99+

});

100+

}

101+102+

it("does not compact when totalTokens is large but stale and the real transcript is small", async () => {

103+

const sessionFile = path.join(rootDir, "session.jsonl");

104+

await fs.writeFile(

105+

sessionFile,

106+

`${JSON.stringify({ message: { role: "user", content: "x".repeat(2_000) } })}\n`,

107+

"utf8",

108+

);

109+

const sessionEntry: SessionEntry = {

110+

sessionId: "session",

111+

sessionFile,

112+

updatedAt: Date.now(),

113+

totalTokens: 200_000,

114+

totalTokensFresh: false,

115+

};

116+

await writeTestSessionStore(path.join(rootDir, "sessions.json"), "agent:main:main", sessionEntry);

117+118+

const entry = await runWithEntry(sessionEntry, sessionFile);

119+120+

expect(entry).toBe(sessionEntry);

121+

expect(compactEmbeddedAgentSessionMock).not.toHaveBeenCalled();

122+

});

123+124+

it("compacts when totalTokens is large and fresh", async () => {

125+

const sessionFile = path.join(rootDir, "session.jsonl");

126+

await fs.writeFile(

127+

sessionFile,

128+

`${JSON.stringify({ message: { role: "user", content: "x".repeat(2_000) } })}\n`,

129+

"utf8",

130+

);

131+

const sessionEntry: SessionEntry = {

132+

sessionId: "session",

133+

sessionFile,

134+

updatedAt: Date.now(),

135+

totalTokens: 200_000,

136+

totalTokensFresh: true,

137+

};

138+

await writeTestSessionStore(path.join(rootDir, "sessions.json"), "agent:main:main", sessionEntry);

139+140+

await runWithEntry(sessionEntry, sessionFile);

141+142+

expect(compactEmbeddedAgentSessionMock).toHaveBeenCalledTimes(1);

143+

});

144+

});