docks-kit 0.20.5 → 0.20.8

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 (72) hide show
  1. package/AGENTS.md +19 -17
  2. package/README.md +17 -6
  3. package/cli/docs/command-guards.md +269 -0
  4. package/cli/docs/install.md +23 -12
  5. package/cli/docs/models.md +3 -2
  6. package/cli/docs/modifiers.md +4 -3
  7. package/cli/docs/omp-context.md +9 -2
  8. package/cli/docs/omp-models.md +61 -31
  9. package/cli/docs/plugins.md +12 -7
  10. package/cli/docs/sync-layers.md +26 -9
  11. package/cli/docs/toolchain.md +7 -4
  12. package/cli/src/argv.ts +2 -0
  13. package/cli/src/argvSurface.ts +23 -0
  14. package/cli/src/argvValidate.ts +3 -3
  15. package/cli/src/commands/docs.ts +6 -1
  16. package/cli/src/commands/harnesses.ts +15 -4
  17. package/cli/src/commands/omp.ts +92 -41
  18. package/cli/src/commands/status.ts +15 -0
  19. package/cli/src/commands/sync.ts +6 -6
  20. package/cli/src/commands/toolchain.ts +8 -2
  21. package/cli/src/commands/update.ts +51 -10
  22. package/cli/src/engine-native/DESIGN.md +56 -35
  23. package/cli/src/engine-native/atomicWrite.ts +64 -0
  24. package/cli/src/engine-native/claudeLsp.ts +9 -2
  25. package/cli/src/engine-native/claudeOptionalPlugins.ts +19 -6
  26. package/cli/src/engine-native/claudePluginPasses.ts +77 -21
  27. package/cli/src/engine-native/claudeRemovals.ts +245 -57
  28. package/cli/src/engine-native/claudeRetired.ts +1 -1
  29. package/cli/src/engine-native/claudeSettings.ts +46 -19
  30. package/cli/src/engine-native/claudeSettingsModifiers.ts +3 -3
  31. package/cli/src/engine-native/claudeSync.ts +18 -16
  32. package/cli/src/engine-native/codexConfig.ts +72 -12
  33. package/cli/src/engine-native/codexHooks.ts +3 -3
  34. package/cli/src/engine-native/codexPaths.ts +14 -0
  35. package/cli/src/engine-native/codexPlugins.ts +48 -23
  36. package/cli/src/engine-native/codexStatus.ts +2 -1
  37. package/cli/src/engine-native/codexSync.ts +33 -7
  38. package/cli/src/engine-native/codexToml.ts +161 -35
  39. package/cli/src/engine-native/deps.ts +4 -9
  40. package/cli/src/engine-native/engineCtx.ts +42 -14
  41. package/cli/src/engine-native/exec.ts +28 -1
  42. package/cli/src/engine-native/harnesses.ts +32 -8
  43. package/cli/src/engine-native/index.ts +6 -1
  44. package/cli/src/engine-native/kitDb.ts +12 -6
  45. package/cli/src/engine-native/liveModels.ts +2 -1
  46. package/cli/src/engine-native/models.ts +6 -3
  47. package/cli/src/engine-native/modes.ts +15 -10
  48. package/cli/src/engine-native/ompFileDeploy.ts +3 -4
  49. package/cli/src/engine-native/ompMarketplace.ts +9 -7
  50. package/cli/src/engine-native/ompOverlay.ts +39 -13
  51. package/cli/src/engine-native/ompPaths.ts +20 -9
  52. package/cli/src/engine-native/ompPlugins.ts +16 -15
  53. package/cli/src/engine-native/ompSync.ts +11 -6
  54. package/cli/src/engine-native/ompYaml.ts +91 -6
  55. package/cli/src/engine-native/os/darwin.ts +2 -0
  56. package/cli/src/engine-native/os/linux.ts +1 -0
  57. package/cli/src/engine-native/os/posix.ts +17 -5
  58. package/cli/src/engine-native/os/types.ts +2 -2
  59. package/cli/src/engine-native/os/windows.ts +24 -16
  60. package/cli/src/engine-native/skillsInstall.ts +10 -5
  61. package/cli/src/engine-native/skillsLinks.ts +14 -1
  62. package/cli/src/engine-native/skillsManifest.ts +20 -0
  63. package/cli/src/engine-native/skillsPrune.ts +33 -26
  64. package/cli/src/engine-native/skillsSync.ts +6 -3
  65. package/cli/src/engine-native/syncDispatch.ts +32 -18
  66. package/cli/src/engine.ts +29 -3
  67. package/cli/src/generated/sotPayload.ts +14 -14
  68. package/cli/src/main.ts +10 -3
  69. package/cli/src/manifests.ts +29 -11
  70. package/docks-kit +6 -3
  71. package/docks-kit.ps1 +22 -11
  72. package/package.json +1 -1
@@ -6,9 +6,11 @@
6
6
  * historical record-oriented behavior.
7
7
  */
8
8
  import { p } from "./exec";
9
- import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
9
+ import { existsSync, readFileSync } from "node:fs";
10
10
 
11
11
  import { resolveEffort } from "../efforts";
12
+ import { replaceFile } from "./atomicWrite";
13
+ import { codexHome } from "./codexPaths";
12
14
  import type { Ctx } from "./index";
13
15
  import type { SettingEdit } from "./sharedTypes";
14
16
 
@@ -16,14 +18,105 @@ export function isTomlHeaderLine(line: string): boolean {
16
18
  return /^[ \t]*\[/.test(line);
17
19
  }
18
20
 
21
+ /** Offset just past the quoted string that starts at `start`, or the line end when it stays open. */
22
+ function skipQuoted(line: string, start: number): number {
23
+ const quote = line[start];
24
+ let offset = start + 1;
25
+ while (offset < line.length) {
26
+ if (quote === '"' && line[offset] === "\\") {
27
+ offset += 2;
28
+ continue;
29
+ }
30
+ if (line[offset] === quote) return offset + 1;
31
+ offset++;
32
+ }
33
+ return offset;
34
+ }
35
+
36
+ /** Offset of the `=` that ends the key on a key line, or undefined for other lines. */
37
+ function keyValueSeparator(line: string): number | undefined {
38
+ if (/^[ \t]*($|#|\[)/.test(line)) return undefined;
39
+ let offset = 0;
40
+ while (offset < line.length) {
41
+ const char = line[offset]!;
42
+ if (char === "=") return offset;
43
+ offset = char === '"' || char === "'" ? skipQuoted(line, offset) : offset + 1;
44
+ }
45
+ return undefined;
46
+ }
47
+
48
+ /**
49
+ * Mark each line that continues a value opened on an earlier line: the body of
50
+ * a `"""` or `'''` string, or the rest of an array or inline table that spans
51
+ * lines. A marked line is never a table header or a key line.
52
+ */
53
+ export function tomlContinuationLines(lines: ReadonlyArray<string>): Array<boolean> {
54
+ const continuation: Array<boolean> = [];
55
+ let openString: string | undefined;
56
+ let depth = 0;
57
+ const scanValue = (line: string, start: number): void => {
58
+ let offset = start;
59
+ while (offset < line.length) {
60
+ if (openString !== undefined) {
61
+ if (openString === '"""' && line[offset] === "\\") {
62
+ offset += 2;
63
+ } else if (line.startsWith(openString, offset)) {
64
+ // A closing delimiter can carry up to two extra quotes of string content.
65
+ let end = offset + 3;
66
+ while (end < offset + 5 && line[end] === openString[0]) end++;
67
+ offset = end;
68
+ openString = undefined;
69
+ } else {
70
+ offset++;
71
+ }
72
+ continue;
73
+ }
74
+ const char = line[offset]!;
75
+ if (char === "#") return;
76
+ if (line.startsWith('"""', offset) || line.startsWith("'''", offset)) {
77
+ openString = line.slice(offset, offset + 3);
78
+ offset += 3;
79
+ continue;
80
+ }
81
+ if (char === '"' || char === "'") {
82
+ offset = skipQuoted(line, offset);
83
+ continue;
84
+ }
85
+ if (char === "[" || char === "{") depth++;
86
+ else if ((char === "]" || char === "}") && depth > 0) depth--;
87
+ offset++;
88
+ }
89
+ };
90
+ for (const line of lines) {
91
+ if (openString !== undefined || depth > 0) {
92
+ continuation.push(true);
93
+ scanValue(line, 0);
94
+ continue;
95
+ }
96
+ continuation.push(false);
97
+ const separator = keyValueSeparator(line);
98
+ if (separator !== undefined) scanValue(line, separator + 1);
99
+ }
100
+ return continuation;
101
+ }
102
+
19
103
  export function replaceTopLevelSetting(content: string, key: string, replacement: string): string {
20
- const lines = content.split("\n");
104
+ // A leading BOM would hide the first key or header from the line patterns.
105
+ const lines = content.replace(/^\uFEFF/, "").split("\n");
21
106
  if (lines[lines.length - 1] === "") lines.pop(); // awk records exclude a trailing empty split artifact
107
+ const continuation = tomlContinuationLines(lines);
22
108
  const keyRe = new RegExp(`^[ \\t]*${key}[ \\t]*=`);
23
109
  const out: Array<string> = [];
24
110
  let inTable = false;
25
111
  let replaced = false;
26
- for (const line of lines) {
112
+ // The continuation lines of a replaced key's value go with the key line.
113
+ let dropping = false;
114
+ for (const [index, line] of lines.entries()) {
115
+ if (continuation[index] === true) {
116
+ if (!dropping) out.push(line);
117
+ continue;
118
+ }
119
+ dropping = false;
27
120
  if (isTomlHeaderLine(line)) {
28
121
  if (!replaced) {
29
122
  out.push(replacement);
@@ -38,6 +131,7 @@ export function replaceTopLevelSetting(content: string, key: string, replacement
38
131
  out.push(replacement);
39
132
  replaced = true;
40
133
  }
134
+ dropping = true;
41
135
  continue;
42
136
  }
43
137
  out.push(line);
@@ -54,16 +148,20 @@ export function replaceTopLevelSettingInFile(
54
148
  const before = readFileSync(file, "utf8");
55
149
  const next = replaceTopLevelSetting(before, key, replacement);
56
150
  if (next === before) return false;
57
- writeFileSync(`${file}.tmp`, next);
58
- renameSync(`${file}.tmp`, file);
151
+ replaceFile(file, next);
59
152
  return true;
60
153
  }
61
154
 
62
155
  type CodexSettingEdit = SettingEdit<"model" | "model_reasoning_effort">;
63
156
 
64
- function syncCodexSetting(ctx: Ctx, edit: CodexSettingEdit): void {
157
+ /**
158
+ * `deployedBefore` is the config text a sync read before its merge. The merge
159
+ * already wrote the modifier value, so only that earlier text shows whether the
160
+ * modifier changed the deployed setting.
161
+ */
162
+ function syncCodexSetting(ctx: Ctx, edit: CodexSettingEdit, deployedBefore?: string): void {
65
163
  const { change, echo, verbose, warn } = ctx.services.logger;
66
- const userCodexSettings = p(ctx.home, ".codex", "config.toml");
164
+ const userCodexSettings = p(codexHome(ctx.home), "config.toml");
67
165
 
68
166
  if (!existsSync(userCodexSettings)) {
69
167
  // A dry-run sync already previewed installing the file, so the edit is not skipped.
@@ -81,7 +179,12 @@ function syncCodexSetting(ctx: Ctx, edit: CodexSettingEdit): void {
81
179
  return;
82
180
  }
83
181
 
84
- if (replaceTopLevelSettingInFile(userCodexSettings, edit.key, `${edit.key} = "${edit.value}"`)) {
182
+ const line = `${edit.key} = "${edit.value}"`;
183
+ const wrote = replaceTopLevelSettingInFile(userCodexSettings, edit.key, line);
184
+ const changedSinceMerge =
185
+ deployedBefore !== undefined &&
186
+ replaceTopLevelSetting(deployedBefore, edit.key, line) !== deployedBefore;
187
+ if (wrote || changedSinceMerge) {
85
188
  change(edit.changed);
86
189
  ctx.nextStepTriggers.codexRestart = true;
87
190
  } else {
@@ -89,30 +192,38 @@ function syncCodexSetting(ctx: Ctx, edit: CodexSettingEdit): void {
89
192
  }
90
193
  }
91
194
 
92
- export function syncCodexModel(ctx: Ctx, model: string): void {
195
+ export function syncCodexModel(ctx: Ctx, model: string, deployedBefore?: string): void {
93
196
  if (model === "") return;
94
- syncCodexSetting(ctx, {
95
- tag: "--codex-model",
96
- key: "model",
97
- value: model,
98
- changed: `Model: deployed Codex model set to ${model} (SoT unchanged; flag-less sync reverts)`,
99
- unchanged: `Model: deployed Codex model already ${model}`,
100
- });
197
+ syncCodexSetting(
198
+ ctx,
199
+ {
200
+ tag: "--codex-model",
201
+ key: "model",
202
+ value: model,
203
+ changed: `Model: deployed Codex model set to ${model} (SoT unchanged; flag-less sync reverts)`,
204
+ unchanged: `Model: deployed Codex model already ${model}`,
205
+ },
206
+ deployedBefore,
207
+ );
101
208
  }
102
209
 
103
- export function syncCodexEffort(ctx: Ctx, effort: string): void {
210
+ export function syncCodexEffort(ctx: Ctx, effort: string, deployedBefore?: string): void {
104
211
  if (effort === "") return;
105
212
  const resolved = resolveEffort("codex", effort);
106
213
  const useDefault = effort === "default";
107
- syncCodexSetting(ctx, {
108
- tag: "--codex-effort",
109
- key: "model_reasoning_effort",
110
- value: resolved,
111
- changed: useDefault
112
- ? `Effort: deployed Codex model_reasoning_effort set to ${resolved} (SoT default)`
113
- : `Effort: deployed Codex model_reasoning_effort set to ${resolved} (SoT unchanged; flag-less sync reverts)`,
114
- unchanged: `Effort: deployed Codex model_reasoning_effort already ${resolved}`,
115
- });
214
+ syncCodexSetting(
215
+ ctx,
216
+ {
217
+ tag: "--codex-effort",
218
+ key: "model_reasoning_effort",
219
+ value: resolved,
220
+ changed: useDefault
221
+ ? `Effort: deployed Codex model_reasoning_effort set to ${resolved} (SoT default)`
222
+ : `Effort: deployed Codex model_reasoning_effort set to ${resolved} (SoT unchanged; flag-less sync reverts)`,
223
+ unchanged: `Effort: deployed Codex model_reasoning_effort already ${resolved}`,
224
+ },
225
+ deployedBefore,
226
+ );
116
227
  }
117
228
 
118
229
  export function mergeTopLevelSettings(sotConfigText: string, userConfig: string): void {
@@ -222,38 +333,53 @@ function tomlTableHeader(line: string): TomlTableHeader | undefined {
222
333
 
223
334
  function mergeTableSettingsText(sotConfigText: string, userConfigText: string): string {
224
335
  const sotLines = sotConfigText.split("\n");
336
+ const sotContinuation = tomlContinuationLines(sotLines);
337
+ const sotHeaders = sotLines.map((line, offset) =>
338
+ sotContinuation[offset] === true ? undefined : tomlTableHeader(line),
339
+ );
225
340
  let merged = userConfigText;
226
341
  for (let tableOffset = 0; tableOffset < sotLines.length; tableOffset++) {
227
- const managedHeader = tomlTableHeader(sotLines[tableOffset]!);
342
+ const managedHeader = sotHeaders[tableOffset];
228
343
  if (managedHeader === undefined) continue;
229
344
 
230
345
  const block: Array<string> = [];
231
346
  for (let blockOffset = tableOffset; blockOffset < sotLines.length; blockOffset++) {
232
- const line = sotLines[blockOffset]!;
233
- if (blockOffset !== tableOffset && tomlTableHeader(line) !== undefined) break;
234
- block.push(line);
347
+ if (blockOffset !== tableOffset && sotHeaders[blockOffset] !== undefined) break;
348
+ block.push(sotLines[blockOffset]!);
235
349
  }
236
350
  const tableBlock = block.join("\n").replace(/\n+$/, "");
237
351
 
238
352
  const userLines = merged.split("\n");
239
353
  if (userLines[userLines.length - 1] === "") userLines.pop();
354
+ const userContinuation = tomlContinuationLines(userLines);
240
355
  let skip = false;
241
356
  const kept: Array<string> = [];
242
- for (const line of userLines) {
243
- const header = tomlTableHeader(line);
357
+ // Blank and comment lines after the last key of a removed block. They belong
358
+ // to the next block or are disabled config, so they stay in the file.
359
+ let trailingComments: Array<string> = [];
360
+ const keepTrailingComments = (): void => {
361
+ const firstContent = trailingComments.findIndex((line) => !/^[ \t]*$/.test(line));
362
+ if (firstContent !== -1) kept.push(...trailingComments.slice(firstContent));
363
+ trailingComments = [];
364
+ };
365
+ for (const [index, line] of userLines.entries()) {
366
+ const continued = userContinuation[index] === true;
367
+ const header = continued ? undefined : tomlTableHeader(line);
244
368
  if (header !== undefined) {
369
+ if (skip) keepTrailingComments();
245
370
  skip = header.path === managedHeader.path;
246
371
  if (skip) continue;
247
372
  }
248
373
  if (!skip) kept.push(line);
374
+ else if (!continued && /^[ \t]*($|#)/.test(line)) trailingComments.push(line);
375
+ else trailingComments = [];
249
376
  }
377
+ if (skip) keepTrailingComments();
250
378
  merged = `${kept.join("\n")}\n\n${tableBlock}\n`;
251
379
  }
252
380
  return merged;
253
381
  }
254
382
 
255
383
  export function mergeTableSettings(sotConfigText: string, userConfig: string): void {
256
- const next = mergeTableSettingsText(sotConfigText, readFileSync(userConfig, "utf8"));
257
- writeFileSync(`${userConfig}.tmp`, next);
258
- renameSync(`${userConfig}.tmp`, userConfig);
384
+ replaceFile(userConfig, mergeTableSettingsText(sotConfigText, readFileSync(userConfig, "utf8")));
259
385
  }
@@ -7,10 +7,10 @@
7
7
  * install; this registry owns WHICH external tools exist, whether they are
8
8
  * required, and the one-line command that installs a missing one.
9
9
  */
10
- import { homedir } from "node:os";
11
10
  import { isAbsolute } from "node:path";
12
11
 
13
12
  import { capture, commandExists, p, which } from "./exec";
13
+ import { engineHome } from "./harnesses";
14
14
  import { isObject, parseJson } from "./jq";
15
15
  import { hostOs, platformName, rawPlatform } from "./os";
16
16
 
@@ -99,11 +99,6 @@ const versionProbe =
99
99
  async (exec) =>
100
100
  parse(await exec.capture(id, versionArgs));
101
101
 
102
- const home = (): string => {
103
- const envHome = process.env["HOME"];
104
- return envHome !== undefined && envHome !== "" ? envHome : homedir();
105
- };
106
-
107
102
  /**
108
103
  * The resolved path gets persisted into global direct-exec hooks, so a
109
104
  * relative `which` hit (relative PATH entry, relative BUN_INSTALL) would
@@ -117,8 +112,8 @@ const findBun = (exec: ProbeExecutor): { command: string; path: string } | undef
117
112
  const root =
118
113
  process.env["BUN_INSTALL"] !== undefined && process.env["BUN_INSTALL"] !== ""
119
114
  ? process.env["BUN_INSTALL"]!
120
- : p(home(), ".bun");
121
- for (const candidate of [p(root, "bin", "bun"), p(home(), ".bun", "bin", "bun")]) {
115
+ : p(engineHome(), ".bun");
116
+ for (const candidate of [p(root, "bin", "bun"), p(engineHome(), ".bun", "bin", "bun")]) {
122
117
  const found = exec.which(candidate);
123
118
  if (found !== "" && isAbsolute(found)) return { command: found, path: found };
124
119
  }
@@ -213,7 +208,7 @@ export const DEPENDENCIES: Record<ToolId, DependencySpec> = {
213
208
  "omp",
214
209
  "optional",
215
210
  () =>
216
- "install omp from https://github.com/can1357/oh-my-pi (an existing install self-updates with `omp update`)",
211
+ "install omp from https://github.com/can1357/oh-my-pi (an existing install updates with `omp update`, or through the tool that manages it, such as Tern)",
217
212
  { version: versionProbe("omp", ["--version"], (out) => out.trim().replace(/^omp[/v]/, "")) },
218
213
  ),
219
214
  bun: spec("bun", "optional", () => "curl -fsSL https://bun.sh/install | bash", {
@@ -65,18 +65,46 @@ export interface Ctx {
65
65
  readonly failures: Array<string>;
66
66
  }
67
67
 
68
- /** Globals default from env using the historical ${VAR:-default} contract. */
69
- export function makeCtx(services: EngineServices): Ctx {
68
+ /**
69
+ * Unprefixed env globals that seed `Ctx` with the historical ${VAR:-default}
70
+ * contract. Only the harness-private native-raw channel honors them; the
71
+ * public CLI takes the same behavior from flags.
72
+ */
73
+ export const ENV_GLOBAL_KEYS = [
74
+ "DRY_RUN",
75
+ "DOCKS_KIT_VERBOSE",
76
+ "SKIP_BUBBLEWRAP",
77
+ "RECONCILE",
78
+ "PRUNE",
79
+ "CLAUDE_PERMISSIVE",
80
+ "CLAUDE_MODEL",
81
+ "CODEX_MODEL",
82
+ "CLAUDE_PLUGINS",
83
+ "CLAUDE_COMPACT_WINDOW",
84
+ "AGENTS_DIR",
85
+ ] as const;
86
+
87
+ export interface CtxOptions {
88
+ /** True only on the native-raw channel: read ENV_GLOBAL_KEYS from the environment. */
89
+ readonly envGlobals: boolean;
90
+ }
91
+
92
+ /**
93
+ * Build the run context. HOME and DOCKS_KIT_INTERACTIVE apply on every path;
94
+ * ENV_GLOBAL_KEYS apply only when `options.envGlobals` is true.
95
+ */
96
+ export function makeCtx(services: EngineServices, options: CtxOptions): Ctx {
70
97
  const env = process.env;
71
98
  const home = engineHome(env);
72
- const compactWindowSource = env["CLAUDE_COMPACT_WINDOW"] ?? "";
99
+ const globals: NodeJS.ProcessEnv = options.envGlobals ? env : {};
100
+ const compactWindowSource = globals["CLAUDE_COMPACT_WINDOW"] ?? "";
73
101
  const claudeCompactWindow =
74
102
  compactWindowSource === "" ? "" : parseCompactWindow(compactWindowSource);
75
103
  if (claudeCompactWindow === undefined) {
76
104
  services.logger.err("CLAUDE_COMPACT_WINDOW expects a token count (e.g. 680000 or 680k)");
77
105
  throw new ExitError(2);
78
106
  }
79
- const claudePlugins = (env["CLAUDE_PLUGINS"] ?? "")
107
+ const claudePlugins = (globals["CLAUDE_PLUGINS"] ?? "")
80
108
  .split(" ")
81
109
  .filter((plugin) => plugin !== "")
82
110
  .map((plugin) => parseClaudePlugin(plugin, services.logger.err));
@@ -84,27 +112,27 @@ export function makeCtx(services: EngineServices): Ctx {
84
112
  repoDir: kitHome(),
85
113
  home,
86
114
  agentsDir:
87
- env["AGENTS_DIR"] !== undefined && env["AGENTS_DIR"] !== ""
88
- ? env["AGENTS_DIR"]
115
+ globals["AGENTS_DIR"] !== undefined && globals["AGENTS_DIR"] !== ""
116
+ ? globals["AGENTS_DIR"]
89
117
  : p(home, ".agents"),
90
118
  interactive:
91
119
  env["DOCKS_KIT_INTERACTIVE"] === "1" ||
92
120
  (env["DOCKS_KIT_INTERACTIVE"] !== "0" &&
93
121
  process.stdout.isTTY === true &&
94
122
  process.stdin.isTTY === true),
95
- dryRun: env["DRY_RUN"] === "1",
96
- verbose: env["DOCKS_KIT_VERBOSE"] === "1",
97
- skipBubblewrap: env["SKIP_BUBBLEWRAP"] === "1",
123
+ dryRun: globals["DRY_RUN"] === "1",
124
+ verbose: globals["DOCKS_KIT_VERBOSE"] === "1",
125
+ skipBubblewrap: globals["SKIP_BUBBLEWRAP"] === "1",
98
126
  skipPluginRefresh: false,
99
- reconcile: env["RECONCILE"] === "1",
100
- prune: env["PRUNE"] === "1",
127
+ reconcile: globals["RECONCILE"] === "1",
128
+ prune: globals["PRUNE"] === "1",
101
129
  claudeCompactWindow,
102
- claudePermissive: env["CLAUDE_PERMISSIVE"] === "1",
130
+ claudePermissive: globals["CLAUDE_PERMISSIVE"] === "1",
103
131
  claudePlugins,
104
- claudeModel: env["CLAUDE_MODEL"] ?? "",
132
+ claudeModel: globals["CLAUDE_MODEL"] ?? "",
105
133
  claudeEffort: "",
106
134
  claudeAdvisor: "",
107
- codexModel: env["CODEX_MODEL"] ?? "",
135
+ codexModel: globals["CODEX_MODEL"] ?? "",
108
136
  codexEffort: "",
109
137
  modifierFlags: new Set(),
110
138
  syncConcurrency: 3,
@@ -91,6 +91,8 @@ export function processFailureSummary(result: AsyncProcessResult): string {
91
91
 
92
92
  export interface AsyncProcessOptions {
93
93
  readonly stdio?: SpawnOptions["stdio"];
94
+ /** Working directory for the child; the parent's when absent. */
95
+ readonly cwd?: string;
94
96
  /** Host whose executable resolution and argv shaping apply; tests inject it. */
95
97
  readonly host?: HostOs;
96
98
  }
@@ -123,6 +125,7 @@ export function spawnProcess(
123
125
  const invocation = host.invoke(executablePath, args);
124
126
  child = spawn(invocation.command, [...invocation.args], {
125
127
  stdio: options.stdio ?? ["ignore", "pipe", "ignore"],
128
+ ...(options.cwd !== undefined ? { cwd: options.cwd } : {}),
126
129
  windowsVerbatimArguments: invocation.windowsVerbatimArguments,
127
130
  });
128
131
  } catch (cause) {
@@ -167,6 +170,27 @@ export async function capture(cmd: string, args: ReadonlyArray<string>): Promise
167
170
  return res.stdout.replace(/[\r\n]+$/, "");
168
171
  }
169
172
 
173
+ /**
174
+ * Splits a Windows PATH on semicolons outside double quotes, then removes one
175
+ * enclosing quote pair from each entry. cmd.exe and libuv read PATH this way.
176
+ */
177
+ function windowsPathEntries(path: string): Array<string> {
178
+ const entries: Array<string> = [];
179
+ let entry = "";
180
+ let quoted = false;
181
+ for (const char of path) {
182
+ if (char === '"') quoted = !quoted;
183
+ if (char === ";" && !quoted) {
184
+ entries.push(entry);
185
+ entry = "";
186
+ } else {
187
+ entry += char;
188
+ }
189
+ }
190
+ entries.push(entry);
191
+ return entries.map((value) => (/^".*"$/.test(value) ? value.slice(1, -1) : value));
192
+ }
193
+
170
194
  /** `command -v` — resolve an executable name on PATH. */
171
195
  export function which(
172
196
  name: string,
@@ -181,7 +205,10 @@ export function which(
181
205
  };
182
206
 
183
207
  if (isAbsolute(name) || name.includes("/")) return runnableCandidate(name);
184
- for (const dir of (process.env["PATH"] ?? "").split(delimiter)) {
208
+ const path = process.env["PATH"] ?? "";
209
+ // Windows rules (a non-empty suffix) read quoted PATH entries; POSIX keeps the literal split.
210
+ const windowsRules = suffixes.some((suffix) => suffix !== "");
211
+ for (const dir of windowsRules ? windowsPathEntries(path) : path.split(delimiter)) {
185
212
  if (dir === "") continue;
186
213
  const candidate = runnableCandidate(join(dir, name));
187
214
  if (candidate !== "") return candidate;
@@ -33,14 +33,27 @@ function normalizeHarnesses(selection: ReadonlyArray<unknown>): Array<Harness> {
33
33
  return HARNESSES.filter((harness) => selected.has(harness));
34
34
  }
35
35
 
36
- /** Resolve the engine home root from HOME with the platform home as fallback. */
37
- export function engineHome(env: NodeJS.ProcessEnv = process.env): string {
38
- const home = env["HOME"];
36
+ /**
37
+ * Resolve the engine home root the way the harnesses resolve `~`. On Windows,
38
+ * USERPROFILE applies and HOME is ignored. Elsewhere, HOME applies. The
39
+ * platform home is the fallback.
40
+ */
41
+ export function engineHome(
42
+ env: NodeJS.ProcessEnv = process.env,
43
+ platform: NodeJS.Platform = process.platform,
44
+ ): string {
45
+ const home = platform === "win32" ? env["USERPROFILE"] : env["HOME"];
39
46
  return home !== undefined && home !== "" ? home : homedir();
40
47
  }
41
48
 
42
- /** Read the stored selection; corruption, a too-new schema, or I/O errors yield undefined. */
43
- export function readHarnessSelection(home: string): ReadonlyArray<Harness> | undefined {
49
+ /** Result of a read of the stored selection that keeps the failure reason. */
50
+ export type StoredSelection =
51
+ | { kind: "stored"; selection: ReadonlyArray<Harness> }
52
+ | { kind: "missing" }
53
+ | { kind: "unreadable"; reason: string };
54
+
55
+ /** Read the stored selection; corruption, a too-new schema, or I/O errors yield "unreadable". */
56
+ export function loadHarnessSelection(home: string): StoredSelection {
44
57
  try {
45
58
  const selection = withKitDb(home, "read", (db) =>
46
59
  normalizeHarnesses(
@@ -50,12 +63,23 @@ export function readHarnessSelection(home: string): ReadonlyArray<Harness> | und
50
63
  .map((row) => row["harness"]),
51
64
  ),
52
65
  );
53
- return selection !== undefined && selection.length > 0 ? selection : undefined;
54
- } catch {
55
- return undefined;
66
+ return selection !== undefined && selection.length > 0
67
+ ? { kind: "stored", selection }
68
+ : { kind: "missing" };
69
+ } catch (error) {
70
+ return {
71
+ kind: "unreadable",
72
+ reason: error instanceof Error ? error.message : String(error),
73
+ };
56
74
  }
57
75
  }
58
76
 
77
+ /** Read the stored selection; corruption, a too-new schema, or I/O errors yield undefined. */
78
+ export function readHarnessSelection(home: string): ReadonlyArray<Harness> | undefined {
79
+ const stored = loadHarnessSelection(home);
80
+ return stored.kind === "stored" ? stored.selection : undefined;
81
+ }
82
+
59
83
  export function writeHarnessSelection(home: string, selection: ReadonlyArray<Harness>): void {
60
84
  if (selection.length === 0) {
61
85
  throw new Error("Cannot write an empty harness selection because sync would become a no-op");
@@ -20,9 +20,14 @@ export type { Ctx, ModifierFlag } from "./engineCtx";
20
20
  export { runBounded, syncConcurrencyForManifest } from "./syncConcurrency";
21
21
  export type { SyncConcurrency, SyncTask } from "./syncConcurrency";
22
22
 
23
+ /**
24
+ * Run one engine operation. `options.envGlobals` defaults to false; only the
25
+ * main.ts native-raw branch sets it, so the public CLI ignores env globals.
26
+ */
23
27
  export async function runEngineNative(
24
28
  argv: ReadonlyArray<string>,
25
29
  services?: EngineServices,
30
+ options: { readonly envGlobals?: boolean } = {},
26
31
  ): Promise<number> {
27
32
  let ctx!: Ctx;
28
33
  const baseServices = services ?? makeEngineServices();
@@ -45,7 +50,7 @@ export async function runEngineNative(
45
50
  platform: baseServices.platform,
46
51
  };
47
52
  try {
48
- ctx = makeCtx(runServices);
53
+ ctx = makeCtx(runServices, { envGlobals: options.envGlobals === true });
49
54
  switch (argv[0]) {
50
55
  case "model":
51
56
  return await modeModel(ctx, argv.slice(1));
@@ -178,15 +178,20 @@ export function withKitDb<T>(
178
178
  if (access === "read" && !existsSync(file) && !existsSync(legacy)) return undefined;
179
179
 
180
180
  const directory = p(home, ".docks-kit");
181
- // `mode` applies only when mkdir creates the path, so an existing permissive
182
- // ~/.docks-kit would keep its mode.
183
- mkdirSync(directory, { recursive: true, mode: 0o700 });
184
- chmodSync(directory, 0o700);
181
+ // A read of an existing kit.db changes no permissions, so it works on a
182
+ // home that cannot be written.
183
+ const secure = access === "write" || !existsSync(file);
184
+ if (secure) {
185
+ // `mode` applies only when mkdir creates the path, so an existing permissive
186
+ // ~/.docks-kit would keep its mode.
187
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
188
+ chmodSync(directory, 0o700);
189
+ }
185
190
 
186
191
  const db = new DatabaseSync(file);
187
192
  try {
188
193
  // SQLite gives the -wal and -shm files the mode of the main file.
189
- if (process.platform !== "win32") chmodSync(file, 0o600);
194
+ if (secure && process.platform !== "win32") chmodSync(file, 0o600);
190
195
  // busy_timeout first: the switch to WAL needs a lock.
191
196
  db.exec(
192
197
  "PRAGMA busy_timeout = 5000; PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL; PRAGMA foreign_keys = ON;",
@@ -225,7 +230,8 @@ export function readCache(
225
230
  const payload = row?.["payload"];
226
231
  if (row?.["fingerprint"] !== CACHE_FINGERPRINT) return undefined;
227
232
  if (typeof fetchedAt !== "number" || typeof payload !== "string") return undefined;
228
- return now - fetchedAt <= maxAgeMs ? payload : undefined;
233
+ const age = now - fetchedAt;
234
+ return age >= 0 && age <= maxAgeMs ? payload : undefined;
229
235
  });
230
236
  } catch {
231
237
  return undefined;
@@ -1,5 +1,6 @@
1
1
  import { readFileSync } from "node:fs";
2
2
 
3
+ import { codexHome } from "./codexPaths";
3
4
  import { capture, p, which } from "./exec";
4
5
  import { LEGACY_SELECTION, readHarnessSelection } from "./harnesses";
5
6
  import { isObject, parseJson } from "./jq";
@@ -208,7 +209,7 @@ const UNREADABLE_CODEX_CACHE = "Codex model cache is unreadable";
208
209
  function codexCatalog(home: string): Lookup {
209
210
  let text: string;
210
211
  try {
211
- text = readFileSync(p(home, ".codex", "models_cache.json"), "utf8");
212
+ text = readFileSync(p(codexHome(home), "models_cache.json"), "utf8");
212
213
  } catch (error) {
213
214
  const missing =
214
215
  typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
@@ -2,6 +2,8 @@
2
2
  * Model-catalog helpers: SoT parsing, listing, and Claude/Codex model validation.
3
3
  * Curated message strings are covered by the golden suites.
4
4
  */
5
+ import { codexHome } from "./codexPaths";
6
+ import { p } from "./exec";
5
7
  import type { Ctx } from "./index";
6
8
  import { isObject, parseJson } from "./jq";
7
9
  import { payloadDisplayPath, payloadText } from "../payload";
@@ -16,7 +18,7 @@ export interface ModelCatalog {
16
18
 
17
19
  const LIVE_SOURCE_LABELS: Record<Exclude<CatalogSource, "curated">, string> = {
18
20
  "anthropic-api": "Anthropic API via Claude Code login",
19
- "codex-cache": "~/.codex/models_cache.json",
21
+ "codex-cache": "models_cache.json in the Codex home",
20
22
  "omp-cli": "omp models --json",
21
23
  };
22
24
 
@@ -88,10 +90,11 @@ export function validateClaudeModel(ctx: Ctx, m: string, catalog: ResolvedCatalo
88
90
  export function validateCodexModel(ctx: Ctx, m: string, catalog: ResolvedCatalog): boolean {
89
91
  if (!/^[A-Za-z0-9._-]+$/.test(m)) return false;
90
92
  if (!catalog.models.some((entry) => entry.id === m)) {
93
+ const config = p(codexHome(ctx.home), "config.toml");
91
94
  ctx.services.logger.warn(
92
95
  catalog.source === "curated"
93
- ? `Codex model '${m}' is not in the kit-verified catalog (SoT/models.json) — applying anyway (check ~/.codex/config.toml if Codex rejects it)`
94
- : `Codex model '${m}' is not in the live Codex model list — applying anyway (check ~/.codex/config.toml if Codex rejects it)`,
96
+ ? `Codex model '${m}' is not in the kit-verified catalog (SoT/models.json) — applying anyway (check ${config} if Codex rejects it)`
97
+ : `Codex model '${m}' is not in the live Codex model list — applying anyway (check ${config} if Codex rejects it)`,
95
98
  );
96
99
  }
97
100
  return true;