docks-kit 0.23.0 → 0.24.0

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 (52) hide show
  1. package/AGENTS.md +19 -20
  2. package/README.md +12 -22
  3. package/cli/docs/command-guards.md +5 -3
  4. package/cli/docs/flags.md +11 -29
  5. package/cli/docs/install.md +1 -1
  6. package/cli/docs/omp-context.md +79 -7
  7. package/cli/docs/omp-models.md +18 -12
  8. package/cli/docs/overview.md +5 -8
  9. package/cli/docs/sync-layers.md +12 -11
  10. package/cli/docs/toolchain.md +4 -4
  11. package/cli/src/argv.ts +0 -4
  12. package/cli/src/argvValidate.ts +2 -9
  13. package/cli/src/commands/docs.ts +2 -2
  14. package/cli/src/commands/omp.ts +1 -1
  15. package/cli/src/commands/scratch.ts +1 -1
  16. package/cli/src/commands/sync.ts +3 -24
  17. package/cli/src/commands/tidy.ts +1 -1
  18. package/cli/src/engine-native/DESIGN.md +21 -31
  19. package/cli/src/engine-native/deps.ts +2 -7
  20. package/cli/src/engine-native/engineCtx.ts +3 -28
  21. package/cli/src/engine-native/index.ts +2 -2
  22. package/cli/src/engine-native/kitDb.ts +21 -37
  23. package/cli/src/engine-native/ompFastMode.ts +1 -1
  24. package/cli/src/engine-native/ompOverlay.ts +1 -1
  25. package/cli/src/engine-native/ompRemovals.ts +24 -3
  26. package/cli/src/engine-native/ompSession.ts +67 -0
  27. package/cli/src/engine-native/ompSync.ts +1 -1
  28. package/cli/src/engine-native/os/posix.ts +0 -1
  29. package/cli/src/engine-native/os/types.ts +0 -4
  30. package/cli/src/engine-native/os/windows.ts +0 -1
  31. package/cli/src/engine-native/parseArgs.ts +1 -61
  32. package/cli/src/engine-native/parseHelp.ts +1 -6
  33. package/cli/src/engine-native/scratch.ts +1 -1
  34. package/cli/src/engine-native/sharedTypes.d.ts +1 -1
  35. package/cli/src/engine-native/syncConcurrency.ts +3 -3
  36. package/cli/src/engine-native/syncDispatch.ts +26 -92
  37. package/cli/src/engine-native/toolchain.ts +1 -5
  38. package/cli/src/generated/sotPayload.ts +6 -8
  39. package/cli/src/main.ts +3 -7
  40. package/package.json +2 -2
  41. package/cli/src/checklistPrompt.ts +0 -464
  42. package/cli/src/commands/harnesses.ts +0 -77
  43. package/cli/src/commands/skills.ts +0 -40
  44. package/cli/src/engine-native/harnesses.ts +0 -138
  45. package/cli/src/engine-native/skillsInstall.ts +0 -135
  46. package/cli/src/engine-native/skillsLinks.ts +0 -216
  47. package/cli/src/engine-native/skillsManifest.ts +0 -36
  48. package/cli/src/engine-native/skillsPrune.ts +0 -117
  49. package/cli/src/engine-native/skillsRecords.ts +0 -138
  50. package/cli/src/engine-native/skillsSync.ts +0 -57
  51. package/cli/src/manifests.ts +0 -53
  52. package/cli/src/terminalCells.ts +0 -191
@@ -1,138 +0,0 @@
1
- /**
2
- * Per-machine harness selection and omp session model, stored in ~/.docks-kit/kit.db (kitDb.ts).
3
- * A missing or unreadable store is represented by undefined so callers
4
- * resolve it to DEFAULT_SELECTION.
5
- */
6
- import { homedir } from "node:os";
7
-
8
- import { inTransaction, isNonBlankString, nonBlankOrNull, withKitDb } from "./kitDb";
9
- import type { OmpSessionModel } from "./sharedTypes";
10
-
11
- export type Harness = "agents" | "omp";
12
-
13
- export const HARNESSES: ReadonlyArray<Harness> = ["agents", "omp"];
14
- export const DEFAULT_SELECTION: ReadonlyArray<Harness> = ["agents", "omp"];
15
-
16
- export type { OmpSessionModel };
17
-
18
- export const DEFAULT_OMP_SESSION_MODEL: OmpSessionModel = {
19
- selector: "opencode-zen/muse-spark-1.3-contributor-free",
20
- thinking: "xhigh",
21
- };
22
-
23
- function isHarness(value: unknown): value is Harness {
24
- return value === "agents" || value === "omp";
25
- }
26
-
27
- function normalizeHarnesses(selection: ReadonlyArray<unknown>): Array<Harness> {
28
- const selected = new Set<Harness>();
29
- for (const value of selection) {
30
- if (isHarness(value)) selected.add(value);
31
- }
32
- return HARNESSES.filter((harness) => selected.has(harness));
33
- }
34
-
35
- /**
36
- * Resolve the engine home root the way the harnesses resolve `~`. On Windows,
37
- * USERPROFILE applies and HOME is ignored. Elsewhere, HOME applies. The
38
- * platform home is the fallback.
39
- */
40
- export function engineHome(
41
- env: NodeJS.ProcessEnv = process.env,
42
- platform: NodeJS.Platform = process.platform,
43
- ): string {
44
- const home = platform === "win32" ? env["USERPROFILE"] : env["HOME"];
45
- return home !== undefined && home !== "" ? home : homedir();
46
- }
47
-
48
- /** Result of a read of the stored selection that keeps the failure reason. */
49
- export type StoredSelection =
50
- | { kind: "stored"; selection: ReadonlyArray<Harness> }
51
- | { kind: "missing" }
52
- | { kind: "unreadable"; reason: string };
53
-
54
- /** Read the stored selection; corruption, a too-new schema, or I/O errors yield "unreadable". */
55
- export function loadHarnessSelection(home: string): StoredSelection {
56
- try {
57
- const selection = withKitDb(home, "read", (db) =>
58
- normalizeHarnesses(
59
- db
60
- .prepare("SELECT harness FROM harness_selection")
61
- .all()
62
- .map((row) => row["harness"]),
63
- ),
64
- );
65
- return selection !== undefined && selection.length > 0
66
- ? { kind: "stored", selection }
67
- : { kind: "missing" };
68
- } catch (error) {
69
- return {
70
- kind: "unreadable",
71
- reason: error instanceof Error ? error.message : String(error),
72
- };
73
- }
74
- }
75
-
76
- /** Read the stored selection; corruption, a too-new schema, or I/O errors yield undefined. */
77
- export function readHarnessSelection(home: string): ReadonlyArray<Harness> | undefined {
78
- const stored = loadHarnessSelection(home);
79
- return stored.kind === "stored" ? stored.selection : undefined;
80
- }
81
-
82
- export function writeHarnessSelection(home: string, selection: ReadonlyArray<Harness>): void {
83
- if (selection.length === 0) {
84
- throw new Error("Cannot write an empty harness selection because sync would become a no-op");
85
- }
86
-
87
- const harnesses = normalizeHarnesses(selection);
88
- if (harnesses.length === 0) {
89
- throw new Error("Harness selection must contain at least one known harness name");
90
- }
91
-
92
- withKitDb(home, "write", (db) =>
93
- inTransaction(db, () => {
94
- db.exec("DELETE FROM harness_selection");
95
- const insert = db.prepare("INSERT INTO harness_selection (harness) VALUES (?)");
96
- for (const harness of harnesses) insert.run(harness);
97
- }),
98
- );
99
- }
100
-
101
- // Read the stored session model without throwing so a corrupt store falls
102
- // back to the default instead of breaking sync.
103
- export function readOmpSessionModel(home: string): OmpSessionModel | undefined {
104
- try {
105
- return withKitDb(home, "read", (db) => {
106
- const row = db.prepare("SELECT selector, thinking FROM omp_session WHERE id = 1").get();
107
- const selector = row?.["selector"];
108
- if (!isNonBlankString(selector)) return undefined;
109
- const thinking = row?.["thinking"];
110
- const model: OmpSessionModel = {
111
- selector,
112
- ...(isNonBlankString(thinking) ? { thinking } : {}),
113
- };
114
- return model;
115
- });
116
- } catch {
117
- return undefined;
118
- }
119
- }
120
-
121
- export function writeOmpSessionModel(home: string, model: OmpSessionModel): void {
122
- // A blank selector would make omp resolve an arbitrary model, so reject it
123
- // before anything reaches disk.
124
- if (!isNonBlankString(model.selector)) {
125
- throw new Error("Omp session model selector must be a non-empty string");
126
- }
127
- // Store a blank or absent level as NULL so a switch to a level-free model
128
- // leaves no stale level behind.
129
- const thinking = nonBlankOrNull(model.thinking);
130
- withKitDb(home, "write", (db) =>
131
- db
132
- .prepare(
133
- `INSERT INTO omp_session (id, selector, thinking) VALUES (1, ?, ?)
134
- ON CONFLICT(id) DO UPDATE SET selector = excluded.selector, thinking = excluded.thinking`,
135
- )
136
- .run(model.selector, thinking),
137
- );
138
- }
@@ -1,135 +0,0 @@
1
- /**
2
- * EngineNative universal-skill install pass (`npx skills@<pin> add`) with
3
- * Claude symlink healing. Split from skillsSync.ts; the orchestration still
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.
9
- */
10
- import { p, spawnProcess } from "./exec";
11
- import type { Ctx } from "./index";
12
- import { ExitError } from "./parseArgs";
13
- import { healClaudeSymlink, isDir } from "./skillsLinks";
14
- import {
15
- canonicalAbsent,
16
- recordPendingInstall,
17
- settlePendingSlug,
18
- writeSkillRecords,
19
- type SkillRecords,
20
- } from "./skillsRecords";
21
- import { normalizeManifest, skillBase } from "./skillsManifest";
22
- import { field } from "./toolchain";
23
-
24
- export interface SkillsState {
25
- present: number;
26
- }
27
-
28
- /** skills::_skills_cli — the pinned npx package spec. */
29
- function skillsCli(ctx: Ctx): string {
30
- const version = field("skills-cli", "verified");
31
- if (version !== "") return `skills@${version}`;
32
- ctx.services.logger.err(
33
- "Universal skills sync aborted because SoT/toolchain.json has no verified skills-cli pin",
34
- );
35
- throw new ExitError(1);
36
- }
37
-
38
- export async function syncUniversal(
39
- ctx: Ctx,
40
- state: SkillsState,
41
- skillsDir: string,
42
- manifest: string,
43
- records: SkillRecords,
44
- ): Promise<void> {
45
- const { change, clearProgress, echo, progress, verbose, warn } = ctx.services.logger;
46
- if (ctx.services.deps.probe("npx").state === "missing") {
47
- ctx.services.deps.warnMissing(
48
- "npx",
49
- ctx.services.logger,
50
- "skipping universal skills bootstrap",
51
- );
52
- return;
53
- }
54
-
55
- let added = 0;
56
- let already = 0;
57
- let failed = 0;
58
- let healed = 0;
59
-
60
- for (const slug of normalizeManifest(manifest)) {
61
- const base = skillBase(slug);
62
-
63
- if (ctx.dryRun) {
64
- if (isDir(p(skillsDir, base))) {
65
- echo(`[dry-run] universal skill present: ${base}`);
66
- healClaudeSymlink(ctx, skillsDir, base);
67
- } else {
68
- echo(`[dry-run] npx ${skillsCli(ctx)} add ${slug} -g -y -a claude-code codex`);
69
- }
70
- continue;
71
- }
72
-
73
- if (isDir(p(skillsDir, base))) {
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
- }
80
- if (healClaudeSymlink(ctx, skillsDir, base)) healed++;
81
- continue;
82
- }
83
-
84
- const cli = skillsCli(ctx);
85
- const pending = canonicalAbsent(skillsDir, slug);
86
- if (pending) recordPendingInstall(records, slug);
87
- progress(`Installing universal skill ${slug}...`);
88
- const res = await spawnProcess(
89
- "npx",
90
- ["--yes", cli, "add", slug, "-g", "-y", "-a", "claude-code", "codex"],
91
- {
92
- stdio: "ignore",
93
- },
94
- );
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
- }
101
- if (res.error === undefined && res.exitCode === 0) {
102
- added++;
103
- if (!isDir(p(skillsDir, base))) {
104
- warn(
105
- `Installed skill name differs from slug ${slug}; declare it as <owner>/<repo>@<skill-name>`,
106
- );
107
- }
108
- } else {
109
- warn(`Failed to install universal skill: ${slug}`);
110
- failed++;
111
- }
112
- }
113
-
114
- if (ctx.dryRun) return;
115
-
116
- state.present = added + already;
117
-
118
- if (added > 0) {
119
- change(`Universal skills synced (+${added} new, ${already} already present)`);
120
- ctx.nextStepTriggers.skillsRestart = true;
121
- } else {
122
- verbose(`Universal skills already in sync (${already} present)`);
123
- }
124
- if (healed > 0) {
125
- change(
126
- `Claude per-tool symlinks healed (+${healed}) — canonical present, ~/.claude/skills/<name> was missing or broken`,
127
- );
128
- ctx.nextStepTriggers.skillsRestart = true;
129
- }
130
- if (failed > 0) {
131
- warn(
132
- `${failed} skill install(s) failed — re-run sync or install manually with: npx --yes ${skillsCli(ctx)} add <slug> -g -y -a claude-code codex`,
133
- );
134
- }
135
- }
@@ -1,216 +0,0 @@
1
- /**
2
- * EngineNative skill link mechanics: Claude per-tool symlink healing plus the
3
- * directory-link-or-marked-copy fallback. Split from skillsSync.ts; the
4
- * install pass (skillsInstall.ts) and the prune pass (skillsPrune.ts) share
5
- * the probe and removal helpers exported here.
6
- */
7
- import {
8
- cpSync,
9
- existsSync,
10
- lstatSync,
11
- mkdirSync,
12
- readlinkSync,
13
- realpathSync,
14
- rmSync,
15
- statSync,
16
- symlinkSync,
17
- writeFileSync,
18
- } from "node:fs";
19
- import { dirname, relative, resolve } from "node:path";
20
- import { p } from "./exec";
21
- import type { Ctx } from "./index";
22
- import { hostOs, type DirectoryLinkKind } from "./os";
23
- import type { EngineServices } from "./services";
24
-
25
- export type LinkOutcome = "symlink" | "junction" | "copy" | "failed";
26
-
27
- /** Lets heal and prune distinguish a kit-owned copy from a user's real directory. */
28
- export const COPY_MARKER = ".docks-kit-copied-skill";
29
-
30
- export function isDir(path: string): boolean {
31
- try {
32
- return statSync(path).isDirectory();
33
- } catch {
34
- return false;
35
- }
36
- }
37
-
38
- /** skills::heal_claude_symlink — true when a heal occurred. */
39
- export function healClaudeSymlink(ctx: Ctx, skillsDir: string, base: string): boolean {
40
- const { echo, warn } = ctx.services.logger;
41
- const canonical = p(skillsDir, base);
42
- const claudeSkillsDir = p(ctx.home, ".claude", "skills");
43
- const claudeLink = p(claudeSkillsDir, base);
44
- const relTarget = relative(dirname(claudeLink), canonical);
45
-
46
- if (!isDir(canonical)) return false;
47
-
48
- const linkStat = lstat(claudeLink);
49
- if (linkStat?.isSymbolicLink() === true) {
50
- const current = safeReadlink(claudeLink);
51
- if (current === relTarget || pointsAt(claudeLink, canonical)) return false;
52
- if (ctx.dryRun) {
53
- echo(
54
- `[dry-run] would replace stale Claude symlink: ~/.claude/skills/${base} -> ${current} (correct: ${relTarget})`,
55
- );
56
- return true;
57
- }
58
- if (!removeLink(claudeLink)) {
59
- warn(
60
- `could not remove stale link ~/.claude/skills/${base} — remove it manually, then re-run sync`,
61
- );
62
- return false;
63
- }
64
- } else if (linkStat !== undefined) {
65
- if (!isKitOwnedCopy(claudeLink)) {
66
- warn(
67
- `~/.claude/skills/${base} exists as a real path (not a symlink) — leaving alone; remove manually if it's stale`,
68
- );
69
- return false;
70
- }
71
- if (ctx.dryRun) {
72
- echo(
73
- `[dry-run] would replace kit-created Claude copy: ~/.claude/skills/${base} -> ${relTarget}`,
74
- );
75
- return true;
76
- }
77
- if (!removeKitOwnedCopy(claudeLink)) {
78
- warn(
79
- `could not remove kit-created copy ~/.claude/skills/${base} — remove it manually, then re-run sync`,
80
- );
81
- return false;
82
- }
83
- } else if (ctx.dryRun) {
84
- echo(`[dry-run] would create missing Claude symlink: ~/.claude/skills/${base} -> ${relTarget}`);
85
- return true;
86
- }
87
-
88
- mkdirSync(claudeSkillsDir, { recursive: true });
89
- return linkOrCopyWithWarnings(relTarget, claudeLink, ctx.services) !== "failed";
90
- }
91
-
92
- export function lstat(path: string): ReturnType<typeof lstatSync> | undefined {
93
- try {
94
- return lstatSync(path);
95
- } catch {
96
- return undefined;
97
- }
98
- }
99
-
100
- /**
101
- * A link only counts when it RESOLVES to the skill directory. Windows picks a
102
- * symlink's file-or-directory type by autodetecting the target against the
103
- * process working directory, not the link's own directory, so a relative
104
- * target can yield a symlink that exists but resolves to nothing. Checking
105
- * resolution is what makes the next mechanism in the chain reachable.
106
- */
107
- function linksToDirectory(path: string): boolean {
108
- if (lstat(path)?.isSymbolicLink() !== true) return false;
109
- try {
110
- return statSync(path).isDirectory();
111
- } catch {
112
- return false;
113
- }
114
- }
115
-
116
- export function isKitOwnedCopy(path: string): boolean {
117
- return lstat(path)?.isDirectory() === true && existsSync(p(path, COPY_MARKER));
118
- }
119
-
120
- export function removeKitOwnedCopy(path: string): boolean {
121
- if (!isKitOwnedCopy(path)) return false;
122
- try {
123
- rmSync(path, { recursive: true, force: true });
124
- return true;
125
- } catch {
126
- return lstat(path) === undefined;
127
- }
128
- }
129
-
130
- function safeReadlink(path: string): string {
131
- try {
132
- return readlinkSync(path);
133
- } catch {
134
- return "";
135
- }
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
-
150
- /** Remove a symlink without touching a real directory. */
151
- export function removeLink(path: string): boolean {
152
- try {
153
- rmSync(path, { force: true });
154
- return true;
155
- } catch {
156
- return lstat(path) === undefined;
157
- }
158
- }
159
-
160
- /** skills::_link_or_copy — try directory links in host order, then a marked copy. */
161
- export function linkOrCopy(
162
- target: string,
163
- link: string,
164
- kinds: ReadonlyArray<DirectoryLinkKind> = hostOs().directoryLinkKinds,
165
- ): LinkOutcome {
166
- const resolvedLink = resolve(link);
167
- const absoluteTarget = resolve(dirname(resolvedLink), target);
168
- if (absoluteTarget === resolvedLink) return "symlink";
169
- removeLink(link);
170
-
171
- for (const kind of kinds) {
172
- try {
173
- if (kind === "symlink") {
174
- symlinkSync(target, link);
175
- } else {
176
- symlinkSync(absoluteTarget, link, "junction");
177
- }
178
- if (linksToDirectory(link)) return kind;
179
- } catch {
180
- // The runtime decides whether each mechanism works; try the next one.
181
- }
182
- removeLink(link);
183
- }
184
-
185
- const copyDestinationWasAbsent = lstat(link) === undefined;
186
- try {
187
- cpSync(absoluteTarget, link, { recursive: true });
188
- writeFileSync(p(link, COPY_MARKER), "");
189
- return "copy";
190
- } catch {
191
- if (copyDestinationWasAbsent) {
192
- try {
193
- rmSync(link, { recursive: true, force: true });
194
- } catch {
195
- // The outcome remains failed; a later sync can retry the destination.
196
- }
197
- }
198
- return "failed";
199
- }
200
- }
201
-
202
- function linkOrCopyWithWarnings(
203
- target: string,
204
- link: string,
205
- services: EngineServices,
206
- ): LinkOutcome {
207
- const outcome = linkOrCopy(target, link);
208
- if (outcome === "copy") {
209
- services.logger.warn(
210
- `created copy fallback ${link} because directory linking is unavailable — a later sync will restore a real link once linking works`,
211
- );
212
- } else if (outcome === "failed") {
213
- services.logger.warn(`could not create symlink ${link}`);
214
- }
215
- return outcome;
216
- }
@@ -1,36 +0,0 @@
1
- /**
2
- * EngineNative universal-skill manifest parsing: cleaned slugs, one per line.
3
- * Split from skillsSync.ts. Pure logic with no process state.
4
- */
5
-
6
- /** skills::_normalize_manifest — cleaned slugs, one per line. */
7
- export function normalizeManifest(content: string): Array<string> {
8
- const out: Array<string> = [];
9
- for (const line of content.split("\n")) {
10
- if (/^[ \t]*#/.test(line)) continue;
11
- if (/^[ \t]*$/.test(line)) continue;
12
- const cleaned = line.replace(/[ \t]*#.*$/, "").replace(/[ \t\r]+/g, "");
13
- if (cleaned.length > 0) out.push(cleaned);
14
- }
15
- return out;
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
- }
@@ -1,117 +0,0 @@
1
- /**
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
- *
6
- * The prune deletes only what the kit created: the canonical skill directory
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.
13
- */
14
- import { existsSync, rmSync } from "node:fs";
15
- import { p } from "./exec";
16
- import type { Ctx } from "./index";
17
- import { compareCodepoints } from "./jq";
18
- import { isKitOwnedCopy, lstat, removeKitOwnedCopy, removeLink } from "./skillsLinks";
19
- import { normalizeManifest, skillBase } from "./skillsManifest";
20
- import { directoryIdentity, type SkillRecords } from "./skillsRecords";
21
-
22
- function removeCanonical(path: string): boolean {
23
- try {
24
- rmSync(path, { recursive: true, force: true });
25
- return true;
26
- } catch {
27
- return lstat(path) === undefined;
28
- }
29
- }
30
-
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 {
41
- const { change, echo, warn } = ctx.services.logger;
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
- );
46
- }
47
-
48
- const current = normalizeManifest(manifest);
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
-
61
- let removed = 0;
62
- let failed = 0;
63
- for (const slug of [...records.owned.keys()].sort(compareCodepoints)) {
64
- if (declared(slug)) continue;
65
- const base = skillBase(slug);
66
- const canonical = p(ctx.agentsDir, "skills", base);
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);
70
- const installedCanonical =
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
- }
79
- const claudeEntry = p(ctx.home, ".claude", "skills", base);
80
- const managedClaudeEntry =
81
- lstat(claudeEntry)?.isSymbolicLink() === true || isKitOwnedCopy(claudeEntry);
82
- if (ctx.dryRun) {
83
- echo(`[dry-run] kit-managed skill no longer in SoT — would remove: ${base}`);
84
- if (managedClaudeEntry) {
85
- echo(`[dry-run] kit-managed Claude skill entry — would remove: ~/.claude/skills/${base}`);
86
- }
87
- continue;
88
- }
89
- if (installedCanonical && !removeCanonical(canonical)) {
90
- warn(`Failed to remove kit-managed skill: ${base}`);
91
- failed++;
92
- continue;
93
- }
94
- if (managedClaudeEntry) {
95
- const entryStat = lstat(claudeEntry);
96
- const removedClaudeEntry =
97
- entryStat === undefined ||
98
- (entryStat.isSymbolicLink() ? removeLink(claudeEntry) : removeKitOwnedCopy(claudeEntry));
99
- if (!removedClaudeEntry) {
100
- warn(`Failed to remove kit-managed Claude skill entry: ${base}`);
101
- failed++;
102
- continue;
103
- }
104
- }
105
- records.owned.delete(slug);
106
- removed++;
107
- }
108
-
109
- if (removed > 0) {
110
- change(`Kit-managed skills removed (-${removed})`);
111
- ctx.nextStepTriggers.skillsRestart = true;
112
- }
113
- if (failed > 0)
114
- warn(
115
- `${failed} skill remove(s) failed — re-run with --prune, or delete ~/.agents/skills/<name> and the ~/.claude/skills/<name> link manually`,
116
- );
117
- }