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
@@ -3,6 +3,7 @@ import { Console, Effect } from "effect";
3
3
  import { existsSync, readFileSync } from "node:fs";
4
4
  import { bail, compiled } from "../engine";
5
5
  import { kitHome } from "../kitHome";
6
+ import { DEPENDENCIES, defaultProbeExecutor, resolvePath } from "../engine-native/deps";
6
7
  import { p, spawnHost } from "../engine-native/exec";
7
8
  import { hostOs, type HostOs } from "../engine-native/os";
8
9
 
@@ -59,22 +60,30 @@ const capturePackageRoot: CapturePackageRoot = (command, args) => {
59
60
  };
60
61
 
61
62
  /**
62
- * A Bun global home is `<root>/.bun/install/global/node_modules/<pkg>`. Windows
63
- * reports that path with backslashes and compares it without case sensitivity.
64
- * On POSIX, a backslash remains a legal filename character, not a separator.
63
+ * The comparison key of a host path. Windows reports paths with backslashes
64
+ * and compares them without case sensitivity. On POSIX, a backslash remains a
65
+ * legal filename character, not a separator.
65
66
  */
67
+ const hostPathKey = (value: string, host: HostOs): string =>
68
+ host.id === "windows"
69
+ ? value.replaceAll("\\", "/").replace(/\/+$/, "").toLowerCase()
70
+ : value.replace(/\/+$/, "");
71
+
72
+ /** Whether two package homes name the same directory on this host. */
73
+ export const samePackageHome = (a: string, b: string, host: HostOs = hostOs()): boolean =>
74
+ hostPathKey(a, host) === hostPathKey(b, host);
75
+
76
+ /** A Bun global home is `<root>/.bun/install/global/node_modules/<pkg>`. */
66
77
  export const packageManagerForHome = (
67
78
  home: string,
68
79
  environment: NodeJS.ProcessEnv = process.env,
69
80
  host: HostOs = hostOs(),
70
81
  ): PackageManager => {
71
- const normalize = (value: string): string =>
72
- host.id === "windows" ? value.replaceAll("\\", "/").toLowerCase() : value;
73
- const normalizedHome = normalize(home);
82
+ const normalizedHome = hostPathKey(home, host);
74
83
  const underEnvironmentRoot = (name: "BUN_INSTALL_GLOBAL_DIR" | "BUN_INSTALL"): boolean => {
75
84
  const root = environment[name]?.trim();
76
85
  if (root === undefined || root === "") return false;
77
- const normalizedRoot = normalize(root).replace(/\/+$/, "") || "/";
86
+ const normalizedRoot = hostPathKey(root, host) || "/";
78
87
  const prefix = normalizedRoot.endsWith("/") ? normalizedRoot : `${normalizedRoot}/`;
79
88
  return normalizedHome === normalizedRoot || normalizedHome.startsWith(prefix);
80
89
  };
@@ -144,6 +153,32 @@ export const packageUpdateResult = (
144
153
  return { alreadyCurrent: false, message: `Updated ${before} -> ${after}.` };
145
154
  };
146
155
 
156
+ export type UpdateBunCommand =
157
+ | { readonly ok: true; readonly command: string }
158
+ | { readonly ok: false; readonly diagnostic: string };
159
+
160
+ /**
161
+ * The Bun that reinstalls checkout dependencies. The source path always runs
162
+ * under Bun, and the launcher may have picked a Bun that is not on PATH, so it
163
+ * reuses `execPath`. A compiled binary resolves Bun like the dependency probe:
164
+ * PATH, then $BUN_INSTALL/bin, then ~/.bun/bin.
165
+ */
166
+ export const updateBunCommand = async (
167
+ isCompiled: boolean,
168
+ execPath: string,
169
+ home: string,
170
+ resolveBun: () => Promise<string> = () => resolvePath(DEPENDENCIES.bun, defaultProbeExecutor),
171
+ ): Promise<UpdateBunCommand> => {
172
+ if (!isCompiled) return { ok: true, command: execPath };
173
+ const resolved = await resolveBun();
174
+ return resolved === ""
175
+ ? {
176
+ ok: false,
177
+ diagnostic: `dependencies changed but Bun was not found - run 'bun install --frozen-lockfile' in ${home}, then docks-kit sync`,
178
+ }
179
+ : { ok: true, command: resolved };
180
+ };
181
+
147
182
  const updateCheckout = (home: string, skipSync: boolean) =>
148
183
  Effect.gen(function* () {
149
184
  if (spawnHost("git", ["--version"], { stdio: "ignore" }).status !== 0) {
@@ -178,13 +213,15 @@ const updateCheckout = (home: string, skipSync: boolean) =>
178
213
 
179
214
  const touched = git(home, ["diff", "--name-only", before, after]).out.split("\n");
180
215
  if (touched.includes("bun.lock") || touched.includes("package.json")) {
181
- const res = spawnHost("bun", ["install", "--frozen-lockfile"], {
216
+ const bun = yield* Effect.promise(() => updateBunCommand(compiled, process.execPath, home));
217
+ if (!bun.ok) return yield* bail(bun.diagnostic, 1);
218
+ const res = spawnHost(bun.command, ["install", "--frozen-lockfile"], {
182
219
  cwd: home,
183
220
  stdio: "inherit",
184
221
  });
185
222
  if (res.error !== undefined || res.status !== 0) {
186
223
  return yield* bail(
187
- "dependencies changed but 'bun install --frozen-lockfile' failed - fix that, then run docks-kit sync",
224
+ `dependencies changed but 'bun install --frozen-lockfile' failed - fix the error, then run 'bun install --frozen-lockfile' in ${home} and docks-kit sync`,
188
225
  1,
189
226
  );
190
227
  }
@@ -242,7 +279,11 @@ const updatePackage = (home: string, skipSync: boolean) =>
242
279
  1,
243
280
  );
244
281
  }
245
- const result = packageUpdateResult(beforeVersion, afterVersion, home === updated.home);
282
+ const result = packageUpdateResult(
283
+ beforeVersion,
284
+ afterVersion,
285
+ samePackageHome(home, updated.home),
286
+ );
246
287
  if (result.message !== "") yield* Console.log(result.message);
247
288
  if (skipSync)
248
289
  return yield* Console.log(
@@ -31,11 +31,16 @@ explicit removed-engine diagnostic and exits 2 with the recovery tag message.
31
31
  materialized settings, writes runtime assets, commits settings, then performs
32
32
  readiness-gated legacy cleanup. Modifiers run after the base commit, removals
33
33
  before plugins, and LSP checks after plugin state.
34
- - **Pipeline concurrency is bounded.** Selected Claude, Codex, and skills
35
- pipelines overlap through one input-ordered pool. The production default is
36
- 3; `DOCKS_KIT_SYNC_CONCURRENCY=1` restores serial execution for golden tests
37
- and debugging (`2` allows two-way overlap). Each individual pipeline remains
38
- serial, and summaries retain canonical Claude, Codex, skills order.
34
+ - **Pipeline concurrency is bounded.** Selected Claude, Codex, skills, and omp
35
+ pipelines run through one input-ordered pool (`syncConcurrency.ts`
36
+ `runBounded`). The production default cap is 3. When all four pipelines are
37
+ selected, omp starts only after an earlier pipeline settles. After the first
38
+ rejection, started pipelines drain and queued pipelines never start.
39
+ `DOCKS_KIT_SYNC_CONCURRENCY=1` restores serial execution for golden tests
40
+ and debugging (`2` allows two-way overlap). A populated skills manifest with
41
+ the `claude` and `agents` targets selected forces serial execution
42
+ (`syncConcurrencyForManifest`). Each individual pipeline remains serial, and
43
+ summaries keep the Claude, Codex, skills, omp order.
39
44
  - **External CLIs stay external.** `claude`, `codex`, `npx`, `npm`, `bun`,
40
45
  `curl`, and platform package managers are spawned with argv arrays,
41
46
  not shell command strings except where an external installer contract
@@ -50,7 +55,8 @@ explicit removed-engine diagnostic and exits 2 with the recovery tag message.
50
55
 
51
56
  The default run reads like a change report: only actual changes, actionable
52
57
  warnings, and the summary. Status-quo confirmations exist but are opt-in.
53
- (Rationale + full call-site audit: `docs/plans/active/cli-log-ux-overhaul.md`.)
58
+ (Rationale: the plan record shipped in commit 13214bc. Recover it with
59
+ `git log -- docs/plans/finished/`.)
54
60
 
55
61
  ### Channels and levels
56
62
 
@@ -116,46 +122,61 @@ changed → restart line; skills changed → discovery line) or under `--verbose
116
122
 
117
123
  ### Platform seam
118
124
 
119
- All host detection routes through `os/index.ts`, which holds the engine's only
120
- `process.platform` read and keeps platform normalization injectable for tests.
125
+ All host detection routes through `os/index.ts`. Its `rawPlatform` function
126
+ holds the engine's host-detection `process.platform` read and keeps platform
127
+ normalization injectable for tests. Two direct reads remain: the POSIX-only
128
+ `chmod` guard in `kitDb.ts` and the default `platform` argument of
129
+ `harnesses.ts` `engineHome`.
121
130
  Per-OS facts live in `os/linux.ts`, `os/darwin.ts`, and `os/windows.ts` behind
122
131
  `HostOs`; consumers select those facts through the package rather than branching
123
132
  on the host directly.
124
133
 
125
134
  ### Verbosity plumbing
126
135
 
127
- `--verbose` / `-v` on the public `sync`, `model`, and `toolchain` commands;
128
- `DOCKS_KIT_VERBOSE=1` selects it on the harness-private raw channel (same
129
- `${VAR:-default}` contract as the other `Ctx` env globals). The default
130
- service factory returns a raw Logger. `runEngineNative` wraps the default or
131
- injected Logger with explicit delegates and owns the sole `ctx.verbose` gate.
136
+ `--verbose` / `-v` on the public `sync`, `model`, and `toolchain` commands
137
+ selects verbose output. On the harness-private raw channel,
138
+ `DOCKS_KIT_VERBOSE=1` also selects it. Only the raw channel honors the
139
+ unprefixed `Ctx` env globals (`engineCtx.ts` `ENV_GLOBAL_KEYS`, with the
140
+ `${VAR:-default}` contract). `main.ts` passes `{ envGlobals: true }` to
141
+ `runEngineNative` only on that channel. The public `engine()` seam ignores
142
+ these variables, and `engineCapture` removes them from the child environment.
143
+ The default service factory returns a raw Logger. `runEngineNative` wraps the
144
+ default or injected Logger with explicit delegates and owns the sole
145
+ `ctx.verbose` gate.
132
146
  There is no factory-level verbosity callback, module-global verbosity flag, or
133
147
  active logger binding.
134
148
 
135
149
  ## Module Map
136
150
 
137
- | Module | Owns |
138
- | ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
139
- | `parseArgs.ts` | engine usage, target selection, flag parsing, legacy rename hints, model flag validation |
140
- | `index.ts` | sync orchestration, target dispatch, run summary and next-step blocks |
141
- | `../payload.ts` | generated text/byte payload reads and presentation-only source labels |
142
- | `claudeSync.ts` | Claude pipeline: Bun bootstrap, prepared settings transaction, runtime assets, deploy-time modifiers, `~/.claude.json`, readiness-gated removed artifacts, plugins, optional plugins, LSP binaries |
143
- | `bun.ts` | per-run memoized Bun resolution/bootstrap shared by the Claude runtime and direct toolchain ensure |
144
- | `claudeRuntime.ts` | sentinel validation, absolute runtime paths, no-cutover settings projection, and per-host statusline and failure-hook command materialization |
145
- | `settings.ts` | pure Claude settings merge/reconcile semantics and permission-array union |
146
- | `claudeModel.ts` | deployed Claude model modifier and direct `model claude` write path |
147
- | `codexSync.ts` | Codex pipeline: bubblewrap check, config merge, rules, AGENTS.md, personal marketplace, plugin refresh |
148
- | `codexToml.ts` | line-based top-level TOML replacement and deployed Codex model modifier |
149
- | `skillsSync.ts` | universal skill install/prune, ordered symlink/junction/copy fallback, Claude entry healing, managed-skill snapshot |
150
- | `toolchain.ts` | tool presence/version probes, verified-version floor reporting, report table |
151
- | `modes.ts` | direct `model` and `toolchain` modes |
152
- | `models.ts` | model catalog listing and validation |
153
- | `jq.ts` | JSON helpers that preserve jq-style merge/order/stringify behavior where the deployed file contract needs it |
154
- | `exec.ts` | slash-stable path helpers, host-aware PATH probes and invocation, capture/spawn wrappers, and change-detecting write/copy helpers |
155
- | `logger.ts` | Logger shape + stable raw stdout/stderr sink factory; the run-scoped verbosity gate lives in `index.ts` |
156
- | `deps.ts` | external-tool registry: identity, requirement class, presence probe, supported-host install hints, per-manager missing-tool dedup; callers supply the current run Logger to `warnMissing` |
157
- | `os/` | host reader, injected platform normalization, and per-OS `HostOs` fact modules |
158
- | `services.ts` | shared raw-Logger + DependencyManager + Platform factory; wrapped in Effect Layers at `cli/src/services.ts`, with the run-scoped Logger gate applied only by `runEngineNative` |
151
+ | Module | Owns |
152
+ | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
153
+ | `parseArgs.ts` | engine usage, target selection, argv dispatch loop, legacy rename hints; re-exports the `parseHelp.ts` help text and early-exit error |
154
+ | `parseModifiers.ts` | deploy-time modifier metadata, scalar modifier setters, compact-window and opt-in plugin parsing, modifier and model flag validation |
155
+ | `index.ts` | entry routing (`model`/`toolchain`/`sync`) and the run-scoped verbosity gate |
156
+ | `engineCtx.ts` | `Ctx` shape and `makeCtx`; the unprefixed env globals (`ENV_GLOBAL_KEYS`) apply only on the native-raw channel |
157
+ | `syncDispatch.ts` | pipeline selection, pool dispatch, run summary, next-step blocks, and the `--- Failures ---` ledger |
158
+ | `syncConcurrency.ts` | input-ordered bounded pool (`runBounded`) and the manifest-driven serial rule (`syncConcurrencyForManifest`) |
159
+ | `../payload.ts` | generated text/byte payload reads and presentation-only source labels |
160
+ | `claudeSync.ts` | Claude pipeline: Bun bootstrap, prepared settings transaction, runtime assets, deploy-time modifiers, `~/.claude.json`, readiness-gated removed artifacts, plugins, optional plugins, LSP binaries |
161
+ | `bun.ts` | per-run memoized Bun resolution/bootstrap shared by the Claude runtime and direct toolchain ensure |
162
+ | `claudeRuntime.ts` | sentinel validation, absolute runtime paths, no-cutover settings projection, and per-host statusline and failure-hook command materialization |
163
+ | `settings.ts` | pure Claude settings merge/reconcile semantics and permission-array union |
164
+ | `claudeSettings.ts` | Claude settings preflight, prepare/commit transaction, dry-run description, and the compact-window and permissive modifiers |
165
+ | `claudeSettingsModifiers.ts` | atomic top-level Claude settings modifiers (model, effort, advisor) and the direct `model claude` write path |
166
+ | `claudeRemovals.ts` | force-prune of retired Claude artifacts and the `claudeRetired.ts` permission inventory without `--reconcile` |
167
+ | `codexSync.ts` | Codex pipeline: bubblewrap check, config merge, rules, AGENTS.md, personal marketplace, plugin refresh |
168
+ | `codexToml.ts` | line-based top-level TOML replacement and deployed Codex model modifier |
169
+ | `skillsSync.ts` | universal skill install/prune, ordered symlink/junction/copy fallback, Claude entry healing, managed-skill snapshot |
170
+ | `ompSync.ts` | omp pipeline orchestration and summary; `ompFileDeploy.ts`, `ompMarketplace.ts`, `ompPlugins.ts`, and `ompRemovals.ts` own the file, marketplace, plugin, and retired-key passes; `ompPaths.ts` resolves roots; `ompYaml.ts` merges YAML |
171
+ | `toolchain.ts` | tool presence/version probes, verified-version floor reporting, report table |
172
+ | `modes.ts` | direct `model` and `toolchain` modes |
173
+ | `models.ts` | model catalog listing and validation |
174
+ | `jq.ts` | JSON helpers that preserve jq-style merge/order/stringify behavior where the deployed file contract needs it |
175
+ | `exec.ts` | slash-stable path helpers, host-aware PATH probes and invocation, capture/spawn wrappers, and change-detecting write/copy helpers |
176
+ | `logger.ts` | Logger shape + stable raw stdout/stderr sink factory; the run-scoped verbosity gate lives in `index.ts` |
177
+ | `deps.ts` | external-tool registry: identity, requirement class, presence probe, supported-host install hints, per-manager missing-tool dedup; callers supply the current run Logger to `warnMissing` |
178
+ | `os/` | host reader, injected platform normalization, and per-OS `HostOs` fact modules |
179
+ | `services.ts` | shared raw-Logger + DependencyManager + Platform factory; wrapped in Effect Layers at `cli/src/services.ts`, with the run-scoped Logger gate applied only by `runEngineNative` |
159
180
 
160
181
  ## Platform Support
161
182
 
@@ -0,0 +1,64 @@
1
+ /**
2
+ * File replacement through a temporary sibling and a rename, so a reader never
3
+ * sees a partial write. Every kit writer that rewrites a user file uses it,
4
+ * because two properties must hold for all of them:
5
+ * - A symlinked target stays a symlink; the file it points to is replaced.
6
+ * - The replaced file keeps its permission bits unless the caller sets them.
7
+ */
8
+ import {
9
+ chmodSync,
10
+ lstatSync,
11
+ readlinkSync,
12
+ realpathSync,
13
+ renameSync,
14
+ statSync,
15
+ writeFileSync,
16
+ } from "node:fs";
17
+ import { dirname, resolve } from "node:path";
18
+
19
+ export interface ReplaceFileOptions {
20
+ /**
21
+ * Permission bits for the written file. Without it, an existing file keeps
22
+ * its bits and a new file gets the process umask default.
23
+ */
24
+ readonly mode?: number;
25
+ }
26
+
27
+ /** The file a write must replace: the link target for a symlink, else the path itself. */
28
+ function writeTarget(target: string): string {
29
+ let isLink: boolean;
30
+ try {
31
+ isLink = lstatSync(target).isSymbolicLink();
32
+ } catch {
33
+ return target;
34
+ }
35
+ if (!isLink) return target;
36
+ try {
37
+ return realpathSync(target);
38
+ } catch {
39
+ // A dangling link: create the file it names, and keep the link.
40
+ return resolve(dirname(target), readlinkSync(target));
41
+ }
42
+ }
43
+
44
+ function permissionBits(file: string): number | undefined {
45
+ try {
46
+ return statSync(file).mode & 0o777;
47
+ } catch {
48
+ return undefined;
49
+ }
50
+ }
51
+
52
+ export function replaceFile(
53
+ target: string,
54
+ content: string | Uint8Array,
55
+ options: ReplaceFileOptions = {},
56
+ ): void {
57
+ const file = writeTarget(target);
58
+ const mode = options.mode ?? permissionBits(file);
59
+ const temporary = `${file}.tmp`;
60
+ writeFileSync(temporary, content, mode === undefined ? {} : { mode });
61
+ // writeFileSync applies `mode` only when it creates the file, and through the umask.
62
+ if (mode !== undefined) chmodSync(temporary, mode);
63
+ renameSync(temporary, file);
64
+ }
@@ -116,11 +116,18 @@ export async function syncLspServers(ctx: Ctx): Promise<void> {
116
116
  const tsServerMissing =
117
117
  hasTs && ctx.services.deps.probe("typescript-language-server").state === "missing";
118
118
  const tscMissing = hasTs && ctx.services.deps.probe("tsc").state === "missing";
119
- const rustMissing = hasRust && ctx.services.deps.probe("rust-analyzer").state === "missing";
119
+ const rustupPresent = ctx.services.deps.probe("rustup").state === "present";
120
+ // rustup links a rust-analyzer proxy into ~/.cargo/bin even when the
121
+ // component is not installed, and that proxy reports no version. With
122
+ // rustup present, a PATH hit without a version counts as missing.
123
+ const rustMissing =
124
+ hasRust &&
125
+ (ctx.services.deps.probe("rust-analyzer").state === "missing" ||
126
+ (rustupPresent && (await ctx.services.deps.version("rust-analyzer")) === ""));
120
127
  // A host without rustup does no Rust work, so the plugin has nothing to
121
128
  // serve there. Installing is impossible and warning every sync would name no
122
129
  // action the user wants, so that host is not counted as missing a tool.
123
- const rustInstallable = rustMissing && ctx.services.deps.probe("rustup").state === "present";
130
+ const rustInstallable = rustMissing && rustupPresent;
124
131
  if (rustMissing && !rustInstallable) {
125
132
  verbose(
126
133
  "Skipping rust-analyzer: rustup is not installed, so the rust-analyzer-lsp plugin stays a no-op",
@@ -60,15 +60,20 @@ async function enableOptionalPlugin(
60
60
  ? (settingsDoc["enabledPlugins"] as JsonObject)[pluginId] === true
61
61
  : false;
62
62
 
63
- if (!(await cli(["plugin", "enable", pluginId])).ok) {
64
- if (marketplaceAdded || !wasInstalled)
65
- change(`Optional plugin ${pluginId}: installed (enable failed — will retry next sync)`);
66
- recordFailure(ctx, `Failed to enable optional plugin ${pluginId}`);
67
- return marketplaceAdded || !wasInstalled;
63
+ // `claude plugin install` enables the plugin at user scope, and
64
+ // `claude plugin enable` fails for a plugin that is already enabled.
65
+ if (!wasEnabled) {
66
+ const enableArgs = ["plugin", "enable", pluginId, "--scope", "user"];
67
+ if (!(await cli(enableArgs)).ok) {
68
+ if (marketplaceAdded || !wasInstalled)
69
+ change(`Optional plugin ${pluginId}: installed (enable failed — will retry next sync)`);
70
+ recordFailure(ctx, `Failed to enable optional plugin ${pluginId}`);
71
+ return marketplaceAdded || !wasInstalled;
72
+ }
68
73
  }
69
74
  const changed = marketplaceAdded || !wasInstalled || !wasEnabled;
70
75
  if (changed) change(`Optional plugin opted in: ${pluginId}`);
71
- else verbose(`Optional plugin already opted in: ${pluginId} (enable re-asserted)`);
76
+ else verbose(`Optional plugin already opted in: ${pluginId}`);
72
77
  return changed;
73
78
  }
74
79
 
@@ -94,6 +99,14 @@ export async function syncOptionalPlugins(ctx: Ctx, claudeDir: string): Promise<
94
99
  warn("claude CLI not in PATH — cannot opt in optional plugins (--claude-plugin)");
95
100
  return;
96
101
  }
102
+ if (ctx.services.deps.probe("git").state === "missing") {
103
+ ctx.services.deps.warnMissing(
104
+ "git",
105
+ ctx.services.logger,
106
+ "plugin marketplaces are git repos — optional plugins (--claude-plugin) skipped; re-run sync after installing",
107
+ );
108
+ return;
109
+ }
97
110
 
98
111
  if (ctx.claudePlugins.includes("supabase")) {
99
112
  if (await enableOptionalPlugin(ctx, claudeDir, "supabase@claude-plugins-official", ""))
@@ -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
  }