diff --git a/README.md b/README.md index e3fc099..b68be53 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,17 @@ Node.js is named, not half-installed (the bridge needs Node 20+). and named. - The tools come live from the server, so a new tool needs no reinstall. Re-run `install` to refresh the skill. +- The **official skills** (`@spacesheep/design`, `@spacesheep/docs`, + `@spacesheep/sheets`) go beside `/sheep` in each harness, as the folders + `skills get -o ` writes (`~/.claude/skills/design`, + `~/.codex/skills/design`, …), at the store's current version. The harness's own + skill picker then finds them by their descriptions, with nothing to fetch first. + A folder is only replaced or removed when it holds install's + `.spacesheep-skill.json`, so a skill of your own by the same name is left alone. + A re-run replaces them when the store has a newer version, and once a day a + harness start does the same in the background (`spacesheep skills refresh`; + `SPACESHEEP_NO_SKILL_REFRESH=1` turns that off). `--skip design` leaves one out, + `--no-skill` all of them with `/sheep`. - A run from `npx` copies the CLI (no dependencies) into `~/.config/spacesheep/cli` for the harnesses to run, since npx clears its own cache, and running npx on every harness start would wait on npm and fail offline. diff --git a/bin/spacesheep.js b/bin/spacesheep.js index 32bf97f..6b04042 100755 --- a/bin/spacesheep.js +++ b/bin/spacesheep.js @@ -18,12 +18,17 @@ if (process.argv[2] === "memory" && process.argv[3] === "sync") { // protocol — nothing else may print there. // `mcp headers` is Claude Code's headersHelper (lib/harnesses.js): it prints the // header that signs a connection in, and nothing else, on every connect. +// Both start with each harness, so both bring the official skills up to date, once a +// day, in a process of their own that the harness doesn't wait for (lib/official.js). +const refreshSkills = () => require("../lib/official").startRefresh({ configDir: require("../lib/config").configDir(), script: __filename }); if (process.argv[2] === "mcp" && process.argv[3] === "headers") { const k = require("../lib/config").resolveKey(); process.stdout.write(JSON.stringify(k ? { Authorization: `Bearer ${k.key}` } : {}) + "\n"); + if (k) refreshSkills(); return; } if (process.argv[2] === "mcp" && (process.argv.length === 3 || process.argv[3] === "serve")) { + if (require("../lib/config").resolveKey()) refreshSkills(); // No process.exit: stdout to a pipe is async, and exiting would drop the answers still in it. require("../lib/bridge").runBridge(); return; @@ -63,7 +68,8 @@ const HELP = ` connect EVERY coding harness on this machine at once: signs the machine in (once), points Claude Code, Codex, Gemini CLI, Antigravity, Cursor, Windsurf, VS Code and opencode at - \`spacesheep mcp\`, and puts the /sheep skill where each reads skills. + \`spacesheep mcp\`, and puts the /sheep skill where each reads skills, + with the official skills (design, docs, sheets) beside it. Takes --code ssc_… or --key ss_… to sign in with no browser. --skip leaves some out: an agent (cursor) or one Claude home by its folder (.claude-work, or just work) @@ -83,6 +89,7 @@ const HELP = ` spacesheep delete [--yes] delete one of your spaces and every version of it (can't be undone); takes a uuid, a link or one of your slugs, and unpins this folder spacesheep skills lint [folder] check a skill folder, or a repo holding one, for the format + spacesheep skills refresh bring the official skills install put here to the store's version Spacesheep reads; no sign-in, and the folder never leaves this machine. --json for CI spacesheep tools [name] every tool the server has, or one tool's arguments @@ -221,7 +228,7 @@ function parse(argv) { * `label` on the new call. */ const spaceLine = (s) => `${(s.emoji || "·").padEnd(2)} ${(s.title || "(untitled)").slice(0, 40).padEnd(42)} ${(s.visibility || "").padEnd(10)} ${s.url || s.id}`; const versionLine = (v) => `${(v.sha || v.id || "").slice(0, 12).padEnd(13)} ${(v.created_at || "").slice(0, 16).padEnd(17)} ${v.version_name || v.name || v.label || ""}`; -const FLAGS = new Set(["--camera", "--screen", "--test", "--beta", "--system", "--load-test", "--service", "--remove-service", "--new", "--replace", "--no-manifest", "--no-team", "--claude", "--codex", "--antigravity", "--no-memory", "--codex-chain", "--once", "--no-service", "--dry-run", "--no-skill", "--no-login"]); +const FLAGS = new Set(["--camera", "--screen", "--test", "--beta", "--system", "--load-test", "--service", "--remove-service", "--new", "--replace", "--no-manifest", "--no-team", "--claude", "--codex", "--antigravity", "--no-memory", "--codex-chain", "--once", "--no-service", "--dry-run", "--no-skill", "--no-login", "--quiet"]); const camel = (s) => s.replace(/-([a-z])/g, (_, c) => c.toUpperCase()); /** --scope as the server names it: stream(s) → "stream", session(s)/ingest → "ingest", full/none → undefined. */ function keyScope(v) { @@ -525,6 +532,12 @@ const LOCAL = { if (opts.help) return out(" spacesheep skills lint [folder] [--json]"); process.exitCode = require("../lib/skill-lint").run(opts._[2], { json: opts.json }); }, + // The official skills `install` put here, brought to the store's version (what a harness + // start runs once a day). Local: it writes folders on this machine. + "skills refresh": async (opts) => { + if (opts.help) return out(" spacesheep skills refresh [--dry-run] [--json] bring the official skills install put here to the store's version"); + return require("../lib/install").refresh(opts, log, out); + }, }; const HELD = new Set(["talk listen", "sessions export", "deploy", "read", "share", "delete"]); // Held too, on the new call: `talk on|off` write this machine's opt-in, and `talk` and `talk diff --git a/lib/install.js b/lib/install.js index e6b721f..4c36781 100644 --- a/lib/install.js +++ b/lib/install.js @@ -15,6 +15,7 @@ const cfg = require("./config"); const { McpClient } = require("./mcp"); const H = require("./harnesses"); const S = require("./skills"); +const O = require("./official"); const machineName = (opts) => String(opts.name || os.hostname().split(".")[0] || "machine").slice(0, 60); const real = (p) => { try { return fs.realpathSync(p); } catch (_) { return p; } }; @@ -125,10 +126,10 @@ const atLeast = (v, min) => { const a = v.split(".").map(Number), b = min.split( function chosen(all, opts = {}) { const words = (v) => [].concat(v || []).flatMap((x) => String(x).split(",")).map((x) => x.trim().toLowerCase()).filter(Boolean); const only = words(opts.only); - const skip = words(opts.skip); + const skip = words(opts.skip).filter((w) => !O.isOfficialWord(w)); // a skill's name, not a harness's for (const [flag, list] of [["--only", only], ["--skip", skip]]) { const unknown = list.filter((w) => !all.some((h) => H.matches(h, w))); - if (unknown.length) throw new Error(`${flag}: no harness called ${unknown.join(", ")} (known: ${[...new Set(all.filter((h) => h.present || !h.id.includes(":")).map((h) => h.id))].join(", ")})`); + if (unknown.length) throw new Error(`${flag}: no harness called ${unknown.join(", ")} (known: ${[...new Set(all.filter((h) => h.present || !h.id.includes(":")).map((h) => h.id))].join(", ")}${flag === "--skip" ? `; or a skill: ${O.OFFICIAL.map(O.slugOf).join(", ")}` : ""})`); } return all.filter((h) => (only.length ? only.some((w) => H.matches(h, w)) : h.present) && !skip.some((w) => H.matches(h, w))); } @@ -136,11 +137,32 @@ function chosen(all, opts = {}) { function chosenSkills(targets, opts = {}) { const words = (v) => [].concat(v || []).flatMap((x) => String(x).split(",")).map((x) => x.trim().toLowerCase()).filter(Boolean); const only = words(opts.only); - const skip = words(opts.skip); + const skip = words(opts.skip).filter((w) => !O.isOfficialWord(w)); const asH = (t) => ({ id: t.id, label: t.harness }); return targets.filter((t) => (!only.length || only.some((w) => H.matches(asH(t), w))) && !skip.some((w) => H.matches(asH(t), w))); } +/** The official skills, for the same choice of harnesses, `--skip design` taken out. */ +async function officialSkills(opts, key, { dryRun, only = false } = {}) { + const skip = [].concat(opts.skip || []).flatMap((x) => String(x).split(",")).map((x) => x.trim().toLowerCase()); + const names = O.namesAfterSkip(skip); + const targets = O.officialTargets(chosenSkills(S.skillTargets(), opts)); + if (!names.length || !targets.length) return []; + const st = O.store({ origin: cfg.origin(), configDir: cfg.configDir(), key, version: require("../package.json").version, cache: !dryRun }); + const go = () => O.installOfficial(targets, { st, names, dryRun, only, stageDir: path.join(cfg.configDir(), "skills-stage") }); + if (dryRun) return go(); + // One at a time on this machine: install waits for a refresh or an uninstall to end; a refresh + // (`only`) finds one running and leaves it, as the next harness start tries again. + const held = await O.withLock(cfg.configDir(), go, { wait: only ? 0 : 120000 }); + if (held.busy) { + // A refresh leaves it for the next harness start, and says why (`--quiet` hides it, as all else). + if (only) { O.logRefreshSkip(cfg.configDir(), O.lockAdvice(held)); return [{ skill: "official skills", harness: "", action: "skipped", error: O.lockAdvice(held) }]; } + throw new Error(O.lockAdvice(held)); + } + if (held.value.some((r) => !r.error)) O.markChecked(cfg.configDir()); + return held.value; +} + const pad = (s, n) => (s + " ".repeat(n)).slice(0, Math.max(n, s.length)); const MARKS = { added: "✓", replaced: "✓", updated: "✓", unchanged: "·", removed: "✓", skipped: "!" }; @@ -171,8 +193,14 @@ async function run(opts, log, out) { try { skillText = await S.fetchSkill(cfg.appOrigin()); skills = S.installSkills(skillText, chosenSkills(S.skillTargets(), opts), { dryRun }); } catch (e) { skillError = e.message; } } + // The official skills beside /sheep (official.js), so the harness's own picker finds them. + let official = []; + if (!opts.noSkill) { + try { official = await officialSkills(opts, k.key, { dryRun }); } + catch (e) { official = [{ skill: "official skills", harness: "", action: "skipped", error: e.message }]; } + } const missing = opts.only ? [] : all.filter((h) => !h.present && !h.id.includes(":") && !/older config/.test(h.label)); - if (opts.json) return out({ machine, username: who || null, tools, command: cmd.argv, copied: cmd.copied, dry_run: dryRun, harnesses: results, skills, skill_error: skillError, not_found: missing.map((h) => h.id) }); + if (opts.json) return out({ machine, username: who || null, tools, command: cmd.argv, copied: cmd.copied, dry_run: dryRun, harnesses: results, skills, skill_error: skillError, official_skills: official, not_found: missing.map((h) => h.id) }); log(`\n ${dryRun ? "Would connect" : "Connected"} this machine${who ? ` (@${who}` : " ("}${machine ? ` on "${machine}"` : ""}) with ${k.how} — ${tools} tools.`); log(` The agents below run: ${cmd.argv.map((a) => (/\s/.test(a) ? JSON.stringify(a) : a)).join(" ")}`); @@ -186,6 +214,11 @@ async function run(opts, log, out) { log(`\n /sheep skill ${S.versionOf(skillText) || ""}`.trimEnd()); for (const s of skills) log(` ${s.error ? "!" : s.note ? "·" : MARKS[s.action] || "·"} ${pad(s.harness, w)} ${pad(s.file || "", 34)} ${describe(s)}`); } + if (official.length) { + log(`\n Official skills (the harness picks them by their description)`); + const sw = Math.max(...official.map((s) => s.skill.length)); + for (const s of official) log(` ${s.error ? "!" : MARKS[s.action] || "·"} ${pad(s.skill, sw)} ${pad(s.harness, w)} ${pad(s.file || "", 30)} ${s.error || `${describe(s)} ${s.version || ""}`.trim()}`); + } // The plugin's own copy of the server stands down for one with the same URL, in // Claude Code 2.1.71 and newer; an older one would list every tool twice. const plugin = H.claudeDirs(os.homedir(), process.env).some((d) => S.pluginEnabled(d)); @@ -257,7 +290,9 @@ async function status(opts, out, log) { try { text = fs.readFileSync(t.file, "utf8"); } catch (_) {} return { harness: t.harness, file: t.shown, version: text && text.includes(S.MARK) ? S.versionOf(text) : null }; }); - if (opts.json) return out({ signed_in: !!k, key_prefix: k ? k.key.slice(0, 8) : null, harnesses: rows, skills }); + const official = O.officialStatus(O.officialTargets(S.skillTargets())); + const lock = O.abandonedLock(cfg.configDir()); + if (opts.json) return out({ signed_in: !!k, key_prefix: k ? k.key.slice(0, 8) : null, harnesses: rows, skills, official_skills: official, official_skills_lock: lock }); log(`\n This machine: ${k ? `signed in (${k.key.slice(0, 8)}…)` : "not signed in — run `npx -y spacesheep@latest install`"}\n`); const w = Math.max(12, ...rows.map((r) => r.harness.length)); for (const r of rows) { @@ -274,6 +309,11 @@ async function status(opts, out, log) { log(`\n /sheep skill`); for (const s of skills) log(` ${pad(s.harness, w)} ${pad(s.file || "", 34)} ${s.note || (s.version ? s.version : "not installed")}`); } + if (official.length) { + log(`\n Official skills`); + for (const s of official) log(` ${pad(s.harness, w)} ${pad(s.file, 34)} ${s.version || "not installed"}`); + } + if (lock) log(`\n ! ${lock} Until then they aren't refreshed.`); log(""); } @@ -281,9 +321,30 @@ async function uninstall(opts, log, out) { const dryRun = !!opts.dryRun; const results = chosen(H.harnesses(), opts).map((h) => H.uninstall(h, { dryRun })); const skills = opts.noSkill ? [] : S.uninstallSkills(chosenSkills(S.skillTargets(), opts), { dryRun }); - if (opts.json) return out({ harnesses: results, skills }); - for (const r of [...results, ...skills]) if (r.action !== "unchanged") log(` ${MARKS[r.action] || "·"} ${pad(r.harness, 14)} ${pad(r.file || "", 34)} ${r.error || r.action}`); + const skip = [].concat(opts.skip || []).flatMap((x) => String(x).split(",")).map((x) => x.trim().toLowerCase()); + const take = () => O.uninstallOfficial(O.officialTargets(chosenSkills(S.skillTargets(), opts)), { names: O.namesAfterSkip(skip), dryRun }); + let official = []; + if (!opts.noSkill && dryRun) official = take(); + else if (!opts.noSkill) { + // Waits out an install or a refresh mid-fetch, so neither can put a folder back after this. + const held = await O.withLock(cfg.configDir(), take, { wait: 120000 }); + official = held.busy ? [{ skill: "official skills", harness: "", action: "skipped", error: O.lockAdvice(held) }] : held.value; + } + if (opts.json) return out({ harnesses: results, skills, official_skills: official }); + for (const r of [...results, ...skills, ...official]) if (r.action !== "unchanged") log(` ${MARKS[r.action] || "·"} ${pad(r.harness, 14)} ${pad(r.file || "", 34)} ${r.error || r.action}`); log(`\n ${dryRun ? "Would remove" : "Removed"} the bridge from ${results.filter((r) => r.action === "removed").length} harness(es). This machine's key stays (\`spacesheep logout\` forgets it).\n`); } -module.exports = { run, status, uninstall, stableCommand, chosen, chosenSkills, ensureKey }; +/** `skills refresh`: the official skills this installed, brought to the store's current + * version; none added. What a harness start runs once a day (official.startRefresh). */ +async function refresh(opts, log, out) { + const k = cfg.resolveKey(); + if (!k) throw Object.assign(new Error("not signed in — run `spacesheep login` (or set SPACESHEEP_KEY)"), { code: "EAUTH" }); + const results = await officialSkills({}, k.key, { dryRun: !!opts.dryRun, only: true }); + if (opts.json) return out({ official_skills: results }); + if (opts.quiet) return; + if (!results.length) return log(" No official skills installed here (`spacesheep install` puts them in)."); + for (const s of results) log(` ${s.error ? "!" : MARKS[s.action] || "·"} ${pad(s.skill, 20)} ${pad(s.file || "", 30)} ${s.error || `${describe(s)} ${s.version || ""}`.trim()}`); +} + +module.exports = { run, status, uninstall, refresh, officialSkills, stableCommand, chosen, chosenSkills, ensureKey }; diff --git a/lib/official.js b/lib/official.js new file mode 100644 index 0000000..f2affa8 --- /dev/null +++ b/lib/official.js @@ -0,0 +1,325 @@ +// The official skills (@spacesheep/design, docs, sheets), put beside /sheep in every +// harness that reads skills, as native skill folders (`~/.claude/skills/design`, +// `~/.codex/skills/design`, …). The harness's own skill picker then routes "design me a +// landing page" to Design, with nothing to fetch first: before this, the agent had to +// follow sheep.md's "a skill from the library comes first" step, and Codex skipped it. +// +// Each folder is exactly what `skills get -o ` writes (doors.takeFolder, the +// same code), at the store's current version, plus one file of ours, MARKER, which says +// which skill and version it is. A folder is only ever replaced or removed when it has +// that file, so a skill the person made or installed by hand is never touched. +// +// Kept current the way /sheep is: compare the copy's version with the store's, and +// replace the copy when they differ. /sheep's agent does that at the start of a run; a +// folder of ~20 files takes ~25 s to fetch, which would come before the first canvas, so +// here the CLI does it instead, outside any turn: `install` (each run), and once a day at +// a harness start (`mcp` and `mcp headers` call startRefresh, which runs `skills refresh` +// in the background). +"use strict"; + +const fs = require("fs"); +const path = require("path"); +const os = require("os"); +const { spawn } = require("child_process"); +const crypto = require("crypto"); + +const OFFICIAL = ["@spacesheep/design", "@spacesheep/docs", "@spacesheep/sheets"]; +const MARKER = ".spacesheep-skill.json"; +const REFRESH_EVERY_MS = 24 * 60 * 60 * 1000; + +/** `@spacesheep/design` → `design`: the folder's name, and the name in its SKILL.md. */ +const slugOf = (name) => String(name).replace(/^@[^/]+\//, ""); + +/** The skills folders the official skills go in: each harness's `skillsDir` from + * skillTargets, where its /sheep is (a Claude home whose /sheep is a command, or comes + * from the plugin, still reads `/skills`). → [{ id, harness, dir, shown }] */ +function officialTargets(targets) { + const seen = new Set(); + const out = []; + for (const t of targets) { + if (!t.skillsDir || seen.has(t.skillsDir)) continue; + seen.add(t.skillsDir); + out.push({ id: t.id, harness: t.harness, dir: t.skillsDir, shown: tilde(t.skillsDir) }); + } + return out; +} +const tilde = (p) => { const h = os.homedir(); return p.startsWith(h + path.sep) ? "~" + p.slice(h.length) : p; }; + +/** `--skip design` (or @spacesheep/design) leaves that skill out, beside the harnesses. */ +const isOfficialWord = (w) => OFFICIAL.some((n) => w === n || w === slugOf(n)); +const namesAfterSkip = (skip) => OFFICIAL.filter((n) => !skip.some((w) => w === n || w === slugOf(n))); + +/** What our marker says about a folder, or null: a folder without it isn't ours. */ +function readMarker(folder) { + try { + const m = JSON.parse(fs.readFileSync(path.join(folder, MARKER), "utf8")); + return m && typeof m.skill === "string" ? m : null; + } catch (_) { return null; } +} +const exists = (p) => { try { fs.lstatSync(p); return true; } catch (_) { return false; } }; + +/** The store's side, through the doors table: `card` is one short call (which version is + * current), `fetch` writes the whole folder, as `skills get -o ` does. */ +function store({ origin, configDir, key, version, fetchImpl, table, cache = true }) { + const doors = require("./doors"); + const loadTable = async () => { + // `cache: false` (--dry-run) writes nothing: the cached table if there is one, else the server's, read and dropped. + if (table === undefined && !cache) table = (await doors.loadTable({ origin, configDir, offline: true })) || (await tableUncached(origin, fetchImpl || fetch)); + if (table === undefined) table = await doors.loadTable({ origin, configDir, ...(fetchImpl ? { fetchImpl } : {}) }); + if (!table) throw new Error("this server has no skills store (no /v1/doors.json)"); + return table; + }; + const ctx = { origin, key: () => key, version, ...(fetchImpl ? { fetchImpl } : {}) }; + return { + async card(name) { + const r = await doors.call(await loadTable(), "skills get", { skill: name, view: "card" }, ctx); + if (!r) throw new Error("this server's table has no `skills get`"); + if (r.error) throw new Error(doors.refusalWords(r.error, { word: true })); + const v = (r.answer && (r.answer.served || (r.answer.skill && r.answer.skill.version))) || {}; + if (!v.number) throw new Error(`the store didn't say which version of ${name} is current`); + return { number: v.number, label: v.label || `v${v.number}`, hash: v.hash || null }; + }, + async fetch(name, dir, number) { + const t = await loadTable(); + const found = doors.match(t, ["skills", "get"]); + const method = found && [].concat(found)[0].method; + if (!method || !method.answer_folder) throw new Error("this server's `skills get` can't write a folder (-o)"); + let said = null; + const inputs = { skill: name }; + if (number) inputs.version = number; // the version the card named, so every copy is the same one + await doors.takeFolder(method, { inputs, global: { out: dir, json: true } }, { ...ctx, out: (s) => { said = s; } }); + return JSON.parse(said); + }, + }; +} + +async function tableUncached(origin, fetchImpl) { + const r = await fetchImpl(`${String(origin).replace(/\/+$/, "")}/v1/doors.json`, { headers: { Accept: "application/json" }, signal: AbortSignal.timeout(10000) }); + if (r.status === 404) return null; + if (!r.ok) throw new Error(`couldn't read the server's table (HTTP ${r.status})`); + const t = JSON.parse(await r.text()); + return t && Array.isArray(t.services) ? t : null; +} + +/** Whether `folder` may be written for `name` now: ours for this skill, or (unless `only`) not there. + * → null when it may, else why not. Asked when the work is chosen and again just before the swap. */ +function mayWrite(folder, name, { only = false } = {}) { + const mark = readMarker(folder); + if (mark) return mark.skill === name ? null : `${mark.skill} is installed there`; + if (exists(folder)) return "a different skill is already there"; + return only ? "it was taken out meanwhile" : null; +} + +/** Replaces `dest` with `from` in two renames, so a harness never reads half a folder. The folder + * moved aside is checked again once it's aside (nothing can change it there): not ours for + * `name`, and it goes back untouched. */ +function swapIn(from, dest, name) { + const old = `${dest}.${process.pid}.old`; + if (exists(dest)) { + fs.renameSync(dest, old); + const mark = readMarker(old); + if (!mark || mark.skill !== name) { fs.renameSync(old, dest); throw new Error("a different skill is already there"); } + } + try { fs.renameSync(from, dest); } + catch (e) { if (exists(old)) fs.renameSync(old, dest); throw e; } + fs.rmSync(old, { recursive: true, force: true }); +} + +/** + * Puts each official skill in each target at the store's current version. + * `only` (refresh): touch only folders that are ours already, never add one. + * → [{ skill, harness, file, action, version, from, error }] + */ +async function installOfficial(targets, { st, names = OFFICIAL, dryRun = false, only = false, stageDir }) { + // The skills side by side: each is a fetch of its own (~25 s for Design), the harnesses' copies one after another. + const each = await Promise.all(names.map((name) => installOne(name, targets, { st, dryRun, only, stageDir }))); + return each.flat(); +} + +async function installOne(name, targets, { st, dryRun, only, stageDir }) { + const results = []; + const slug = slugOf(name); + const row = (t, more) => ({ skill: name, harness: t.harness, file: path.join(t.shown, slug), ...more }); + let card; + try { card = await st.card(name); } + catch (e) { for (const t of targets) results.push(row(t, { action: "skipped", error: e.message })); return results; } + // Which targets need this version written, and what each has now. + const todo = []; + for (const t of targets) { + const folder = path.join(t.dir, slug); + const mark = readMarker(folder); + if (only && (!mark || mark.skill !== name)) continue; // refresh: only what install put there + const no = mayWrite(folder, name); + if (no) { results.push(row(t, { action: "skipped", error: no })); continue; } + if (mark && mark.number === card.number && exists(path.join(folder, "SKILL.md"))) { results.push(row(t, { action: "unchanged", version: card.label })); continue; } + todo.push({ t, folder, from: mark ? mark.version || null : null, added: !mark }); + } + if (!todo.length) return results; + if (dryRun) { for (const x of todo) results.push(row(x.t, { action: x.added ? "added" : "updated", from: x.from, version: card.label })); return results; } + // Fetched once, then copied into each harness. + const stage = path.join(stageDir, `${slug}.${process.pid}.${Date.now()}`); + let got; + try { + fs.mkdirSync(stageDir, { recursive: true, mode: 0o700 }); + got = await st.fetch(name, stage, card.number); + fs.writeFileSync(path.join(stage, MARKER), JSON.stringify({ skill: name, version: got.version || card.label, number: card.number, hash: card.hash, installed_by: "spacesheep install" }, null, 2) + "\n"); + } catch (e) { + fs.rmSync(stage, { recursive: true, force: true }); + for (const x of todo) results.push(row(x.t, { action: "skipped", error: `couldn't fetch it: ${e.message}` })); + return results; + } + for (const x of todo) { + const tmp = `${x.folder}.${process.pid}.tmp`; + try { + // The fetch took a while: a folder made, changed or taken out since is left as it is now. + const no = mayWrite(x.folder, name, { only }); + if (no) { results.push(row(x.t, { action: "skipped", error: no })); continue; } + fs.mkdirSync(x.t.dir, { recursive: true }); + fs.rmSync(tmp, { recursive: true, force: true }); + fs.cpSync(stage, tmp, { recursive: true }); + swapIn(tmp, x.folder, name); + results.push(row(x.t, { action: x.added ? "added" : "updated", from: x.from, version: got.version || card.label })); + } catch (e) { + fs.rmSync(tmp, { recursive: true, force: true }); + results.push(row(x.t, { action: "skipped", error: e.message })); + } + } + fs.rmSync(stage, { recursive: true, force: true }); + return results; +} + +/** Takes out the folders this installed (those with our marker), and nothing else. */ +function uninstallOfficial(targets, { names = OFFICIAL, dryRun = false } = {}) { + const out = []; + for (const name of names) for (const t of targets) { + const folder = path.join(t.dir, slugOf(name)); + const mark = readMarker(folder); + if (!mark || mark.skill !== name) continue; + if (!dryRun) { + try { fs.rmSync(folder, { recursive: true, force: true }); } + catch (e) { out.push({ skill: name, harness: t.harness, file: path.join(t.shown, slugOf(name)), action: "skipped", error: e.message }); continue; } + } + out.push({ skill: name, harness: t.harness, file: path.join(t.shown, slugOf(name)), action: "removed" }); + } + return out; +} + +/** Which version each harness has. → [{ skill, harness, file, version }] */ +function officialStatus(targets, { names = OFFICIAL } = {}) { + const out = []; + for (const name of names) for (const t of targets) { + const mark = readMarker(path.join(t.dir, slugOf(name))); + out.push({ skill: name, harness: t.harness, file: path.join(t.shown, slugOf(name)), version: mark && mark.skill === name ? mark.version : null }); + } + return out; +} + +const lockPath = (configDir) => path.join(configDir, "official-skills.lock"); +const alive = (pid) => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === "EPERM"; } }; + +/** Runs `fn` holding this machine's lock on the official skills' folders, so an install, a + * refresh and an uninstall never interleave (a refresh can't put back what an uninstall just + * took out). `wait`: how long to wait for another holder; past it, `fn` doesn't run and this + * resolves `busy` with what's known of the holder (lockAdvice words it). + * The lock appears whole: its record is written to a file of this process's own and then + * hard-linked into place (`link` fails if the lock is there), so nobody reads it half-written. + * A lock is never taken over, however old, or whatever its owner: only the person can tell + * that it's abandoned, so it stays until its owner or they delete it. One whose owner isn't + * running is reported at once, rather than waited on. */ +async function withLock(configDir, fn, { wait = 120000, now = Date.now } = {}) { + const file = lockPath(configDir); + fs.mkdirSync(configDir, { recursive: true, mode: 0o700 }); + const until = now() + wait; + const mine = JSON.stringify({ pid: process.pid, at: now(), id: crypto.randomBytes(8).toString("hex") }) + "\n"; + const tmp = `${file}.${process.pid}.${crypto.randomBytes(4).toString("hex")}`; + fs.writeFileSync(tmp, mine, { flag: "wx" }); + try { + for (;;) { + try { fs.linkSync(tmp, file); break; } + catch (e) { + if (e.code !== "EEXIST") throw e; + const held = readLock(file); + if (!held) continue; // released between link and read: try again + const busy = { busy: true, file, pid: held.pid, since: held.at, running: held.pid ? alive(held.pid) : null }; + if (busy.running === false || now() >= until) return busy; + await new Promise((r) => setTimeout(r, 250)); + } + } + } finally { try { fs.unlinkSync(tmp); } catch (_) {} } + try { return { value: await fn() }; } + finally { try { if (fs.readFileSync(file, "utf8") === mine) fs.unlinkSync(file); } catch (_) {} } +} + +/** The lock's owner as it says: { pid, at } (both null when it can't be read, a permission + * error included), or null only when there's no lock. */ +function readLock(file) { + let text; + try { text = fs.readFileSync(file, "utf8"); } + catch (e) { return e.code === "ENOENT" ? null : { pid: null, at: null }; } + try { const r = JSON.parse(text); if (r && Number.isInteger(r.pid) && r.pid > 0) return { pid: r.pid, at: Number(r.at) || null }; } catch (_) {} + return { pid: null, at: null }; +} + +/** What to tell the person when withLock is busy: who holds it, and how to clear it if nobody does. */ +function lockAdvice(held) { + const since = held.since ? ` since ${new Date(held.since).toISOString()}` : ""; + const clear = `If no spacesheep is running, delete ${held.file} and try again.`; + if (held.running) return `another spacesheep (pid ${held.pid}${since}) is changing the official skills; try again when it's done. ${clear}`; + if (held.running === false) return `the official skills are locked by pid ${held.pid}${since}, which isn't running any more. ${clear}`; + return `the official skills' lock can't be read, so it's left alone. ${clear}`; +} + +/** The lock, when it outlived its owner (or can't be read): lockAdvice's line for it. Null when + * there's none, or its owner is still running. What `status` shows, so a crashed install doesn't + * leave the daily refresh skipping with nobody seeing it. */ +function abandonedLock(configDir) { + const file = lockPath(configDir), held = readLock(file); + if (!held) return null; + const running = held.pid ? alive(held.pid) : null; + return running ? null : lockAdvice({ file, pid: held.pid, since: held.at, running }); +} + +const refreshLogPath = (configDir) => path.join(configDir, "official-skills-refresh.log"); + +/** A refresh that skipped says so here, its last skip only (a detached refresh has no terminal). */ +function logRefreshSkip(configDir, text, now = Date.now()) { + try { fs.writeFileSync(refreshLogPath(configDir), `${new Date(now).toISOString()} skipped: ${text}\n`); } catch (_) {} +} + +const stampPath = (configDir) => path.join(configDir, "official-skills-check.json"); + +/** Says the official skills were just checked; `install` and `skills refresh` write it. + * Its being there is also what turns startRefresh on: no file, nothing installed. */ +function markChecked(configDir, now = Date.now()) { + try { + fs.mkdirSync(configDir, { recursive: true, mode: 0o700 }); + fs.writeFileSync(stampPath(configDir), JSON.stringify({ checked: now }) + "\n"); + } catch (_) {} +} + +/** At a harness start: once a day, `skills refresh` in the background, detached, so the + * harness never waits on it. Only where install put the official skills (its stamp is + * there). Harnesses starting together start one: each stamp is claimed once, by creating + * a claim file named for it (`wx`, so only one creator wins), and the winner moves the + * stamp on. Never throws, never prints (stdout is the MCP protocol). */ +function startRefresh({ configDir, script, env = process.env, now = Date.now(), run = spawn } = {}) { + try { + if (env.CI || env.SPACESHEEP_NO_UPDATE_CHECK || env.SPACESHEEP_NO_SKILL_REFRESH) return false; + let last; + try { last = Number(JSON.parse(fs.readFileSync(stampPath(configDir), "utf8")).checked) || 0; } catch (_) { return false; } + if (now - last < REFRESH_EVERY_MS) return false; + const claim = `official-skills-refresh.${last}.claim`; + try { fs.writeFileSync(path.join(configDir, claim), `${process.pid}\n`, { flag: "wx" }); } + catch (_) { return false; } // another harness claimed this one + fs.writeFileSync(stampPath(configDir), JSON.stringify({ checked: now }) + "\n"); + // Older claims go; this one stays, so a start that read the same stamp late still loses. + for (const f of fs.readdirSync(configDir)) if (/^official-skills-refresh\.\d+\.claim$/.test(f) && f !== claim) { try { fs.unlinkSync(path.join(configDir, f)); } catch (_) {} } + const child = run(process.execPath, [script, "skills", "refresh", "--quiet"], { detached: true, stdio: "ignore", env }); + // A spawn that fails (no node at that path, EAGAIN) says so on `error`: unheard, it would end the harness's process. + if (child && child.on) child.on("error", () => {}); + if (child && child.unref) child.unref(); + return true; + } catch (_) { return false; } +} + +module.exports = { OFFICIAL, isOfficialWord, namesAfterSkip, MARKER, REFRESH_EVERY_MS, slugOf, officialTargets, readMarker, store, installOfficial, uninstallOfficial, officialStatus, startRefresh, markChecked, stampPath, withLock, lockPath, readLock, lockAdvice, abandonedLock, refreshLogPath, logRefreshSkip }; diff --git a/lib/skills.js b/lib/skills.js index 2f0626d..2f786c1 100644 --- a/lib/skills.js +++ b/lib/skills.js @@ -63,11 +63,13 @@ function skillTargets({ home = os.homedir(), env = process.env } = {}) { if (!exists(dir) || (i > 0 && !exists(path.join(dir, ".claude.json")))) return; const id = claudeId(dir, i === 0); const label = i === 0 ? "Claude Code" : `Claude Code (${tilde(dir)})`; - if (pluginEnabled(dir)) return out.push({ id, harness: label, skip: "the spacesheep plugin carries it" }); + // `skillsDir`: where the other skills go (official.js), whatever carries /sheep here. + const skillsDir = path.join(dir, "skills"); + if (pluginEnabled(dir)) return out.push({ id, harness: label, skip: "the spacesheep plugin carries it", skillsDir }); // `npx spacesheep-skill` installed it as a command: keep it one /sheep, updated there. const command = path.join(dir, "commands", "sheep.md"); - if (exists(command)) return out.push({ id, harness: label, file: command, frontmatter: false }); - out.push({ id, harness: label, file: path.join(dir, "skills", "sheep", "SKILL.md"), frontmatter: true }); + if (exists(command)) return out.push({ id, harness: label, file: command, frontmatter: false, skillsDir }); + out.push({ id, harness: label, file: path.join(skillsDir, "sheep", "SKILL.md"), frontmatter: true, skillsDir }); }); const others = [ ["codex", "Codex", path.join(env.CODEX_HOME || path.join(home, ".codex"), "skills")], @@ -75,7 +77,7 @@ function skillTargets({ home = os.homedir(), env = process.env } = {}) { ["gemini", "Gemini CLI", path.join(home, ".gemini", "skills")], ["antigravity", "Antigravity", path.join(home, ".gemini", "config", "skills")], ]; - for (const [id, harness, dir] of others) if (exists(dir)) out.push({ id, harness, file: path.join(dir, "sheep", "SKILL.md"), frontmatter: true }); + for (const [id, harness, dir] of others) if (exists(dir)) out.push({ id, harness, file: path.join(dir, "sheep", "SKILL.md"), frontmatter: true, skillsDir: dir }); for (const t of out) if (t.file) t.shown = tilde(t.file); return out; } diff --git a/test/official.test.js b/test/official.test.js new file mode 100644 index 0000000..a2a3c94 --- /dev/null +++ b/test/official.test.js @@ -0,0 +1,249 @@ +"use strict"; +// The official skills `install` puts beside /sheep (lib/official.js): fetched as `skills get -o` writes them, one marker +// file of ours, replaced only when the store's version moves, never over a folder that isn't ours, and refreshed once a +// day from a harness start. +const test = require("node:test"); +const assert = require("node:assert"); +const fs = require("fs"); +const os = require("os"); +const path = require("path"); +const O = require("../lib/official"); +const S = require("../lib/skills"); +const { chosen } = require("../lib/install"); +const H = require("../lib/harnesses"); + +const tmp = (p = "ss-off-") => fs.mkdtempSync(path.join(os.tmpdir(), p)); +const flag = (input, type = "text") => ({ flag: `--${input}`, input, type }); +const at = (name, ref) => ({ name, type: name === "version" || name === "offset" ? "integer" : "text", at: [name === "skill_id" ? "skill" : name], ...(ref ? { ref, either: "skill" } : {}) }); +// GetSkill as the server's doors.json has it (test/answer-folder.test.js). +const TABLE = { services: [{ methods: [{ + method: "GetSkill", verb: "Get", http: "GET", path: "/v1/skills/{skill.id}", where: "query", errors: ["not_found"], + cli: { command: "spacesheep skills get", usage: "spacesheep skills get [flags]", args: ["skill"], flags: [flag("view", "one of card, full"), flag("path"), flag("version", "integer"), flag("offset", "integer")] }, + inputs: [at("skill", "name"), at("skill_id", "id"), at("view"), at("path"), at("version"), at("offset")], + answer_folder: { list: "files", list_with: { input: "view", value: "full" }, path: "path", file: "file", text: "text", bytes: "data", offset: "offset", next: "next_offset", served: "served", number: "number", label: "label", pin: "version" }, +}] }] }; + +/** A store with one skill per name: `live.n` is its current version, each version has its own files. */ +function fakeStore(live, seen = []) { + const files = (n) => (n === 1 ? { "SKILL.md": "---\nname: design\n---\nv1\n", "assets/fold.js": "1" } : { "SKILL.md": `---\nname: design\n---\nv${n}\n`, "references/new.md": "n" }); + const fetchImpl = async (url) => { + const q = Object.fromEntries(new URL(url).searchParams); + seen.push(q); + const reply = (body) => ({ ok: true, status: 200, text: async () => JSON.stringify(body) }); + const v = Number(q.version) || live.n, served = { number: v, label: `v1.0.${v}`, hash: `h${v}` }; + if (!q.path) return reply({ skill: { name: q.skill, version: served }, served, ...(q.view === "full" ? { files: Object.keys(files(v)) } : {}) }); + return reply({ served, file: { path: q.path, text: files(v)[q.path] }, next_offset: 0 }); + }; + return O.store({ origin: "http://x", key: "ss_test", version: "0", table: TABLE, fetchImpl }); +} +const targets = (home) => ["a", "b"].map((n) => ({ id: n, harness: n, dir: path.join(home, n, "skills"), shown: `~/${n}/skills` })); +const ls = (d) => fs.readdirSync(d, { recursive: true }).filter((f) => fs.statSync(path.join(d, f)).isFile()).sort(); + +test("official: each harness gets the folder skills get -o writes, plus our marker; a re-run leaves it; a new version replaces it", async () => { + const home = tmp(), live = { n: 1 }, seen = [], st = fakeStore(live, seen), stageDir = path.join(home, "stage"); + const names = ["@spacesheep/design"]; + const first = await O.installOfficial(targets(home), { st, names, stageDir }); + assert.deepStrictEqual(first.map((r) => [r.harness, r.action, r.version]), [["a", "added", "v1.0.1"], ["b", "added", "v1.0.1"]]); + const folder = path.join(home, "a", "skills", "design"); + assert.deepStrictEqual(ls(folder), [O.MARKER, "SKILL.md", "assets/fold.js"]); + assert.deepStrictEqual(O.readMarker(folder), { skill: "@spacesheep/design", version: "v1.0.1", number: 1, hash: "h1", installed_by: "spacesheep install" }); + assert.deepStrictEqual(fs.readdirSync(stageDir), [], "the staging copy is cleaned up"); + // Fetched once for both harnesses: one card, one listing, one call a file. + assert.strictEqual(seen.filter((q) => q.view === "full").length, 1); + + seen.length = 0; + const again = await O.installOfficial(targets(home), { st, names, stageDir }); + assert.deepStrictEqual(again.map((r) => r.action), ["unchanged", "unchanged"]); + assert.deepStrictEqual(seen.map((q) => q.view), ["card"], "a re-run at the same version asks only which version is current"); + + live.n = 2; + const dry = await O.installOfficial(targets(home), { st, names, stageDir, dryRun: true }); + assert.deepStrictEqual(dry.map((r) => [r.action, r.from, r.version]), [["updated", "v1.0.1", "v1.0.2"], ["updated", "v1.0.1", "v1.0.2"]]); + assert.strictEqual(O.readMarker(folder).number, 1, "--dry-run writes nothing"); + const up = await O.installOfficial(targets(home), { st, names, stageDir }); + assert.deepStrictEqual(up.map((r) => r.action), ["updated", "updated"]); + assert.deepStrictEqual(ls(folder), [O.MARKER, "SKILL.md", "references/new.md"], "the old version's files are gone, not mixed in"); + assert.ok(seen.filter((q) => q.path).every((q) => q.version === "2"), "every file is the version the card named"); +}); + +test("official: a folder that isn't ours is never written; refresh only touches ours and adds none", async () => { + const home = tmp(), st = fakeStore({ n: 1 }), stageDir = path.join(home, "stage"), names = ["@spacesheep/design"]; + const mine = path.join(home, "a", "skills", "design"); + fs.mkdirSync(mine, { recursive: true }); + fs.writeFileSync(path.join(mine, "SKILL.md"), "my own design skill"); + const r = await O.installOfficial(targets(home), { st, names, stageDir }); + assert.deepStrictEqual(r.map((x) => [x.harness, x.action, x.error || null]), [["a", "skipped", "a different skill is already there"], ["b", "added", null]]); + assert.strictEqual(fs.readFileSync(path.join(mine, "SKILL.md"), "utf8"), "my own design skill"); + + const other = tmp(); + assert.deepStrictEqual(await O.installOfficial(targets(other), { st, names, stageDir, only: true }), []); + assert.ok(!fs.existsSync(path.join(other, "a")), "refresh adds no skill install didn't put there"); +}); + +test("official: uninstall takes out only the folders install put there", async () => { + const home = tmp(), st = fakeStore({ n: 1 }), names = ["@spacesheep/design"]; + await O.installOfficial(targets(home), { st, names, stageDir: path.join(home, "stage") }); + const mine = path.join(home, "b", "skills", "docs"); + fs.mkdirSync(mine, { recursive: true }); + const dry = O.uninstallOfficial(targets(home), { dryRun: true }); + assert.strictEqual(dry.length, 2); + assert.ok(fs.existsSync(path.join(home, "a", "skills", "design", "SKILL.md"))); + const r = O.uninstallOfficial(targets(home)); + assert.deepStrictEqual(r.map((x) => [x.skill, x.harness, x.action]), [["@spacesheep/design", "a", "removed"], ["@spacesheep/design", "b", "removed"]]); + assert.ok(!fs.existsSync(path.join(home, "a", "skills", "design"))); + assert.ok(fs.existsSync(mine), "a folder without our marker stays"); +}); + +test("official: they go wherever /sheep goes, a Claude home with the plugin or the command copy included", () => { + const home = tmp(); + for (const d of [".claude/commands", ".codex/skills", ".gemini/config/skills"]) fs.mkdirSync(path.join(home, d), { recursive: true }); + fs.writeFileSync(path.join(home, ".claude", "commands", "sheep.md"), ""); + const t = O.officialTargets(S.skillTargets({ home, env: {} })); + assert.deepStrictEqual(t.map((x) => [x.id, path.relative(home, x.dir)]), [["claude-code", ".claude/skills"], ["codex", ".codex/skills"], ["antigravity", ".gemini/config/skills"]]); + const plugin = tmp(); + fs.mkdirSync(path.join(plugin, ".claude", "plugins"), { recursive: true }); + fs.writeFileSync(path.join(plugin, ".claude", "plugins", "installed_plugins.json"), JSON.stringify({ plugins: { "spacesheep@spacesheep": [] } })); + assert.deepStrictEqual(O.officialTargets(S.skillTargets({ home: plugin, env: {} })).map((x) => path.relative(plugin, x.dir)), [".claude/skills"]); +}); + +test("official: --skip design leaves that skill out, and isn't taken for a harness", () => { + const home = tmp(); + fs.mkdirSync(path.join(home, ".codex")); + const all = H.harnesses({ home, platform: "linux", env: {} }); + assert.deepStrictEqual(chosen(all, { skip: "design" }).map((h) => h.id), ["codex"]); + assert.throws(() => chosen(all, { skip: "desing" }), /no harness called desing.*or a skill: design, docs, sheets/); + assert.deepStrictEqual(O.namesAfterSkip(["design", "@spacesheep/sheets"]), ["@spacesheep/docs"]); +}); + +test("official: a harness start refreshes once a day, in the background, and only where install put them", () => { + const dir = tmp("ss-cfg-"), runs = [], run = (cmd, args, o) => { runs.push({ cmd, args, o }); return { unref() {} }; }; + const go = (now, env = {}) => O.startRefresh({ configDir: dir, script: "/x/spacesheep.js", env, now, run }); + assert.strictEqual(go(1e12), false, "nothing installed: no stamp, no refresh"); + O.markChecked(dir, 1e12); + assert.strictEqual(go(1e12 + 60_000), false, "checked a minute ago"); + assert.strictEqual(go(1e12 + O.REFRESH_EVERY_MS, { CI: "1" }), false); + assert.strictEqual(go(1e12 + O.REFRESH_EVERY_MS), true); + assert.deepStrictEqual(runs.map((r) => [r.args, r.o.detached, r.o.stdio]), [[["/x/spacesheep.js", "skills", "refresh", "--quiet"], true, "ignore"]]); + assert.strictEqual(go(1e12 + O.REFRESH_EVERY_MS + 1000), false, "the stamp moved first: a second harness starting now starts none"); +}); + +/** The fake store, with `during(name)` run while the folder is being fetched (another process at work). */ +function racing(live, during) { + const st = fakeStore(live); + return { card: st.card, fetch: async (name, dir, n) => { const got = await st.fetch(name, dir, n); await during(name); return got; } }; +} + +test("official: a folder marked for another skill is never written", async () => { + const home = tmp(), folder = path.join(home, "a", "skills", "design"); + fs.mkdirSync(folder, { recursive: true }); + fs.writeFileSync(path.join(folder, O.MARKER), JSON.stringify({ skill: "@someone/design", version: "v9", number: 9 })); + const r = await O.installOfficial(targets(home).slice(0, 1), { st: fakeStore({ n: 1 }), names: ["@spacesheep/design"], stageDir: path.join(home, "stage") }); + assert.deepStrictEqual(r.map((x) => [x.action, x.error]), [["skipped", "@someone/design is installed there"]]); + assert.deepStrictEqual(fs.readdirSync(folder), [O.MARKER]); + assert.strictEqual(O.uninstallOfficial(targets(home)).length, 0, "nor taken out"); +}); + +test("official: what changed during the fetch is checked again at the swap", async () => { + const names = ["@spacesheep/design"]; + // A folder of the person's own made while it fetched: left as it is. + let home = tmp(); + const mine = path.join(home, "a", "skills", "design"); + let r = await O.installOfficial(targets(home).slice(0, 1), { names, stageDir: path.join(home, "stage"), st: racing({ n: 1 }, () => { fs.mkdirSync(mine, { recursive: true }); fs.writeFileSync(path.join(mine, "SKILL.md"), "mine"); }) }); + assert.deepStrictEqual(r.map((x) => [x.action, x.error]), [["skipped", "a different skill is already there"]]); + assert.strictEqual(fs.readFileSync(path.join(mine, "SKILL.md"), "utf8"), "mine"); + // A refresh whose folder was taken out (uninstall) while it fetched: not put back. + home = tmp(); + await O.installOfficial(targets(home).slice(0, 1), { names, stageDir: path.join(home, "stage"), st: fakeStore({ n: 1 }) }); + const ours = path.join(home, "a", "skills", "design"); + r = await O.installOfficial(targets(home).slice(0, 1), { names, only: true, stageDir: path.join(home, "stage"), st: racing({ n: 2 }, () => fs.rmSync(ours, { recursive: true })) }); + assert.deepStrictEqual(r.map((x) => [x.action, x.error]), [["skipped", "it was taken out meanwhile"]]); + assert.ok(!fs.existsSync(ours)); + assert.deepStrictEqual(fs.readdirSync(path.join(home, "a", "skills")), [], "no tmp or old copy left behind"); +}); + +test("official: one install, refresh or uninstall at a time", async () => { + const dir = tmp("ss-cfg-"); + let inside = 0; + const first = O.withLock(dir, async () => { inside++; await new Promise((r) => setTimeout(r, 300)); return "a"; }); + const busy = await O.withLock(dir, async () => "b", { wait: 0 }); + assert.strictEqual(busy.busy, true, "a refresh finds it held and leaves it"); + assert.strictEqual(busy.running, true); + assert.match(O.lockAdvice(busy), /another spacesheep \(pid \d+ since .*\) is changing/); + assert.strictEqual(O.abandonedLock(dir), null, "a lock whose owner runs isn't reported"); + const waited = O.withLock(dir, async () => { assert.strictEqual(inside, 1); return "c"; }, { wait: 5000 }); + assert.deepStrictEqual([await first, await waited], [{ value: "a" }, { value: "c" }]); + assert.deepStrictEqual(fs.readdirSync(dir), [], "no lock or temp file left behind"); + // Held, the lock is the whole record and nothing else: its temp file is gone already. + await O.withLock(dir, async () => { + assert.deepStrictEqual(fs.readdirSync(dir), ["official-skills.lock"]); + assert.strictEqual(JSON.parse(fs.readFileSync(O.lockPath(dir), "utf8")).pid, process.pid); + }); +}); + +test("official: a lock is never taken over: not half-written, not old, not one whose owner is gone", async () => { + const dir = tmp("ss-cfg-"), file = O.lockPath(dir); + let ran = 0; + const fn = async () => ran++; + // A contender that opened the lock (wx) and paused before writing its record. + fs.writeFileSync(file, "", { flag: "wx" }); + const unread = await O.withLock(dir, fn, { wait: 0 }); + assert.deepStrictEqual([unread.busy, unread.pid, unread.running], [true, null, null]); + assert.strictEqual(fs.readFileSync(file, "utf8"), "", "the paused writer's lock is still there"); + // One this user can't read (mode 000) is held too, and named, rather than spun on as if gone. + if (process.getuid && process.getuid() !== 0) { + fs.chmodSync(file, 0o000); + const t0 = Date.now(); + const denied = await O.withLock(dir, fn, { wait: 0 }); + assert.ok(Date.now() - t0 < 1000, "answers at once"); + assert.deepStrictEqual([denied.busy, denied.pid, denied.running], [true, null, null]); + assert.match(O.abandonedLock(dir), /lock can't be read/); + fs.chmodSync(file, 0o600); + } + // A live holder whose lock is past any age: the clock 16 minutes on doesn't free it. + fs.writeFileSync(file, JSON.stringify({ pid: process.pid, at: Date.now() })); + const later = () => Date.now() + 16 * 60 * 1000; + assert.strictEqual((await O.withLock(dir, fn, { wait: 0, now: later })).running, true); + // An owner that's gone is reported at once, not waited on, and its lock stays. + fs.writeFileSync(file, JSON.stringify({ pid: 2 ** 22 + 12345, at: Date.parse("2026-11-29T14:00:00Z") })); + const t = Date.now(); + const gone = await O.withLock(dir, fn, { wait: 60000 }); + assert.ok(Date.now() - t < 1000, "not waited on"); + assert.deepStrictEqual([gone.busy, gone.running], [true, false]); + assert.strictEqual(ran, 0, "the critical section never ran"); + assert.ok(fs.existsSync(file)); + // What install, uninstall and status say: who, since when, and the file to delete. + const line = O.abandonedLock(dir); + assert.strictEqual(line, O.lockAdvice(gone)); + assert.match(line, /pid 4206649 since 2026-11-29T14:00:00\.000Z, which isn't running any more/); + assert.ok(line.includes(`delete ${file}`)); + // Deleted by the person, it's free again. + fs.unlinkSync(file); + assert.deepStrictEqual(await O.withLock(dir, fn, { wait: 0 }), { value: 0 }); + assert.deepStrictEqual(fs.readdirSync(dir), []); +}); + +test("official: the daily claim is won once per stamp, and a spawn that fails doesn't reach the harness", async () => { + const dir = tmp("ss-cfg-"), { EventEmitter } = require("events"), kids = []; + const run = () => { const k = new EventEmitter(); k.unref = () => {}; kids.push(k); return k; }; + O.markChecked(dir, 1000); + const later = 1000 + O.REFRESH_EVERY_MS; + assert.strictEqual(O.startRefresh({ configDir: dir, script: "/x", env: {}, now: later, run }), true); + // A second harness that read the old stamp before the first moved it on. + O.markChecked(dir, 1000); + assert.strictEqual(O.startRefresh({ configDir: dir, script: "/x", env: {}, now: later, run }), false); + assert.strictEqual(kids.length, 1); + assert.doesNotThrow(() => kids[0].emit("error", Object.assign(new Error("spawn ENOENT"), { code: "ENOENT" }))); +}); + +test("official: --dry-run reads the server's table without caching it", async () => { + const dir = tmp("ss-cfg-"), seen = []; + const fetchImpl = async (url) => { + seen.push(String(url)); + if (String(url).endsWith("/v1/doors.json")) return { ok: true, status: 200, headers: { get: () => null }, text: async () => JSON.stringify(TABLE) }; + return { ok: true, status: 200, text: async () => JSON.stringify({ served: { number: 3, label: "v1.0.3" } }) }; + }; + const st = O.store({ origin: "http://x", configDir: dir, key: "ss_test", version: "0", fetchImpl, cache: false }); + assert.deepStrictEqual(await st.card("@spacesheep/design"), { number: 3, label: "v1.0.3", hash: null }); + assert.ok(seen[0].endsWith("/v1/doors.json")); + assert.deepStrictEqual(fs.readdirSync(dir), [], "nothing written to the config folder"); +});