musubi-cli 0.1.0 → 0.3.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.
package/dist/graph.js CHANGED
@@ -5,83 +5,211 @@ import { format } from "./semver.js";
5
5
  const escape = (text) => text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
6
6
  // Inside a quoted attribute only "&", "<", and the quote need escaping, so edges keep their "->".
7
7
  const attribute = (text) => text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/"/g, "&quot;");
8
- const NODE_W = 220;
8
+ const NODE_W = 232;
9
9
  const NODE_H = 64;
10
- const GAP_X = 120;
11
- const GAP_Y = 28;
10
+ const GAP_X = 160;
11
+ const GAP_Y = 26;
12
12
  const PAD = 24;
13
- // Writes one self-contained HTML page that draws each skill as a box and each followed content as
14
- // an arrow from the consumer to the provider. Providers sit to the right of the skills that follow them.
15
- export function graph(roots, out, cwd) {
16
- const report = new Report(cwd);
17
- const { declarations } = load(roots, report);
18
- const edges = [];
19
- for (const declaration of declarations.values()) {
20
- for (const follow of declaration.follows) {
21
- edges.push({ from: declaration.skill.name, to: follow.skill, ref: follow.ref, range: follow.range?.text ?? "?" });
22
- }
13
+ // Labels are drawn in a monospace face at this size, and each declares its width as textLength,
14
+ // so the room left for them does not depend on the font the viewer has.
15
+ const LABEL_SIZE = 11;
16
+ const LABEL_CHAR = LABEL_SIZE * 0.6;
17
+ const LABEL_INSET = 12;
18
+ const LABEL_RISE = 8;
19
+ const LABEL_STEP = 15;
20
+ const BEND_ROOM = 96;
21
+ // A line leaves its box from a small round port and ends in a ">" head just left of the box it points to.
22
+ const PORT_R = 3.5;
23
+ const HEAD_GAP = 3;
24
+ const HEAD_LEN = 7;
25
+ const HEAD_HALF = 5.5;
26
+ // Lines into one box arrive this far apart, kept this far inside the box's top and bottom.
27
+ const ENTRY_GAP = 12;
28
+ const ENTRY_MARGIN = 10;
29
+ // The light runs along each line once a loop. Its trail is three strokes, measured in hundredths of
30
+ // the line, so every line takes the same time from end to end. The light travels for TRAVEL of the
31
+ // loop, reaches the head at ARRIVE, and the head lights up as it arrives.
32
+ const LOOP = "2.4s";
33
+ const TAILS = [
34
+ [26, 5, 0.14],
35
+ [15, 3, 0.4],
36
+ [6, 2.2, 0.95],
37
+ ];
38
+ const TRAVEL = 0.8;
39
+ const REACH = 100 + TAILS[0][0];
40
+ const ARRIVE = (TRAVEL * 100) / REACH;
41
+ const labelWidth = (label) => Math.ceil(label.length * LABEL_CHAR);
42
+ const num = (value) => String(Math.round(value * 100) / 100);
43
+ const times = (...values) => values.map((v) => String(Math.round(v * 1000) / 1000)).join(";");
44
+ // Ids of the lines, so the light can follow them. The prefix comes from the edges, so two graphs on
45
+ // one page do not share ids and the same graph always gets the same ids.
46
+ function idPrefix(edges) {
47
+ let hash = 0x811c9dc5;
48
+ for (const char of edges.map((e) => e.key).join("\n")) {
49
+ hash ^= char.codePointAt(0);
50
+ hash = Math.imul(hash, 0x01000193) >>> 0;
23
51
  }
24
- const names = new Set([...declarations.keys(), ...edges.map((e) => e.to)]);
25
- // A skill's column is the length of the longest chain of skills that follow it, so arrows point right.
52
+ return `musubi-${hash.toString(36)}`;
53
+ }
54
+ // The line, its moving light, its head, and its port. The line comes first, so readers of the SVG
55
+ // that take an edge's first path get the line.
56
+ function edgeLight(id, d, start, tip) {
57
+ const loop = `dur="${LOOP}" repeatCount="indefinite"`;
58
+ const tails = TAILS.map(([length, width, opacity]) => `<path class="tail" d="${d}" pathLength="100" stroke-width="${width}" opacity="${opacity}" stroke-dasharray="${length} 300">` +
59
+ `<animate attributeName="stroke-dashoffset" values="${length};${length - REACH};${length - REACH}" keyTimes="${times(0, TRAVEL, 1)}" ${loop}/></path>`).join("");
60
+ const [tx, ty] = tip;
61
+ const head = `M${num(tx - HEAD_LEN)},${num(ty - HEAD_HALF)} L${num(tx)},${num(ty)} L${num(tx - HEAD_LEN)},${num(ty + HEAD_HALF)}`;
62
+ const flash = `<animate attributeName="opacity" values="0;0;1;0;0" keyTimes="${times(0, ARRIVE - 0.035, ARRIVE + 0.015, ARRIVE + 0.225, 1)}" ${loop}/>`;
63
+ return [
64
+ `<path class="line" id="${id}" d="${d}"/>`,
65
+ tails,
66
+ `<path class="chevron" d="${head}"/>`,
67
+ `<path class="chevron flash" d="${head}">${flash}</path>`,
68
+ `<circle class="dot" r="3"><animateMotion ${loop} calcMode="linear" keyPoints="0;1;1" keyTimes="${times(0, ARRIVE, 1)}"><mpath href="#${id}"/></animateMotion>`,
69
+ `<animate attributeName="opacity" values="1;1;0;0" keyTimes="${times(0, ARRIVE, ARRIVE + 0.025, 1)}" ${loop}/></circle>`,
70
+ `<circle class="port" cx="${num(start[0])}" cy="${num(start[1])}" r="${PORT_R}"/>`,
71
+ ].join("");
72
+ }
73
+ // Draws each node as a box and each edge as an arrow from the follower to the provider, as one SVG.
74
+ // A node's column is the length of the longest chain of nodes that follow it, so providers sit to the
75
+ // right of the skills that follow them and every arrow points right.
76
+ // Every arrow leaves its box in a straight line that runs past the longest label leaving that column,
77
+ // and only bends after it, so no line crosses a label. Labels of one box stack upward over its line.
78
+ export function graphSvg(nodes, edges) {
26
79
  const depth = new Map();
27
- const column = (name, seen) => {
28
- if (depth.has(name))
29
- return depth.get(name);
30
- if (seen.has(name))
80
+ const column = (id, seen) => {
81
+ if (depth.has(id))
82
+ return depth.get(id);
83
+ if (seen.has(id))
31
84
  return 0;
32
- seen.add(name);
33
- const followers = edges.filter((e) => e.to === name).map((e) => column(e.from, seen) + 1);
85
+ seen.add(id);
86
+ const followers = edges.filter((e) => e.to === id).map((e) => column(e.from, seen) + 1);
34
87
  const value = followers.length > 0 ? Math.max(...followers) : 0;
35
- depth.set(name, value);
88
+ depth.set(id, value);
36
89
  return value;
37
90
  };
38
- const nodes = new Map();
91
+ const placed = new Map();
39
92
  const rows = new Map();
40
- for (const name of [...names].sort()) {
41
- const c = column(name, new Set());
93
+ for (const node of nodes) {
94
+ const c = column(node.id, new Set());
42
95
  const row = rows.get(c) ?? 0;
43
96
  rows.set(c, row + 1);
44
- const provides = [...(declarations.get(name)?.provides.values() ?? [])].map((p) => `${p.name} ${p.version ? format(p.version) : "?"}`);
45
- nodes.set(name, { name, column: c, row, provides });
97
+ placed.set(node.id, { node, column: c, row });
46
98
  }
47
- const columns = Math.max(1, ...[...nodes.values()].map((n) => n.column + 1));
99
+ const drawn = edges.filter((e) => placed.has(e.from) && placed.has(e.to));
100
+ // The straight run out of a column ends past the widest label that leaves any box in it.
101
+ const run = new Map();
102
+ const stack = new Map();
103
+ for (const e of drawn) {
104
+ const c = placed.get(e.from).column;
105
+ run.set(c, Math.max(run.get(c) ?? 0, LABEL_INSET * 2 + labelWidth(e.label)));
106
+ stack.set(e.from, (stack.get(e.from) ?? 0) + 1);
107
+ }
108
+ const gap = Math.max(GAP_X, ...[...run.values()].map((r) => r + BEND_ROOM));
109
+ const stacked = Math.max(1, ...stack.values());
110
+ // Room above the first row for the highest label of a box with many arrows.
111
+ const head = PAD + Math.max(0, LABEL_RISE + LABEL_SIZE + (stacked - 1) * LABEL_STEP - (PAD + NODE_H / 2));
112
+ const columns = Math.max(1, ...[...placed.values()].map((p) => p.column + 1));
48
113
  const maxRows = Math.max(1, ...rows.values());
49
- const width = PAD * 2 + columns * NODE_W + (columns - 1) * GAP_X;
50
- const height = PAD * 2 + maxRows * NODE_H + (maxRows - 1) * GAP_Y;
51
- const x = (n) => PAD + n.column * (NODE_W + GAP_X);
52
- const y = (n) => PAD + n.row * (NODE_H + GAP_Y);
53
- const edgeSvg = edges
54
- .map((e) => {
55
- const a = nodes.get(e.from);
56
- const b = nodes.get(e.to);
114
+ const width = PAD * 2 + columns * NODE_W + (columns - 1) * gap;
115
+ const height = head + PAD + maxRows * NODE_H + (maxRows - 1) * GAP_Y;
116
+ // Columns with fewer boxes are centred against the tallest column.
117
+ const top = (c) => (height - head - PAD - ((rows.get(c) ?? 1) * NODE_H + ((rows.get(c) ?? 1) - 1) * GAP_Y)) / 2;
118
+ const x = (p) => PAD + p.column * (NODE_W + gap);
119
+ const y = (p) => head + top(p.column) + p.row * (NODE_H + GAP_Y);
120
+ // Lines into one box arrive at different heights, in the order of the boxes they come from, so their
121
+ // heads do not sit on one point and the lines do not cross on the way in.
122
+ const middle = (id) => y(placed.get(id)) + NODE_H / 2;
123
+ const entry = new Map();
124
+ for (const to of new Set(drawn.map((e) => e.to))) {
125
+ const into = drawn.filter((e) => e.to === to).sort((a, b) => middle(a.from) - middle(b.from) || drawn.indexOf(a) - drawn.indexOf(b));
126
+ const step = into.length > 1 ? Math.min(ENTRY_GAP, (NODE_H - 2 * ENTRY_MARGIN) / (into.length - 1)) : 0;
127
+ into.forEach((e, i) => entry.set(e, (i - (into.length - 1) / 2) * step));
128
+ }
129
+ const prefix = idPrefix(drawn);
130
+ const seen = new Map();
131
+ const edgeSvg = drawn
132
+ .map((e, i) => {
133
+ const a = placed.get(e.from);
134
+ const b = placed.get(e.to);
57
135
  const x1 = x(a) + NODE_W;
58
136
  const y1 = y(a) + NODE_H / 2;
59
- const x2 = x(b);
60
- const y2 = y(b) + NODE_H / 2;
61
- const mid = (x1 + x2) / 2;
62
- const label = `${e.ref.split("/")[1]} ${e.range}`;
137
+ const sx = x1 + PORT_R;
138
+ const xs = x1 + run.get(a.column);
139
+ const tip = x(b) - HEAD_GAP;
140
+ const x2 = tip - 0.5;
141
+ const y2 = y(b) + NODE_H / 2 + entry.get(e);
142
+ const k = seen.get(e.from) ?? 0;
143
+ seen.set(e.from, k + 1);
144
+ const straight = Math.abs(y1 - y2) < 0.01;
145
+ // A box's only line, when it does not bend, carries its label over its middle. Every other label
146
+ // sits over the straight run its box's lines share, before any of them bends.
147
+ const alone = straight && stack.get(e.from) === 1;
148
+ const mid = (xs + x2) / 2;
149
+ const d = alone
150
+ ? `M${num(sx)},${num(y1)} H${num(x2)}`
151
+ : straight
152
+ ? `M${num(sx)},${num(y1)} H${num(xs)} H${num(x2)}`
153
+ : `M${num(sx)},${num(y1)} H${num(xs)} C${num(mid)},${num(y1)} ${num(mid)},${num(y2)} ${num(x2)},${num(y2)}`;
154
+ const centre = alone ? (sx + x2) / 2 : (sx + xs) / 2;
155
+ const labelW = labelWidth(e.label);
63
156
  return [
64
- `<g class="edge" data-edge="${attribute(`${e.from} -> ${e.ref}`)}">`,
65
- `<path d="M${x1},${y1} C${mid},${y1} ${mid},${y2} ${x2 - 6},${y2}" marker-end="url(#arrow)"/>`,
66
- `<text x="${mid}" y="${(y1 + y2) / 2 - 8}" text-anchor="middle">${escape(label)}</text>`,
157
+ `<g class="edge" data-edge="${attribute(e.key)}">`,
158
+ edgeLight(`${prefix}-${i}`, d, [x1, y1], [tip, y2]),
159
+ `<text class="label" x="${num(centre - labelW / 2)}" y="${num(y1 - LABEL_RISE - k * LABEL_STEP)}" font-size="${LABEL_SIZE}" textLength="${labelW}" lengthAdjust="spacingAndGlyphs">${escape(e.label)}</text>`,
67
160
  "</g>",
68
161
  ].join("");
69
162
  })
70
163
  .join("\n");
71
- const nodeSvg = [...nodes.values()]
72
- .map((n) => {
73
- const detail = n.provides.length > 0 ? `provides ${n.provides.join(", ")}` : declarations.has(n.name) ? "follows only" : "not installed";
74
- return [
75
- `<g class="node${declarations.has(n.name) ? "" : " missing"}" data-skill="${attribute(n.name)}">`,
76
- `<rect x="${x(n)}" y="${y(n)}" width="${NODE_W}" height="${NODE_H}" rx="10"/>`,
77
- `<text class="name" x="${x(n) + 14}" y="${y(n) + 26}">${escape(n.name)}</text>`,
78
- `<text class="detail" x="${x(n) + 14}" y="${y(n) + 46}">${escape(detail)}</text>`,
79
- "</g>",
164
+ const nodeSvg = [...placed.values()]
165
+ .map((p) => {
166
+ const n = p.node;
167
+ const classes = ["node", n.missing ? "missing" : "", n.current ? "current" : ""].filter(Boolean).join(" ");
168
+ const cx = num(x(p) + NODE_W / 2);
169
+ const box = [
170
+ `<rect x="${x(p)}" y="${y(p)}" width="${NODE_W}" height="${NODE_H}" rx="10"/>`,
171
+ `<text class="name" x="${cx}" y="${num(y(p) + 22)}" text-anchor="middle" dominant-baseline="central">${escape(n.name)}</text>`,
172
+ `<text class="detail" x="${cx}" y="${num(y(p) + 43)}" text-anchor="middle" dominant-baseline="central">${escape(n.detail)}</text>`,
80
173
  ].join("");
174
+ const inner = n.href ? `<a href="${attribute(n.href)}">${box}</a>` : box;
175
+ return `<g class="${classes}" data-skill="${attribute(n.id)}">${inner}</g>`;
81
176
  })
82
177
  .join("\n");
83
- const rowsHtml = edges
84
- .map((e) => `<tr><td>${escape(e.from)}</td><td>${escape(e.ref)}</td><td>${escape(e.range)}</td></tr>`)
178
+ // Lines come after the boxes, so the half of each port that sits over a box's edge stays visible.
179
+ const svg = `<svg width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" role="img" aria-label="Skill dependency graph">
180
+ ${nodeSvg}
181
+ ${edgeSvg}
182
+ </svg>`;
183
+ return { svg, width, height };
184
+ }
185
+ // Writes one self-contained HTML page that draws each skill as a box and each followed content as
186
+ // an arrow from the consumer to the provider. Providers sit to the right of the skills that follow them.
187
+ export function graph(roots, out, cwd) {
188
+ const report = new Report(cwd);
189
+ const { declarations } = load(roots, report);
190
+ const edges = [];
191
+ const follows = [];
192
+ for (const declaration of declarations.values()) {
193
+ for (const follow of declaration.follows) {
194
+ const range = follow.range?.text ?? "?";
195
+ follows.push({ from: declaration.skill.name, ref: follow.ref, range });
196
+ edges.push({
197
+ from: declaration.skill.name,
198
+ to: follow.skill,
199
+ label: `${follow.content} ${range}`,
200
+ key: `${declaration.skill.name} -> ${follow.ref}`,
201
+ });
202
+ }
203
+ }
204
+ const names = [...new Set([...declarations.keys(), ...edges.map((e) => e.to)])].sort();
205
+ const nodes = names.map((name) => {
206
+ const provides = [...(declarations.get(name)?.provides.values() ?? [])].map((p) => `${p.name} ${p.version ? format(p.version) : "?"}`);
207
+ const detail = provides.length > 0 ? `provides ${provides.join(", ")}` : declarations.has(name) ? "follows only" : "not installed";
208
+ return { id: name, name, detail, missing: !declarations.has(name) };
209
+ });
210
+ const { svg } = graphSvg(nodes, edges);
211
+ const rowsHtml = follows
212
+ .map((f) => `<tr><td>${escape(f.from)}</td><td>${escape(f.ref)}</td><td>${escape(f.range)}</td></tr>`)
85
213
  .join("\n");
86
214
  const html = `<!doctype html>
87
215
  <html lang="en">
@@ -101,22 +229,23 @@ svg text { fill: var(--fg); font: 13px system-ui, sans-serif; }
101
229
  .node.missing rect { stroke: #c0503a; stroke-dasharray: 5 4; }
102
230
  .node .name { font-weight: 600; font-size: 14px; }
103
231
  .node .detail { fill: var(--muted); font-size: 12px; }
104
- .edge path { fill: none; stroke: var(--line); stroke-width: 1.5; }
105
- .edge text { fill: var(--muted); font-size: 12px; }
106
- #arrow path { fill: var(--line); }
232
+ .edge .line { fill: none; stroke: var(--line); stroke-width: 1.5; stroke-linecap: round; }
233
+ .edge .tail { fill: none; stroke: var(--accent); stroke-linecap: round; }
234
+ .edge .dot { fill: var(--accent); filter: drop-shadow(0 0 2px var(--accent)) drop-shadow(0 0 5px var(--accent)); }
235
+ .edge .chevron { fill: none; stroke: var(--line); stroke-width: 1.6; stroke-linecap: round; stroke-linejoin: round; }
236
+ .edge .chevron.flash { stroke: var(--accent); opacity: 0; filter: drop-shadow(0 0 4px var(--accent)); }
237
+ .edge .port { fill: var(--bg); stroke: var(--line); stroke-width: 1.5; }
238
+ .edge text { fill: var(--muted); font: 11px ui-monospace, "JetBrains Mono", Menlo, monospace; }
239
+ @media (prefers-reduced-motion: reduce) { .edge .tail, .edge .dot, .edge .flash { display: none; } }
107
240
  table { border-collapse: collapse; margin-top: 20px; }
108
241
  th, td { text-align: left; padding: 6px 14px 6px 0; border-bottom: 1px solid var(--line); }
109
242
  </style>
110
243
  </head>
111
244
  <body>
112
245
  <h1>Skill dependencies</h1>
113
- <p>Each arrow runs from a skill to the content it follows. ${nodes.size} skills, ${edges.length} followed contents.</p>
246
+ <p>Each arrow runs from a skill to the content it follows. ${nodes.length} skills, ${follows.length} followed contents.</p>
114
247
  <div class="canvas">
115
- <svg width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" role="img" aria-label="Skill dependency graph">
116
- <defs><marker id="arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 z"/></marker></defs>
117
- ${edgeSvg}
118
- ${nodeSvg}
119
- </svg>
248
+ ${svg}
120
249
  </div>
121
250
  <table>
122
251
  <thead><tr><th>Skill</th><th>Follows</th><th>Range</th></tr></thead>
@@ -129,6 +258,6 @@ ${rowsHtml}
129
258
  `;
130
259
  writeFileSync(out, html);
131
260
  report.print();
132
- process.stderr.write(`musubi graph: wrote ${report.where(out)} (skills=${nodes.size}, follows=${edges.length})\n`);
261
+ process.stderr.write(`musubi graph: wrote ${report.where(out)} (skills=${nodes.length}, follows=${follows.length})\n`);
133
262
  return 0;
134
263
  }
@@ -0,0 +1,168 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, realpathSync, rmSync, statSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { basename, join, relative, resolve } from "node:path";
5
+ import { check } from "./check.js";
6
+ import { Report } from "./report.js";
7
+ import { format, satisfies } from "./semver.js";
8
+ import { defaultRoots, discover, FOLDERS, readDeclaration } from "./skills.js";
9
+ const GIT_URL = /^(?:https?|ssh|git|file):\/\/|^[^@\s]+@[^:\s]+:/;
10
+ // Every folder in the source that holds a SKILL.md is a skill named by its folder, however deep it
11
+ // sits, because repositories keep skills under plugins/<name>/skills/ or .claude/skills/ alike.
12
+ function skillsIn(root) {
13
+ const found = new Map();
14
+ const seen = new Set();
15
+ const walk = (dir) => {
16
+ const real = realpathSync(dir);
17
+ if (seen.has(real))
18
+ return;
19
+ seen.add(real);
20
+ if (dir !== root && existsSync(join(dir, "SKILL.md"))) {
21
+ found.set(basename(dir), [...(found.get(basename(dir)) ?? []), dir]);
22
+ return;
23
+ }
24
+ for (const name of readdirSync(dir).sort()) {
25
+ if (name === ".git" || name === "node_modules")
26
+ continue;
27
+ const path = join(dir, name);
28
+ if (statSync(path, { throwIfNoEntry: false })?.isDirectory())
29
+ walk(path);
30
+ }
31
+ };
32
+ walk(root);
33
+ return found;
34
+ }
35
+ // A follow's provider is installed without being named when one of the user's languages has the
36
+ // same primary language as one of the follow's, so ja-JP matches ja.
37
+ function languageMatches(follow, languages) {
38
+ const primary = (tag) => tag.split("-")[0].toLowerCase();
39
+ return follow.languages.some((tag) => languages.some((language) => primary(language) === primary(tag)));
40
+ }
41
+ export function install(o) {
42
+ let to;
43
+ if (o.to !== null)
44
+ to = resolve(o.cwd, o.to);
45
+ else {
46
+ const first = FOLDERS.map((folder) => resolve(o.cwd, folder)).find((dir) => statSync(dir, { throwIfNoEntry: false })?.isDirectory());
47
+ if (!first) {
48
+ process.stderr.write(`musubi install: no skills folder (${FOLDERS.join(", ")}) in this folder; name one with --to\n`);
49
+ return 2;
50
+ }
51
+ to = first;
52
+ }
53
+ const temporary = [];
54
+ try {
55
+ const sources = [];
56
+ for (const given of o.sources) {
57
+ const folder = resolve(o.cwd, given);
58
+ if (statSync(folder, { throwIfNoEntry: false })?.isDirectory()) {
59
+ sources.push({ given, dir: folder, skills: skillsIn(folder) });
60
+ continue;
61
+ }
62
+ if (!GIT_URL.test(given)) {
63
+ process.stderr.write(`musubi install: the source "${given}" is neither a folder nor a git URL\n`);
64
+ return 2;
65
+ }
66
+ const clone = mkdtempSync(join(tmpdir(), "musubi-install-"));
67
+ temporary.push(clone);
68
+ const git = spawnSync("git", ["clone", "--quiet", "--depth", "1", given, join(clone, "repo")], { encoding: "utf8" });
69
+ if (git.status !== 0) {
70
+ const why = git.error?.message ?? git.stderr.trim().split("\n").at(-1) ?? "";
71
+ process.stderr.write(`musubi install: could not clone ${given}: ${why}\n`);
72
+ return 1;
73
+ }
74
+ sources.push({ given, dir: join(clone, "repo"), skills: skillsIn(join(clone, "repo")) });
75
+ }
76
+ // The skills an agent already reads, in the order musubi check reads them, with --to first.
77
+ const quiet = new Report(o.cwd);
78
+ const roots = [to, ...defaultRoots(o.cwd, o.home)];
79
+ const installed = discover(roots, quiet);
80
+ const problems = [];
81
+ const copies = [];
82
+ const kept = [];
83
+ const declarations = new Map();
84
+ const bound = [];
85
+ const leftOut = [];
86
+ // Walks the follows from the named skills: a required follow always brings its provider, and an
87
+ // optional one only when the user names the provider or a language matches.
88
+ const queue = o.names.map((name) => ({ name }));
89
+ while (queue.length > 0) {
90
+ const { name, need } = queue.shift();
91
+ if (declarations.has(name))
92
+ continue;
93
+ let skill = installed.get(name);
94
+ if (skill)
95
+ kept.push(skill);
96
+ else {
97
+ const source = sources.find((s) => s.skills.has(name));
98
+ const dirs = source?.skills.get(name) ?? [];
99
+ if (!source) {
100
+ problems.push(need ? `no source holds a skill named ${name}, which ${need.consumer} follows for ${need.follow.ref}` : `no source holds a skill named ${name}`);
101
+ declarations.set(name, null);
102
+ continue;
103
+ }
104
+ if (dirs.length > 1) {
105
+ const paths = dirs.map((dir) => relative(source.dir, dir).split("\\").join("/"));
106
+ problems.push(`the source ${source.given} holds more than one skill named ${name}: ${paths.join(", ")}`);
107
+ declarations.set(name, null);
108
+ continue;
109
+ }
110
+ skill = { name, dir: dirs[0] };
111
+ if (existsSync(join(to, name)))
112
+ problems.push(`${join(to, name)} already exists and holds no SKILL.md, so ${name} cannot be installed there`);
113
+ copies.push({ skill, source });
114
+ }
115
+ const declaration = readDeclaration(skill, quiet);
116
+ declarations.set(name, declaration);
117
+ for (const follow of declaration?.follows ?? []) {
118
+ const wanted = !follow.optional || o.with.includes(follow.skill) || languageMatches(follow, o.languages);
119
+ if (!wanted) {
120
+ leftOut.push({ consumer: name, follow });
121
+ continue;
122
+ }
123
+ bound.push({ consumer: name, follow });
124
+ queue.push({ name: follow.skill, need: { consumer: name, follow } });
125
+ }
126
+ }
127
+ // A provider must provide the content at a version the consumer accepts before anything is copied.
128
+ for (const { consumer, follow } of bound) {
129
+ const declaration = declarations.get(follow.skill);
130
+ if (declaration === null)
131
+ continue;
132
+ const provided = declaration?.provides.get(follow.content);
133
+ if (!provided)
134
+ problems.push(`${consumer} follows ${follow.ref}, but ${follow.skill} provides no content named ${follow.content}`);
135
+ else if (provided.version && follow.range && !satisfies(provided.version, follow.range)) {
136
+ problems.push(`${consumer} accepts ${follow.range.text} of ${follow.ref}, but ${follow.skill} provides ${format(provided.version)}`);
137
+ }
138
+ }
139
+ if (problems.length > 0) {
140
+ for (const problem of problems)
141
+ process.stderr.write(`musubi install: ${problem}\n`);
142
+ process.stderr.write("musubi install: nothing was installed\n");
143
+ return 1;
144
+ }
145
+ const where = (path) => relative(o.cwd, path) || path;
146
+ mkdirSync(to, { recursive: true });
147
+ for (const { skill, source } of copies) {
148
+ cpSync(skill.dir, join(to, skill.name), { recursive: true, dereference: true, filter: (path) => basename(path) !== ".git" });
149
+ process.stdout.write(`installed ${skill.name} from ${source.given} (${relative(source.dir, skill.dir).split("\\").join("/")}) into ${where(to)}\n`);
150
+ }
151
+ for (const skill of kept)
152
+ process.stdout.write(`${skill.name} is already installed in ${where(skill.dir)}, so it was kept as it is\n`);
153
+ for (const { consumer, follow } of leftOut) {
154
+ if (declarations.has(follow.skill))
155
+ continue;
156
+ process.stdout.write(`left out ${follow.skill}, which ${consumer} follows only when it is installed; add it with --with ${follow.skill}\n`);
157
+ }
158
+ for (const name of o.with) {
159
+ if (!declarations.has(name))
160
+ process.stderr.write(`warning: --with ${name} names no optional follow of the skills installed\n`);
161
+ }
162
+ return check(roots, o.cwd, false);
163
+ }
164
+ finally {
165
+ for (const dir of temporary)
166
+ rmSync(dir, { recursive: true, force: true });
167
+ }
168
+ }
package/dist/skills.js CHANGED
@@ -1,12 +1,14 @@
1
1
  import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
2
2
  import { isAbsolute, join, relative, resolve } from "node:path";
3
- import { definitionVersions } from "./definition.js";
3
+ import { definitionVersions, optionalVersions, whenVersions } from "./definition.js";
4
4
  import { INTEGRITY } from "./fingerprint.js";
5
5
  import { isObject, JsonError, parseLocated, pointer } from "./json.js";
6
6
  import { readRules } from "./rules.js";
7
7
  import { parseRange, parseVersion } from "./semver.js";
8
8
  // The folders the agents read skills from, in the project and in the home folder.
9
- const FOLDERS = [".claude/skills", ".agents/skills", ".github/skills", ".gemini/skills"];
9
+ export const FOLDERS = [".claude/skills", ".agents/skills", ".github/skills", ".gemini/skills"];
10
+ // A language tag such as ja or ja-JP, as an optional follow's "when" and --lang write it.
11
+ export const LANGUAGE_TAG = /^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{1,8})*$/;
10
12
  export function defaultRoots(cwd, home) {
11
13
  return [cwd, home].flatMap((base) => FOLDERS.map((folder) => resolve(base, folder)));
12
14
  }
@@ -62,6 +64,26 @@ export function readDeclaration(skill, report) {
62
64
  }
63
65
  const { value, lines } = located;
64
66
  const at = (...keys) => lines.get(pointer(...keys)) ?? 1;
67
+ // "when" of an optional follow holds one field, a list of language tags (decision record 0009).
68
+ const readWhen = (when, ref, optional) => {
69
+ const line = at("follows", ref, "when");
70
+ if (!optional)
71
+ report.problem(path, line, `"when" of "${ref}" needs "optional": true`);
72
+ if (!isObject(when) || when.languages === undefined) {
73
+ report.problem(path, line, `"when" of "${ref}" must be an object with "languages"`);
74
+ return [];
75
+ }
76
+ for (const key of Object.keys(when)) {
77
+ if (key !== "languages")
78
+ report.problem(path, at("follows", ref, "when", key), `unknown field "${key}" in "when" of "${ref}"`);
79
+ }
80
+ const { languages } = when;
81
+ if (!Array.isArray(languages) || languages.length === 0 || !languages.every((tag) => typeof tag === "string" && LANGUAGE_TAG.test(tag))) {
82
+ report.problem(path, at("follows", ref, "when", "languages"), `"languages" of "${ref}" must list language tags such as "ja"`);
83
+ return [];
84
+ }
85
+ return languages;
86
+ };
65
87
  if (!isObject(value)) {
66
88
  report.problem(path, 1, "musubi.json holds one JSON object");
67
89
  return declaration;
@@ -133,9 +155,17 @@ export function readDeclaration(skill, report) {
133
155
  report.problem(path, line, `"${ref}" must be an object with "version" and "integrity"`);
134
156
  continue;
135
157
  }
136
- for (const key of Object.keys(entry))
137
- if (!FOLLOWED.has(key))
158
+ const knowsOptional = typeof value.musubi === "string" && optionalVersions.has(value.musubi);
159
+ const knowsWhen = typeof value.musubi === "string" && whenVersions.has(value.musubi);
160
+ for (const key of Object.keys(entry)) {
161
+ const known = FOLLOWED.has(key) || (key === "optional" && knowsOptional) || (key === "when" && knowsWhen);
162
+ if (!known)
138
163
  report.problem(path, at("follows", ref, key), `unknown field "${key}" in "${ref}"`);
164
+ }
165
+ if (knowsOptional && entry.optional !== undefined && typeof entry.optional !== "boolean") {
166
+ report.problem(path, at("follows", ref, "optional"), `"optional" of "${ref}" must be true or false`);
167
+ }
168
+ const languages = knowsWhen && entry.when !== undefined ? readWhen(entry.when, ref, entry.optional === true) : [];
139
169
  const versionLine = lines.get(pointer("follows", ref, "version")) ?? line;
140
170
  const range = typeof entry.version === "string" ? parseRange(entry.version) : null;
141
171
  if (!range)
@@ -162,7 +192,8 @@ export function readDeclaration(skill, report) {
162
192
  }
163
193
  }
164
194
  const [skillName, content] = ref.split("/");
165
- declaration.follows.push({ ref, skill: skillName, content, range, integrity, examples, line, versionLine, integrityLine });
195
+ const optional = knowsOptional && entry.optional === true;
196
+ declaration.follows.push({ ref, skill: skillName, content, range, integrity, examples, optional, languages, line, versionLine, integrityLine });
166
197
  }
167
198
  }
168
199
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "musubi-cli",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "Binds the content one agent skill provides to the skills that follow it, and checks them again when that content changes",
5
5
  "keywords": [
6
6
  "agent-skills",
@@ -31,7 +31,10 @@
31
31
  "scripts": {
32
32
  "build": "tsc -p tsconfig.build.json",
33
33
  "test": "node --test --test-reporter=tap tests/*.test.ts",
34
- "prepack": "tsc -p tsconfig.build.json"
34
+ "prepack": "tsc -p tsconfig.build.json",
35
+ "site": "node site/build.ts && node site/serve.ts",
36
+ "site:build": "node site/build.ts",
37
+ "site:publish": "node site/publish.ts"
35
38
  },
36
39
  "devDependencies": {
37
40
  "@types/node": "^24.0.0",
@@ -0,0 +1,68 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "check.schema.json",
4
+ "title": "musubi check rules",
5
+ "description": "The rules a provider skill's check holds. musubi check reads them and never runs provider code.",
6
+ "type": "object",
7
+ "additionalProperties": false,
8
+ "required": ["musubi", "rules"],
9
+ "properties": {
10
+ "$schema": { "type": "string" },
11
+ "musubi": { "const": "2026-11-20" },
12
+ "rules": {
13
+ "type": "array",
14
+ "minItems": 1,
15
+ "items": {
16
+ "oneOf": [
17
+ {
18
+ "type": "object",
19
+ "additionalProperties": false,
20
+ "required": ["kind", "headings"],
21
+ "properties": {
22
+ "kind": { "const": "headings" },
23
+ "headings": {
24
+ "type": "array",
25
+ "minItems": 1,
26
+ "description": "Heading lines that must appear, in this order. Other headings may come between them.",
27
+ "items": { "type": "string", "minLength": 1 }
28
+ }
29
+ }
30
+ },
31
+ {
32
+ "type": "object",
33
+ "additionalProperties": false,
34
+ "required": ["kind", "text"],
35
+ "properties": {
36
+ "kind": { "const": "forbid" },
37
+ "text": {
38
+ "type": "array",
39
+ "minItems": 1,
40
+ "description": "Text that must not remain outside code blocks.",
41
+ "items": { "type": "string", "minLength": 1 }
42
+ }
43
+ }
44
+ },
45
+ {
46
+ "type": "object",
47
+ "additionalProperties": false,
48
+ "required": ["kind", "heading", "columns"],
49
+ "properties": {
50
+ "kind": { "const": "table-columns" },
51
+ "heading": {
52
+ "type": "string",
53
+ "minLength": 1,
54
+ "description": "The heading line whose first table is checked."
55
+ },
56
+ "columns": {
57
+ "type": "array",
58
+ "minItems": 1,
59
+ "description": "Columns the table must have. It may have more.",
60
+ "items": { "type": "string", "minLength": 1 }
61
+ }
62
+ }
63
+ }
64
+ ]
65
+ }
66
+ }
67
+ }
68
+ }