docks-kit 0.22.13 → 0.22.20

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 (53) hide show
  1. package/AGENTS.md +94 -80
  2. package/README.md +7 -7
  3. package/cli/docs/command-guards.md +7 -3
  4. package/cli/docs/flags.md +59 -9
  5. package/cli/docs/install.md +2 -2
  6. package/cli/docs/omp-context.md +14 -8
  7. package/cli/docs/omp-models.md +1 -1
  8. package/cli/docs/overview.md +1 -1
  9. package/cli/docs/platforms.md +4 -2
  10. package/cli/docs/plugins.md +8 -5
  11. package/cli/docs/sync-layers.md +6 -4
  12. package/cli/docs/toolchain.md +24 -14
  13. package/cli/src/argv.ts +7 -4
  14. package/cli/src/argvValidate.ts +2 -16
  15. package/cli/src/commands/docs.ts +1 -1
  16. package/cli/src/commands/omp.ts +56 -15
  17. package/cli/src/commands/sync.ts +6 -6
  18. package/cli/src/commands/tidy.ts +83 -26
  19. package/cli/src/engine-native/DESIGN.md +93 -56
  20. package/cli/src/engine-native/atomicWrite.ts +168 -8
  21. package/cli/src/engine-native/codexConfig.ts +2 -6
  22. package/cli/src/engine-native/codexPlugins.ts +1 -1
  23. package/cli/src/engine-native/codexSync.ts +137 -26
  24. package/cli/src/engine-native/codexToml.ts +4 -86
  25. package/cli/src/engine-native/deps.ts +51 -51
  26. package/cli/src/engine-native/exec.ts +3 -0
  27. package/cli/src/engine-native/index.ts +1 -1
  28. package/cli/src/engine-native/kitLock.ts +121 -0
  29. package/cli/src/engine-native/modes.ts +49 -31
  30. package/cli/src/engine-native/ompChild.ts +26 -0
  31. package/cli/src/engine-native/ompFastMode.ts +14 -7
  32. package/cli/src/engine-native/ompFileDeploy.ts +12 -6
  33. package/cli/src/engine-native/ompMarketplace.ts +25 -18
  34. package/cli/src/engine-native/ompPlugins.ts +23 -14
  35. package/cli/src/engine-native/ompRemovals.ts +51 -23
  36. package/cli/src/engine-native/ompSync.ts +66 -32
  37. package/cli/src/engine-native/os/targets.ts +16 -4
  38. package/cli/src/engine-native/os/types.ts +1 -1
  39. package/cli/src/engine-native/parseArgs.ts +27 -17
  40. package/cli/src/engine-native/processes.ts +16 -0
  41. package/cli/src/engine-native/scratch.ts +18 -0
  42. package/cli/src/engine-native/skillsInstall.ts +27 -2
  43. package/cli/src/engine-native/skillsPrune.ts +51 -49
  44. package/cli/src/engine-native/skillsRecords.ts +138 -0
  45. package/cli/src/engine-native/skillsSync.ts +16 -13
  46. package/cli/src/engine-native/syncDispatch.ts +186 -4
  47. package/cli/src/engine-native/tidy.ts +102 -119
  48. package/cli/src/engine-native/tomlLines.ts +92 -0
  49. package/cli/src/generated/sotPayload.ts +4 -4
  50. package/cli/src/main.ts +5 -30
  51. package/cli/src/manifests.ts +24 -4
  52. package/package.json +2 -2
  53. package/cli/src/engine-native/tidyLock.ts +0 -163
@@ -3,7 +3,7 @@
3
3
  * golden-tested messages, same exit codes.
4
4
  */
5
5
  import { p } from "./exec";
6
- import { readFileSync } from "node:fs";
6
+ import { existsSync, readFileSync } from "node:fs";
7
7
  import { payloadText } from "../payload";
8
8
 
9
9
  import { codexHome } from "./codexPaths";
@@ -14,12 +14,13 @@ import { isObject, parseJson, type Json } from "./jq";
14
14
  import { printModels, validateClaudeModel, validateCodexModel } from "./models";
15
15
  import { defaultLiveInputs, resolveCatalog } from "./liveModels";
16
16
  import { bunBootstrap } from "./bun";
17
+ import { withFolderLocks, withSyncLock } from "./syncDispatch";
17
18
  import { upgradeLspServers } from "./claudeLsp";
18
19
  import { belowFloor, field, installedVersion, outdatedReport, present, report } from "./toolchain";
19
20
  import { topLevelTomlString } from "../manifests";
20
21
 
21
22
  export async function modeModel(ctx: Ctx, args: ReadonlyArray<string>): Promise<number> {
22
- const { echo, err, warn } = ctx.services.logger;
23
+ const { err } = ctx.services.logger;
23
24
  let tool: "claude" | "codex" | "" = "";
24
25
  let value = "";
25
26
  for (const arg of args) {
@@ -36,39 +37,56 @@ export async function modeModel(ctx: Ctx, args: ReadonlyArray<string>): Promise<
36
37
  err("Usage: model <claude|codex> [value] [--dry-run]");
37
38
  return 2;
38
39
  }
40
+ if (value === "") return await showModel(ctx, tool);
41
+ // A write does the same read-modify-write of settings.json and config.toml as a sync.
42
+ return await withSyncLock(ctx, args, async () => {
43
+ // `model codex` writes config.toml in the Codex folder, which syncs of
44
+ // other homes can share. It creates no folder, so a missing one needs no lock.
45
+ const codexDir = codexHome(ctx.home);
46
+ const folders = tool === "codex" && existsSync(codexDir) ? [codexDir] : [];
47
+ return await withFolderLocks(ctx, folders, () => writeModel(ctx, tool, value));
48
+ });
49
+ }
50
+
51
+ /** Print the deployed model, the SoT model, and the model catalog of `tool`. */
52
+ async function showModel(ctx: Ctx, tool: "claude" | "codex"): Promise<number> {
53
+ const { echo, err, warn } = ctx.services.logger;
39
54
  const catalog = await resolveCatalog(tool, defaultLiveInputs(ctx.home));
40
- if (value === "") {
41
- if (tool === "claude") {
42
- const deployed = p(ctx.home, ".claude", "settings.json");
43
- const result = readConfig(deployed);
44
- if (result.kind === "missing") {
45
- warn("~/.claude/settings.json missing");
46
- return 0;
47
- }
48
- if (result.kind === "read-error") {
49
- err(`Failed to read ~/.claude/settings.json: ${String(result.error)}`);
50
- return 1;
51
- }
52
- echo(`deployed: ${jsonModelText(result.data)}`);
53
- echo(`SoT: ${jsonModelText(payloadText("SoT/.claude/settings.json"))}`);
54
- } else {
55
- const deployed = p(codexHome(ctx.home), "config.toml");
56
- const result = readConfig(deployed);
57
- if (result.kind === "missing") {
58
- warn(`${deployed} missing`);
59
- return 0;
60
- }
61
- if (result.kind === "read-error") {
62
- err(`Failed to read ${deployed}: ${String(result.error)}`);
63
- return 1;
64
- }
65
- echo(`deployed: ${topLevelTomlString(result.data, "model") ?? ""}`);
66
- echo(`SoT: ${topLevelTomlString(payloadText("SoT/.codex/config.toml"), "model") ?? ""}`);
55
+ if (tool === "claude") {
56
+ const deployed = p(ctx.home, ".claude", "settings.json");
57
+ const result = readConfig(deployed);
58
+ if (result.kind === "missing") {
59
+ warn("~/.claude/settings.json missing");
60
+ return 0;
67
61
  }
68
- printModels(ctx, catalog);
69
- return 0;
62
+ if (result.kind === "read-error") {
63
+ err(`Failed to read ~/.claude/settings.json: ${String(result.error)}`);
64
+ return 1;
65
+ }
66
+ echo(`deployed: ${jsonModelText(result.data)}`);
67
+ echo(`SoT: ${jsonModelText(payloadText("SoT/.claude/settings.json"))}`);
68
+ } else {
69
+ const deployed = p(codexHome(ctx.home), "config.toml");
70
+ const result = readConfig(deployed);
71
+ if (result.kind === "missing") {
72
+ warn(`${deployed} missing`);
73
+ return 0;
74
+ }
75
+ if (result.kind === "read-error") {
76
+ err(`Failed to read ${deployed}: ${String(result.error)}`);
77
+ return 1;
78
+ }
79
+ echo(`deployed: ${topLevelTomlString(result.data, "model") ?? ""}`);
80
+ echo(`SoT: ${topLevelTomlString(payloadText("SoT/.codex/config.toml"), "model") ?? ""}`);
70
81
  }
82
+ printModels(ctx, catalog);
83
+ return 0;
84
+ }
71
85
 
86
+ /** Validate `value` against the model catalog of `tool`, then write it. */
87
+ async function writeModel(ctx: Ctx, tool: "claude" | "codex", value: string): Promise<number> {
88
+ const { err } = ctx.services.logger;
89
+ const catalog = await resolveCatalog(tool, defaultLiveInputs(ctx.home));
72
90
  if (tool === "claude") {
73
91
  if (!validateClaudeModel(ctx, value, catalog)) {
74
92
  printModels(ctx, catalog);
@@ -0,0 +1,26 @@
1
+ /**
2
+ * The `omp` child processes of a sync. Every `omp` command that the
3
+ * marketplace and plugin passes run starts through `spawnOmp`, so each child
4
+ * writes into the data root that the sync locked.
5
+ */
6
+ import { spawnProcess, type AsyncProcessOptions, type AsyncProcessResult } from "./exec";
7
+ import type { OmpPaths } from "./ompPaths";
8
+
9
+ /**
10
+ * Run `omp args` pinned to the data root of `paths`, the root that the sync
11
+ * locked. omp adopts `$XDG_DATA_HOME/omp` as its data root once that folder
12
+ * exists, and another sync can create it after this sync took its locks.
13
+ * When the locked data root is the config root, the child gets no
14
+ * `XDG_DATA_HOME`, so its resolver keeps the config root. When the locked
15
+ * data root is the XDG root, the child gets the environment of this process.
16
+ */
17
+ export function spawnOmp(
18
+ paths: OmpPaths,
19
+ args: ReadonlyArray<string>,
20
+ stdio: AsyncProcessOptions["stdio"],
21
+ ): Promise<AsyncProcessResult> {
22
+ if (paths.dataRoot !== paths.configRoot) return spawnProcess("omp", args, { stdio });
23
+ const env = { ...process.env };
24
+ delete env["XDG_DATA_HOME"];
25
+ return spawnProcess("omp", args, { stdio, env });
26
+ }
@@ -4,9 +4,11 @@
4
4
  * OpenAI and OpenAI-Codex models; `none` omits `service_tier`. The SoT does not
5
5
  * declare `tier.openai`, so the additive sync merge keeps the toggled value.
6
6
  */
7
- import { chmodSync, existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
7
+ import { existsSync, readFileSync } from "node:fs";
8
8
  import { isMap, parseDocument } from "yaml";
9
9
 
10
+ import { replaceFile } from "./atomicWrite";
11
+
10
12
  export const FAST_ON_TIER = "priority";
11
13
  export const FAST_OFF_TIER = "none";
12
14
 
@@ -42,15 +44,20 @@ export function toggleOpenAiFast(configText: string): FastToggle {
42
44
  return { previous, next, text: doc.toString() };
43
45
  }
44
46
 
45
- /** Toggle `tier.openai` in the deployed config.yml with an atomic 0600 write. */
46
- export function toggleDeployedOpenAiFast(configPath: string): FastToggle {
47
+ /** Throw the error of the toggle when the deployed config.yml is missing. */
48
+ export function requireDeployedConfig(configPath: string): void {
47
49
  if (!existsSync(configPath)) {
48
50
  throw new Error(`${configPath} does not exist; run 'docks-kit sync omp' first`);
49
51
  }
52
+ }
53
+
54
+ /**
55
+ * Toggle `tier.openai` in the deployed config.yml with an atomic 0600 write.
56
+ * replaceFile writes through a symlinked config.yml, so the link stays.
57
+ */
58
+ export function toggleDeployedOpenAiFast(configPath: string): FastToggle {
59
+ requireDeployedConfig(configPath);
50
60
  const toggle = toggleOpenAiFast(readFileSync(configPath, "utf8"));
51
- const temporary = `${configPath}.tmp`;
52
- writeFileSync(temporary, toggle.text, { mode: 0o600 });
53
- chmodSync(temporary, 0o600);
54
- renameSync(temporary, configPath);
61
+ replaceFile(configPath, toggle.text, { mode: 0o600 });
55
62
  return toggle;
56
63
  }
@@ -36,7 +36,7 @@ function writePrivateFile(target: string, content: string): void {
36
36
  chmodSync(target, 0o600);
37
37
  }
38
38
 
39
- function backupPrivateFile(target: string): void {
39
+ export function backupPrivateFile(target: string): void {
40
40
  copyFileSync(target, `${target}.bak`);
41
41
  chmodSync(`${target}.bak`, 0o600);
42
42
  }
@@ -69,12 +69,17 @@ export function syncWholeFile(
69
69
  ctx.nextStepTriggers.ompRestart = true;
70
70
  }
71
71
 
72
+ /**
73
+ * Merges the SoT YAML into the deployed file. Returns true when this call wrote
74
+ * `<target>.bak`, so a later pass on the same file in this sync keeps that
75
+ * pre-sync backup instead of replacing it with the merged bytes.
76
+ */
72
77
  export function syncMergedYaml(
73
78
  ctx: Ctx,
74
79
  sourcePath: OmpTextPayloadPath,
75
80
  target: string,
76
81
  merge: (sotText: string, deployedText: string) => string,
77
- ): void {
82
+ ): boolean {
78
83
  const { change, echo, verbose } = ctx.services.logger;
79
84
  const source = payloadDisplayPath(sourcePath);
80
85
  const sotText = payloadText(sourcePath);
@@ -83,23 +88,23 @@ export function syncMergedYaml(
83
88
  if (!existsSync(target)) {
84
89
  if (ctx.dryRun) {
85
90
  echo(`[dry-run] cp ${source} -> ${target}`);
86
- return;
91
+ return false;
87
92
  }
88
93
  writePrivateFile(target, sotText);
89
94
  change(`omp ${name} installed`);
90
95
  ctx.nextStepTriggers.ompRestart = true;
91
- return;
96
+ return false;
92
97
  }
93
98
 
94
99
  const deployedText = readFileSync(target, "utf8");
95
100
  const merged = merge(sotText, deployedText);
96
101
  if (merged === deployedText) {
97
102
  verbose(`omp ${name} already in sync`);
98
- return;
103
+ return false;
99
104
  }
100
105
  if (ctx.dryRun) {
101
106
  echo(`[dry-run] merge ${source} -> ${target} (backup at ${target}.bak)`);
102
- return;
107
+ return false;
103
108
  }
104
109
 
105
110
  backupPrivateFile(target);
@@ -107,4 +112,5 @@ export function syncMergedYaml(
107
112
  replaceFile(target, merged, { mode: 0o600 });
108
113
  change(`omp ${name} merged (backup at ${name}.bak)`);
109
114
  ctx.nextStepTriggers.ompRestart = true;
115
+ return true;
110
116
  }
@@ -5,10 +5,12 @@
5
5
  */
6
6
  import { existsSync, readFileSync } from "node:fs";
7
7
 
8
- import { processFailureSummary, spawnProcess } from "./exec";
8
+ import { p, processFailureSummary } from "./exec";
9
9
  import { recordFailure } from "./failures";
10
10
  import type { Ctx } from "./index";
11
11
  import { isObject, parseJson } from "./jq";
12
+ import { spawnOmp } from "./ompChild";
13
+ import type { OmpPaths } from "./ompPaths";
12
14
 
13
15
  const MARKETPLACE_NAME = "docks";
14
16
  const MARKETPLACE_SOURCE = "https://github.com/DocksDocks/docks.git";
@@ -42,17 +44,16 @@ function registryHasDocks(registryFile: string): boolean {
42
44
  * the active registry lists docks, only the legacy registry lists it, or
43
45
  * neither does. In the middle state the kit never copies user data itself; it
44
46
  * takes the refresh path, whose own resolution inside omp performs that
45
- * adoption and leaves the active registry present.
47
+ * adoption and leaves the active registry present. `paths` are the omp paths
48
+ * that the sync locked.
46
49
  */
47
- export async function syncMarketplace(
48
- ctx: Ctx,
49
- registryFile: string,
50
- legacyRegistryFile?: string,
51
- ): Promise<void> {
50
+ export async function syncMarketplace(ctx: Ctx, paths: OmpPaths): Promise<void> {
52
51
  const { change, clearProgress, echo, progress, verbose } = ctx.services.logger;
53
- const registered = registryHasDocks(registryFile);
52
+ const registered = registryHasDocks(p(paths.dataRoot, "marketplaces.json"));
54
53
  const adoptable =
55
- !registered && legacyRegistryFile !== undefined && registryHasDocks(legacyRegistryFile);
54
+ !registered &&
55
+ paths.dataRoot !== paths.configRoot &&
56
+ registryHasDocks(p(paths.configRoot, "marketplaces.json"));
56
57
 
57
58
  // syncPlugins owns the single skip message for both missing CLIs, and it runs
58
59
  // right after this pass. Without omp no marketplace command can run at all,
@@ -77,9 +78,11 @@ export async function syncMarketplace(
77
78
 
78
79
  if (!registered && !adoptable) {
79
80
  progress("Registering omp docks marketplace...");
80
- const result = await spawnProcess("omp", ["plugin", "marketplace", "add", MARKETPLACE_SOURCE], {
81
- stdio: ["ignore", "pipe", "pipe"],
82
- });
81
+ const result = await spawnOmp(
82
+ paths,
83
+ ["plugin", "marketplace", "add", MARKETPLACE_SOURCE],
84
+ ["ignore", "pipe", "pipe"],
85
+ );
83
86
  clearProgress();
84
87
  if (result.error === undefined && result.exitCode === 0) {
85
88
  change("omp docks marketplace registered");
@@ -102,9 +105,11 @@ export async function syncMarketplace(
102
105
  // does that and fetches nothing, so it stays inside the flag's contract
103
106
  // while leaving the active registry present.
104
107
  progress("Adopting omp docks marketplace registry...");
105
- const listed = await spawnProcess("omp", ["plugin", "marketplace", "list"], {
106
- stdio: ["ignore", "ignore", "pipe"],
107
- });
108
+ const listed = await spawnOmp(
109
+ paths,
110
+ ["plugin", "marketplace", "list"],
111
+ ["ignore", "ignore", "pipe"],
112
+ );
108
113
  clearProgress();
109
114
  if (listed.error === undefined && listed.exitCode === 0) {
110
115
  change("omp docks marketplace registry adopted; refresh-only update skipped");
@@ -118,9 +123,11 @@ export async function syncMarketplace(
118
123
  }
119
124
 
120
125
  progress("Updating omp docks marketplace...");
121
- const result = await spawnProcess("omp", ["plugin", "marketplace", "update", MARKETPLACE_NAME], {
122
- stdio: ["ignore", "pipe", "pipe"],
123
- });
126
+ const result = await spawnOmp(
127
+ paths,
128
+ ["plugin", "marketplace", "update", MARKETPLACE_NAME],
129
+ ["ignore", "pipe", "pipe"],
130
+ );
124
131
  clearProgress();
125
132
  if (result.error === undefined && result.exitCode === 0) {
126
133
  verbose("omp docks marketplace refreshed");
@@ -15,12 +15,14 @@
15
15
  import { randomBytes } from "node:crypto";
16
16
  import { chmodSync, mkdirSync, readdirSync, realpathSync, unlinkSync } from "node:fs";
17
17
 
18
- import { replaceFile } from "./atomicWrite";
19
- import { p, processFailureSummary, spawnProcess } from "./exec";
18
+ import { removeStaleTemporaries, replaceFile } from "./atomicWrite";
19
+ import { p, processFailureSummary } from "./exec";
20
20
  import { recordFailure } from "./failures";
21
21
  import type { Ctx } from "./index";
22
22
  import { isObject, parseJson } from "./jq";
23
+ import { spawnOmp } from "./ompChild";
23
24
  import { KIT_PLUGIN_NAME, kitPluginDir } from "./ompKitPlugin";
25
+ import type { OmpPaths } from "./ompPaths";
24
26
  import { kitCacheDir } from "./scratch";
25
27
  import { field } from "./toolchain";
26
28
 
@@ -85,10 +87,8 @@ function marketplaceEntryVersion(entries: unknown): string | undefined {
85
87
  return undefined;
86
88
  }
87
89
 
88
- async function installedPluginIdsFromCli(): Promise<InstalledPlugins | undefined> {
89
- const result = await spawnProcess("omp", ["plugin", "list", "--json"], {
90
- stdio: ["ignore", "pipe", "ignore"],
91
- });
90
+ async function installedPluginIdsFromCli(paths: OmpPaths): Promise<InstalledPlugins | undefined> {
91
+ const result = await spawnOmp(paths, ["plugin", "list", "--json"], ["ignore", "pipe", "ignore"]);
92
92
  if (result.error !== undefined || result.exitCode !== 0) return undefined;
93
93
 
94
94
  const value = parseJson(result.stdout);
@@ -145,12 +145,13 @@ function describeOperation(
145
145
 
146
146
  async function runPluginCommand(
147
147
  ctx: Ctx,
148
+ paths: OmpPaths,
148
149
  plugin: string,
149
150
  args: ReadonlyArray<string>,
150
151
  ): Promise<boolean> {
151
152
  const { clearProgress, progress } = ctx.services.logger;
152
153
  progress(`Updating omp plugin ${plugin}...`);
153
- const result = await spawnProcess("omp", args, { stdio: ["ignore", "pipe", "pipe"] });
154
+ const result = await spawnOmp(paths, args, ["ignore", "pipe", "pipe"]);
154
155
  clearProgress();
155
156
  if (result.error === undefined && result.exitCode === 0) return true;
156
157
 
@@ -194,8 +195,15 @@ function versionChanges(
194
195
  return upgrades;
195
196
  }
196
197
 
197
- /** Removes the oldest event files beyond the newest UPGRADE_EVENTS_KEPT. */
198
+ /**
199
+ * Removes the oldest event files beyond the newest UPGRADE_EVENTS_KEPT, and
200
+ * the temporary files that killed event writes left.
201
+ */
198
202
  function pruneUpgradeLog(dir: string): void {
203
+ removeStaleTemporaries(
204
+ dir,
205
+ (target) => target.kind === "name" && UPGRADE_EVENT_FILE.test(target.name),
206
+ );
199
207
  const events = readdirSync(dir).flatMap((name) => {
200
208
  const match = UPGRADE_EVENT_FILE.exec(name);
201
209
  return match === null ? [] : [{ name, finishedAt: Number(match[1]) }];
@@ -250,7 +258,8 @@ function recordUpgrades(home: string, upgrades: ReadonlyArray<PluginUpgrade>): s
250
258
  return undefined;
251
259
  }
252
260
 
253
- export async function syncPlugins(ctx: Ctx): Promise<number> {
261
+ /** Run the plugin pass. `paths` are the omp paths that the sync locked. */
262
+ export async function syncPlugins(ctx: Ctx, paths: OmpPaths): Promise<number> {
254
263
  const { change, clearProgress, echo, progress, verbose, warn } = ctx.services.logger;
255
264
 
256
265
  if (ctx.services.deps.probe("omp").state === "missing") {
@@ -289,7 +298,7 @@ export async function syncPlugins(ctx: Ctx): Promise<number> {
289
298
  const piIntercomPin = field("pi-intercom", "verified");
290
299
 
291
300
  progress("Checking installed omp plugins...");
292
- const installed = await installedPluginIdsFromCli();
301
+ const installed = await installedPluginIdsFromCli(paths);
293
302
  clearProgress();
294
303
  if (installed === undefined) {
295
304
  warn("omp plugin inventory unavailable — falling back to the full refresh path");
@@ -313,7 +322,7 @@ export async function syncPlugins(ctx: Ctx): Promise<number> {
313
322
  const args = present
314
323
  ? ["plugin", "upgrade", "--scope", "user", pluginId]
315
324
  : ["plugin", "install", "--scope", "user", pluginId];
316
- const succeeded = await runPluginCommand(ctx, pluginId, args);
325
+ const succeeded = await runPluginCommand(ctx, paths, pluginId, args);
317
326
  // The operation boundary: an omp process that started later loaded the new folder.
318
327
  const finishedAt = Date.now();
319
328
  if (succeeded) {
@@ -341,7 +350,7 @@ export async function syncPlugins(ctx: Ctx): Promise<number> {
341
350
  const args = present
342
351
  ? ["install", "--force", `pi-intercom@${piIntercomPin}`]
343
352
  : ["install", `pi-intercom@${piIntercomPin}`];
344
- if (await runPluginCommand(ctx, "pi-intercom", args)) {
353
+ if (await runPluginCommand(ctx, paths, "pi-intercom", args)) {
345
354
  operations.push({
346
355
  kind: "npm",
347
356
  id: "pi-intercom",
@@ -360,7 +369,7 @@ export async function syncPlugins(ctx: Ctx): Promise<number> {
360
369
  const linkedTarget = kitPluginPath === undefined ? undefined : realPath(kitPluginPath);
361
370
  if (linkedTarget !== undefined && linkedTarget === realPath(kitDir)) {
362
371
  verbose(`omp kit plugin ${KIT_PLUGIN_NAME} already linked`);
363
- } else if (await runPluginCommand(ctx, KIT_PLUGIN_NAME, ["plugin", "link", kitDir])) {
372
+ } else if (await runPluginCommand(ctx, paths, KIT_PLUGIN_NAME, ["plugin", "link", kitDir])) {
364
373
  operations.push({ kind: "link", id: KIT_PLUGIN_NAME });
365
374
  if (installed?.npm.has(KIT_PLUGIN_NAME) !== true) pluginsInstalled++;
366
375
  }
@@ -368,7 +377,7 @@ export async function syncPlugins(ctx: Ctx): Promise<number> {
368
377
  if (operations.length > 0) {
369
378
  // A second inventory read gives the versions that the operations left.
370
379
  progress("Reading omp plugin versions...");
371
- const after = await installedPluginIdsFromCli();
380
+ const after = await installedPluginIdsFromCli(paths);
372
381
  clearProgress();
373
382
  const items = operations.map((operation) => describeOperation(operation, after));
374
383
  change(`omp plugins synced: ${items.join(", ")}`);
@@ -9,10 +9,12 @@
9
9
  * sync, without `--reconcile`. Message strings and prune semantics are part of
10
10
  * the contract.
11
11
  */
12
- import { existsSync, readFileSync, writeFileSync } from "node:fs";
12
+ import { existsSync, readFileSync } from "node:fs";
13
13
  import { isDeepStrictEqual } from "node:util";
14
14
  import { isMap, isScalar, isSeq, parseDocument, type YAMLMap } from "yaml";
15
+ import { replaceFile } from "./atomicWrite";
15
16
  import type { Ctx } from "./index";
17
+ import { backupPrivateFile } from "./ompFileDeploy";
16
18
  import { bashPatternKey, bashRuleKey } from "./ompYaml";
17
19
 
18
20
  type RetiredScalar = string | number | boolean;
@@ -296,12 +298,17 @@ const retiredBashRules: Pruner = (root) => {
296
298
  return pruned;
297
299
  };
298
300
 
299
- /** Applies each pruner to one deployed omp YAML file. */
301
+ /**
302
+ * Applies each pruner to one deployed omp YAML file. `alreadyBackedUp` is true
303
+ * when the merge of this sync already wrote `<file>.bak`; a second backup would
304
+ * replace those pre-sync bytes with the merged bytes.
305
+ */
300
306
  function pruneRetired(
301
307
  ctx: Ctx,
302
308
  file: string,
303
309
  label: string,
304
310
  pruners: ReadonlyArray<Pruner>,
311
+ alreadyBackedUp: boolean,
305
312
  ): number {
306
313
  const { change, echo, verbose, warn } = ctx.services.logger;
307
314
  if (!existsSync(file)) return 0;
@@ -325,33 +332,54 @@ function pruneRetired(
325
332
  echo(`[dry-run] prune ${file}: ${pruned.join(", ")}`);
326
333
  return pruned.length;
327
334
  }
328
- writeFileSync(file, String(doc));
329
- change(`omp ${label} pruned ${pruned.length} retired entr(ies): ${pruned.join(", ")}`);
335
+ if (!alreadyBackedUp) backupPrivateFile(file);
336
+ // replaceFile writes through a symlinked file, so the link stays.
337
+ replaceFile(file, String(doc), { mode: 0o600 });
338
+ const backupNote = alreadyBackedUp ? "" : ` (backup at ${label}.bak)`;
339
+ change(
340
+ `omp ${label} pruned ${pruned.length} retired entr(ies): ${pruned.join(", ")}${backupNote}`,
341
+ );
330
342
  return pruned.length;
331
343
  }
332
344
 
333
345
  /** Prunes retired kit-owned keys and bash rules from a deployed omp config.yml. */
334
- export function syncOmpRemovals(ctx: Ctx, configFile: string): number {
335
- return pruneRetired(ctx, configFile, "config.yml", [
336
- retiredKeys([
337
- ...OMP_RETIRED_VALUES.map(([path, value]): RetiredEntry => [
338
- path,
339
- (node) => isScalar(node) && node.value === value,
346
+ export function syncOmpRemovals(ctx: Ctx, configFile: string, alreadyBackedUp: boolean): number {
347
+ return pruneRetired(
348
+ ctx,
349
+ configFile,
350
+ "config.yml",
351
+ [
352
+ retiredKeys([
353
+ ...OMP_RETIRED_VALUES.map(([path, value]): RetiredEntry => [
354
+ path,
355
+ (node) => isScalar(node) && node.value === value,
356
+ ]),
357
+ ...OMP_RETIRED_KEYS.map((path): RetiredEntry => [path, () => true]),
340
358
  ]),
341
- ...OMP_RETIRED_KEYS.map((path): RetiredEntry => [path, () => true]),
342
- ]),
343
- retiredBashRules,
344
- ]);
359
+ retiredBashRules,
360
+ ],
361
+ alreadyBackedUp,
362
+ );
345
363
  }
346
364
 
347
365
  /** Prunes retired kit-owned blocks from a deployed omp models.yml. */
348
- export function syncOmpModelRemovals(ctx: Ctx, modelsFile: string): number {
349
- return pruneRetired(ctx, modelsFile, "models.yml", [
350
- retiredKeys(
351
- OMP_RETIRED_MODEL_BLOCKS.map(([path, block]): RetiredEntry => [
352
- path,
353
- (node) => isMap(node) && isDeepStrictEqual(node.toJSON(), block),
354
- ]),
355
- ),
356
- ]);
366
+ export function syncOmpModelRemovals(
367
+ ctx: Ctx,
368
+ modelsFile: string,
369
+ alreadyBackedUp: boolean,
370
+ ): number {
371
+ return pruneRetired(
372
+ ctx,
373
+ modelsFile,
374
+ "models.yml",
375
+ [
376
+ retiredKeys(
377
+ OMP_RETIRED_MODEL_BLOCKS.map(([path, block]): RetiredEntry => [
378
+ path,
379
+ (node) => isMap(node) && isDeepStrictEqual(node.toJSON(), block),
380
+ ]),
381
+ ),
382
+ ],
383
+ alreadyBackedUp,
384
+ );
357
385
  }