docks-kit 0.20.6 → 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 +18 -16
  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 +43 -19
  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 +37 -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
@@ -4,12 +4,15 @@
4
4
  * from existing installations without `--reconcile`. Message strings and
5
5
  * prune semantics are part of the contract.
6
6
  */
7
- import { existsSync, readFileSync, renameSync, rmdirSync, rmSync, writeFileSync } from "node:fs";
7
+ import { createHash } from "node:crypto";
8
+ import { copyFileSync, existsSync, readFileSync, renameSync, rmdirSync, rmSync } from "node:fs";
9
+ import { replaceFile } from "./atomicWrite";
8
10
  import type { ClaudeRuntimeState } from "./claudeSync";
9
11
  import { RETIRED_PERMISSION_RULES } from "./claudeRetired";
10
12
  import { p } from "./exec";
11
13
  import type { Ctx } from "./index";
12
14
  import { isObject, jqStringify, parseJson, type Json } from "./jq";
15
+ import { lstat } from "./skillsLinks";
13
16
 
14
17
  const REMOVED_MANIFEST = {
15
18
  hooks: ["disable-claudeai-connectors.sh"],
@@ -25,7 +28,6 @@ const REMOVED_MANIFEST = {
25
28
  "env.CLAUDE_CODE_EFFORT_LEVEL",
26
29
  "enabledPlugins.effect-kit@docks",
27
30
  "enabledPlugins.session-relay@docks",
28
- "hooks.PreToolUse",
29
31
  ],
30
32
  permissionRules: {
31
33
  allow: ["Write(./)", "Bash(rtk *)", ...RETIRED_PERMISSION_RULES.allow],
@@ -43,12 +45,123 @@ const REMOVED_MANIFEST = {
43
45
  runtimeReady: {
44
46
  hooks: ["notify.sh"],
45
47
  files: ["statusline.sh", "fetch-usage.sh"],
46
- settingsKeys: ["hooks.Stop"],
47
48
  },
48
49
  };
49
50
 
50
- /** claude::_prune_json_keys — present-count; deletes when !dryRun. */
51
- function pruneJsonKeys(ctx: Ctx, file: string, keys: Array<string>): number {
51
+ /**
52
+ * Hook handler commands that the kit shipped in SoT/.claude/settings.json and
53
+ * then retired. The pass removes only these handlers, so user handlers on the
54
+ * same events stay. The Stop pass runs only after the Bun runtime cutover.
55
+ */
56
+ const RETIRED_HOOK_COMMANDS = {
57
+ PreToolUse: ["$HOME/.claude/hooks/rtk-rewrite.sh", "rtk hook claude"],
58
+ Stop: [
59
+ "bash $HOME/.claude/fetch-usage.sh",
60
+ "ffplay -nodisp -autoexit ~/.claude/alert_bubble.mp3",
61
+ "ffplay -nodisp -autoexit https://raw.githubusercontent.com/DocksDocks/public/main/alert_bubble.mp3",
62
+ ],
63
+ } as const;
64
+
65
+ type RetiredHookEvent = keyof typeof RETIRED_HOOK_COMMANDS;
66
+
67
+ /**
68
+ * SHA-256 of every version of the runtime-ready artifacts that the kit
69
+ * shipped, keyed by the path under ~/.claude. A copy with another hash is the
70
+ * user's file, so the prune keeps it as `<path>.bak`.
71
+ */
72
+ const LEGACY_ARTIFACT_HASHES: Readonly<Record<string, ReadonlyArray<string>>> = {
73
+ "statusline.sh": [
74
+ "292df944d7f28bacde854105891a270fbbe1a114172d0000d8d2c4366097c18d",
75
+ "3a3ec8911c3916a1ba1fdf8ac5a8c4d8231ecc7dcd1f7355c7787603b9734efe",
76
+ "8189f5fb83dfbbf864737a4613062912c0120659f01f56f61b0a3ed7ed69949c",
77
+ "8dd0d6db2fcb9cec042756f9d14e09ee0214041b9d85fa5e26b8c99a06b65cd9",
78
+ "b97abaf97874c7bc0b6052eb8f14f73bccff20c3b79f7d6b2ff79137daef360d",
79
+ "baec096cbcf70245613a9ea10fe7cbdb50b16d02106b3cb6a0861a783b2de97c",
80
+ "c7233f4006f603ee5431d02daf896a58167d20461171f9a1a329f8127ced4835",
81
+ ],
82
+ "fetch-usage.sh": [
83
+ "304f5a17d9c4356ed7f3eedf7f38766b8e8e7fce91a80a6efbad0b8a6b43654d",
84
+ "35531c6941d2e203f385baf6db9a9a17f57471ceadf91c6ee252b2f1aee0b456",
85
+ "9b8fcac8bc3a45d505c58ca48013f4949a3a3d1cf5064872871286c2a81196f9",
86
+ "ceaa5b5241edf639ca873439e1f1013b7e0d902a23d2bf831317e064a3ccab46",
87
+ ],
88
+ "hooks/notify.sh": [
89
+ "2beb02119bd9bad3045341e12022fb7234b53b02c08908e4a9949968980f6e69",
90
+ "90261530799aaf978949572521d2a73105a4104a47c86132a3815c26f0078216",
91
+ ],
92
+ };
93
+
94
+ /** What retireArtifact did with one path. `suffix` names the backup, such as `.bak.1`. */
95
+ type ArtifactRetirement =
96
+ | { readonly kind: "absent" }
97
+ | { readonly kind: "removed" }
98
+ | { readonly kind: "preserved"; readonly suffix: string };
99
+
100
+ /**
101
+ * The first unoccupied backup suffix for `path`: `.bak`, then `.bak.1`,
102
+ * `.bak.2`, and so on. The check uses lstat, so a dangling symlink occupies
103
+ * its name.
104
+ */
105
+ function freeBackupSuffix(path: string): string {
106
+ let suffix = ".bak";
107
+ for (let n = 1; lstat(`${path}${suffix}`) !== undefined; n++) suffix = `.bak.${n}`;
108
+ return suffix;
109
+ }
110
+
111
+ /**
112
+ * Retire one artifact. A path in LEGACY_ARTIFACT_HASHES is removed only when
113
+ * its content matches a shipped version. Other content moves to the first
114
+ * unoccupied backup name, so an earlier backup stays. A path without hashes
115
+ * has a kit-only name and is removed. The presence check uses lstat, so a
116
+ * dangling symlink is removed too.
117
+ */
118
+ function retireArtifact(
119
+ ctx: Ctx,
120
+ path: string,
121
+ shipped: ReadonlyArray<string> | undefined,
122
+ ): ArtifactRetirement {
123
+ const stats = lstat(path);
124
+ if (stats === undefined) return { kind: "absent" };
125
+ const owned =
126
+ shipped === undefined ||
127
+ (stats.isFile() &&
128
+ shipped.includes(createHash("sha256").update(readFileSync(path)).digest("hex")));
129
+ if (owned) {
130
+ if (ctx.dryRun) ctx.services.logger.echo(`[dry-run] rm ${path}`);
131
+ else rmSync(path, { force: true });
132
+ return { kind: "removed" };
133
+ }
134
+ const suffix = freeBackupSuffix(path);
135
+ if (ctx.dryRun) ctx.services.logger.echo(`[dry-run] mv ${path} ${path}${suffix}`);
136
+ else renameSync(path, `${path}${suffix}`);
137
+ return { kind: "preserved", suffix };
138
+ }
139
+
140
+ /**
141
+ * Copy settings.json to settings.json.bak once per sync, just before the
142
+ * first write of the removals pass. When an earlier pass of the same sync
143
+ * already wrote the backup, the copy never runs, so that backup keeps the
144
+ * original bytes.
145
+ */
146
+ function settingsBackup(file: string, alreadyBackedUp: boolean): () => void {
147
+ let done = alreadyBackedUp;
148
+ return () => {
149
+ if (done) return;
150
+ copyFileSync(file, `${file}.bak`);
151
+ done = true;
152
+ };
153
+ }
154
+
155
+ /**
156
+ * claude::_prune_json_keys — present-count; deletes when !dryRun. The pass
157
+ * calls `beforeWrite` just before it writes the file.
158
+ */
159
+ function pruneJsonKeys(
160
+ ctx: Ctx,
161
+ file: string,
162
+ keys: Array<string>,
163
+ beforeWrite: () => void,
164
+ ): number {
52
165
  if (keys.length === 0 || !existsSync(file)) return 0;
53
166
  const doc = parseJson(readFileSync(file, "utf8"));
54
167
  if (doc === undefined) return 0;
@@ -74,8 +187,8 @@ function pruneJsonKeys(ctx: Ctx, file: string, keys: Array<string>): number {
74
187
  }
75
188
  if (isObject(cur)) delete cur[path[path.length - 1]!];
76
189
  }
77
- writeFileSync(`${file}.tmp`, jqStringify(doc));
78
- renameSync(`${file}.tmp`, file);
190
+ beforeWrite();
191
+ replaceFile(file, jqStringify(doc));
79
192
  }
80
193
  return presentKeys.length;
81
194
  }
@@ -84,6 +197,7 @@ function prunePermissionRules(
84
197
  ctx: Ctx,
85
198
  file: string,
86
199
  rules: Readonly<Record<"allow" | "deny" | "ask", ReadonlyArray<string>>>,
200
+ beforeWrite: () => void,
87
201
  ): number {
88
202
  if (!existsSync(file)) return 0;
89
203
  const doc = parseJson(readFileSync(file, "utf8"));
@@ -99,40 +213,98 @@ function prunePermissionRules(
99
213
  permissions[key] = values.filter((value) => typeof value !== "string" || !removed.has(value));
100
214
  }
101
215
  if (present > 0 && !ctx.dryRun) {
102
- writeFileSync(`${file}.tmp`, jqStringify(doc));
103
- renameSync(`${file}.tmp`, file);
216
+ beforeWrite();
217
+ replaceFile(file, jqStringify(doc));
104
218
  }
105
219
  return present;
106
220
  }
107
221
 
108
- export function syncRemovals(ctx: Ctx, claudeDir: string, runtime: ClaudeRuntimeState): void {
222
+ /**
223
+ * Remove the retired kit handlers from the named hook events. A group that
224
+ * loses all its handlers is dropped, and an event with no groups left is
225
+ * dropped. A null or non-array event value is dropped too. The pass calls
226
+ * `beforeWrite` just before it writes the file. Returns the count of removed
227
+ * entries.
228
+ */
229
+ function pruneRetiredHookHandlers(
230
+ ctx: Ctx,
231
+ file: string,
232
+ events: ReadonlyArray<RetiredHookEvent>,
233
+ beforeWrite: () => void,
234
+ ): number {
235
+ if (!existsSync(file)) return 0;
236
+ const doc = parseJson(readFileSync(file, "utf8"));
237
+ if (doc === undefined || !isObject(doc) || !isObject(doc["hooks"])) return 0;
238
+ const hooks = doc["hooks"];
239
+ let removed = 0;
240
+ for (const event of events) {
241
+ const groups = hooks[event];
242
+ if (groups === undefined) continue;
243
+ if (!Array.isArray(groups)) {
244
+ delete hooks[event];
245
+ removed++;
246
+ continue;
247
+ }
248
+ const retired: ReadonlyArray<string> = RETIRED_HOOK_COMMANDS[event];
249
+ let removedFromEvent = 0;
250
+ const kept: Array<Json> = [];
251
+ for (const group of groups) {
252
+ if (!isObject(group) || !Array.isArray(group["hooks"])) {
253
+ kept.push(group);
254
+ continue;
255
+ }
256
+ const handlers = group["hooks"].filter(
257
+ (handler) =>
258
+ !isObject(handler) ||
259
+ handler["type"] !== "command" ||
260
+ typeof handler["command"] !== "string" ||
261
+ !retired.includes(handler["command"]),
262
+ );
263
+ const count = group["hooks"].length - handlers.length;
264
+ removedFromEvent += count;
265
+ if (count === 0) kept.push(group);
266
+ else if (handlers.length > 0) kept.push({ ...group, hooks: handlers });
267
+ }
268
+ if (removedFromEvent === 0) continue;
269
+ removed += removedFromEvent;
270
+ if (kept.length > 0) hooks[event] = kept;
271
+ else delete hooks[event];
272
+ }
273
+ if (removed > 0 && !ctx.dryRun) {
274
+ beforeWrite();
275
+ replaceFile(file, jqStringify(doc));
276
+ }
277
+ return removed;
278
+ }
279
+
280
+ /**
281
+ * Prune retired artifacts, settings keys, permission rules, and hook handlers.
282
+ * `settingsBackedUp` is true when an earlier pass of this sync already copied
283
+ * settings.json to settings.json.bak. The pass then keeps that backup.
284
+ */
285
+ export function syncRemovals(
286
+ ctx: Ctx,
287
+ claudeDir: string,
288
+ runtime: ClaudeRuntimeState,
289
+ settingsBackedUp: boolean,
290
+ ): void {
109
291
  const { change, echo } = ctx.services.logger;
292
+ const ready = runtime.kind === "ready";
110
293
  let hooksRemoved = 0;
111
294
  let filesRemoved = 0;
112
- const hooks = [
113
- ...REMOVED_MANIFEST.hooks,
114
- ...(runtime.kind === "ready" ? REMOVED_MANIFEST.runtimeReady.hooks : []),
115
- ];
116
- const files = [
117
- ...REMOVED_MANIFEST.files,
118
- ...(runtime.kind === "ready" ? REMOVED_MANIFEST.runtimeReady.files : []),
119
- ];
120
- const settingsKeys = [
121
- ...REMOVED_MANIFEST.settingsKeys.filter(
122
- (key) => key !== "advisorModel" || ctx.claudeAdvisor === "",
123
- ),
124
- ...(runtime.kind === "ready" ? REMOVED_MANIFEST.runtimeReady.settingsKeys : []),
125
- ];
295
+ const preserved: Array<string> = [];
296
+ const hooks = [...REMOVED_MANIFEST.hooks, ...(ready ? REMOVED_MANIFEST.runtimeReady.hooks : [])];
297
+ const files = [...REMOVED_MANIFEST.files, ...(ready ? REMOVED_MANIFEST.runtimeReady.files : [])];
298
+ const settingsKeys = REMOVED_MANIFEST.settingsKeys.filter(
299
+ (key) => key !== "advisorModel" || ctx.claudeAdvisor === "",
300
+ );
301
+ const hookEvents: Array<RetiredHookEvent> = ready ? ["PreToolUse", "Stop"] : ["PreToolUse"];
126
302
 
127
303
  for (const name of hooks) {
128
- const path = p(claudeDir, "hooks", name);
129
- if (!existsSync(path)) continue;
130
- if (ctx.dryRun) {
131
- echo(`[dry-run] rm ${path}`);
132
- } else {
133
- rmSync(path, { force: true });
134
- hooksRemoved++;
135
- }
304
+ const label = `hooks/${name}`;
305
+ const result = retireArtifact(ctx, p(claudeDir, "hooks", name), LEGACY_ARTIFACT_HASHES[label]);
306
+ if (result.kind === "removed") hooksRemoved++;
307
+ else if (result.kind === "preserved") preserved.push(`${label}${result.suffix}`);
136
308
  }
137
309
  if (!ctx.dryRun && hooksRemoved > 0) {
138
310
  try {
@@ -142,35 +314,40 @@ export function syncRemovals(ctx: Ctx, claudeDir: string, runtime: ClaudeRuntime
142
314
  }
143
315
  }
144
316
 
145
- for (const rel of files) {
146
- const path = p(claudeDir, rel);
147
- if (!existsSync(path)) continue;
148
- if (ctx.dryRun) {
149
- echo(`[dry-run] rm ${path}`);
150
- } else {
151
- rmSync(path, { force: true });
152
- filesRemoved++;
153
- }
154
- }
155
-
156
- for (const rel of REMOVED_MANIFEST.homeFiles) {
157
- const path = p(ctx.home, rel);
158
- if (!existsSync(path)) continue;
159
- if (ctx.dryRun) {
160
- echo(`[dry-run] rm ${path}`);
161
- } else {
162
- rmSync(path, { force: true });
163
- filesRemoved++;
164
- }
317
+ const filePaths = [
318
+ ...files.map((rel) => ({
319
+ path: p(claudeDir, rel),
320
+ label: rel,
321
+ shipped: LEGACY_ARTIFACT_HASHES[rel],
322
+ })),
323
+ ...REMOVED_MANIFEST.homeFiles.map((rel) => ({
324
+ path: p(ctx.home, rel),
325
+ label: `~/${rel}`,
326
+ shipped: undefined,
327
+ })),
328
+ ];
329
+ for (const { path, label, shipped } of filePaths) {
330
+ const result = retireArtifact(ctx, path, shipped);
331
+ if (result.kind === "removed") filesRemoved++;
332
+ else if (result.kind === "preserved") preserved.push(`${label}${result.suffix}`);
165
333
  }
166
334
 
167
- const skeys = pruneJsonKeys(ctx, p(claudeDir, "settings.json"), settingsKeys);
335
+ const settingsPath = p(claudeDir, "settings.json");
336
+ const backup = settingsBackup(settingsPath, settingsBackedUp);
337
+ const skeys = pruneJsonKeys(ctx, settingsPath, settingsKeys, backup);
168
338
  const permissionRules = prunePermissionRules(
169
339
  ctx,
170
- p(claudeDir, "settings.json"),
340
+ settingsPath,
171
341
  REMOVED_MANIFEST.permissionRules,
342
+ backup,
343
+ );
344
+ const hookHandlers = pruneRetiredHookHandlers(ctx, settingsPath, hookEvents, backup);
345
+ const cjkeys = pruneJsonKeys(
346
+ ctx,
347
+ p(ctx.home, ".claude.json"),
348
+ REMOVED_MANIFEST.claudeJsonKeys,
349
+ () => {},
172
350
  );
173
- const cjkeys = pruneJsonKeys(ctx, p(ctx.home, ".claude.json"), REMOVED_MANIFEST.claudeJsonKeys);
174
351
 
175
352
  if (ctx.dryRun) {
176
353
  if (skeys > 0)
@@ -180,15 +357,26 @@ export function syncRemovals(ctx: Ctx, claudeDir: string, runtime: ClaudeRuntime
180
357
  `[dry-run] del ${permissionRules} stale permission rule(s) from ${p(claudeDir, "settings.json")}`,
181
358
  );
182
359
  }
360
+ if (hookHandlers > 0) {
361
+ echo(
362
+ `[dry-run] del ${hookHandlers} retired hook handler(s) from ${p(claudeDir, "settings.json")}`,
363
+ );
364
+ }
183
365
  if (cjkeys > 0)
184
366
  echo(`[dry-run] del ${cjkeys} stale key(s) from ${p(ctx.home, ".claude.json")}`);
185
367
  return;
186
368
  }
187
369
 
188
- if (hooksRemoved + filesRemoved + skeys + permissionRules + cjkeys > 0) {
370
+ const artifacts = hooksRemoved + filesRemoved + preserved.length;
371
+ if (artifacts + skeys + permissionRules + hookHandlers + cjkeys > 0) {
189
372
  const permissionSummary = permissionRules > 0 ? `, permission rules: ${permissionRules}` : "";
373
+ const handlerSummary = hookHandlers > 0 ? `, retired hook handlers: ${hookHandlers}` : "";
374
+ const preservedSummary =
375
+ preserved.length > 0
376
+ ? `, preserved as backup: ${preserved.length} (${preserved.join(", ")})`
377
+ : "";
190
378
  change(
191
- `Pruned stale artifacts (hooks: ${hooksRemoved}, files: ${filesRemoved}, settings keys: ${skeys}, claude.json keys: ${cjkeys}${permissionSummary})`,
379
+ `Pruned stale artifacts (hooks: ${hooksRemoved}, files: ${filesRemoved}, settings keys: ${skeys}, claude.json keys: ${cjkeys}${permissionSummary}${handlerSummary}${preservedSummary})`,
192
380
  );
193
381
  ctx.nextStepTriggers.claudeRestart = true;
194
382
  }
@@ -2,7 +2,7 @@
2
2
  *
3
3
  * `mergeSettings` unions the deployed arrays with the SoT arrays, so dropping a
4
4
  * rule from `SoT/.claude/settings.json` never removes it from a file an earlier
5
- * sync already wrote. `claudeSync.ts syncRemovals` force-prunes this exact-string
5
+ * sync already wrote. `claudeRemovals.ts syncRemovals` force-prunes this exact-string
6
6
  * inventory on every host so the retirement reaches existing installations
7
7
  * without `--reconcile`.
8
8
  *
@@ -3,13 +3,15 @@
3
3
  * with the runtime cutover and deploy-time modifiers is load-bearing and
4
4
  * golden-tested; message strings and JSON semantics are part of the contract.
5
5
  */
6
- import { copyFileSync, existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
6
+ import { copyFileSync, existsSync, readFileSync } from "node:fs";
7
+ import { replaceFile } from "./atomicWrite";
7
8
  import { p } from "./exec";
8
9
  import type { Ctx } from "./index";
9
10
  import { isObject, jqStringify, parseJson, type Json } from "./jq";
10
11
  import { ExitError } from "./parseArgs";
11
12
  import { mergeSettings, reconcileSettings } from "./settings";
12
13
  import { payloadDisplayPath } from "../payload";
14
+ import type { JsonObject } from "./sharedTypes";
13
15
 
14
16
  export interface PreparedClaudeSettings {
15
17
  readonly path: string;
@@ -23,6 +25,33 @@ function assertMaterializedSettings(bytes: string): void {
23
25
  throw new Error("Claude settings contain unresolved runtime sentinels");
24
26
  }
25
27
 
28
+ /**
29
+ * Read the deployed settings document. An unparsable or non-object document
30
+ * aborts the sync, because a merge would replace the user's settings.
31
+ */
32
+ function readDeployedSettings(ctx: Ctx, path: string): { text: string; doc: JsonObject } {
33
+ const text = readFileSync(path, "utf8");
34
+ const doc = parseJson(text);
35
+ if (doc === undefined || !isObject(doc)) {
36
+ const reason = doc === undefined ? "is not valid JSON" : "must contain a JSON object";
37
+ ctx.services.logger.err(
38
+ `Aborting sync: ${path} ${reason}. Fix it manually or delete it to reinstall.`,
39
+ );
40
+ throw new ExitError(1);
41
+ }
42
+ return { text, doc };
43
+ }
44
+
45
+ /**
46
+ * Check the deployed settings before any sync pipeline starts. A document
47
+ * that cannot merge stops the whole sync, so no other harness changes first.
48
+ */
49
+ export function preflightClaudeSettings(ctx: Ctx): void {
50
+ if (!ctx.syncClaude) return;
51
+ const path = p(ctx.home, ".claude", "settings.json");
52
+ if (existsSync(path)) readDeployedSettings(ctx, path);
53
+ }
54
+
26
55
  /** Build the candidate settings bytes before the readiness-gated runtime cutover mutates disk. */
27
56
  export function prepareClaudeSettings(
28
57
  ctx: Ctx,
@@ -31,37 +60,35 @@ export function prepareClaudeSettings(
31
60
  ): PreparedClaudeSettings {
32
61
  const path = p(claudeDir, "settings.json");
33
62
  if (!existsSync(path)) {
34
- const bytes = jqStringify(repo);
63
+ // Write the form the next sync produces, so a second sync finds no change.
64
+ const canonical = ctx.reconcile ? reconcileSettings(repo, {}) : mergeSettings(repo, {});
65
+ const bytes = jqStringify(canonical);
35
66
  assertMaterializedSettings(bytes);
36
67
  return { path, bytes, previousBytes: undefined, changed: true };
37
68
  }
38
69
 
39
- const previousBytes = readFileSync(path, "utf8");
40
- const user = parseJson(previousBytes);
41
- if (user === undefined || !isObject(user)) {
42
- const reason = user === undefined ? "is not valid JSON" : "must contain a JSON object";
43
- ctx.services.logger.err(
44
- `Aborting sync: ${path} ${reason}. Fix it manually or delete it to reinstall.`,
45
- );
46
- throw new ExitError(1);
47
- }
70
+ // engineSync runs this check in preflightClaudeSettings; it stays here for other callers.
71
+ const { text: previousBytes, doc: user } = readDeployedSettings(ctx, path);
48
72
  const merged = ctx.reconcile ? reconcileSettings(repo, user) : mergeSettings(repo, user);
49
73
  const bytes = jqStringify(merged);
50
74
  assertMaterializedSettings(bytes);
51
75
  return { path, bytes, previousBytes, changed: bytes !== previousBytes };
52
76
  }
53
77
 
54
- /** Commit a fully prepared document; callers must finish runtime preparation first. */
55
- export function commitClaudeSettings(ctx: Ctx, prepared: PreparedClaudeSettings): void {
78
+ /**
79
+ * Commit a fully prepared document; callers must finish runtime preparation first.
80
+ * Returns true when the commit copied the previous settings to settings.json.bak.
81
+ */
82
+ export function commitClaudeSettings(ctx: Ctx, prepared: PreparedClaudeSettings): boolean {
56
83
  const { change, verbose } = ctx.services.logger;
57
84
  if (!prepared.changed) {
58
85
  verbose("Settings already in sync");
59
- return;
86
+ return false;
60
87
  }
61
88
 
62
- if (prepared.previousBytes !== undefined) copyFileSync(prepared.path, `${prepared.path}.bak`);
63
- writeFileSync(`${prepared.path}.tmp`, prepared.bytes);
64
- renameSync(`${prepared.path}.tmp`, prepared.path);
89
+ const backedUp = prepared.previousBytes !== undefined;
90
+ if (backedUp) copyFileSync(prepared.path, `${prepared.path}.bak`);
91
+ replaceFile(prepared.path, prepared.bytes);
65
92
  ctx.nextStepTriggers.claudeRestart = true;
66
93
  if (prepared.previousBytes === undefined) {
67
94
  change("Settings installed");
@@ -72,6 +99,7 @@ export function commitClaudeSettings(ctx: Ctx, prepared: PreparedClaudeSettings)
72
99
  } else {
73
100
  change("Settings merged (backup at settings.json.bak)");
74
101
  }
102
+ return backedUp;
75
103
  }
76
104
 
77
105
  export function describeSettingsSync(ctx: Ctx, claudeDir: string): void {
@@ -114,8 +142,7 @@ function jqEditSettings(
114
142
  edit(doc);
115
143
  const out = jqStringify(doc);
116
144
  if (out === before) return false;
117
- writeFileSync(`${userSettings}.tmp`, out);
118
- renameSync(`${userSettings}.tmp`, userSettings);
145
+ replaceFile(userSettings, out);
119
146
  return true;
120
147
  }
121
148
 
@@ -1,6 +1,7 @@
1
1
  /** Atomic top-level Claude settings modifiers, including direct model mode. */
2
2
  import { p } from "./exec";
3
- import { readFileSync, renameSync, writeFileSync } from "node:fs";
3
+ import { readFileSync } from "node:fs";
4
+ import { replaceFile } from "./atomicWrite";
4
5
 
5
6
  import { resolveEffort } from "../efforts";
6
7
  import type { Ctx } from "./index";
@@ -59,8 +60,7 @@ function syncClaudeSetting(ctx: Ctx, edit: ClaudeSettingEdit): void {
59
60
  verbose(edit.unchanged);
60
61
  return;
61
62
  }
62
- writeFileSync(`${userSettings}.tmp`, out);
63
- renameSync(`${userSettings}.tmp`, userSettings);
63
+ replaceFile(userSettings, out);
64
64
  change(edit.changed);
65
65
  ctx.nextStepTriggers.claudeRestart = true;
66
66
  }
@@ -4,14 +4,8 @@
4
4
  * plugins. Message strings, guard order, JSON semantics, and spawned argv are
5
5
  * golden-tested.
6
6
  */
7
- import {
8
- appendFileSync,
9
- existsSync,
10
- mkdirSync,
11
- readFileSync,
12
- renameSync,
13
- writeFileSync,
14
- } from "node:fs";
7
+ import { appendFileSync, copyFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
8
+ import { replaceFile } from "./atomicWrite";
15
9
  import { bunBootstrap } from "./bun";
16
10
  import { syncClaudeAdvisor, syncClaudeEffort, syncClaudeModel } from "./claudeSettingsModifiers";
17
11
  import {
@@ -74,12 +68,13 @@ export async function claudeSync(ctx: Ctx): Promise<ClaudeRuntimeState> {
74
68
 
75
69
  syncClaudeRuntime(ctx, runtime);
76
70
  syncClaudeMd(ctx, claudeDir);
71
+ let settingsBackedUp = false;
77
72
  if (ctx.dryRun) {
78
73
  describeSettingsSync(ctx, claudeDir);
79
74
  } else {
80
- commitClaudeSettings(ctx, prepared);
75
+ settingsBackedUp = commitClaudeSettings(ctx, prepared);
81
76
  }
82
- syncRemovals(ctx, claudeDir, runtime);
77
+ syncRemovals(ctx, claudeDir, runtime, settingsBackedUp);
83
78
  syncCompactWindow(ctx, claudeDir);
84
79
  syncPermissive(ctx, claudeDir);
85
80
  syncClaudeModel(ctx, ctx.claudeModel);
@@ -140,8 +135,12 @@ function syncClaudeMd(ctx: Ctx, claudeDir: string): void {
140
135
  }
141
136
 
142
137
  const source = payloadText("SoT/.claude/CLAUDE.md");
143
- if (writeTextIfChanged(p(claudeDir, "CLAUDE.md"), source)) {
144
- change("CLAUDE.md synced");
138
+ const target = p(claudeDir, "CLAUDE.md");
139
+ // A first sync can find the user's own global instructions here; keep them.
140
+ const replaced = existsSync(target) && readFileSync(target, "utf8") !== source;
141
+ if (replaced) copyFileSync(target, `${target}.bak`);
142
+ if (writeTextIfChanged(target, source)) {
143
+ change(`CLAUDE.md synced${replaced ? " (backup at CLAUDE.md.bak)" : ""}`);
145
144
  } else {
146
145
  verbose("CLAUDE.md already in sync");
147
146
  }
@@ -189,13 +188,13 @@ function syncClaudeJson(ctx: Ctx): void {
189
188
  if (out === before) {
190
189
  changed = false;
191
190
  } else {
192
- writeFileSync(`${claudeJson}.tmp`, out);
193
- renameSync(`${claudeJson}.tmp`, claudeJson);
191
+ replaceFile(claudeJson, out);
194
192
  }
195
193
  } else {
196
194
  const obj: JsonObject = {};
197
195
  applyFilter(obj);
198
- writeFileSync(claudeJson, jqStringify(obj));
196
+ // The file holds MCP server credentials, so a new file is private to the user.
197
+ replaceFile(claudeJson, jqStringify(obj), { mode: 0o600 });
199
198
  }
200
199
  if (changed) {
201
200
  change(`~/.claude.json updated (showTurnDuration${haveMcp ? ", mcpServers" : ""})`);
@@ -227,7 +226,10 @@ async function syncConnectorEnv(ctx: Ctx): Promise<void> {
227
226
  }
228
227
  }
229
228
 
230
- const target = p(ctx.home, setting.target(process.env["SHELL"]));
229
+ const target = p(
230
+ ctx.home,
231
+ setting.target(process.env["SHELL"], (f) => existsSync(p(ctx.home, f))),
232
+ );
231
233
  if (ctx.dryRun) {
232
234
  echo(`[dry-run] append '${setting.line}' to ${target}`);
233
235
  return;