Files
openclaw/src/commands/agent.session.test.ts
Peter Steinberger 4273ca9dbd refactor(sessions): remove file-era transcript runtime (#113233)
* refactor(sessions): keep helper transcripts in memory

* refactor(sessions): remove file-era transcript storage

* test(sessions): use SQLite identity in attempt persistence

* test(codex): isolate legacy transcript fixtures

* fix(sessions): preserve SQLite transcript identity

* fix(sessions): harden transcript lifecycle invariants

* fix(sessions): validate transcript identities

* fix(sessions): close identity compatibility gaps

* fix(sessions): preserve leaf and plugin identities

* fix(sessions): retain dispatch transcript targets

* fix(sessions): preserve active transcript context

* fix(sessions): isolate artifact accounting

* fix(sessions): bound SQLite usage accounting

* fix(sessions): retain bounded latest usage

* fix(sessions): align rebased transcript targets

* test(sessions): align accessor scope fixture

* fix(telegram): derive SQLite transcript identity

* refactor(sessions): remove file-era compaction residue

* chore(sessions): lower max-lines baseline

* fix(sessions): preserve structured transcript identity

* test(sessions): align doctor identity assertions

* fix(sessions): isolate default SDK database

* refactor(sessions): remove dead file-era exports

* fix(sessions): reconcile SQLite transcript identity

* fix(sessions): pass checkpoint identity explicitly

* test(sessions): make entry field probe explicit

* test(sessions): satisfy transcript cleanup lint

* test(sessions): align diagnostics identity proof

* fix(sessions): finish transcript runtime teardown

* fix(sessions): preserve transcript identity invariants

* fix(sessions): harden transcript compatibility edges

* fix(sessions): preserve checkpoint transcript anchors

* fix(sessions): preserve SQLite lifecycle invariants

* fix(sessions): retarget compaction successors

* test(sessions): preserve transcript fixture semantics

* feat(plugin-sdk): add command transcript targets

* fix(sessions): serialize transcript rewrites

* fix(sessions): validate legacy successor identity

* fix(sessions): normalize compaction ownership

* fix(sessions): validate successor identity before adoption

* fix(sessions): preserve plugin transcript ownership

* fix(sessions): carry transcript identity through commands

* fix(sessions): import legacy checkpoint artifacts into SQLite

* fix(sessions): preserve successor transcript ownership

* fix(sessions): align transcript consumers with target identity

* fix(sessions): scope transcript token estimates

* fix(sessions): retain agent identity across lifecycle hooks

* fix(sessions): resolve scoped SQLite targets

* fix(sessions): isolate lifecycle transcript targets

* fix(sessions): validate compaction agent ownership

* fix(sessions): preserve reset and cleanup lifecycle

* fix(sessions): serialize prompt cleanup lifecycle

* fix(sessions): remove stale lock import

* fix(sessions): preserve reset target context

* fix(sessions): fence prompt reload takeover

* fix(sessions): unblock abort and default lifecycle reads

* fix(sessions): validate legacy successor scope

* fix(sessions): reject metadata-only runtime rows

* fix(sessions): propagate custom transcript stores

* fix(sessions): preserve adopted retry targets

* fix(sessions): allow unkeyed usage reads

* fix(sessions): harden runtime target boundaries

* fix(sessions): serialize retry transcript writes

* fix(sessions): bound prompt reload disposal

* fix(sessions): complete retry marker identity

* fix(sessions): keep legacy marker identity minimal

* test(sessions): tighten teardown fixture types

* fix(sessions): preserve compatibility target identity

* test(sessions): persist post-checkpoint boundary turn

* test(sessions): align runtime store mock contracts

* style(sessions): simplify persisted identity guard

* fix(sessions): prefer complete typed targets

* fix(sessions): recover legacy marker targets

* test(sessions): align marker lookup fixture scope

* fix(sessions): validate partial transcript targets

* fix(sessions): reconcile partial transcript identities

* fix(sessions): canonicalize compatibility identities

* test(sessions): cover compatibility aliases

* fix(sessions): adopt legacy successor identity

* fix(sessions): preserve usage read identity

* fix(sessions): preserve partial marker compatibility

* fix(sessions): validate legacy successor mappings

* fix(sessions): reconcile marker store mappings

* fix(sessions): preserve legacy fallback identity

* fix(sessions): harden marker alias resolution

* fix(sessions): prefer verified successor aliases

* fix(sessions): resolve preferred marker aliases

* fix(sessions): serialize cleanup admission

* fix(sessions): align marker lookup scopes

* fix(codex): type marker alias summaries

* style(sessions): satisfy changed lint

* test(sessions): align structured target assertions

* fix(sessions): reconcile latest identity contracts

* fix(sessions): validate transcript identity boundaries

* docs(sessions): explain stable registry keys

* fix(sessions): harden compatibility target round trips

* fix(sessions): port usage identity to split modules

* test(sessions): align subagent transcript identity

* fix(sessions): finish transcript identity migration

* fix(agents): route subagent completion capture through transcript targets

* fix(agents): settle SQLite prompt handoff during cleanup

* chore: shrink max-lines baseline after teardown

* fix(sessions): port teardown across split runtime owners

* fix(sessions): carry transcript targets through split owners

* test(agents): use SQLite compaction target in abort coverage

* chore: retain unrelated max-lines suppressions

* chore: shrink max-lines baseline after main splits

* style(agents): const compaction checkpoint locals

* fix(sessions): harden SQLite teardown boundaries

* test(sessions): use typed metadata in predicate isolation fixture

* test(agents): cover malformed settlement rejections lint-safely

* fix(sessions): close remaining SQLite identity races

* fix(agents): fail closed on incomplete successor targets

* fix(sessions): preserve transcript identity fallbacks

* fix(agents): preserve session-key abort admission

* fix(trajectory): validate incomplete export targets

* test(sessions): drop retired pricing cache imports

* fix(sessions): validate partial transcript identities

* fix(sessions): close transcript identity edge cases

* fix(plugins): reserve retired transcript locator slot

* fix(sessions): scope transcript locks by target

* style(sessions): simplify SDK initialization error

* fix(sessions): preserve initialized transcript state

* fix(codex): verify mirrored history session keys

* fix(sessions): reject stale transcript ownership

* fix(sessions): anchor asynchronous transcript ownership

* fix(sessions): measure active transcript state

* fix(sessions): preserve scoped transcript compaction

* fix(sessions): harden transcript identity and lifecycle

* fix(sessions): resolve scoped command transcript stores

* fix(sessions): make transcript appends failure-atomic

* fix(sessions): enforce scoped transcript ownership

* fix(sessions): reject cross-owner transcript handoffs

* fix(sessions): fence cleanup transcript ownership

* fix(sessions): retire stale write ownership contexts

* fix(sessions): preserve pending session migration state

* fix(sessions): validate migrated transcript ownership

* fix(sessions): validate usage transcript targets

* fix(sessions): clear predecessor transcript metadata

* fix(sessions): align durable session event targets

* fix(sessions): fence late prompt handoffs

* fix(sessions): fence lifecycle transcript fallbacks

* fix(sessions): bound zero-length memory capture

* fix(sessions): preserve transcript teardown ownership

* fix(sessions): reject duplicate cleanup ownership

* fix(sessions): serialize runtime writes with sqlite leases

* fix(sessions): close sqlite teardown concurrency gaps

* fix(sessions): preserve nested lifecycle failures

* fix(sessions): canonicalize sqlite transcript ownership

* fix(sessions): settle disposed prompt handoffs

* fix(sessions): resolve canonical attempt lock targets

* test(sessions): align canonical target fixtures

* test(sessions): retire redundant jsonl parser coverage

* refactor(sessions): split active transcript cursors

* test(memory): retire legacy marker fixture

* fix(sessions): preserve canonical transcript access after rebase

* fix(sessions): fence prompt lease and return transcript targets

* fix(sessions): colocate transcript leases with target store

* fix(sessions): canonicalize transcript lease and worker targets

* fix(sessions): preserve plugin and fork identity markers

* fix(sessions): complete sqlite transcript target migration

* fix(sessions): integrate canonical followup identity

* fix(sessions): preserve bounded transcript topology

* fix(sessions): validate transcript identity boundaries

* fix(context): separate caller and successor targets

* test(sessions): split persistence compatibility coverage

* test(sessions): preserve fixture topology efficiently

* chore(sdk): refresh plugin api baseline

* test(agents): align compaction lock target mocks

* test(sessions): seed malformed transcript fixtures directly

* fix(agents): canonicalize transcript compatibility inputs

* fix(agents): type optional tool result ids

* test(ci): stabilize loaded process timing

* test(tui): wait for collect queue admission
2026-07-27 22:33:24 -04:00

367 lines
14 KiB
TypeScript

// Agent session command tests cover session resolution, agent scoping, and temp-home session stores.
import path from "node:path";
import { withTempHome as withTempHomeBase } from "openclaw/plugin-sdk/test-env";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { resolveAgentDir, resolveSessionAgentId } from "../agents/agent-scope.js";
import { resolveSession } from "../agents/command/session.js";
import {
appendTranscriptEvent,
loadSessionEntry,
replaceSessionEntry,
} from "../config/sessions/session-accessor.js";
import { clearSessionStoreCacheForTest } from "../config/sessions/store-writer-state.js";
import { resolveSessionTranscriptFile } from "../config/sessions/transcript.js";
import type { SessionEntry } from "../config/sessions/types.js";
import type { OpenClawConfig } from "../config/types.openclaw.js";
import { buildOutboundSessionContext } from "../infra/outbound/session-context.js";
import { normalizeSessionDeliveryState } from "../utils/delivery-context.shared.js";
async function withTempHome<T>(fn: (home: string) => Promise<T>): Promise<T> {
return withTempHomeBase(fn, {
prefix: "openclaw-agent-session-",
skipSessionCleanup: true,
});
}
function mockConfig(
home: string,
storePath: string,
agentsList?: Array<{ id: string; default?: boolean }>,
): OpenClawConfig {
return {
agents: {
defaults: {
model: { primary: "anthropic/claude-opus-4-6" },
models: { "anthropic/claude-opus-4-6": {} },
workspace: path.join(home, "openclaw"),
},
list: agentsList,
},
session: { store: storePath, mainKey: "main" },
} as OpenClawConfig;
}
async function writeSessionStoreSeed(
storePath: string,
sessions: Record<string, SessionEntry>,
): Promise<void> {
await Promise.all(
Object.entries(sessions).map(([sessionKey, entry]) =>
replaceSessionEntry({ sessionKey, storePath }, entry),
),
);
}
async function withCrossAgentResumeFixture(
run: (params: { sessionId: string; sessionKey: string; cfg: OpenClawConfig }) => Promise<void>,
): Promise<void> {
await withTempHome(async (home) => {
const storePattern = path.join(home, "agents", "{agentId}", "sessions", "sessions.json");
const execStore = path.join(home, "agents", "exec", "sessions", "sessions.json");
const sessionId = "session-exec-hook";
const sessionKey = "agent:exec:hook:gmail:thread-1";
await writeSessionStoreSeed(execStore, {
[sessionKey]: {
sessionId,
updatedAt: Date.now(),
systemSent: true,
},
});
const cfg = mockConfig(home, storePattern, [{ id: "dev" }, { id: "exec", default: true }]);
await run({ sessionId, sessionKey, cfg });
});
}
beforeEach(() => {
clearSessionStoreCacheForTest();
// Freshness fixtures seed times relative to Date.now(); near the 04:00
// local daily-reset boundary the seeded window straddles it and reuse
// scenarios flip to new sessions. Pin local noon so no timezone can hit it.
vi.useFakeTimers({ toFake: ["Date"] });
const localNoon = new Date();
localNoon.setHours(12, 0, 0, 0);
vi.setSystemTime(localNoon);
});
afterEach(() => {
vi.useRealTimers();
});
describe("agent session resolution", () => {
it("creates a stable session key for explicit session-id-only runs", async () => {
await withTempHome(async (home) => {
const store = path.join(home, "sessions.json");
const cfg = mockConfig(home, store);
const resolution = resolveSession({ cfg, sessionId: "explicit-session-123" });
expect(resolution.sessionKey).toBe("agent:main:explicit:explicit-session-123");
expect(resolution.sessionId).toBe("explicit-session-123");
});
});
it("uses the resumed session agent scope when sessionId resolves to another agent store", async () => {
await withCrossAgentResumeFixture(async ({ sessionId, sessionKey, cfg }) => {
const resolution = resolveSession({ cfg, sessionId });
expect(resolution.sessionKey).toBe(sessionKey);
const agentId = resolveSessionAgentId({ sessionKey: resolution.sessionKey, config: cfg });
expect(agentId).toBe("exec");
expect(resolveAgentDir(cfg, agentId)).toContain(
`${path.sep}agents${path.sep}exec${path.sep}agent`,
);
});
});
it("resolves duplicate cross-agent sessionIds deterministically", async () => {
await withTempHome(async (home) => {
const storePattern = path.join(home, "agents", "{agentId}", "sessions", "sessions.json");
const otherStore = path.join(home, "agents", "other", "sessions", "sessions.json");
const retiredStore = path.join(home, "agents", "retired", "sessions", "sessions.json");
await writeSessionStoreSeed(otherStore, {
"agent:other:main": {
sessionId: "run-dup",
updatedAt: Date.now() + 1_000,
},
});
await writeSessionStoreSeed(retiredStore, {
"agent:retired:acp:run-dup": {
sessionId: "run-dup",
updatedAt: Date.now(),
},
});
const cfg = mockConfig(home, storePattern, [
{ id: "other" },
{ id: "retired", default: true },
]);
const resolution = resolveSession({ cfg, sessionId: "run-dup" });
expect(resolution.sessionKey).toBe("agent:retired:acp:run-dup");
expect(resolution.storePath).toBe(retiredStore);
});
});
it("uses origin.provider for channel-specific session reset overrides", async () => {
await withTempHome(async (home) => {
const store = path.join(home, "sessions.json");
await writeSessionStoreSeed(store, {
main: {
sessionId: "origin-provider-reset",
updatedAt: Date.now() - 30 * 60_000,
delivery: normalizeSessionDeliveryState({
context: { channel: "quietchat" },
origin: { provider: "quietchat" },
}),
},
});
const cfg = mockConfig(home, store);
cfg.session = {
...cfg.session,
reset: { mode: "idle", idleMinutes: 10 },
resetByChannel: {
quietchat: { mode: "idle", idleMinutes: 120 },
},
};
const resolution = resolveSession({ cfg, sessionKey: "main" });
expect(resolution.sessionId).toBe("origin-provider-reset");
expect(resolution.isNewSession).toBe(false);
});
});
it("handles terminal main sessions whose transcript is newer than the registry", async () => {
const scenarios = [
{
label: "canonical done main",
mainKey: "main",
sessionKey: "agent:main:main",
status: "done" as const,
expectNewSession: false,
},
{
label: "raw done main alias",
mainKey: "main",
sessionKey: "main",
status: "done" as const,
expectNewSession: false,
},
{
label: "custom done main alias",
mainKey: "work",
sessionKey: "agent:main:main",
status: "done" as const,
expectNewSession: false,
},
{
label: "killed main",
mainKey: "main",
sessionKey: "agent:main:main",
status: "killed" as const,
expectNewSession: true,
},
{
label: "endedAt-only main",
mainKey: "main",
sessionKey: "agent:main:main",
status: undefined,
expectNewSession: true,
},
] as const;
for (const scenario of scenarios) {
await withTempHome(async (home) => {
const store = path.join(home, "sessions.json");
const sessionFile = path.join(home, `session-${scenario.label.replaceAll(" ", "-")}.jsonl`);
const sessionId = `stale-terminal-${scenario.label.replaceAll(" ", "-")}`;
const registryUpdatedAt = Date.now() - 10_000;
await writeSessionStoreSeed(store, {
[scenario.sessionKey]: {
sessionId,
sessionFile,
updatedAt: registryUpdatedAt,
...(scenario.status ? { status: scenario.status } : {}),
sessionStartedAt: registryUpdatedAt - 60_000,
lastInteractionAt: registryUpdatedAt - 30_000,
startedAt: registryUpdatedAt - 1_000,
endedAt: registryUpdatedAt - 100,
cliSessionBindings: {
"claude-cli": { sessionId: "old-claude-cli-session" },
"codex-cli": { sessionId: "old-codex-cli-session" },
},
cliSessionIds: {
"claude-cli": "old-claude-cli-session",
"codex-cli": "old-codex-cli-session",
},
claudeCliSessionId: "old-claude-cli-session",
},
});
await appendTranscriptEvent(
{
agentId: "main",
sessionId,
sessionKey: scenario.sessionKey,
storePath: store,
},
{ type: "custom", timestamp: "1970-01-01T00:00:00.001Z" },
);
const cfg = mockConfig(home, store);
cfg.session = { ...cfg.session, mainKey: scenario.mainKey };
const resolution = resolveSession({ cfg, sessionKey: scenario.sessionKey });
expect(resolution.isNewSession).toBe(scenario.expectNewSession);
if (!scenario.expectNewSession) {
expect(resolution.sessionId).toBe(sessionId);
return;
}
expect(resolution.sessionId).not.toBe(sessionId);
expect(resolution.sessionEntry?.sessionFile).toBeUndefined();
expect(resolution.sessionEntry?.status).toBeUndefined();
expect(resolution.sessionEntry?.startedAt).toBeUndefined();
expect(resolution.sessionEntry?.endedAt).toBeUndefined();
expect(resolution.sessionEntry?.runtimeMs).toBeUndefined();
expect(resolution.sessionEntry?.sessionStartedAt).toBeUndefined();
expect(resolution.sessionEntry?.lastInteractionAt).toBeUndefined();
expect(resolution.sessionEntry?.cliSessionBindings).toBeUndefined();
expect(resolution.sessionEntry?.cliSessionIds).toBeUndefined();
expect(resolution.sessionEntry?.claudeCliSessionId).toBeUndefined();
});
}
});
it("preserves explicit session-id resumes for stale terminal main rows", async () => {
await withTempHome(async (home) => {
const store = path.join(home, "sessions.json");
const sessionFile = path.join(home, "explicit-terminal-main.jsonl");
const sessionId = "explicit-terminal-main";
const registryUpdatedAt = Date.now() - 10_000;
await writeSessionStoreSeed(store, {
"agent:main:main": {
sessionId,
sessionFile,
updatedAt: registryUpdatedAt,
status: "done",
startedAt: registryUpdatedAt - 1_000,
endedAt: registryUpdatedAt - 100,
runtimeMs: 900,
},
});
await appendTranscriptEvent(
{
agentId: "main",
sessionId,
sessionKey: "agent:main:main",
storePath: store,
},
{ type: "custom", timestamp: "1970-01-01T00:00:00.001Z" },
);
const cfg = mockConfig(home, store);
const resolution = resolveSession({ cfg, sessionId });
expect(resolution.sessionKey).toBe("agent:main:main");
expect(resolution.sessionId).toBe(sessionId);
expect(resolution.isNewSession).toBe(false);
expect(resolution.sessionEntry).not.toHaveProperty("sessionFile");
expect(resolution.sessionEntry?.status).toBe("done");
expect(resolution.sessionEntry?.startedAt).toBe(registryUpdatedAt - 1_000);
expect(resolution.sessionEntry?.endedAt).toBe(registryUpdatedAt - 100);
expect(resolution.sessionEntry?.runtimeMs).toBe(900);
if (!resolution.sessionKey || !resolution.sessionStore) {
throw new Error("expected resolved explicit session store");
}
const resolvedTranscript = await resolveSessionTranscriptFile({
sessionId: resolution.sessionId,
sessionKey: resolution.sessionKey,
sessionEntry: resolution.sessionEntry,
sessionStore: resolution.sessionStore,
storePath: resolution.storePath,
agentId: "main",
});
expect(resolvedTranscript.sessionFile).toBe(resolution.sessionKey);
await expect(
resolveSessionTranscriptFile({
sessionId: resolution.sessionId,
sessionKey: resolution.sessionKey,
sessionEntry: undefined,
sessionStore: resolution.sessionStore,
storePath: resolution.storePath,
agentId: "main",
}),
).resolves.toMatchObject({
sessionEntry: expect.objectContaining({ sessionId }),
});
const persisted = loadSessionEntry({
sessionKey: resolution.sessionKey,
storePath: resolution.storePath,
});
expect(persisted?.sessionId).toBe(sessionId);
expect(persisted).not.toHaveProperty("sessionFile");
expect(persisted?.status).toBe("done");
expect(persisted?.startedAt).toBe(registryUpdatedAt - 1_000);
expect(persisted?.endedAt).toBe(registryUpdatedAt - 100);
expect(persisted?.runtimeMs).toBe(900);
});
});
it("forwards resolved outbound session context when resuming by sessionId", async () => {
await withCrossAgentResumeFixture(async ({ sessionId, sessionKey, cfg }) => {
const resolution = resolveSession({ cfg, sessionId });
expect(resolution.sessionKey).toBe(sessionKey);
const agentId = resolveSessionAgentId({ sessionKey: resolution.sessionKey, config: cfg });
const outboundContext = buildOutboundSessionContext({
cfg,
sessionKey: resolution.sessionKey,
agentId,
});
if (!outboundContext) {
throw new Error("expected outbound session context");
}
expect(outboundContext.key).toBe(sessionKey);
expect(outboundContext.agentId).toBe("exec");
});
});
});