Repository navigation
Expand file tree
/
Copy pathplan-apply.test.js
More file actions
675 lines (639 loc) · 27.1 KB
/
Copy pathplan-apply.test.js
File metadata and controls
675 lines (639 loc) · 27.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
import assert from "node:assert/strict";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import test, { afterEach } from "node:test";
import {
applyRestore,
applySwitch,
applySync,
getStatus,
prepareRestore,
prepareSwitch,
prepareSync
} from "../src/service.js";
import { listBackups } from "../src/backup.js";
import { openDatabase } from "../src/sqlite.js";
const cleanups = [];
afterEach(async () => { for (const cleanup of cleanups.splice(0).reverse()) await cleanup(); });
async function makeFixture() {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "provider-sync-plan-apply-"));
const codexHome = path.join(root, ".codex");
const rolloutPath = path.join(codexHome, "sessions", "2026", "08", "25", "rollout-a.jsonl");
const stateDbPath = path.join(codexHome, "sqlite", "state_5.sqlite");
await fs.mkdir(path.dirname(rolloutPath), { recursive: true });
await fs.mkdir(path.join(codexHome, "archived_sessions"), { recursive: true });
await fs.mkdir(path.dirname(stateDbPath), { recursive: true });
await fs.writeFile(
path.join(codexHome, "config.toml"),
'model_provider = "openai"\nmodel = "gpt-5"\n',
"utf8"
);
const meta = {
id: "thread-a",
timestamp: "2026-08-25T00:00:00.000Z",
cwd: "C:\\AITemp",
source: "cli",
cli_version: "0.115.0",
model_provider: "custom"
};
await fs.writeFile(
rolloutPath,
`${JSON.stringify({ timestamp: meta.timestamp, type: "session_meta", payload: meta })}\n`,
"utf8"
);
const db = await openDatabase(stateDbPath);
try {
db.exec(`
CREATE TABLE threads (
id TEXT PRIMARY KEY,
model_provider TEXT,
cwd TEXT NOT NULL DEFAULT '',
archived INTEGER NOT NULL DEFAULT 0,
first_user_message TEXT NOT NULL DEFAULT '',
model TEXT
)
`);
db.prepare("INSERT INTO threads (id, model_provider, cwd, archived, first_user_message, model) VALUES (?, ?, ?, ?, ?, ?)")
.run("thread-a", "custom", "C:\\AITemp", 0, "hello", "old-model");
} finally {
db.close();
}
return { root, codexHome, rolloutPath, stateDbPath };
}
function backupRoot(codexHome) {
return path.join(codexHome, "backups_state", "provider-sync");
}
async function backupCount(codexHome) {
try {
return (await fs.readdir(backupRoot(codexHome))).length;
} catch (error) {
if (error?.code === "ENOENT") return 0;
throw error;
}
}
test("prepareSync returns schema v1 summary and applySync consumes it exactly once", async () => {
const value = await makeFixture();
try {
const plan = await prepareSync({ codexHome: value.codexHome });
assert.equal(plan.schemaVersion, 1);
assert.equal(plan.operation, "sync");
assert.equal(plan.requiresConfirmation, true);
assert.equal(plan.target.provider, "openai");
assert.equal(plan.impact.rolloutFilesToChange, 1);
assert.match(plan.planId, /^[A-Za-z0-9_-]{32,128}$/);
const applied = await applySync({ schemaVersion: 1, planId: plan.planId });
assert.equal(applied.schemaVersion, 1);
assert.equal(applied.operation, "sync");
assert.equal(applied.outcome, "completed");
assert.match(applied.operationId, /^[0-9a-f-]{36}$/);
assert.equal(applied.result.targetProvider, "openai");
assert.equal(await backupCount(value.codexHome), 1);
await assert.rejects(
applySync({ schemaVersion: 1, planId: plan.planId }),
(error) => error?.code === "PLAN_EXPIRED"
);
} finally {
await fs.rm(value.root, { recursive: true, force: true });
}
});
test("a prepared manual plan has priority over a Watch Apply without weakening single consumption", async () => {
const value = await makeFixture();
try {
const manualPlan = await prepareSync({ codexHome: value.codexHome });
const watchPlan = await prepareSync({ codexHome: value.codexHome, __actor: "watch" });
await assert.rejects(
applySync({ schemaVersion: 1, planId: watchPlan.planId }),
(error) => error?.code === "OPERATION_BUSY"
&& error?.details?.busyScope === "codex-home"
&& error?.details?.reason === "manual-intent"
);
assert.equal(await backupCount(value.codexHome), 0);
const applied = await applySync({ schemaVersion: 1, planId: manualPlan.planId });
assert.equal(applied.outcome, "completed");
assert.equal(await backupCount(value.codexHome), 1);
await assert.rejects(
applySync({ schemaVersion: 1, planId: watchPlan.planId }),
(error) => error?.code === "PLAN_EXPIRED"
);
} finally {
await fs.rm(value.root, { recursive: true, force: true });
}
});
test("Apply publishes one operation id, projects progress, and cancels before backup", async () => {
const value = await makeFixture();
const controller = new AbortController();
const lifecycle = [];
try {
const plan = await prepareSync({ codexHome: value.codexHome });
await assert.rejects(
applySync(
{ schemaVersion: 1, planId: plan.planId },
{
onOperationStarted(started) {
lifecycle.push({ kind: "started", ...started });
},
onProgress(progress) {
lifecycle.push({ kind: "progress", ...progress });
if (progress.stage === "create_backup" && progress.status === "start") {
controller.abort();
}
},
signal: controller.signal
}
),
(error) => error?.code === "OPERATION_CANCELLED"
&& error?.operationId === lifecycle[0]?.operationId
);
assert.equal(lifecycle[0]?.kind, "started");
assert.equal(lifecycle[0]?.operation, "sync");
assert.ok(lifecycle.some((event) => event.kind === "progress"));
assert.equal(await backupCount(value.codexHome), 0);
assert.equal((await getStatus({ codexHome: value.codexHome })).operationInProgress, null);
} finally {
await fs.rm(value.root, { recursive: true, force: true });
}
});
test("Apply can cancel after backup completes but before the first mutation", async () => {
const value = await makeFixture();
const controller = new AbortController();
const configBefore = await fs.readFile(path.join(value.codexHome, "config.toml"));
const rolloutBefore = await fs.readFile(value.rolloutPath);
try {
const plan = await prepareSync({ codexHome: value.codexHome });
await assert.rejects(
applySync(
{ schemaVersion: 1, planId: plan.planId },
{
onProgress(progress) {
if (progress.stage === "create_backup" && progress.status === "complete") {
controller.abort();
}
},
signal: controller.signal
}
),
(error) => error?.code === "OPERATION_CANCELLED"
);
assert.equal(await backupCount(value.codexHome), 1);
assert.deepEqual(await fs.readFile(path.join(value.codexHome, "config.toml")), configBefore);
assert.deepEqual(await fs.readFile(value.rolloutPath), rolloutBefore);
const database = await openDatabase(value.stateDbPath, { readOnly: true });
try {
assert.equal(
database.prepare("SELECT model_provider FROM threads WHERE id = ?").get("thread-a").model_provider,
"custom"
);
} finally {
database.close();
}
} finally {
await fs.rm(value.root, { recursive: true, force: true });
}
});
test("SQLite busy preflight runs before backup even when only rollout bytes need mutation", async () => {
const value = await makeFixture();
const rolloutBefore = await fs.readFile(value.rolloutPath);
let writer;
try {
const database = await openDatabase(value.stateDbPath);
try {
database.prepare("UPDATE threads SET model_provider = ? WHERE id = ?").run("openai", "thread-a");
} finally {
database.close();
}
const plan = await prepareSync({ codexHome: value.codexHome });
assert.equal(plan.impact.rolloutFilesToChange, 1);
assert.equal(plan.impact.sqliteRowsToChange, 0);
writer = await openDatabase(value.stateDbPath);
writer.exec("BEGIN IMMEDIATE");
await assert.rejects(
applySync({ schemaVersion: 1, planId: plan.planId }),
(error) => error?.code === "SQLITE_BUSY"
);
assert.equal(await backupCount(value.codexHome), 0);
assert.deepEqual(await fs.readFile(value.rolloutPath), rolloutBefore);
} finally {
if (writer) {
try {
writer.exec("ROLLBACK");
} catch {
// The test is already complete if SQLite closed the transaction.
}
writer.close();
}
await fs.rm(value.root, { recursive: true, force: true });
}
});
test("Apply ignores cancellation after the first mutation and completes the convergent write", async () => {
const value = await makeFixture();
const controller = new AbortController();
const rolloutBefore = await fs.readFile(value.rolloutPath);
let startedOperationId;
try {
const plan = await prepareSync({
codexHome: value.codexHome,
faultInjector({ point }) {
if (point === "after_rollout_mutation_before_applied") controller.abort();
}
});
const applied = await applySync(
{ schemaVersion: 1, planId: plan.planId },
{
signal: controller.signal,
onOperationStarted(value) { startedOperationId = value.operationId; }
}
);
assert.equal(applied.operationId, startedOperationId);
assert.equal(applied.outcome, "completed");
assert.notDeepEqual(await fs.readFile(value.rolloutPath), rolloutBefore);
const database = await openDatabase(value.stateDbPath, { readOnly: true });
try {
assert.equal(
database.prepare("SELECT model_provider FROM threads WHERE id = ?").get("thread-a").model_provider,
"openai"
);
} finally {
database.close();
}
const status = await getStatus({ codexHome: value.codexHome });
assert.equal(status.pendingRecovery, false);
assert.deepEqual(status.pendingTransactions, []);
} finally {
await fs.rm(value.root, { recursive: true, force: true });
}
});
test("applySync rejects config drift under the write locks before backup", async () => {
const value = await makeFixture();
try {
const plan = await prepareSync({ codexHome: value.codexHome });
await fs.appendFile(path.join(value.codexHome, "config.toml"), "# changed\n", "utf8");
await assert.rejects(
applySync({ schemaVersion: 1, planId: plan.planId }),
(error) => error?.code === "STALE_STATE" && error?.details?.reason === "config"
);
assert.equal(await backupCount(value.codexHome), 0);
} finally {
await fs.rm(value.root, { recursive: true, force: true });
}
});
test("applySync skips individual rollout and Provider row drift", async () => {
for (const drift of ["rollout", "state-db"]) {
const value = await makeFixture();
try {
const plan = await prepareSync({ codexHome: value.codexHome });
if (drift === "rollout") {
await fs.writeFile(value.rolloutPath, (await fs.readFile(value.rolloutPath, "utf8")).replace('"custom"', '"other"'));
} else {
const db = await openDatabase(value.stateDbPath);
try {
db.prepare("UPDATE threads SET model_provider = ? WHERE id = ?").run("changed", "thread-a");
} finally {
db.close();
}
}
const result = await applySync({ schemaVersion: 1, planId: plan.planId });
assert.equal(result.outcome, "partial", drift);
const db = await openDatabase(value.stateDbPath);
try { assert.equal(db.prepare("SELECT model_provider FROM threads WHERE id = 'thread-a'").get().model_provider, drift === "rollout" ? "custom" : "changed"); } finally { db.close(); }
assert.equal(await backupCount(value.codexHome), drift === "rollout" ? 0 : 1, drift);
} finally {
await fs.rm(value.root, { recursive: true, force: true });
}
}
});
test("Sync and Switch allow body appends and non-Provider WAL updates between preview and apply", async (t) => {
for (const operation of ["sync", "switch"]) {
const value = await makeFixture();
cleanups.push(() => fs.rm(value.root, { recursive: true, force: true }));
await fs.appendFile(path.join(value.codexHome, "config.toml"), '[model_providers.prov_a]\nname = "fixture"\n');
const db = await openDatabase(value.stateDbPath);
try {
db.exec("PRAGMA journal_mode=WAL");
const plan = operation === "sync"
? await prepareSync({ codexHome: value.codexHome })
: await prepareSwitch({ codexHome: value.codexHome, provider: "prov_a", keepRootModel: true });
const body = '{"type":"event_msg","payload":{"type":"user_message","message":"synthetic append"}}\n';
await fs.appendFile(value.rolloutPath, body);
db.prepare("UPDATE threads SET first_user_message = ? WHERE id = ?").run("synthetic update", "thread-a");
db.exec("PRAGMA wal_checkpoint(TRUNCATE)");
const result = await (operation === "sync" ? applySync : applySwitch)({ schemaVersion: 1, planId: plan.planId });
assert.equal(result.outcome, "completed");
const bytes = await fs.readFile(value.rolloutPath, "utf8");
assert.equal(bytes.slice(bytes.indexOf("\n") + 1), body);
const row = db.prepare("SELECT * FROM threads WHERE id = ?").get("thread-a");
assert.equal(row.model_provider, operation === "sync" ? "openai" : "prov_a");
assert.equal(row.first_user_message, "synthetic update");
assert.equal(row.model, "old-model");
} finally { db.close(); }
}
});
test("Provider plans skip changed targets and defer new targets but reject schema drift", async (t) => {
for (const drift of ["replace", "truncate", "new-rollout", "new-row", "schema"]) {
const value = await makeFixture();
cleanups.push(() => fs.rm(value.root, { recursive: true, force: true }));
await fs.appendFile(value.rolloutPath, '{"type":"event_msg"}\n');
const plan = await prepareSync({ codexHome: value.codexHome });
if (drift === "replace") {
const bytes = await fs.readFile(value.rolloutPath);
await fs.rename(value.rolloutPath, `${value.rolloutPath}.old`);
await fs.writeFile(value.rolloutPath, bytes);
} else if (drift === "truncate") {
await fs.truncate(value.rolloutPath, Number((await fs.stat(value.rolloutPath)).size) - 1);
} else if (drift === "new-rollout") {
await fs.copyFile(value.rolloutPath, path.join(path.dirname(value.rolloutPath), "rollout-new.jsonl"));
} else {
const db = await openDatabase(value.stateDbPath);
try {
db.exec(drift === "schema" ? "ALTER TABLE threads ADD COLUMN extra TEXT" : "INSERT INTO threads (id, model_provider) VALUES ('thread-b', 'custom')");
} finally { db.close(); }
}
if (drift === "schema") {
await assert.rejects(applySync({ schemaVersion: 1, planId: plan.planId }), error => error.code === "STALE_STATE");
assert.equal(await backupCount(value.codexHome), 0);
} else {
const result = await applySync({ schemaVersion: 1, planId: plan.planId });
if (["replace", "truncate"].includes(drift)) {
assert.equal(result.outcome, "partial");
assert.equal(result.result.changedSessionFiles, 0);
assert.equal(result.result.sqliteRowsUpdated, 0);
} else if (drift === "new-row") {
const db = await openDatabase(value.stateDbPath);
try { assert.equal(db.prepare("SELECT model_provider FROM threads WHERE id='thread-b'").get().model_provider, "custom"); } finally { db.close(); }
} else {
assert.match(await fs.readFile(path.join(path.dirname(value.rolloutPath), "rollout-new.jsonl"), "utf8"), /"custom"/);
}
}
}
});
test("Sync rejects an undefined config Provider with no backup or mutation, then succeeds once configured", async (t) => {
const value = await makeFixture();
cleanups.push(() => fs.rm(value.root, { recursive: true, force: true }));
const configPath = path.join(value.codexHome, "config.toml");
const config = "model_provider = 'dal' # selected elsewhere\n";
await fs.writeFile(configPath, config);
const before = await fs.readFile(value.rolloutPath);
const databaseBefore = await fs.readFile(value.stateDbPath);
await assert.rejects(prepareSync({ codexHome: value.codexHome }), (error) => error.code === "INVALID_INPUT" && error.details.reason === "provider-not-configured");
assert.equal(await backupCount(value.codexHome), 0);
assert.deepEqual(await fs.readFile(value.rolloutPath), before);
assert.deepEqual(await fs.readFile(value.stateDbPath), databaseBefore);
assert.equal(await fs.readFile(configPath, "utf8"), config);
await fs.appendFile(configPath, "[model_providers.'dal'] # configured\nname = 'fixture'\n");
const plan = await prepareSync({ codexHome: value.codexHome });
assert.equal(plan.target.provider, "dal");
assert.equal((await applySync({ schemaVersion: 1, planId: plan.planId })).outcome, "completed");
});
test("profile revision drift is checked after preparation and consumes the plan", async () => {
const value = await makeFixture();
try {
let revision = "profile-r1";
const plan = await prepareSync({
codexHome: value.codexHome,
profileId: "work",
profileRevision: revision,
profileResolver: async () => ({
id: "work",
revision,
codexHome: value.codexHome
})
});
revision = "profile-r2";
await assert.rejects(
applySync({ schemaVersion: 1, planId: plan.planId }),
(error) => error?.code === "STALE_STATE" && error?.details?.reason === "profile"
);
await assert.rejects(
applySync({ schemaVersion: 1, planId: plan.planId }),
(error) => error?.code === "PLAN_EXPIRED"
);
assert.equal(await backupCount(value.codexHome), 0);
} finally {
await fs.rm(value.root, { recursive: true, force: true });
}
});
test("status returns the last complete snapshot with operation metadata while Apply is paused", async () => {
const value = await makeFixture();
let entered;
let release;
const enteredPromise = new Promise((resolve) => { entered = resolve; });
const releasePromise = new Promise((resolve) => { release = resolve; });
try {
const plan = await prepareSync({
codexHome: value.codexHome,
faultInjector: async ({ point }) => {
if (point === "before_backup") {
entered();
await releasePromise;
}
}
});
const applyPromise = applySync({ schemaVersion: 1, planId: plan.planId });
await enteredPromise;
const status = await getStatus({ codexHome: value.codexHome });
assert.equal(status.rolloutScanComplete, true);
assert.equal(status.operationInProgress.operation, "sync");
assert.equal(status.operationInProgress.actor, "manual");
assert.match(status.operationInProgress.operationId, /^[0-9a-f-]{36}$/);
release();
await applyPromise;
assert.equal((await getStatus({ codexHome: value.codexHome })).operationInProgress, null);
} finally {
release?.();
await fs.rm(value.root, { recursive: true, force: true });
}
});
test("two concurrent Apply calls for one plan start exactly one operation", async () => {
const value = await makeFixture();
try {
const plan = await prepareSync({ codexHome: value.codexHome });
const settled = await Promise.allSettled([
applySync({ schemaVersion: 1, planId: plan.planId }),
applySync({ schemaVersion: 1, planId: plan.planId })
]);
assert.equal(settled.filter((entry) => entry.status === "fulfilled").length, 1);
const rejected = settled.find((entry) => entry.status === "rejected");
assert.equal(rejected.reason.code, "PLAN_EXPIRED");
assert.equal(await backupCount(value.codexHome), 1);
} finally {
await fs.rm(value.root, { recursive: true, force: true });
}
});
test("different Codex Homes sharing one State DB rely on native SQLite transactions", async () => {
const value = await makeFixture();
const secondHome = path.join(value.root, "second-codex-home");
const secondRollout = path.join(secondHome, "sessions", "2026", "08", "25", "rollout-b.jsonl");
let entered;
let release;
const enteredPromise = new Promise((resolve) => { entered = resolve; });
const releasePromise = new Promise((resolve) => { release = resolve; });
try {
await fs.mkdir(path.dirname(secondRollout), { recursive: true });
await fs.mkdir(path.join(secondHome, "archived_sessions"), { recursive: true });
await fs.writeFile(
path.join(secondHome, "config.toml"),
`model_provider = "openai"\nsqlite_home = ${JSON.stringify(path.dirname(value.stateDbPath))}\n`,
"utf8"
);
await fs.writeFile(secondRollout, `${JSON.stringify({
timestamp: "2026-08-25T00:00:00.000Z",
type: "session_meta",
payload: {
id: "thread-b",
timestamp: "2026-08-25T00:00:00.000Z",
cwd: "C:\\AITemp",
source: "cli",
cli_version: "0.115.0",
model_provider: "custom"
}
})}\n`, "utf8");
const firstPlan = await prepareSync({
codexHome: value.codexHome,
faultInjector: async ({ point }) => {
if (point === "before_backup") {
entered();
await releasePromise;
}
}
});
const firstApply = applySync({ schemaVersion: 1, planId: firstPlan.planId });
await enteredPromise;
const secondPlan = await prepareSync({ codexHome: secondHome });
const secondApplied = await applySync({ schemaVersion: 1, planId: secondPlan.planId });
assert.equal(secondApplied.outcome, "completed");
assert.equal(await backupCount(secondHome), 1);
assert.match(await fs.readFile(secondRollout, "utf8"), /"model_provider":"openai"/);
release();
const firstApplied = await firstApply;
assert.equal(firstApplied.outcome, "partial");
assert.ok(firstApplied.result.skipSummary.items.some(item => item.reason === "row-changed"));
} finally {
release?.();
await fs.rm(value.root, { recursive: true, force: true });
}
});
test("prepareSwitch/applySwitch preserves all three model-mode intents in consumed plans", async () => {
for (const fixture of [
{ expectedMode: "provider-default", options: {}, expectedModel: "relay-model" },
{ expectedMode: "keep-root-model", options: { keepRootModel: true }, expectedModel: "gpt-5" },
{ expectedMode: "explicit", options: { model: "explicit-model" }, expectedModel: "explicit-model" }
]) {
const value = await makeFixture();
try {
await fs.appendFile(
path.join(value.codexHome, "config.toml"),
'\n[model_providers.relay]\nmodel = "relay-model"\nbase_url = "https://example.invalid"\n',
"utf8"
);
const plan = await prepareSwitch({
codexHome: value.codexHome,
provider: "relay",
...fixture.options
});
assert.equal(plan.operation, "switch");
assert.equal(plan.target.modelMode, fixture.expectedMode);
assert.equal(plan.target.previousProvider, "openai");
assert.equal(plan.target.previousRootModel, "gpt-5");
assert.equal(plan.target.provider, "relay");
assert.equal(plan.target.model, fixture.expectedModel);
const applied = await applySwitch({ schemaVersion: 1, planId: plan.planId });
assert.equal(applied.outcome, "completed");
const configText = await fs.readFile(path.join(value.codexHome, "config.toml"), "utf8");
assert.match(configText, /^model_provider = "relay"/m);
assert.match(configText, new RegExp(`^model = "${fixture.expectedModel}"`, "m"));
} finally {
await fs.rm(value.root, { recursive: true, force: true });
}
}
});
test("Switch re-resolves the authoritative State DB under the Home lock", async () => {
const value = await makeFixture();
const legacyStateDbPath = path.join(value.codexHome, "state_5.sqlite");
let newDefaultBytes = null;
try {
await fs.appendFile(
path.join(value.codexHome, "config.toml"),
'\n[model_providers.relay]\nmodel = "relay-model"\nbase_url = "https://example.invalid"\n',
"utf8"
);
await fs.rename(value.stateDbPath, legacyStateDbPath);
await fs.rm(path.dirname(value.stateDbPath), { recursive: true, force: true });
assert.equal(
(await getStatus({ codexHome: value.codexHome })).stateDbLocation.path,
legacyStateDbPath
);
const configBefore = await fs.readFile(path.join(value.codexHome, "config.toml"));
const rolloutBefore = await fs.readFile(value.rolloutPath);
const legacyBefore = await fs.readFile(legacyStateDbPath);
const plan = await prepareSwitch({
codexHome: value.codexHome,
provider: "relay",
faultInjector: async ({ point }) => {
if (point !== "after_switch_storage_preflight") return;
await fs.mkdir(path.dirname(value.stateDbPath), { recursive: true });
await fs.copyFile(legacyStateDbPath, value.stateDbPath);
newDefaultBytes = await fs.readFile(value.stateDbPath);
}
});
await assert.rejects(
applySwitch({ schemaVersion: 1, planId: plan.planId }),
(error) => error?.code === "STALE_STATE" && error?.details?.reason === "storage"
);
assert.equal(await backupCount(value.codexHome), 0);
assert.deepEqual(await fs.readFile(path.join(value.codexHome, "config.toml")), configBefore);
assert.deepEqual(await fs.readFile(value.rolloutPath), rolloutBefore);
assert.deepEqual(await fs.readFile(legacyStateDbPath), legacyBefore);
assert.deepEqual(await fs.readFile(value.stateDbPath), newDefaultBytes);
} finally {
await fs.rm(value.root, { recursive: true, force: true });
}
});
test("prepareRestore/applyRestore binds a managed backup and rejects backup drift before mutation", async () => {
const value = await makeFixture();
try {
const syncPlan = await prepareSync({ codexHome: value.codexHome });
await applySync({ schemaVersion: 1, planId: syncPlan.planId });
const inventory = await listBackups(value.codexHome);
const backup = inventory.backups[0];
assert.ok(backup?.id);
const stalePlan = await prepareRestore({
codexHome: value.codexHome,
backupId: backup.id,
restoreConfig: false,
restoreDatabase: true,
restoreSessions: true
});
await fs.appendFile(path.join(backup.path, "metadata.json"), "\n", "utf8");
await assert.rejects(
applyRestore({ schemaVersion: 1, planId: stalePlan.planId }),
(error) => error?.code === "STALE_STATE" && error?.details?.reason === "backup"
);
const dbBefore = await fs.readFile(value.stateDbPath);
// Restore the exact metadata bytes from the immutable source plan fixture,
// then prepare a fresh plan and apply it.
const metadataText = await fs.readFile(path.join(backup.path, "metadata.json"), "utf8");
await fs.writeFile(path.join(backup.path, "metadata.json"), metadataText.trimEnd(), "utf8");
const freshPlan = await prepareRestore({
codexHome: value.codexHome,
backupId: backup.id,
restoreConfig: false,
restoreDatabase: true,
restoreSessions: true
});
const restored = await applyRestore({ schemaVersion: 1, planId: freshPlan.planId });
assert.equal(restored.operation, "restore");
assert.equal(restored.outcome, "completed");
assert.notDeepEqual(await fs.readFile(value.stateDbPath), dbBefore);
const db = await openDatabase(value.stateDbPath);
try {
assert.equal(
db.prepare("SELECT model_provider FROM threads WHERE id = ?").get("thread-a").model_provider,
"custom"
);
} finally {
db.close();
}
} finally {
await fs.rm(value.root, { recursive: true, force: true });
}
});