Skip to content

Commit c348a86

Browse files
committed
test(sessions): prove Goal participant upgrade boundaries
1 parent c8ef48a commit c348a86

3 files changed

Lines changed: 131 additions & 11 deletions

File tree

‎src/commands/doctor-session-sqlite.shared-store.test.ts‎

Lines changed: 66 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,14 @@ import fs from "node:fs";
22
import path from "node:path";
33
import { afterEach, describe, expect, it } from "vitest";
44
import { useAutoCleanupTempDirTracker } from "../../test/helpers/temp-dir.js";
5+
import {
6+
lookupSessionGoalOperation,
7+
type SessionGoalOperation,
8+
} from "../config/sessions/goals-operations.js";
59
import {
610
loadExactSessionEntry,
711
listSessionParticipantsReadOnly,
12+
persistSessionTranscriptTurn,
813
upsertSessionEntryCore,
914
} from "../config/sessions/session-accessor.js";
1015
import {
@@ -67,8 +72,36 @@ async function createStore(layout: "shared" | "custom") {
6772

6873
async function createHistoricalSharedStore(corruptIndex = false) {
6974
const store = await createStore("shared");
75+
const goalOperation = {
76+
action: "start",
77+
operationId: "goal-before-participant-upgrade",
78+
issuedAtMs: Date.now(),
79+
requestFingerprint: "shared-store-goal-fixture",
80+
objective: "Preserve this Goal across the participant migration.",
81+
} satisfies SessionGoalOperation;
82+
const turn = await persistSessionTranscriptTurn(
83+
{ ...store.scope, sessionId: "doctor-session" },
84+
{
85+
expectedSessionId: "doctor-session",
86+
messages: [{ message: { role: "user", content: goalOperation.objective } }],
87+
sessionTurnMutation: { kind: "goal", operation: goalOperation, runId: "goal-start" },
88+
updateMode: "none",
89+
},
90+
);
91+
const goalReceipt = turn.sessionTurnMutationResult?.result;
92+
expect(goalReceipt).toMatchObject({ action: "start", status: "started", runId: "goal-start" });
93+
expect(
94+
lookupSessionGoalOperation({
95+
...store.scope,
96+
expectedSessionId: "doctor-session",
97+
operation: goalOperation,
98+
}),
99+
).toEqual(goalReceipt);
100+
closeOpenClawAgentDatabasesForTest();
101+
closeOpenClawStateDatabaseForTest();
70102
const database = openNodeSqliteDatabase(store.sqlitePath);
71103
try {
104+
const goalState = readStoredGoalState(database, store.scope.sessionKey);
72105
// Restore the actual v17 table contract as well as both version markers;
73106
// header-only downgrades test refusal, not an ordinary supported upgrade.
74107
database.exec("DROP TABLE session_participants;");
@@ -94,10 +127,31 @@ async function createHistoricalSharedStore(corruptIndex = false) {
94127
const schemaVersion = Number(database.prepare("PRAGMA schema_version").get()?.schema_version);
95128
database.exec(`PRAGMA schema_version = ${schemaVersion + 1};`);
96129
}
130+
return { ...store, goalOperation, goalReceipt, goalState };
97131
} finally {
98132
database.close();
99133
}
100-
return store;
134+
}
135+
136+
function readStoredGoalState(
137+
database: ReturnType<typeof openNodeSqliteDatabase>,
138+
sessionKey: string,
139+
) {
140+
return {
141+
goal: database
142+
.prepare(
143+
"SELECT json_extract(entry_json, '$.goal') AS goal_json FROM session_nodes WHERE session_key = ?",
144+
)
145+
.get(sessionKey),
146+
receipts: database
147+
.prepare("SELECT * FROM session_goal_operations WHERE session_key = ? ORDER BY operation_id")
148+
.all(sessionKey),
149+
ddl: database
150+
.prepare(
151+
"SELECT name, sql FROM sqlite_schema WHERE tbl_name = 'session_goal_operations' ORDER BY name",
152+
)
153+
.all(),
154+
};
101155
}
102156

103157
async function repairHistoricalSharedStore(
@@ -122,7 +176,7 @@ async function repairHistoricalSharedStore(
122176
}
123177
}
124178

125-
function expectUpgradedSharedStore(store: Awaited<ReturnType<typeof createStore>>) {
179+
function expectUpgradedSharedStore(store: Awaited<ReturnType<typeof createHistoricalSharedStore>>) {
126180
const reopened = openOpenClawAgentDatabase(store.options);
127181
expect(reopened.agentId).toBe("main");
128182
expect(reopened.db.prepare("PRAGMA user_version").get()?.user_version).toBe(18);
@@ -131,6 +185,15 @@ function expectUpgradedSharedStore(store: Awaited<ReturnType<typeof createStore>
131185
schema_version: 18,
132186
});
133187
expect(loadExactSessionEntry(store.scope)?.entry.sessionId).toBe("doctor-session");
188+
expect(loadExactSessionEntry(store.scope)?.entry.goal).toEqual(store.goalReceipt?.goal);
189+
expect(readStoredGoalState(reopened.db, store.scope.sessionKey)).toEqual(store.goalState);
190+
expect(
191+
lookupSessionGoalOperation({
192+
...store.scope,
193+
expectedSessionId: "doctor-session",
194+
operation: store.goalOperation,
195+
}),
196+
).toEqual(store.goalReceipt);
134197
expect(listSessionParticipantsReadOnly(store.scope).get(store.scope.sessionKey)).toEqual([
135198
{
136199
identity: { type: "profile", id: "person" },
@@ -220,6 +283,7 @@ describe("Doctor canonical session SQLite targets", () => {
220283
).toBe(false);
221284
const preserved = openNodeSqliteDatabase(store.sqlitePath, { readOnly: true });
222285
try {
286+
expect(readStoredGoalState(preserved, store.scope.sessionKey)).toEqual(store.goalState);
223287
expect(preserved.prepare("PRAGMA user_version").get()?.user_version).toBe(17);
224288
expect(preserved.prepare("SELECT agent_id, schema_version FROM schema_meta").get()).toEqual({
225289
agent_id: "main",

‎src/gateway/server.chat-goal.test.ts‎

Lines changed: 62 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import { clearConfigCache, getRuntimeConfig } from "../config/config.js";
99
import {
1010
appendTranscriptMessage,
1111
deleteSessionEntryLifecycle,
12+
listSessionParticipantsReadOnly,
1213
loadSessionEntry,
1314
loadTranscriptEventsSync,
1415
patchSessionEntryCore,
@@ -592,10 +593,41 @@ describe("Goal chat admission and continuation", () => {
592593

593594
it("resumes through the real reply pipeline without a visible synthetic user row", async () => {
594595
const objective = "Finish the release checklist";
595-
const started = await rpc("chat.send", goalStart(objective));
596+
const profile = ensureProfileForEmail("[email protected]");
597+
const requestClient: GatewayClient = {
598+
...client,
599+
authenticatedUserProfile: {
600+
profileId: profile.id,
601+
displayName: null,
602+
hasAvatar: false,
603+
updatedAt: 1,
604+
},
605+
};
606+
const participants = () => listSessionParticipantsReadOnly(scope()).get(sessionKey) ?? [];
607+
expect(participants()).toEqual([]);
608+
const startRequest = goalStart(objective);
609+
const started = await rpc("chat.send", startRequest, undefined, requestClient);
596610
expect(started.mock.calls[0]?.[0]).toBe(true);
597611
await waitForModelRun();
598612
await waitForDispatchEnd();
613+
const startMessage = userMessages()[0];
614+
const startTimestamp =
615+
startMessage && "timestamp" in startMessage ? startMessage.timestamp : undefined;
616+
expect(startTimestamp).toEqual(expect.any(Number));
617+
const startParticipants = [
618+
{
619+
identity: { type: "profile", id: profile.id },
620+
contributionCount: 1,
621+
firstPromptedAt: startTimestamp,
622+
lastPromptedAt: startTimestamp,
623+
},
624+
];
625+
// Participant persistence is a post-admission microtask, not part of the Goal ACK.
626+
await vi.waitFor(() => expect(participants()).toEqual(startParticipants));
627+
const startReplay = await rpc("chat.send", startRequest, undefined, requestClient);
628+
expect(startReplay.mock.calls[0]?.[1]).toMatchObject({ replayed: true });
629+
expect(runEmbeddedAgent).toHaveBeenCalledOnce();
630+
expect(participants()).toEqual(startParticipants);
599631
const goal = loadSessionEntry(scope())?.goal;
600632
expect(goal).toBeDefined();
601633
await patchSessionEntryCore(scope(), (entry) => ({
@@ -614,7 +646,7 @@ describe("Goal chat admission and continuation", () => {
614646
issuedAtMs: Date.now(),
615647
};
616648
modelStarted = createDeferred();
617-
const resumed = await rpc("sessions.goal.update", request);
649+
const resumed = await rpc("sessions.goal.update", request, undefined, requestClient);
618650
expect(resumed).toHaveBeenCalledWith(
619651
true,
620652
expect.objectContaining({ status: "started", runId: "goal-resume", goalId: goal?.id }),
@@ -623,6 +655,7 @@ describe("Goal chat admission and continuation", () => {
623655
);
624656
await waitForModelRun(2);
625657
await waitForDispatchEnd();
658+
expect(participants()).toEqual(startParticipants);
626659
expect(loadSessionEntry(scope())?.goal?.status).toBe("active");
627660
expect(userMessages()).toEqual([
628661
expect.objectContaining({ content: objective }),
@@ -641,9 +674,35 @@ describe("Goal chat admission and continuation", () => {
641674
expect(result.messages?.filter((message) => message.role === "user")).toEqual([
642675
expect.objectContaining({ content: objective }),
643676
]);
644-
const replay = await rpc("sessions.goal.update", request);
677+
const replay = await rpc("sessions.goal.update", request, undefined, requestClient);
645678
expect(replay.mock.calls[0]?.[1]).toMatchObject({ replayed: true, runId: "goal-resume" });
646679
expect(runEmbeddedAgent).toHaveBeenCalledTimes(2);
647680
expect(userMessages()).toHaveLength(2);
681+
expect(participants()).toEqual(startParticipants);
682+
683+
modelStarted = createDeferred();
684+
const next = await rpc(
685+
"chat.send",
686+
{
687+
sessionKey,
688+
sessionId,
689+
message: "Also review the changelog.",
690+
idempotencyKey: randomUUID(),
691+
},
692+
undefined,
693+
requestClient,
694+
);
695+
expect(next.mock.calls[0]?.[0]).toBe(true);
696+
await waitForModelRun(3);
697+
await waitForDispatchEnd();
698+
const nextMessage = userMessages().at(-1);
699+
const nextTimestamp =
700+
nextMessage && "timestamp" in nextMessage ? nextMessage.timestamp : undefined;
701+
expect(nextTimestamp).toEqual(expect.any(Number));
702+
await vi.waitFor(() =>
703+
expect(participants()).toEqual([
704+
{ ...startParticipants[0], contributionCount: 2, lastPromptedAt: nextTimestamp },
705+
]),
706+
);
648707
});
649708
});

‎test/scripts/declaration-source-index.test.ts‎

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11
import { spawnSync } from "node:child_process";
22
import fs from "node:fs";
3-
import os from "node:os";
43
import path from "node:path";
54
import { build } from "tsdown";
65
import { afterEach, beforeEach, describe, expect, it } from "vitest";
76
import { discoverDeclarationSources } from "../../scripts/lib/declaration-source-index.mts";
7+
import { useAutoCleanupTempDirTracker } from "../helpers/temp-dir.js";
88

99
describe("declaration source discovery", () => {
10+
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
1011
let root: string;
1112
let tsconfig: string;
1213

@@ -18,7 +19,7 @@ describe("declaration source discovery", () => {
1819
}
1920

2021
beforeEach(() => {
21-
root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "declaration-source-index-")));
22+
root = fs.realpathSync(tempDirs.make("declaration-source-index-"));
2223
write("package.json", '{"type":"module"}');
2324
fs.symlinkSync(path.resolve("node_modules"), path.join(root, "node_modules"), "junction");
2425
tsconfig = write(
@@ -39,10 +40,6 @@ describe("declaration source discovery", () => {
3940
);
4041
});
4142

42-
afterEach(() => {
43-
fs.rmSync(root, { recursive: true, force: true });
44-
});
45-
4643
it("emits aliases and transitive type-only sources outside the selected entry roots", async () => {
4744
const entry = write(
4845
"entries/sdk.ts",

0 commit comments

Comments
 (0)