@jive-sh/skill-sync 0.4.15-latest-darwin-arm64 → 0.4.15

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 (43) hide show
  1. package/README.md +121 -0
  2. package/bin/package.json +1 -0
  3. package/bin/skill-sync +576 -0
  4. package/bin/skill-sync-daemon +576 -0
  5. package/dist/daemons/skill-sync-daemon.js +500 -0
  6. package/dist/daemons/skill-sync-daemon.js.map +1 -0
  7. package/dist/entrypoints/skill-sync.js +153 -0
  8. package/dist/entrypoints/skill-sync.js.map +1 -0
  9. package/dist/index.js +10 -0
  10. package/dist/index.js.map +1 -0
  11. package/dist/internal/config.js +157 -0
  12. package/dist/internal/config.js.map +1 -0
  13. package/dist/internal/control.js +101 -0
  14. package/dist/internal/control.js.map +1 -0
  15. package/dist/internal/folders.js +46 -0
  16. package/dist/internal/folders.js.map +1 -0
  17. package/dist/internal/path.js +36 -0
  18. package/dist/internal/path.js.map +1 -0
  19. package/dist/internal/server.js +32 -0
  20. package/dist/internal/server.js.map +1 -0
  21. package/dist/internal/skill-check.js +83 -0
  22. package/dist/internal/skill-check.js.map +1 -0
  23. package/dist/internal/sync.js +162 -0
  24. package/dist/internal/sync.js.map +1 -0
  25. package/dist/internal/usage.js +419 -0
  26. package/dist/internal/usage.js.map +1 -0
  27. package/dist/internal/wire.js +24 -0
  28. package/dist/internal/wire.js.map +1 -0
  29. package/install.cjs +576 -0
  30. package/package.json +39 -11
  31. package/src/daemons/skill-sync-daemon.ts +493 -0
  32. package/src/entrypoints/skill-sync.ts +156 -0
  33. package/src/index.ts +15 -0
  34. package/src/internal/config.ts +198 -0
  35. package/src/internal/control.ts +140 -0
  36. package/src/internal/folders.ts +49 -0
  37. package/src/internal/path.ts +32 -0
  38. package/src/internal/server.ts +34 -0
  39. package/src/internal/skill-check.ts +97 -0
  40. package/src/internal/sync.ts +197 -0
  41. package/src/internal/usage.ts +457 -0
  42. package/src/internal/wire.ts +241 -0
  43. package/multi-call-binary +0 -4
@@ -0,0 +1,198 @@
1
+ import { createHash } from "node:crypto";
2
+ import { mkdirSync, readFileSync, writeFileSync, existsSync, readdirSync, rmSync, statSync } from "node:fs";
3
+ import { homedir, hostname, userInfo } from "node:os";
4
+ import { join, relative, sep } from "node:path";
5
+
6
+ /**
7
+ * Per-machine settings, sync state and the sync token, all under `~/.jive/`.
8
+ *
9
+ * A file rather than environment variables: the endpoint and which machine this is differ per computer
10
+ * and have to survive a login, which is exactly what a config file is for and exactly what an environment
11
+ * variable is not. Which folders to sync is not in here: they are detected, and the choice to leave one
12
+ * out is kept on the server so the dashboard can change it and a reinstalled daemon still remembers it.
13
+ */
14
+
15
+ const JIVE_HOME = join(homedir(), ".jive");
16
+ export const CONFIG_PATH = join(JIVE_HOME, "skill-sync.json");
17
+ const STATE_PATH = join(JIVE_HOME, "skill-sync-state.json");
18
+ /**
19
+ * The sync token, written at sign-in so the daemon is still signed in after a restart, a reboot or an
20
+ * upgrade. An ordinary file: anything that can read the home directory can copy the token, and the
21
+ * dashboard can revoke it.
22
+ */
23
+ export const TOKEN_PATH = join(JIVE_HOME, "skill-sync-token.json");
24
+ /**
25
+ * How the CLI reaches the running daemon: a Unix socket in `~/.jive/`, or a named pipe on Windows. Only
26
+ * this user can open either, which is what lets the CLI hand the daemon work that involves the token.
27
+ */
28
+ export const CONTROL_SOCKET = process.platform === "win32"
29
+ ? `\\\\.\\pipe\\jive-skill-sync-${userInfo().username}`
30
+ : join(JIVE_HOME, "skill-sync.sock");
31
+
32
+ /** Managed by Claude's own cloud sync; see `Settings.exclude`. */
33
+ const DEFAULT_EXCLUDE = ["synced"] as const;
34
+
35
+ /** What `~/.jive/skill-sync.json` holds: nothing secret, so it can live in a file. */
36
+ export interface Settings {
37
+ readonly endpoint: string;
38
+ /**
39
+ * Top-level directory names under each synced folder to leave alone.
40
+ *
41
+ * `synced` holds the skills Claude already pulls from the cloud itself. Syncing them here would mean
42
+ * two systems writing the same files, each undoing the other, and none of them are yours to edit.
43
+ * The list applies to every detected folder, so in `~/.agents/skills`, which Codex and Grok read, it
44
+ * keeps a skill named `synced` from syncing.
45
+ */
46
+ readonly exclude: ReadonlyArray<string>;
47
+ /** Names this machine on the server: on the dashboard, and as the machine each edit came from. */
48
+ readonly machine: string;
49
+ }
50
+
51
+ /** Settings plus the token, which the daemon has once signed in. */
52
+ export interface Config extends Settings {
53
+ readonly token: string;
54
+ }
55
+
56
+ /** Sync progress for one folder. Each folder syncs with the server on its own, so each has its own. */
57
+ export interface State {
58
+ /** Highest server sequence number already applied. */
59
+ cursor: number;
60
+ /** Last hash this machine agreed with the server on, per relative path. Absent means never synced. */
61
+ known: Record<string, string>;
62
+ /** The synced list as of last cycle, to notice a skill being added to it. */
63
+ skills?: string[];
64
+ }
65
+
66
+ /** Every folder's `State`, keyed by the folder's absolute path. */
67
+ export type States = Record<string, State>;
68
+
69
+ /**
70
+ * The settings, writing a template on first run. Undefined when the file lacks an endpoint or a machine
71
+ * name, which only happens if someone edited it.
72
+ */
73
+ export function loadSettings(): Settings | undefined {
74
+ if (!existsSync(CONFIG_PATH)) {
75
+ mkdirSync(JIVE_HOME, { recursive: true });
76
+ writeFileSync(CONFIG_PATH, `${JSON.stringify({
77
+ endpoint: "https://skill-sync.jive.sh",
78
+ machine: machineName(),
79
+ exclude: DEFAULT_EXCLUDE,
80
+ }, null, 2)}\n`);
81
+ }
82
+ const settings = readJson<Partial<Settings>>(CONFIG_PATH);
83
+ if (!settings.endpoint || !settings.machine) return undefined;
84
+ return { endpoint: settings.endpoint, machine: settings.machine, exclude: settings.exclude ?? DEFAULT_EXCLUDE };
85
+ }
86
+
87
+ function readJson<T>(path: string): T {
88
+ try {
89
+ return JSON.parse(readFileSync(path, "utf-8")) as T;
90
+ } catch {
91
+ return {} as T;
92
+ }
93
+ }
94
+
95
+ /**
96
+ * Every folder's sync state.
97
+ *
98
+ * Before folders were detected the file held one folder's `{ cursor, known }`, for the folder then named
99
+ * by `skillsDir` in the settings. That state is carried over to that folder: dropping it would make the
100
+ * folder look never-synced, and every file in it that differs from the server would become a conflict.
101
+ */
102
+ export function loadStates(): States {
103
+ const stored = readJson<Partial<State> & { folders?: States }>(STATE_PATH);
104
+ if (stored.folders !== undefined) return stored.folders;
105
+ const legacyFolder = readJson<{ skillsDir?: string }>(CONFIG_PATH).skillsDir;
106
+ if (legacyFolder !== undefined && stored.cursor !== undefined && stored.known !== undefined) {
107
+ return { [legacyFolder]: { cursor: stored.cursor, known: stored.known } };
108
+ }
109
+ return {};
110
+ }
111
+
112
+ /** The saved token, or undefined when this machine is signed out. */
113
+ export function loadToken(): string | undefined {
114
+ return readJson<{ token?: string }>(TOKEN_PATH).token;
115
+ }
116
+
117
+ export function saveToken(token: string): void {
118
+ mkdirSync(JIVE_HOME, { recursive: true });
119
+ writeFileSync(TOKEN_PATH, `${JSON.stringify({ token }, null, 2)}\n`);
120
+ }
121
+
122
+ export function deleteToken(): void {
123
+ rmSync(TOKEN_PATH, { force: true });
124
+ }
125
+
126
+ export function stateFor(states: States, folder: string): State {
127
+ states[folder] ??= { cursor: 0, known: {} };
128
+ return states[folder];
129
+ }
130
+
131
+ export function saveStates(states: States): void {
132
+ mkdirSync(JIVE_HOME, { recursive: true });
133
+ writeFileSync(STATE_PATH, `${JSON.stringify({ folders: states }, null, 2)}\n`);
134
+ }
135
+
136
+ /**
137
+ * A name ending in `.lock` is another program's lock, never an agent home, a skill or a skill's file.
138
+ * Claude Code locks a path by creating an empty `<path>.lock` folder beside it and removing it when done;
139
+ * counted as an agent home, `~/.claude-<name>.lock` was filled with skills and the lock could not be released.
140
+ */
141
+ export const isLock = (name: string): boolean => name.endsWith(".lock");
142
+
143
+ /** `HOSTNAME` is not set on macOS, so the template was writing "unknown" on exactly this machine. */
144
+ function machineName(): string {
145
+ return hostname().replace(/\.local$/, "").replace(/[^A-Za-z0-9-]+/g, "-") || "unknown";
146
+ }
147
+
148
+ /**
149
+ * The `skills` folder of every agent home in `home`: Claude's `~/.claude` and each `~/.claude-<name>`
150
+ * (each a `CLAUDE_CONFIG_DIR`), and `~/.agents/skills`, where both Codex and Grok read a user's skills.
151
+ * `~/.agents/skills` counts when `~/.agents`, Codex's home `~/.codex`, or a Grok home (`~/.grok` or a
152
+ * `~/.grok-<name>`, each a `GROK_HOME`) exists, because a machine with either installed may have no
153
+ * `~/.agents` yet. Grok also reads `$GROK_HOME/skills`, but syncing that too would give Grok every skill
154
+ * twice.
155
+ *
156
+ * Every home is a candidate, whether or not it has a `skills` folder yet, so an account added later
157
+ * joins without anyone listing it. Which of them actually sync is the user's choice on the dashboard; a
158
+ * folder that is synced and missing is created.
159
+ */
160
+ export function detectFolders(home: string = homedir()): string[] {
161
+ return [...new Set(readdirSync(home)
162
+ .filter((entry) => !isLock(entry))
163
+ .filter((entry) => statSync(join(home, entry)).isDirectory())
164
+ .flatMap((entry) => {
165
+ if (entry === ".claude" || entry.startsWith(".claude-")) return [join(home, entry, "skills")];
166
+ if (entry === ".agents" || entry === ".codex" || entry === ".grok" || entry.startsWith(".grok-")) {
167
+ return [join(home, ".agents", "skills")];
168
+ }
169
+ return [];
170
+ }))]
171
+ .sort();
172
+ }
173
+
174
+ export function hashBytes(bytes: Uint8Array): string {
175
+ return createHash("sha256").update(bytes).digest("hex");
176
+ }
177
+
178
+ /**
179
+ * Every file under a synced folder, as paths relative to it with forward slashes.
180
+ *
181
+ * Normalised because the same skill synced from Windows and macOS must be one row, not two.
182
+ */
183
+ export function listLocalFiles(folder: string, exclude: ReadonlyArray<string> = DEFAULT_EXCLUDE): string[] {
184
+ if (!existsSync(folder)) return [];
185
+
186
+ const found: string[] = [];
187
+ const walk = (dir: string, top: boolean): void => {
188
+ for (const entry of readdirSync(dir)) {
189
+ if (entry.startsWith(".") || isLock(entry)) continue;
190
+ if (top && exclude.includes(entry)) continue;
191
+ const full = join(dir, entry);
192
+ if (statSync(full).isDirectory()) walk(full, false);
193
+ else found.push(relative(folder, full).split(sep).join("/"));
194
+ }
195
+ };
196
+ walk(folder, true);
197
+ return found.sort();
198
+ }
@@ -0,0 +1,140 @@
1
+ import { createConnection, createServer, type Server, type Socket } from "node:net";
2
+ import { chmodSync, rmSync } from "node:fs";
3
+ import { CONTROL_SOCKET } from "./config";
4
+ import type { ListedSkill } from "./wire";
5
+
6
+ /**
7
+ * The channel between the CLI and the running daemon.
8
+ *
9
+ * The daemon owns the sync token: it receives it from the browser and keeps it in `~/.jive/`, so it never
10
+ * passes through the CLI. The CLI's `login`, `logout`, `list` and `add` are requests to the daemon over this
11
+ * channel. Messages are newline-delimited JSON; each request gets events until one that
12
+ * ends it.
13
+ */
14
+
15
+ export type ControlRequest =
16
+ | { readonly type: "login" }
17
+ | { readonly type: "logout" }
18
+ /** The synced list, which the daemon fetches from the server with its token. */
19
+ | { readonly type: "list" }
20
+ /** Puts a skill on this machine on the synced list, after checking its files (`checkSkillToAdd`). */
21
+ | { readonly type: "add"; readonly skill: string };
22
+
23
+ export type ControlEvent =
24
+ /** Sign-in has started: the CLI opens this URL in the browser, where the passkey is verified. */
25
+ | { readonly type: "open"; readonly url: string }
26
+ | { readonly type: "signedIn"; readonly machine: string }
27
+ | { readonly type: "signedOut"; readonly revoked: boolean }
28
+ | { readonly type: "list"; readonly skills: ReadonlyArray<ListedSkill> }
29
+ /**
30
+ * The skill is on the synced list. `added` is false when it already was. `folders` are this machine's
31
+ * folders that hold it; `syncingFolders` are those ticked on the dashboard, which upload it.
32
+ */
33
+ | {
34
+ readonly type: "added";
35
+ readonly skill: string;
36
+ readonly added: boolean;
37
+ readonly folders: ReadonlyArray<string>;
38
+ readonly syncingFolders: ReadonlyArray<string>;
39
+ }
40
+ | { readonly type: "error"; readonly message: string };
41
+
42
+ const isFinal = (event: ControlEvent): boolean => event.type !== "open";
43
+
44
+ /** The daemon is not running, as opposed to running and refusing the request. */
45
+ export class DaemonUnreachable extends Error {}
46
+
47
+ /** Sends one request and calls `onEvent` for each event until the final one, which it resolves with. */
48
+ export function request(message: ControlRequest, onEvent: (event: ControlEvent) => void): Promise<ControlEvent> {
49
+ return new Promise((resolve, reject) => {
50
+ let settled = false;
51
+ const socket = createConnection(CONTROL_SOCKET);
52
+ socket.on("connect", () => socket.write(`${JSON.stringify(message)}\n`));
53
+ socket.on("error", (cause: NodeJS.ErrnoException) => {
54
+ if (settled) return;
55
+ settled = true;
56
+ reject(cause.code === "ENOENT" || cause.code === "ECONNREFUSED"
57
+ ? new DaemonUnreachable(`the skill-sync daemon is not running (${cause.code} on ${CONTROL_SOCKET})`)
58
+ : cause);
59
+ });
60
+ readLines(socket, (line) => {
61
+ const event = JSON.parse(line) as ControlEvent;
62
+ onEvent(event);
63
+ if (isFinal(event) && !settled) {
64
+ settled = true;
65
+ socket.end();
66
+ resolve(event);
67
+ }
68
+ });
69
+ socket.on("close", () => {
70
+ if (!settled) {
71
+ settled = true;
72
+ reject(new Error("the daemon closed the connection without answering"));
73
+ }
74
+ });
75
+ });
76
+ }
77
+
78
+ /** One request being answered: send events, and end the conversation with a final one. */
79
+ export interface Reply {
80
+ readonly send: (event: ControlEvent) => void;
81
+ }
82
+
83
+ /**
84
+ * Listens on the control socket. Resolves false, without listening, when another live daemon already
85
+ * holds it: two installs of skill-sync mean two daemons, and the second stands down rather than fight.
86
+ */
87
+ export async function serve(handle: (message: ControlRequest, reply: Reply) => void): Promise<Server | false> {
88
+ if (await answers()) return false;
89
+ // Nothing answered, so a socket file left here is from a daemon that died; it would block the listen.
90
+ if (process.platform !== "win32") rmSync(CONTROL_SOCKET, { force: true });
91
+
92
+ const server = createServer((socket) => {
93
+ const reply: Reply = {
94
+ send: (event) => {
95
+ if (socket.writable) socket.write(`${JSON.stringify(event)}\n`);
96
+ if (isFinal(event)) socket.end();
97
+ },
98
+ };
99
+ readLines(socket, (line) => {
100
+ try {
101
+ handle(JSON.parse(line) as ControlRequest, reply);
102
+ } catch (cause) {
103
+ reply.send({ type: "error", message: cause instanceof Error ? cause.message : String(cause) });
104
+ }
105
+ });
106
+ socket.on("error", () => undefined); // A CLI that went away mid-request; nothing to tell it.
107
+ });
108
+ await new Promise<void>((resolve, reject) => {
109
+ server.once("error", reject);
110
+ server.listen(CONTROL_SOCKET, () => resolve());
111
+ });
112
+ // Only this user may talk to the daemon that holds their token.
113
+ if (process.platform !== "win32") chmodSync(CONTROL_SOCKET, 0o600);
114
+ return server;
115
+ }
116
+
117
+ /** Whether a live daemon is listening on the control socket. */
118
+ function answers(): Promise<boolean> {
119
+ return new Promise((resolve) => {
120
+ const socket = createConnection(CONTROL_SOCKET);
121
+ socket.on("connect", () => {
122
+ socket.end();
123
+ resolve(true);
124
+ });
125
+ socket.on("error", () => resolve(false));
126
+ });
127
+ }
128
+
129
+ function readLines(socket: Socket, onLine: (line: string) => void): void {
130
+ let buffer = "";
131
+ socket.on("data", (chunk) => {
132
+ buffer += chunk.toString();
133
+ let newline: number;
134
+ while ((newline = buffer.indexOf("\n")) >= 0) {
135
+ const line = buffer.slice(0, newline).trim();
136
+ buffer = buffer.slice(newline + 1);
137
+ if (line !== "") onLine(line);
138
+ }
139
+ });
140
+ }
@@ -0,0 +1,49 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { detectFolders, hashBytes, listLocalFiles, type Config } from "./config";
4
+ import { fetchServer } from "./server";
5
+ import {
6
+ skillOf, type FileHash, type FolderPrefs, type FoldersRequest, type FoldersResponse, type LocalSkill,
7
+ } from "./wire";
8
+
9
+ /**
10
+ * What this machine tells the service about its folders, and what it hears back.
11
+ *
12
+ * The daemon and the CLI both register, so this lives in one place: they must describe a folder the same
13
+ * way, or the dashboard would show whichever of them spoke last.
14
+ */
15
+
16
+ /**
17
+ * The skills on disk in one folder, with each file's hash. Hashing every file on each check is cheap at
18
+ * skills' size, and it is what lets the dashboard show whether this folder's copy is the synced one.
19
+ */
20
+ export function localSkills(folder: string, config: Config): LocalSkill[] {
21
+ const byName = new Map<string, FileHash[]>();
22
+ for (const path of listLocalFiles(folder, config.exclude)) {
23
+ const name = skillOf(path);
24
+ let hash: string;
25
+ try {
26
+ hash = hashBytes(readFileSync(join(folder, path)));
27
+ } catch {
28
+ continue; // Deleted between listing and reading; the next check reports the folder as it is.
29
+ }
30
+ byName.set(name, [...(byName.get(name) ?? []), { path, hash }]);
31
+ }
32
+ return [...byName].map(([name, files]) => ({ name, files }));
33
+ }
34
+
35
+ /** Everything registration sends, so a caller can tell when it has changed and is worth re-sending. */
36
+ export function describe(config: Config): FoldersRequest {
37
+ return { folders: detectFolders().map((path) => ({ path, skills: localSkills(path, config) })) };
38
+ }
39
+
40
+ /** Registers this machine's folders and skills; returns the folders to sync and the skills in each. */
41
+ export async function register(config: Config, request: FoldersRequest): Promise<ReadonlyArray<FolderPrefs>> {
42
+ const response = await fetchServer(config, "/folders", {
43
+ method: "POST",
44
+ headers: { "content-type": "application/json" },
45
+ body: JSON.stringify(request),
46
+ });
47
+ if (!response.ok) throw new Error(`POST /folders: ${response.status} ${await response.text()}`);
48
+ return (await response.json() as FoldersResponse).folders;
49
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Validation for the one piece of untrusted input that becomes a filesystem path.
3
+ *
4
+ * Shared by the Worker and the daemon on purpose, and deliberately free of any Node import so the Worker
5
+ * can bundle it. Both ends check: the server so one compromised client cannot poison what every machine
6
+ * pulls, and the daemon because a server it does not control is not a thing to take paths from either.
7
+ *
8
+ * Without this, a pushed path of `../../.ssh/authorized_keys` is joined to the skills directory and
9
+ * written wherever the daemon's user can write.
10
+ */
11
+
12
+ /** Long enough for any real nesting, short enough that nothing can be used to exhaust anything. */
13
+ const MAX_LENGTH = 512;
14
+
15
+ export function invalidPathReason(path: string): string | undefined {
16
+ if (path.length === 0 || path.length > MAX_LENGTH) return "path is empty or too long";
17
+ if (path.includes("\0")) return "path contains a null byte";
18
+ if (path.includes("\\")) return "path must use forward slashes";
19
+ if (path.startsWith("/")) return "path must be relative";
20
+ // A Windows drive letter is absolute on the machine that matters even though it has no leading slash.
21
+ if (/^[A-Za-z]:/.test(path)) return "path must be relative";
22
+
23
+ for (const segment of path.split("/")) {
24
+ if (segment === "") return "path has an empty segment";
25
+ if (segment === "." || segment === "..") return "path must not contain . or .. segments";
26
+ }
27
+ return undefined;
28
+ }
29
+
30
+ export function isValidPath(path: string): boolean {
31
+ return invalidPathReason(path) === undefined;
32
+ }
@@ -0,0 +1,34 @@
1
+ import type { Config } from "./config";
2
+
3
+ /**
4
+ * Requests to the skill-sync service, signed with this machine's token.
5
+ *
6
+ * Every request goes through `fetchServer`, so a token the server no longer accepts is noticed the same
7
+ * way whichever request hits it first.
8
+ */
9
+
10
+ /** The server answered 401: the token was revoked or is unknown, so no retry with it can succeed. */
11
+ export class TokenRejected extends Error {
12
+ constructor(message: string, readonly token: string) {
13
+ super(message);
14
+ }
15
+ }
16
+
17
+ export function authHeaders(config: Config, extra: Record<string, string>): Record<string, string> {
18
+ return { authorization: `Bearer ${config.token}`, "x-skill-sync-machine": config.machine, ...extra };
19
+ }
20
+
21
+ /**
22
+ * Sends one request to the server with the token. Throws `TokenRejected` on 401; every other status is
23
+ * returned for the caller to judge, since some (a 409 from `PUT /files`) are answers rather than failures.
24
+ */
25
+ export async function fetchServer(config: Config, path: string, init: RequestInit = {}): Promise<Response> {
26
+ const response = await fetch(`${config.endpoint}${path}`, {
27
+ ...init,
28
+ headers: authHeaders(config, (init.headers ?? {}) as Record<string, string>),
29
+ });
30
+ if (response.status === 401) {
31
+ throw new TokenRejected(`${init.method ?? "GET"} ${path}: the server rejected this machine's token`, config.token);
32
+ }
33
+ return response;
34
+ }
@@ -0,0 +1,97 @@
1
+ import { existsSync, readFileSync, statSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { isSkillName } from "./wire";
4
+
5
+ /**
6
+ * Whether a skill on this machine may go on the synced list, checked before `skill-sync add` asks the
7
+ * server to add it.
8
+ *
9
+ * The synced list is for skills meant for every project. A skill made for one project lives in that
10
+ * project (its `.claude/skills`, `.agents/skills` or `.grok/skills`), which is never one of the folders
11
+ * skill-sync detects, so a skill is accepted only from a detected folder. That is the one sign of a
12
+ * project-specific skill that can be read from disk; a skill written into a home folder but about one
13
+ * project is not caught here.
14
+ */
15
+ export type SkillCheck =
16
+ | { readonly ok: true; readonly folders: ReadonlyArray<string> }
17
+ | { readonly ok: false; readonly reason: string };
18
+
19
+ export function checkSkillToAdd(input: {
20
+ readonly skill: string;
21
+ /** The skills folders skill-sync detects on this machine (`detectFolders`). */
22
+ readonly folders: ReadonlyArray<string>;
23
+ /** Top-level names skill-sync never syncs (`Settings.exclude`). */
24
+ readonly exclude: ReadonlyArray<string>;
25
+ }): SkillCheck {
26
+ const { skill, folders, exclude } = input;
27
+ if (!isSkillName(skill)) {
28
+ return { ok: false, reason: `"${skill}" is not a skill name: lowercase letters and digits in hyphen-joined words, at most 64 characters` };
29
+ }
30
+ if (exclude.includes(skill)) {
31
+ return { ok: false, reason: `"${skill}" is excluded from syncing in ~/.jive/skill-sync.json` };
32
+ }
33
+ const holding = folders.filter((folder) => isDirectory(join(folder, skill)));
34
+ if (holding.length === 0) {
35
+ return {
36
+ ok: false,
37
+ reason: `no skills folder skill-sync syncs has a "${skill}" folder; it looked in ${folders.join(", ") || "no folders"}. `
38
+ + "Only skills meant for every project sync: write the skill into one of those folders. A skill inside a "
39
+ + "project's own skills folder is specific to that project and stays there.",
40
+ };
41
+ }
42
+ for (const folder of holding) {
43
+ const problem = frontmatterProblem(skill, join(folder, skill, "SKILL.md"));
44
+ if (problem !== undefined) return { ok: false, reason: problem };
45
+ }
46
+ return { ok: true, folders: holding };
47
+ }
48
+
49
+ /** Why a skill's `SKILL.md` would not load as that skill, or undefined when it would. */
50
+ function frontmatterProblem(skill: string, path: string): string | undefined {
51
+ if (!existsSync(path)) return `${path} does not exist; every skill needs a SKILL.md`;
52
+ const fields = readFrontmatter(readFileSync(path, "utf8"));
53
+ if (fields === undefined) return `${path} does not start with a frontmatter block between --- lines`;
54
+ const name = fields.get("name");
55
+ if (name === undefined || name === "") return `${path}'s frontmatter has no name`;
56
+ if (name !== skill) return `${path}'s frontmatter name is "${name}", but its folder is "${skill}"; they must match`;
57
+ if ((fields.get("description") ?? "") === "") return `${path}'s frontmatter has no description, which is how agents decide to load it`;
58
+ return undefined;
59
+ }
60
+
61
+ /**
62
+ * The top-level keys of a `SKILL.md`'s frontmatter, with their values as text. Covers what skills use: a
63
+ * plain or quoted value on the key's line, or a block (`>` or `|`) on the indented lines after it.
64
+ */
65
+ export function readFrontmatter(text: string): Map<string, string> | undefined {
66
+ const lines = text.replace(/^/, "").split(/\r?\n/);
67
+ if (lines[0]?.trim() !== "---") return undefined;
68
+ const end = lines.findIndex((line, index) => index > 0 && line.trim() === "---");
69
+ if (end === -1) return undefined;
70
+ const fields = new Map<string, string>();
71
+ let blockKey: string | undefined;
72
+ for (const line of lines.slice(1, end)) {
73
+ const field = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(line);
74
+ if (field !== null) {
75
+ const key = field[1]!;
76
+ const raw = field[2]!;
77
+ blockKey = /^[>|][+-]?$/.test(raw.trim()) ? key : undefined;
78
+ fields.set(key, blockKey === undefined ? unquote(raw.trim()) : "");
79
+ } else if (blockKey !== undefined && /^\s+\S/.test(line)) {
80
+ fields.set(blockKey, `${fields.get(blockKey)} ${line.trim()}`.trim());
81
+ }
82
+ }
83
+ return fields;
84
+ }
85
+
86
+ function unquote(value: string): string {
87
+ const quoted = /^(["'])(.*)\1$/.exec(value);
88
+ return quoted === null ? value : quoted[2]!;
89
+ }
90
+
91
+ function isDirectory(path: string): boolean {
92
+ try {
93
+ return statSync(path).isDirectory();
94
+ } catch {
95
+ return false;
96
+ }
97
+ }