Repository navigation
Expand file tree
/
Copy pathstatus-coordination.test.js
More file actions
719 lines (689 loc) · 30.5 KB
/
Copy pathstatus-coordination.test.js
File metadata and controls
719 lines (689 loc) · 30.5 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
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import fs from "node:fs/promises";
import { appendFileSync } from "node:fs";
import http from "node:http";
import os from "node:os";
import path from "node:path";
import test, { afterEach } from "node:test";
import { openDatabase } from "../src/sqlite.js";
import { createWebCoreFacade } from "../src/web-core-adapter.js";
import { createWebUiServer } from "../src/web-server.js";
import { createMemoryWebUiState } from "../src/web-state.js";
import { getStatus } from "../packages/core/src/application/status.js";
import { acquireLock } from "../src/locking.js";
import { getDiagnostics } from "../packages/core/src/application/diagnostics.js";
import { prepareSync, applySync } from "../src/service.js";
// Node 16 has afterEach, but no TestContext.mock. Keep these filesystem
// injections test-local and restore them even when a tested assertion fails.
const methodRestores = [];
const methodMocks = {
method(object, key, implementation) {
const original = object[key];
methodRestores.push(() => { object[key] = original; });
object[key] = implementation;
},
restoreAll() { for (const restore of methodRestores.splice(0).reverse()) restore(); }
};
afterEach(() => methodMocks.restoreAll());
async function request(origin, pathname, body, headers = {}) {
return new Promise((resolve, reject) => {
const target = new URL(origin);
const serialized = body === undefined ? null : JSON.stringify(body);
const client = http.request({
hostname: target.hostname,
port: target.port,
path: pathname,
method: "POST",
headers: {
...(serialized ? {
"Content-Type": "application/json",
"Content-Length": Buffer.byteLength(serialized)
} : {}),
...headers
}
}, (response) => {
const chunks = [];
response.on("data", (chunk) => chunks.push(chunk));
response.on("end", () => {
const text = Buffer.concat(chunks).toString("utf8");
resolve({ status: response.statusCode, payload: JSON.parse(text) });
});
});
client.once("error", reject);
if (serialized) client.write(serialized);
client.end();
});
}
async function makeFixture() {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "provider-sync-status-lock-"));
const codexHome = path.join(root, ".codex");
const sqliteHome = path.join(root, "shared-sqlite");
const stateDbPath = path.join(sqliteHome, "state_5.sqlite");
const rolloutPath = path.join(codexHome, "sessions", "2026", "08", "25", "rollout-status.jsonl");
await fs.mkdir(path.dirname(rolloutPath), { recursive: true });
await fs.mkdir(path.join(codexHome, "archived_sessions"), { recursive: true });
await fs.mkdir(sqliteHome, { recursive: true });
const configText = (provider) => [
`model_provider = "${provider}"`,
`sqlite_home = ${JSON.stringify(sqliteHome)}`,
""
].join("\n");
await fs.writeFile(path.join(codexHome, "config.toml"), configText("openai"), "utf8");
await fs.writeFile(rolloutPath, `${JSON.stringify({
timestamp: "2026-08-25T00:00:00.000Z",
type: "session_meta",
payload: {
id: "status-thread",
model_provider: "openai",
cwd: "C:\\AITemp"
}
})}\n`, "utf8");
const database = await openDatabase(stateDbPath);
try {
database.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
)
`);
database.prepare("INSERT INTO threads (id, model_provider, cwd, archived, first_user_message) VALUES (?, ?, ?, ?, ?)")
.run("status-thread", "openai", "C:\\AITemp", 0, "redacted");
} finally {
database.close();
}
return { root, codexHome, sqliteHome, stateDbPath, rolloutPath, configText };
}
async function startRealWeb(codexHome, webRoot) {
await fs.mkdir(webRoot, { recursive: true });
await fs.writeFile(path.join(webRoot, "index.html"), "<!doctype html><title>status</title>", "utf8");
const stateStore = createMemoryWebUiState({ codexHome });
const coreFacade = createWebCoreFacade(stateStore);
const handle = createWebUiServer({ webRoot, stateStore, services: { coreFacade } });
await new Promise((resolve, reject) => {
handle.server.once("error", reject);
handle.server.listen(0, "127.0.0.1", resolve);
});
const address = handle.server.address();
const origin = `http://127.0.0.1:${address.port}`;
handle.setBaseUrl(origin);
const paired = await request(origin, "/api/pair", undefined, {
Origin: origin,
"X-Codex-Provider-Pairing": handle.issuePairing()
});
assert.equal(paired.status, 200);
const credential = paired.payload.deviceCredential;
return {
handle,
coreFacade,
stateStore,
origin,
async status() {
return request(origin, "/api/status", { profileId: "default" }, {
Origin: origin,
"X-Codex-Provider-Device": credential
});
},
async close() {
await new Promise((resolve, reject) => handle.server.close((error) => error ? reject(error) : resolve()));
}
};
}
async function startHolder({ mode, codexHome, stateDbPath, configText = "" }) {
const lockingUrl = new URL("../src/locking.js", import.meta.url).href;
const stateLockUrl = new URL("../src/state-db-lock.js", import.meta.url).href;
const sqliteUrl = new URL("../src/sqlite.js", import.meta.url).href;
const script = `
import fs from "node:fs/promises";
import path from "node:path";
import { once } from "node:events";
import { acquireLock } from ${JSON.stringify(lockingUrl)};
import { acquireStateDbLock } from ${JSON.stringify(stateLockUrl)};
import { openDatabase } from ${JSON.stringify(sqliteUrl)};
const mode = process.env.STATUS_HOLDER_MODE;
const codexHome = process.env.STATUS_CODEX_HOME;
const stateDbPath = process.env.STATUS_STATE_DB;
const releaseHome = mode === "home" ? await acquireLock(codexHome, "external-status-home") : null;
const heldState = await acquireStateDbLock(stateDbPath, mode === "home" ? "external-status-home" : "external-status-db");
try {
if (mode === "home") {
await fs.writeFile(path.join(codexHome, "config.toml"), process.env.STATUS_CONFIG_TEXT, "utf8");
} else {
const database = await openDatabase(stateDbPath);
try {
database.prepare("UPDATE threads SET model_provider = ? WHERE id = ?").run("external", "status-thread");
} finally {
database.close();
}
}
process.stdout.write(JSON.stringify({ ready: true }) + "\\n");
await once(process.stdin, "data");
} finally {
await heldState.release();
if (releaseHome) await releaseHome();
}
`;
const child = spawn(process.execPath, ["--input-type=module", "-e", script], {
cwd: process.cwd(),
env: {
...process.env,
STATUS_HOLDER_MODE: mode,
STATUS_CODEX_HOME: codexHome,
STATUS_STATE_DB: stateDbPath,
STATUS_CONFIG_TEXT: configText
},
stdio: ["pipe", "pipe", "pipe"]
});
let stderr = "";
child.stderr.setEncoding("utf8");
child.stderr.on("data", (chunk) => { stderr += chunk; });
const ready = await new Promise((resolve, reject) => {
let stdout = "";
child.stdout.setEncoding("utf8");
child.stdout.on("data", (chunk) => {
stdout += chunk;
const lineEnd = stdout.indexOf("\n");
if (lineEnd < 0) return;
try {
resolve(JSON.parse(stdout.slice(0, lineEnd)));
} catch (error) {
reject(error);
}
});
child.once("error", reject);
child.once("exit", (code) => {
if (code !== null) reject(new Error(`Status lock holder exited ${code} before ready: ${stderr}`));
});
});
assert.equal(ready.ready, true);
return async () => {
child.stdin.end("release\n");
const code = await new Promise((resolve) => child.once("exit", resolve));
assert.equal(code, 0, stderr);
};
}
function asLastComplete(status) {
const value = JSON.parse(JSON.stringify(status));
value.operationInProgress = null;
delete value.statusReadBlocked;
delete value.alignment;
return value;
}
test("stale Home lock does not trap Status and is reclaimed through ordinary Plan/Apply", async () => {
const fixture = await makeFixture();
try {
const lockDir = path.join(fixture.codexHome, "tmp", "provider-sync.lock");
await fs.mkdir(lockDir, { recursive: true });
const ownerPath = path.join(lockDir, "owner.json");
const ownerText = JSON.stringify({ pid: 2147483647, processStartMarker: "windows:1" });
await fs.writeFile(ownerPath, ownerText);
const options = { codexHome: fixture.codexHome, sqliteHome: fixture.sqliteHome };
for (let attempt = 0; attempt < 2; attempt++) {
const status = await getStatus(options);
assert.equal(status.operationInProgress, null);
assert.equal(status.staleLockDetected, true);
assert.equal(status.statusReadBlocked, undefined);
assert.equal(await fs.readFile(ownerPath, "utf8"), ownerText);
}
const plan = await prepareSync(options);
const result = await applySync({ schemaVersion: 1, planId: plan.planId });
assert.equal(result.outcome, "completed");
const status = await getStatus(options);
assert.equal(status.operationInProgress, null);
assert.equal(status.staleLockDetected, undefined);
await assert.rejects(fs.stat(ownerPath), { code: "ENOENT" });
} finally {
await fs.rm(fixture.root, { recursive: true, force: true });
}
});
test("Core and Web Status block on the Home lock and ignore legacy State DB resource locks", async () => {
const fixture = await makeFixture();
const web = await startRealWeb(fixture.codexHome, path.join(fixture.root, "web"));
let releaseHolder = null;
try {
const profileRevision = web.stateStore.getProfile("default").revision;
const statusOptions = {
profile: { profileId: "default", profileRevision }
};
const readCoreStatus = () => web.coreFacade.getStatus(statusOptions);
const baselineWebResponse = await web.status();
assert.equal(baselineWebResponse.status, 200);
const baselineCore = await readCoreStatus();
releaseHolder = await startHolder({
mode: "home",
codexHome: fixture.codexHome,
stateDbPath: fixture.stateDbPath,
configText: fixture.configText("external")
});
const blockedCore = await readCoreStatus();
const blockedWebResponse = await web.status();
assert.equal(blockedCore.operationInProgress.actor, "external");
assert.equal(blockedCore.operationInProgress.busyScope, "codex-home");
assert.equal(blockedCore.statusReadBlocked.reason, "codex-home-lock");
assert.deepEqual(asLastComplete(blockedCore), asLastComplete(baselineCore));
assert.equal(blockedWebResponse.status, 200);
assert.equal(blockedWebResponse.payload.status.alignment.aligned, false);
assert.equal(blockedWebResponse.payload.status.operationInProgress.busyScope, "codex-home");
assert.deepEqual(
asLastComplete(blockedWebResponse.payload.status),
asLastComplete(baselineCore)
);
await releaseHolder();
releaseHolder = null;
assert.equal((await readCoreStatus()).currentProvider, "external");
await fs.writeFile(path.join(fixture.codexHome, "config.toml"), fixture.configText("openai"), "utf8");
assert.equal((await web.status()).status, 200);
const stateBaselineCore = await readCoreStatus();
releaseHolder = await startHolder({
mode: "state-db",
codexHome: fixture.codexHome,
stateDbPath: fixture.stateDbPath
});
const stateBlockedCore = await readCoreStatus();
const stateBlockedWeb = (await web.status()).payload.status;
assert.equal(stateBlockedCore.operationInProgress, null);
assert.equal(stateBlockedCore.statusReadBlocked, undefined);
assert.equal(stateBlockedCore.sqliteCounts.sessions.external, 1);
assert.equal(stateBlockedWeb.operationInProgress, null);
assert.equal(stateBlockedWeb.sqliteCounts.sessions.external, 1);
assert.notDeepEqual(asLastComplete(stateBlockedCore), asLastComplete(stateBaselineCore));
await releaseHolder();
releaseHolder = null;
const refreshed = await readCoreStatus();
assert.equal(refreshed.sqliteCounts.sessions.external, 1);
const lockDir = path.join(fixture.codexHome, "tmp", "provider-sync.lock");
await fs.mkdir(lockDir, { recursive: true });
await fs.writeFile(path.join(lockDir, "owner.json"), "{malformed", "utf8");
const unverifiable = await readCoreStatus();
assert.equal(unverifiable.operationInProgress.lockState, "unverifiable");
assert.equal(unverifiable.rolloutScanComplete, false);
assert.ok(unverifiable.statusReadBlocked);
await fs.rm(lockDir, { recursive: true, force: true });
} finally {
await releaseHolder?.().catch(() => {});
await web.close();
await fs.rm(fixture.root, { recursive: true, force: true });
}
});
// Model a writer appending just after the header is read, without timers,
// production hooks or any real Codex data. Status revisions also read bounded headers.
function afterHeaderRead(t, fixture, callback) {
const open = fs.open;
let reads = 0;
methodMocks.method(fs, "open", async (filePath, flags, ...args) => {
const handle = await open(filePath, flags, ...args);
if (filePath === fixture.rolloutPath && flags === "r") {
const close = handle.close.bind(handle);
handle.close = async () => { await close(); await callback(++reads); };
}
return handle;
});
return () => reads;
}
const syntheticAppend = (fixture) => fs.appendFile(fixture.rolloutPath,
'{"type":"event_msg","payload":{"type":"user_message","message":"synthetic append"}}\n');
async function syntheticProviderChange(fixture) {
const text = await fs.readFile(fixture.rolloutPath, "utf8");
fixture.providerMutations = (fixture.providerMutations ?? 0) + 1;
const provider = `p${String(fixture.providerMutations).padStart(5, "0")}`;
await fs.writeFile(fixture.rolloutPath, text.replace(/"model_provider":"[^"]+"/, `"model_provider":"${provider}"`));
}
for (const lockState of ["active", "unverifiable"]) {
test(`Diagnostics under ${lockState} lock exports safety without opening any rollout`, async () => {
const fixture = await makeFixture();
let release;
try {
if (lockState === "active") release = await acquireLock(fixture.codexHome, "sync");
else {
const lockDir = path.join(fixture.codexHome, "tmp", "provider-sync.lock");
await fs.mkdir(lockDir, { recursive: true });
await fs.writeFile(path.join(lockDir, "owner.json"), "{");
}
const open = fs.open;
const readFile = fs.readFile;
methodMocks.method(fs, "open", async (file, ...args) => {
assert.notEqual(file, fixture.rolloutPath, "blocked diagnostic must not open rollout");
return open(file, ...args);
});
methodMocks.method(fs, "readFile", async (file, ...args) => {
assert.notEqual(file, fixture.rolloutPath);
return readFile(file, ...args);
});
const result = await getDiagnostics({ codexHome: fixture.codexHome });
assert.equal(result.safety.operationInProgress.lockState, lockState);
assert.equal(result.safety.rolloutScanComplete, false);
assert.equal(result.historyIntegrity, undefined);
} finally {
methodMocks.restoreAll();
await release?.();
await fs.rm(fixture.root, { recursive: true, force: true });
}
});
}
for (const locked of [false, true]) {
test(`Diagnostics preserves current facts after revision failure, with Home lock priority (${locked})`, async (t) => {
const fixture = await makeFixture();
let release;
try {
await getStatus({ codexHome: fixture.codexHome, includeSessionActivity: false });
let armed = false;
let failed = false;
const stat = fs.stat;
methodMocks.method(fs, "stat", async (file, ...args) => {
if (armed && !failed && file === fixture.rolloutPath) {
failed = true;
if (locked) release = await acquireLock(fixture.codexHome, "synthetic-sync");
throw Object.assign(new Error("synthetic stat failure"), { code: "EIO" });
}
return stat(file, ...args);
});
const result = await getDiagnostics({ codexHome: fixture.codexHome, requestControl: { onProgress(event) {
if (event.stage === "inspect_diagnostics_index") armed = true;
} } });
assert.equal(failed, true);
assert.equal(result.safety.rolloutScanComplete, false);
if (locked) assert.equal(result.safety.operationInProgress.lockState, "active");
else {
assert.equal(result.safety.operationInProgress, null);
assert.equal(result.provider.rolloutCounts.sessions.openai, 1);
}
} finally {
methodMocks.restoreAll();
await release?.();
await fs.rm(fixture.root, { recursive: true, force: true });
}
});
}
test("Explicit Diagnostics scans facts once and retains current findings on drift without content hashing", async (t) => {
const fixture = await makeFixture();
try {
await getStatus({ codexHome: fixture.codexHome, includeSessionActivity: false });
const readFile = fs.readFile;
methodMocks.method(fs, "readFile", async (file, ...args) => {
assert.notEqual(file, fixture.rolloutPath, "diagnostic revision must not re-read/hash the rollout body");
return readFile(file, ...args);
});
let scans = 0;
const diagnostics = await getDiagnostics({ codexHome: fixture.codexHome, includeSessionActivity: false,
requestControl: { onProgress: (event) => {
if (event.stage === "inspect_diagnostics_index") {
scans += 1;
appendFileSync(fixture.rolloutPath, '{"type":"event_msg","payload":{"type":"user_message","message":"synthetic"}}\n');
}
} }
});
assert.equal(scans, 1);
assert.equal(diagnostics.safety.operationInProgress, null);
assert.equal(diagnostics.safety.rolloutScanComplete, false);
assert.equal(diagnostics.provider.rolloutCounts.sessions.openai, 1);
assert.equal(diagnostics.historyIntegrity.counts.filesScanned, 1);
} finally {
methodMocks.restoreAll();
await fs.rm(fixture.root, { recursive: true, force: true });
}
});
test("Diagnostic drift preserves findings but a real Home lock still takes priority", async (t) => {
const fixture = await makeFixture();
let release;
try {
await getStatus({ codexHome: fixture.codexHome, includeSessionActivity: false });
const readFile = fs.readFile;
let configReads = 0;
methodMocks.method(fs, "readFile", async (file, ...args) => {
const value = await readFile(file, ...args);
if (file === path.join(fixture.codexHome, "config.toml") && ++configReads === 2) {
await syntheticAppend(fixture);
release = await acquireLock(fixture.codexHome, "synthetic-sync");
}
return value;
});
const result = await getDiagnostics({ codexHome: fixture.codexHome });
assert.equal(configReads, 2);
assert.equal(result.safety.operationInProgress.lockState, "active");
assert.equal(result.safety.rolloutScanComplete, false);
} finally {
methodMocks.restoreAll();
await release?.();
await fs.rm(fixture.root, { recursive: true, force: true });
}
});
for (const revision of ["config", "state-db"]) {
test(`Status ${revision} drift also stays separate from operation state`, async (t) => {
const fixture = await makeFixture();
try {
afterHeaderRead(t, fixture, async (count) => {
if (revision === "config") {
await fs.writeFile(path.join(fixture.codexHome, "config.toml"), fixture.configText("new-provider"));
} else {
const database = await openDatabase(fixture.stateDbPath);
try { database.prepare("UPDATE threads SET model_provider = ? WHERE id = ?").run(`writer-${count}`, "status-thread"); }
finally { database.close(); }
}
});
const status = await getStatus({ codexHome: fixture.codexHome, includeSessionActivity: false });
assert.equal(status.operationInProgress, null);
assert.equal(status.rolloutScanComplete, false);
assert.deepEqual(status.statusReadBlocked, { reason: "state-changed-during-status", revision });
} finally {
methodMocks.restoreAll();
await fs.rm(fixture.root, { recursive: true, force: true });
}
});
}
for (const cached of [false, true]) {
test(`Status revision drift needs refresh, never a fabricated writer (cached=${cached})`, async (t) => {
const fixture = await makeFixture();
try {
const options = { codexHome: fixture.codexHome, includeSessionActivity: false };
const baseline = cached ? await getStatus(options) : null;
const reads = afterHeaderRead(t, fixture, () => syntheticProviderChange(fixture));
const blocked = await getStatus(options);
assert.equal(reads(), 5, "two bounded scans plus three header revisions, no polling");
assert.equal(blocked.operationInProgress, null);
assert.deepEqual(blocked.statusReadBlocked, { reason: "state-changed-during-status", revision: "rollout" });
assert.equal(blocked.rolloutScanComplete, false);
assert.equal(blocked.pendingRecovery, false);
if (baseline) {
assert.equal(blocked.snapshotAt, baseline.snapshotAt);
assert.deepEqual(blocked.rolloutCounts, baseline.rolloutCounts);
assert.equal(blocked.storageRevision, baseline.storageRevision);
} else {
assert.equal(blocked.currentProvider, undefined, "no invented Provider before the first complete snapshot");
}
methodMocks.restoreAll();
const refreshed = await getStatus(options);
assert.equal(refreshed.operationInProgress, null);
assert.equal(refreshed.statusReadBlocked, undefined);
assert.equal(refreshed.rolloutScanComplete, true);
assert.equal(refreshed.backupSummary.count, 0);
assert.deepEqual(refreshed.rolloutCounts.sessions, { p00005: 1 });
} finally {
methodMocks.restoreAll();
await fs.rm(fixture.root, { recursive: true, force: true });
}
});
}
test("Status remains available throughout ordinary appends without a retry", async (t) => {
const fixture = await makeFixture();
try {
const reads = afterHeaderRead(t, fixture, () => syntheticAppend(fixture));
const status = await getStatus({ codexHome: fixture.codexHome, includeSessionActivity: false });
assert.equal(reads(), 3, "one scan and two bounded Provider revisions, no retry for appends");
assert.equal(status.operationInProgress, null);
assert.equal(status.statusReadBlocked, undefined);
assert.equal(status.rolloutScanComplete, true);
} finally {
methodMocks.restoreAll();
await fs.rm(fixture.root, { recursive: true, force: true });
}
});
test("Status tolerates non-Provider SQLite WAL churn and never hashes database or chat bodies", async (t) => {
const fixture = await makeFixture();
const db = await openDatabase(fixture.stateDbPath);
try {
db.exec("PRAGMA journal_mode=WAL");
// A body much larger than the metadata read budget; never parse/hash it for Status.
await fs.appendFile(fixture.rolloutPath, "x".repeat(2 * 1024 * 1024));
const readFile = fs.readFile;
methodMocks.method(fs, "readFile", async (file, ...args) => {
assert.ok(![fixture.rolloutPath, fixture.stateDbPath, `${fixture.stateDbPath}-wal`, `${fixture.stateDbPath}-shm`].includes(file),
"Status must not read whole rollout/SQLite/WAL/SHM files");
return readFile(file, ...args);
});
const reads = afterHeaderRead(t, fixture, async count => {
await syntheticAppend(fixture);
db.prepare("UPDATE threads SET first_user_message = ?, cwd = ?, model = ? WHERE id = ?")
.run(`fixture-${count}`, `project-${count}`, `model-${count}`, "status-thread");
db.exec("PRAGMA wal_checkpoint(PASSIVE)");
});
const status = await getStatus({ codexHome: fixture.codexHome, includeSessionActivity: false });
assert.equal(reads(), 3);
assert.equal(status.statusReadBlocked, undefined);
assert.equal(status.operationInProgress, null);
assert.equal(status.rolloutScanComplete, true);
assert.deepEqual(status.rolloutCounts.sessions, { openai: 1 });
assert.deepEqual(status.sqliteCounts.sessions, { openai: 1 });
assert.equal(status.backupSummary.count, 0);
} finally {
methodMocks.restoreAll();
db.close();
await fs.rm(fixture.root, { recursive: true, force: true });
}
});
test("Status still rejects archived index drift rather than returning a mixed distribution", async (t) => {
const fixture = await makeFixture();
const db = await openDatabase(fixture.stateDbPath);
try {
afterHeaderRead(t, fixture, async count => {
db.prepare("UPDATE threads SET archived = ? WHERE id = ?").run(count, "status-thread");
});
const status = await getStatus({ codexHome: fixture.codexHome, includeSessionActivity: false });
assert.equal(status.statusReadBlocked?.revision, "state-db");
assert.equal(status.rolloutScanComplete, false);
assert.equal(status.operationInProgress, null);
} finally {
methodMocks.restoreAll();
db.close();
await fs.rm(fixture.root, { recursive: true, force: true });
}
});
test("HTTP Status stays usable during normal chatting", async (t) => {
const fixture = await makeFixture();
const web = await startRealWeb(fixture.codexHome, path.join(fixture.root, "web"));
try {
afterHeaderRead(t, fixture, () => syntheticAppend(fixture));
const response = await web.status();
assert.equal(response.status, 200);
assert.equal(response.payload.status.statusReadBlocked, undefined);
assert.equal(response.payload.status.rolloutScanComplete, true);
assert.equal(response.payload.status.alignment.aligned, true);
} finally {
methodMocks.restoreAll();
await web.close();
await fs.rm(fixture.root, { recursive: true, force: true });
}
});
test("Status keeps oversized metadata incomplete rather than claiming a healthy empty scan", async () => {
const fixture = await makeFixture();
try {
// A sparse, unterminated header exceeds the limit without allocating its text.
await fs.writeFile(fixture.rolloutPath, "x");
await fs.truncate(fixture.rolloutPath, 128 * 1024 * 1024 + 1);
const status = await getStatus({ codexHome: fixture.codexHome, includeSessionActivity: false });
assert.equal(status.rolloutScanComplete, false);
assert.equal(status.operationInProgress, null);
assert.deepEqual(status.rolloutCounts.sessions, {});
} finally { await fs.rm(fixture.root, { recursive: true, force: true }); }
});
for (const change of ["replace", "truncate"]) {
test(`Status rechecks a ${change} once and accepts the fresh stable snapshot`, async t => {
const fixture = await makeFixture();
try {
const header = await fs.readFile(fixture.rolloutPath);
await syntheticAppend(fixture);
const reads = afterHeaderRead(t, fixture, async count => {
if (count !== 1) return;
if (change === "truncate") await fs.truncate(fixture.rolloutPath, header.length);
else {
await fs.rename(fixture.rolloutPath, `${fixture.rolloutPath}.old`);
await fs.writeFile(fixture.rolloutPath, header);
}
});
const status = await getStatus({ codexHome: fixture.codexHome, includeSessionActivity: false });
assert.equal(status.statusReadBlocked, undefined);
assert.equal(reads(), 5, "one bounded fresh scan verifies the replacement; no polling");
assert.equal(status.rolloutScanComplete, true);
assert.deepEqual(status.rolloutCounts.sessions, { openai: 1 });
assert.equal(status.operationInProgress, null);
} finally {
methodMocks.restoreAll();
await fs.rm(fixture.root, { recursive: true, force: true });
}
});
}
for (const phase of [0, 2, 4]) {
test(`Status revision capture failure at phase ${phase} stays unverified, not busy`, async (t) => {
const fixture = await makeFixture();
try {
const reads = afterHeaderRead(t, fixture, () => syntheticProviderChange(fixture));
const stat = fs.lstat;
methodMocks.method(fs, "lstat", async (filePath, ...args) => {
if (filePath === fixture.rolloutPath && reads() >= phase) {
throw Object.assign(new Error("synthetic revision failure"), { code: "EIO" });
}
return stat(filePath, ...args);
});
const status = await getStatus({ codexHome: fixture.codexHome, includeSessionActivity: false });
assert.equal(reads(), phase);
assert.equal(status.operationInProgress, null);
assert.equal(status.statusReadBlocked.reason, "revision-unverifiable");
assert.equal(status.rolloutScanComplete, false);
methodMocks.restoreAll();
assert.equal((await getStatus({ codexHome: fixture.codexHome, includeSessionActivity: false })).statusReadBlocked, undefined);
} finally {
methodMocks.restoreAll();
await fs.rm(fixture.root, { recursive: true, force: true });
}
});
}
test("A real Home lock acquired during the retry takes priority over revision drift", async (t) => {
const fixture = await makeFixture();
let release;
try {
afterHeaderRead(t, fixture, async (count) => {
await syntheticProviderChange(fixture);
if (count === 4) release = await acquireLock(fixture.codexHome, "synthetic-sync");
});
const status = await getStatus({ codexHome: fixture.codexHome, includeSessionActivity: false });
assert.equal(status.statusReadBlocked.reason, "codex-home-lock");
assert.equal(status.operationInProgress.lockState, "active");
assert.equal(status.operationInProgress.busyScope, "codex-home");
} finally {
methodMocks.restoreAll();
await release?.();
await fs.rm(fixture.root, { recursive: true, force: true });
}
});
test("Core facade and HTTP preserve the refresh-needed state without a busy operation", async (t) => {
const fixture = await makeFixture();
const web = await startRealWeb(fixture.codexHome, path.join(fixture.root, "web"));
try {
afterHeaderRead(t, fixture, () => syntheticProviderChange(fixture));
const response = await web.status();
assert.equal(response.status, 200);
assert.equal(response.payload.status.operationInProgress, null);
assert.deepEqual(response.payload.status.statusReadBlocked, { reason: "state-changed-during-status" });
assert.equal(response.payload.status.rolloutScanComplete, false);
assert.equal(response.payload.status.alignment.aligned, false);
methodMocks.restoreAll();
assert.equal((await web.status()).payload.status.statusReadBlocked, undefined);
} finally {
methodMocks.restoreAll();
await web.close();
await fs.rm(fixture.root, { recursive: true, force: true });
}
});