skillrepo 4.3.0 → 4.5.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.
@@ -1,21 +1,36 @@
1
1
  /**
2
- * `skillrepo list` (#679).
2
+ * `skillrepo list` — list library skills with per-row local drift state (#1555).
3
3
  *
4
- * Lists the authenticated account's library contents. Default output
5
- * is a human-readable table via `cli-table3`. `--json` flag prints
6
- * the raw metadata array for piping into `jq` or other tools.
4
+ * Historically (#679) this only showed the server-side library. As of
5
+ * #1555 the table adds a `Local` column showing how each skill's
6
+ * on-disk placement stacks up against the library + last-sync
7
+ * baseline: `current` / `stale` / `missing` / `edited`. A footer
8
+ * reports the library-level ETag state ("library in sync" vs
9
+ * "library has changed since last sync").
7
10
  *
8
- * Calls GET /api/v1/library and ignores the inlined file content —
9
- * we only need metadata for display. There is no metadata-only
10
- * endpoint; reading the full library payload is the cost of reusing
11
- * the same route the sync engine uses.
11
+ * Pipeline:
12
+ * 1. `getLibrary` returns the current registry skills + ETag.
13
+ * 2. `readLastSync` reads the v2 `.last-sync` map (per-skill SHAs +
14
+ * versions) for the on-disk-vs-synced comparison.
15
+ * 3. `detectAgents` identifies which vendors actually have footprint
16
+ * on this machine / in this project — we only report drift
17
+ * against vendors the user uses.
18
+ * 4. `walkDetectedPlacements` reads each detected vendor's
19
+ * placement dir and computes SHAs from disk.
20
+ * 5. `computeSkillState` + `rollupState` from `drift.mjs` turn the
21
+ * three axes into a per-vendor state and a per-skill rollup.
12
22
  *
13
23
  * Flags:
14
- * --json Pipe-friendly JSON output
15
- * --key/--url Override credentials
24
+ * --json Pipe-friendly JSON output (bare array preserved
25
+ * from #679 — purely additive: new `state` and
26
+ * `placements[]` fields per item, no top-level
27
+ * wrapper).
28
+ * --key/--url Override credentials.
16
29
  *
17
- * No --global / --agent flags `list` is a library-state inspector,
18
- * not a writer.
30
+ * No `--global`, `--detail`, `--vendor`, or `--include-extra` flags
31
+ * in v1 — YAGNI per the epic's decisions log. Project-scope
32
+ * placement only; extra-on-disk skills (in placement but not in
33
+ * library) are hidden by default.
19
34
  */
20
35
 
21
36
  import Table from "cli-table3";
@@ -23,6 +38,11 @@ import Table from "cli-table3";
23
38
  import { getLibrary } from "../lib/http.mjs";
24
39
  import { resolveFlags } from "../lib/cli-config.mjs";
25
40
  import { formatIdentifier } from "../lib/identifier.mjs";
41
+ import { readLastSync } from "../lib/sync.mjs";
42
+ import { detectAgents } from "../lib/detect-agents.mjs";
43
+ import { walkDetectedPlacements } from "../lib/placement-walk.mjs";
44
+ import { getAgentByKey } from "../lib/agent-registry.mjs";
45
+ import { computeSkillState, rollupState, SKILL_STATE } from "../lib/drift.mjs";
26
46
 
27
47
  /**
28
48
  * Run `list`. Throws CliError on any failure.
@@ -36,59 +56,165 @@ export async function runList(argv, io = {}) {
36
56
  const stdout = io.stdout ?? process.stdout;
37
57
  const flags = resolveFlags(argv);
38
58
 
39
- const result = await getLibrary(flags.serverUrl, flags.apiKey);
59
+ const libraryResponse = await getLibrary(flags.serverUrl, flags.apiKey);
40
60
 
41
- // `list` does not care about removals or sync state — we just want
42
- // the current set. Skills are returned by the same endpoint as the
43
- // sync, but with full file content we discard.
44
- //
45
61
  // Defensive guard: `list` calls getLibrary without an If-None-Match
46
62
  // header so it can't legitimately receive a 304 today. But getLibrary's
47
63
  // contract documents `notModified: true` as a possible return shape,
48
64
  // and a future refactor that adds caching at this layer could
49
- // accidentally start sending the header. Treat `result.skills` as
50
- // possibly empty rather than possibly undefined.
51
- const skills = Array.isArray(result.skills) ? result.skills : [];
65
+ // accidentally start sending the header.
66
+ const skills = Array.isArray(libraryResponse.skills) ? libraryResponse.skills : [];
67
+
68
+ // Detect agents + walk placements regardless of skill count — we
69
+ // need this info for both the table and the JSON shape.
70
+ const detected = detectAgents().filter((d) => d.detected);
71
+
72
+ // Pre-resolve the detected vendor entries ONCE. `getAgentByKey` is
73
+ // O(N) over the registry; doing this per-skill across 50+ skills
74
+ // was wasted work. We also filter to vendors with a non-null
75
+ // projectTarget here so the per-skill loop only iterates vendors
76
+ // that actually contribute a placement.
77
+ const detectedVendorEntries = detected
78
+ .map((d) => getAgentByKey(d.key))
79
+ .filter((entry) => entry !== null && entry.projectTarget !== null);
80
+ const detectedKeys = detectedVendorEntries.map((e) => e.key);
81
+
82
+ const placementsMap = walkDetectedPlacements(detectedKeys);
83
+
84
+ // Read `.last-sync` ONCE. Direct map access on the parsed
85
+ // `skills` payload — no per-skill helper indirection — for both
86
+ // wasted-I/O reasons (N reads of the same file otherwise) AND
87
+ // a within-run snapshot-consistency window (a concurrent
88
+ // `skillrepo update` writing the file mid-list would otherwise
89
+ // produce inconsistent classifications across skills in the
90
+ // same render).
91
+ const lastSync = readLastSync();
92
+ const lastSyncSkillsMap =
93
+ lastSync && lastSync.skills && typeof lastSync.skills === "object"
94
+ ? lastSync.skills
95
+ : {};
96
+
97
+ // Build the augmented per-skill state for every library skill. This
98
+ // is the canonical shape both the table renderer and JSON formatter
99
+ // project from.
100
+ const augmented = skills.map((skill) =>
101
+ augmentSkill(skill, detectedVendorEntries, placementsMap, lastSyncSkillsMap),
102
+ );
52
103
 
53
104
  if (flags.json) {
54
- stdout.write(JSON.stringify(formatJson(skills), null, 2) + "\n");
105
+ stdout.write(JSON.stringify(formatJson(augmented), null, 2) + "\n");
55
106
  return;
56
107
  }
57
108
 
58
- if (skills.length === 0) {
109
+ if (augmented.length === 0) {
59
110
  stdout.write(
60
111
  "\n Your library is empty.\n Use `skillrepo add <@owner/name>` to add a skill.\n\n",
61
112
  );
62
113
  return;
63
114
  }
64
115
 
65
- printTable(skills, stdout);
116
+ printTable(augmented, detected, stdout);
117
+ printFooter(augmented, libraryResponse.etag, lastSync, stdout, canUseGlyphs(stdout));
66
118
  }
67
119
 
120
+ // ── Per-skill augmentation ─────────────────────────────────────────────
121
+
68
122
  /**
69
- * Read the column width from the active output stream, falling back
70
- * to process.stdout's TTY column count if the injected stream
71
- * doesn't carry one (e.g., a test capture stream), then to a 100-col
72
- * default for non-TTY contexts. Reading from `out.columns` first
73
- * means a future test that injects a stream advertising a specific
74
- * width will be honored.
123
+ * Compute `state` (rollup) + `placements[]` for a library skill.
124
+ *
125
+ * For each detected vendor (pre-resolved by the caller) look up the
126
+ * on-disk placement and the last-sync baseline, classify the state,
127
+ * and emit a placement entry. Then roll the per-vendor states up to
128
+ * a single `state` for the table column.
129
+ *
130
+ * Baseline lookups go through the caller-provided `lastSyncSkillsMap`
131
+ * to avoid re-reading `.last-sync` per skill — both a wasted-I/O
132
+ * concern and a within-run snapshot consistency concern (an
133
+ * in-flight `skillrepo update` could otherwise change the file
134
+ * between our N reads).
135
+ *
136
+ * @param {object} skill - Library skill from `getLibrary` response.
137
+ * @param {import("../lib/agent-registry.mjs").AgentEntry[]} detectedVendorEntries
138
+ * Pre-resolved registry entries for the detected vendors that
139
+ * contribute a project placement. Computed once in `runList` so
140
+ * the registry lookup doesn't happen per skill.
141
+ * @param {Map<string, import("../lib/placement-walk.mjs").LocalPlacement>} placementsMap
142
+ * @param {Record<string, import("../lib/sync.mjs").SyncedSkillEntry>} lastSyncSkillsMap
143
+ * The `skills` map from `.last-sync` v2, captured once before the
144
+ * per-skill loop. Lookup is a direct dictionary access, not a
145
+ * re-read of the file.
75
146
  */
76
- function streamColumns(out) {
77
- if (out && typeof out.columns === "number" && out.columns > 0) {
78
- return out.columns;
147
+ function augmentSkill(skill, detectedVendorEntries, placementsMap, lastSyncSkillsMap) {
148
+ const baselineKey = `${skill.owner}/${skill.name}`;
149
+ const baseline = validateBaselineShape(lastSyncSkillsMap[baselineKey]);
150
+ const placements = [];
151
+
152
+ for (const entry of detectedVendorEntries) {
153
+ const placementKey = `${entry.key}::project::${skill.name}`;
154
+ const onDisk = placementsMap.get(placementKey) ?? null;
155
+
156
+ const localPlacement = onDisk
157
+ ? {
158
+ present: true,
159
+ skillMdSha256: onDisk.skillMdSha256,
160
+ filesSha256: onDisk.filesSha256,
161
+ }
162
+ : { present: false, skillMdSha256: null, filesSha256: null };
163
+
164
+ const state = computeSkillState({
165
+ libraryVersion: skill.version ?? null,
166
+ lastSyncEntry: baseline,
167
+ localPlacement,
168
+ });
169
+
170
+ placements.push({
171
+ vendor: entry.key,
172
+ scope: "project",
173
+ state,
174
+ // `localVersion` is the version that was synced (from
175
+ // `.last-sync`) — NOT a version pulled from on-disk
176
+ // frontmatter, which the spec doesn't mandate. When there's no
177
+ // baseline, this is null and the `state` will already be
178
+ // `missing`, so the field is honest about what we know.
179
+ localVersion: baseline?.version ?? null,
180
+ });
79
181
  }
80
- if (process.stdout.columns && process.stdout.columns > 0) {
81
- return process.stdout.columns;
182
+
183
+ const state = rollupState(placements.map((p) => p.state));
184
+
185
+ return { ...skill, state, placements };
186
+ }
187
+
188
+ /**
189
+ * Reject a `.last-sync` entry that's missing required string fields.
190
+ * A tampered or partially-written entry returns null, which
191
+ * `computeSkillState` treats as "no baseline → missing" — the
192
+ * conservative verdict for cache state we can't trust.
193
+ */
194
+ function validateBaselineShape(entry) {
195
+ if (!entry || typeof entry !== "object") return null;
196
+ if (
197
+ typeof entry.version !== "string" ||
198
+ typeof entry.skillMdSha256 !== "string" ||
199
+ typeof entry.filesSha256 !== "string"
200
+ ) {
201
+ return null;
82
202
  }
83
- return 100;
203
+ return entry;
84
204
  }
85
205
 
206
+ // ── JSON formatter ─────────────────────────────────────────────────────
207
+
86
208
  /**
87
- * Strip file content and reduce to the JSON shape that scripts care
88
- * about. Kept stable as a public-ish contract for `--json` consumers.
209
+ * Pipe-friendly bare array, additive on top of the #679 shape.
210
+ * Existing scripts that read `[0].owner`, etc. keep working. New
211
+ * fields: `state` (rollup) and `placements[]` (per-vendor truth).
212
+ *
213
+ * The footer never appears in JSON — `list --json` is consumed by
214
+ * scripts, and the ETag-state footer is a human-only signal.
89
215
  */
90
- function formatJson(skills) {
91
- return skills
216
+ function formatJson(augmented) {
217
+ return augmented
92
218
  .slice()
93
219
  .sort(sortByOwnerAndName)
94
220
  .map((s) => ({
@@ -98,17 +224,34 @@ function formatJson(skills) {
98
224
  description: s.description,
99
225
  updatedAt: s.updatedAt,
100
226
  filesIncomplete: s.filesIncomplete ?? false,
227
+ state: s.state,
228
+ placements: s.placements,
101
229
  }));
102
230
  }
103
231
 
104
- function printTable(skills, out) {
105
- const sorted = skills.slice().sort(sortByOwnerAndName);
232
+ // ── Human-output rendering ─────────────────────────────────────────────
233
+
234
+ function printTable(augmented, detected, out) {
235
+ const useGlyphs = canUseGlyphs(out);
236
+
237
+ // "Detected:" line uses displayName for polish. Empty when no
238
+ // vendors detected; that situation also produces all-`missing`
239
+ // states, which the footer covers.
240
+ if (detected.length > 0) {
241
+ const detectedLabel = detected
242
+ .map((d) => `${d.displayName} (project)`)
243
+ .join(", ");
244
+ out.write(`\n Detected: ${detectedLabel}\n`);
245
+ } else {
246
+ out.write(
247
+ "\n No agents detected in this project — drift cannot be reported.\n",
248
+ );
249
+ }
250
+
251
+ const sorted = augmented.slice().sort(sortByOwnerAndName);
106
252
 
107
- // cli-table3 supports word wrapping but we manually truncate
108
- // descriptions so the table stays readable on standard 80-col
109
- // terminals. The full description is available via --json.
110
253
  const table = new Table({
111
- head: ["Skill", "Version", "Updated", "Description"],
254
+ head: ["Skill", "Library", "Local", "Updated", "Description"],
112
255
  colWidths: computeColWidths(streamColumns(out)),
113
256
  wordWrap: true,
114
257
  style: { head: ["bold"] },
@@ -118,26 +261,156 @@ function printTable(skills, out) {
118
261
  table.push([
119
262
  formatIdentifier(s),
120
263
  s.version || "—",
264
+ renderLocalCell(s.state, useGlyphs),
121
265
  formatRelativeDate(s.updatedAt),
122
266
  truncate(s.description || "", 60),
123
267
  ]);
124
268
  }
125
269
 
126
270
  out.write("\n" + table.toString() + "\n\n");
127
- out.write(` ${sorted.length} skill${sorted.length === 1 ? "" : "s"} in your library.\n\n`);
271
+
272
+ const driftCount = sorted.filter((s) => s.state !== SKILL_STATE.CURRENT).length;
273
+ if (driftCount === 0) {
274
+ out.write(
275
+ ` ${sorted.length} skill${sorted.length === 1 ? "" : "s"} in your library.\n`,
276
+ );
277
+ } else {
278
+ out.write(
279
+ ` ${sorted.length} skill${sorted.length === 1 ? "" : "s"} in your library. ` +
280
+ `${driftCount} need${driftCount === 1 ? "s" : ""} attention.\n`,
281
+ );
282
+ }
283
+ }
284
+
285
+ /**
286
+ * Library footer — answers "is my local copy in sync with the
287
+ * registry's manifest right now?" Distinct from per-row drift,
288
+ * which answers "is each individual skill's on-disk content
289
+ * current?"
290
+ *
291
+ * Four cases — order matters for the "least confusing precedence":
292
+ *
293
+ * - No `.last-sync` at all → "no sync history." The user has
294
+ * never run `update`; per-row drift is all `missing` anyway.
295
+ * A clear "you need to run update" line is the right message.
296
+ *
297
+ * - ETag matches AND every skill is current → fully in sync.
298
+ * The reassuring case.
299
+ *
300
+ * - ETag matches BUT some rows show drift → library hasn't
301
+ * changed but local placements have. User ran update at some
302
+ * point but then either edited files or has missing
303
+ * placements. "Library in sync, run update to refresh"
304
+ * reflects this without lying about what's wrong.
305
+ *
306
+ * - ETag differs → library has new content since last sync.
307
+ * "Library has changed, run update."
308
+ *
309
+ * The footer NEVER appears in `--json` output (caller already
310
+ * handles that in `runList`).
311
+ */
312
+ function printFooter(augmented, libraryEtag, lastSync, out, useGlyphs) {
313
+ if (augmented.length === 0) return; // Empty-library branch already wrote its own message.
314
+
315
+ // Match the renderLocalCell glyph/ASCII policy. Pre-#1555 the footer
316
+ // used Unicode unconditionally even when the table fell back to
317
+ // ASCII for non-TTY / NO_COLOR. Inconsistency made piped output
318
+ // half-styled.
319
+ const ok = useGlyphs ? "✓" : "[ok]";
320
+ const warn = useGlyphs ? "⚠" : "[!]";
321
+
322
+ const driftCount = augmented.filter((s) => s.state !== SKILL_STATE.CURRENT).length;
323
+
324
+ if (!lastSync || !lastSync.etag) {
325
+ out.write(
326
+ "\n No sync history on this machine — run `skillrepo update` to fetch your skills.\n\n",
327
+ );
328
+ return;
329
+ }
330
+
331
+ const etagMatches =
332
+ typeof libraryEtag === "string" && libraryEtag !== "" && libraryEtag === lastSync.etag;
333
+
334
+ if (etagMatches && driftCount === 0) {
335
+ out.write(`\n ${ok} library in sync — local skills up to date.\n\n`);
336
+ return;
337
+ }
338
+
339
+ if (etagMatches && driftCount > 0) {
340
+ out.write(
341
+ `\n ${warn} library in sync — but ${driftCount} skill${
342
+ driftCount === 1 ? "" : "s"
343
+ } show${driftCount === 1 ? "s" : ""} local drift.\n` +
344
+ " Run `skillrepo update` to refresh.\n\n",
345
+ );
346
+ return;
347
+ }
348
+
349
+ // ETag differs (or one side is missing the etag — treat as differs,
350
+ // since we can't claim sync).
351
+ out.write(
352
+ `\n ${warn} library has changed since last sync — run \`skillrepo update\`.\n\n`,
353
+ );
354
+ }
355
+
356
+ // ── Rendering helpers ──────────────────────────────────────────────────
357
+
358
+ /** Glyphs vs ASCII tokens, per NO_COLOR / non-TTY. */
359
+ function canUseGlyphs(stream) {
360
+ if (process.env.NO_COLOR) return false;
361
+ // `isTTY` is undefined on capture streams; treat as "no TTY → ASCII"
362
+ // since CI and pipe consumers would otherwise see escape codes /
363
+ // glyphs they can't render uniformly.
364
+ return stream && stream.isTTY === true;
365
+ }
366
+
367
+ function renderLocalCell(state, useGlyphs) {
368
+ switch (state) {
369
+ case SKILL_STATE.CURRENT:
370
+ return useGlyphs ? "✓" : "OK";
371
+ case SKILL_STATE.STALE:
372
+ return useGlyphs ? "⚠ stale" : "STALE";
373
+ case SKILL_STATE.MISSING:
374
+ return useGlyphs ? "✗ miss" : "MISS";
375
+ case SKILL_STATE.EDITED:
376
+ return useGlyphs ? "✎ edit" : "EDIT";
377
+ default:
378
+ return useGlyphs ? "?" : "?";
379
+ }
380
+ }
381
+
382
+ /**
383
+ * Read the column width from the active output stream, falling back
384
+ * to process.stdout's TTY column count if the injected stream
385
+ * doesn't carry one (e.g., a test capture stream), then to a 100-col
386
+ * default for non-TTY contexts.
387
+ */
388
+ function streamColumns(out) {
389
+ if (out && typeof out.columns === "number" && out.columns > 0) {
390
+ return out.columns;
391
+ }
392
+ if (process.stdout.columns && process.stdout.columns > 0) {
393
+ return process.stdout.columns;
394
+ }
395
+ return 100;
128
396
  }
129
397
 
130
398
  function computeColWidths(terminalColumns) {
131
- // Cap at 120 so the table doesn't get unreadably wide on
132
- // ultra-wide terminals; floor at 100 so the description still has
133
- // room when the terminal is narrower than typical.
399
+ // Cap at 120 so the table doesn't get unreadably wide on ultra-
400
+ // wide terminals; floor at 100 so the description still has room.
401
+ // The Local column is fixed-width (10 chars — biggest glyph cell
402
+ // is "✎ edit" plus padding).
134
403
  const total = terminalColumns > 60 ? Math.min(terminalColumns, 120) : 100;
135
- // Skill ~30, version ~10, updated ~14, description gets the rest
136
- const skillCol = 32;
137
- const versionCol = 12;
138
- const updatedCol = 14;
139
- const descCol = Math.max(20, total - skillCol - versionCol - updatedCol - 6); // -6 for borders
140
- return [skillCol, versionCol, updatedCol, descCol];
404
+ const skillCol = 30;
405
+ const libraryCol = 10;
406
+ const localCol = 10;
407
+ const updatedCol = 12;
408
+ // -8 accounts for the 6 between-column borders
409
+ const descCol = Math.max(
410
+ 20,
411
+ total - skillCol - libraryCol - localCol - updatedCol - 8,
412
+ );
413
+ return [skillCol, libraryCol, localCol, updatedCol, descCol];
141
414
  }
142
415
 
143
416
  function truncate(s, n) {
@@ -164,7 +437,6 @@ function formatRelativeDate(iso) {
164
437
  if (days < 7) return `${days}d ago`;
165
438
  const weeks = Math.floor(days / 7);
166
439
  if (weeks < 26) return `${weeks}w ago`;
167
- // Older than ~6 months: fall back to a date
168
440
  return new Date(iso).toISOString().slice(0, 10);
169
441
  }
170
442
 
@@ -174,6 +174,12 @@ export function writeConfig(config) {
174
174
  for (const key of ["accountSlug", "accountId", "userId"]) {
175
175
  if (config[key] !== undefined) merged[key] = config[key];
176
176
  }
177
+ // Telemetry opt-in/out flag (#1539). Persisted only when the caller
178
+ // explicitly sets it — omitting means "no preference recorded,"
179
+ // which the telemetry module treats as "enabled" (opt-out default).
180
+ if (typeof config.telemetry === "boolean") {
181
+ merged.telemetry = config.telemetry;
182
+ }
177
183
 
178
184
  // Atomic write via temp-file + rename. Matches the file-write.mjs
179
185
  // pattern: the config file is never in a half-written state, so
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Skill-content SHA helpers (#1553 — `.last-sync` v2).
3
+ *
4
+ * Two flavors of SHA-256 digest computed over a skill's file payload:
5
+ *
6
+ * • `skillMdSha256` — SHA-256 over the SKILL.md content as UTF-8 bytes.
7
+ * The server intentionally returns an empty string for SKILL.md's
8
+ * `sha256` field (see `src/lib/api/skill-response.ts:224`), so
9
+ * clients must compute it locally. Used to detect user edits to
10
+ * the SKILL.md frontmatter or body between syncs.
11
+ *
12
+ * • `filesSha256` — SHA-256 over a deterministic projection of every
13
+ * file's path and content hash. The projection is:
14
+ *
15
+ * <path-1>|<sha-1>\n<path-2>|<sha-2>\n...<path-n>|<sha-n>
16
+ *
17
+ * where entries are sorted by `path` using byte-order comparison
18
+ * (NOT locale-aware), joined by `\n`, with NO trailing newline.
19
+ * Implementations that re-derive this projection MUST match this
20
+ * format byte-for-byte — a trailing newline would change the
21
+ * resulting digest and break every drift comparison. Used to
22
+ * detect edits to ANY file in the skill — references/, scripts/,
23
+ * assets/, plus SKILL.md — in a single constant-size value.
24
+ *
25
+ * Why two SHAs instead of one
26
+ * ---------------------------
27
+ * `filesSha256` is the "anything changed?" rollup. `skillMdSha256`
28
+ * isolates SKILL.md edits, which are by far the most common kind of
29
+ * user modification (the spec encourages keeping SKILL.md under 500
30
+ * lines and pushing detail into references/, so SKILL.md is the
31
+ * working face of a skill). Surfacing "edited" specifically against
32
+ * SKILL.md gives clearer messages and lets `list` and a future
33
+ * `status` distinguish "user tweaked the body" from "support file
34
+ * changed."
35
+ *
36
+ * Path-format requirements
37
+ * ------------------------
38
+ * Callers MUST pass paths in canonical POSIX form (`/` separators,
39
+ * relative to the skill root, no leading `./`). The CLI's sync path
40
+ * uses server-provided paths directly, which already meet this
41
+ * requirement. A future on-disk reader (#1555) is responsible for
42
+ * normalizing platform-native separators back to `/` before calling
43
+ * these helpers — otherwise the same skill would produce different
44
+ * `filesSha256` values on Windows vs. POSIX and every disk read would
45
+ * spuriously report `edited`.
46
+ *
47
+ * Byte-content requirements
48
+ * -------------------------
49
+ * `content` is hashed as UTF-8 bytes. The CLI does not support
50
+ * binary file payloads today (see `validateSkill` in `file-write.mjs`),
51
+ * so `content` is always a JS string and `Buffer.from(content, "utf8")`
52
+ * produces the same bytes written to disk by `writeFileSync(path,
53
+ * content, "utf-8")`. If binary support is added, this helper needs
54
+ * an `encoding` discriminant per file.
55
+ */
56
+
57
+ import { createHash } from "node:crypto";
58
+
59
+ /**
60
+ * @typedef {Object} SkillFileLike
61
+ * @property {string} path - Canonical POSIX path relative to skill root.
62
+ * @property {string} content - UTF-8 string content as written to disk.
63
+ */
64
+
65
+ /**
66
+ * @typedef {Object} SkillShas
67
+ * @property {string | null} skillMdSha256
68
+ * Hex-encoded SHA-256 of SKILL.md's content. `null` when no SKILL.md
69
+ * is present in `files` — that's a malformed skill, and callers
70
+ * should not persist a result with `skillMdSha256: null` to
71
+ * `.last-sync`. The helper still returns it (rather than throwing)
72
+ * so callers can branch — throwing here would couple this pure
73
+ * function to a policy decision that belongs at the call site.
74
+ * @property {string} filesSha256
75
+ * Hex-encoded SHA-256 over the sorted `path|sha` projection of
76
+ * every file. Never `null`: an empty `files` array hashes to the
77
+ * SHA-256 of the empty string, which is a well-defined value.
78
+ */
79
+
80
+ /**
81
+ * Compute both digests for a skill's file payload.
82
+ *
83
+ * Pure function — no I/O, no filesystem access, no clock reads. The
84
+ * same input always produces the same output, which is what lets the
85
+ * sync path and the (future) disk-walk path compare results
86
+ * meaningfully.
87
+ *
88
+ * SKILL.md identification: case-sensitive, root-level only. A file at
89
+ * `path: "skill.md"` (lowercase) or `path: "docs/SKILL.md"` (nested)
90
+ * is NOT treated as the canonical SKILL.md. The spec at agentskills.io
91
+ * mandates the exact filename `SKILL.md` at the skill root; matching
92
+ * the server's behavior here keeps `filesSha256` consistent with
93
+ * server-side hashing rules.
94
+ *
95
+ * @param {ReadonlyArray<SkillFileLike>} files
96
+ * @returns {SkillShas}
97
+ */
98
+ export function computeSkillShas(files) {
99
+ if (!Array.isArray(files)) {
100
+ throw new TypeError("computeSkillShas: files must be an array");
101
+ }
102
+
103
+ /** @type {{ path: string, sha: string }[]} */
104
+ const perFile = [];
105
+ /** @type {string | null} */
106
+ let skillMdSha256 = null;
107
+
108
+ for (const file of files) {
109
+ if (!file || typeof file.path !== "string" || typeof file.content !== "string") {
110
+ throw new TypeError(
111
+ "computeSkillShas: each file must have string `path` and string `content`",
112
+ );
113
+ }
114
+ const sha = createHash("sha256").update(file.content, "utf8").digest("hex");
115
+ perFile.push({ path: file.path, sha });
116
+ if (file.path === "SKILL.md") {
117
+ skillMdSha256 = sha;
118
+ }
119
+ }
120
+
121
+ // Byte-order sort (not locale-aware). The `localeCompare` API is
122
+ // explicitly avoided here — two callers in different locales would
123
+ // otherwise hash to different values for the same skill, defeating
124
+ // the whole point of the digest.
125
+ perFile.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
126
+
127
+ const projection = perFile.map((entry) => `${entry.path}|${entry.sha}`).join("\n");
128
+ const filesSha256 = createHash("sha256").update(projection, "utf8").digest("hex");
129
+
130
+ return { skillMdSha256, filesSha256 };
131
+ }