Skip to content

Commit c6862ad

Browse files
committed
fix(codex): keep user edits to config.toml across ocx sync
Injection (run by ocx sync, start, and settings changes) removed every root model_context_window even though OpenCodex never writes that key, and it rewrote a marker-owned [agents] default_subagent_* value whenever the marker comment survived, including after the user edited the value. Root model_context_window is now left alone. The journal records the exact managed sub-agent default values each injection writes; a marked value that no longer matches that record is adopted as user-owned (its marker is dropped) on both sync and restore. Without a record the marker alone still decides. Refs #7425
1 parent 516aaaa commit c6862ad

14 files changed

Lines changed: 302 additions & 76 deletions

File tree

‎docs-site/src/content/docs/guides/codex-integration.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -407,6 +407,10 @@ Root keys such as `openai_base_url`, `model_provider`, and `model_catalog_json`
407407
first `[table]` header. The injector guarantees that placement, removes its own stale/duplicate
408408
copies, and never overwrites a user-owned root `openai_base_url`; if one exists, sync updates the
409409
catalog but reports that routing was not injected.
410+
411+
Sync and restore also leave a root `model_context_window` in place, since OpenCodex never writes
412+
that key. Codex applies it to every model ahead of the catalog's per-model windows, so delete it
413+
yourself if you want each model to report its own window.
410414
:::
411415

412416
## Shared model catalog

‎docs-site/src/content/docs/guides/sub-agent-surface.md‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -137,9 +137,11 @@ opencodex no sign that v1 is available, so the guidance is not added there.
137137
The default-off `syncCodexSubagentDefaults` option is separate from guidance. When opencodex owns
138138
active Codex routing, sync or restart can write the selected values as marker-owned
139139
`[agents] default_subagent_model` and `default_subagent_reasoning_effort` entries in Codex TOML.
140-
opencodex updates or removes only fields bearing its markers. If either target field is user-owned,
141-
the pair is left unchanged rather than partially written; ambiguous TOML is rejected without a
142-
write. External provider managers and user-owned root routing also remain authoritative.
140+
opencodex updates or removes only fields bearing its markers. If you edit a managed value in place,
141+
the next sync keeps your value, drops the marker, and treats the field as yours from then on. If
142+
either target field is user-owned, the pair is left unchanged rather than partially written;
143+
ambiguous TOML is rejected without a write. External provider managers and user-owned root
144+
routing also remain authoritative.
143145

144146
## Fallback chains
145147

‎scripts/test-layout/layout.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -723,7 +723,7 @@
723723
"codex-sqlite-home.test.ts": "codex-integration",
724724
"codex-sync-api.test.ts": "codex-integration",
725725
"codex-sync-new-model-policy.test.ts": "codex-integration",
726-
"codex-sync-response.test.ts": "codex-integration",
726+
"codex-sync-response.test.ts": "codex-integration", "codex-sync-user-edits.test.ts": "codex-integration",
727727
"codex-tool-mode.test.ts": "codex-integration",
728728
"codex-transition-state-adoption.test.ts": "codex-integration",
729729
"codex-transition-state-first-use-regression.test.ts": "codex-integration",

‎src/codex/inject.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -512,6 +512,7 @@ async function injectCodexConfigImpl(
512512
// not durable) and the line we removed (so re-enabling the sidecar can return it).
513513
injectedRootWebSearch: plan.injectedRootWebSearch,
514514
replacedRootWebSearch: plan.replacedRootWebSearch,
515+
injectedSubagentDefaults: plan.injectedSubagentDefaults,
515516
// This is the catalog artifact selected for this injection, even when config.toml
516517
// already points at that path and therefore needs no textual rewrite.
517518
injectedCatalogPath: plan.catalogPath,
@@ -896,7 +897,6 @@ export {
896897
setRootOpenaiBaseUrl,
897898
setRootRealtimeWsBaseUrl,
898899
stripInjectedOpenaiBaseUrl,
899-
stripRootContextWindowOverrides,
900900
} from "./inject/config-toml";
901901

902902
export {

‎src/codex/inject/config-toml.ts‎

Lines changed: 0 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -479,24 +479,6 @@ export function stripExistingModelProvider(content: string): string {
479479
return bom + sourceText(lines.filter((_, index) => !drop.has(index)));
480480
}
481481

482-
/**
483-
* Drop ROOT-level `model_context_window` overrides (keys before the first table header). Codex
484-
* treats this root key as a global override that wins over the per-model catalog values, so a stale
485-
* `model_context_window = 1000000` makes every model (e.g. gpt-5.5) report a 1M window. User-owned
486-
* compaction limits do not alter the advertised context window and must survive reinjection.
487-
*/
488-
export function stripRootContextWindowOverrides(content: string): string {
489-
const { bom, lines, rootEnd } = rootSourceLines(content);
490-
const drop = new Set<number>();
491-
for (let index = 0; index < rootEnd; index++) {
492-
if (!lines[index]!.structural || rootAssignmentKey(lines[index]!.text) !== "model_context_window") continue;
493-
const assignment = sourceAssignmentSpan(lines, index, rootEnd);
494-
if (!assignment) throw new Error("Cannot safely rewrite an incomplete model_context_window assignment.");
495-
for (let at = index; at < assignment.end; at++) drop.add(at);
496-
}
497-
return bom + sourceText(lines.filter((_, index) => !drop.has(index)));
498-
}
499-
500482
export function stripRootRoutedModel(content: string): string {
501483
const { bom, lines, rootEnd } = rootSourceLines(content);
502484
return bom + sourceText(lines.filter((line, index) => index >= rootEnd || !line.structural

‎src/codex/inject/plan.ts‎

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,12 @@ import {
1818
journaledInjectedOpenaiBaseUrl,
1919
journaledInjectedRealtimeWsBaseUrl,
2020
journaledInjectedRootWebSearch,
21+
journaledInjectedSubagentDefaults,
2122
journaledReplacedRootWebSearch,
2223
} from "../journal";
2324
import { stripJournaledOpenaiBaseUrl } from "../injected-marker";
2425
import { CODEX_CONFIG_PATH, resolveCodexStateDbPath } from "../paths";
25-
import { transformManagedSubagentDefaults } from "../subagent-defaults";
26+
import { transformManagedSubagentDefaults, type WrittenSubagentDefaults } from "../subagent-defaults";
2627
import type { OcxConfig } from "../../types";
2728
import type { CodexWriteCandidate } from "../write-coordination";
2829
import {
@@ -42,7 +43,6 @@ import {
4243
stripExistingModelProvider,
4344
stripInjectedOpenaiBaseUrl,
4445
stripOpencodexCatalogPath,
45-
stripRootContextWindowOverrides,
4646
} from "./config-toml";
4747
import { hasOcxProviderTable, removeOcxSection } from "./remove";
4848
import {
@@ -81,6 +81,8 @@ export interface CodexInjectionPlanOk {
8181
injectedRootWebSearch: string | null;
8282
/** The user-owned root `web_search` line this plan removed, for the journal to carry. */
8383
replacedRootWebSearch: string | null;
84+
/** The marker-owned `[agents]` defaults this plan writes, for the journal to carry; null when none. */
85+
injectedSubagentDefaults: WrittenSubagentDefaults | null;
8486
nativeSubagentDefaultsWarning: string | undefined;
8587
managedDefaultsMessage: string;
8688
/**
@@ -130,9 +132,12 @@ export function deriveCodexInjectionPlan(
130132
// root routing key: inserting that key ahead of a marker-owned first table
131133
// would otherwise separate the table marker from its header. Ambiguous
132134
// markers fail closed without writing config, profile, or journal state.
135+
// A marked value that no longer matches the journaled write was edited by the
136+
// user (#7425); it is adopted into the baseline instead of being cleaned.
133137
const nativeDefaultsBaseline = transformManagedSubagentDefaults(
134138
source,
135139
null,
140+
journaledInjectedSubagentDefaults({ readOnly: ctx.journalReadOnly }),
136141
);
137142
if (!nativeDefaultsBaseline.ok) {
138143
return {
@@ -186,7 +191,8 @@ export function deriveCodexInjectionPlan(
186191
}
187192
content = removeProfileSection(content);
188193
content = stripExistingModelProvider(content);
189-
content = stripRootContextWindowOverrides(content);
194+
// A root `model_context_window` is never written by OpenCodex, so it is the user's choice and
195+
// survives injection (#7425). Codex applies it to every model ahead of the catalog's windows.
190196
content = normalizeServiceTier(content);
191197
content = ensureFastModeFeature(content, config?.fastMode);
192198
// Codex's own web-search switch follows the sidecar's master switch. While the sidecar is off,
@@ -291,6 +297,7 @@ export function deriveCodexInjectionPlan(
291297
let managedDefaultsMessage = routingOwnershipWarning
292298
? ` ⚠️ ${routingOwnershipWarning}\n`
293299
: "";
300+
let injectedSubagentDefaults: WrittenSubagentDefaults | null = null;
294301
if (managedDefaults.ok) {
295302
content = managedDefaults.content;
296303
if (desiredSubagentDefaults && managedDefaults.conflicts.length > 0) {
@@ -299,6 +306,13 @@ export function deriveCodexInjectionPlan(
299306
.join(", ");
300307
nativeSubagentDefaultsWarning = `Native Codex sub-agent defaults were not injected: user-owned ${keys} preserved.`;
301308
managedDefaultsMessage = ` ⚠️ ${nativeSubagentDefaultsWarning}\n`;
309+
} else if (desiredSubagentDefaults && !keptUserBaseUrl) {
310+
injectedSubagentDefaults = {
311+
default_subagent_model: desiredSubagentDefaults.model,
312+
...(desiredSubagentDefaults.reasoningEffort !== undefined
313+
? { default_subagent_reasoning_effort: desiredSubagentDefaults.reasoningEffort }
314+
: {}),
315+
};
302316
}
303317
} else {
304318
const action =
@@ -388,6 +402,7 @@ export function deriveCodexInjectionPlan(
388402
keptUserRealtimeWsBaseUrl,
389403
injectedRootWebSearch: webSearch.wroteValue,
390404
replacedRootWebSearch: webSearch.replacedUserLine,
405+
injectedSubagentDefaults,
391406
nativeSubagentDefaultsWarning,
392407
managedDefaultsMessage,
393408
historyRelabelRefusal: observedHistoryRefusal,

‎src/codex/inject/remove.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,13 @@ import {
1515
journaledInjectedOpenaiBaseUrl,
1616
journaledInjectedRealtimeWsBaseUrl,
1717
journaledInjectedRootWebSearch,
18+
journaledInjectedSubagentDefaults,
1819
journaledReplacedRootWebSearch,
1920
} from "../journal";
2021
import { CODEX_CONFIG_PATH, CODEX_PROFILE_PATH } from "../paths";
2122
import { getCodexHome } from "../paths";
2223
import { codexHomeIsAbsent } from "../codex-home-owner";
23-
import { transformManagedSubagentDefaults } from "../subagent-defaults";
24+
import { transformManagedSubagentDefaults, type WrittenSubagentDefaults } from "../subagent-defaults";
2425
import {
2526
applyEol,
2627
dominantEol,
@@ -93,6 +94,7 @@ function stripOpencodexConfigResult(
9394
journaledRealtimeWsBaseUrl: string | null = null,
9495
journaledRootWebSearch: string | null = null,
9596
journaledReplacedWebSearch: string | null = null,
97+
journaledSubagentDefaults: WrittenSubagentDefaults | null = null,
9698
): StripOpencodexConfigResult {
9799
let out = content;
98100
const hadRootOcxProvider =
@@ -129,7 +131,8 @@ function stripOpencodexConfigResult(
129131
// Routed root model ids (`model = "provider/slug"`) only make sense while the proxy serves
130132
// them — strip on both the legacy re-tag form and the Design B injected-base-url form.
131133
if (hadRootOcxProvider || hadInjectedBaseUrl) out = stripRootRoutedModel(out);
132-
const managedDefaults = transformManagedSubagentDefaults(out, null);
134+
// A marked value the user edited after injection is theirs (#7425) and survives restore.
135+
const managedDefaults = transformManagedSubagentDefaults(out, null, journaledSubagentDefaults);
133136
if (managedDefaults.ok) out = managedDefaults.content;
134137
out = stripOpencodexCatalogPath(out);
135138
return {
@@ -246,6 +249,7 @@ export function removeCodexConfig(
246249
journaledRealtimeWsBaseUrl,
247250
journaledRootWebSearch,
248251
journaledReplaced,
252+
journaledInjectedSubagentDefaults(),
249253
);
250254
// Captured from the pre-strip bytes: the strip is what removes the table, so reading it
251255
// afterwards would find nothing.

‎src/codex/journal.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import { hasInjectedCodexRouting } from "./injected-marker";
99
import { configWriteLockFailureMessage, withConfigWriteLockHeld } from "./config-write-lock";
1010
import type { LockHandle } from "./config-write-lock";
1111
import { CODEX_HOME, CODEX_CONFIG_PATH, CODEX_PROFILE_PATH } from "./paths";
12+
import type { WrittenSubagentDefaults } from "./subagent-defaults";
1213

1314
/**
1415
* Exported so that anything reasoning ABOUT the journal points at the journal.
@@ -76,6 +77,15 @@ interface Journal {
7677
* file we actually touched.
7778
*/
7879
injectedCatalogPath?: string | null;
80+
/**
81+
* The marker-owned `[agents]` default values this injection wrote, keyed by TOML key.
82+
*
83+
* #7425: the marker comment proves OpenCodex wrote a line once, not that the value is still
84+
* ours. A user (or a comment-preserving Codex settings writer) can change the value and keep
85+
* the comment, and the next sync used to revert it. The recorded value is what tells an
86+
* untouched managed line apart from an edited one. Null when no managed default was written.
87+
*/
88+
injectedSubagentDefaults?: WrittenSubagentDefaults | null;
7989
/** Injection binding survives native snapshot replacement and is released by native restore. */
8090
opencodexHome?: string;
8191
pid: number;
@@ -203,6 +213,8 @@ export interface InjectedJournalOwnership {
203213
injectedRootWebSearch?: string | null;
204214
/** Omitted by callers that removed no user `web_search` line. */
205215
replacedRootWebSearch?: string | null;
216+
/** Omitted by callers that wrote no managed `[agents]` default, which is the value it then records. */
217+
injectedSubagentDefaults?: WrittenSubagentDefaults | null;
206218
}
207219

208220
export function markJournalInjectedState(
@@ -230,6 +242,7 @@ export function markJournalInjectedState(
230242
journal.injectedRealtimeWsBaseUrl = ownership.injectedRealtimeWsBaseUrl;
231243
journal.injectedRootWebSearch = ownership.injectedRootWebSearch ?? null;
232244
journal.replacedRootWebSearch = ownership.replacedRootWebSearch ?? null;
245+
journal.injectedSubagentDefaults = ownership.injectedSubagentDefaults ?? null;
233246
journal.injectedCatalogPath = ownership.injectedCatalogPath;
234247
journal.opencodexHome = opencodexHomeForInjection(journal.opencodexHome);
235248
atomicWriteFile(JOURNAL_PATH, JSON.stringify(journal), undefined, hooks);
@@ -267,6 +280,21 @@ export function journaledInjectedCatalogPath(): string | null {
267280
return readJournal()?.injectedCatalogPath ?? null;
268281
}
269282

283+
/**
284+
* The managed `[agents]` default values the last injection wrote, or null when there is no
285+
* record. The journal is read from disk, so only string values for the two known keys count.
286+
*/
287+
export function journaledInjectedSubagentDefaults(options: { readOnly?: boolean } = {}): WrittenSubagentDefaults | null {
288+
const recorded: unknown = readJournal(options.readOnly !== true)?.injectedSubagentDefaults;
289+
if (typeof recorded !== "object" || recorded === null) return null;
290+
const written: WrittenSubagentDefaults = {};
291+
for (const key of ["default_subagent_model", "default_subagent_reasoning_effort"] as const) {
292+
const value = (recorded as Record<string, unknown>)[key];
293+
if (typeof value === "string") written[key] = value;
294+
}
295+
return Object.keys(written).length > 0 ? written : null;
296+
}
297+
270298
export function removeJournal(hooks: AtomicWriteHooks = {}): void {
271299
assertCodexHomeOwner(CODEX_HOME);
272300
hooks.validateBeforeRename?.(JOURNAL_PATH);

‎src/codex/subagent-defaults.ts‎

Lines changed: 56 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,16 @@ export interface ManagedSubagentDefaults {
2121
reasoningEffort?: string;
2222
}
2323

24+
/**
25+
* The exact values the last injection wrote under a marker, as recorded in the
26+
* injection journal. A marker proves only that OpenCodex once wrote the line;
27+
* this record proves which value it wrote. A marked value that no longer
28+
* matches it was edited by someone else — the user, or a Codex settings writer
29+
* that keeps comments — and is adopted as user-owned instead of reverted.
30+
* Absent (`null`/`undefined`) means no evidence, and the marker alone decides.
31+
*/
32+
export type WrittenSubagentDefaults = Partial<Record<ManagedSubagentDefaultKey, string>>;
33+
2434
export interface ManagedSubagentDefaultsConflict {
2535
key: ManagedSubagentDefaultKey;
2636
line: number;
@@ -303,15 +313,50 @@ function invalidInput(content: string, error: string): ManagedSubagentDefaultsTr
303313
return { ok: false, changed: false, content, conflicts: [], error };
304314
}
305315

316+
/** The decoded string value of a single-line `key = "value"` assignment, or null. */
317+
function assignedString(line: SourceLine, key: ManagedSubagentDefaultKey): string | null {
318+
try {
319+
const value = (Bun.TOML.parse(line.text) as Record<string, unknown>)[key];
320+
return typeof value === "string" ? value : null;
321+
} catch { // no-excuse-ok: catch -- an unparsable value is not edit evidence; the replace step rejects it.
322+
return null;
323+
}
324+
}
325+
326+
/**
327+
* Marker lines whose value differs from what OpenCodex recorded writing. The
328+
* marker is dropped so the line reads as what it now is: a user-owned value.
329+
*/
330+
function userEditedMarkers(
331+
lines: readonly SourceLine[],
332+
shape: TomlShape,
333+
written: WrittenSubagentDefaults | null | undefined,
334+
): number[] {
335+
if (!written) return [];
336+
const stale: number[] = [];
337+
for (const definition of shape.definitions.values()) {
338+
const recorded = written[definition.key];
339+
if (!definition.owned || typeof recorded !== "string") continue;
340+
const current = assignedString(lines[definition.index]!, definition.key);
341+
if (current !== null && current !== recorded) stale.push(definition.index - 1);
342+
}
343+
return stale;
344+
}
345+
306346
/**
307347
* Add/update opencodex-owned native subagent defaults, or remove them with
308348
* `defaults = null`. Unmarked target keys are user-owned: they are retained and
309349
* returned as conflicts rather than overwritten. Ambiguous TOML is rejected
310350
* byte-for-byte so callers never have to guess what was changed.
351+
*
352+
* `written` is the journal's record of the values the last injection wrote.
353+
* When supplied, a marked value that differs from it is user-edited: its marker
354+
* is dropped and the value is treated exactly like any other user-owned key.
311355
*/
312356
export function transformManagedSubagentDefaults(
313357
content: string,
314358
defaults: ManagedSubagentDefaults | null,
359+
written?: WrittenSubagentDefaults | null,
315360
): ManagedSubagentDefaultsTransformResult {
316361
if (defaults !== null) {
317362
if (typeof defaults.model !== "string" || defaults.model.length === 0) {
@@ -329,14 +374,20 @@ export function transformManagedSubagentDefaults(
329374
}
330375
}
331376

332-
const lines = splitSourceLines(content);
377+
let lines = splitSourceLines(content);
333378
if (defaults === null && !lines.some(line =>
334379
markerLine(line, MANAGED_SUBAGENT_DEFAULT_MARKER)
335380
|| markerLine(line, MANAGED_AGENTS_TABLE_MARKER))) {
336381
return { ok: true, changed: false, content, conflicts: [] };
337382
}
338-
const analysis = analyzeToml(lines);
383+
let analysis = analyzeToml(lines);
339384
if ("error" in analysis) return invalidInput(content, analysis.error);
385+
const stale = new Set(userEditedMarkers(lines, analysis.shape, written));
386+
if (stale.size > 0) {
387+
lines = lines.filter((_, index) => !stale.has(index));
388+
analysis = analyzeToml(lines);
389+
if ("error" in analysis) return invalidInput(content, analysis.error);
390+
}
340391
const { shape } = analysis;
341392
const eol = dominantEol(lines);
342393
const desired = new Map<ManagedSubagentDefaultKey, string>();
@@ -361,8 +412,10 @@ export function transformManagedSubagentDefaults(
361412
// Model and effort are one effective native-default pair. A partial write
362413
// could apply a newly managed effort to a user's model (or vice versa), so
363414
// any desired-key ownership conflict makes the whole enable/update a no-op.
415+
// Only an adopted user edit's stale marker is dropped from the result.
364416
if (conflicts.length > 0) {
365-
return { ok: true, changed: false, content, conflicts };
417+
const adopted = joinSourceLines(lines);
418+
return { ok: true, changed: adopted !== content, content: adopted, conflicts };
366419
}
367420
}
368421

‎structure/config.md‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -206,12 +206,12 @@ reading prose as configuration; formatted doctor paths pass through user-path re
206206

207207
> Decision record: [ADR-0017](decisions/ADR-0017-config-injection.md)
208208
209-
Native Codex sub-agent defaults are a separate, explicit opt-in. When
210-
`syncCodexSubagentDefaults` is true and `injectionModel` is set, injection writes marker-owned
211-
`agents.default_subagent_model` and, when configured,
212-
`agents.default_subagent_reasoning_effort`. Unmarked values are user-owned and must never be
213-
overwritten. Disabling the option and fallback restore remove only marker-owned values; journal
214-
restore must preserve later user edits while stripping those managed values.
209+
Native Codex sub-agent defaults are a separate, explicit opt-in. When `syncCodexSubagentDefaults`
210+
is true and `injectionModel` is set, injection writes marker-owned `agents.default_subagent_model`
211+
and, when configured, `agents.default_subagent_reasoning_effort`, and journals the values it wrote.
212+
Unmarked values, and marked values that differ from that record (#7425), are user-owned and never
213+
overwritten; the stale marker is dropped. Disabling and fallback restore remove only owned values;
214+
journal restore keeps later user edits. Injection never writes or strips root `model_context_window`.
215215

216216
An injection whose OpenCodex config explicitly selects the v1 multi-agent surface also
217217
reconciles Codex's higher-precedence global `features.multi_agent_v2` override to disabled before

0 commit comments

Comments
 (0)