docks-kit 0.22.28 → 0.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/AGENTS.md +42 -89
  2. package/README.md +35 -72
  3. package/cli/docs/command-guards.md +233 -197
  4. package/cli/docs/flags.md +17 -65
  5. package/cli/docs/install.md +2 -3
  6. package/cli/docs/omp-context.md +79 -7
  7. package/cli/docs/omp-models.md +27 -12
  8. package/cli/docs/overview.md +7 -18
  9. package/cli/docs/platforms.md +2 -2
  10. package/cli/docs/sync-layers.md +14 -60
  11. package/cli/docs/toolchain.md +12 -81
  12. package/cli/src/argv.ts +0 -12
  13. package/cli/src/argvValidate.ts +3 -54
  14. package/cli/src/commands/docs.ts +3 -15
  15. package/cli/src/commands/omp.ts +1 -1
  16. package/cli/src/commands/scratch.ts +1 -1
  17. package/cli/src/commands/sync.ts +5 -120
  18. package/cli/src/commands/tidy.ts +1 -1
  19. package/cli/src/commands/toolchain.ts +4 -12
  20. package/cli/src/engine-native/DESIGN.md +69 -100
  21. package/cli/src/engine-native/deps.ts +7 -92
  22. package/cli/src/engine-native/engineCtx.ts +9 -103
  23. package/cli/src/engine-native/exec.ts +1 -18
  24. package/cli/src/engine-native/index.ts +6 -8
  25. package/cli/src/engine-native/jq.ts +4 -37
  26. package/cli/src/engine-native/kitDb.ts +21 -37
  27. package/cli/src/engine-native/modes.ts +3 -132
  28. package/cli/src/engine-native/ompFastMode.ts +1 -1
  29. package/cli/src/engine-native/ompOverlay.ts +1 -1
  30. package/cli/src/engine-native/ompRemovals.ts +24 -3
  31. package/cli/src/engine-native/ompSession.ts +67 -0
  32. package/cli/src/engine-native/ompSync.ts +1 -1
  33. package/cli/src/engine-native/os/darwin.ts +0 -4
  34. package/cli/src/engine-native/os/index.ts +1 -2
  35. package/cli/src/engine-native/os/linux.ts +0 -3
  36. package/cli/src/engine-native/os/posix.ts +2 -47
  37. package/cli/src/engine-native/os/types.ts +1 -36
  38. package/cli/src/engine-native/os/windows.ts +0 -50
  39. package/cli/src/engine-native/parseArgs.ts +7 -180
  40. package/cli/src/engine-native/parseHelp.ts +4 -44
  41. package/cli/src/engine-native/scratch.ts +1 -1
  42. package/cli/src/engine-native/services.ts +1 -2
  43. package/cli/src/engine-native/sharedTypes.d.ts +1 -41
  44. package/cli/src/engine-native/syncConcurrency.ts +3 -15
  45. package/cli/src/engine-native/syncDispatch.ts +30 -143
  46. package/cli/src/engine-native/toolchain.ts +6 -45
  47. package/cli/src/engine.ts +0 -75
  48. package/cli/src/generated/sotPayload.ts +14 -43
  49. package/cli/src/main.ts +8 -24
  50. package/cli/src/payload.ts +2 -8
  51. package/cli/tsconfig.json +1 -3
  52. package/package.json +3 -5
  53. package/cli/docs/models.md +0 -58
  54. package/cli/docs/modifiers.md +0 -52
  55. package/cli/docs/plugins.md +0 -70
  56. package/cli/src/checklistPrompt.ts +0 -464
  57. package/cli/src/commands/harnesses.ts +0 -80
  58. package/cli/src/commands/model.ts +0 -68
  59. package/cli/src/commands/models.ts +0 -75
  60. package/cli/src/commands/plugins.ts +0 -35
  61. package/cli/src/commands/skills.ts +0 -40
  62. package/cli/src/commands/status.ts +0 -206
  63. package/cli/src/efforts.ts +0 -89
  64. package/cli/src/engine-native/claudeLsp.ts +0 -301
  65. package/cli/src/engine-native/claudeOptionalPlugins.ts +0 -126
  66. package/cli/src/engine-native/claudePluginPasses.ts +0 -426
  67. package/cli/src/engine-native/claudeRemovals.ts +0 -383
  68. package/cli/src/engine-native/claudeRetired.ts +0 -165
  69. package/cli/src/engine-native/claudeRuntime.ts +0 -157
  70. package/cli/src/engine-native/claudeSettings.ts +0 -201
  71. package/cli/src/engine-native/claudeSettingsModifiers.ts +0 -115
  72. package/cli/src/engine-native/claudeSync.ts +0 -312
  73. package/cli/src/engine-native/codexConfig.ts +0 -214
  74. package/cli/src/engine-native/codexHooks.ts +0 -91
  75. package/cli/src/engine-native/codexPaths.ts +0 -14
  76. package/cli/src/engine-native/codexPlugins.ts +0 -315
  77. package/cli/src/engine-native/codexStatus.ts +0 -25
  78. package/cli/src/engine-native/codexSync.ts +0 -314
  79. package/cli/src/engine-native/codexToml.ts +0 -303
  80. package/cli/src/engine-native/harnesses.ts +0 -138
  81. package/cli/src/engine-native/liveModels.ts +0 -264
  82. package/cli/src/engine-native/models.ts +0 -101
  83. package/cli/src/engine-native/parseModifiers.ts +0 -225
  84. package/cli/src/engine-native/settings.ts +0 -42
  85. package/cli/src/engine-native/skillsInstall.ts +0 -135
  86. package/cli/src/engine-native/skillsLinks.ts +0 -216
  87. package/cli/src/engine-native/skillsManifest.ts +0 -36
  88. package/cli/src/engine-native/skillsPrune.ts +0 -117
  89. package/cli/src/engine-native/skillsRecords.ts +0 -138
  90. package/cli/src/engine-native/skillsSync.ts +0 -57
  91. package/cli/src/engine-native/tomlLines.ts +0 -92
  92. package/cli/src/manifests.ts +0 -145
  93. package/cli/src/terminalCells.ts +0 -191
@@ -1,314 +0,0 @@
1
- /**
2
- * EngineNative `sync codex` pipeline. Line-based TOML passes intentionally
3
- * avoid a TOML library because reformatting user configs would be a behavior
4
- * change. Guard order, message strings, and backup behavior are golden-tested.
5
- */
6
- import { createHash } from "node:crypto";
7
- import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
8
-
9
- import { resolveEffort } from "../efforts";
10
- import {
11
- payloadBytes,
12
- payloadDisplayPath,
13
- payloadPaths,
14
- payloadText,
15
- type PayloadPath,
16
- } from "../payload";
17
- import { replaceFile, replaceTextIfChanged } from "./atomicWrite";
18
- import { syncConfig } from "./codexConfig";
19
- import { removeRetiredImportedHooks } from "./codexHooks";
20
- import { codexHome } from "./codexPaths";
21
- import { removeLegacyDocksMarketplace, syncMarketplace, syncPlugins } from "./codexPlugins";
22
- import { replaceTopLevelSetting, syncCodexEffort, syncCodexModel } from "./codexToml";
23
- import { p, spawnProcess } from "./exec";
24
- import type { Ctx } from "./index";
25
- import { compareCodepoints } from "./jq";
26
- import { hostOs } from "./os";
27
-
28
- export { removeRetiredPluginTablesText } from "./codexConfig";
29
- export { codexNextSteps, codexSummary } from "./codexStatus";
30
-
31
- export async function codexSync(ctx: Ctx): Promise<void> {
32
- const codexDir = codexHome(ctx.home);
33
- const sotConfig = payloadText("SoT/.codex/config.toml");
34
- const userConfig = p(codexDir, "config.toml");
35
-
36
- // Merge the SoT with the --codex-model / --codex-effort values already applied.
37
- // A repeated modifier run then merges to the same bytes and keeps config.toml.bak.
38
- let deployedSotConfig = sotConfig;
39
- if (ctx.codexModel !== "") {
40
- deployedSotConfig = replaceTopLevelSetting(
41
- deployedSotConfig,
42
- "model",
43
- `model = "${ctx.codexModel}"`,
44
- );
45
- }
46
- if (ctx.codexEffort !== "") {
47
- deployedSotConfig = replaceTopLevelSetting(
48
- deployedSotConfig,
49
- "model_reasoning_effort",
50
- `model_reasoning_effort = "${resolveEffort("codex", ctx.codexEffort)}"`,
51
- );
52
- }
53
-
54
- await ensureBubblewrap(ctx);
55
- if (!ctx.dryRun) mkdirSync(codexDir, { recursive: true });
56
- // Only a real sync compares against this text; a dry run reads nothing.
57
- const deployedBefore = ctx.dryRun
58
- ? undefined
59
- : existsSync(userConfig)
60
- ? readFileSync(userConfig, "utf8")
61
- : "";
62
- syncConfig(ctx, deployedSotConfig, userConfig);
63
- removeRetiredImportedHooks(ctx, codexDir);
64
- syncCodexModel(ctx, ctx.codexModel, deployedBefore);
65
- syncCodexEffort(ctx, ctx.codexEffort, deployedBefore);
66
- syncRules(
67
- ctx,
68
- payloadPaths("SoT/.codex/rules/"),
69
- p(codexDir, "rules"),
70
- p(codexDir, ".kit-managed-rules"),
71
- );
72
- syncAgentsMd(ctx, payloadText("SoT/.codex/AGENTS.md"), p(codexDir, "AGENTS.md"));
73
- const unresolvedMarketplace = syncMarketplace(
74
- ctx,
75
- payloadText("SoT/.codex/plugins/marketplace.json"),
76
- p(ctx.agentsDir, "plugins", "marketplace.json"),
77
- );
78
- await removeLegacyDocksMarketplace(ctx, userConfig);
79
- await syncPlugins(ctx, sotConfig, unresolvedMarketplace);
80
- }
81
-
82
- // ---------------------------------------------------------- bubblewrap ----
83
-
84
- async function ensureBubblewrap(ctx: Ctx): Promise<void> {
85
- const { change, echo, warn } = ctx.services.logger;
86
- if (!bwrapSupportedOs(ctx)) return;
87
-
88
- if (ctx.dryRun) {
89
- echo("[dry-run] verify bubblewrap installed (recommended Codex Linux sandbox runtime)");
90
- return;
91
- }
92
-
93
- if (ctx.services.deps.probe("bwrap").state === "present") return;
94
-
95
- if (ctx.skipBubblewrap) {
96
- warn(
97
- "bubblewrap not installed (--skip-bubblewrap skips auto-install). Codex may use its bundled helper if user namespaces work; recommended install: sudo apt install -y bubblewrap",
98
- );
99
- return;
100
- }
101
-
102
- const pmInstall = bwrapDetectPmInstallCmd(ctx);
103
- if (pmInstall === "") {
104
- warn(
105
- "bubblewrap not installed and no supported package manager found (apt-get/dnf/pacman/zypper). Codex may use its bundled helper if user namespaces work; install system bubblewrap manually when possible.",
106
- );
107
- return;
108
- }
109
-
110
- warn(
111
- `bubblewrap not installed - recommended for Codex Linux sandbox. Running: ${pmInstall} (sudo prompt may appear)`,
112
- );
113
- const runInstaller = () =>
114
- spawnProcess("bash", ["-c", pmInstall], { stdio: ["inherit", "inherit", "inherit"] });
115
- const res = await (ctx.terminalLease?.withExclusive(runInstaller) ?? runInstaller());
116
- if (res.exitCode !== 0) {
117
- warn(`Failed to auto-install bubblewrap. Install manually: ${pmInstall}`);
118
- return;
119
- }
120
-
121
- if (ctx.services.deps.probe("bwrap").state === "missing") {
122
- warn("Package install reported success but bwrap not on PATH — check installation manually");
123
- return;
124
- }
125
-
126
- const namespaceProbe = await spawnProcess("unshare", ["-Ur", "true"], { stdio: "ignore" });
127
- if (namespaceProbe.error !== undefined) {
128
- warn(`Could not run unshare to check user namespaces: ${namespaceProbe.error.message}`);
129
- } else if (namespaceProbe.exitCode === 0) {
130
- change(`bubblewrap installed and functional (${await ctx.services.deps.version("bwrap")})`);
131
- } else {
132
- warn(
133
- "bubblewrap installed but unprivileged user namespaces appear blocked. On Ubuntu 24.04+, prefer loading the AppArmor bwrap-userns-restrict profile; fallback: sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0",
134
- );
135
- }
136
- }
137
-
138
- function bwrapSupportedOs(ctx: Ctx): boolean {
139
- const { warn } = ctx.services.logger;
140
- const os = hostOs(ctx.services.platform.name());
141
- if (os.supportsBubblewrap) return true;
142
- if (os.id === "unknown") {
143
- warn("Unknown OS — skipping bubblewrap check; Codex sandbox may not work");
144
- }
145
- return false;
146
- }
147
-
148
- function bwrapDetectPmInstallCmd(ctx: Ctx): string {
149
- if (ctx.services.deps.probe("apt-get").state === "present")
150
- return "sudo apt-get install -y bubblewrap";
151
- if (ctx.services.deps.probe("dnf").state === "present") return "sudo dnf install -y bubblewrap";
152
- if (ctx.services.deps.probe("pacman").state === "present")
153
- return "sudo pacman -S --noconfirm bubblewrap";
154
- if (ctx.services.deps.probe("zypper").state === "present")
155
- return "sudo zypper install -y bubblewrap";
156
- return "";
157
- }
158
-
159
- // ------------------------------------------------------- rules + agents ----
160
-
161
- /** One `<sha256> <file name>` line of the rules manifest, the `sha256sum` format. */
162
- const RULES_RECORD = /^([0-9a-f]{64}) {2}([^/\\]+\.rules)$/;
163
-
164
- function sha256Hex(bytes: Uint8Array): string {
165
- return createHash("sha256").update(bytes).digest("hex");
166
- }
167
-
168
- /**
169
- * The rules files that syncs wrote: file name to the sha256 hashes of the kit
170
- * bytes recorded for it, in manifest order. A sync that stopped after its
171
- * write-ahead can leave two lines, so two hashes, for one name.
172
- */
173
- function readRulesRecords(manifestFile: string): Map<string, Set<string>> {
174
- const records = new Map<string, Set<string>>();
175
- if (!existsSync(manifestFile)) return records;
176
- for (const line of readFileSync(manifestFile, "utf8").split("\n")) {
177
- const record = RULES_RECORD.exec(line);
178
- if (record === null) continue;
179
- const name = record[2]!;
180
- const hashes = records.get(name) ?? new Set<string>();
181
- hashes.add(record[1]!);
182
- records.set(name, hashes);
183
- }
184
- return records;
185
- }
186
-
187
- /**
188
- * Replaces the manifest with one `<sha256> <name>` line per recorded hash,
189
- * sorted by name. A name keeps the order of its hashes. Writes no manifest
190
- * when there is no record and no manifest.
191
- */
192
- function writeRulesManifest(
193
- manifestFile: string,
194
- records: ReadonlyMap<string, ReadonlySet<string>>,
195
- ): void {
196
- const manifest = [...records]
197
- .sort(([left], [right]) => compareCodepoints(left, right))
198
- .flatMap(([name, hashes]) => [...hashes].map((hash) => `${hash} ${name}\n`))
199
- .join("");
200
- if (manifest !== "" || existsSync(manifestFile)) replaceTextIfChanged(manifestFile, manifest);
201
- }
202
-
203
- /**
204
- * Deploys the SoT rules files and records each one in `manifestFile`. Codex
205
- * applies every `*.rules` file in `rules/`, so a file that the SoT dropped
206
- * keeps its old rules active. Each sync therefore removes a recorded file
207
- * that the SoT no longer ships while its bytes have one of the hashes recorded
208
- * for its name. An edited file stays, keeps its records, and gets a warning on
209
- * each sync. Sync deploys each name that the SoT ships over an existing file,
210
- * recorded or not. It backs up a file that differs to `<name>.bak`. It then
211
- * replaces it through a temporary file and a rename, so an interrupted write
212
- * keeps the previous file. Codex does not load the `*.tmp` file. Cleanup
213
- * never reads or removes a file that the SoT does not ship and no sync
214
- * recorded, such as the `default.rules` file of Codex.
215
- *
216
- * Record ahead: before the deploy, sync writes the manifest with the recorded
217
- * hashes of each name plus the kit hash of each shipped name. So a sync that
218
- * stops after a deploy leaves a record of the bytes it wrote. A name whose kit
219
- * bytes change then has two lines. Every recorded hash is a hash of kit
220
- * bytes, so no record lets cleanup remove bytes that the user wrote. After the
221
- * deploy, sync writes one line per shipped name, and a kept name keeps its
222
- * hashes. Both writes go through a temporary file and a rename, so an
223
- * interrupted write keeps the previous manifest.
224
- */
225
- export function syncRules(
226
- ctx: Ctx,
227
- sotRules: ReadonlyArray<PayloadPath>,
228
- userRulesDir: string,
229
- manifestFile: string,
230
- ): void {
231
- const { change, echo, verbose, warn } = ctx.services.logger;
232
- const ruleFiles = sotRules.filter((path) => path.endsWith(".rules")).sort(compareCodepoints);
233
- const fileName = (path: string): string => path.slice(path.lastIndexOf("/") + 1);
234
- const shippedNames = new Set(ruleFiles.map(fileName));
235
- const recorded = readRulesRecords(manifestFile);
236
- const nextRecords = new Map<string, ReadonlySet<string>>();
237
- const firstRule = sotRules[0];
238
-
239
- if (ctx.dryRun) {
240
- if (firstRule !== undefined) {
241
- const firstDisplay = payloadDisplayPath(firstRule);
242
- const sotRulesDir = firstDisplay.slice(0, firstDisplay.lastIndexOf("/"));
243
- echo(`[dry-run] cp ${sotRulesDir}/*.rules -> ${userRulesDir}/`);
244
- }
245
- } else if (firstRule !== undefined) {
246
- mkdirSync(userRulesDir, { recursive: true });
247
- const deploys = ruleFiles.map((ruleFile) => {
248
- const content = payloadBytes(ruleFile);
249
- return { name: fileName(ruleFile), content, hash: sha256Hex(content) };
250
- });
251
- const ahead = new Map(recorded);
252
- for (const { name, hash } of deploys) {
253
- ahead.set(name, new Set([...(recorded.get(name) ?? []), hash]));
254
- nextRecords.set(name, new Set([hash]));
255
- }
256
- writeRulesManifest(manifestFile, ahead);
257
-
258
- let rulesChanged = false;
259
- for (const { name, content } of deploys) {
260
- const userRuleFile = p(userRulesDir, name);
261
- const identical = existsSync(userRuleFile) && readFileSync(userRuleFile).equals(content);
262
- if (identical) continue;
263
- if (existsSync(userRuleFile)) copyFileSync(userRuleFile, `${userRuleFile}.bak`);
264
- replaceFile(userRuleFile, content);
265
- rulesChanged = true;
266
- }
267
- if (rulesChanged) {
268
- change("Codex rules synced");
269
- ctx.nextStepTriggers.codexRestart = true;
270
- } else if (ruleFiles.length > 0) verbose("Codex rules already in sync");
271
- }
272
-
273
- for (const [name, recordedHashes] of recorded) {
274
- if (shippedNames.has(name)) continue;
275
- const file = p(userRulesDir, name);
276
- if (!existsSync(file)) continue;
277
- if (!recordedHashes.has(sha256Hex(readFileSync(file)))) {
278
- warn(
279
- `Codex rules: kept ${file}: the SoT no longer ships it, and it differs from the kit copy. Review it and delete it if you do not need its rules.`,
280
- );
281
- nextRecords.set(name, recordedHashes);
282
- continue;
283
- }
284
- if (ctx.dryRun) {
285
- echo(`[dry-run] remove ${file}`);
286
- continue;
287
- }
288
- rmSync(file, { force: true });
289
- change(`Codex rules: removed ${file}; the SoT no longer ships it`);
290
- ctx.nextStepTriggers.codexRestart = true;
291
- }
292
- if (ctx.dryRun) return;
293
-
294
- writeRulesManifest(manifestFile, nextRecords);
295
- }
296
-
297
- function syncAgentsMd(ctx: Ctx, sotAgentsMdText: string, userAgentsMd: string): void {
298
- const { change, echo, verbose } = ctx.services.logger;
299
- const sotAgentsMd = payloadDisplayPath("SoT/.codex/AGENTS.md");
300
-
301
- if (ctx.dryRun) {
302
- echo(`[dry-run] cp ${sotAgentsMd} -> ${userAgentsMd}`);
303
- return;
304
- }
305
-
306
- if (existsSync(userAgentsMd) && readFileSync(userAgentsMd, "utf8") === sotAgentsMdText) {
307
- verbose("Codex AGENTS.md already in sync");
308
- return;
309
- }
310
- if (existsSync(userAgentsMd)) copyFileSync(userAgentsMd, `${userAgentsMd}.bak`);
311
- writeFileSync(userAgentsMd, sotAgentsMdText);
312
- change("Codex AGENTS.md synced");
313
- ctx.nextStepTriggers.codexRestart = true;
314
- }
@@ -1,303 +0,0 @@
1
- /**
2
- * Line-based Codex TOML passes: top-level setting replacement, the SoT
3
- * top-level and table merges used by `sync codex`, and `--codex-model` /
4
- * `--codex-effort`. A TOML library would reformat user configs and break the
5
- * golden contract. The key is used as a raw regex fragment, preserving the
6
- * historical record-oriented behavior.
7
- */
8
- import { p } from "./exec";
9
- import { existsSync, readFileSync } from "node:fs";
10
-
11
- import { resolveEffort } from "../efforts";
12
- import { replaceFile } from "./atomicWrite";
13
- import { codexHome } from "./codexPaths";
14
- import type { Ctx } from "./index";
15
- import type { SettingEdit } from "./sharedTypes";
16
- import { isTomlHeaderLine, tomlContinuationLines } from "./tomlLines";
17
-
18
- export function replaceTopLevelSetting(content: string, key: string, replacement: string): string {
19
- // A leading BOM would hide the first key or header from the line patterns.
20
- const lines = content.replace(/^\uFEFF/, "").split("\n");
21
- if (lines[lines.length - 1] === "") lines.pop(); // awk records exclude a trailing empty split artifact
22
- const continuation = tomlContinuationLines(lines);
23
- const keyRe = new RegExp(`^[ \\t]*${key}[ \\t]*=`);
24
- const out: Array<string> = [];
25
- let inTable = false;
26
- let replaced = false;
27
- // The continuation lines of a replaced key's value go with the key line.
28
- let dropping = false;
29
- for (const [index, line] of lines.entries()) {
30
- if (continuation[index] === true) {
31
- if (!dropping) out.push(line);
32
- continue;
33
- }
34
- dropping = false;
35
- if (isTomlHeaderLine(line)) {
36
- if (!replaced) {
37
- out.push(replacement);
38
- replaced = true;
39
- }
40
- inTable = true;
41
- out.push(line);
42
- continue;
43
- }
44
- if (!inTable && keyRe.test(line)) {
45
- if (!replaced) {
46
- out.push(replacement);
47
- replaced = true;
48
- }
49
- dropping = true;
50
- continue;
51
- }
52
- out.push(line);
53
- }
54
- if (!replaced) out.push(replacement);
55
- return `${out.join("\n")}\n`;
56
- }
57
-
58
- export function replaceTopLevelSettingInFile(
59
- file: string,
60
- key: string,
61
- replacement: string,
62
- ): boolean {
63
- const before = readFileSync(file, "utf8");
64
- const next = replaceTopLevelSetting(before, key, replacement);
65
- if (next === before) return false;
66
- replaceFile(file, next);
67
- return true;
68
- }
69
-
70
- type CodexSettingEdit = SettingEdit<"model" | "model_reasoning_effort">;
71
-
72
- /**
73
- * `deployedBefore` is the config text a sync read before its merge. The merge
74
- * already wrote the modifier value, so only that earlier text shows whether the
75
- * modifier changed the deployed setting.
76
- */
77
- function syncCodexSetting(ctx: Ctx, edit: CodexSettingEdit, deployedBefore?: string): void {
78
- const { change, echo, verbose, warn } = ctx.services.logger;
79
- const userCodexSettings = p(codexHome(ctx.home), "config.toml");
80
-
81
- if (!existsSync(userCodexSettings)) {
82
- // A dry-run sync already previewed installing the file, so the edit is not skipped.
83
- // The `docks-kit model codex <m>` command creates no file, so the skip stands.
84
- if (ctx.dryRun && ctx.syncCodex) {
85
- echo(`[dry-run] (${edit.tag}) set ${edit.key} = "${edit.value}" in ${userCodexSettings}`);
86
- return;
87
- }
88
- warn(`(${edit.tag}) ${userCodexSettings} missing — skipped`);
89
- return;
90
- }
91
-
92
- if (ctx.dryRun) {
93
- echo(`[dry-run] (${edit.tag}) set ${edit.key} = "${edit.value}" in ${userCodexSettings}`);
94
- return;
95
- }
96
-
97
- const line = `${edit.key} = "${edit.value}"`;
98
- const wrote = replaceTopLevelSettingInFile(userCodexSettings, edit.key, line);
99
- const changedSinceMerge =
100
- deployedBefore !== undefined &&
101
- replaceTopLevelSetting(deployedBefore, edit.key, line) !== deployedBefore;
102
- if (wrote || changedSinceMerge) {
103
- change(edit.changed);
104
- ctx.nextStepTriggers.codexRestart = true;
105
- } else {
106
- verbose(edit.unchanged);
107
- }
108
- }
109
-
110
- export function syncCodexModel(ctx: Ctx, model: string, deployedBefore?: string): void {
111
- if (model === "") return;
112
- syncCodexSetting(
113
- ctx,
114
- {
115
- tag: "--codex-model",
116
- key: "model",
117
- value: model,
118
- changed: `Model: deployed Codex model set to ${model} (SoT unchanged; flag-less sync reverts)`,
119
- unchanged: `Model: deployed Codex model already ${model}`,
120
- },
121
- deployedBefore,
122
- );
123
- }
124
-
125
- export function syncCodexEffort(ctx: Ctx, effort: string, deployedBefore?: string): void {
126
- if (effort === "") return;
127
- const resolved = resolveEffort("codex", effort);
128
- const useDefault = effort === "default";
129
- syncCodexSetting(
130
- ctx,
131
- {
132
- tag: "--codex-effort",
133
- key: "model_reasoning_effort",
134
- value: resolved,
135
- changed: useDefault
136
- ? `Effort: deployed Codex model_reasoning_effort set to ${resolved} (SoT default)`
137
- : `Effort: deployed Codex model_reasoning_effort set to ${resolved} (SoT unchanged; flag-less sync reverts)`,
138
- unchanged: `Effort: deployed Codex model_reasoning_effort already ${resolved}`,
139
- },
140
- deployedBefore,
141
- );
142
- }
143
-
144
- export function mergeTopLevelSettings(sotConfigText: string, userConfig: string): void {
145
- for (const line of sotConfigText.split("\n")) {
146
- if (isTomlHeaderLine(line)) break;
147
- if (/^[ \t]*($|#)/.test(line)) continue;
148
- const setting = /^[ \t]*([A-Za-z0-9_.-]+)[ \t]*=/.exec(line);
149
- if (setting === null) continue;
150
- replaceTopLevelSettingInFile(userConfig, setting[1]!, line);
151
- }
152
- }
153
-
154
- interface TomlTableHeader {
155
- readonly path: string;
156
- }
157
-
158
- const TOML_BASIC_ESCAPES: Readonly<Record<string, string>> = {
159
- b: "\b",
160
- t: "\t",
161
- n: "\n",
162
- f: "\f",
163
- r: "\r",
164
- '"': '"',
165
- "\\": "\\",
166
- };
167
-
168
- function tomlBasicEscape(
169
- line: string,
170
- offset: number,
171
- ): { readonly next: number; readonly value: string } | undefined {
172
- const escaped = line[offset];
173
- const simple = escaped === undefined ? undefined : TOML_BASIC_ESCAPES[escaped];
174
- if (simple !== undefined) return { next: offset + 1, value: simple };
175
- const digits = escaped === "u" ? 4 : escaped === "U" ? 8 : 0;
176
- if (digits === 0) return undefined;
177
- const hex = line.slice(offset + 1, offset + 1 + digits);
178
- if (hex.length !== digits || !/^[0-9A-Fa-f]+$/.test(hex)) return undefined;
179
- const codePoint = Number.parseInt(hex, 16);
180
- if (codePoint > 0x10ffff || (codePoint >= 0xd800 && codePoint <= 0xdfff)) return undefined;
181
- return { next: offset + 1 + digits, value: String.fromCodePoint(codePoint) };
182
- }
183
-
184
- /** Decode a table header to the TOML path that determines managed ownership. */
185
- function tomlTableHeader(line: string): TomlTableHeader | undefined {
186
- let offset = 0;
187
- const skipWhitespace = (): void => {
188
- while (line[offset] === " " || line[offset] === "\t") offset++;
189
- };
190
-
191
- skipWhitespace();
192
- if (line[offset] !== "[") return undefined;
193
- offset++;
194
- const array = line[offset] === "[";
195
- if (array) offset++;
196
-
197
- const keys: Array<string> = [];
198
- while (true) {
199
- skipWhitespace();
200
- const quote = line[offset];
201
- let key = "";
202
- if (quote === '"' || quote === "'") {
203
- offset++;
204
- let closed = false;
205
- while (offset < line.length) {
206
- const char = line[offset]!;
207
- if (char === quote) {
208
- offset++;
209
- closed = true;
210
- break;
211
- }
212
- if (quote === '"' && char === "\\") {
213
- const escape = tomlBasicEscape(line, offset + 1);
214
- if (escape === undefined) return undefined;
215
- key += escape.value;
216
- offset = escape.next;
217
- continue;
218
- }
219
- if (char === "\n" || char === "\r") return undefined;
220
- key += char;
221
- offset++;
222
- }
223
- if (!closed) return undefined;
224
- } else {
225
- const start = offset;
226
- while (offset < line.length && /[A-Za-z0-9_-]/.test(line[offset]!)) offset++;
227
- if (offset === start) return undefined;
228
- key = line.slice(start, offset);
229
- }
230
- keys.push(key);
231
-
232
- skipWhitespace();
233
- if (line[offset] === ".") {
234
- offset++;
235
- continue;
236
- }
237
- if (line[offset] !== "]") return undefined;
238
- offset++;
239
- if (array) {
240
- if (line[offset] !== "]") return undefined;
241
- offset++;
242
- }
243
- skipWhitespace();
244
- if (offset < line.length && line[offset] !== "#") return undefined;
245
- return { path: JSON.stringify(keys) };
246
- }
247
- }
248
-
249
- function mergeTableSettingsText(sotConfigText: string, userConfigText: string): string {
250
- const sotLines = sotConfigText.split("\n");
251
- const sotContinuation = tomlContinuationLines(sotLines);
252
- const sotHeaders = sotLines.map((line, offset) =>
253
- sotContinuation[offset] === true ? undefined : tomlTableHeader(line),
254
- );
255
- let merged = userConfigText;
256
- for (let tableOffset = 0; tableOffset < sotLines.length; tableOffset++) {
257
- const managedHeader = sotHeaders[tableOffset];
258
- if (managedHeader === undefined) continue;
259
-
260
- const block: Array<string> = [];
261
- for (let blockOffset = tableOffset; blockOffset < sotLines.length; blockOffset++) {
262
- if (blockOffset !== tableOffset && sotHeaders[blockOffset] !== undefined) break;
263
- block.push(sotLines[blockOffset]!);
264
- }
265
- const tableBlock = block.join("\n").replace(/\n+$/, "");
266
-
267
- const userLines = merged.split("\n");
268
- if (userLines[userLines.length - 1] === "") userLines.pop();
269
- const userContinuation = tomlContinuationLines(userLines);
270
- let skip = false;
271
- const kept: Array<string> = [];
272
- // Blank and comment lines after the last key of a removed block. They belong
273
- // to the next block or are disabled config, so they stay in the file.
274
- let trailingComments: Array<string> = [];
275
- const keepTrailingComments = (): void => {
276
- const firstContent = trailingComments.findIndex((line) => !/^[ \t]*$/.test(line));
277
- if (firstContent !== -1) kept.push(...trailingComments.slice(firstContent));
278
- trailingComments = [];
279
- };
280
- for (const [index, line] of userLines.entries()) {
281
- const continued = userContinuation[index] === true;
282
- const header = continued ? undefined : tomlTableHeader(line);
283
- if (header !== undefined) {
284
- if (skip) keepTrailingComments();
285
- skip = header.path === managedHeader.path;
286
- if (skip) continue;
287
- }
288
- if (!skip) kept.push(line);
289
- else if (!continued && /^[ \t]*($|#)/.test(line)) trailingComments.push(line);
290
- else trailingComments = [];
291
- }
292
- if (skip) keepTrailingComments();
293
- // The blank lines before a removed last block would otherwise stay in
294
- // `kept`, and each sync would add one more blank line before the table.
295
- while (kept.length > 0 && /^[ \t]*$/.test(kept[kept.length - 1]!)) kept.pop();
296
- merged = `${kept.join("\n")}\n\n${tableBlock}\n`;
297
- }
298
- return merged;
299
- }
300
-
301
- export function mergeTableSettings(sotConfigText: string, userConfig: string): void {
302
- replaceFile(userConfig, mergeTableSettingsText(sotConfigText, readFileSync(userConfig, "utf8")));
303
- }