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,6 +6,7 @@ import { p } from "./exec";
6
6
  import { readFileSync } from "node:fs";
7
7
  import { payloadText } from "../payload";
8
8
 
9
+ import { codexHome } from "./codexPaths";
9
10
  import { syncClaudeModel } from "./claudeSettingsModifiers";
10
11
  import { syncCodexModel } from "./codexToml";
11
12
  import type { Ctx } from "./index";
@@ -14,7 +15,7 @@ import { printModels, validateClaudeModel, validateCodexModel } from "./models";
14
15
  import { defaultLiveInputs, resolveCatalog } from "./liveModels";
15
16
  import { bunBootstrap } from "./bun";
16
17
  import { upgradeLspServers } from "./claudeLsp";
17
- import { installedVersion, outdatedReport, present, report } from "./toolchain";
18
+ import { belowFloor, field, installedVersion, outdatedReport, present, report } from "./toolchain";
18
19
  import { topLevelTomlString } from "../manifests";
19
20
 
20
21
  export async function modeModel(ctx: Ctx, args: ReadonlyArray<string>): Promise<number> {
@@ -51,14 +52,14 @@ export async function modeModel(ctx: Ctx, args: ReadonlyArray<string>): Promise<
51
52
  echo(`deployed: ${jsonModelText(result.data)}`);
52
53
  echo(`SoT: ${jsonModelText(payloadText("SoT/.claude/settings.json"))}`);
53
54
  } else {
54
- const deployed = p(ctx.home, ".codex", "config.toml");
55
+ const deployed = p(codexHome(ctx.home), "config.toml");
55
56
  const result = readConfig(deployed);
56
57
  if (result.kind === "missing") {
57
- warn("~/.codex/config.toml missing");
58
+ warn(`${deployed} missing`);
58
59
  return 0;
59
60
  }
60
61
  if (result.kind === "read-error") {
61
- err(`Failed to read ~/.codex/config.toml: ${String(result.error)}`);
62
+ err(`Failed to read ${deployed}: ${String(result.error)}`);
62
63
  return 1;
63
64
  }
64
65
  echo(`deployed: ${topLevelTomlString(result.data, "model") ?? ""}`);
@@ -115,10 +116,10 @@ function jsonModelText(text: string): string {
115
116
  }
116
117
 
117
118
  const TOOLCHAIN_USAGE =
118
- "Usage: toolchain [check|ensure <tool>|outdated [--refresh]|upgrade [--dry-run]]";
119
+ "Usage: toolchain [check|ensure <tool> [--dry-run]|outdated [--refresh]|upgrade [--dry-run]]";
119
120
 
120
121
  export async function modeToolchain(ctx: Ctx, args: ReadonlyArray<string>): Promise<number> {
121
- const { echo, err, verbose } = ctx.services.logger;
122
+ const { echo, err, verbose, warn } = ctx.services.logger;
122
123
  const words = args.filter((arg) => !arg.startsWith("--"));
123
124
  const op = words[0] ?? "check";
124
125
  const tool = words[1] ?? "";
@@ -158,11 +159,15 @@ export async function modeToolchain(ctx: Ctx, args: ReadonlyArray<string>): Prom
158
159
  if (alreadyInstalled) {
159
160
  // A present tool whose --version cannot be read reports `unknown` in the
160
161
  // doctor table; keep the same vocabulary rather than an empty pair of
161
- // parentheses.
162
+ // parentheses. `ensure` never upgrades (policy `present`), but a Bun
163
+ // below the kit floor is a real problem, so it warns on every run.
162
164
  const probed = await installedVersion(ctx, "bun");
163
- const installed = probed === "" ? "version unknown" : probed;
164
- if (ctx.dryRun) echo(`[dry-run] bun up to date (${installed})`);
165
- else verbose(`bun up to date (${installed})`);
165
+ const floor = field("bun", "floor");
166
+ const label = probed === "" ? "version unknown" : probed;
167
+ if (belowFloor(probed, floor)) {
168
+ warn(`bun ${probed} is below the kit floor ${floor}; run bun upgrade`);
169
+ } else if (ctx.dryRun) echo(`[dry-run] bun present (${label})`);
170
+ else verbose(`bun present (${label})`);
166
171
  }
167
172
  return 0;
168
173
  }
@@ -9,12 +9,12 @@ import {
9
9
  existsSync,
10
10
  mkdirSync,
11
11
  readFileSync,
12
- renameSync,
13
12
  writeFileSync,
14
13
  } from "node:fs";
15
14
  import { basename } from "node:path";
16
15
 
17
16
  import { payloadDisplayPath, payloadText, type PayloadPath } from "../payload";
17
+ import { replaceFile } from "./atomicWrite";
18
18
  import type { Ctx } from "./index";
19
19
 
20
20
  export type OmpTextPayloadPath = Extract<PayloadPath, `SoT/.omp/${string}`>;
@@ -103,9 +103,8 @@ export function syncMergedYaml(
103
103
  }
104
104
 
105
105
  backupPrivateFile(target);
106
- writePrivateFile(`${target}.tmp`, merged);
107
- renameSync(`${target}.tmp`, target);
108
- chmodSync(target, 0o600);
106
+ // replaceFile writes through a symlinked config.yml or models.yml, so the link stays.
107
+ replaceFile(target, merged, { mode: 0o600 });
109
108
  change(`omp ${name} merged (backup at ${name}.bak)`);
110
109
  ctx.nextStepTriggers.ompRestart = true;
111
110
  }
@@ -54,6 +54,15 @@ export async function syncMarketplace(
54
54
  const adoptable =
55
55
  !registered && legacyRegistryFile !== undefined && registryHasDocks(legacyRegistryFile);
56
56
 
57
+ // syncPlugins owns the single skip message for both missing CLIs, and it runs
58
+ // right after this pass. Without omp no marketplace command can run at all,
59
+ // and without git a marketplace clone cannot resolve, so both are deliberate
60
+ // skips: return silently instead of spawning and recording a failure. The
61
+ // probes run before the dry-run branch, so a dry run previews only the
62
+ // commands that a real run on this host would run.
63
+ if (ctx.services.deps.probe("omp").state === "missing") return;
64
+ if (ctx.services.deps.probe("git").state === "missing") return;
65
+
57
66
  if (ctx.dryRun) {
58
67
  if (adoptable) {
59
68
  echo(
@@ -66,13 +75,6 @@ export async function syncMarketplace(
66
75
  return;
67
76
  }
68
77
 
69
- // syncPlugins owns the single skip message for both missing CLIs, and it runs
70
- // right after this pass. Without omp no marketplace command can run at all,
71
- // and without git a marketplace clone cannot resolve, so both are deliberate
72
- // skips: return silently instead of spawning and recording a failure.
73
- if (ctx.services.deps.probe("omp").state === "missing") return;
74
- if (ctx.services.deps.probe("git").state === "missing") return;
75
-
76
78
  if (!registered && !adoptable) {
77
79
  progress("Registering omp docks marketplace...");
78
80
  const result = await spawnProcess("omp", ["plugin", "marketplace", "add", MARKETPLACE_SOURCE], {
@@ -1,7 +1,13 @@
1
1
  /**
2
2
  * Run overlay for `docks-kit omp`. The overlay merges over the deployed omp
3
- * config for one run only, so every key that can cause paid spend is set here
4
- * and every other key falls through to the deployed paid config.
3
+ * config for one run only. It sets the 16 roles in ROLE_ORDER to the free
4
+ * model and empties the 13 retry chains in FALLBACK_ORDER. omp merges the
5
+ * overlay key by key, so each deployed retry chain that is not in
6
+ * FALLBACK_ORDER stays as deployed. The `web` role and its retry chain are
7
+ * not in the overlay, so the deployed web-search provider order applies, and
8
+ * that order can include a paid chat model. A deployed `plan`, `slow`, or
9
+ * `designer` chain also stays and can name a paid model. Every other key
10
+ * falls through to the deployed config.
5
11
  */
6
12
  import { createHash } from "node:crypto";
7
13
  import type { OmpSessionModel } from "./harnesses";
@@ -24,20 +30,26 @@ export const THINKING_LADDER: ReadonlyArray<string> = [
24
30
  ];
25
31
 
26
32
  /**
27
- * One overlay file per model, so a second launcher on another model cannot
28
- * rewrite the file a running session still reads. A selector carries a slash
29
- * and may carry other characters a host rejects in a file name, so unsafe
30
- * characters become hyphens. That mapping alone is not injective, because
31
- * `a/b` and `a-b` both fold to `a-b`, so a digest of the exact selector keeps
32
- * two distinct models on two distinct files.
33
+ * One overlay file per distinct model and level combination, so a second
34
+ * launcher cannot rewrite the file a running session still reads. omp
35
+ * reloads a changed overlay mid-session, so the digest covers the exact
36
+ * rendered overlay: the selector, both levels, and every rendered key. A
37
+ * selector carries a slash and may carry other characters a host rejects in
38
+ * a file name, so unsafe characters in the readable prefix become hyphens.
33
39
  */
34
- export function overlayFileName(selector: string): string {
35
- const safe = selector.replace(/[^A-Za-z0-9._-]/g, "-");
36
- const digest = createHash("sha256").update(selector).digest("hex").slice(0, 8);
40
+ export function overlayFileName(model: OmpSessionModel): string {
41
+ const safe = model.selector.replace(/[^A-Za-z0-9._-]/g, "-");
42
+ const digest = createHash("sha256").update(renderFreeOverlay(model)).digest("hex").slice(0, 8);
37
43
  return `omp-free-${safe}-${digest}.yml`;
38
44
  }
39
45
 
40
- /** Role keys in the order used by SoT/.omp/config.yml for readable diffs. */
46
+ /**
47
+ * Role keys in the order used by SoT/.omp/config.yml for readable diffs. The
48
+ * SoT does not set `memory` and `judge`, so they come last. An unset role
49
+ * falls back to the omp built-in priority chain, which can name a paid model.
50
+ * The `web` role is left out on purpose, so the deployed web-search provider
51
+ * order applies.
52
+ */
41
53
  const ROLE_ORDER: ReadonlyArray<string> = [
42
54
  "smol",
43
55
  "advisor",
@@ -52,9 +64,16 @@ const ROLE_ORDER: ReadonlyArray<string> = [
52
64
  "fable",
53
65
  "switch_fable",
54
66
  "astra",
67
+ "reviewer",
68
+ "memory",
69
+ "judge",
55
70
  ];
56
71
 
57
- /** Retry chain keys in the order used by SoT/.omp/config.yml. */
72
+ /**
73
+ * Retry chain keys in the order used by SoT/.omp/config.yml, then `memory` and
74
+ * `judge`. An explicit empty chain stops omp from using its built-in priority
75
+ * chain. The `web` chain is left out, so the deployed chain applies.
76
+ */
58
77
  const FALLBACK_ORDER: ReadonlyArray<string> = [
59
78
  "default",
60
79
  "advisor",
@@ -66,6 +85,9 @@ const FALLBACK_ORDER: ReadonlyArray<string> = [
66
85
  "switch_fable",
67
86
  "fable",
68
87
  "astra",
88
+ "reviewer",
89
+ "memory",
90
+ "judge",
69
91
  ];
70
92
 
71
93
  /**
@@ -89,6 +111,10 @@ export function parseFreeModels(catalogJson: unknown): ReadonlyArray<CatalogMode
89
111
  if (typeof cost !== "object" || cost === null || Array.isArray(cost)) continue;
90
112
  const charges = cost as Record<string, unknown>;
91
113
  if (charges["input"] !== 0 || charges["output"] !== 0) continue;
114
+ // omp prices a usage-billed or plan-included model at zero, so a zero
115
+ // cost is not proof of a free model. Older omp output has no status.
116
+ const status = record["pricingStatus"];
117
+ if (typeof status === "string" && status !== "free" && status !== "unknown") continue;
92
118
  const rawName = record["name"];
93
119
  const name = typeof rawName === "string" && rawName.length > 0 ? rawName : selector;
94
120
  const rawLevels = record["thinking"];
@@ -8,7 +8,7 @@
8
8
  * dry run stays free of omp subcommands.
9
9
  */
10
10
  import { existsSync } from "node:fs";
11
- import { isAbsolute, resolve } from "node:path";
11
+ import { resolve } from "node:path";
12
12
 
13
13
  import { p } from "./exec";
14
14
 
@@ -51,11 +51,6 @@ function normalizeProfile(value: string | undefined): string | undefined {
51
51
  return name;
52
52
  }
53
53
 
54
- /** Upstream applies `path.resolve` to PI_CODING_AGENT_DIR, so cwd anchors a relative value. */
55
- function resolveAgentOverride(value: string): string {
56
- return isAbsolute(value) ? value : resolve(process.cwd(), value);
57
- }
58
-
59
54
  export function ompPaths({ home, env, platform }: OmpPathInputs): OmpPaths {
60
55
  // OMP_PROFILE wins whenever it is defined, including when explicitly empty;
61
56
  // PI_PROFILE is only the legacy fallback.
@@ -72,12 +67,28 @@ export function ompPaths({ home, env, platform }: OmpPathInputs): OmpPaths {
72
67
  const configRoot = profile === undefined ? baseRoot : p(baseRoot, "profiles", profile);
73
68
 
74
69
  // A named profile derives its own agent directory and ignores the override.
70
+ // The default profile also ignores an override that equals the agent
71
+ // directory of the PI_PROFILE profile, because omp exports that value in a
72
+ // profile session. Upstream compares the raw string here.
73
+ // Upstream applies `path.resolve` to a used override. The call anchors a
74
+ // relative value at cwd and normalizes an absolute value.
75
75
  const agentOverride = env["PI_CODING_AGENT_DIR"];
76
76
  const defaultAgentDir = p(configRoot, "agent");
77
+ const legacyProfile = normalizeProfile(env["PI_PROFILE"]);
78
+ const overrideIgnored =
79
+ profile === undefined &&
80
+ legacyProfile !== undefined &&
81
+ agentOverride === p(baseRoot, "profiles", legacyProfile, "agent");
82
+ const resolvedOverride =
83
+ profile === undefined && !overrideIgnored && agentOverride !== undefined && agentOverride !== ""
84
+ ? resolve(agentOverride)
85
+ : undefined;
86
+ // resolve() rewrites separators on Windows, so an override that names the
87
+ // default directory is compared in resolved form and keeps the default path.
77
88
  const agentDir =
78
- profile === undefined && agentOverride !== undefined && agentOverride !== ""
79
- ? resolveAgentOverride(agentOverride)
80
- : defaultAgentDir;
89
+ resolvedOverride === undefined || resolvedOverride === resolve(defaultAgentDir)
90
+ ? defaultAgentDir
91
+ : resolvedOverride;
81
92
 
82
93
  return {
83
94
  profile,
@@ -76,21 +76,6 @@ async function runPluginCommand(
76
76
  export async function syncPlugins(ctx: Ctx): Promise<number> {
77
77
  const { change, clearProgress, echo, progress, verbose, warn } = ctx.services.logger;
78
78
 
79
- if (ctx.dryRun) {
80
- const piIntercomPin = field("pi-intercom", "verified");
81
- for (const pluginId of MARKETPLACE_PLUGIN_IDS) {
82
- echo(`[dry-run] omp plugin install --scope user ${pluginId}`);
83
- }
84
- if (piIntercomPin === "") {
85
- warn(
86
- "pi-intercom install skipped because SoT/toolchain.json has no verified pi-intercom pin",
87
- );
88
- } else {
89
- echo(`[dry-run] omp install pi-intercom@${piIntercomPin}`);
90
- }
91
- return 0;
92
- }
93
-
94
79
  if (ctx.services.deps.probe("omp").state === "missing") {
95
80
  ctx.services.deps.warnMissing(
96
81
  "omp",
@@ -107,6 +92,22 @@ export async function syncPlugins(ctx: Ctx): Promise<number> {
107
92
  );
108
93
  return 0;
109
94
  }
95
+
96
+ if (ctx.dryRun) {
97
+ const piIntercomPin = field("pi-intercom", "verified");
98
+ for (const pluginId of MARKETPLACE_PLUGIN_IDS) {
99
+ echo(`[dry-run] omp plugin install --scope user ${pluginId}`);
100
+ }
101
+ if (piIntercomPin === "") {
102
+ warn(
103
+ "pi-intercom install skipped because SoT/toolchain.json has no verified pi-intercom pin",
104
+ );
105
+ } else {
106
+ echo(`[dry-run] omp install pi-intercom@${piIntercomPin}`);
107
+ }
108
+ return 0;
109
+ }
110
+
110
111
  const piIntercomPin = field("pi-intercom", "verified");
111
112
 
112
113
  progress("Checking installed omp plugins...");
@@ -58,13 +58,18 @@ export async function ompSync(ctx: Ctx): Promise<OmpState> {
58
58
  syncMergedYaml(ctx, "SoT/.omp/models.yml", p(agentDir, "models.yml"), mergeOmpModels);
59
59
  syncOmpModelRemovals(ctx, p(agentDir, "models.yml"));
60
60
 
61
- const intercomRootSetting = process.env["PI_CODING_AGENT_DIR"];
61
+ // omp exports PI_CODING_AGENT_DIR as the agent directory of a named profile,
62
+ // and pi-intercom reads the trimmed value. Without a profile, the kit uses
63
+ // the PI_CODING_AGENT_DIR value when it is set, else ~/.pi/agent.
64
+ const intercomRootSetting = process.env["PI_CODING_AGENT_DIR"]?.trim();
62
65
  const intercomRoot =
63
- intercomRootSetting !== undefined && intercomRootSetting !== ""
64
- ? isAbsolute(intercomRootSetting)
65
- ? intercomRootSetting
66
- : resolve(process.cwd(), intercomRootSetting)
67
- : p(ctx.home, ".pi", "agent");
66
+ paths.profile !== undefined
67
+ ? paths.agentDir
68
+ : intercomRootSetting !== undefined && intercomRootSetting !== ""
69
+ ? isAbsolute(intercomRootSetting)
70
+ ? intercomRootSetting
71
+ : resolve(process.cwd(), intercomRootSetting)
72
+ : p(ctx.home, ".pi", "agent");
68
73
  const intercomDir = p(intercomRoot, "intercom");
69
74
  if (!ctx.dryRun) ensureDirectory(intercomDir);
70
75
  syncWholeFile(
@@ -7,12 +7,19 @@
7
7
  * wildcards ahead of role chains, so a stale wildcard would silently override
8
8
  * the kit-managed role chains. models.yml drops nothing; a user file may carry
9
9
  * provider credentials and custom models the kit never declares.
10
+ *
11
+ * A SoT sequence replaces the deployed sequence, except `bash.patterns` in
12
+ * config.yml: `mergeBashPatterns` keeps the user's command rules and groups all
13
+ * rules by approval.
10
14
  */
11
- import { isMap, isScalar, parseDocument, type YAMLMap } from "yaml";
15
+ import { isMap, isScalar, isSeq, parseDocument, type YAMLMap, type YAMLSeq } from "yaml";
12
16
 
13
17
  /** Decides whether a deployed-only key at `path` is dropped instead of kept. */
14
18
  type DropDeployedKey = (path: ReadonlyArray<string>, key: string) => boolean;
15
19
 
20
+ /** Merges the deployed sequence at `path` into the SoT sequence in place. */
21
+ type MergeSequence = (path: ReadonlyArray<string>, sotSeq: YAMLSeq, deployedSeq: YAMLSeq) => void;
22
+
16
23
  const fallbackChainsPath = ["retry", "fallbackChains"] as const;
17
24
 
18
25
  function stringKey(key: unknown): string | undefined {
@@ -33,6 +40,70 @@ const dropFallbackWildcard: DropDeployedKey = (path, key) =>
33
40
 
34
41
  const keepEveryKey: DropDeployedKey = () => false;
35
42
 
43
+ const keepSotSequence: MergeSequence = () => {};
44
+
45
+ /**
46
+ * Identity of one `bash.patterns` rule, normalized the way omp reads it: the
47
+ * approval is trimmed and lowercased, and whitespace runs in `match` collapse to
48
+ * one space. Returns undefined for an entry omp would ignore.
49
+ */
50
+ function bashPatternKey(node: unknown): string | undefined {
51
+ if (!isMap(node)) return undefined;
52
+ const match = node.get("match");
53
+ const approval = node.get("approval");
54
+ if (typeof match !== "string" || typeof approval !== "string") return undefined;
55
+ return `${approval.trim().toLowerCase()}\u0000${match.trim().replace(/\s+/gu, " ")}`;
56
+ }
57
+
58
+ /**
59
+ * omp evaluates `bash.patterns` in order, and the first matching rule wins. The
60
+ * merge groups the rules: kit deny, user deny, user prompt, kit exception allow,
61
+ * kit prompt, the other user rules in their deployed order, then kit allow. A
62
+ * kit exception is a kit allow that the SoT lists before its first prompt: an
63
+ * option-terminated form such as `git rm -- *` that a broader kit prompt
64
+ * (`git rm *`) would otherwise shadow, because a glob cannot exclude it. A user
65
+ * deny or prompt therefore always precedes every kit allow, and no user or
66
+ * tail allow loosens a deny or a prompt. A deployed rule equal to a kit rule is
67
+ * the kit copy, so a re-sync changes nothing. A rule the kit stops shipping
68
+ * stays as a user rule.
69
+ */
70
+ const mergeBashPatterns: MergeSequence = (path, sotSeq, deployedSeq) => {
71
+ if (path.length !== 2 || path[0] !== "bash" || path[1] !== "patterns") return;
72
+ const kitKeys = new Set(sotSeq.items.map(bashPatternKey));
73
+ const kit: Record<"deny" | "exception" | "prompt" | "allow", Array<unknown>> = {
74
+ deny: [],
75
+ exception: [],
76
+ prompt: [],
77
+ allow: [],
78
+ };
79
+ const user: Record<"deny" | "prompt" | "other", Array<unknown>> = {
80
+ deny: [],
81
+ prompt: [],
82
+ other: [],
83
+ };
84
+ for (const item of sotSeq.items) {
85
+ const approval = bashPatternKey(item)?.split("\u0000")[0];
86
+ if (approval === "deny" || approval === "prompt") kit[approval].push(item);
87
+ else if (kit.prompt.length === 0 && approval === "allow") kit.exception.push(item);
88
+ else kit.allow.push(item);
89
+ }
90
+ for (const item of deployedSeq.items) {
91
+ const key = bashPatternKey(item);
92
+ if (key !== undefined && kitKeys.has(key)) continue;
93
+ const approval = key?.split("\u0000")[0];
94
+ user[approval === "deny" || approval === "prompt" ? approval : "other"].push(item);
95
+ }
96
+ sotSeq.items = [
97
+ ...kit.deny,
98
+ ...user.deny,
99
+ ...user.prompt,
100
+ ...kit.exception,
101
+ ...kit.prompt,
102
+ ...user.other,
103
+ ...kit.allow,
104
+ ];
105
+ };
106
+
36
107
  function pruneMapping(mapping: YAMLMap, path: ReadonlyArray<string>, drop: DropDeployedKey): void {
37
108
  for (let index = mapping.items.length - 1; index >= 0; index--) {
38
109
  const pair = mapping.items[index];
@@ -55,6 +126,7 @@ function mergeMappings(
55
126
  deployedMapping: YAMLMap,
56
127
  path: ReadonlyArray<string>,
57
128
  drop: DropDeployedKey,
129
+ mergeSequence: MergeSequence,
58
130
  ): void {
59
131
  for (const sotPair of sotMapping.items) {
60
132
  const key = stringKey(sotPair.key);
@@ -64,7 +136,10 @@ function mergeMappings(
64
136
  (candidate) => stringKey(candidate.key) === key,
65
137
  );
66
138
  if (deployedPair !== undefined && isMap(sotPair.value) && isMap(deployedPair.value)) {
67
- mergeMappings(sotPair.value, deployedPair.value, [...path, key], drop);
139
+ mergeMappings(sotPair.value, deployedPair.value, [...path, key], drop, mergeSequence);
140
+ }
141
+ if (deployedPair !== undefined && isSeq(sotPair.value) && isSeq(deployedPair.value)) {
142
+ mergeSequence([...path, key], sotPair.value, deployedPair.value);
68
143
  }
69
144
  }
70
145
 
@@ -87,6 +162,7 @@ function mergeYamlDocuments(
87
162
  deployedText: string,
88
163
  name: string,
89
164
  drop: DropDeployedKey,
165
+ mergeSequence: MergeSequence,
90
166
  ): string {
91
167
  const deployedDoc = parseDocument(deployedText);
92
168
  const deployedError = deployedDoc.errors[0];
@@ -115,16 +191,25 @@ function mergeYamlDocuments(
115
191
  throw new Error(`SoT omp ${name} YAML root must be a mapping`);
116
192
  }
117
193
 
118
- mergeMappings(sotDoc.contents, deployedContents, [], drop);
194
+ mergeMappings(sotDoc.contents, deployedContents, [], drop, mergeSequence);
119
195
  return sotDoc.toString();
120
196
  }
121
197
 
122
- /** config.yml merge: keeps user-only keys, drops stale fallback-chain wildcards. */
198
+ /**
199
+ * config.yml merge: keeps user-only keys and user `bash.patterns` rules, drops
200
+ * stale fallback-chain wildcards.
201
+ */
123
202
  export function mergeOmpConfig(sotText: string, deployedText: string): string {
124
- return mergeYamlDocuments(sotText, deployedText, "config.yml", dropFallbackWildcard);
203
+ return mergeYamlDocuments(
204
+ sotText,
205
+ deployedText,
206
+ "config.yml",
207
+ dropFallbackWildcard,
208
+ mergeBashPatterns,
209
+ );
125
210
  }
126
211
 
127
212
  /** models.yml merge: keeps every user-only key, including credentials and custom models. */
128
213
  export function mergeOmpModels(sotText: string, deployedText: string): string {
129
- return mergeYamlDocuments(sotText, deployedText, "models.yml", keepEveryKey);
214
+ return mergeYamlDocuments(sotText, deployedText, "models.yml", keepEveryKey, keepSotSequence);
130
215
  }
@@ -5,6 +5,8 @@ export const darwin: HostOs = posixHost({
5
5
  id: "darwin",
6
6
  toolchainOs: "darwin",
7
7
  supportsBubblewrap: false,
8
+ // macOS terminals start bash as a login shell. It reads the first existing file of these and never reads .bashrc.
9
+ bashTargets: [".bash_profile", ".bash_login", ".profile"],
8
10
  packageManagerHints: {
9
11
  git: "brew install git",
10
12
  jq: "brew install jq",
@@ -5,6 +5,7 @@ export const linux: HostOs = posixHost({
5
5
  id: "linux",
6
6
  toolchainOs: "linux",
7
7
  supportsBubblewrap: true,
8
+ bashTargets: [".bashrc"],
8
9
  packageManagerHints: {
9
10
  git: "sudo apt install -y git (or your distro's package manager)",
10
11
  jq: "sudo apt install -y jq",
@@ -10,8 +10,7 @@ function posixLiteral(value: string): string {
10
10
  export type PackageManagerHints = Readonly<Record<Exclude<HintedTool, "claude" | "codex">, string>>;
11
11
 
12
12
  const UPSTREAM_INSTALLER_HINTS: Readonly<Record<"claude" | "codex", string>> = {
13
- claude:
14
- "curl -fsSL https://claude.ai/install.sh -o /tmp/claude-install.sh && bash /tmp/claude-install.sh",
13
+ claude: 'tmp=$(mktemp) && curl -fsSL https://claude.ai/install.sh -o "$tmp" && bash "$tmp"',
15
14
  codex:
16
15
  'tmp=$(mktemp) && curl -fsSL https://chatgpt.com/codex/install.sh -o "$tmp" && CODEX_NON_INTERACTIVE=1 sh "$tmp"',
17
16
  };
@@ -21,6 +20,8 @@ interface PosixHostInputs {
21
20
  readonly toolchainOs: HostOs["toolchainOs"];
22
21
  readonly supportsBubblewrap: boolean;
23
22
  readonly packageManagerHints: PackageManagerHints;
23
+ /** Home-relative bash startup files in read order; the first existing one gets the write, else the first entry. */
24
+ readonly bashTargets: readonly [string, ...string[]];
24
25
  }
25
26
 
26
27
  /** Members shared by every POSIX host; linux and darwin differ only in the inputs. */
@@ -49,11 +50,22 @@ export function posixHost(inputs: PosixHostInputs): HostOs {
49
50
  },
50
51
  environmentSetting: (name, value) => ({
51
52
  kind: "profile",
52
- candidates: [".zshrc", ".bashrc", ".bash_profile", ".profile", ".zshenv"],
53
- target: (shell) => {
53
+ // Bash reads .bash_login only as a login file. Only a host that writes to it
54
+ // scans it, so a dormant copy cannot block the write to the loaded file.
55
+ candidates: [
56
+ ".zshrc",
57
+ ".bashrc",
58
+ ".bash_profile",
59
+ ...(inputs.bashTargets.includes(".bash_login") ? [".bash_login"] : []),
60
+ ".profile",
61
+ ".zshenv",
62
+ ],
63
+ target: (shell, exists) => {
54
64
  const shellPath = shell ?? "bash";
55
65
  const shellName = shellPath.slice(shellPath.lastIndexOf("/") + 1);
56
- return shellName === "zsh" ? ".zshrc" : shellName === "bash" ? ".bashrc" : ".profile";
66
+ if (shellName === "zsh") return ".zshrc";
67
+ if (shellName !== "bash") return ".profile";
68
+ return inputs.bashTargets.find(exists) ?? inputs.bashTargets[0];
57
69
  },
58
70
  line: `export ${name}=${value}`,
59
71
  }),
@@ -24,8 +24,8 @@ export type EnvironmentSetting =
24
24
  readonly kind: "profile";
25
25
  /** Home-relative files scanned for an existing setting. */
26
26
  readonly candidates: ReadonlyArray<string>;
27
- /** Home-relative file that receives the write for this shell. */
28
- readonly target: (shell: string | undefined) => string;
27
+ /** Home-relative file that receives the write for this shell; `exists` tests a home-relative file. */
28
+ readonly target: (shell: string | undefined, exists: (file: string) => boolean) => string;
29
29
  /** Line appended to the target file. */
30
30
  readonly line: string;
31
31
  }
@@ -3,7 +3,7 @@ import { p } from "../exec";
3
3
  import type { HostOs } from "./types";
4
4
 
5
5
  function powershellLiteral(value: string): string {
6
- return `'${value.replaceAll("'", "''")}'`;
6
+ return `'${value.replace(/['\u2018\u2019\u201A\u201B]/g, "$&$&")}'`;
7
7
  }
8
8
 
9
9
  function encodedPowerShellCommand(script: string): string {
@@ -14,8 +14,8 @@ function encodedPowerShellCommand(script: string): string {
14
14
  /**
15
15
  * Windows shim encoding handles three hazards: Windows argv parsing, cmd
16
16
  * metacharacter parsing, and percent/newline values that cmd cannot escape.
17
- * The encoders are ported from cross-spawn's escape.js and its parseNonShell
18
- * assembly, based on:
17
+ * The caret encoders are ported from cross-spawn's escape.js and its
18
+ * parseNonShell assembly; the backslash encoder is a linear MSVCRT pass. Based on:
19
19
  * https://github.com/moxystudio/node-cross-spawn
20
20
  * https://qntm.org/cmd
21
21
  * https://flatt.tech/research/posts/batbadbut-you-cant-securely-execute-commands-on-windows/
@@ -27,15 +27,27 @@ function escapeCommand(arg: string): string {
27
27
  return arg.replace(metaCharsRegExp, "^$1");
28
28
  }
29
29
 
30
- function escapeArgument(arg: string, doubleEscapeMetaChars: boolean): string {
31
- arg = `${arg}`;
32
- arg = arg.replace(/(?=(\\+?)?)\1"/g, '$1$1\\"');
33
- arg = arg.replace(/(?=(\\+?)?)\1$/, "$1$1");
30
+ function escapeArgument(arg: string): string {
31
+ // One linear pass applies the MSVCRT argv rules: a backslash run before a
32
+ // quote doubles and gains one escape, and a trailing run doubles before the
33
+ // closing quote. A greedy regex would be quadratic on long backslash runs.
34
+ let out = "";
35
+ let run = 0;
36
+ for (const ch of arg) {
37
+ if (ch === "\\") {
38
+ run++;
39
+ continue;
40
+ }
41
+ out += ch === '"' ? `${"\\".repeat(2 * run + 1)}"` : `${"\\".repeat(run)}${ch}`;
42
+ run = 0;
43
+ }
44
+ arg = out + "\\".repeat(2 * run);
34
45
  arg = `"${arg}"`;
46
+ // Two caret layers: the outer cmd removes one layer, and a batch file that
47
+ // forwards `%*` parses the arguments again. The kit cannot see which batch
48
+ // files forward `%*`, so every .cmd/.bat argument gets both layers.
49
+ arg = arg.replace(metaCharsRegExp, "^$1");
35
50
  arg = arg.replace(metaCharsRegExp, "^$1");
36
- if (doubleEscapeMetaChars) {
37
- arg = arg.replace(metaCharsRegExp, "^$1");
38
- }
39
51
  return arg;
40
52
  }
41
53
 
@@ -77,11 +89,7 @@ function commandShimInvocation(executablePath: string, args: ReadonlyArray<strin
77
89
  for (const arg of args) assertCommandLineValue(arg, "argument");
78
90
 
79
91
  const normalizedPath = win32.normalize(executablePath);
80
- const doubleEscapeMetaChars = /node_modules[\\/]\.bin[\\/][^\\/]+\.cmd$/i.test(normalizedPath);
81
- const commandLine = [
82
- escapeCommand(normalizedPath),
83
- ...args.map((arg) => escapeArgument(arg, doubleEscapeMetaChars)),
84
- ].join(" ");
92
+ const commandLine = [escapeCommand(normalizedPath), ...args.map(escapeArgument)].join(" ");
85
93
  return {
86
94
  command: commandInterpreter(),
87
95
  args: ["/d", "/v:off", "/s", "/c", `"${commandLine}"`],
@@ -89,7 +97,7 @@ function commandShimInvocation(executablePath: string, args: ReadonlyArray<strin
89
97
  } as const;
90
98
  }
91
99
 
92
- // Authored now, but unreachable until the supported-host admission gate opens.
100
+ // Host module for the windows-x64 and windows-arm64 targets admitted in os/targets.ts.
93
101
  export const windows: HostOs = {
94
102
  id: "windows",
95
103
  toolchainOs: "windows",