docks-kit 0.20.6 → 0.20.9

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 (73) hide show
  1. package/AGENTS.md +19 -17
  2. package/README.md +17 -6
  3. package/cli/docs/command-guards.md +275 -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 +28 -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/ompRemovals.ts +125 -30
  54. package/cli/src/engine-native/ompSync.ts +11 -6
  55. package/cli/src/engine-native/ompYaml.ts +96 -6
  56. package/cli/src/engine-native/os/darwin.ts +2 -0
  57. package/cli/src/engine-native/os/linux.ts +1 -0
  58. package/cli/src/engine-native/os/posix.ts +17 -5
  59. package/cli/src/engine-native/os/types.ts +2 -2
  60. package/cli/src/engine-native/os/windows.ts +24 -16
  61. package/cli/src/engine-native/skillsInstall.ts +10 -5
  62. package/cli/src/engine-native/skillsLinks.ts +14 -1
  63. package/cli/src/engine-native/skillsManifest.ts +20 -0
  64. package/cli/src/engine-native/skillsPrune.ts +33 -26
  65. package/cli/src/engine-native/skillsSync.ts +6 -3
  66. package/cli/src/engine-native/syncDispatch.ts +32 -18
  67. package/cli/src/engine.ts +29 -3
  68. package/cli/src/generated/sotPayload.ts +14 -14
  69. package/cli/src/main.ts +10 -3
  70. package/cli/src/manifests.ts +29 -11
  71. package/docks-kit +6 -3
  72. package/docks-kit.ps1 +22 -11
  73. package/package.json +1 -1
@@ -7,12 +7,19 @@
7
7
  * wildcards ahead of role chains, so a stale wildcard would silently override
8
8
  * the kit-managed role chains. models.yml drops nothing; a user file may carry
9
9
  * provider credentials and custom models the kit never declares.
10
+ *
11
+ * A SoT sequence replaces the deployed sequence, except `bash.patterns` in
12
+ * config.yml: `mergeBashPatterns` keeps the user's command rules and groups all
13
+ * rules by approval.
10
14
  */
11
- import { isMap, isScalar, parseDocument, type YAMLMap } from "yaml";
15
+ import { isMap, isScalar, isSeq, parseDocument, type YAMLMap, type YAMLSeq } from "yaml";
12
16
 
13
17
  /** Decides whether a deployed-only key at `path` is dropped instead of kept. */
14
18
  type DropDeployedKey = (path: ReadonlyArray<string>, key: string) => boolean;
15
19
 
20
+ /** Merges the deployed sequence at `path` into the SoT sequence in place. */
21
+ type MergeSequence = (path: ReadonlyArray<string>, sotSeq: YAMLSeq, deployedSeq: YAMLSeq) => void;
22
+
16
23
  const fallbackChainsPath = ["retry", "fallbackChains"] as const;
17
24
 
18
25
  function stringKey(key: unknown): string | undefined {
@@ -33,6 +40,75 @@ const dropFallbackWildcard: DropDeployedKey = (path, key) =>
33
40
 
34
41
  const keepEveryKey: DropDeployedKey = () => false;
35
42
 
43
+ const keepSotSequence: MergeSequence = () => {};
44
+
45
+ /**
46
+ * Identity of one `bash.patterns` rule, normalized the way omp reads it: the
47
+ * approval is trimmed and lowercased, and whitespace runs in `match` collapse to
48
+ * one space.
49
+ */
50
+ export function bashRuleKey(match: string, approval: string): string {
51
+ return `${approval.trim().toLowerCase()}\u0000${match.trim().replace(/\s+/gu, " ")}`;
52
+ }
53
+
54
+ /** `bashRuleKey` of one deployed rule node, or undefined for an entry omp would ignore. */
55
+ export function bashPatternKey(node: unknown): string | undefined {
56
+ if (!isMap(node)) return undefined;
57
+ const match = node.get("match");
58
+ const approval = node.get("approval");
59
+ if (typeof match !== "string" || typeof approval !== "string") return undefined;
60
+ return bashRuleKey(match, approval);
61
+ }
62
+
63
+ /**
64
+ * omp evaluates `bash.patterns` in order, and the first matching rule wins. The
65
+ * merge groups the rules: kit deny, user deny, user prompt, kit exception allow,
66
+ * kit prompt, the other user rules in their deployed order, then kit allow. A
67
+ * kit exception is a kit allow that the SoT lists before its first prompt: an
68
+ * option-terminated form such as `git rm -- *` that a broader kit prompt
69
+ * (`git rm *`) would otherwise shadow, because a glob cannot exclude it. A user
70
+ * deny or prompt therefore always precedes every kit allow, and no user or
71
+ * tail allow loosens a deny or a prompt. A deployed rule equal to a kit rule is
72
+ * the kit copy, so a re-sync changes nothing. A rule the kit stops shipping
73
+ * stays as a user rule.
74
+ */
75
+ const mergeBashPatterns: MergeSequence = (path, sotSeq, deployedSeq) => {
76
+ if (path.length !== 2 || path[0] !== "bash" || path[1] !== "patterns") return;
77
+ const kitKeys = new Set(sotSeq.items.map(bashPatternKey));
78
+ const kit: Record<"deny" | "exception" | "prompt" | "allow", Array<unknown>> = {
79
+ deny: [],
80
+ exception: [],
81
+ prompt: [],
82
+ allow: [],
83
+ };
84
+ const user: Record<"deny" | "prompt" | "other", Array<unknown>> = {
85
+ deny: [],
86
+ prompt: [],
87
+ other: [],
88
+ };
89
+ for (const item of sotSeq.items) {
90
+ const approval = bashPatternKey(item)?.split("\u0000")[0];
91
+ if (approval === "deny" || approval === "prompt") kit[approval].push(item);
92
+ else if (kit.prompt.length === 0 && approval === "allow") kit.exception.push(item);
93
+ else kit.allow.push(item);
94
+ }
95
+ for (const item of deployedSeq.items) {
96
+ const key = bashPatternKey(item);
97
+ if (key !== undefined && kitKeys.has(key)) continue;
98
+ const approval = key?.split("\u0000")[0];
99
+ user[approval === "deny" || approval === "prompt" ? approval : "other"].push(item);
100
+ }
101
+ sotSeq.items = [
102
+ ...kit.deny,
103
+ ...user.deny,
104
+ ...user.prompt,
105
+ ...kit.exception,
106
+ ...kit.prompt,
107
+ ...user.other,
108
+ ...kit.allow,
109
+ ];
110
+ };
111
+
36
112
  function pruneMapping(mapping: YAMLMap, path: ReadonlyArray<string>, drop: DropDeployedKey): void {
37
113
  for (let index = mapping.items.length - 1; index >= 0; index--) {
38
114
  const pair = mapping.items[index];
@@ -55,6 +131,7 @@ function mergeMappings(
55
131
  deployedMapping: YAMLMap,
56
132
  path: ReadonlyArray<string>,
57
133
  drop: DropDeployedKey,
134
+ mergeSequence: MergeSequence,
58
135
  ): void {
59
136
  for (const sotPair of sotMapping.items) {
60
137
  const key = stringKey(sotPair.key);
@@ -64,7 +141,10 @@ function mergeMappings(
64
141
  (candidate) => stringKey(candidate.key) === key,
65
142
  );
66
143
  if (deployedPair !== undefined && isMap(sotPair.value) && isMap(deployedPair.value)) {
67
- mergeMappings(sotPair.value, deployedPair.value, [...path, key], drop);
144
+ mergeMappings(sotPair.value, deployedPair.value, [...path, key], drop, mergeSequence);
145
+ }
146
+ if (deployedPair !== undefined && isSeq(sotPair.value) && isSeq(deployedPair.value)) {
147
+ mergeSequence([...path, key], sotPair.value, deployedPair.value);
68
148
  }
69
149
  }
70
150
 
@@ -87,6 +167,7 @@ function mergeYamlDocuments(
87
167
  deployedText: string,
88
168
  name: string,
89
169
  drop: DropDeployedKey,
170
+ mergeSequence: MergeSequence,
90
171
  ): string {
91
172
  const deployedDoc = parseDocument(deployedText);
92
173
  const deployedError = deployedDoc.errors[0];
@@ -115,16 +196,25 @@ function mergeYamlDocuments(
115
196
  throw new Error(`SoT omp ${name} YAML root must be a mapping`);
116
197
  }
117
198
 
118
- mergeMappings(sotDoc.contents, deployedContents, [], drop);
199
+ mergeMappings(sotDoc.contents, deployedContents, [], drop, mergeSequence);
119
200
  return sotDoc.toString();
120
201
  }
121
202
 
122
- /** config.yml merge: keeps user-only keys, drops stale fallback-chain wildcards. */
203
+ /**
204
+ * config.yml merge: keeps user-only keys and user `bash.patterns` rules, drops
205
+ * stale fallback-chain wildcards.
206
+ */
123
207
  export function mergeOmpConfig(sotText: string, deployedText: string): string {
124
- return mergeYamlDocuments(sotText, deployedText, "config.yml", dropFallbackWildcard);
208
+ return mergeYamlDocuments(
209
+ sotText,
210
+ deployedText,
211
+ "config.yml",
212
+ dropFallbackWildcard,
213
+ mergeBashPatterns,
214
+ );
125
215
  }
126
216
 
127
217
  /** models.yml merge: keeps every user-only key, including credentials and custom models. */
128
218
  export function mergeOmpModels(sotText: string, deployedText: string): string {
129
- return mergeYamlDocuments(sotText, deployedText, "models.yml", keepEveryKey);
219
+ return mergeYamlDocuments(sotText, deployedText, "models.yml", keepEveryKey, keepSotSequence);
130
220
  }
@@ -5,6 +5,8 @@ export const darwin: HostOs = posixHost({
5
5
  id: "darwin",
6
6
  toolchainOs: "darwin",
7
7
  supportsBubblewrap: false,
8
+ // macOS terminals start bash as a login shell. It reads the first existing file of these and never reads .bashrc.
9
+ bashTargets: [".bash_profile", ".bash_login", ".profile"],
8
10
  packageManagerHints: {
9
11
  git: "brew install git",
10
12
  jq: "brew install jq",
@@ -5,6 +5,7 @@ export const linux: HostOs = posixHost({
5
5
  id: "linux",
6
6
  toolchainOs: "linux",
7
7
  supportsBubblewrap: true,
8
+ bashTargets: [".bashrc"],
8
9
  packageManagerHints: {
9
10
  git: "sudo apt install -y git (or your distro's package manager)",
10
11
  jq: "sudo apt install -y jq",
@@ -10,8 +10,7 @@ function posixLiteral(value: string): string {
10
10
  export type PackageManagerHints = Readonly<Record<Exclude<HintedTool, "claude" | "codex">, string>>;
11
11
 
12
12
  const UPSTREAM_INSTALLER_HINTS: Readonly<Record<"claude" | "codex", string>> = {
13
- claude:
14
- "curl -fsSL https://claude.ai/install.sh -o /tmp/claude-install.sh && bash /tmp/claude-install.sh",
13
+ claude: 'tmp=$(mktemp) && curl -fsSL https://claude.ai/install.sh -o "$tmp" && bash "$tmp"',
15
14
  codex:
16
15
  'tmp=$(mktemp) && curl -fsSL https://chatgpt.com/codex/install.sh -o "$tmp" && CODEX_NON_INTERACTIVE=1 sh "$tmp"',
17
16
  };
@@ -21,6 +20,8 @@ interface PosixHostInputs {
21
20
  readonly toolchainOs: HostOs["toolchainOs"];
22
21
  readonly supportsBubblewrap: boolean;
23
22
  readonly packageManagerHints: PackageManagerHints;
23
+ /** Home-relative bash startup files in read order; the first existing one gets the write, else the first entry. */
24
+ readonly bashTargets: readonly [string, ...string[]];
24
25
  }
25
26
 
26
27
  /** Members shared by every POSIX host; linux and darwin differ only in the inputs. */
@@ -49,11 +50,22 @@ export function posixHost(inputs: PosixHostInputs): HostOs {
49
50
  },
50
51
  environmentSetting: (name, value) => ({
51
52
  kind: "profile",
52
- candidates: [".zshrc", ".bashrc", ".bash_profile", ".profile", ".zshenv"],
53
- target: (shell) => {
53
+ // Bash reads .bash_login only as a login file. Only a host that writes to it
54
+ // scans it, so a dormant copy cannot block the write to the loaded file.
55
+ candidates: [
56
+ ".zshrc",
57
+ ".bashrc",
58
+ ".bash_profile",
59
+ ...(inputs.bashTargets.includes(".bash_login") ? [".bash_login"] : []),
60
+ ".profile",
61
+ ".zshenv",
62
+ ],
63
+ target: (shell, exists) => {
54
64
  const shellPath = shell ?? "bash";
55
65
  const shellName = shellPath.slice(shellPath.lastIndexOf("/") + 1);
56
- return shellName === "zsh" ? ".zshrc" : shellName === "bash" ? ".bashrc" : ".profile";
66
+ if (shellName === "zsh") return ".zshrc";
67
+ if (shellName !== "bash") return ".profile";
68
+ return inputs.bashTargets.find(exists) ?? inputs.bashTargets[0];
57
69
  },
58
70
  line: `export ${name}=${value}`,
59
71
  }),
@@ -24,8 +24,8 @@ export type EnvironmentSetting =
24
24
  readonly kind: "profile";
25
25
  /** Home-relative files scanned for an existing setting. */
26
26
  readonly candidates: ReadonlyArray<string>;
27
- /** Home-relative file that receives the write for this shell. */
28
- readonly target: (shell: string | undefined) => string;
27
+ /** Home-relative file that receives the write for this shell; `exists` tests a home-relative file. */
28
+ readonly target: (shell: string | undefined, exists: (file: string) => boolean) => string;
29
29
  /** Line appended to the target file. */
30
30
  readonly line: string;
31
31
  }
@@ -3,7 +3,7 @@ import { p } from "../exec";
3
3
  import type { HostOs } from "./types";
4
4
 
5
5
  function powershellLiteral(value: string): string {
6
- return `'${value.replaceAll("'", "''")}'`;
6
+ return `'${value.replace(/['\u2018\u2019\u201A\u201B]/g, "$&$&")}'`;
7
7
  }
8
8
 
9
9
  function encodedPowerShellCommand(script: string): string {
@@ -14,8 +14,8 @@ function encodedPowerShellCommand(script: string): string {
14
14
  /**
15
15
  * Windows shim encoding handles three hazards: Windows argv parsing, cmd
16
16
  * metacharacter parsing, and percent/newline values that cmd cannot escape.
17
- * The encoders are ported from cross-spawn's escape.js and its parseNonShell
18
- * assembly, based on:
17
+ * The caret encoders are ported from cross-spawn's escape.js and its
18
+ * parseNonShell assembly; the backslash encoder is a linear MSVCRT pass. Based on:
19
19
  * https://github.com/moxystudio/node-cross-spawn
20
20
  * https://qntm.org/cmd
21
21
  * https://flatt.tech/research/posts/batbadbut-you-cant-securely-execute-commands-on-windows/
@@ -27,15 +27,27 @@ function escapeCommand(arg: string): string {
27
27
  return arg.replace(metaCharsRegExp, "^$1");
28
28
  }
29
29
 
30
- function escapeArgument(arg: string, doubleEscapeMetaChars: boolean): string {
31
- arg = `${arg}`;
32
- arg = arg.replace(/(?=(\\+?)?)\1"/g, '$1$1\\"');
33
- arg = arg.replace(/(?=(\\+?)?)\1$/, "$1$1");
30
+ function escapeArgument(arg: string): string {
31
+ // One linear pass applies the MSVCRT argv rules: a backslash run before a
32
+ // quote doubles and gains one escape, and a trailing run doubles before the
33
+ // closing quote. A greedy regex would be quadratic on long backslash runs.
34
+ let out = "";
35
+ let run = 0;
36
+ for (const ch of arg) {
37
+ if (ch === "\\") {
38
+ run++;
39
+ continue;
40
+ }
41
+ out += ch === '"' ? `${"\\".repeat(2 * run + 1)}"` : `${"\\".repeat(run)}${ch}`;
42
+ run = 0;
43
+ }
44
+ arg = out + "\\".repeat(2 * run);
34
45
  arg = `"${arg}"`;
46
+ // Two caret layers: the outer cmd removes one layer, and a batch file that
47
+ // forwards `%*` parses the arguments again. The kit cannot see which batch
48
+ // files forward `%*`, so every .cmd/.bat argument gets both layers.
49
+ arg = arg.replace(metaCharsRegExp, "^$1");
35
50
  arg = arg.replace(metaCharsRegExp, "^$1");
36
- if (doubleEscapeMetaChars) {
37
- arg = arg.replace(metaCharsRegExp, "^$1");
38
- }
39
51
  return arg;
40
52
  }
41
53
 
@@ -77,11 +89,7 @@ function commandShimInvocation(executablePath: string, args: ReadonlyArray<strin
77
89
  for (const arg of args) assertCommandLineValue(arg, "argument");
78
90
 
79
91
  const normalizedPath = win32.normalize(executablePath);
80
- const doubleEscapeMetaChars = /node_modules[\\/]\.bin[\\/][^\\/]+\.cmd$/i.test(normalizedPath);
81
- const commandLine = [
82
- escapeCommand(normalizedPath),
83
- ...args.map((arg) => escapeArgument(arg, doubleEscapeMetaChars)),
84
- ].join(" ");
92
+ const commandLine = [escapeCommand(normalizedPath), ...args.map(escapeArgument)].join(" ");
85
93
  return {
86
94
  command: commandInterpreter(),
87
95
  args: ["/d", "/v:off", "/s", "/c", `"${commandLine}"`],
@@ -89,7 +97,7 @@ function commandShimInvocation(executablePath: string, args: ReadonlyArray<strin
89
97
  } as const;
90
98
  }
91
99
 
92
- // Authored now, but unreachable until the supported-host admission gate opens.
100
+ // Host module for the windows-x64 and windows-arm64 targets admitted in os/targets.ts.
93
101
  export const windows: HostOs = {
94
102
  id: "windows",
95
103
  toolchainOs: "windows",
@@ -1,13 +1,13 @@
1
1
  /**
2
2
  * EngineNative universal-skill install pass (`npx skills@<pin> add`) with
3
3
  * Claude symlink healing. Split from skillsSync.ts; the orchestration still
4
- * lives there. The prune pass (skillsPrune.ts) shares `skillsCli`.
4
+ * lives there.
5
5
  */
6
6
  import { p, spawnProcess } from "./exec";
7
7
  import type { Ctx } from "./index";
8
8
  import { ExitError } from "./parseArgs";
9
9
  import { healClaudeSymlink, isDir } from "./skillsLinks";
10
- import { normalizeManifest } from "./skillsManifest";
10
+ import { normalizeManifest, skillBase } from "./skillsManifest";
11
11
  import { field } from "./toolchain";
12
12
 
13
13
  export interface SkillsState {
@@ -15,7 +15,7 @@ export interface SkillsState {
15
15
  }
16
16
 
17
17
  /** skills::_skills_cli — the pinned npx package spec. */
18
- export function skillsCli(ctx: Ctx): string {
18
+ function skillsCli(ctx: Ctx): string {
19
19
  const version = field("skills-cli", "verified");
20
20
  if (version !== "") return `skills@${version}`;
21
21
  ctx.services.logger.err(
@@ -46,7 +46,7 @@ export async function syncUniversal(
46
46
  let healed = 0;
47
47
 
48
48
  for (const slug of normalizeManifest(manifest)) {
49
- const base = slug.slice(slug.lastIndexOf("/") + 1);
49
+ const base = skillBase(slug);
50
50
 
51
51
  if (ctx.dryRun) {
52
52
  if (isDir(p(skillsDir, base))) {
@@ -75,6 +75,11 @@ export async function syncUniversal(
75
75
  clearProgress();
76
76
  if (res.error === undefined && res.exitCode === 0) {
77
77
  added++;
78
+ if (!isDir(p(skillsDir, base))) {
79
+ warn(
80
+ `Installed skill name differs from slug ${slug}; declare it as <owner>/<repo>@<skill-name>`,
81
+ );
82
+ }
78
83
  } else {
79
84
  warn(`Failed to install universal skill: ${slug}`);
80
85
  failed++;
@@ -99,7 +104,7 @@ export async function syncUniversal(
99
104
  }
100
105
  if (failed > 0) {
101
106
  warn(
102
- `${failed} skill install(s) failed — re-run sync or install manually with: npx skills add <slug> -g -y -a claude-code codex`,
107
+ `${failed} skill install(s) failed — re-run sync or install manually with: npx --yes ${skillsCli(ctx)} add <slug> -g -y -a claude-code codex`,
103
108
  );
104
109
  }
105
110
  }
@@ -10,6 +10,7 @@ import {
10
10
  lstatSync,
11
11
  mkdirSync,
12
12
  readlinkSync,
13
+ realpathSync,
13
14
  rmSync,
14
15
  statSync,
15
16
  symlinkSync,
@@ -47,7 +48,7 @@ export function healClaudeSymlink(ctx: Ctx, skillsDir: string, base: string): bo
47
48
  const linkStat = lstat(claudeLink);
48
49
  if (linkStat?.isSymbolicLink() === true) {
49
50
  const current = safeReadlink(claudeLink);
50
- if (current === relTarget) return false;
51
+ if (current === relTarget || pointsAt(claudeLink, canonical)) return false;
51
52
  if (ctx.dryRun) {
52
53
  echo(
53
54
  `[dry-run] would replace stale Claude symlink: ~/.claude/skills/${base} -> ${current} (correct: ${relTarget})`,
@@ -134,6 +135,18 @@ function safeReadlink(path: string): string {
134
135
  }
135
136
  }
136
137
 
138
+ /**
139
+ * True when `link` resolves to `target`. A junction stores an absolute target,
140
+ * so the link text never equals the relative form that a symlink uses.
141
+ */
142
+ function pointsAt(link: string, target: string): boolean {
143
+ try {
144
+ return realpathSync.native(link) === realpathSync.native(target);
145
+ } catch {
146
+ return false;
147
+ }
148
+ }
149
+
137
150
  /** Remove a symlink without touching a real directory. */
138
151
  export function removeLink(path: string): boolean {
139
152
  try {
@@ -14,3 +14,23 @@ export function normalizeManifest(content: string): Array<string> {
14
14
  }
15
15
  return out;
16
16
  }
17
+
18
+ /**
19
+ * The directory the skills CLI installs for a manifest slug. The CLI names a
20
+ * skill directory after the skill. It reads `@<skill>` only in the
21
+ * `<owner>/<repo>@<skill>` form (skills@1.7.0 parseSource), so an `@` in a local
22
+ * path or URL stays part of the name. Any other slug means one skill named after
23
+ * its last path segment. The name goes through the CLI's `sanitizeName` rule.
24
+ */
25
+ export function skillBase(slug: string): string {
26
+ const selector = /^[^/]+\/[^/@]+@(.+)$/.exec(slug)?.[1];
27
+ const nativeForm = !slug.includes(":") && !slug.startsWith(".") && !slug.startsWith("/");
28
+ const name =
29
+ selector !== undefined && nativeForm ? selector : slug.slice(slug.lastIndexOf("/") + 1);
30
+ const sanitized = name
31
+ .toLowerCase()
32
+ .replace(/[^a-z0-9._]+/g, "-")
33
+ .replace(/^[.-]+|[.-]+$/g, "")
34
+ .slice(0, 255);
35
+ return sanitized === "" ? "unnamed-skill" : sanitized;
36
+ }
@@ -2,27 +2,35 @@
2
2
  * EngineNative kit-managed skill prune (`--prune` reconcile against the
3
3
  * snapshot) and snapshot write. Split from skillsSync.ts; the orchestration
4
4
  * still lives there.
5
+ *
6
+ * The prune deletes only what the kit created: the canonical skill directory
7
+ * and the kit-managed Claude entry. It does not call `skills remove`, because
8
+ * that command deletes the same-named directory of every known agent.
5
9
  */
6
- import { existsSync, mkdirSync, readFileSync } from "node:fs";
7
- import { p, spawnProcess, writeTextIfChanged } from "./exec";
10
+ import { existsSync, mkdirSync, readFileSync, rmSync } from "node:fs";
11
+ import { p, writeTextIfChanged } from "./exec";
8
12
  import type { Ctx } from "./index";
9
13
  import { compareCodepoints } from "./jq";
10
- import { skillsCli } from "./skillsInstall";
11
14
  import { isKitOwnedCopy, lstat, removeKitOwnedCopy, removeLink } from "./skillsLinks";
12
- import { normalizeManifest } from "./skillsManifest";
15
+ import { normalizeManifest, skillBase } from "./skillsManifest";
13
16
 
14
17
  // ----------------------------------------------------- prune + snapshot ----
15
18
 
16
- function readSlugs(file: string): Array<string> {
19
+ export function readSlugs(file: string): Array<string> {
17
20
  return existsSync(file) ? normalizeManifest(readFileSync(file, "utf8")) : [];
18
21
  }
19
22
 
20
- export async function reconcileRemovals(
21
- ctx: Ctx,
22
- manifest: string,
23
- snapshot: string,
24
- ): Promise<Array<string>> {
25
- const { change, clearProgress, echo, progress, warn } = ctx.services.logger;
23
+ function removeCanonical(path: string): boolean {
24
+ try {
25
+ rmSync(path, { recursive: true, force: true });
26
+ return true;
27
+ } catch {
28
+ return lstat(path) === undefined;
29
+ }
30
+ }
31
+
32
+ export function reconcileRemovals(ctx: Ctx, manifest: string, snapshot: string): Array<string> {
33
+ const { change, echo, warn } = ctx.services.logger;
26
34
  if (!existsSync(snapshot)) {
27
35
  if (ctx.dryRun) {
28
36
  echo(
@@ -33,14 +41,18 @@ export async function reconcileRemovals(
33
41
  }
34
42
 
35
43
  const current = normalizeManifest(manifest);
36
- const currentBases = new Set(current.map((slug) => slug.slice(slug.lastIndexOf("/") + 1)));
44
+ const currentBases = new Set(current.map(skillBase));
37
45
  let removed = 0;
38
46
  let failed = 0;
39
47
  const failedSlugs: Array<string> = [];
40
48
  for (const slug of readSlugs(snapshot)) {
41
49
  if (current.includes(slug)) continue;
42
- const base = slug.slice(slug.lastIndexOf("/") + 1);
50
+ const base = skillBase(slug);
43
51
  if (currentBases.has(base)) continue;
52
+ const canonical = p(ctx.agentsDir, "skills", base);
53
+ // The skills CLI installs a canonical skill as a real directory that holds SKILL.md.
54
+ const installedCanonical =
55
+ lstat(canonical)?.isDirectory() === true && existsSync(p(canonical, "SKILL.md"));
44
56
  const claudeEntry = p(ctx.home, ".claude", "skills", base);
45
57
  const managedClaudeEntry =
46
58
  lstat(claudeEntry)?.isSymbolicLink() === true || isKitOwnedCopy(claudeEntry);
@@ -51,16 +63,7 @@ export async function reconcileRemovals(
51
63
  }
52
64
  continue;
53
65
  }
54
- progress(`Removing universal skill ${base}...`);
55
- const res = await spawnProcess(
56
- "npx",
57
- ["--yes", skillsCli(ctx), "remove", "--global", base, "-y"],
58
- {
59
- stdio: "ignore",
60
- },
61
- );
62
- clearProgress();
63
- if (res.error !== undefined || res.exitCode !== 0) {
66
+ if (installedCanonical && !removeCanonical(canonical)) {
64
67
  warn(`Failed to remove kit-managed skill: ${base}`);
65
68
  failed++;
66
69
  failedSlugs.push(slug);
@@ -87,21 +90,25 @@ export async function reconcileRemovals(
87
90
  }
88
91
  if (failed > 0)
89
92
  warn(
90
- `${failed} skill remove(s) failed — re-run with --prune or run: npx skills remove --global <name> -y`,
93
+ `${failed} skill remove(s) failed — re-run with --prune, or delete ~/.agents/skills/<name> and the ~/.claude/skills/<name> link manually`,
91
94
  );
92
95
  return failedSlugs;
93
96
  }
94
97
 
98
+ /**
99
+ * Writes the declared slugs plus `retainedSlugs`. A slug leaves the snapshot
100
+ * only after a successful --prune removes it.
101
+ */
95
102
  export function updateSnapshot(
96
103
  ctx: Ctx,
97
104
  manifest: string,
98
105
  snapshot: string,
99
- failedRemovals: ReadonlyArray<string>,
106
+ retainedSlugs: ReadonlyArray<string>,
100
107
  ): void {
101
108
  if (ctx.dryRun) return;
102
109
 
103
110
  mkdirSync(ctx.agentsDir, { recursive: true });
104
- const sorted = [...new Set([...normalizeManifest(manifest), ...failedRemovals])].sort(
111
+ const sorted = [...new Set([...normalizeManifest(manifest), ...retainedSlugs])].sort(
105
112
  compareCodepoints,
106
113
  );
107
114
  writeTextIfChanged(snapshot, sorted.length > 0 ? `${sorted.join("\n")}\n` : "");
@@ -14,7 +14,7 @@ import { payloadText } from "../payload";
14
14
  import { p } from "./exec";
15
15
  import type { Ctx } from "./index";
16
16
  import { syncUniversal, type SkillsState } from "./skillsInstall";
17
- import { reconcileRemovals, updateSnapshot } from "./skillsPrune";
17
+ import { readSlugs, reconcileRemovals, updateSnapshot } from "./skillsPrune";
18
18
 
19
19
  export type { SkillsState } from "./skillsInstall";
20
20
  export { COPY_MARKER, linkOrCopy, type LinkOutcome } from "./skillsLinks";
@@ -29,8 +29,11 @@ export async function skillsSync(ctx: Ctx): Promise<SkillsState> {
29
29
  if (!ctx.dryRun) mkdirSync(skillsDir, { recursive: true });
30
30
 
31
31
  await syncUniversal(ctx, state, skillsDir, manifest);
32
- const failedRemovals = ctx.prune ? await reconcileRemovals(ctx, manifest, snapshot) : [];
33
- updateSnapshot(ctx, manifest, snapshot, failedRemovals);
32
+ // A tracked slug leaves the snapshot only after a successful --prune removes it.
33
+ const retainedSlugs = ctx.prune
34
+ ? reconcileRemovals(ctx, manifest, snapshot)
35
+ : readSlugs(snapshot);
36
+ updateSnapshot(ctx, manifest, snapshot, retainedSlugs);
34
37
  return state;
35
38
  }
36
39
 
@@ -6,6 +6,7 @@
6
6
  */
7
7
  import { payloadText } from "../payload";
8
8
  import { claudeNextSteps, claudeSummary, claudeSync, type ClaudeRuntimeState } from "./claudeSync";
9
+ import { preflightClaudeSettings } from "./claudeSettings";
9
10
  import { codexNextSteps, codexSummary, codexSync } from "./codexSync";
10
11
  import type { Ctx } from "./index";
11
12
  import { ompNextSteps, ompSummary, ompSync, type OmpState } from "./ompSync";
@@ -35,6 +36,8 @@ export async function engineSync(ctx: Ctx, args: ReadonlyArray<string>): Promise
35
36
  err("DOCKS_KIT_SYNC_CONCURRENCY must be 1, 2, or 3");
36
37
  throw new ExitError(2);
37
38
  }
39
+ // An abort-class check runs before any pipeline starts, so the abort stops the whole sync.
40
+ preflightClaudeSettings(ctx);
38
41
 
39
42
  type PipelineResult =
40
43
  | { readonly kind: "claude"; readonly runtime: ClaudeRuntimeState }
@@ -86,20 +89,26 @@ export async function engineSync(ctx: Ctx, args: ReadonlyArray<string>): Promise
86
89
  const remaining = new Set(selected.map(({ name }) => name));
87
90
  const lease = acquireTerminal(`Syncing ${[...remaining].join(", ")}...`);
88
91
  ctx.terminalLease = lease;
92
+ const tasks = selected.map(({ name, run }): SyncTask<PipelineResult> => async () => {
93
+ try {
94
+ return await run();
95
+ } finally {
96
+ remaining.delete(name);
97
+ if (remaining.size > 0) lease.update(`Syncing ${[...remaining].join(", ")}...`);
98
+ }
99
+ });
89
100
  let results: Array<PipelineResult>;
90
101
  try {
91
- const tasks = selected.map(({ name, run }): SyncTask<PipelineResult> => async () => {
92
- try {
93
- return await run();
94
- } finally {
95
- remaining.delete(name);
96
- if (remaining.size > 0) lease.update(`Syncing ${[...remaining].join(", ")}...`);
97
- }
98
- });
99
- results = await runBounded(tasks, ctx.syncConcurrency);
100
- } finally {
101
- lease.release();
102
- ctx.terminalLease = undefined;
102
+ try {
103
+ results = await runBounded(tasks, ctx.syncConcurrency);
104
+ } finally {
105
+ lease.release();
106
+ ctx.terminalLease = undefined;
107
+ }
108
+ } catch (error) {
109
+ // A rejected pipeline skips the summary. Print the failures that the other pipelines recorded.
110
+ printFailures(ctx);
111
+ throw error;
103
112
  }
104
113
 
105
114
  const claudeRan = ctx.syncClaude;
@@ -131,11 +140,16 @@ export async function engineSync(ctx: Ctx, args: ReadonlyArray<string>): Promise
131
140
  echo("");
132
141
  for (const line of advice) echo(line);
133
142
  }
134
- if (ctx.failures.length > 0) {
135
- echo("");
136
- echo("--- Failures ---");
137
- for (const failure of ctx.failures) echo(`- ${failure}`);
138
- return 1;
139
- }
143
+ if (printFailures(ctx)) return 1;
140
144
  return 0;
141
145
  }
146
+
147
+ /** Print the `--- Failures ---` ledger. Returns true when the ledger has entries. */
148
+ function printFailures(ctx: Ctx): boolean {
149
+ const { echo } = ctx.services.logger;
150
+ if (ctx.failures.length === 0) return false;
151
+ echo("");
152
+ echo("--- Failures ---");
153
+ for (const failure of ctx.failures) echo(`- ${failure}`);
154
+ return true;
155
+ }