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
@@ -3,7 +3,9 @@
3
3
  * inside `syncPlugins` is load-bearing and golden-tested; message strings
4
4
  * and spawned argv are part of the contract.
5
5
  */
6
- import { existsSync, renameSync, writeFileSync } from "node:fs";
6
+ import { existsSync } from "node:fs";
7
+ import { tmpdir } from "node:os";
8
+ import { replaceFile } from "./atomicWrite";
7
9
  import { p, spawnProcess } from "./exec";
8
10
  import { recordFailure } from "./failures";
9
11
  import type { Ctx } from "./index";
@@ -19,23 +21,50 @@ import {
19
21
  import { payloadText } from "../payload";
20
22
  import type { JsonObject } from "./sharedTypes";
21
23
 
22
- /** Claude Code's built-in marketplace: always present, never added or pruned by the kit. */
24
+ /**
25
+ * Claude Code's official marketplace: protected from prune, and added on demand
26
+ * when a kit plugin comes from it and the marketplace is not registered yet.
27
+ */
23
28
  const OFFICIAL_MARKETPLACE = "claude-plugins-official";
29
+ const OFFICIAL_MARKETPLACE_REPO = "anthropics/claude-plugins-official";
30
+
31
+ /**
32
+ * Success text of `claude plugin update` when the version changed, e.g.
33
+ * `Plugin "x" updated from 1.0.0 to 1.0.1 for scope user`. The text for an
34
+ * up-to-date plugin ("already at the latest version") does not match.
35
+ */
36
+ const PLUGIN_UPDATED_RE = /\bupdated from \S+ to \S+ for scope\b/;
37
+
38
+ /** First non-empty trimmed line of a stream, or undefined when it has none. */
39
+ function firstLine(text: string): string | undefined {
40
+ return text
41
+ .split("\n")
42
+ .map((line) => line.trim())
43
+ .find((line) => line !== "");
44
+ }
24
45
 
25
46
  export async function cli(
26
47
  args: Array<string>,
27
48
  ): Promise<{ ok: boolean; out: string; detail: string }> {
28
- const res = await spawnProcess("claude", args, { stdio: ["ignore", "pipe", "pipe"] });
49
+ // A `claude plugin` command without `--scope` also edits the project
50
+ // settings of its working directory. A neutral working directory keeps
51
+ // every command on the user scope, whatever directory the user runs sync from.
52
+ const res = await spawnProcess("claude", args, {
53
+ stdio: ["ignore", "pipe", "pipe"],
54
+ cwd: tmpdir(),
55
+ });
29
56
  // A spawn error carries its cause in `error`, not in either stream, and that
30
57
  // is the case a failure message cannot afford to drop: it names an
31
58
  // unresolvable launcher instead of a rejected command.
32
- const out = res.error !== undefined ? res.error.message : `${res.stdout}${res.stderr}`;
33
- const detail =
34
- out
35
- .split("\n")
36
- .map((line) => line.trim())
37
- .find((line) => line !== "") ?? "unknown error";
38
- return { ok: res.error === undefined && res.exitCode === 0, out, detail };
59
+ if (res.error !== undefined) {
60
+ const out = res.error.message;
61
+ return { ok: false, out, detail: firstLine(out) ?? "unknown error" };
62
+ }
63
+ // The CLI prints progress lines on stdout and the cause on stderr, so the
64
+ // failure detail reads stderr first.
65
+ const out = `${res.stdout}${res.stderr}`;
66
+ const detail = firstLine(res.stderr) ?? firstLine(res.stdout) ?? "unknown error";
67
+ return { ok: res.exitCode === 0, out, detail };
39
68
  }
40
69
 
41
70
  /** Failure message tail: the cause, then the command to re-run by hand. */
@@ -127,11 +156,11 @@ export async function syncPlugins(ctx: Ctx, claudeDir: string): Promise<void> {
127
156
  );
128
157
  };
129
158
  const addedMarketplaces = new Set<string>();
130
- // The official marketplace is built in; a successful add is usable before its inventory is written.
159
+ // A successful add is usable before its inventory is written.
131
160
  // A missing inventory proves absence (fresh home); an unreadable one does not, so refresh as before.
132
161
  const skippedRefresh = new Set<string>();
133
162
  const marketplaceReady = (mpName: string): boolean => {
134
- if (mpName === OFFICIAL_MARKETPLACE || addedMarketplaces.has(mpName)) return true;
163
+ if (addedMarketplaces.has(mpName)) return true;
135
164
  const known = existsSync(knownMarketplaces) ? readJsonFile(knownMarketplaces) : {};
136
165
  if (known === undefined || !isObject(known) || knownMarketplace(mpName)) return true;
137
166
  if (!skippedRefresh.has(mpName)) {
@@ -143,6 +172,11 @@ export async function syncPlugins(ctx: Ctx, claudeDir: string): Promise<void> {
143
172
  return false;
144
173
  };
145
174
 
175
+ // Kit-owned plugin IDs: SoT-declared plus this run's --claude-plugin opt-ins.
176
+ const kitPluginIds = new Set<string>(Object.keys(sotPlugins));
177
+ if (ctx.claudePlugins.includes("supabase")) kitPluginIds.add("supabase@claude-plugins-official");
178
+ if (ctx.claudePlugins.includes("n8n")) kitPluginIds.add("n8n-mcp-skills@n8n-mcp-skills");
179
+
146
180
  // Pass 1 — add missing marketplaces (SoT insertion order, like to_entries).
147
181
  let addedMp = 0;
148
182
  let f1 = 0;
@@ -167,6 +201,32 @@ export async function syncPlugins(ctx: Ctx, claudeDir: string): Promise<void> {
167
201
  }
168
202
  }
169
203
 
204
+ // Claude Code registers its official marketplace only in an interactive
205
+ // session. A fresh home therefore needs the kit to add it before any install.
206
+ const needsOfficial = [...kitPluginIds].some((pluginId) =>
207
+ pluginId.endsWith(`@${OFFICIAL_MARKETPLACE}`),
208
+ );
209
+ if (
210
+ needsOfficial &&
211
+ !addedMarketplaces.has(OFFICIAL_MARKETPLACE) &&
212
+ !knownMarketplace(OFFICIAL_MARKETPLACE)
213
+ ) {
214
+ const addArgs = ["plugin", "marketplace", "add", OFFICIAL_MARKETPLACE_REPO];
215
+ progress(`Adding marketplace ${OFFICIAL_MARKETPLACE}...`);
216
+ const officialResult = await cli(addArgs);
217
+ clearProgress();
218
+ if (officialResult.ok) {
219
+ addedMp++;
220
+ addedMarketplaces.add(OFFICIAL_MARKETPLACE);
221
+ } else {
222
+ recordFailure(
223
+ ctx,
224
+ `Failed to add marketplace: ${OFFICIAL_MARKETPLACE} (${OFFICIAL_MARKETPLACE_REPO}): ${manually(officialResult.detail, addArgs)}`,
225
+ );
226
+ f1++;
227
+ }
228
+ }
229
+
170
230
  // Pass 2 — install SoT-enabled plugins missing at user scope (jq keys[] sorts),
171
231
  // refreshing each source marketplace once so the install resolves a current snapshot.
172
232
  let addedPl = 0;
@@ -210,10 +270,6 @@ export async function syncPlugins(ctx: Ctx, claudeDir: string): Promise<void> {
210
270
  const installedKeys =
211
271
  installedDoc !== undefined && isObject(installedDoc) ? sortedKeys(installedDoc["plugins"]) : [];
212
272
  const nonUserMarketplaces = nonUserScopeMarketplaces(installedDoc);
213
- // Kit-owned plugin IDs: SoT-declared plus this run's --claude-plugin opt-ins.
214
- const kitPluginIds = new Set<string>(Object.keys(sotPlugins));
215
- if (ctx.claudePlugins.includes("supabase")) kitPluginIds.add("supabase@claude-plugins-official");
216
- if (ctx.claudePlugins.includes("n8n")) kitPluginIds.add("n8n-mcp-skills@n8n-mcp-skills");
217
273
 
218
274
  // Kit-owned marketplaces: SoT-declared plus every marketplace those plugins come from.
219
275
  const kitMarketplaces = new Set<string>(Object.keys(sotMarketplaces));
@@ -254,7 +310,7 @@ export async function syncPlugins(ctx: Ctx, claudeDir: string): Promise<void> {
254
310
  `Failed to update plugin: ${pluginId}: ${manually(updateResult.detail, ["plugin", "update", pluginId, "--scope", "user"])}`,
255
311
  );
256
312
  f4++;
257
- } else if (updateResult.out.includes("Successfully updated")) {
313
+ } else if (PLUGIN_UPDATED_RE.test(updateResult.out)) {
258
314
  updatedPl++;
259
315
  }
260
316
  }
@@ -341,13 +397,14 @@ async function reassertEnabledState(
341
397
  ? (user["enabledPlugins"] as JsonObject)[pluginId]
342
398
  : undefined;
343
399
  if (enabled !== true) continue;
344
- const disableResult = await cli(["plugin", "disable", pluginId]);
400
+ const disableArgs = ["plugin", "disable", pluginId, "--scope", "user"];
401
+ const disableResult = await cli(disableArgs);
345
402
  if (disableResult.ok) {
346
403
  cliDisabled = true;
347
404
  } else {
348
405
  recordFailure(
349
406
  ctx,
350
- `Failed to disable SoT-false plugin: ${pluginId} (will retry next sync): ${manually(disableResult.detail, ["plugin", "disable", pluginId])}`,
407
+ `Failed to disable SoT-false plugin: ${pluginId} (will retry next sync): ${manually(disableResult.detail, disableArgs)}`,
351
408
  );
352
409
  }
353
410
  }
@@ -364,7 +421,6 @@ async function reassertEnabledState(
364
421
  );
365
422
  const out = jqStringify(user);
366
423
  if (out === beforeCanonical) return cliDisabled;
367
- writeFileSync(`${userSettingsFile}.tmp`, out);
368
- renameSync(`${userSettingsFile}.tmp`, userSettingsFile);
424
+ replaceFile(userSettingsFile, out);
369
425
  return true;
370
426
  }
@@ -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
  *