Files
openclaw/src/commitments/commitments-full-chain.integration.test.ts
Peter Steinberger edecdbd05e refactor(config): config-surface reduction tranche 3 — product consolidations (review request) (#111527)
* refactor(config): consolidate media model lists

* refactor(config): unify memory configuration

* refactor(config): consolidate TTS ownership

* refactor(config): move typing policy to agents

* refactor(config): retire product-level config surfaces

* refactor(config): share scoped tool policy type

* chore(config): refresh generated baselines

* fix(config): honor agent typing overrides

* fix(config): migrate sibling config consumers

* refactor(infra): keep base64url decoder private

* fix(config): strip invalid legacy TTS values

* chore(config): refresh rebased baseline hash

* fix(doctor): route legacy messages.tts.realtime voice to talk during tts move

* refactor(config): polish final layout names

* refactor(config): freeze retired tuning defaults

* feat(config): add fast mode default symmetry

* refactor(config): key agent entries by id

* docs(config): update final layout reference

* test(config): cover final layout migrations

* chore(config): refresh final layout baselines

* fix(config): align final layout runtime readers

* fix(config): align remaining readers

* fix(config): stabilize final layout migrations

* fix(config): finalize config projection proof

* fix(config): address final layout review

* docs(release): preserve historical config names

* fix(config): complete keyed agent migration

* fix(config): close final migration gaps

* fix(config): finish full-branch review

* fix(config): complete runtime secret detection

* fix(config): close final review findings

* fix(config): finish canonical docs and heartbeat migration

* fix(config): integrate latest main after rebase

* refactor(env): isolate test-only controls

* refactor(env): isolate build and development controls

* refactor(env): collapse process identity indirection

* refactor(env): remove duplicate config and temp aliases

* docs(env): define the operator-facing allowlist

* ci(env): ratchet production variable count

* fix(env): remove stale provider helper import

* fix(env): make ratchet sorting explicit

* test(env): keep test seam in dead-code audit

* test(env): cover ratchet growth and boundary; document surface budgets

* docs(config): document tier-eval consolidations

* docs(config): clarify speech preference ownership

* test(memory): align retired tuning fixtures

* refactor(memory): freeze engine heuristics

* refactor(config): apply tier-eval tranche

* refactor(tts): move persona shaping to providers

* refactor(compaction): move prompt policy to providers

* test(config): align hookified prompt fixtures

* chore(deadcode): classify test-only exports

* chore(github): remove unused spawn helper

* chore(deadcode): classify queue diagnostics

* chore(deadcode): remove unused lane snapshot export

* chore(plugin-sdk): ratchet consolidated surface

* fix(config): integrate latest main after rebase
2026-07-21 20:28:43 -07:00

200 lines
7.4 KiB
TypeScript

// Exercises the full commitment extraction-to-follow-up chain.
import { afterEach, describe, expect, it, vi } from "vitest";
import type { OpenClawConfig } from "../config/config.js";
import { runHeartbeatOnce } from "../infra/heartbeat-runner.js";
import { installHeartbeatRunnerTestRuntime } from "../infra/heartbeat-runner.test-harness.js";
import {
seedSessionStore,
withTempHeartbeatSandbox,
} from "../infra/heartbeat-runner.test-utils.js";
import { closeOpenClawStateDatabaseForTest } from "../state/openclaw-state-db.js";
import { withEnvAsync } from "../test-utils/env.js";
import { enqueueCommitmentExtraction } from "./runtime.js";
import {
configureCommitmentExtractionRuntime,
drainCommitmentExtractionQueue,
resetCommitmentExtractionRuntimeForTests,
} from "./runtime.test-support.js";
import { readCommitmentsForTest } from "./store.test-utils.js";
import type { CommitmentExtractionBatchResult, CommitmentExtractionItem } from "./types.js";
vi.mock("./config.js", async (importOriginal) => ({
...(await importOriginal<typeof import("./config.js")>()),
resolveCommitmentsConfig: () => ({
enabled: true,
maxPerDay: 3,
extraction: {
debounceMs: 15_000,
batchMaxItems: 8,
queueMaxItems: 64,
confidenceThreshold: 0.72,
careConfidenceThreshold: 0.86,
timeoutSeconds: 45,
},
}),
}));
installHeartbeatRunnerTestRuntime();
describe("commitments full-chain integration", () => {
const writeMs = Date.parse("2026-04-29T16:00:00.000Z");
const dueMs = writeMs + 10 * 60_000;
afterEach(() => {
closeOpenClawStateDatabaseForTest();
resetCommitmentExtractionRuntimeForTests();
vi.useRealTimers();
vi.unstubAllEnvs();
});
it("flows from hidden extraction to stored commitment to scoped heartbeat delivery", async () => {
vi.useFakeTimers();
vi.setSystemTime(writeMs);
await withTempHeartbeatSandbox(async ({ tmpDir, storePath, replySpy }) => {
await withEnvAsync({ OPENCLAW_STATE_DIR: tmpDir }, async () => {
const sessionKey = "agent:main:telegram:user-155462274";
const cfg: OpenClawConfig = {
agents: {
defaults: {
workspace: tmpDir,
heartbeat: {
every: "5m",
target: "last",
},
},
},
channels: { telegram: { allowFrom: ["*"] } },
session: { store: storePath },
};
await seedSessionStore(storePath, sessionKey, {
lastChannel: "telegram",
lastProvider: "telegram",
lastTo: "stale-target",
});
configureCommitmentExtractionRuntime({
forceInTests: true,
extractBatch: vi.fn(
async ({
items,
}: {
items: CommitmentExtractionItem[];
}): Promise<CommitmentExtractionBatchResult> => ({
candidates: (() => {
const [firstItem] = items;
if (!firstItem) {
throw new Error("Expected commitment extraction item");
}
return [
{
itemId: firstItem.itemId,
kind: "event_check_in",
sensitivity: "routine",
source: "inferred_user_context",
reason: "The user mentioned an interview happening today.",
suggestedText: "How did the interview go?",
dedupeKey: "interview:2026-04-29",
confidence: 0.93,
dueWindow: {
earliest: new Date(dueMs).toISOString(),
latest: new Date(dueMs + 60 * 60_000).toISOString(),
timezone: "America/Los_Angeles",
},
},
];
})(),
}),
),
setTimer: () => ({ unref() {} }) as ReturnType<typeof setTimeout>,
clearTimer: () => undefined,
});
expect(
enqueueCommitmentExtraction({
cfg,
nowMs: writeMs,
agentId: "main",
sessionKey,
channel: "telegram",
accountId: "primary",
to: "155462274",
sourceMessageId: "qa-message-1",
userText: "I have an interview later today.",
assistantText: "Good luck, I hope it goes well.",
}),
).toBe(true);
await expect(drainCommitmentExtractionQueue()).resolves.toBe(1);
const pendingCommitments = readCommitmentsForTest();
expect(pendingCommitments).toHaveLength(1);
const [pendingCommitment] = pendingCommitments;
if (!pendingCommitment) {
throw new Error("Expected pending commitment");
}
expect(pendingCommitment.status).toBe("pending");
expect(pendingCommitment.agentId).toBe("main");
expect(pendingCommitment.sessionKey).toBe(sessionKey);
expect(pendingCommitment.channel).toBe("telegram");
expect(pendingCommitment.to).toBe("155462274");
expect(pendingCommitment.suggestedText).toBe("How did the interview go?");
expect(pendingCommitment.dueWindow.earliestMs).toBe(dueMs);
expect(pendingCommitment).not.toHaveProperty("sourceUserText");
expect(pendingCommitment).not.toHaveProperty("sourceAssistantText");
vi.setSystemTime(dueMs + 60_000);
const sendTelegram = vi.fn().mockResolvedValue({
messageId: "m1",
chatId: "155462274",
});
replySpy.mockImplementation(
async (
ctx: { Body?: string; OriginatingChannel?: string; OriginatingTo?: string },
opts?: { disableTools?: boolean },
) => {
if (!opts) {
throw new Error("Expected commitment heartbeat reply options");
}
expect(ctx.Body).toContain("Due inferred follow-up commitments");
expect(ctx.Body).toContain("How did the interview go?");
expect(ctx.Body).not.toContain("I have an interview later today.");
expect(ctx.Body).not.toContain("Good luck, I hope it goes well.");
expect(ctx.OriginatingChannel).toBe("telegram");
expect(ctx.OriginatingTo).toBe("155462274");
expect(opts.disableTools).toBe(true);
return { text: "How did the interview go?" };
},
);
const result = await runHeartbeatOnce({
cfg,
agentId: "main",
sessionKey,
deps: {
getReplyFromConfig: replySpy,
telegram: sendTelegram,
getQueueSize: () => 0,
nowMs: () => dueMs + 60_000,
},
});
expect(result.status).toBe("ran");
expect(sendTelegram).toHaveBeenCalledOnce();
const sendCall = sendTelegram.mock.calls[0];
if (!sendCall) {
throw new Error("Expected Telegram send call");
}
expect(sendCall[0]).toBe("155462274");
expect(sendCall[1]).toBe("How did the interview go?");
expect(sendCall[2]?.accountId).toBe("primary");
const [deliveredCommitment] = readCommitmentsForTest();
if (!deliveredCommitment) {
throw new Error("Expected delivered commitment");
}
expect(deliveredCommitment.status).toBe("sent");
expect(deliveredCommitment.attempts).toBe(1);
expect(deliveredCommitment.sentAtMs).toBe(dueMs + 60_000);
});
});
});
});