|
1 | 1 | // Tests direct runtime config overrides passed into agent runner execution. |
| 2 | +import { writeFile } from "node:fs/promises"; |
2 | 3 | import { join } from "node:path"; |
3 | 4 | import { beforeEach, describe, expect, it, vi } from "vitest"; |
4 | 5 | import { FailoverError } from "../../agents/failover-error.js"; |
5 | | -import { replaceSessionEntry } from "../../config/sessions/session-accessor.js"; |
| 6 | +import { SessionManager } from "../../agents/sessions/session-manager.js"; |
| 7 | +import { |
| 8 | + appendTranscriptMessage, |
| 9 | + loadSessionEntry, |
| 10 | + replaceSessionEntry, |
| 11 | +} from "../../config/sessions/session-accessor.js"; |
6 | 12 | import type { SessionParticipantIdentity } from "../../config/sessions/session-participant-identity.js"; |
7 | 13 | import type { SessionEntry } from "../../config/sessions/types.js"; |
| 14 | +import { |
| 15 | + clearMemoryPluginState, |
| 16 | + registerMemoryCapability, |
| 17 | +} from "../../plugins/memory-state.test-fixtures.js"; |
8 | 18 | import { prepareSessionParticipantInput } from "../../sessions/session-participant-input.js"; |
9 | | -import { createDeferredCore } from "../../shared/deferred.js"; |
10 | 19 | import { withTestDir } from "../../test-helpers/temp-dir.js"; |
11 | 20 | import { getReplyPayloadMetadata } from "../reply-payload.js"; |
12 | 21 | import type { TemplateContext } from "../templating.js"; |
13 | 22 | import { SILENT_REPLY_TOKEN } from "../tokens.js"; |
14 | | -import { createTestFollowupRun } from "./agent-runner.test-fixtures.js"; |
| 23 | +import { createTestFollowupRun, withTestModelContextTokens } from "./agent-runner.test-fixtures.js"; |
15 | 24 | import type { QueueSettings } from "./queue.js"; |
16 | 25 | import { resolveReplyOperationAgentTurn } from "./reply-operation-agent-turn-state.js"; |
17 | 26 | import { |
@@ -459,110 +468,127 @@ describe("runReplyAgent runtime config", () => { |
459 | 468 | expect(replyOperation.setPhase).toHaveBeenLastCalledWith("running"); |
460 | 469 | }); |
461 | 470 |
|
462 | | - it("rotates, rebinds, and optionally notifies when memory flush is exhausted", async () => { |
463 | | - await withTestDir({ prefix: "openclaw-direct-runtime-" }, async (tempDir) => { |
464 | | - const { replyParams, followupRun } = createDirectRuntimeReplyParams({ |
465 | | - shouldFollowup: false, |
466 | | - isActive: false, |
467 | | - }); |
468 | | - const sessionKey = "agent:main:telegram:default:direct:test"; |
469 | | - const sessionEntry: SessionEntry = { |
470 | | - sessionId: "session-1", |
471 | | - updatedAt: 1, |
472 | | - compactionCount: 4, |
473 | | - memoryFlush: { kind: "failed", failureCount: 2 }, |
474 | | - }; |
475 | | - const sessionStore = { [sessionKey]: sessionEntry }; |
476 | | - const storePath = join(tempDir, "sessions.json"); |
477 | | - await replaceSessionEntry({ storePath, sessionKey }, sessionEntry); |
478 | | - replyParams.sessionKey = sessionKey; |
479 | | - replyParams.storePath = storePath; |
480 | | - replyParams.sessionEntry = sessionEntry; |
481 | | - replyParams.sessionStore = sessionStore; |
482 | | - resolveQueuedReplyExecutionConfigMock.mockResolvedValue({ |
483 | | - ...freshCfg, |
484 | | - agents: { defaults: { compaction: { notifyUser: true } } }, |
485 | | - }); |
486 | | - const onBlockReply = vi.fn(); |
487 | | - replyParams.opts = { onBlockReply }; |
488 | | - const replyOperation = createReplyOperation(); |
489 | | - replyParams.replyOperation = replyOperation; |
490 | | - runSessionCompactionIfNeededMock.mockImplementation( |
491 | | - async (params: { sessionEntry?: unknown }) => params.sessionEntry, |
492 | | - ); |
493 | | - runMemoryFlushIfNeededMock.mockImplementation( |
494 | | - async (params: { |
495 | | - sessionEntry?: SessionEntry; |
496 | | - onVisibleErrorPayloads?: (payloads: Array<{ text?: string; isError?: boolean }>) => void; |
497 | | - }) => { |
498 | | - params.onVisibleErrorPayloads?.([ |
499 | | - { |
500 | | - text: "⚠️ Memory flush failed after 3 attempts; skipping for this cycle. It will retry after the next compaction.", |
501 | | - isError: true, |
502 | | - }, |
503 | | - ]); |
504 | | - return { |
505 | | - sessionEntry: { |
506 | | - ...params.sessionEntry, |
507 | | - memoryFlush: { kind: "failed", compactionCount: 4, failureCount: 3 }, |
508 | | - }, |
509 | | - outcome: "exhausted", |
510 | | - }; |
511 | | - }, |
512 | | - ); |
513 | | - const baselineSettlement = createDeferredCore(); |
514 | | - resetReplyRunSessionMock.mockImplementation(async (params: unknown) => { |
515 | | - const resetParams = params as { |
516 | | - activeSessionEntry?: SessionEntry; |
517 | | - activeSessionStore?: Record<string, SessionEntry>; |
518 | | - followupRun: typeof followupRun; |
519 | | - onActiveSessionEntry: (entry: SessionEntry) => void; |
520 | | - onNewSession: (sessionId: string, sessionFile: string) => void; |
521 | | - }; |
522 | | - const sessionFile = "/tmp/session-rotated.jsonl"; |
523 | | - const nextEntry = { |
524 | | - ...resetParams.activeSessionEntry, |
525 | | - sessionId: "session-rotated", |
| 471 | + it("preserves conversation after byte-forced memory exhaustion and unnecessary preflight", async () => { |
| 472 | + const memory = await vi.importActual<typeof import("./agent-runner-memory.js")>( |
| 473 | + "./agent-runner-memory.js", |
| 474 | + ); |
| 475 | + const reset = await vi.importActual<typeof import("./agent-runner-session-reset.js")>( |
| 476 | + "./agent-runner-session-reset.js", |
| 477 | + ); |
| 478 | + runMemoryFlushIfNeededMock.mockImplementation(memory.runMemoryFlushIfNeeded); |
| 479 | + runSessionCompactionIfNeededMock.mockImplementation(memory.runSessionCompactionIfNeeded); |
| 480 | + resetReplyRunSessionMock.mockImplementation(reset.resetReplyRunSession); |
| 481 | + registerMemoryCapability("memory-core", { |
| 482 | + flushPlanResolver: () => ({ |
| 483 | + softThresholdTokens: 4_000, |
| 484 | + forceFlushTranscriptBytes: 1, |
| 485 | + reserveTokensFloor: 20_000, |
| 486 | + prompt: "Save durable notes. NO_REPLY", |
| 487 | + systemPrompt: "Write memory to memory/notes.md.", |
| 488 | + relativePath: "memory/notes.md", |
| 489 | + }), |
| 490 | + }); |
| 491 | + try { |
| 492 | + await withTestDir({ prefix: "openclaw-direct-runtime-" }, async (tempDir) => { |
| 493 | + const { replyParams, followupRun } = createDirectRuntimeReplyParams({ |
| 494 | + shouldFollowup: false, |
| 495 | + isActive: false, |
| 496 | + }); |
| 497 | + const sessionKey = "agent:main:telegram:default:direct:test"; |
| 498 | + const sessionEntry: SessionEntry = { |
| 499 | + sessionId: "session-1", |
| 500 | + lifecycleRevision: "before-maintenance", |
526 | 501 | updatedAt: 1, |
527 | | - compactionCount: 0, |
| 502 | + totalTokens: 100, |
| 503 | + totalTokensFresh: true, |
| 504 | + totalTokensVersion: 1, |
| 505 | + compactionCount: 4, |
| 506 | + memoryFlush: { kind: "failed", failureCount: 2 }, |
528 | 507 | }; |
529 | | - if (resetParams.activeSessionStore) { |
530 | | - resetParams.activeSessionStore[sessionKey] = nextEntry; |
| 508 | + const sessionStore = { [sessionKey]: sessionEntry }; |
| 509 | + const storePath = join(tempDir, "sessions.json"); |
| 510 | + const scope = { agentId: "main", sessionId: sessionEntry.sessionId, sessionKey, storePath }; |
| 511 | + await replaceSessionEntry(scope, sessionEntry); |
| 512 | + const olderMessage = { role: "user", content: "Remember the older marker: amber-orchid" }; |
| 513 | + const messages = [ |
| 514 | + olderMessage, |
| 515 | + { role: "assistant", content: "Noted." }, |
| 516 | + ...Array.from({ length: 3 }, (_, index) => [ |
| 517 | + { role: "user", content: `Recent question ${index}` }, |
| 518 | + { role: "assistant", content: `Recent answer ${index}` }, |
| 519 | + ]).flat(), |
| 520 | + ]; |
| 521 | + for (const message of messages) { |
| 522 | + await appendTranscriptMessage(scope, { message }); |
531 | 523 | } |
532 | | - await replaceSessionEntry({ storePath, sessionKey }, nextEntry); |
533 | | - await baselineSettlement.promise; |
534 | | - resetParams.followupRun.run.sessionId = nextEntry.sessionId; |
535 | | - resetParams.followupRun.run.sessionFile = sessionFile; |
536 | | - resetParams.onActiveSessionEntry(nextEntry); |
537 | | - resetParams.onNewSession(nextEntry.sessionId, sessionFile); |
538 | | - return true; |
539 | | - }); |
| 524 | + // A file blocks the memory directory: optional maintenance fails without token pressure. |
| 525 | + await writeFile(join(tempDir, "memory"), "not a directory"); |
| 526 | + followupRun.run.workspaceDir = tempDir; |
| 527 | + followupRun.run.provider = "anthropic"; |
| 528 | + followupRun.run.model = "claude-sonnet-4-6"; |
| 529 | + replyParams.sessionKey = sessionKey; |
| 530 | + replyParams.storePath = storePath; |
| 531 | + replyParams.sessionEntry = sessionEntry; |
| 532 | + replyParams.sessionStore = sessionStore; |
| 533 | + resolveQueuedReplyExecutionConfigMock.mockResolvedValue( |
| 534 | + withTestModelContextTokens({ |
| 535 | + cfg: { agents: { defaults: { compaction: { notifyUser: true } } } }, |
| 536 | + followupRun, |
| 537 | + defaultModel: replyParams.defaultModel, |
| 538 | + contextTokens: 100_000, |
| 539 | + }), |
| 540 | + ); |
| 541 | + const onBlockReply = vi.fn(); |
| 542 | + replyParams.opts = { onBlockReply }; |
| 543 | + const replyOperation = createReplyOperation(); |
| 544 | + replyParams.replyOperation = replyOperation; |
| 545 | + executeAgentTurnMock.mockImplementation(async () => { |
| 546 | + expect(SessionManager.open(scope).buildSessionContext().messages).toEqual( |
| 547 | + messages.map((message) => expect.objectContaining(message)), |
| 548 | + ); |
| 549 | + return { |
| 550 | + runId: "runtime-config-test", |
| 551 | + outcome: { kind: "rejected", payload: { text: "main reply" } }, |
| 552 | + }; |
| 553 | + }); |
540 | 554 |
|
541 | | - const resultPromise = runReplyAgent(replyParams); |
542 | | - await vi.waitFor(() => expect(resetReplyRunSessionMock).toHaveBeenCalledOnce()); |
543 | | - expect(executeAgentTurnMock).not.toHaveBeenCalled(); |
544 | | - baselineSettlement.resolve(); |
545 | | - const result = await resultPromise; |
546 | | - |
547 | | - expect(result).toEqual({ text: "main reply" }); |
548 | | - expect(resetReplyRunSessionMock).toHaveBeenCalledOnce(); |
549 | | - expect(resetReplyRunSessionMock.mock.calls[0]?.[0]).toMatchObject({ |
550 | | - options: { |
551 | | - failureLabel: "memory flush exhaustion", |
552 | | - cleanupTranscripts: false, |
553 | | - }, |
554 | | - sessionKey, |
555 | | - queueKey: "main", |
| 555 | + const result = await runReplyAgent(replyParams); |
| 556 | + |
| 557 | + expect(result).toEqual({ text: "main reply" }); |
| 558 | + expect(resetReplyRunSessionMock).not.toHaveBeenCalled(); |
| 559 | + expect(followupRun.run.sessionId).toBe(sessionEntry.sessionId); |
| 560 | + expect(replyOperation.sessionId).toBe(sessionEntry.sessionId); |
| 561 | + expect(loadSessionEntry(scope)).toMatchObject({ |
| 562 | + sessionId: sessionEntry.sessionId, |
| 563 | + lifecycleRevision: sessionEntry.lifecycleRevision, |
| 564 | + compactionCount: 4, |
| 565 | + totalTokens: 100, |
| 566 | + totalTokensFresh: true, |
| 567 | + memoryFlush: { kind: "succeeded", compactionCount: 4 }, |
| 568 | + }); |
| 569 | + expect(sessionStore[sessionKey]).toMatchObject({ |
| 570 | + lifecycleRevision: sessionEntry.lifecycleRevision, |
| 571 | + compactionCount: 4, |
| 572 | + totalTokens: 100, |
| 573 | + }); |
| 574 | + expect(runMemoryFlushIfNeededMock).toHaveBeenCalledOnce(); |
| 575 | + await expect(runMemoryFlushIfNeededMock.mock.results[0]?.value).resolves.toMatchObject({ |
| 576 | + outcome: "exhausted", |
| 577 | + }); |
| 578 | + expect(runSessionCompactionIfNeededMock).toHaveBeenCalledOnce(); |
| 579 | + expect(runMemoryFlushIfNeededMock.mock.invocationCallOrder[0]).toBeLessThan( |
| 580 | + runSessionCompactionIfNeededMock.mock.invocationCallOrder[0]!, |
| 581 | + ); |
| 582 | + expect(onBlockReply).toHaveBeenCalledWith( |
| 583 | + expect.objectContaining({ |
| 584 | + text: "⚠️ Memory maintenance temporarily failed; continuing your reply.", |
| 585 | + }), |
| 586 | + ); |
| 587 | + expect(executeAgentTurnMock).toHaveBeenCalledOnce(); |
556 | 588 | }); |
557 | | - expect(followupRun.run.sessionId).toBe("session-rotated"); |
558 | | - expect(replyOperation.sessionId).toBe("session-rotated"); |
559 | | - expect(onBlockReply).toHaveBeenCalledWith( |
560 | | - expect.objectContaining({ |
561 | | - text: "⚠️ Memory maintenance temporarily failed; continuing your reply.", |
562 | | - }), |
563 | | - ); |
564 | | - expect(executeAgentTurnMock).toHaveBeenCalledOnce(); |
565 | | - }); |
| 589 | + } finally { |
| 590 | + clearMemoryPluginState(); |
| 591 | + } |
566 | 592 | }); |
567 | 593 |
|
568 | 594 | it("keeps the compacted session when preflight recovers an exhausted memory flush", async () => { |
@@ -593,53 +619,32 @@ describe("runReplyAgent runtime config", () => { |
593 | 619 | expect(executeAgentTurnMock).toHaveBeenCalledOnce(); |
594 | 620 | }); |
595 | 621 |
|
596 | | - it("rotates when preflight cannot recover an exhausted memory flush", async () => { |
597 | | - const { replyParams } = createDirectRuntimeReplyParams({ |
598 | | - shouldFollowup: false, |
599 | | - isActive: false, |
600 | | - }); |
601 | | - runMemoryFlushIfNeededMock.mockResolvedValue({ |
602 | | - sessionEntry: { sessionId: "session-1", updatedAt: 1, compactionCount: 4 }, |
603 | | - outcome: "exhausted", |
604 | | - }); |
605 | | - runSessionCompactionIfNeededMock.mockRejectedValue( |
606 | | - new Error("Preflight compaction required but failed: context_overflow"), |
607 | | - ); |
608 | | - |
609 | | - await expect(runReplyAgent(replyParams)).resolves.toEqual({ text: "main reply" }); |
610 | | - |
611 | | - expect(resetReplyRunSessionMock).toHaveBeenCalledOnce(); |
612 | | - expect(resetReplyRunSessionMock.mock.calls[0]?.[0]).toMatchObject({ |
613 | | - options: { |
614 | | - failureLabel: "memory flush exhaustion", |
615 | | - cleanupTranscripts: false, |
616 | | - }, |
617 | | - }); |
618 | | - expect(executeAgentTurnMock).toHaveBeenCalledOnce(); |
619 | | - }); |
620 | | - |
621 | | - it("surfaces unrelated preflight failures after an exhausted memory flush", async () => { |
622 | | - const { replyParams } = createDirectRuntimeReplyParams({ |
623 | | - shouldFollowup: false, |
624 | | - isActive: false, |
625 | | - }); |
626 | | - runMemoryFlushIfNeededMock.mockResolvedValue({ |
627 | | - sessionEntry: { sessionId: "session-1", updatedAt: 1, compactionCount: 4 }, |
628 | | - outcome: "exhausted", |
629 | | - }); |
630 | | - runSessionCompactionIfNeededMock.mockRejectedValue( |
631 | | - new Error("Preflight compaction required but failed: auth profile mismatch"), |
632 | | - ); |
| 622 | + it.each(["context_overflow", "auth profile mismatch"])( |
| 623 | + "surfaces required preflight failure (%s) after memory exhaustion without resetting", |
| 624 | + async (reason) => { |
| 625 | + const { replyParams } = createDirectRuntimeReplyParams({ |
| 626 | + shouldFollowup: false, |
| 627 | + isActive: false, |
| 628 | + }); |
| 629 | + runMemoryFlushIfNeededMock.mockResolvedValue({ |
| 630 | + sessionEntry: { sessionId: "session-1", updatedAt: 1, compactionCount: 4 }, |
| 631 | + outcome: "exhausted", |
| 632 | + }); |
| 633 | + runSessionCompactionIfNeededMock.mockRejectedValue( |
| 634 | + new Error(`Preflight compaction required but failed: ${reason}`), |
| 635 | + ); |
633 | 636 |
|
634 | | - const result = await runReplyAgent(replyParams); |
| 637 | + const result = await runReplyAgent(replyParams); |
635 | 638 |
|
636 | | - if (!result || Array.isArray(result)) { |
637 | | - throw new Error("expected a single preflight compaction failure reply payload"); |
638 | | - } |
639 | | - expect(result.text).toContain("auto-compaction could not recover"); |
640 | | - expect(resetReplyRunSessionMock).not.toHaveBeenCalled(); |
641 | | - expect(executeAgentTurnMock).not.toHaveBeenCalled(); |
642 | | - }); |
| 639 | + if (!result || Array.isArray(result)) { |
| 640 | + throw new Error("expected a single preflight compaction failure reply payload"); |
| 641 | + } |
| 642 | + expect(result.text).toContain("auto-compaction could not recover"); |
| 643 | + expect(getReplyPayloadMetadata(result)?.deliverDespiteSourceReplySuppression).toBe(true); |
| 644 | + expect(resetReplyRunSessionMock).not.toHaveBeenCalled(); |
| 645 | + expect(executeAgentTurnMock).not.toHaveBeenCalled(); |
| 646 | + }, |
| 647 | + ); |
643 | 648 |
|
644 | 649 | it.each(["abortByUser", "abortForRestart"] as const)( |
645 | 650 | "records %s during memory flush as cancellation without starting the main turn", |
|
0 commit comments