From 7dea998cebc07836855e939e65ca76cbab108717 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 23:52:28 +0000 Subject: [PATCH 1/4] wip(cli): os skills install, update and status Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzgNCAXyGfBQFZBwixH --- packages/cli/package.json | 3 + packages/cli/src/commands/skills/install.ts | 67 ++++ packages/cli/src/commands/skills/status.ts | 126 +++++++ packages/cli/src/commands/skills/update.ts | 62 ++++ packages/cli/src/utils/skills-catalog.ts | 332 ++++++++++++++++++ packages/cli/src/utils/skills-command.ts | 154 ++++++++ .../cli/src/utils/skills-install-state.ts | 214 +++++++++++ 7 files changed, 958 insertions(+) create mode 100644 packages/cli/src/commands/skills/install.ts create mode 100644 packages/cli/src/commands/skills/status.ts create mode 100644 packages/cli/src/commands/skills/update.ts create mode 100644 packages/cli/src/utils/skills-catalog.ts create mode 100644 packages/cli/src/utils/skills-command.ts create mode 100644 packages/cli/src/utils/skills-install-state.ts diff --git a/packages/cli/package.json b/packages/cli/package.json index b2ae84b5c83..40d7d0c85db 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -96,6 +96,9 @@ "secret": { "description": "Maintain stored secrets: report orphaned rows, re-wrap old ciphertext" }, + "skills": { + "description": "Install, update and check the published ObjectStack skills catalog in your agent's skills directory" + }, "storage": { "description": "Inspect stored files: report orphaned attachments" } diff --git a/packages/cli/src/commands/skills/install.ts b/packages/cli/src/commands/skills/install.ts new file mode 100644 index 00000000000..b0b8dc7bc7a --- /dev/null +++ b/packages/cli/src/commands/skills/install.ts @@ -0,0 +1,67 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * `os skills install` — copy the published skills catalog + * (`@objectstack/skills`) at one version into an agent's skills directory, in + * a project or in an empty directory: no `package.json` is read or written. + * + * The version is `--version`, else the target environment's (`--target`, read + * as `os validate --target` reads it), else this CLI's own; the output names + * which. The catalog is the package tarball at exactly that version from the + * npm registry this environment configures (`utils/skills-catalog.ts`). What + * was written is recorded beside it (`utils/skills-install-state.ts`), so + * `os skills update` and `os skills status` can tell the catalog's skills from + * the user's own. A directory that already holds a recorded catalog is + * refused, naming `os skills update`; same-named skill directories the record + * does not name are refused unless `--force` replaces them. + */ + +import { Command, Flags } from '@oclif/core'; +import { isExitSignal, printError, printHeader, printSuccess } from '../../utils/format.js'; +import { runSkillsWrite, skillsCommonFlags, skillsWriteLines } from '../../utils/skills-command.js'; + +export default class SkillsInstall extends Command { + static override description = + 'Install the published ObjectStack skills catalog at the server\'s version into your agent\'s skills directory, with or without a project'; + + static override examples = [ + '$ os skills install # this CLI\'s version, into .claude/skills/', + '$ os skills install --version 18.5.0 # the version an MCP server names', + '$ os skills install --target https://acme.example.com # the version a target environment runs', + '$ os skills install --dir .agents/skills # another agent\'s skills directory', + ]; + + static override flags = { + ...skillsCommonFlags, + force: Flags.boolean({ + description: 'Replace skill directories this command did not install that share a catalog skill\'s name', + default: false, + }), + }; + + async run(): Promise { + const { flags } = await this.parse(SkillsInstall); + if (!flags.json) printHeader('Skills install'); + try { + const result = await runSkillsWrite({ + command: 'install', + version: flags.version, + target: flags.target, + dir: flags.dir, + force: flags.force, + cliVersion: this.config.version, + }); + if (flags.json) { + console.log(JSON.stringify(result, null, 2)); + return; + } + for (const line of skillsWriteLines(result)) console.log(` ${line}`); + printSuccess(`Installed ${result.added.length + result.adopted.length} skills of @objectstack/skills ${result.version}.`); + } catch (error) { + if (isExitSignal(error)) throw error; + if (flags.json) console.log(JSON.stringify({ ok: false, command: 'install', error: (error as Error).message }, null, 2)); + else printError((error as Error).message); + this.exit(1); + } + } +} diff --git a/packages/cli/src/commands/skills/status.ts b/packages/cli/src/commands/skills/status.ts new file mode 100644 index 00000000000..f1cef08e959 --- /dev/null +++ b/packages/cli/src/commands/skills/status.ts @@ -0,0 +1,126 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * `os skills status` — the catalog `os skills install` recorded, against the + * version it should be: `--version`, else the target environment's + * (`--target`), else this CLI's own — the order `install` uses. + * + * Reported: the installed and the expected version; `missing` — recorded + * skills whose directory is gone; `modified` — recorded skills with a file + * changed, removed or added; `extra` — skill directories the record does not + * name, the user's own, listed and never judged. + * + * A mismatch is: no recorded catalog, another version, or any missing or + * modified skill. The command exits 0 either way unless `--check` is given, + * when a mismatch exits 1. The registry is not read: the comparison is the + * record against the disk and the expected version. + */ + +import { Command, Flags } from '@oclif/core'; +import { isExitSignal, printError, printHeader, printSuccess, printWarning } from '../../utils/format.js'; +import { resolveSkillsVersion, type SkillsVersionSource } from '../../utils/skills-catalog.js'; +import { resolveSkillsDir, skillsCommonFlags } from '../../utils/skills-command.js'; +import { + describeModifiedSkill, + inspectSkillsDir, + readSkillsManifest, + type ModifiedSkill, +} from '../../utils/skills-install-state.js'; + +/** The status report, both faces. */ +export interface SkillsStatusReport { + ok: true; + command: 'status'; + dir: string; + /** The recorded version, or `null` when `os skills install` has not run here. */ + installedVersion: string | null; + expectedVersion: string; + expectedSource: SkillsVersionSource; + expectedFrom: string; + versionMatches: boolean; + missing: string[]; + modified: ModifiedSkill[]; + extra: string[]; + mismatch: boolean; +} + +export default class SkillsStatus extends Command { + static override description = + 'Report the installed skills catalog against the server\'s version: missing, modified and extra skills; --check exits 1 on a mismatch'; + + static override examples = [ + '$ os skills status', + '$ os skills status --target https://acme.example.com --check # exit 1 when the catalog is not the target\'s', + '$ os skills status --json', + ]; + + static override flags = { + ...skillsCommonFlags, + check: Flags.boolean({ + description: 'Exit 1 when the catalog is missing, at another version, or has missing or modified skills', + default: false, + }), + }; + + async run(): Promise { + const { flags } = await this.parse(SkillsStatus); + if (!flags.json) printHeader('Skills status'); + let report: SkillsStatusReport; + try { + const dir = resolveSkillsDir(flags.dir); + const manifest = readSkillsManifest(dir); + const expected = await resolveSkillsVersion({ + version: flags.version, + target: flags.target, + cliVersion: this.config.version, + }); + const { missing, modified, extra } = inspectSkillsDir(dir, manifest); + const installedVersion = manifest?.version ?? null; + const versionMatches = installedVersion === expected.version; + report = { + ok: true, + command: 'status', + dir, + installedVersion, + expectedVersion: expected.version, + expectedSource: expected.source, + expectedFrom: expected.from, + versionMatches, + missing, + modified, + extra, + mismatch: !versionMatches || missing.length > 0 || modified.length > 0, + }; + } catch (error) { + if (isExitSignal(error)) throw error; + if (flags.json) console.log(JSON.stringify({ ok: false, command: 'status', error: (error as Error).message }, null, 2)); + else printError((error as Error).message); + this.exit(1); + return; + } + + if (flags.json) { + console.log(JSON.stringify(report, null, 2)); + } else { + console.log(` Directory ${report.dir}`); + console.log(` Installed ${report.installedVersion ?? 'none (os skills install has not run here)'}`); + console.log(` Expected ${report.expectedVersion}, from ${report.expectedFrom}`); + if (report.missing.length > 0) console.log(` Missing ${report.missing.join(', ')}`); + for (const m of report.modified) console.log(` Modified ${describeModifiedSkill(m)}`); + if (report.extra.length > 0) console.log(` Extra ${report.extra.join(', ')} (not the catalog's; left alone)`); + if (!report.mismatch) { + printSuccess(`The catalog is @objectstack/skills ${report.expectedVersion}, unmodified.`); + } else if (report.installedVersion === null) { + printWarning(`No catalog is installed here. Run \`os skills install\` to install ${report.expectedVersion}.`); + } else if (!report.versionMatches) { + printWarning( + `The catalog is ${report.installedVersion}, not ${report.expectedVersion}. ` + + 'Run `os skills update` with the same --version or --target to move it.', + ); + } else { + printWarning('Catalog skills are missing or changed. `os skills update` restores them (with --force when files were changed).'); + } + } + if (flags.check && report.mismatch) this.exit(1); + } +} diff --git a/packages/cli/src/commands/skills/update.ts b/packages/cli/src/commands/skills/update.ts new file mode 100644 index 00000000000..f0921bd6039 --- /dev/null +++ b/packages/cli/src/commands/skills/update.ts @@ -0,0 +1,62 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * `os skills update` — move the catalog `os skills install` recorded to + * another version: the target's, by the same order `install` uses. + * + * Only skills the record names are written: each is replaced at the new + * version, and each the new version no longer ships is removed. ⛔ A skill + * directory the record does not name is never written, replaced or removed — + * a new catalog skill whose name one of them already uses is refused, naming + * it. A recorded skill changed locally is refused too, naming the files, + * unless `--force` discards the change. + */ + +import { Command, Flags } from '@oclif/core'; +import { isExitSignal, printError, printHeader, printSuccess } from '../../utils/format.js'; +import { runSkillsWrite, skillsCommonFlags, skillsWriteLines } from '../../utils/skills-command.js'; + +export default class SkillsUpdate extends Command { + static override description = + 'Update the skills catalog `os skills install` wrote to the server\'s version; your own skills are never touched'; + + static override examples = [ + '$ os skills update # this CLI\'s version', + '$ os skills update --target https://acme.example.com # the version a target environment runs', + '$ os skills update --version 18.6.0', + ]; + + static override flags = { + ...skillsCommonFlags, + force: Flags.boolean({ + description: 'Discard local changes to catalog skills instead of refusing', + default: false, + }), + }; + + async run(): Promise { + const { flags } = await this.parse(SkillsUpdate); + if (!flags.json) printHeader('Skills update'); + try { + const result = await runSkillsWrite({ + command: 'update', + version: flags.version, + target: flags.target, + dir: flags.dir, + force: flags.force, + cliVersion: this.config.version, + }); + if (flags.json) { + console.log(JSON.stringify(result, null, 2)); + return; + } + for (const line of skillsWriteLines(result)) console.log(` ${line}`); + printSuccess(`Updated the catalog from ${result.previousVersion} to @objectstack/skills ${result.version}.`); + } catch (error) { + if (isExitSignal(error)) throw error; + if (flags.json) console.log(JSON.stringify({ ok: false, command: 'update', error: (error as Error).message }, null, 2)); + else printError((error as Error).message); + this.exit(1); + } + } +} diff --git a/packages/cli/src/utils/skills-catalog.ts b/packages/cli/src/utils/skills-catalog.ts new file mode 100644 index 00000000000..662a868ac20 --- /dev/null +++ b/packages/cli/src/utils/skills-catalog.ts @@ -0,0 +1,332 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The published skills catalog, read for `os skills install | update | status`: + * which version to read ({@link resolveSkillsVersion}) and the catalog at that + * version ({@link fetchSkillsCatalog}). + * + * ## Which version + * + * In this order, and the answer always says which one it took: + * + * 1. `--version V`, an exact version; + * 2. `--target T`, the target environment's restriction profile — the same + * reader, with the same file-or-URL forms and the same refusals, as + * `os validate --target` (`loadRestrictionProfile`); its + * `versions.skills` is the version that environment runs; + * 3. this CLI's own version. `@objectstack/skills` and `@objectstack/cli` sit + * in one `fixed` group of `.changeset/config.json`, so every release + * publishes both at one version and the CLI's version names the catalog + * written for it. + * + * Only an exact version is read: a range or a dist-tag would install whatever + * the registry resolves it to today, which may be another major's catalog. + * + * ## Where the catalog comes from + * + * The `@objectstack/skills` tarball at exactly that version, from the npm + * registry this environment configures. It is fetched with `npm pack`, run in + * the current directory, so the registry, scope mapping, credentials and proxy + * the user's `.npmrc` files and `npm_config_*` variables name are the ones + * used — no registry URL or auth is re-derived here. ⛔ No third-party + * installer: the tarball is unpacked in process and only + * `package/dist/skills//**` is kept, for each `` that holds a + * `SKILL.md` (the layout `packages/skills/scripts/sync-catalog.mjs` publishes). + * A version the registry does not have is refused, naming it; a tarball that + * is not that package at that version, that carries a link or a path outside + * its own tree, or that holds no skill, is refused too. + */ + +import { execFile } from 'node:child_process'; +import { mkdtempSync, readdirSync, readFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { gunzipSync } from 'node:zlib'; + +import { loadRestrictionProfile } from './restriction-profile.js'; + +/** The package the catalog ships in. */ +export const SKILLS_PACKAGE = '@objectstack/skills'; + +/** Where a skill directory sits inside the package tarball. */ +const TARBALL_SKILLS_PREFIX = 'package/dist/skills/'; + +/** How long `npm pack` may take before the read is refused. */ +const NPM_PACK_TIMEOUT_MS = 120_000; + +/** An exact semver version: `MAJOR.MINOR.PATCH`, with an optional pre-release and build. */ +const EXACT_VERSION = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/; + +/** A skill directory name: one path segment, no leading dot. */ +const SKILL_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; + +/** Whether `value` names one release exactly (no range, no dist-tag). */ +export function isExactVersion(value: string): boolean { + return EXACT_VERSION.test(value); +} + +/** Where the version to install came from. */ +export type SkillsVersionSource = 'flag' | 'target' | 'cli'; + +export interface ResolvedSkillsVersion { + version: string; + source: SkillsVersionSource; + /** One phrase for the output: where the version was read. */ + from: string; +} + +/** + * The version to read, in the order the module header gives. Throws a plain + * `Error` whose message is the refusal: a `--version` that is not exact, a + * target whose profile cannot be read (the validate reader's own sentence), + * or a profile naming a skills version that is not exact. + */ +export async function resolveSkillsVersion(args: { + version?: string; + target?: string; + cliVersion: string; + cwd?: string; +}): Promise { + if (args.version !== undefined) { + const version = args.version.trim(); + if (!isExactVersion(version)) { + throw new Error( + `\`--version ${args.version}\` is not an exact version. Name one release, such as ${args.cliVersion}: ` + + 'a range or a tag would install whatever the registry resolves it to today.', + ); + } + return { version, source: 'flag', from: '--version' }; + } + if (args.target !== undefined) { + const { profile, source } = await loadRestrictionProfile(args.target, args.cwd); + const version = profile.versions.skills; + if (!isExactVersion(version)) { + throw new Error( + `--target ${args.target}: the restriction profile at ${source} names skills version '${version}', ` + + 'which is not an exact version, so no catalog can be chosen from it.', + ); + } + return { version, source: 'target', from: `the target's restriction profile (${source})` }; + } + return { version: args.cliVersion, source: 'cli', from: `this CLI's own version (@objectstack/cli ${args.cliVersion})` }; +} + +/** The catalog at one version: skill name → path inside the skill → bytes. */ +export interface SkillsCatalog { + version: string; + skills: Map>; +} + +/** One `npm pack` outcome: the tarball's bytes, or why there are none. */ +export type SkillsTarballFetch = + | { ok: true; tarball: Buffer } + | { ok: false; notFound: boolean; reason: string }; + +/** `npm pack`'s `--json` answer: an array of packed tarballs, or `{ error }`. */ +function npmPackError(stdout: string): { code?: string; summary?: string } | undefined { + try { + const parsed = JSON.parse(stdout) as { error?: { code?: unknown; summary?: unknown } }; + const error = parsed?.error; + if (!error) return undefined; + return { + code: typeof error.code === 'string' ? error.code : undefined, + summary: typeof error.summary === 'string' ? error.summary : undefined, + }; + } catch { + return undefined; + } +} + +/** + * Reads the package tarball from the configured registry. A seam: tests stand + * in for the registry here, so no test touches the network. + */ +export const skillsRegistry = { + fetchTarball(version: string, cwd: string = process.cwd()): Promise { + const spec = `${SKILLS_PACKAGE}@${version}`; + const destination = mkdtempSync(join(tmpdir(), 'os-skills-pack-')); + return new Promise((resolvePromise) => { + execFile( + 'npm', + ['pack', spec, '--pack-destination', destination, '--json'], + { + cwd, + timeout: NPM_PACK_TIMEOUT_MS, + maxBuffer: 16 * 1024 * 1024, + // `npm` is a `.cmd` shim on Windows, which only a shell resolves. + shell: process.platform === 'win32', + }, + (error, stdout, stderr) => { + try { + if (error) { + const code = (error as NodeJS.ErrnoException).code; + if (code === 'ENOENT') { + resolvePromise({ + ok: false, + notFound: false, + reason: '`npm` was not found on your PATH. The catalog is read with npm, which ships with Node.js.', + }); + return; + } + const npm = npmPackError(String(stdout)); + const notFound = npm?.code === 'ETARGET' || npm?.code === 'E404'; + const detail = npm?.summary + ?? String(stderr).split('\n').find((line) => line.trim().length > 0) + ?? error.message; + resolvePromise({ ok: false, notFound, reason: `npm pack ${spec}: ${detail}` }); + return; + } + const tarball = readdirSync(destination).find((name) => name.endsWith('.tgz')); + if (!tarball) { + resolvePromise({ ok: false, notFound: false, reason: `npm pack ${spec} wrote no tarball.` }); + return; + } + resolvePromise({ ok: true, tarball: readFileSync(join(destination, tarball)) }); + } finally { + rmSync(destination, { recursive: true, force: true }); + } + }, + ); + }); + }, +}; + +/** One member of a tar archive. */ +export interface TarEntry { + path: string; + /** The ustar type flag: `0` a file, `5` a directory, `2` a symlink, … */ + type: string; + data: Buffer; +} + +/** A NUL-terminated string field of a tar header. */ +function tarString(block: Buffer, offset: number, length: number): string { + const field = block.subarray(offset, offset + length); + const end = field.indexOf(0); + return field.subarray(0, end === -1 ? field.length : end).toString('utf8'); +} + +/** An octal number field of a tar header. */ +function tarOctal(block: Buffer, offset: number, length: number): number { + const text = tarString(block, offset, length).trim(); + if (text === '') return 0; + if (!/^[0-7]+$/.test(text)) throw new Error(`a tar header field reads '${text}', not an octal number`); + return Number.parseInt(text, 8); +} + +/** The `path` record of a pax extended header (` =\n` records). */ +function paxPath(data: Buffer): string | undefined { + let offset = 0; + let path: string | undefined; + while (offset < data.length) { + const space = data.indexOf(0x20, offset); + if (space === -1) break; + const length = Number.parseInt(data.subarray(offset, space).toString('ascii'), 10); + if (!Number.isFinite(length) || length <= 0) break; + const record = data.subarray(space + 1, offset + length - 1).toString('utf8'); + const equals = record.indexOf('='); + if (equals !== -1 && record.slice(0, equals) === 'path') path = record.slice(equals + 1); + offset += length; + } + return path; +} + +/** + * The members of a gzipped tar archive, as `npm pack` writes it: ustar headers, + * with long paths in the ustar prefix, a pax `path` record or a GNU long name. + * Throws on a header whose checksum does not match or an archive cut short. + */ +export function readTarGz(tgz: Buffer): TarEntry[] { + const tar = gunzipSync(tgz); + const entries: TarEntry[] = []; + let offset = 0; + let longPath: string | undefined; + while (offset + 512 <= tar.length) { + const header = tar.subarray(offset, offset + 512); + if (header.every((byte) => byte === 0)) break; + const stored = tarOctal(header, 148, 8); + let sum = 0; + for (let i = 0; i < 512; i++) sum += i >= 148 && i < 156 ? 0x20 : header[i]; + if (sum !== stored) throw new Error(`the tar header at byte ${offset} fails its checksum`); + const size = tarOctal(header, 124, 12); + const type = header[156] === 0 ? '0' : String.fromCharCode(header[156]); + const start = offset + 512; + if (start + size > tar.length) throw new Error('the archive ends inside a member'); + const data = tar.subarray(start, start + size); + offset = start + Math.ceil(size / 512) * 512; + if (type === 'x') { longPath = paxPath(data) ?? longPath; continue; } + if (type === 'L') { longPath = tarString(data, 0, data.length); continue; } + if (type === 'g') continue; + const name = tarString(header, 0, 100); + const prefix = tarString(header, 257, 6).startsWith('ustar') ? tarString(header, 345, 155) : ''; + entries.push({ path: longPath ?? (prefix ? `${prefix}/${name}` : name), type, data: Buffer.from(data) }); + longPath = undefined; + } + return entries; +} + +/** + * The catalog in a package tarball. Throws a plain `Error` naming what is + * wrong when the tarball is not `@objectstack/skills` at `version`, carries a + * link or a path that leaves its own tree under `dist/skills/`, or holds no + * skill. Files directly under `dist/skills/` (its README) are not a skill and + * are not kept. + */ +export function catalogFromTarball(tgz: Buffer, version: string): SkillsCatalog { + const refuse = (problem: string) => new Error(`The ${SKILLS_PACKAGE}@${version} tarball ${problem} Nothing was written.`); + let entries: TarEntry[]; + try { + entries = readTarGz(tgz); + } catch (error) { + throw refuse(`could not be read: ${(error as Error).message}.`); + } + const manifest = entries.find((entry) => entry.path === 'package/package.json'); + let declared: { name?: unknown; version?: unknown } = {}; + try { + declared = manifest ? JSON.parse(manifest.data.toString('utf8')) : {}; + } catch { /* reported below as not this package */ } + if (declared.name !== SKILLS_PACKAGE || declared.version !== version) { + throw refuse( + `declares ${typeof declared.name === 'string' ? declared.name : 'no name'}@` + + `${typeof declared.version === 'string' ? declared.version : 'no version'}, not ${SKILLS_PACKAGE}@${version}.`, + ); + } + const files = new Map>(); + for (const entry of entries) { + if (!entry.path.startsWith(TARBALL_SKILLS_PREFIX)) continue; + const parts = entry.path.slice(TARBALL_SKILLS_PREFIX.length).split('/').filter((part, i, all) => !(part === '' && i === all.length - 1)); + if (parts.some((part) => part === '' || part === '.' || part === '..')) { + throw refuse(`carries the path '${entry.path}', which leaves its own tree.`); + } + if (entry.type === '5') continue; + if (entry.type !== '0' && entry.type !== '7') { + throw refuse(`carries '${entry.path}' as tar type '${entry.type}'; the catalog holds regular files only.`); + } + if (parts.length < 2) continue; + const [skill, ...rest] = parts; + if (!SKILL_NAME.test(skill)) throw refuse(`carries a skill directory named '${skill}', which is not a directory name.`); + if (!files.has(skill)) files.set(skill, new Map()); + files.get(skill)!.set(rest.join('/'), entry.data); + } + const skills = new Map([...files].filter(([, skillFiles]) => skillFiles.has('SKILL.md')).sort(([a], [b]) => a.localeCompare(b))); + if (skills.size === 0) throw refuse('holds no skill (no dist/skills//SKILL.md).'); + return { version, skills }; +} + +/** + * The catalog at `version`, read from the configured registry. Throws a plain + * `Error` whose message is the refusal; a version the registry does not have + * is named. + */ +export async function fetchSkillsCatalog(version: string, cwd: string = process.cwd()): Promise { + const fetched = await skillsRegistry.fetchTarball(version, cwd); + if (!fetched.ok) { + throw new Error( + fetched.notFound + ? `${SKILLS_PACKAGE} ${version} is not published on the npm registry this environment uses (${fetched.reason}). ` + + 'Nothing was written.' + : `${SKILLS_PACKAGE} ${version} could not be read from the npm registry: ${fetched.reason} Nothing was written.`, + ); + } + return catalogFromTarball(fetched.tarball, version); +} diff --git a/packages/cli/src/utils/skills-command.ts b/packages/cli/src/utils/skills-command.ts new file mode 100644 index 00000000000..66b7caadbc8 --- /dev/null +++ b/packages/cli/src/utils/skills-command.ts @@ -0,0 +1,154 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The flags and the write path the three `os skills` commands share. Kept out + * of `src/commands/skills/`, where every module is a command. + */ + +import { isAbsolute, resolve } from 'node:path'; +import { Flags } from '@oclif/core'; + +import { fetchSkillsCatalog, resolveSkillsVersion, type ResolvedSkillsVersion } from './skills-catalog.js'; +import { + DEFAULT_SKILLS_DIR, + applySkillsWrite, + inspectSkillsDir, + planSkillsWrite, + readSkillsManifest, + describeModifiedSkill, + type SkillsWritePlan, +} from './skills-install-state.js'; + +/** `--version`, `--target`, `--dir` and `--json`, as all three commands spell them. */ +export const skillsCommonFlags = { + version: Flags.string({ + description: 'Exact @objectstack/skills version to use (default: the target\'s, then this CLI\'s own version)', + exclusive: ['target'], + }), + target: Flags.string({ + description: + 'Target environment whose skills version to use: its http(s) URL (its published restriction profile is read) ' + + 'or a restriction profile JSON file, the same forms as `os validate --target`', + exclusive: ['version'], + }), + dir: Flags.string({ + description: `The agent's skills directory (default: ${DEFAULT_SKILLS_DIR} under the current directory)`, + }), + json: Flags.boolean({ description: 'Output one JSON document on stdout' }), +}; + +/** The skills directory `--dir` names, absolute. */ +export function resolveSkillsDir(dir: string | undefined, cwd: string = process.cwd()): string { + const chosen = dir ?? DEFAULT_SKILLS_DIR; + return isAbsolute(chosen) ? chosen : resolve(cwd, chosen); +} + +/** One write's outcome, for both faces. */ +export interface SkillsWriteResult { + ok: true; + command: 'install' | 'update'; + dir: string; + version: string; + versionSource: ResolvedSkillsVersion['source']; + versionFrom: string; + previousVersion: string | null; + added: string[]; + replaced: string[]; + removed: string[]; + /** Same-named directories the record did not name that `install --force` replaced. */ + adopted: string[]; + /** Skill directories left alone because the record does not name them. */ + untouched: string[]; +} + +/** + * `install` or `update`: resolve the version, refuse what the command must not + * do (see each command's description), fetch the catalog and write it. Throws + * a plain `Error` whose message is the refusal; nothing is written before every + * refusal has been judged. + */ +export async function runSkillsWrite(args: { + command: 'install' | 'update'; + version?: string; + target?: string; + dir?: string; + force: boolean; + cliVersion: string; + cwd?: string; +}): Promise { + const cwd = args.cwd ?? process.cwd(); + const dir = resolveSkillsDir(args.dir, cwd); + const manifest = readSkillsManifest(dir); + + if (args.command === 'install' && manifest) { + throw new Error( + `${dir} already holds the catalog at ${manifest.version} (installed by \`os skills install\`). ` + + 'Run `os skills update` to move it to another version.', + ); + } + if (args.command === 'update' && !manifest) { + throw new Error( + `${dir} holds no catalog installed by \`os skills install\`, so there is nothing to update. ` + + 'Run `os skills install` first.', + ); + } + if (args.command === 'update' && manifest && !args.force) { + const local = inspectSkillsDir(dir, manifest).modified; + if (local.length > 0) { + throw new Error( + `Catalog skills in ${dir} were changed locally, and an update replaces them: ` + + `${local.map(describeModifiedSkill).join(' | ')}. Move your changes into a skill of your own, ` + + 'or pass --force to discard them.', + ); + } + } + + const resolved = await resolveSkillsVersion({ version: args.version, target: args.target, cliVersion: args.cliVersion, cwd }); + const catalog = await fetchSkillsCatalog(resolved.version, cwd); + const plan: SkillsWritePlan = planSkillsWrite(dir, catalog, manifest); + + if (plan.conflicts.length > 0 && !(args.command === 'install' && args.force)) { + const names = plan.conflicts.join(', '); + throw new Error( + args.command === 'install' + ? `${dir} already has skill directories this command did not install, with the names of catalog skills: ${names}. ` + + 'Remove them, or pass --force to replace them with the catalog\'s (for example a copy an earlier ' + + '`skills experimental_sync` made). Nothing was written.' + : `${resolved.version} adds catalog skills whose names a directory of yours already uses: ${names}. ` + + '`os skills update` never touches a skill it did not install: rename or remove yours, then update. Nothing was written.', + ); + } + + const before = inspectSkillsDir(dir, manifest); + applySkillsWrite(dir, catalog, plan); + return { + ok: true, + command: args.command, + dir, + version: resolved.version, + versionSource: resolved.source, + versionFrom: resolved.from, + previousVersion: manifest?.version ?? null, + added: plan.added, + replaced: plan.replaced, + removed: plan.dropped, + adopted: plan.conflicts, + untouched: before.extra.filter((name) => !plan.conflicts.includes(name)), + }; +} + +/** The text face of a write: what was written, from which version source, and what was left alone. */ +export function skillsWriteLines(result: SkillsWriteResult): string[] { + const lines = [ + `Version ${result.version}, from ${result.versionFrom}`, + `Directory ${result.dir}`, + ]; + if (result.previousVersion !== null) lines.push(`Previous ${result.previousVersion}`); + const list = (label: string, names: string[]) => { if (names.length > 0) lines.push(`${label} ${names.join(', ')}`); }; + list('Added ', result.added); + list('Replaced ', result.replaced); + list('Removed ', result.removed); + list('Adopted ', result.adopted); + list('Untouched', result.untouched); + return lines; +} diff --git a/packages/cli/src/utils/skills-install-state.ts b/packages/cli/src/utils/skills-install-state.ts new file mode 100644 index 00000000000..0b64350b7d4 --- /dev/null +++ b/packages/cli/src/utils/skills-install-state.ts @@ -0,0 +1,214 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * What `os skills install` wrote into an agent's skills directory, and how the + * directory compares with it — the record `update` and `status` read to tell + * the catalog's skills from the user's own. + * + * ## The record + * + * {@link SKILLS_MANIFEST_FILE}, beside the skills it describes: the package, + * the version, and every file of every catalog skill with its SHA-256. A skill + * directory the record does not name is the user's: ⛔ `update` never writes, + * replaces or removes one, and `install` replaces a same-named one only when + * told to (`--force`), naming it. + * + * ## The comparison ({@link inspectSkillsDir}) + * + * - `missing` — a recorded skill whose directory is gone; + * - `modified` — a recorded skill with a file changed, removed or added; + * - `extra` — a skill directory the record does not name (the user's own, + * reported and left alone). + */ + +import { createHash } from 'node:crypto'; +import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'; +import { dirname, join, relative, sep } from 'node:path'; + +import { SKILLS_PACKAGE, isExactVersion, type SkillsCatalog } from './skills-catalog.js'; + +/** The record's file name, inside the skills directory. */ +export const SKILLS_MANIFEST_FILE = '.objectstack-skills.json'; + +/** Where a Claude Code project keeps its skills, relative to the working directory. */ +export const DEFAULT_SKILLS_DIR = join('.claude', 'skills'); + +/** The record `install` writes and `update` rewrites. */ +export interface SkillsManifest { + package: typeof SKILLS_PACKAGE; + version: string; + /** Skill name → path inside the skill → `sha256` hex of its bytes. */ + skills: Record>; +} + +/** One recorded skill that no longer matches the record. */ +export interface ModifiedSkill { + skill: string; + /** Recorded files whose bytes differ. */ + changed: string[]; + /** Recorded files that are gone. */ + removed: string[]; + /** Files the record does not name. */ + added: string[]; +} + +export interface SkillsDirInspection { + missing: string[]; + modified: ModifiedSkill[]; + extra: string[]; +} + +function sha256(bytes: Buffer): string { + return createHash('sha256').update(bytes).digest('hex'); +} + +/** The record for a catalog, as `install` / `update` write it. */ +export function manifestForCatalog(catalog: SkillsCatalog): SkillsManifest { + const skills: Record> = {}; + for (const [name, files] of catalog.skills) { + skills[name] = Object.fromEntries([...files].sort(([a], [b]) => a.localeCompare(b)).map(([path, bytes]) => [path, sha256(bytes)])); + } + return { package: SKILLS_PACKAGE, version: catalog.version, skills }; +} + +/** + * The record in `dir`, or `null` when there is none. Throws a plain `Error` + * naming the file when it is there but is not a record this command wrote: + * reading half a record would let `update` touch skills it did not install. + */ +export function readSkillsManifest(dir: string): SkillsManifest | null { + const file = join(dir, SKILLS_MANIFEST_FILE); + if (!existsSync(file)) return null; + const refuse = (problem: string) => new Error( + `${file} ${problem} It is the record \`os skills install\` writes; remove it and run \`os skills install\` again.`, + ); + let raw: unknown; + try { + raw = JSON.parse(readFileSync(file, 'utf8')); + } catch (error) { + throw refuse(`is not JSON (${(error as Error).message}).`); + } + const record = raw as Partial | null; + if (!record || typeof record !== 'object' || record.package !== SKILLS_PACKAGE + || typeof record.version !== 'string' || !isExactVersion(record.version) + || !record.skills || typeof record.skills !== 'object' || Array.isArray(record.skills)) { + throw refuse(`does not record ${SKILLS_PACKAGE} at an exact version with its skills.`); + } + for (const [name, files] of Object.entries(record.skills)) { + const bad = !files || typeof files !== 'object' || Array.isArray(files) + || Object.entries(files).some(([path, hash]) => typeof hash !== 'string' || path.split('/').includes('..')) + || name.includes('/') || name.includes('\\') || name.startsWith('.'); + if (bad) throw refuse(`records the skill '${name}' in a shape it cannot read.`); + } + return record as SkillsManifest; +} + +/** Every file under `root`, as `/`-separated paths relative to it. */ +function listFiles(root: string): string[] { + const out: string[] = []; + for (const entry of readdirSync(root, { recursive: true, withFileTypes: true })) { + if (!entry.isFile() && !entry.isSymbolicLink()) continue; + out.push(relative(root, join(entry.parentPath, entry.name)).split(sep).join('/')); + } + return out.sort(); +} + +/** The skill directories in `dir`: every directory that is not hidden. */ +function skillDirectories(dir: string): string[] { + if (!existsSync(dir)) return []; + return readdirSync(dir, { withFileTypes: true }) + .filter((entry) => entry.isDirectory() && !entry.name.startsWith('.')) + .map((entry) => entry.name) + .sort(); +} + +/** How one recorded skill on disk differs from its record, or `undefined` when it matches. */ +function compareSkill(dir: string, skill: string, recorded: Record): ModifiedSkill | undefined { + const root = join(dir, skill); + const onDisk = new Set(listFiles(root)); + const changed: string[] = []; + const removed: string[] = []; + for (const [path, hash] of Object.entries(recorded)) { + if (!onDisk.has(path)) { removed.push(path); continue; } + if (sha256(readFileSync(join(root, path))) !== hash) changed.push(path); + } + const added = [...onDisk].filter((path) => !(path in recorded)); + if (changed.length + removed.length + added.length === 0) return undefined; + return { skill, changed: changed.sort(), removed: removed.sort(), added }; +} + +/** How `dir` compares with `manifest` (see the module header). With no record, every skill directory is extra. */ +export function inspectSkillsDir(dir: string, manifest: SkillsManifest | null): SkillsDirInspection { + const recorded = manifest?.skills ?? {}; + const missing: string[] = []; + const modified: ModifiedSkill[] = []; + for (const [skill, files] of Object.entries(recorded).sort(([a], [b]) => a.localeCompare(b))) { + const root = join(dir, skill); + if (!existsSync(root) || !statSync(root).isDirectory()) { missing.push(skill); continue; } + const drift = compareSkill(dir, skill, files); + if (drift) modified.push(drift); + } + const extra = skillDirectories(dir).filter((name) => !(name in recorded)); + return { missing, modified, extra }; +} + +/** What writing a catalog over `dir` would do. */ +export interface SkillsWritePlan { + /** Catalog skills written where no directory of that name was. */ + added: string[]; + /** Recorded skills rewritten at the new version. */ + replaced: string[]; + /** Recorded skills the new version no longer ships: removed. */ + dropped: string[]; + /** Directories the record does not name that share a catalog skill's name. */ + conflicts: string[]; +} + +/** The plan for writing `catalog` into `dir`, whose current record is `manifest`. */ +export function planSkillsWrite(dir: string, catalog: SkillsCatalog, manifest: SkillsManifest | null): SkillsWritePlan { + const recorded = manifest?.skills ?? {}; + const present = new Set(skillDirectories(dir)); + const added: string[] = []; + const replaced: string[] = []; + const conflicts: string[] = []; + for (const name of catalog.skills.keys()) { + if (name in recorded) replaced.push(name); + else if (present.has(name) || existsSync(join(dir, name))) conflicts.push(name); + else added.push(name); + } + const dropped = Object.keys(recorded).filter((name) => !catalog.skills.has(name)).sort(); + return { added, replaced, dropped, conflicts }; +} + +/** + * Write `catalog` into `dir` along `plan`: remove each dropped skill, replace + * each recorded one and each conflict (the caller decided those may go), add + * the rest, then write the record last. Only directories the plan names are + * touched. + */ +export function applySkillsWrite(dir: string, catalog: SkillsCatalog, plan: SkillsWritePlan): SkillsManifest { + mkdirSync(dir, { recursive: true }); + for (const name of plan.dropped) rmSync(join(dir, name), { recursive: true, force: true }); + for (const [name, files] of catalog.skills) { + const root = join(dir, name); + rmSync(root, { recursive: true, force: true }); + for (const [path, bytes] of files) { + const target = join(root, ...path.split('/')); + mkdirSync(dirname(target), { recursive: true }); + writeFileSync(target, bytes); + } + } + const manifest = manifestForCatalog(catalog); + writeFileSync(join(dir, SKILLS_MANIFEST_FILE), `${JSON.stringify(manifest, null, 2)}\n`); + return manifest; +} + +/** One line per modified skill, for the text face: what changed, was removed or was added. */ +export function describeModifiedSkill(m: ModifiedSkill): string { + const parts = [ + m.changed.length ? `changed ${m.changed.join(', ')}` : '', + m.removed.length ? `removed ${m.removed.join(', ')}` : '', + m.added.length ? `added ${m.added.join(', ')}` : '', + ].filter(Boolean); + return `${m.skill}: ${parts.join('; ')}`; +} From bec9bdc5cbbfc48f53639b86705d5258ded34808 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 00:08:12 +0000 Subject: [PATCH 2/4] feat(cli): os skills install, update and status at the server version The MCP open server names os skills install --version in its skills install line; docs and changeset. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzgNCAXyGfBQFZBwixH --- .changeset/34773-os-skills-install.md | 17 + content/docs/ai/connect-mcp.mdx | 11 +- content/docs/ai/skills.mdx | 20 +- content/docs/deployment/cli.mdx | 83 ++++ packages/cli/test/skills-commands.test.ts | 399 ++++++++++++++++++ packages/mcp/README.md | 7 +- .../initialize-selection-rule-34686.test.ts | 14 +- packages/mcp/src/mcp-server-runtime.ts | 9 +- 8 files changed, 547 insertions(+), 13 deletions(-) create mode 100644 .changeset/34773-os-skills-install.md create mode 100644 packages/cli/test/skills-commands.test.ts diff --git a/.changeset/34773-os-skills-install.md b/.changeset/34773-os-skills-install.md new file mode 100644 index 00000000000..0da327d7f0a --- /dev/null +++ b/.changeset/34773-os-skills-install.md @@ -0,0 +1,17 @@ +--- +'@objectstack/cli': patch +'@objectstack/mcp': patch +--- + +feat(cli): `os skills install | update | status` install, update and check the published skills catalog at the server's version, with or without a project + +Clause-②: yes (widening: a new published CLI command group, `os skills install | update | status`) +Metadata-protocol: none + +Nothing installed the published skills catalog except `create-objectstack`'s scaffold-time sync, so a user who only connected an MCP client had no way to install it, and a project had no command to refresh it after an upgrade. + +- **`os skills install`** copies `@objectstack/skills` at one version into the agent's skills directory (`.claude/skills/` under the current directory, or `--dir`), in an empty directory or in a project; no `package.json` is read or written. The version is `--version` (exact), else the target environment's (`--target`, a URL or a restriction profile file, read exactly as `os validate --target` reads it), else the CLI's own version (the two are released together); the output names which. The tarball is read with `npm pack` from the registry the environment configures, and only `dist/skills//` is copied. A version the registry does not publish is refused, naming it. What was written is recorded in `.objectstack-skills.json` beside the skills. +- **`os skills update`** moves the recorded catalog to another version: it replaces the catalog's skills, removes those the new version dropped, and never writes, replaces or removes a skill directory it did not install. A catalog skill changed locally is refused unless `--force`. +- **`os skills status`** reports the installed version against the expected one, plus missing, modified and extra skills; it exits `0`, or `1` on a mismatch with `--check`. All three take `--json`. + +`@objectstack/mcp`: the open server's `initialize` skills install line now names `os skills install --version ` (and its `npx -p @objectstack/cli@` form for a machine without the CLI) instead of `pnpm add -D @objectstack/skills@`, which needed a project. This supersedes, in the same release, the `pnpm add -D` command the entry introducing that line describes. diff --git a/content/docs/ai/connect-mcp.mdx b/content/docs/ai/connect-mcp.mdx index 65d130bfe83..486bae3cf60 100644 --- a/content/docs/ai/connect-mcp.mdx +++ b/content/docs/ai/connect-mcp.mdx @@ -301,9 +301,14 @@ such sentence. The instructions also name the published skills package and the version to install, which is the server's own version -(`Published skills: @objectstack/skills `, with -`pnpm add -D @objectstack/skills@`); see -[Skills](/docs/ai/skills) for syncing it into your agent. A deployment that sets +(`Published skills: @objectstack/skills `), with the command that +installs it into your agent's skills directory, with or without a project: +`os skills install --version `, or +`npx -p @objectstack/cli@ os skills install --version ` where +the CLI is not installed. If you only connected an MCP client and have no +project, run it in the directory your agent works in; it writes +`.claude/skills/` there (`--dir` names another). See +[Skills](/docs/ai/skills#installing-skills) for updating and checking it. A deployment that sets the MCP plugin's `instructions` option serves that text as written instead, and the local stdio server's instructions carry neither part. diff --git a/content/docs/ai/skills.mdx b/content/docs/ai/skills.mdx index 5289decb47f..73cc4dedb3e 100644 --- a/content/docs/ai/skills.mdx +++ b/content/docs/ai/skills.mdx @@ -26,7 +26,21 @@ See [Agents](/docs/ai/agents#you-extend-the-platform-with-skills-not-agents) for ## Installing skills -Skills ship as the npm package `@objectstack/skills`, released with the other `@objectstack/*` packages at one shared version. Install it at your installed `@objectstack/spec`'s version — the catalog's version is then your spec's — and copy it from `node_modules` into your agent's directory, the two steps `create-objectstack` runs when it scaffolds a project: +Skills ship as the npm package `@objectstack/skills`, released with the other `@objectstack/*` packages at one shared version. The CLI installs the catalog at the version your server runs into your agent's skills directory, with or without a project — no `package.json` is read or written: + +```bash +os skills install # this CLI's version: the catalog written for it +os skills install --target https://acme.example.com # the version a target environment runs +os skills install --version 18.5.0 # the version an MCP server's instructions name +``` + +The skills land as real files in `.claude/skills/` under the current directory (`--dir` names another agent's directory), beside a record of what was installed, `.objectstack-skills.json`. The catalog is read from the npm registry your environment configures; a version it does not publish is refused, naming it. + +**With no project.** If you only connected an MCP client, the server's `initialize` instructions name its version and the command, `os skills install --version `. Run it in the directory your agent works in; without the CLI installed, `npx -p @objectstack/cli@ os skills install --version ` does the same. + +**After an upgrade.** The catalog is versioned and updated as **one unit**, with ObjectStack itself. `os skills status` reports the installed version against the expected one (the same `--version` / `--target` / CLI order), plus catalog skills that are missing or modified and skill directories of your own (`--check` exits `1` on a mismatch, for CI). `os skills update` moves the catalog to the expected version: it replaces the catalog's skills, removes those the new version dropped, and never touches a skill it did not install. Commit `.claude/skills/` with the project. See the [CLI reference](/docs/deployment/cli#skills) for every flag. + +A project can also depend on the package and sync it from `node_modules` with the third-party skills CLI, the two steps `create-objectstack` runs when it scaffolds a project: ```bash pnpm add -D "@objectstack/skills@$(node -p "require('@objectstack/spec/package.json').version")" @@ -34,9 +48,7 @@ pnpm add -D "@objectstack/skills@$(node -p "require('@objectstack/spec/package.j npx skills@1.7.2 experimental_sync --agent claude-code --copy -y ``` -Add the package with the manager that installed the project: in a pnpm project, `npm install --save-dev` exits `1` with `npm error Cannot read properties of null (reading 'edgesOut')`. - -The skills land as real files in `.claude/skills/`; commit them with the project, and keep `--copy` — without it they are links into `node_modules`, which a clone does not have. Name your own runtime after `--agent` (`codex`, `cursor`, …). The catalog is versioned and updated as **one unit**, with ObjectStack itself: bump `@objectstack/skills` with the other `@objectstack/*` packages, then re-run the sync. The package is published from `18.0.0-next.0` on (there is no 17.x release); for what the sync writes, the versions, the one scaffolder that is an exception and the `next` channel, see the [AI Skills Reference](/docs/ai/skills-reference#installing-skills). +Add the package with the manager that installed the project: in a pnpm project, `npm install --save-dev` exits `1` with `npm error Cannot read properties of null (reading 'edgesOut')`. Keep `--copy` — without it the skills are links into `node_modules`, which a clone does not have — and name your own runtime after `--agent` (`codex`, `cursor`, …). To move such a project to `os skills`, run `os skills install --force`: it replaces the synced directories of the same names with the catalog's and records them. The package is published from `18.0.0-next.0` on (there is no 17.x release); for what the sync writes, the versions, the one scaffolder that is an exception and the `next` channel, see the [AI Skills Reference](/docs/ai/skills-reference#installing-skills). --- diff --git a/content/docs/deployment/cli.mdx b/content/docs/deployment/cli.mdx index 2b7dbac084b..454d9903d7b 100644 --- a/content/docs/deployment/cli.mdx +++ b/content/docs/deployment/cli.mdx @@ -3672,6 +3672,89 @@ the grant, use the environment's console: **Account → Connect an AI Assistant* | `-s, --server ` | `OS_CLOUD_URL` | Control-plane URL. Default `https://cloud.objectos.ai`, or the URL recorded by `os cloud login` | | `-t, --token ` | `OS_CLOUD_API_KEY` | Bearer token, used only to find the environment; `$OS_TOKEN` and `~/.objectstack/cloud.json` are the fallbacks | +### Skills + +The published skills catalog (`@objectstack/skills`, see [AI Skills](/docs/ai/skills)) +installed into, updated in and checked against your coding agent's skills +directory. All three work in an empty directory as well as in a project: no +`package.json` is read or written. + +| Command | Description | +|---------|-------------| +| `os skills install` | Copy the catalog at one version into the skills directory, and record what was written | +| `os skills update` | Move the recorded catalog to another version; skills it did not install are never touched | +| `os skills status` | Report the installed catalog against the expected version: missing, modified and extra skills | + +**Which version.** `--version ` (an exact version), else `--target ` — +the version the target environment runs, read from its restriction profile +exactly as [`os validate --target`](#os-validate) reads it (an environment's +`http(s)` URL, or a profile JSON file) — else this CLI's own version, which is +the catalog's: the two are released together. The output names which one was +used. A range or a tag is refused, and so is a version the registry does not +publish, naming it. + +**Where from.** The `@objectstack/skills` tarball at exactly that version, read +with `npm pack` from the npm registry your environment configures (your +`.npmrc` files and `npm_config_*` variables apply). Only its +`dist/skills//` directories are copied. + +**What is recorded.** `install` writes `.objectstack-skills.json` beside the +skills: the version and every file of every catalog skill with its hash. That +record is how `update` and `status` tell the catalog's skills from your own. + +#### `os skills install` + +```bash +os skills install # this CLI's version, into .claude/skills/ +os skills install --version 18.5.0 # the version an MCP server names +os skills install --target https://acme.example.com # the version a target environment runs +os skills install --dir .agents/skills # another agent's skills directory +``` + +A directory that already holds a recorded catalog is refused, naming +`os skills update`. A skill directory the record does not name but which shares +a catalog skill's name (for example one an earlier `skills experimental_sync` +copied) is refused, naming it; `--force` replaces it with the catalog's. + +#### `os skills update` + +```bash +os skills update # this CLI's version +os skills update --target https://acme.example.com # the version a target environment runs +os skills update --version 18.6.0 +``` + +Replaces each recorded skill at the new version and removes each one the new +version no longer ships. A skill directory the record does not name is never +written, replaced or removed: a new catalog skill whose name one of yours +already uses is refused, naming it. A recorded skill you changed is refused, +naming the files; `--force` discards the change. With no recorded catalog the +command refuses, naming `os skills install`. + +#### `os skills status` + +```bash +os skills status +os skills status --target https://acme.example.com --check # exit 1 when the catalog is not the target's +os skills status --json +``` + +Reports the installed and the expected version (resolved in the order above), +`missing` (recorded skills whose directory is gone), `modified` (recorded skills +with a file changed, removed or added) and `extra` (skill directories the record +does not name — yours, listed and never judged). The registry is not read. A +mismatch is no recorded catalog, another version, or any missing or modified +skill: the command exits `0` regardless, and `1` on a mismatch with `--check`. + +| Flag | Commands | Purpose | +|---|---|---| +| `--version ` | all three | Exact catalog version (not with `--target`) | +| `--target ` | all three | Target environment URL or restriction profile file whose skills version to use | +| `--dir ` | all three | The skills directory (default `.claude/skills/` under the current directory) | +| `--json` | all three | One JSON document on stdout | +| `--force` | `install`, `update` | `install`: replace same-named directories it did not install. `update`: discard local changes to catalog skills | +| `--check` | `status` | Exit `1` on a mismatch | + ### Packages The two commands that move a compiled app onto a platform. They target diff --git a/packages/cli/test/skills-commands.test.ts b/packages/cli/test/skills-commands.test.ts new file mode 100644 index 00000000000..6b966d5dbf7 --- /dev/null +++ b/packages/cli/test/skills-commands.test.ts @@ -0,0 +1,399 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * `os skills install | update | status` against a stubbed registry and a + * stubbed target environment — no network. + * + * The commands run for real, in an empty temporary directory with no + * `package.json`. Two seams are replaced: `skillsRegistry.fetchTarball` is the + * npm registry (it answers tarballs this file builds, or "not published"), and + * `fetch` is the target environment's published restriction profile, read by + * the same reader `os validate --target` uses. + */ + +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { gzipSync } from 'node:zlib'; +import { Config } from '@oclif/core'; + +const { default: SkillsInstall } = await import('../src/commands/skills/install.js'); +const { default: SkillsUpdate } = await import('../src/commands/skills/update.js'); +const { default: SkillsStatus } = await import('../src/commands/skills/status.js'); +const { skillsRegistry, catalogFromTarball, resolveSkillsVersion } = await import('../src/utils/skills-catalog.js'); +const { SKILLS_MANIFEST_FILE } = await import('../src/utils/skills-install-state.js'); + +const PKG = dirname(dirname(fileURLToPath(import.meta.url))); +// The oclif config is loaded once, here: a clocked test window measures the commands, never this load. +const CONFIG = await Config.load(PKG); +const CLI_VERSION = (JSON.parse(readFileSync(join(PKG, 'package.json'), 'utf8')) as { version: string }).version; +const SERVER = 'https://acme.example.test'; +const PROFILE_URL = `${SERVER}/api/v1/discovery/restriction-profile`; + +// ─── a tarball, as `npm pack` writes one ───────────────────────────── + +type TarMember = { path: string; data?: string; type?: string }; + +function tarHeader(path: string, size: number, type: string): Buffer { + const header = Buffer.alloc(512); + let name = path; + let prefix = ''; + if (Buffer.byteLength(path) > 100) { + const cut = path.lastIndexOf('/', 155); + prefix = path.slice(0, cut); + name = path.slice(cut + 1); + } + header.write(name, 0, 100, 'utf8'); + header.write('0000644\0', 100); + header.write('0000000\0', 108); + header.write('0000000\0', 116); + header.write(`${size.toString(8).padStart(11, '0')}\0`, 124); + header.write('00000000000\0', 136); + header.write(' ', 148); + header.write(type, 156); + header.write('ustar\0', 257); + header.write('00', 263); + header.write(prefix, 345, 155, 'utf8'); + let sum = 0; + for (const byte of header) sum += byte; + header.write(`${sum.toString(8).padStart(6, '0')}\0 `, 148); + return header; +} + +function tarGz(members: TarMember[]): Buffer { + const blocks: Buffer[] = []; + for (const member of members) { + const data = Buffer.from(member.data ?? '', 'utf8'); + blocks.push(tarHeader(member.path, data.length, member.type ?? '0'), data, Buffer.alloc((512 - (data.length % 512)) % 512)); + } + blocks.push(Buffer.alloc(1024)); + return gzipSync(Buffer.concat(blocks)); +} + +/** A catalog: skill name → path → content. */ +type Catalog = Record>; + +function skillsTarball(version: string, catalog: Catalog, extra: TarMember[] = []): Buffer { + return tarGz([ + { path: 'package/package.json', data: JSON.stringify({ name: '@objectstack/skills', version }) }, + { path: 'package/README.md', data: 'readme' }, + { path: 'package/dist/skills/README.md', data: 'catalog readme, not a skill' }, + ...Object.entries(catalog).flatMap(([skill, files]) => + Object.entries(files).map(([path, data]) => ({ path: `package/dist/skills/${skill}/${path}`, data }))), + ...extra, + ]); +} + +const V1 = '18.5.0'; +const V2 = '18.6.0'; +const CATALOG_V1: Catalog = { + 'objectstack-data': { 'SKILL.md': 'data v1', 'rules/naming.md': 'snake_case v1' }, + 'objectstack-query': { 'SKILL.md': 'query v1' }, + 'objectstack-legacy': { 'SKILL.md': 'legacy v1' }, +}; +const CATALOG_V2: Catalog = { + 'objectstack-data': { 'SKILL.md': 'data v2', 'rules/naming.md': 'snake_case v2' }, + 'objectstack-query': { 'SKILL.md': 'query v2' }, + 'objectstack-ask': { 'SKILL.md': 'ask v2' }, +}; + +/** The registry: these versions are published, every other one is not. */ +function stubRegistry(published: Record): string[] { + const asked: string[] = []; + vi.spyOn(skillsRegistry, 'fetchTarball').mockImplementation(async (version: string) => { + asked.push(version); + const catalog = published[version]; + if (!catalog) { + return { ok: false, notFound: true, reason: `npm pack @objectstack/skills@${version}: No matching version found for @objectstack/skills@${version}.` }; + } + return { ok: true, tarball: skillsTarball(version, catalog) }; + }); + return asked; +} + +/** The target environment: its published restriction profile names this skills version. */ +const server = { skills: V1 }; +function stubServer(): string[] { + const asked: string[] = []; + vi.stubGlobal('fetch', vi.fn(async (input: string) => { + const url = String(input); + asked.push(url); + if (url !== PROFILE_URL) return new Response('{}', { status: 404, headers: { 'content-type': 'application/json' } }); + const data = { + allowCode: false, + allowSandboxedJs: true, + allowScheduledAutomation: false, + allowedFlowNodeTypes: ['start', 'end'], + versions: { spec: server.skills, skills: server.skills }, + }; + return new Response(JSON.stringify({ success: true, data }), { status: 200, headers: { 'content-type': 'application/json' } }); + })); + return asked; +} + +describe('os skills', () => { + let work = ''; + const prevCwd = process.cwd(); + let output: string[] = []; + + beforeEach(() => { + work = mkdtempSync(join(tmpdir(), 'os-skills-34773-')); + process.chdir(work); + server.skills = V1; + output = []; + const record = (...args: unknown[]) => { output.push(args.map(String).join(' ').replace(/\u001b\[[0-9;]*m/g, '')); }; + vi.spyOn(console, 'log').mockImplementation(record); + vi.spyOn(console, 'error').mockImplementation(record); + }); + + afterEach(() => { + process.chdir(prevCwd); + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + rmSync(work, { recursive: true, force: true }); + }); + + async function run(command: { run(argv: string[], opts?: Config): Promise }, argv: string[]): Promise { + try { + await command.run(argv, CONFIG); + return 0; + } catch (err: any) { + const exit = err?.oclif?.exit ?? err?.exitCode; + if (exit === undefined) throw err; + return exit; + } + } + + const skillsDir = () => join(work, '.claude', 'skills'); + const read = (...parts: string[]) => readFileSync(join(skillsDir(), ...parts), 'utf8'); + const manifest = () => JSON.parse(read(SKILLS_MANIFEST_FILE)); + const json = () => JSON.parse(output.join('\n')); + const text = () => output.join('\n'); + + it('Done when: in an empty directory, installs the catalog a running server runs, and status reports a mismatch after the server is upgraded', async () => { + stubRegistry({ [V1]: CATALOG_V1, [V2]: CATALOG_V2 }); + stubServer(); + expect(existsSync(join(work, 'package.json'))).toBe(false); + + expect(await run(SkillsInstall, ['--target', SERVER])).toBe(0); + expect(read('objectstack-data', 'SKILL.md')).toBe('data v1'); + expect(manifest().version).toBe(V1); + expect(text()).toContain(`Version ${V1}, from the target's restriction profile (${PROFILE_URL})`); + + output = []; + expect(await run(SkillsStatus, ['--target', SERVER, '--check'])).toBe(0); + + server.skills = V2; + output = []; + expect(await run(SkillsStatus, ['--target', SERVER, '--check', '--json'])).toBe(1); + expect(json()).toMatchObject({ installedVersion: V1, expectedVersion: V2, expectedSource: 'target', versionMatches: false, mismatch: true }); + expect(existsSync(join(work, 'package.json'))).toBe(false); + }); + + it('install into an empty directory: the catalog\'s skills land, the README beside them does not, and the record names the version and every file', async () => { + stubRegistry({ [V1]: CATALOG_V1 }); + expect(await run(SkillsInstall, ['--version', V1, '--json'])).toBe(0); + expect(read('objectstack-data', 'rules', 'naming.md')).toBe('snake_case v1'); + expect(read('objectstack-query', 'SKILL.md')).toBe('query v1'); + expect(existsSync(join(skillsDir(), 'README.md'))).toBe(false); + const record = manifest(); + expect(record.package).toBe('@objectstack/skills'); + expect(record.version).toBe(V1); + expect(Object.keys(record.skills).sort()).toEqual(['objectstack-data', 'objectstack-legacy', 'objectstack-query']); + expect(Object.keys(record.skills['objectstack-data']).sort()).toEqual(['SKILL.md', 'rules/naming.md']); + expect(json()).toMatchObject({ ok: true, command: 'install', version: V1, versionSource: 'flag', added: ['objectstack-data', 'objectstack-legacy', 'objectstack-query'] }); + }); + + it('--dir installs into another directory', async () => { + stubRegistry({ [V1]: CATALOG_V1 }); + expect(await run(SkillsInstall, ['--version', V1, '--dir', 'agents/skills'])).toBe(0); + expect(readFileSync(join(work, 'agents', 'skills', 'objectstack-query', 'SKILL.md'), 'utf8')).toBe('query v1'); + expect(existsSync(skillsDir())).toBe(false); + }); + + it('version order: --version, then the target, then this CLI\'s own version, and the output says which', async () => { + stubServer(); + expect(await resolveSkillsVersion({ version: V2, cliVersion: CLI_VERSION })).toMatchObject({ version: V2, source: 'flag' }); + expect(await resolveSkillsVersion({ target: SERVER, cliVersion: CLI_VERSION })).toMatchObject({ version: V1, source: 'target' }); + expect(await resolveSkillsVersion({ cliVersion: CLI_VERSION })).toMatchObject({ version: CLI_VERSION, source: 'cli' }); + + const asked = stubRegistry({ [CLI_VERSION]: CATALOG_V1 }); + expect(await run(SkillsInstall, [])).toBe(0); + expect(asked).toEqual([CLI_VERSION]); + expect(text()).toContain(`from this CLI's own version (@objectstack/cli ${CLI_VERSION})`); + }); + + it('a target profile file is read the way `os validate --target` reads it', async () => { + const file = join(work, 'profile.json'); + writeFileSync(file, JSON.stringify({ allowCode: true, allowSandboxedJs: true, allowScheduledAutomation: true, allowedFlowNodeTypes: [], versions: { spec: V2, skills: V2 } })); + expect(await resolveSkillsVersion({ target: 'profile.json', cliVersion: CLI_VERSION, cwd: work })).toMatchObject({ version: V2, source: 'target' }); + }); + + it('--version and --target together are refused', async () => { + const asked = stubRegistry({ [V1]: CATALOG_V1 }); + expect(await run(SkillsInstall, ['--version', V1, '--target', SERVER])).not.toBe(0); + expect(asked).toEqual([]); + }); + + it('a version the registry does not have is refused, naming it, and nothing is written', async () => { + stubRegistry({ [V1]: CATALOG_V1 }); + expect(await run(SkillsInstall, ['--version', '99.0.0'])).toBe(1); + expect(text()).toContain('@objectstack/skills 99.0.0 is not published on the npm registry this environment uses'); + expect(existsSync(skillsDir())).toBe(false); + }); + + it('a version that is not exact is refused before the registry is asked', async () => { + const asked = stubRegistry({ [V1]: CATALOG_V1 }); + expect(await run(SkillsInstall, ['--version', '^18.5.0'])).toBe(1); + expect(text()).toContain('is not an exact version'); + expect(asked).toEqual([]); + }); + + it('install over a recorded catalog is refused, naming update', async () => { + stubRegistry({ [V1]: CATALOG_V1 }); + expect(await run(SkillsInstall, ['--version', V1])).toBe(0); + output = []; + expect(await run(SkillsInstall, ['--version', V1])).toBe(1); + expect(text()).toContain('Run `os skills update`'); + }); + + it('install refuses a same-named directory it did not install, and --force adopts it', async () => { + stubRegistry({ [V1]: CATALOG_V1 }); + mkdirSync(join(skillsDir(), 'objectstack-data'), { recursive: true }); + writeFileSync(join(skillsDir(), 'objectstack-data', 'SKILL.md'), 'an earlier sync'); + expect(await run(SkillsInstall, ['--version', V1])).toBe(1); + expect(text()).toContain('objectstack-data'); + expect(read('objectstack-data', 'SKILL.md')).toBe('an earlier sync'); + expect(existsSync(join(skillsDir(), SKILLS_MANIFEST_FILE))).toBe(false); + + output = []; + expect(await run(SkillsInstall, ['--version', V1, '--force', '--json'])).toBe(0); + expect(read('objectstack-data', 'SKILL.md')).toBe('data v1'); + expect(json().adopted).toEqual(['objectstack-data']); + }); + + it('update replaces the catalog\'s skills, removes the ones the new version dropped, and leaves the user\'s own skill untouched', async () => { + stubRegistry({ [V1]: CATALOG_V1, [V2]: CATALOG_V2 }); + mkdirSync(join(skillsDir(), 'my-own'), { recursive: true }); + writeFileSync(join(skillsDir(), 'my-own', 'SKILL.md'), 'mine'); + expect(await run(SkillsInstall, ['--version', V1])).toBe(0); + + output = []; + expect(await run(SkillsUpdate, ['--version', V2, '--json'])).toBe(0); + expect(read('objectstack-data', 'SKILL.md')).toBe('data v2'); + expect(read('objectstack-ask', 'SKILL.md')).toBe('ask v2'); + expect(existsSync(join(skillsDir(), 'objectstack-legacy'))).toBe(false); + expect(read('my-own', 'SKILL.md')).toBe('mine'); + expect(manifest().version).toBe(V2); + expect(Object.keys(manifest().skills)).not.toContain('my-own'); + expect(json()).toMatchObject({ + previousVersion: V1, version: V2, added: ['objectstack-ask'], replaced: ['objectstack-data', 'objectstack-query'], + removed: ['objectstack-legacy'], untouched: ['my-own'], + }); + }); + + it('update never touches a directory it did not install: a new catalog skill that collides with one is refused', async () => { + stubRegistry({ [V1]: CATALOG_V1, [V2]: CATALOG_V2 }); + expect(await run(SkillsInstall, ['--version', V1])).toBe(0); + mkdirSync(join(skillsDir(), 'objectstack-ask'), { recursive: true }); + writeFileSync(join(skillsDir(), 'objectstack-ask', 'SKILL.md'), 'mine, same name'); + output = []; + expect(await run(SkillsUpdate, ['--version', V2, '--force'])).toBe(1); + expect(text()).toContain('never touches a skill it did not install'); + expect(read('objectstack-ask', 'SKILL.md')).toBe('mine, same name'); + expect(read('objectstack-data', 'SKILL.md')).toBe('data v1'); + }); + + it('update refuses to discard a local change to a catalog skill unless --force', async () => { + stubRegistry({ [V1]: CATALOG_V1, [V2]: CATALOG_V2 }); + expect(await run(SkillsInstall, ['--version', V1])).toBe(0); + writeFileSync(join(skillsDir(), 'objectstack-data', 'SKILL.md'), 'edited'); + output = []; + expect(await run(SkillsUpdate, ['--version', V2])).toBe(1); + expect(text()).toContain('objectstack-data: changed SKILL.md'); + expect(read('objectstack-data', 'SKILL.md')).toBe('edited'); + expect(await run(SkillsUpdate, ['--version', V2, '--force'])).toBe(0); + expect(read('objectstack-data', 'SKILL.md')).toBe('data v2'); + }); + + it('update with no recorded catalog is refused, naming install', async () => { + stubRegistry({ [V1]: CATALOG_V1 }); + expect(await run(SkillsUpdate, ['--version', V1])).toBe(1); + expect(text()).toContain('Run `os skills install` first'); + }); + + it('status: a match exits 0 with and without --check', async () => { + stubRegistry({ [V1]: CATALOG_V1 }); + expect(await run(SkillsInstall, ['--version', V1])).toBe(0); + output = []; + expect(await run(SkillsStatus, ['--version', V1, '--check', '--json'])).toBe(0); + expect(json()).toMatchObject({ installedVersion: V1, expectedVersion: V1, versionMatches: true, missing: [], modified: [], extra: [], mismatch: false }); + }); + + it('status: a version mismatch exits 0 by default and 1 with --check', async () => { + stubRegistry({ [V1]: CATALOG_V1 }); + expect(await run(SkillsInstall, ['--version', V1])).toBe(0); + output = []; + expect(await run(SkillsStatus, ['--version', V2])).toBe(0); + expect(text()).toContain(`The catalog is ${V1}, not ${V2}`); + expect(await run(SkillsStatus, ['--version', V2, '--check'])).toBe(1); + }); + + it('status: missing, modified and extra skills; only missing and modified are a mismatch', async () => { + stubRegistry({ [V1]: CATALOG_V1 }); + expect(await run(SkillsInstall, ['--version', V1])).toBe(0); + mkdirSync(join(skillsDir(), 'my-own')); + writeFileSync(join(skillsDir(), 'my-own', 'SKILL.md'), 'mine'); + output = []; + expect(await run(SkillsStatus, ['--version', V1, '--check', '--json'])).toBe(0); + expect(json()).toMatchObject({ extra: ['my-own'], mismatch: false }); + + rmSync(join(skillsDir(), 'objectstack-legacy'), { recursive: true }); + writeFileSync(join(skillsDir(), 'objectstack-data', 'SKILL.md'), 'edited'); + rmSync(join(skillsDir(), 'objectstack-data', 'rules', 'naming.md')); + writeFileSync(join(skillsDir(), 'objectstack-query', 'notes.md'), 'added'); + output = []; + expect(await run(SkillsStatus, ['--version', V1, '--check', '--json'])).toBe(1); + expect(json()).toMatchObject({ + versionMatches: true, + missing: ['objectstack-legacy'], + modified: [ + { skill: 'objectstack-data', changed: ['SKILL.md'], removed: ['rules/naming.md'], added: [] }, + { skill: 'objectstack-query', changed: [], removed: [], added: ['notes.md'] }, + ], + extra: ['my-own'], + mismatch: true, + }); + }); + + it('status with nothing installed is a mismatch under --check', async () => { + expect(await run(SkillsStatus, ['--version', V1, '--check', '--json'])).toBe(1); + expect(json()).toMatchObject({ installedVersion: null, mismatch: true }); + }); +}); + +describe('the catalog in a tarball', () => { + it('keeps only dist/skills//** of the skills that carry a SKILL.md, including a long path', () => { + const long = `references/${'d'.repeat(60)}/${'e'.repeat(40)}.md`; + const catalog = catalogFromTarball(skillsTarball(V1, { a: { 'SKILL.md': 'a', [long]: 'deep' } }, [ + { path: 'package/dist/skills/not-a-skill/notes.md', data: 'no SKILL.md' }, + ]), V1); + expect([...catalog.skills.keys()]).toEqual(['a']); + expect(catalog.skills.get('a')!.get(long)!.toString()).toBe('deep'); + }); + + it('refuses a tarball that is another version', () => { + expect(() => catalogFromTarball(skillsTarball(V2, CATALOG_V2), V1)).toThrow(/declares @objectstack\/skills@18\.6\.0, not @objectstack\/skills@18\.5\.0/); + }); + + it('refuses a link and a path that leaves its tree', () => { + expect(() => catalogFromTarball(skillsTarball(V1, CATALOG_V1, [{ path: 'package/dist/skills/a/link', type: '2' }]), V1)).toThrow(/regular files only/); + expect(() => catalogFromTarball(skillsTarball(V1, CATALOG_V1, [{ path: 'package/dist/skills/a/../../x', data: 'x' }]), V1)).toThrow(/leaves its own tree/); + }); + + it('refuses a catalog with no skill', () => { + expect(() => catalogFromTarball(skillsTarball(V1, {}), V1)).toThrow(/holds no skill/); + }); +}); diff --git a/packages/mcp/README.md b/packages/mcp/README.md index 25aae1ade9d..03513239b36 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -85,8 +85,11 @@ grant, then two parts: and no candidates falls back to the object tools and says the answer is not from a governed metric. A grant without `data:read` gets no such sentence. - **The skills install line**: `Published skills: @objectstack/skills ` - and its `pnpm add -D` command, at this package's own version (the two are - released together), never the `version` option. + and the command that installs it into the agent's skills directory with or + without a project, `os skills install --version ` (with its + `npx -p @objectstack/cli@` form for a machine without the CLI), at + this package's own version (the packages are released together), never the + `version` option. The stdio server's instructions are fixed when it is constructed, before its tools are bridged, and carry neither part. diff --git a/packages/mcp/src/initialize-selection-rule-34686.test.ts b/packages/mcp/src/initialize-selection-rule-34686.test.ts index cf33e7df170..a6a91b3a1d7 100644 --- a/packages/mcp/src/initialize-selection-rule-34686.test.ts +++ b/packages/mcp/src/initialize-selection-rule-34686.test.ts @@ -11,7 +11,8 @@ * bridge that defines no description for one of the pair get no rule — each * pinned beside its `tools/list` control. * - The install line names `@objectstack/skills` at this package's own - * version (one `fixed` changeset group), for every grant. + * version (one `fixed` changeset group), for every grant, and the CLI + * command that installs it with or without a project (#34773). * - Host-injected text and the runtime's configured text are whole answers * their author owns: nothing is appended to either. */ @@ -159,10 +160,19 @@ describe('[#34686] initialize instructions — the skills install line', () => { for (const o of [{}, { grantedScopes: [MCP_OAUTH_SCOPE_DATA_READ] }, { grantedScopes: [MCP_OAUTH_SCOPE_DATA_WRITE] }] as Opts[]) { const text = await instructionsOf(runtime, makeBridge(), o); expect(text).toContain(`Published skills: @objectstack/skills ${OWN_VERSION}`); - expect(text).toContain(`@objectstack/skills@${OWN_VERSION}`); expect(text).not.toContain('0.0.1-operator'); } }); + + // [#34773] The install is the CLI's own command, at that version, which needs + // no project: a client that only connected over MCP can follow it in an empty + // directory. The npx form is for a machine without the CLI installed. + it('names `os skills install --version` at that version, and no project-only install', async () => { + const text = await instructionsOf(runtime, makeBridge()); + expect(text).toContain(`os skills install --version ${OWN_VERSION}`); + expect(text).toContain(`npx -p @objectstack/cli@${OWN_VERSION} os skills install --version ${OWN_VERSION}`); + expect(text).not.toContain('pnpm add'); + }); }); describe('[#34686] initialize instructions — host and configured texts are left whole', () => { diff --git a/packages/mcp/src/mcp-server-runtime.ts b/packages/mcp/src/mcp-server-runtime.ts index c11a91bff90..72e32b481dc 100644 --- a/packages/mcp/src/mcp-server-runtime.ts +++ b/packages/mcp/src/mcp-server-runtime.ts @@ -1835,12 +1835,17 @@ const DATASET_SELECTION_RULE = * override, not a package version. No line when the manifest cannot be read * (`PACKAGE_VERSION` undefined), since an unversioned install takes the * registry's `latest`, which may be another major's catalog. + * [#34773] The install is `os skills install --version`, the CLI's command + * that needs no project, so a client that only connected over MCP can follow + * it in an empty directory; the `npx -p @objectstack/cli@VERSION` form is for + * a machine without the CLI. The CLI is in the same `fixed` group. */ function skillsInstallLine(version: string | undefined): string | undefined { if (!version) return undefined; return `Published skills: @objectstack/skills ${version}. To give a coding agent the ObjectStack procedures, ` - + `install that version in the project (pnpm add -D @objectstack/skills@${version}) and follow the package ` - + 'README to sync the skills into the agent\'s skills directory.'; + + `install that version into the agent's skills directory with the ObjectStack CLI, with or without a project: ` + + `os skills install --version ${version} (where the CLI is not installed: ` + + `npx -p @objectstack/cli@${version} os skills install --version ${version}).`; } /** From e5b66d7fc978f031521b95abe4ec42c5d9b7097d Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 01:51:58 +0000 Subject: [PATCH 3/4] test(cli): pins for skills paths, records and the Windows npm pack call The npm pack invocation is built by npmPackInvocation, behaviour unchanged. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzgNCAXyGfBQFZBwixH --- packages/cli/src/utils/skills-catalog.ts | 31 +++++++---- packages/cli/test/skills-commands.test.ts | 65 ++++++++++++++++++++++- 2 files changed, 85 insertions(+), 11 deletions(-) diff --git a/packages/cli/src/utils/skills-catalog.ts b/packages/cli/src/utils/skills-catalog.ts index 662a868ac20..d46ac97091d 100644 --- a/packages/cli/src/utils/skills-catalog.ts +++ b/packages/cli/src/utils/skills-catalog.ts @@ -141,21 +141,34 @@ function npmPackError(stdout: string): { code?: string; summary?: string } | und * Reads the package tarball from the configured registry. A seam: tests stand * in for the registry here, so no test touches the network. */ +/** + * The `npm pack` invocation for one spec into `destination`. On Windows `npm` + * is a `.cmd` shim, which only a shell resolves, and under `shell: true` Node + * joins the arguments unquoted, so a path argument is quoted there. + */ +export function npmPackInvocation(spec: string, destination: string, cwd: string, platform: NodeJS.Platform = process.platform): { + command: string; + args: string[]; + options: { cwd: string; timeout: number; maxBuffer: number; shell: boolean }; +} { + const shell = platform === 'win32'; + return { + command: 'npm', + args: ['pack', spec, '--pack-destination', destination, '--json'], + options: { cwd, timeout: NPM_PACK_TIMEOUT_MS, maxBuffer: 16 * 1024 * 1024, shell }, + }; +} + export const skillsRegistry = { fetchTarball(version: string, cwd: string = process.cwd()): Promise { const spec = `${SKILLS_PACKAGE}@${version}`; const destination = mkdtempSync(join(tmpdir(), 'os-skills-pack-')); + const invocation = npmPackInvocation(spec, destination, cwd); return new Promise((resolvePromise) => { execFile( - 'npm', - ['pack', spec, '--pack-destination', destination, '--json'], - { - cwd, - timeout: NPM_PACK_TIMEOUT_MS, - maxBuffer: 16 * 1024 * 1024, - // `npm` is a `.cmd` shim on Windows, which only a shell resolves. - shell: process.platform === 'win32', - }, + invocation.command, + invocation.args, + invocation.options, (error, stdout, stderr) => { try { if (error) { diff --git a/packages/cli/test/skills-commands.test.ts b/packages/cli/test/skills-commands.test.ts index 6b966d5dbf7..f856bb1e4d9 100644 --- a/packages/cli/test/skills-commands.test.ts +++ b/packages/cli/test/skills-commands.test.ts @@ -22,8 +22,8 @@ import { Config } from '@oclif/core'; const { default: SkillsInstall } = await import('../src/commands/skills/install.js'); const { default: SkillsUpdate } = await import('../src/commands/skills/update.js'); const { default: SkillsStatus } = await import('../src/commands/skills/status.js'); -const { skillsRegistry, catalogFromTarball, resolveSkillsVersion } = await import('../src/utils/skills-catalog.js'); -const { SKILLS_MANIFEST_FILE } = await import('../src/utils/skills-install-state.js'); +const { skillsRegistry, catalogFromTarball, resolveSkillsVersion, npmPackInvocation } = await import('../src/utils/skills-catalog.js'); +const { SKILLS_MANIFEST_FILE, applySkillsWrite, readSkillsManifest } = await import('../src/utils/skills-install-state.js'); const PKG = dirname(dirname(fileURLToPath(import.meta.url))); // The oclif config is loaded once, here: a clocked test window measures the commands, never this load. @@ -393,7 +393,68 @@ describe('the catalog in a tarball', () => { expect(() => catalogFromTarball(skillsTarball(V1, CATALOG_V1, [{ path: 'package/dist/skills/a/../../x', data: 'x' }]), V1)).toThrow(/leaves its own tree/); }); + it('refuses a Windows separator or a drive letter in a path segment', () => { + expect(() => catalogFromTarball(skillsTarball(V1, CATALOG_V1, [{ path: 'package/dist/skills/a/..\\..\\x', data: 'x' }]), V1)).toThrow(/leaves its own tree/); + expect(() => catalogFromTarball(skillsTarball(V1, CATALOG_V1, [{ path: 'package/dist/skills/a/C:x', data: 'x' }]), V1)).toThrow(/leaves its own tree/); + }); + it('refuses a catalog with no skill', () => { expect(() => catalogFromTarball(skillsTarball(V1, {}), V1)).toThrow(/holds no skill/); }); }); + +describe('writing stays under the skills directory', () => { + let root = ''; + beforeEach(() => { root = mkdtempSync(join(tmpdir(), 'os-skills-34773-root-')); }); + afterEach(() => { rmSync(root, { recursive: true, force: true }); }); + + it('refuses a catalog file whose target resolves outside the skills directory, and writes nothing there', () => { + const dir = join(root, 'skills'); + const catalog = { version: V1, skills: new Map([['a', new Map([['SKILL.md', Buffer.from('a')], ['../../escaped.md', Buffer.from('x')]])]]) }; + expect(() => applySkillsWrite(dir, catalog, { added: ['a'], replaced: [], dropped: [], conflicts: [] })).toThrow(/outside/); + expect(existsSync(join(root, 'escaped.md'))).toBe(false); + }); + + it('refuses a record naming a skill or a file with a Windows separator or a drive letter', () => { + const write = (skills: Record>) => { + mkdirSync(root, { recursive: true }); + writeFileSync(join(root, SKILLS_MANIFEST_FILE), JSON.stringify({ package: '@objectstack/skills', version: V1, skills })); + }; + write({ 'C:x': { 'SKILL.md': 'h' } }); + expect(() => readSkillsManifest(root)).toThrow(/cannot read/); + write({ a: { '..\\..\\x': 'h' } }); + expect(() => readSkillsManifest(root)).toThrow(/cannot read/); + }); +}); + +describe('the npm pack invocation', () => { + const DEST = 'C:\\Users\\Ada Lovelace\\AppData\\Local\\Temp\\os-skills-pack-x'; + + it('on Windows runs through a shell and quotes the destination, so a path with a space stays one argument', () => { + const { command, args, options } = npmPackInvocation('@objectstack/skills@18.5.0', DEST, 'C:\\work', 'win32'); + expect(command).toBe('npm'); + expect(options.shell).toBe(true); + expect(args).toEqual(['pack', '@objectstack/skills@18.5.0', '--pack-destination', `"${DEST}"`, '--json']); + }); + + it('elsewhere runs without a shell and passes the destination as it is', () => { + const { args, options } = npmPackInvocation('@objectstack/skills@18.5.0', '/tmp/a b/os-skills-pack-x', '/work', 'linux'); + expect(options.shell).toBe(false); + expect(args).toEqual(['pack', '@objectstack/skills@18.5.0', '--pack-destination', '/tmp/a b/os-skills-pack-x', '--json']); + }); +}); + +describe('a malformed record is refused whole', () => { + let root = ''; + beforeEach(() => { root = mkdtempSync(join(tmpdir(), 'os-skills-34773-record-')); }); + afterEach(() => { rmSync(root, { recursive: true, force: true }); }); + + it.each([ + ['an empty skill name', { '': { 'SKILL.md': 'h' }, a: { 'SKILL.md': 'h' } }], + ['a `..` skill name', { '..': { 'SKILL.md': 'h' }, a: { 'SKILL.md': 'h' } }], + ['a backslash in a skill name', { 'a\\b': { 'SKILL.md': 'h' }, a: { 'SKILL.md': 'h' } }], + ])('%s', (_label, skills) => { + writeFileSync(join(root, SKILLS_MANIFEST_FILE), JSON.stringify({ package: '@objectstack/skills', version: V1, skills })); + expect(() => readSkillsManifest(root)).toThrow(/cannot read/); + }); +}); From bbb4b559c725123927de8e0950ec5ecb77f49d97 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 01:52:54 +0000 Subject: [PATCH 4/4] fix(cli): os skills keeps every write under the skills directory Refuses a backslash or a colon in a tarball path segment and in a recorded skill or file name, validates recorded names with the catalog name rule, resolves every target under the skills root before the first write, and quotes the npm pack destination where Windows runs it through a shell. The pending initialize-instructions changeset names os skills install. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzgNCAXyGfBQFZBwixH --- .changeset/34686-initialize-selection-rule.md | 2 +- .changeset/34773-os-skills-install.md | 2 +- packages/cli/src/utils/skills-catalog.ts | 15 ++++++-- .../cli/src/utils/skills-install-state.ts | 36 +++++++++++++------ 4 files changed, 40 insertions(+), 15 deletions(-) diff --git a/.changeset/34686-initialize-selection-rule.md b/.changeset/34686-initialize-selection-rule.md index 6fb4439489d..933c26381b4 100644 --- a/.changeset/34686-initialize-selection-rule.md +++ b/.changeset/34686-initialize-selection-rule.md @@ -12,6 +12,6 @@ A client connected to the open MCP server over HTTP was told one sentence at `in When neither the host's per-request text nor the plugin's `instructions` option answers, `result.instructions` now carries, after that sentence: - **The selection rule**, only where the request registers both `list_datasets` and `query_dataset` (a bridge with the dataset members and a grant that admits `data:read`; an API key or session counts): look for a governed metric first with `list_datasets` and the question's business words; a word matches only an equal name, label or synonym; one measure match answers through `query_dataset`; several matches are a question for the user; no match falls back to `query_records` / `aggregate_records` and says the answer is not from a governed metric. A grant without `data:read` gets no dataset sentence. -- **The skills install line**: `Published skills: @objectstack/skills ` with its `pnpm add -D` command, at this package's own version (released together with `@objectstack/skills`), not the `version` option. +- **The skills install line**: `Published skills: @objectstack/skills ` with the command that installs it into the agent's skills directory, with or without a project, `os skills install --version `, at this package's own version (released together with `@objectstack/skills`), not the `version` option. Host-injected instructions and the `instructions` option are served exactly as before, with nothing appended. The stdio server's instructions are unchanged. diff --git a/.changeset/34773-os-skills-install.md b/.changeset/34773-os-skills-install.md index 0da327d7f0a..f2feec6f762 100644 --- a/.changeset/34773-os-skills-install.md +++ b/.changeset/34773-os-skills-install.md @@ -14,4 +14,4 @@ Nothing installed the published skills catalog except `create-objectstack`'s sca - **`os skills update`** moves the recorded catalog to another version: it replaces the catalog's skills, removes those the new version dropped, and never writes, replaces or removes a skill directory it did not install. A catalog skill changed locally is refused unless `--force`. - **`os skills status`** reports the installed version against the expected one, plus missing, modified and extra skills; it exits `0`, or `1` on a mismatch with `--check`. All three take `--json`. -`@objectstack/mcp`: the open server's `initialize` skills install line now names `os skills install --version ` (and its `npx -p @objectstack/cli@` form for a machine without the CLI) instead of `pnpm add -D @objectstack/skills@`, which needed a project. This supersedes, in the same release, the `pnpm add -D` command the entry introducing that line describes. +`@objectstack/mcp`: the open server's `initialize` skills install line now names `os skills install --version ` (and its `npx -p @objectstack/cli@` form for a machine without the CLI) instead of `pnpm add -D @objectstack/skills@`, which needed a project. diff --git a/packages/cli/src/utils/skills-catalog.ts b/packages/cli/src/utils/skills-catalog.ts index d46ac97091d..22e6c55a1c4 100644 --- a/packages/cli/src/utils/skills-catalog.ts +++ b/packages/cli/src/utils/skills-catalog.ts @@ -58,7 +58,16 @@ const NPM_PACK_TIMEOUT_MS = 120_000; const EXACT_VERSION = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/; /** A skill directory name: one path segment, no leading dot. */ -const SKILL_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; +export const SKILL_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; + +/** + * Whether one `/`-separated path segment stays inside its directory on every + * platform: not empty, not `.` or `..`, and no `\` (a separator on Windows) + * and no `:` (a drive letter or an alternate data stream there). + */ +export function isSafePathSegment(segment: string): boolean { + return segment !== '' && segment !== '.' && segment !== '..' && !segment.includes('\\') && !segment.includes(':'); +} /** Whether `value` names one release exactly (no range, no dist-tag). */ export function isExactVersion(value: string): boolean { @@ -154,7 +163,7 @@ export function npmPackInvocation(spec: string, destination: string, cwd: string const shell = platform === 'win32'; return { command: 'npm', - args: ['pack', spec, '--pack-destination', destination, '--json'], + args: ['pack', spec, '--pack-destination', shell ? `"${destination}"` : destination, '--json'], options: { cwd, timeout: NPM_PACK_TIMEOUT_MS, maxBuffer: 16 * 1024 * 1024, shell }, }; } @@ -308,7 +317,7 @@ export function catalogFromTarball(tgz: Buffer, version: string): SkillsCatalog for (const entry of entries) { if (!entry.path.startsWith(TARBALL_SKILLS_PREFIX)) continue; const parts = entry.path.slice(TARBALL_SKILLS_PREFIX.length).split('/').filter((part, i, all) => !(part === '' && i === all.length - 1)); - if (parts.some((part) => part === '' || part === '.' || part === '..')) { + if (!parts.every(isSafePathSegment)) { throw refuse(`carries the path '${entry.path}', which leaves its own tree.`); } if (entry.type === '5') continue; diff --git a/packages/cli/src/utils/skills-install-state.ts b/packages/cli/src/utils/skills-install-state.ts index 0b64350b7d4..33147240110 100644 --- a/packages/cli/src/utils/skills-install-state.ts +++ b/packages/cli/src/utils/skills-install-state.ts @@ -23,9 +23,9 @@ import { createHash } from 'node:crypto'; import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'; -import { dirname, join, relative, sep } from 'node:path'; +import { dirname, join, relative, resolve, sep } from 'node:path'; -import { SKILLS_PACKAGE, isExactVersion, type SkillsCatalog } from './skills-catalog.js'; +import { SKILLS_PACKAGE, SKILL_NAME, isExactVersion, isSafePathSegment, type SkillsCatalog } from './skills-catalog.js'; /** The record's file name, inside the skills directory. */ export const SKILLS_MANIFEST_FILE = '.objectstack-skills.json'; @@ -95,9 +95,8 @@ export function readSkillsManifest(dir: string): SkillsManifest | null { throw refuse(`does not record ${SKILLS_PACKAGE} at an exact version with its skills.`); } for (const [name, files] of Object.entries(record.skills)) { - const bad = !files || typeof files !== 'object' || Array.isArray(files) - || Object.entries(files).some(([path, hash]) => typeof hash !== 'string' || path.split('/').includes('..')) - || name.includes('/') || name.includes('\\') || name.startsWith('.'); + const bad = !SKILL_NAME.test(name) || !files || typeof files !== 'object' || Array.isArray(files) + || Object.entries(files).some(([path, hash]) => typeof hash !== 'string' || !path.split('/').every(isSafePathSegment)); if (bad) throw refuse(`records the skill '${name}' in a shape it cannot read.`); } return record as SkillsManifest; @@ -180,6 +179,19 @@ export function planSkillsWrite(dir: string, catalog: SkillsCatalog, manifest: S return { added, replaced, dropped, conflicts }; } +/** + * `target` resolved, refused unless it lies strictly under `root`: the last + * guard between a catalog path and the disk, whatever the reader admitted. + */ +function underRoot(root: string, target: string): string { + const base = resolve(root); + const resolved = resolve(target); + if (!resolved.startsWith(base + sep)) { + throw new Error(`Refusing to write ${resolved}: it resolves outside the skills directory ${base}. Nothing outside it is touched.`); + } + return resolved; +} + /** * Write `catalog` into `dir` along `plan`: remove each dropped skill, replace * each recorded one and each conflict (the caller decided those may go), add @@ -187,13 +199,17 @@ export function planSkillsWrite(dir: string, catalog: SkillsCatalog, manifest: S * touched. */ export function applySkillsWrite(dir: string, catalog: SkillsCatalog, plan: SkillsWritePlan): SkillsManifest { + // Every target is judged before the first write, so a refusal leaves the directory as it was. + const dropped = plan.dropped.map((name) => underRoot(dir, join(dir, name))); + const writes = [...catalog.skills].map(([name, files]) => { + const root = underRoot(dir, join(dir, name)); + return { root, files: [...files].map(([path, bytes]) => ({ target: underRoot(root, join(root, ...path.split('/'))), bytes })) }; + }); mkdirSync(dir, { recursive: true }); - for (const name of plan.dropped) rmSync(join(dir, name), { recursive: true, force: true }); - for (const [name, files] of catalog.skills) { - const root = join(dir, name); + for (const target of dropped) rmSync(target, { recursive: true, force: true }); + for (const { root, files } of writes) { rmSync(root, { recursive: true, force: true }); - for (const [path, bytes] of files) { - const target = join(root, ...path.split('/')); + for (const { target, bytes } of files) { mkdirSync(dirname(target), { recursive: true }); writeFileSync(target, bytes); }