@a2f0/agent-tool 0.1.66 → 0.1.67

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.
package/README.md CHANGED
@@ -82,7 +82,8 @@ validation suite, and release procedures.
82
82
  aggregate gates, release verification, durable validation receipts, and
83
83
  toolchain/protection diagnostics.
84
84
  - [CLI reference](docs/reference.md): existing review, version, skill installation,
85
- command capture, import-graph checks, configuration, and distribution contracts.
85
+ user-wide skill links, command capture, import-graph checks, configuration, and
86
+ distribution contracts.
86
87
  - [Development](docs/development.md): setup, source layout, validation, and release
87
88
  procedures for this package.
88
89
  - [Images](docs/images.md): declarative brand sources and generated outputs.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@a2f0/agent-tool",
3
- "version": "0.1.66",
3
+ "version": "0.1.67",
4
4
  "packageManager": "bun@1.4.4",
5
5
  "type": "module",
6
6
  "description": "Portable cross-agent review, PR workflows, and shared skills",
package/src/cli.ts CHANGED
@@ -12,6 +12,7 @@ import { carryReviewCommand } from "./review/carry";
12
12
  import { runAgentToolAction } from "./runAgentToolAction";
13
13
  import { BUNDLED_SKILLS } from "./skills/bundled";
14
14
  import { checkSkills, installSkills } from "./skills/install";
15
+ import { checkSkillLinks, linkSkills } from "./skills/link";
15
16
  import { bunCommand } from "./bun/dependencies";
16
17
  import { checkPermissions, installPermissions, showPermissions } from "./permissions/install";
17
18
  import { bumpVersions, checkVersions, planVersions } from "./version/bumpVersions";
@@ -74,6 +75,8 @@ Usage: agent-tool [--repo <directory>] [--config <file>] <command>
74
75
  skills list
75
76
  skills install [--harness <all|claude|codex|opencode|hermes>] [--apply]
76
77
  skills check [--harness <all|claude|codex|opencode|hermes>]
78
+ skills link [--apply] Link agent-tool.json skills.user into each user skill directory
79
+ skills check-links Read-only: exit 1 while a declared user skill link is missing, broken, or conflicts
77
80
  bun install [--cwd <dir>] Frozen-lockfile install with the pinned Bun
78
81
  bun add <name@version>... [--dev|--optional|--peer] [--exact] [--cwd <dir>]
79
82
  bun update <name[@version]>... [--cwd <dir>] Change versions of declared dependencies only
@@ -191,7 +194,24 @@ export function main(argv = process.argv.slice(2)): number | Promise<number> {
191
194
  if (command === "skills") {
192
195
  const action = args.shift();
193
196
  if (action === "list") { usage(args.length === 0, "Usage: agent-tool skills list"); output(Object.keys(BUNDLED_SKILLS)); return 0; }
194
- usage(action === "install" || action === "check", "Usage: agent-tool skills <list|install|check>");
197
+ if (action === "link" || action === "check-links") {
198
+ let apply = false;
199
+ while (args.length) {
200
+ const flag = args.shift();
201
+ if (flag === "--apply") { usage(action === "link", "skills check-links is read-only; --apply is not allowed."); usage(!apply, "Duplicate --apply."); apply = true; }
202
+ else throw new Error(`Unknown skills ${action} argument '${flag}'.`);
203
+ }
204
+ // The checkout's top level, so a subdirectory cannot read as a repository that declares nothing.
205
+ const root = gitRoot();
206
+ const names = loadConfig(root).skills.user;
207
+ if (action === "check-links") {
208
+ const result = checkSkillLinks(root, names);
209
+ output(result); return result.ok ? 0 : 1;
210
+ }
211
+ const result = linkSkills(root, names, apply);
212
+ output(result); return result.changes.some(change => change.status === "conflict" || change.result === "failed") ? 1 : 0;
213
+ }
214
+ usage(action === "install" || action === "check", "Usage: agent-tool skills <list|install|check|link|check-links>");
195
215
  let target = "all", apply = false;
196
216
  while (args.length) {
197
217
  const flag = args.shift();
package/src/config.ts CHANGED
@@ -26,6 +26,8 @@ export interface AgentToolConfig extends WorkflowConfig {
26
26
  screenshots: ScreenshotsConfig;
27
27
  graph: GraphConfig;
28
28
  permissions: { executables: Record<string, PermissionClass> };
29
+ /** `user`: skills `skills link` links into each user skill directory, by skill directory name. */
30
+ skills: { user: string[] };
29
31
  /** Null when the repository declares no push gate. */
30
32
  pushGate: PushGateConfig | null;
31
33
  }
@@ -49,6 +51,7 @@ export const DEFAULT_CONFIG: AgentToolConfig = {
49
51
  screenshots: structuredClone(SCREENSHOTS_DEFAULTS),
50
52
  graph: structuredClone(GRAPH_DEFAULTS),
51
53
  permissions: { executables: {} },
54
+ skills: { user: [] },
52
55
  pushGate: null,
53
56
  };
54
57
 
@@ -101,7 +104,7 @@ export function parseConfig(source: string): AgentToolConfig {
101
104
  keys(input, Object.keys(DEFAULT_CONFIG), "config");
102
105
  if (input.schemaVersion !== 1) throw new Error("Unsupported config schemaVersion; expected 1.");
103
106
  const result = structuredClone(DEFAULT_CONFIG);
104
- for (const section of ["subject", "merge", "review", "versions", "pr", "branch", "commits", "hooks", "binaries", "permissions"] as const) {
107
+ for (const section of ["subject", "merge", "review", "versions", "pr", "branch", "commits", "hooks", "binaries", "permissions", "skills"] as const) {
105
108
  if (input[section] === undefined) continue;
106
109
  const settings = object(input[section], section);
107
110
  keys(settings, Object.keys(result[section]), section);
@@ -146,6 +149,10 @@ export function parseConfig(source: string): AgentToolConfig {
146
149
  // Names become literal tokens in harness rules, so keep them free of rule syntax.
147
150
  const executables = object(result.permissions.executables, "permissions.executables");
148
151
  for (const [name, value] of Object.entries(executables)) if (!/^[\w.+-]+$/.test(name) || !(typeof value === "string" && Object.hasOwn(CLASSES, value))) invalid(`permissions.executables.${name}`);
152
+ // Names become entries in user skill directories, so each is a plain skill directory name, once.
153
+ // `synced` is Claude Code's own account-synced skill store.
154
+ const user = result.skills.user;
155
+ if (!Array.isArray(user) || user.some(name => typeof name !== "string" || name.length > 64 || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name) || name === "synced") || new Set(user).size !== user.length) invalid("skills.user");
149
156
  validateWorkflowConfig(result);
150
157
  return result;
151
158
  }
@@ -9,7 +9,7 @@ export const CLASSES = {
9
9
  share: { decision: "allow", description: "Publishes work for review without changing a shared branch: pushes a feature branch, opens a PR, answers review threads, or prunes a merged PR's feature branch." },
10
10
  release: { decision: "ask", description: "Merges into a shared branch, publishes a package, or deletes remote state." },
11
11
  intake: { decision: "ask", description: "Brings new third-party code into the repository." },
12
- policy: { decision: "ask", description: "Changes the permissions agents run with." },
12
+ policy: { decision: "ask", description: "Changes the permissions agents run with, or links user-wide skills every session loads." },
13
13
  exec: { decision: "ask", description: "Runs whatever command or file its arguments name." },
14
14
  } as const;
15
15
  export type PermissionClass = keyof typeof CLASSES;
@@ -19,7 +19,7 @@ export type Decision = "allow" | "ask";
19
19
  export interface CatalogEntry { command: string; class: PermissionClass; applyClass?: PermissionClass }
20
20
 
21
21
  export const CATALOG: CatalogEntry[] = [
22
- ...["--help", "--version", "logs", "runs list", "doctor", "config show", "branch check", "branch status", "commits check", "checks binaries", "repo context", "policy check", "toolchain check", "ci gate", "release plan", "release verify", "pr context", "pr checks", "pr logs", "pr preflight", "pr threads list", "versions plan", "versions check", "dependencies check-terraform-plan", "dependencies diff", "skills list", "skills check", "hooks check", "push-gate hook", "push-gate check", "repo base-health", "review carry", "images list", "graph check", "state-machines", "permissions show", "permissions check", "proc list"]
22
+ ...["--help", "--version", "logs", "runs list", "doctor", "config show", "branch check", "branch status", "commits check", "checks binaries", "repo context", "policy check", "toolchain check", "ci gate", "release plan", "release verify", "pr context", "pr checks", "pr logs", "pr preflight", "pr threads list", "versions plan", "versions check", "dependencies check-terraform-plan", "dependencies diff", "skills list", "skills check", "skills check-links", "hooks check", "push-gate hook", "push-gate check", "repo base-health", "review carry", "images list", "graph check", "state-machines", "permissions show", "permissions check", "proc list"]
23
23
  .map(command => ({ command, class: "read" as const })),
24
24
  ...["bun install", "bun update", "bun remove", "bun test", "branch create", "versions bump", "versions prepare", "versions resolve-conflicts", "images build", "screenshots build", "review", "init", "proc stop"]
25
25
  .map(command => ({ command, class: "local" as const })),
@@ -27,6 +27,8 @@ export const CATALOG: CatalogEntry[] = [
27
27
  { command: "hooks install", class: "read", applyClass: "local" },
28
28
  { command: "teardown", class: "read", applyClass: "local" },
29
29
  { command: "permissions install", class: "read", applyClass: "policy" },
30
+ // Linking writes outside the checkout, into the user skill directories every session loads.
31
+ { command: "skills link", class: "read", applyClass: "policy" },
30
32
  ...["branch push", "pr open", "pr cancel-runs", "pr threads reply", "pr threads resolve"].map(command => ({ command, class: "share" as const })),
31
33
  { command: "pr merge", class: "release" },
32
34
  // Cleanup acts only after GitHub confirms the PR MERGED and the local and remote
@@ -0,0 +1,320 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { existsSync, lstatSync, mkdirSync, readdirSync, readlinkSync, realpathSync, renameSync, statSync, symlinkSync, unlinkSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import path from "node:path";
5
+ import { readRegularFile } from "../system/files";
6
+
7
+ /**
8
+ * User-wide skills: a repository declares them by name in `skills.user`, and `skills link`
9
+ * links each into every user skill directory, so every harness session sees them whatever
10
+ * repository it starts in. Claude Code reads `<config dir>/skills` for each config directory;
11
+ * `~/.agents/skills` is the user-level counterpart of a project's `.agents/skills`.
12
+ */
13
+ export type UserSkillHarness = "claude" | "agents";
14
+ export interface UserSkillDirectory { harness: UserSkillHarness; directory: string }
15
+
16
+ /**
17
+ * What a link path holds: nothing (`create`); a symbolic link that does not resolve to a skill
18
+ * directory, or that resolves to another copy of the skill in this repository (`repair`); a link
19
+ * to this repository's source (`unchanged`); a link to the same skill elsewhere, such as another
20
+ * clone (`kept`); or anything else (`conflict`): a file or directory, or a link to a different
21
+ * skill. Only `create` and `repair` are ever written.
22
+ */
23
+ export type SkillLinkStatus = "create" | "repair" | "unchanged" | "kept" | "conflict";
24
+ /** One declared skill in one user skill directory: `status` is the plan's classification and `current` an existing link's own text. */
25
+ export interface SkillLinkPlan { skill: string; directory: string; path: string; target: string; status: SkillLinkStatus; current?: string }
26
+ /**
27
+ * A planned entry and, only when an applied write was attempted, its `result`: `written`, or
28
+ * `failed` with `error` saying why. An entry without one was not written.
29
+ */
30
+ export type SkillLink = SkillLinkPlan & ({ result?: never; error?: never } | { result: "written"; error?: never } | { result: "failed"; error: string });
31
+
32
+ type Environment = Record<string, string | undefined>;
33
+ const errorCode = (error: unknown) => (error as NodeJS.ErrnoException).code ?? "";
34
+ /** Errors that mean a path, or what a link names, does not exist as asked. */
35
+ const ABSENT = ["ENOENT", "ENOTDIR", "ELOOP"];
36
+
37
+ function statOrNull(file: string) {
38
+ try { return statSync(file); } catch (error) { if (ABSENT.includes(errorCode(error))) return null; throw error; }
39
+ }
40
+ function isLink(file: string): boolean {
41
+ try { return lstatSync(file).isSymbolicLink(); } catch (error) { if (ABSENT.includes(errorCode(error))) return false; throw error; }
42
+ }
43
+ const isDirectory = (file: string) => statOrNull(file)?.isDirectory() ?? false;
44
+ /** A directory holding a regular `SKILL.md`, following links as the harnesses do. */
45
+ const holdsSkill = (directory: string) => isDirectory(directory) && (statOrNull(path.join(directory, "SKILL.md"))?.isFile() ?? false);
46
+ function within(parent: string, child: string): boolean {
47
+ const relative = path.relative(parent, child);
48
+ return !relative || (!relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative));
49
+ }
50
+
51
+ /** The home directory, from `HOME` first so tests and callers can isolate it. */
52
+ export function userHome(env: Environment = process.env): string {
53
+ return path.resolve(env.HOME || homedir());
54
+ }
55
+
56
+ /** Keeps the first of each real path, so links and aliases name one directory once. */
57
+ function unique<T>(items: T[], key: (item: T) => string): T[] {
58
+ const seen = new Set<string>();
59
+ return items.filter(item => { const value = key(item); if (seen.has(value)) return false; seen.add(value); return true; });
60
+ }
61
+
62
+ /**
63
+ * The real path of a directory that may not exist yet: its nearest existing ancestor's, then the
64
+ * rest, following a dangling link to where it points, so a link to a directory not created yet
65
+ * names that directory. A link loop stops after 40 links, at whichever name it reached, which
66
+ * planning then refuses as a link that does not resolve to a directory.
67
+ */
68
+ function realDirectory(directory: string, hops = 0): string {
69
+ try { return realpathSync(directory); }
70
+ catch (error) { if (!ABSENT.includes(errorCode(error))) throw error; }
71
+ const parent = path.dirname(directory);
72
+ if (parent === directory) return directory;
73
+ const resolved = path.join(realDirectory(parent, hops), path.basename(directory));
74
+ if (hops >= 40 || !isLink(resolved)) return resolved;
75
+ return realDirectory(path.resolve(path.dirname(resolved), readlinkSync(resolved)), hops + 1);
76
+ }
77
+
78
+ /**
79
+ * Claude Code config directories, in this order: the one `CLAUDE_CONFIG_DIR` names when it is set
80
+ * to an absolute path; `~/.claude`; then every other directory directly in home whose name starts with
81
+ * `.claude` and that holds `settings.json` or `.claude.json`, such as `~/.claude2`. Claude Code
82
+ * writes `.claude.json` into a directory it runs with, and provisioning links `settings.json` into
83
+ * one. Only existing directories count, so files such as `~/.claude.json` never do, and a
84
+ * directory reached twice, by a link or by `CLAUDE_CONFIG_DIR`, counts once, by real path.
85
+ */
86
+ export function claudeConfigDirectories(env: Environment = process.env): string[] {
87
+ const home = userHome(env);
88
+ const candidates: string[] = [];
89
+ // Only an absolute path: a relative one depends on where Claude Code started, which is unknown here.
90
+ if (env.CLAUDE_CONFIG_DIR && path.isAbsolute(env.CLAUDE_CONFIG_DIR)) candidates.push(path.normalize(env.CLAUDE_CONFIG_DIR));
91
+ candidates.push(path.join(home, ".claude"));
92
+ let names: string[] = [];
93
+ try { names = readdirSync(home).sort(); } catch (error) { if (!ABSENT.includes(errorCode(error))) throw error; }
94
+ for (const name of names) {
95
+ if (!name.startsWith(".claude") || name === ".claude") continue;
96
+ const directory = path.join(home, name);
97
+ if (["settings.json", ".claude.json"].some(marker => existsSync(path.join(directory, marker)))) candidates.push(directory);
98
+ }
99
+ return unique(candidates.filter(isDirectory), directory => realpathSync(directory));
100
+ }
101
+
102
+ /**
103
+ * `~/.agents/skills`, then `<dir>/skills` for each Claude Code config directory. A skills
104
+ * directory reached twice, such as `~/.claude2/skills` linked to `~/.claude/skills`, counts once,
105
+ * under the name that is not itself a link, so a link to a directory not created yet resolves
106
+ * once that directory is created.
107
+ */
108
+ export function userSkillDirectories(env: Environment = process.env): UserSkillDirectory[] {
109
+ const directories = [
110
+ { harness: "agents" as const, directory: path.join(userHome(env), ".agents", "skills") },
111
+ ...claudeConfigDirectories(env).map(directory => ({ harness: "claude" as const, directory: path.join(directory, "skills") })),
112
+ ].map(item => ({ ...item, key: realDirectory(item.directory), link: isLink(item.directory) }));
113
+ const chosen = new Map<string, typeof directories[number]>();
114
+ for (const item of directories) {
115
+ const first = chosen.get(item.key);
116
+ if (!first || (first.link && !item.link)) chosen.set(item.key, item);
117
+ }
118
+ return directories.filter(item => chosen.get(item.key) === item).map(({ harness, directory }) => ({ harness, directory }));
119
+ }
120
+
121
+ /**
122
+ * The repository directory a harness links to for one skill: its installed copy for that harness
123
+ * when it holds `SKILL.md` (`.claude/skills/<name>` or `.agents/skills/<name>`), otherwise the
124
+ * repository-owned `skills/<name>`, as an absolute real path inside the repository.
125
+ */
126
+ export function skillSource(root: string, harness: UserSkillHarness, name: string): string {
127
+ const installed = harness === "claude" ? ".claude/skills" : ".agents/skills";
128
+ const found = [`${installed}/${name}`, `skills/${name}`].find(relative => holdsSkill(path.join(root, relative)));
129
+ if (!found) throw new Error(`Declared user skill '${name}' has no SKILL.md in ${installed}/${name} or skills/${name}.`);
130
+ const source = realpathSync(path.join(root, found));
131
+ if (!within(root, source)) throw new Error(`Declared user skill '${name}' resolves outside the repository: ${found}.`);
132
+ // Links are matched to skills by name, so a source must be the skill it is declared as.
133
+ const named = skillName(source);
134
+ if (named !== name) throw new Error(`Declared user skill '${name}' is named '${named}' in ${found}/SKILL.md.`);
135
+ return source;
136
+ }
137
+
138
+ /** The skill a directory holds: its `SKILL.md` front matter `name`, else the directory's name; none without `SKILL.md`. */
139
+ function skillName(directory: string): string | undefined {
140
+ if (!holdsSkill(directory)) return undefined;
141
+ // One non-blocking, link-refusing read of the resolved file, so a FIFO cannot stall the check.
142
+ let file: string;
143
+ try { file = realpathSync(path.join(directory, "SKILL.md")); }
144
+ catch (error) { if (ABSENT.includes(errorCode(error))) return undefined; throw error; }
145
+ const read = readRegularFile(file);
146
+ if (read.status !== "file") return undefined;
147
+ const front = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(read.contents)?.[1];
148
+ const raw = front === undefined ? undefined : /^name:[ \t]*(.*?)[ \t]*$/m.exec(front)?.[1];
149
+ // A quoted value keeps everything inside its quotes; a YAML comment may follow either form.
150
+ const name = raw === undefined ? undefined : /^(["'])(.*?)\1(?:\s+#.*)?$/.exec(raw)?.[2] ?? raw.replace(/(?:^|\s+)#.*$/, "");
151
+ return name || path.basename(directory);
152
+ }
153
+
154
+ /** Whether anything, even a dangling link, exists at `file`; an entry that cannot be inspected counts. */
155
+ function hasEntry(file: string): boolean {
156
+ try { lstatSync(file); return true; } catch (error) { return errorCode(error) !== "ENOENT"; }
157
+ }
158
+
159
+ /** Inside the repository and not inside a repository nested in it, such as a workspace's checkouts. */
160
+ function inRepository(root: string, file: string): boolean {
161
+ if (!within(root, file)) return false;
162
+ for (let directory = file; directory !== root && within(root, directory); directory = path.dirname(directory)) {
163
+ if (hasEntry(path.join(directory, ".git"))) return false;
164
+ }
165
+ return true;
166
+ }
167
+
168
+ /** Classify one link path against its intended target without changing anything. */
169
+ function classify(root: string, file: string, target: string, skill: string): Pick<SkillLinkPlan, "status" | "current"> {
170
+ let link: boolean;
171
+ try { link = lstatSync(file).isSymbolicLink(); }
172
+ catch (error) { if (errorCode(error) === "ENOENT") return { status: "create" }; throw error; }
173
+ if (!link) return { status: "conflict" };
174
+ const current = readlinkSync(file);
175
+ let resolved: string;
176
+ try { resolved = realpathSync(file); }
177
+ catch (error) { if (ABSENT.includes(errorCode(error))) return { status: "repair", current }; throw error; }
178
+ if (resolved === target) return { status: "unchanged", current };
179
+ const name = skillName(resolved);
180
+ if (name === undefined) return { status: "repair", current };
181
+ if (name !== skill) return { status: "conflict", current };
182
+ // This repository owns both copies, so the link moves to the one this harness should load.
183
+ return { status: inRepository(root, resolved) ? "repair" : "kept", current };
184
+ }
185
+
186
+ /** Whether a user skill directory exists; one that names anything but a directory is refused. */
187
+ function directoryExists(directory: string): boolean {
188
+ try { lstatSync(directory); }
189
+ catch (error) {
190
+ if (errorCode(error) === "ENOENT") return false;
191
+ // A parent that is a file or a link loop: refused below as not a directory.
192
+ if (errorCode(error) !== "ENOTDIR" && errorCode(error) !== "ELOOP") throw error;
193
+ }
194
+ if (isDirectory(directory)) return true;
195
+ if (isLink(directory)) throw new Error(`User skill directory is a link that does not resolve to a directory: ${directory} -> ${readlinkSync(directory)}`);
196
+ throw new Error(`User skill directory is not a directory: ${directory}`);
197
+ }
198
+
199
+ /**
200
+ * One entry per declared skill and user skill directory. Every source resolves first, for both
201
+ * harnesses, so a declaration without one fails on every machine and before anything is read
202
+ * from home. Only the declared names are ever examined.
203
+ */
204
+ export function planSkillLinks(rootDir: string, names: string[], env: Environment = process.env): SkillLinkPlan[] {
205
+ if (!names.length) return [];
206
+ const root = realpathSync(rootDir);
207
+ const sources = {
208
+ agents: names.map(name => skillSource(root, "agents", name)),
209
+ claude: names.map(name => skillSource(root, "claude", name)),
210
+ };
211
+ const links: SkillLinkPlan[] = [];
212
+ for (const { harness, directory } of userSkillDirectories(env)) {
213
+ const exists = directoryExists(directory);
214
+ names.forEach((skill, index) => {
215
+ const target = sources[harness][index]!, file = path.join(directory, skill);
216
+ links.push({ skill, directory, path: file, target, ...(exists ? classify(root, file, target, skill) : { status: "create" as const }) });
217
+ });
218
+ }
219
+ return links;
220
+ }
221
+
222
+ /**
223
+ * Replace a link through a fresh temporary link and a rename, so the name is never missing. Only
224
+ * the link the plan classified is replaced: the path must still hold a link with the same text
225
+ * just before the rename. Node has no exchanging rename, so a writer racing that instant is
226
+ * outside this guard; only another process writing the user's skill directories could do it.
227
+ */
228
+ function replaceLink(link: SkillLinkPlan): void {
229
+ const temporary = path.join(link.directory, `.${link.skill}.agent-tool-${randomUUID()}.tmp`);
230
+ symlinkSync(link.target, temporary, "dir");
231
+ let renamed = false;
232
+ try {
233
+ let current: string | undefined;
234
+ // EINVAL: not a link.
235
+ try { current = readlinkSync(link.path); } catch (error) { if (!["ENOENT", "ENOTDIR", "EINVAL"].includes(errorCode(error))) throw error; }
236
+ if (current === undefined || current !== link.current) throw new Error(`Refusing to replace ${link.path}, which changed since the plan.`);
237
+ renameSync(temporary, link.path);
238
+ renamed = true;
239
+ } finally {
240
+ // Best effort: the original error matters more than a temporary link left behind.
241
+ if (!renamed) try { unlinkSync(temporary); } catch {}
242
+ }
243
+ }
244
+
245
+ /**
246
+ * Writes a plan's `create` and `repair` entries. Each write stands alone: one that fails, such as
247
+ * a create whose path was taken since the plan, records its `error` and the rest still run, so
248
+ * the result says exactly what was written. Nothing that is not a link is replaced or removed,
249
+ * and a plan with a conflict writes nothing. `linkSkills` also refuses linked worktrees first;
250
+ * this is exported so tests can change the filesystem between the plan and the writes.
251
+ */
252
+ export function applySkillLinks(changes: SkillLinkPlan[]): SkillLink[] {
253
+ if (changes.some(change => change.status === "conflict")) return changes;
254
+ return changes.map((change): SkillLink => {
255
+ if (change.status !== "create" && change.status !== "repair") return change;
256
+ try {
257
+ if (change.status === "create") {
258
+ mkdirSync(change.directory, { recursive: true, mode: 0o700 });
259
+ // Fails rather than overwrites if anything appeared since the plan.
260
+ symlinkSync(change.target, change.path, "dir");
261
+ } else replaceLink(change);
262
+ return { ...change, result: "written" };
263
+ } catch (error) {
264
+ return { ...change, result: "failed", error: error instanceof Error ? error.message : String(error) };
265
+ }
266
+ });
267
+ }
268
+
269
+ /** Whether a directory is, or is inside, a `modules` directory of a Git directory. */
270
+ function insideModules(directory: string): boolean {
271
+ for (let current = directory; path.dirname(current) !== current; current = path.dirname(current)) {
272
+ if (path.basename(current) === "modules" && existsSync(path.join(path.dirname(current), "HEAD"))) return true;
273
+ }
274
+ return false;
275
+ }
276
+
277
+ /**
278
+ * Whether the checkout lives in a linked worktree. `git rev-parse --git-common-dir` would miss a
279
+ * submodule inside a linked worktree, so this reads the layout: the checkout's `.git` is a file
280
+ * naming a Git directory that, or one of whose ancestors up to the enclosing `.git` directory,
281
+ * holds `commondir`, which Git writes only into a linked worktree's Git directory. The ancestors
282
+ * cover a submodule checked out inside a linked worktree, whose Git directory sits under that
283
+ * worktree's `modules/`. The walk stops at the outermost Git directory, so a stray `commondir`
284
+ * above the repository never counts.
285
+ */
286
+ function linkedWorktree(root: string): boolean {
287
+ const read = readRegularFile(path.join(root, ".git"));
288
+ const gitdir = read.status === "file" ? /^gitdir:[ \t]*(.+?)[ \t]*$/m.exec(read.contents)?.[1] : undefined;
289
+ if (gitdir === undefined) return false;
290
+ for (let directory = path.resolve(root, gitdir); ; directory = path.dirname(directory)) {
291
+ if (existsSync(path.join(directory, "commondir"))) return true;
292
+ const parent = path.dirname(directory);
293
+ if (parent === directory || path.basename(directory) === ".git") return false;
294
+ // A Git directory that is not a submodule's, under another Git directory's `modules/`, is the
295
+ // outermost, as with `--separate-git-dir`.
296
+ if (existsSync(path.join(directory, "HEAD")) && !insideModules(parent)) return false;
297
+ }
298
+ }
299
+
300
+ /**
301
+ * Previews by default. With `apply`, creates missing links, creating a missing skills directory
302
+ * (mode 0700), and repairs broken ones. A conflict anywhere blocks every write. Links follow the
303
+ * checked-out working tree, so a linked worktree, which is removed when its work is done, is refused.
304
+ * `applied` is true only when every write succeeded; a failed one carries `error`.
305
+ */
306
+ export function linkSkills(rootDir: string, names: string[], apply = false, env: Environment = process.env): { applied: boolean; changes: SkillLink[] } {
307
+ const changes = planSkillLinks(rootDir, names, env);
308
+ if (!apply || changes.some(change => change.status === "conflict")) return { applied: false, changes };
309
+ if (changes.some(change => change.status === "create" || change.status === "repair") && linkedWorktree(realpathSync(rootDir))) {
310
+ throw new Error("Refusing to link user-wide skills from a linked worktree, whose removal would break them; run skills link from the main checkout.");
311
+ }
312
+ const applied = applySkillLinks(changes);
313
+ return { applied: applied.every(change => change.result !== "failed"), changes: applied };
314
+ }
315
+
316
+ /** Read-only: ok while every declared link is unchanged or kept, so health reports can gate on it. */
317
+ export function checkSkillLinks(rootDir: string, names: string[], env: Environment = process.env): { ok: boolean; changes: SkillLink[] } {
318
+ const changes = planSkillLinks(rootDir, names, env);
319
+ return { ok: changes.every(change => change.status === "unchanged" || change.status === "kept"), changes };
320
+ }