docks-kit 0.22.12 → 0.22.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/AGENTS.md +95 -81
  2. package/README.md +7 -7
  3. package/cli/docs/command-guards.md +7 -3
  4. package/cli/docs/flags.md +59 -9
  5. package/cli/docs/install.md +2 -2
  6. package/cli/docs/omp-context.md +14 -8
  7. package/cli/docs/omp-models.md +1 -1
  8. package/cli/docs/overview.md +1 -1
  9. package/cli/docs/platforms.md +4 -2
  10. package/cli/docs/plugins.md +8 -5
  11. package/cli/docs/sync-layers.md +29 -15
  12. package/cli/docs/toolchain.md +24 -14
  13. package/cli/src/argv.ts +7 -4
  14. package/cli/src/argvValidate.ts +2 -16
  15. package/cli/src/commands/docs.ts +1 -1
  16. package/cli/src/commands/omp.ts +56 -15
  17. package/cli/src/commands/sync.ts +6 -6
  18. package/cli/src/commands/tidy.ts +83 -26
  19. package/cli/src/engine-native/DESIGN.md +93 -56
  20. package/cli/src/engine-native/atomicWrite.ts +168 -8
  21. package/cli/src/engine-native/codexConfig.ts +2 -6
  22. package/cli/src/engine-native/codexPlugins.ts +1 -1
  23. package/cli/src/engine-native/codexSync.ts +137 -26
  24. package/cli/src/engine-native/codexToml.ts +4 -86
  25. package/cli/src/engine-native/deps.ts +51 -51
  26. package/cli/src/engine-native/exec.ts +3 -0
  27. package/cli/src/engine-native/index.ts +1 -1
  28. package/cli/src/engine-native/kitLock.ts +121 -0
  29. package/cli/src/engine-native/modes.ts +49 -31
  30. package/cli/src/engine-native/ompChild.ts +26 -0
  31. package/cli/src/engine-native/ompFastMode.ts +14 -7
  32. package/cli/src/engine-native/ompFileDeploy.ts +12 -6
  33. package/cli/src/engine-native/ompMarketplace.ts +25 -18
  34. package/cli/src/engine-native/ompPlugins.ts +39 -18
  35. package/cli/src/engine-native/ompRemovals.ts +51 -23
  36. package/cli/src/engine-native/ompSync.ts +78 -38
  37. package/cli/src/engine-native/os/targets.ts +16 -4
  38. package/cli/src/engine-native/os/types.ts +1 -1
  39. package/cli/src/engine-native/parseArgs.ts +27 -17
  40. package/cli/src/engine-native/processes.ts +16 -0
  41. package/cli/src/engine-native/scratch.ts +18 -0
  42. package/cli/src/engine-native/skillsInstall.ts +27 -2
  43. package/cli/src/engine-native/skillsPrune.ts +51 -49
  44. package/cli/src/engine-native/skillsRecords.ts +138 -0
  45. package/cli/src/engine-native/skillsSync.ts +16 -13
  46. package/cli/src/engine-native/syncDispatch.ts +186 -4
  47. package/cli/src/engine-native/tidy.ts +102 -119
  48. package/cli/src/engine-native/tomlLines.ts +92 -0
  49. package/cli/src/generated/sotPayload.ts +5 -5
  50. package/cli/src/main.ts +5 -30
  51. package/cli/src/manifests.ts +24 -4
  52. package/package.json +2 -2
  53. package/cli/src/engine-native/tidyLock.ts +0 -163
@@ -2,7 +2,8 @@
2
2
  * EngineNative `sync omp` pipeline. config.yml merges through mergeOmpConfig
3
3
  * and models.yml through mergeOmpModels. Both preserve user-only keys.
4
4
  * Paths come from ompPaths because profiles, PI_CONFIG_DIR,
5
- * PI_CODING_AGENT_DIR, and XDG roots each move them.
5
+ * PI_CODING_AGENT_DIR, and XDG roots each move them. `runSync` resolves them
6
+ * once, before it takes the folder locks, and the pipeline writes only there.
6
7
  * Resolution stays within the environment and filesystem probes so no omp
7
8
  * subcommand runs under ctx.dryRun.
8
9
  *
@@ -15,8 +16,9 @@ import { isAbsolute, resolve } from "node:path";
15
16
 
16
17
  import { bunBootstrap } from "./bun";
17
18
  import { p } from "./exec";
19
+ import { recordFailure } from "./failures";
18
20
  import type { Ctx } from "./index";
19
- import { ompPaths } from "./ompPaths";
21
+ import { ompPaths, type OmpPaths } from "./ompPaths";
20
22
  import { mergeOmpConfig, mergeOmpModels } from "./ompYaml";
21
23
  import { ensureDirectory, syncMergedYaml, syncWholeFile } from "./ompFileDeploy";
22
24
  import { syncKitPlugin } from "./ompKitPlugin";
@@ -26,16 +28,49 @@ import { syncOmpModelRemovals, syncOmpRemovals } from "./ompRemovals";
26
28
 
27
29
  export interface OmpState {
28
30
  readonly pluginsInstalled: number;
31
+ /** The omp agent folder that the sync wrote. */
32
+ readonly agentDir: string;
29
33
  }
30
34
 
31
- export async function ompSync(ctx: Ctx): Promise<OmpState> {
32
- await bunBootstrap(ctx, ctx.services);
35
+ /** The omp folders that a sync writes. */
36
+ export interface OmpWriteFolders {
37
+ readonly paths: OmpPaths;
38
+ /** The folder of the pi-intercom `config.json`. */
39
+ readonly intercomDir: string;
40
+ }
33
41
 
42
+ /**
43
+ * Resolve the omp paths and the intercom folder of this run. `runSync` calls
44
+ * it once, takes a folder lock in each folder, and gives the result to
45
+ * `ompSync`. A second resolution could pick an XDG data root that another
46
+ * sync created after the locks.
47
+ */
48
+ export function ompWriteFolders(ctx: Ctx): OmpWriteFolders {
34
49
  const paths = ompPaths({
35
50
  home: ctx.home,
36
51
  env: process.env,
37
52
  platform: ctx.services.platform.raw(),
38
53
  });
54
+ // omp exports PI_CODING_AGENT_DIR as the agent directory of a named profile,
55
+ // and pi-intercom reads the trimmed value. Without a profile, the kit uses
56
+ // the PI_CODING_AGENT_DIR value when it is set, else ~/.pi/agent.
57
+ const intercomRootSetting = process.env["PI_CODING_AGENT_DIR"]?.trim();
58
+ const intercomRoot =
59
+ paths.profile !== undefined
60
+ ? paths.agentDir
61
+ : intercomRootSetting !== undefined && intercomRootSetting !== ""
62
+ ? isAbsolute(intercomRootSetting)
63
+ ? intercomRootSetting
64
+ : resolve(process.cwd(), intercomRootSetting)
65
+ : p(ctx.home, ".pi", "agent");
66
+ return { paths, intercomDir: p(intercomRoot, "intercom") };
67
+ }
68
+
69
+ /** Run the omp pipeline in `folders`, the folders that `runSync` resolved and locked. */
70
+ export async function ompSync(ctx: Ctx, folders: OmpWriteFolders): Promise<OmpState> {
71
+ await bunBootstrap(ctx, ctx.services);
72
+
73
+ const { paths, intercomDir } = folders;
39
74
  const agentDir = paths.agentDir;
40
75
  if (!ctx.dryRun) ensureDirectory(agentDir);
41
76
 
@@ -53,25 +88,14 @@ export async function ompSync(ctx: Ctx): Promise<OmpState> {
53
88
  "omp mcp.json already in sync",
54
89
  "omp mcp.json synced",
55
90
  );
56
- syncMergedYaml(ctx, "SoT/.omp/config.yml", p(agentDir, "config.yml"), mergeOmpConfig);
91
+ const configFile = p(agentDir, "config.yml");
92
+ const configBackedUp = syncMergedYaml(ctx, "SoT/.omp/config.yml", configFile, mergeOmpConfig);
57
93
  // mergeOmpConfig is additive, so the prune must run on the merged result.
58
- syncOmpRemovals(ctx, p(agentDir, "config.yml"));
59
- syncMergedYaml(ctx, "SoT/.omp/models.yml", p(agentDir, "models.yml"), mergeOmpModels);
60
- syncOmpModelRemovals(ctx, p(agentDir, "models.yml"));
94
+ syncOmpRemovals(ctx, configFile, configBackedUp);
95
+ const modelsFile = p(agentDir, "models.yml");
96
+ const modelsBackedUp = syncMergedYaml(ctx, "SoT/.omp/models.yml", modelsFile, mergeOmpModels);
97
+ syncOmpModelRemovals(ctx, modelsFile, modelsBackedUp);
61
98
 
62
- // omp exports PI_CODING_AGENT_DIR as the agent directory of a named profile,
63
- // and pi-intercom reads the trimmed value. Without a profile, the kit uses
64
- // the PI_CODING_AGENT_DIR value when it is set, else ~/.pi/agent.
65
- const intercomRootSetting = process.env["PI_CODING_AGENT_DIR"]?.trim();
66
- const intercomRoot =
67
- paths.profile !== undefined
68
- ? paths.agentDir
69
- : intercomRootSetting !== undefined && intercomRootSetting !== ""
70
- ? isAbsolute(intercomRootSetting)
71
- ? intercomRootSetting
72
- : resolve(process.cwd(), intercomRootSetting)
73
- : p(ctx.home, ".pi", "agent");
74
- const intercomDir = p(intercomRoot, "intercom");
75
99
  if (!ctx.dryRun) ensureDirectory(intercomDir);
76
100
  syncWholeFile(
77
101
  ctx,
@@ -83,33 +107,49 @@ export async function ompSync(ctx: Ctx): Promise<OmpState> {
83
107
  // The plugin pass links this directory, so the files must exist first.
84
108
  syncKitPlugin(ctx);
85
109
 
86
- const legacyRegistryFile =
87
- paths.dataRoot === paths.configRoot ? undefined : p(paths.configRoot, "marketplaces.json");
88
- await syncMarketplace(ctx, p(paths.dataRoot, "marketplaces.json"), legacyRegistryFile);
89
- const pluginsInstalled = await syncPlugins(ctx);
90
- return { pluginsInstalled };
110
+ await syncMarketplace(ctx, paths);
111
+ const pluginsInstalled = await syncPlugins(ctx, paths);
112
+
113
+ // omp adopts `$XDG_DATA_HOME/omp` once it exists. When another sync created
114
+ // it during this run, a later omp process uses that root and does not see
115
+ // the plugins of the locked root. The next sync locks and fills the new root.
116
+ if (!ctx.dryRun) {
117
+ const currentRoot = ompPaths({
118
+ home: ctx.home,
119
+ env: process.env,
120
+ platform: ctx.services.platform.raw(),
121
+ }).dataRoot;
122
+ if (currentRoot !== paths.dataRoot) {
123
+ recordFailure(
124
+ ctx,
125
+ `omp data root moved to ${currentRoot} during the sync; run docks-kit sync again`,
126
+ );
127
+ }
128
+ }
129
+ return { pluginsInstalled, agentDir };
91
130
  }
92
131
 
93
132
  // -------------------------------------------------------------- summary ----
94
133
 
95
134
  export function ompSummary(ctx: Ctx, state: OmpState): void {
96
135
  const { echo } = ctx.services.logger;
97
- const agentDir = ompPaths({
98
- home: ctx.home,
99
- env: process.env,
100
- platform: ctx.services.platform.raw(),
101
- }).agentDir;
102
- echo(`omp: ${agentDir}`);
136
+ echo(`omp: ${state.agentDir}`);
103
137
  if (!ctx.dryRun) echo(`omp plugins: ${state.pluginsInstalled} installed`);
104
138
  }
105
139
 
140
+ /**
141
+ * The omp next steps. The upgrade rule and the restart advice are independent,
142
+ * because a sync can upgrade a plugin and also change a file that needs a restart.
143
+ */
106
144
  export function ompNextSteps(ctx: Ctx): Array<string> {
145
+ const steps: Array<string> = [];
107
146
  if (ctx.nextStepTriggers.ompPluginUpgraded) {
108
- return [
109
- "Restart running omp sessions: a plugin upgrade removed the plugin folders that they loaded.",
110
- ];
147
+ steps.push(
148
+ "Run /reload-plugins in each running omp session, then read each plugin skill again through skill://. Restart omp instead when an upgraded plugin ships hooks, extension modules, or non-MCP tools.",
149
+ );
150
+ }
151
+ if (ctx.verbose || ctx.nextStepTriggers.ompRestart) {
152
+ steps.push("Restart omp to load any refreshed plugins, skills, or tools.");
111
153
  }
112
- return ctx.verbose || ctx.nextStepTriggers.ompRestart
113
- ? ["Restart omp to load any refreshed plugins, skills, or tools."]
114
- : [];
154
+ return steps;
115
155
  }
@@ -1,8 +1,20 @@
1
1
  /**
2
- * Host-to-artifact map (Platform seam in DESIGN.md). Every launcher, installer,
3
- * build script, and release workflow selects a compiled binary from this one
4
- * table; cli/test/unit/hostTargets.test.ts parses those scripts and fails when
5
- * any of them drifts from it.
2
+ * Host-to-artifact map (Platform seam in DESIGN.md). The two launchers select
3
+ * a compiled binary from this table, `cli/build-binaries.sh` builds its
4
+ * targets, and `release-cli.yml` publishes its artifacts. Each of these files
5
+ * lists the names by hand, so `cli/test/unit/hostTargets.test.ts` checks them
6
+ * against this table:
7
+ * - the artifact names and `uname` keys in the Bash launcher `docks-kit`;
8
+ * - the artifact name and processor architecture in `docks-kit.ps1`;
9
+ * - the default `TARGETS` list of `cli/build-binaries.sh`;
10
+ * - the four artifact names in each of the two lists of
11
+ * `.github/workflows/release-cli.yml`: the `with.path` list of the
12
+ * `actions/upload-artifact` step in job `build`, and the `for asset in`
13
+ * list of the `gh release upload` step in job `github-release`.
14
+ * The same test also checks two facts outside this table: the generated Bun
15
+ * pin in the two launchers and the two installers equals the
16
+ * `SoT/toolchain.json` pin, and `docks-kit.ps1` and `install.ps1` hold only
17
+ * ASCII bytes.
6
18
  *
7
19
  * Membership here is the support matrix: adding a row is how a host becomes
8
20
  * supported, and `requireSupportedHost` in cli/src/engine.ts admits exactly the
@@ -54,7 +54,7 @@ export interface HostOs {
54
54
  readonly toolchainOs: string;
55
55
  /** Bubblewrap is the Linux-only Codex sandbox runtime. */
56
56
  readonly supportsBubblewrap: boolean;
57
- /** Directory-link mechanisms tried in order before `skillsSync.ts linkOrCopy` copies. */
57
+ /** Directory-link mechanisms tried in order before `skillsLinks.ts linkOrCopy` copies. */
58
58
  readonly directoryLinkKinds: ReadonlyArray<DirectoryLinkKind>;
59
59
  /** One-line install command for a tool whose package differs per OS. */
60
60
  readonly installHint: (tool: HintedTool) => string;
@@ -36,6 +36,32 @@ const TARGET_FLAGS = {
36
36
  omp: "syncOmp",
37
37
  } satisfies Record<Harness, TargetFlag>;
38
38
 
39
+ /**
40
+ * The rename hint for each retired sync flag. The engine prints it here, and
41
+ * the public CLI layer (`argvValidate.ts`) rejects the same flag with the same
42
+ * text, so the two paths cannot drift.
43
+ */
44
+ export const LEGACY_FLAG_HINTS = {
45
+ "--claude": "--claude was renamed: pass the target as a word, e.g. 'sync claude'",
46
+ "--codex": "--codex was renamed: pass the target as a word, e.g. 'sync codex'",
47
+ "--agents": "--agents was renamed: pass the target as a word, e.g. 'sync agents'",
48
+ "--omp": "--omp was renamed: pass the target as a word, e.g. 'sync omp'",
49
+ "--force": "--force was renamed to --reconcile",
50
+ "--remove-plugins":
51
+ "--remove-plugins was renamed to --prune (it also removes marketplaces + kit-managed skills)",
52
+ "--680k": "--680k was renamed to --claude-compact-window=680k",
53
+ "--permissive": "--permissive was renamed to --claude-permissive",
54
+ "--supabase": "--supabase was renamed to --claude-plugin=supabase",
55
+ "--n8n": "--n8n was renamed to --claude-plugin=n8n",
56
+ "--skip-rtk": "--skip-rtk was renamed to --skip-bubblewrap",
57
+ } as const satisfies Record<string, string>;
58
+
59
+ type LegacyFlag = keyof typeof LEGACY_FLAG_HINTS;
60
+
61
+ /** Own-key check, so a word such as `constructor` never reads an Object prototype member. */
62
+ export const isLegacyFlag = (flag: string): flag is LegacyFlag =>
63
+ Object.hasOwn(LEGACY_FLAG_HINTS, flag);
64
+
39
65
  function selectTarget(ctx: Ctx, target: Harness): void {
40
66
  ctx[TARGET_FLAGS[target]] = true;
41
67
  ctx.targetFilterSet = true;
@@ -131,30 +157,14 @@ export function parseArgs(ctx: Ctx, args: ReadonlyArray<string>): void {
131
157
  case "--codex":
132
158
  case "--agents":
133
159
  case "--omp":
134
- err(`${arg} was renamed: pass the target as a word, e.g. 'sync ${arg.slice(2)}'`);
135
- throw new ExitError(2);
136
160
  case "--force":
137
- err("--force was renamed to --reconcile");
138
- throw new ExitError(2);
139
161
  case "--remove-plugins":
140
- err(
141
- "--remove-plugins was renamed to --prune (it also removes marketplaces + kit-managed skills)",
142
- );
143
- throw new ExitError(2);
144
162
  case "--680k":
145
- err("--680k was renamed to --claude-compact-window=680k");
146
- throw new ExitError(2);
147
163
  case "--permissive":
148
- err("--permissive was renamed to --claude-permissive");
149
- throw new ExitError(2);
150
164
  case "--supabase":
151
- err("--supabase was renamed to --claude-plugin=supabase");
152
- throw new ExitError(2);
153
165
  case "--n8n":
154
- err("--n8n was renamed to --claude-plugin=n8n");
155
- throw new ExitError(2);
156
166
  case "--skip-rtk":
157
- err("--skip-rtk was renamed to --skip-bubblewrap");
167
+ err(LEGACY_FLAG_HINTS[arg]);
158
168
  throw new ExitError(2);
159
169
  case "-h":
160
170
  case "--help":
@@ -0,0 +1,16 @@
1
+ /** Checks on other processes by PID. */
2
+
3
+ /**
4
+ * True only when no process has `pid`: `process.kill(pid, 0)` throws ESRCH.
5
+ * A live process, a process of another user (EPERM), and every other error
6
+ * give false. So a caller that removes the files of an exited process keeps
7
+ * them when it is not sure.
8
+ */
9
+ export function processExited(pid: number): boolean {
10
+ try {
11
+ process.kill(pid, 0);
12
+ return false;
13
+ } catch (cause) {
14
+ return typeof cause === "object" && cause !== null && "code" in cause && cause.code === "ESRCH";
15
+ }
16
+ }
@@ -24,6 +24,24 @@ export function kitCacheDir(home: string): string {
24
24
  return p(home, ".cache", "docks-kit");
25
25
  }
26
26
 
27
+ /** The `kitLock.ts` lock that `docks-kit tidy --apply` holds while it plans and applies. */
28
+ export function tidyApplyLockPath(home: string): string {
29
+ return join(kitCacheDir(home), "tidy-lock.db");
30
+ }
31
+
32
+ /** The `kitLock.ts` lock that `docks-kit sync` and `docks-kit model` hold while they write. */
33
+ export function syncLockPath(home: string): string {
34
+ return join(kitCacheDir(home), "sync-lock.db");
35
+ }
36
+
37
+ /**
38
+ * The `kitLock.ts` lock inside a Codex, agents, or omp folder that a sync
39
+ * writes. Syncs of different homes that share the folder all take it.
40
+ */
41
+ export function folderSyncLockPath(folder: string): string {
42
+ return join(folder, ".docks-kit-sync-lock.db");
43
+ }
44
+
27
45
  export function scratchRoot(home: string): string {
28
46
  return p(kitCacheDir(home), "scratch");
29
47
  }
@@ -1,12 +1,23 @@
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.
4
+ * lives there. The pass records a slug as pending before its install only
5
+ * when the canonical directory does not exist (`skillsRecords.ts`). After
6
+ * the install, it moves the slug to the owned record when its directory
7
+ * exists. It writes both records before the next install starts. A canonical
8
+ * directory that existed before is reused and never recorded.
5
9
  */
6
10
  import { p, spawnProcess } from "./exec";
7
11
  import type { Ctx } from "./index";
8
12
  import { ExitError } from "./parseArgs";
9
13
  import { healClaudeSymlink, isDir } from "./skillsLinks";
14
+ import {
15
+ canonicalAbsent,
16
+ recordPendingInstall,
17
+ settlePendingSlug,
18
+ writeSkillRecords,
19
+ type SkillRecords,
20
+ } from "./skillsRecords";
10
21
  import { normalizeManifest, skillBase } from "./skillsManifest";
11
22
  import { field } from "./toolchain";
12
23
 
@@ -29,6 +40,7 @@ export async function syncUniversal(
29
40
  state: SkillsState,
30
41
  skillsDir: string,
31
42
  manifest: string,
43
+ records: SkillRecords,
32
44
  ): Promise<void> {
33
45
  const { change, clearProgress, echo, progress, verbose, warn } = ctx.services.logger;
34
46
  if (ctx.services.deps.probe("npx").state === "missing") {
@@ -60,19 +72,32 @@ export async function syncUniversal(
60
72
 
61
73
  if (isDir(p(skillsDir, base))) {
62
74
  already++;
75
+ if (!records.owned.has(slug) && !records.legacy.has(slug)) {
76
+ warn(
77
+ `Universal skill ${slug}: reused the existing ~/.agents/skills/${base}; the kit did not install it, so --prune keeps it`,
78
+ );
79
+ }
63
80
  if (healClaudeSymlink(ctx, skillsDir, base)) healed++;
64
81
  continue;
65
82
  }
66
83
 
84
+ const cli = skillsCli(ctx);
85
+ const pending = canonicalAbsent(skillsDir, slug);
86
+ if (pending) recordPendingInstall(records, slug);
67
87
  progress(`Installing universal skill ${slug}...`);
68
88
  const res = await spawnProcess(
69
89
  "npx",
70
- ["--yes", skillsCli(ctx), "add", slug, "-g", "-y", "-a", "claude-code", "codex"],
90
+ ["--yes", cli, "add", slug, "-g", "-y", "-a", "claude-code", "codex"],
71
91
  {
72
92
  stdio: "ignore",
73
93
  },
74
94
  );
75
95
  clearProgress();
96
+ if (pending) {
97
+ // The owned record goes first, so a stop between the writes keeps the slug pending.
98
+ settlePendingSlug(records, skillsDir, slug);
99
+ writeSkillRecords(ctx, records);
100
+ }
76
101
  if (res.error === undefined && res.exitCode === 0) {
77
102
  added++;
78
103
  if (!isDir(p(skillsDir, base))) {
@@ -1,24 +1,23 @@
1
1
  /**
2
- * EngineNative kit-managed skill prune (`--prune` reconcile against the
3
- * snapshot) and snapshot write. Split from skillsSync.ts; the orchestration
4
- * still lives there.
2
+ * EngineNative kit skill prune (`--prune` reconcile against the owned record
3
+ * of `skillsRecords.ts`). Split from skillsSync.ts; the orchestration still
4
+ * lives there.
5
5
  *
6
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.
7
+ * of a slug in `.kit-owned-skills` and the kit-managed Claude entry. It
8
+ * removes a canonical directory only while it keeps the `<dev>:<ino>` that
9
+ * the owned record names. It does not call `skills remove`, because that
10
+ * command deletes the same-named directory of every known agent. A slug that
11
+ * only the legacy `.kit-managed-skills` names is kept with a message, because
12
+ * an older kit also recorded directories that the user made.
9
13
  */
10
- import { existsSync, mkdirSync, readFileSync, rmSync } from "node:fs";
11
- import { p, writeTextIfChanged } from "./exec";
14
+ import { existsSync, rmSync } from "node:fs";
15
+ import { p } from "./exec";
12
16
  import type { Ctx } from "./index";
13
17
  import { compareCodepoints } from "./jq";
14
18
  import { isKitOwnedCopy, lstat, removeKitOwnedCopy, removeLink } from "./skillsLinks";
15
19
  import { normalizeManifest, skillBase } from "./skillsManifest";
16
-
17
- // ----------------------------------------------------- prune + snapshot ----
18
-
19
- export function readSlugs(file: string): Array<string> {
20
- return existsSync(file) ? normalizeManifest(readFileSync(file, "utf8")) : [];
21
- }
20
+ import { directoryIdentity, type SkillRecords } from "./skillsRecords";
22
21
 
23
22
  function removeCanonical(path: string): boolean {
24
23
  try {
@@ -29,30 +28,54 @@ function removeCanonical(path: string): boolean {
29
28
  }
30
29
  }
31
30
 
32
- export function reconcileRemovals(ctx: Ctx, manifest: string, snapshot: string): Array<string> {
31
+ /**
32
+ * Removes each owned skill that the SoT no longer declares, and drops it from
33
+ * `records.owned` (in memory). A failed removal keeps the slug, so the next
34
+ * prune tries again. An owned slug whose directory is not the one that the
35
+ * kit installed is kept with a line. It leaves the record, so the line prints
36
+ * once. A legacy slug that the SoT dropped gets a keep line while its
37
+ * canonical path still has an entry. Only the legacy record names it, so the
38
+ * kit keeps it.
39
+ */
40
+ export function reconcileRemovals(ctx: Ctx, manifest: string, records: SkillRecords): void {
33
41
  const { change, echo, warn } = ctx.services.logger;
34
- if (!existsSync(snapshot)) {
35
- if (ctx.dryRun) {
36
- echo(
37
- `[dry-run] (--prune) no kit-managed-skills snapshot yet; first real sync writes ${snapshot}, then future --prune runs reconcile against it`,
38
- );
39
- }
40
- return [];
42
+ if (ctx.dryRun && !existsSync(records.ownedFile)) {
43
+ echo(
44
+ `[dry-run] (--prune) no kit-owned-skills record yet; a sync writes ${records.ownedFile} when it installs a skill, and --prune removes only the skills that it names`,
45
+ );
41
46
  }
42
47
 
43
48
  const current = normalizeManifest(manifest);
44
49
  const currentBases = new Set(current.map(skillBase));
50
+ const declared = (slug: string): boolean =>
51
+ current.includes(slug) || currentBases.has(skillBase(slug));
52
+
53
+ for (const slug of [...records.legacy].sort(compareCodepoints)) {
54
+ if (declared(slug) || records.owned.has(slug)) continue;
55
+ if (lstat(p(ctx.agentsDir, "skills", skillBase(slug))) === undefined) continue;
56
+ warn(
57
+ `keep ${slug}: an older kit recorded it, so the kit cannot prove it installed it; remove it by hand if the kit did`,
58
+ );
59
+ }
60
+
45
61
  let removed = 0;
46
62
  let failed = 0;
47
- const failedSlugs: Array<string> = [];
48
- for (const slug of readSlugs(snapshot)) {
49
- if (current.includes(slug)) continue;
63
+ for (const slug of [...records.owned.keys()].sort(compareCodepoints)) {
64
+ if (declared(slug)) continue;
50
65
  const base = skillBase(slug);
51
- if (currentBases.has(base)) continue;
52
66
  const canonical = p(ctx.agentsDir, "skills", base);
53
- // The skills CLI installs a canonical skill as a real directory that holds SKILL.md.
67
+ // The skills CLI installs a canonical skill as a real directory that holds
68
+ // SKILL.md. A gone directory needs only the Claude entry cleanup.
69
+ const canonicalStat = lstat(canonical);
54
70
  const installedCanonical =
55
- lstat(canonical)?.isDirectory() === true && existsSync(p(canonical, "SKILL.md"));
71
+ canonicalStat?.isDirectory() === true &&
72
+ existsSync(p(canonical, "SKILL.md")) &&
73
+ directoryIdentity(canonical) === records.owned.get(slug);
74
+ if (canonicalStat !== undefined && !installedCanonical) {
75
+ warn(`keep ${slug}: the directory is not the one that the kit installed`);
76
+ if (!ctx.dryRun) records.owned.delete(slug);
77
+ continue;
78
+ }
56
79
  const claudeEntry = p(ctx.home, ".claude", "skills", base);
57
80
  const managedClaudeEntry =
58
81
  lstat(claudeEntry)?.isSymbolicLink() === true || isKitOwnedCopy(claudeEntry);
@@ -66,7 +89,6 @@ export function reconcileRemovals(ctx: Ctx, manifest: string, snapshot: string):
66
89
  if (installedCanonical && !removeCanonical(canonical)) {
67
90
  warn(`Failed to remove kit-managed skill: ${base}`);
68
91
  failed++;
69
- failedSlugs.push(slug);
70
92
  continue;
71
93
  }
72
94
  if (managedClaudeEntry) {
@@ -77,10 +99,10 @@ export function reconcileRemovals(ctx: Ctx, manifest: string, snapshot: string):
77
99
  if (!removedClaudeEntry) {
78
100
  warn(`Failed to remove kit-managed Claude skill entry: ${base}`);
79
101
  failed++;
80
- failedSlugs.push(slug);
81
102
  continue;
82
103
  }
83
104
  }
105
+ records.owned.delete(slug);
84
106
  removed++;
85
107
  }
86
108
 
@@ -92,24 +114,4 @@ export function reconcileRemovals(ctx: Ctx, manifest: string, snapshot: string):
92
114
  warn(
93
115
  `${failed} skill remove(s) failed — re-run with --prune, or delete ~/.agents/skills/<name> and the ~/.claude/skills/<name> link manually`,
94
116
  );
95
- return failedSlugs;
96
- }
97
-
98
- /**
99
- * Writes the declared slugs plus `retainedSlugs`. A slug leaves the snapshot
100
- * only after a successful --prune removes it.
101
- */
102
- export function updateSnapshot(
103
- ctx: Ctx,
104
- manifest: string,
105
- snapshot: string,
106
- retainedSlugs: ReadonlyArray<string>,
107
- ): void {
108
- if (ctx.dryRun) return;
109
-
110
- mkdirSync(ctx.agentsDir, { recursive: true });
111
- const sorted = [...new Set([...normalizeManifest(manifest), ...retainedSlugs])].sort(
112
- compareCodepoints,
113
- );
114
- writeTextIfChanged(snapshot, sorted.length > 0 ? `${sorted.join("\n")}\n` : "");
115
117
  }
@@ -0,0 +1,138 @@
1
+ /**
2
+ * EngineNative skill ownership records under `~/.agents`:
3
+ * - `.kit-pending-skills`, one slug per line: a slug whose install runs. Sync
4
+ * adds it before `npx skills add` only when the canonical skill directory
5
+ * does not exist. So it never names a directory that existed before the
6
+ * install.
7
+ * - `.kit-owned-skills`, one `<slug>\t<dev>:<ino>` line per skill: the skills
8
+ * that the kit installed, with the identity of the directory that the
9
+ * install created. It is the only record that lets `--prune` remove a
10
+ * skill, and only while the directory keeps that identity.
11
+ * - `.kit-managed-skills`: the legacy snapshot. An older kit also recorded
12
+ * directories that the user made there, so sync reads it and never writes
13
+ * it, and its entries never let `--prune` remove a skill.
14
+ *
15
+ * After each install, sync writes the owned record before the slug leaves the
16
+ * pending record, and before the next install starts. So a sync that stops at
17
+ * any point leaves each installed slug in one of the two records. The next
18
+ * sync moves a leftover pending slug to the owned record when its directory
19
+ * exists, and drops it otherwise.
20
+ */
21
+ import { existsSync, lstatSync, readFileSync, rmSync } from "node:fs";
22
+ import { replaceTextIfChanged } from "./atomicWrite";
23
+ import { p } from "./exec";
24
+ import type { Ctx } from "./index";
25
+ import { compareCodepoints } from "./jq";
26
+ import { isDir, lstat } from "./skillsLinks";
27
+ import { normalizeManifest, skillBase } from "./skillsManifest";
28
+
29
+ export interface SkillRecords {
30
+ readonly ownedFile: string;
31
+ readonly pendingFile: string;
32
+ readonly legacyFile: string;
33
+ /** Each owned slug and the `<dev>:<ino>` identity of the directory that its install created. */
34
+ readonly owned: Map<string, string>;
35
+ readonly pending: Set<string>;
36
+ readonly legacy: ReadonlySet<string>;
37
+ }
38
+
39
+ /** The `<dev>:<ino>` identity of the entry at `path`, or undefined when no entry exists. */
40
+ export function directoryIdentity(path: string): string | undefined {
41
+ // bigint keeps a Windows file index exact; a number loses digits above 2^53.
42
+ const stats = lstatSync(path, { bigint: true, throwIfNoEntry: false });
43
+ return stats === undefined ? undefined : `${stats.dev}:${stats.ino}`;
44
+ }
45
+
46
+ function readSlugs(file: string): Set<string> {
47
+ return new Set(existsSync(file) ? normalizeManifest(readFileSync(file, "utf8")) : []);
48
+ }
49
+
50
+ /**
51
+ * Read the owned record. A line with no identity keeps the slug with an empty
52
+ * identity, which matches no directory, so it never lets `--prune` remove one.
53
+ */
54
+ function readOwned(file: string): Map<string, string> {
55
+ const owned = new Map<string, string>();
56
+ if (!existsSync(file)) return owned;
57
+ for (const line of readFileSync(file, "utf8").split("\n")) {
58
+ const [slug = "", identity = ""] = line.trim().split("\t");
59
+ if (slug !== "") owned.set(slug, identity);
60
+ }
61
+ return owned;
62
+ }
63
+
64
+ function slugLines(slugs: ReadonlySet<string>): string {
65
+ const sorted = [...slugs].sort(compareCodepoints);
66
+ return sorted.length > 0 ? `${sorted.join("\n")}\n` : "";
67
+ }
68
+
69
+ function ownedLines(owned: ReadonlyMap<string, string>): string {
70
+ const slugs = [...owned.keys()].sort(compareCodepoints);
71
+ return slugs.map((slug) => `${slug}\t${owned.get(slug) ?? ""}\n`).join("");
72
+ }
73
+
74
+ export function readSkillRecords(agentsDir: string): SkillRecords {
75
+ const ownedFile = p(agentsDir, ".kit-owned-skills");
76
+ const pendingFile = p(agentsDir, ".kit-pending-skills");
77
+ const legacyFile = p(agentsDir, ".kit-managed-skills");
78
+ return {
79
+ ownedFile,
80
+ pendingFile,
81
+ legacyFile,
82
+ owned: readOwned(ownedFile),
83
+ pending: readSlugs(pendingFile),
84
+ legacy: readSlugs(legacyFile),
85
+ };
86
+ }
87
+
88
+ /** True when the canonical skill directory of `slug` has no entry, so an install creates it. */
89
+ export function canonicalAbsent(skillsDir: string, slug: string): boolean {
90
+ return lstat(p(skillsDir, skillBase(slug))) === undefined;
91
+ }
92
+
93
+ /**
94
+ * Ends the pending state of `slug`. When its canonical directory exists, the
95
+ * slug moves to the owned record with the identity of that directory. Else it
96
+ * leaves the pending record. A slug that the owned record already names keeps
97
+ * its identity. A sync that stopped between the two record writes leaves the
98
+ * slug in both records, and the directory can change before the next sync.
99
+ * Changes the records in memory only; `writeSkillRecords` writes them.
100
+ */
101
+ export function settlePendingSlug(records: SkillRecords, skillsDir: string, slug: string): void {
102
+ if (!records.pending.delete(slug) || records.owned.has(slug)) return;
103
+ const canonical = p(skillsDir, skillBase(slug));
104
+ const identity = isDir(canonical) ? directoryIdentity(canonical) : undefined;
105
+ if (identity !== undefined) records.owned.set(slug, identity);
106
+ }
107
+
108
+ /**
109
+ * Records `slug` as pending and writes the pending record before its install
110
+ * starts. The canonical directory is gone, so an owned identity of the slug is
111
+ * stale. It leaves the owned record first, so the install can record the new
112
+ * directory.
113
+ */
114
+ export function recordPendingInstall(records: SkillRecords, slug: string): void {
115
+ if (records.owned.delete(slug)) {
116
+ replaceTextIfChanged(records.ownedFile, ownedLines(records.owned));
117
+ }
118
+ records.pending.add(slug);
119
+ replaceTextIfChanged(records.pendingFile, slugLines(records.pending));
120
+ }
121
+
122
+ /**
123
+ * Writes the owned record, then the pending record, so a sync that stops
124
+ * between the two writes keeps the pending slugs for the next sync. An empty
125
+ * pending record is removed. Writes nothing under dry run.
126
+ */
127
+ export function writeSkillRecords(ctx: Ctx, records: SkillRecords): void {
128
+ if (ctx.dryRun) return;
129
+ const owned = ownedLines(records.owned);
130
+ if (owned !== "" || existsSync(records.ownedFile)) {
131
+ replaceTextIfChanged(records.ownedFile, owned);
132
+ }
133
+ if (records.pending.size > 0) {
134
+ replaceTextIfChanged(records.pendingFile, slugLines(records.pending));
135
+ } else {
136
+ rmSync(records.pendingFile, { force: true });
137
+ }
138
+ }