From 0857e952d1214ccd426d7480cefe1fa08c5ee6e0 Mon Sep 17 00:00:00 2001 From: XiaoSeS <87064762+XiaoSeS@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:08:00 +0800 Subject: [PATCH 1/4] feat(cli): check and safely upgrade installed repository skills Signed-off-by: XiaoSeS <87064762+XiaoSeS@users.noreply.github.com> --- cli/src/commands/help.ts | 8 +- cli/src/commands/repository.ts | 24 +++- cli/src/commands/upgrade.ts | 9 +- cli/src/index.ts | 3 +- .../services/repository-upgrade-service.ts | 57 ++++++++ cli/src/services/upgrade-service.ts | 10 +- .../repository-upgrade-command.test.ts | 131 ++++++++++++++++++ .../.openspec.yaml | 2 + .../design.md | 29 ++++ .../proposal.md | 25 ++++ .../specs/github-repository-upgrades/spec.md | 51 +++++++ .../upgrade-github-repository-skills/tasks.md | 22 +++ 12 files changed, 356 insertions(+), 15 deletions(-) create mode 100644 cli/src/services/repository-upgrade-service.ts create mode 100644 cli/test/integration/repository-upgrade-command.test.ts create mode 100644 openspec/changes/upgrade-github-repository-skills/.openspec.yaml create mode 100644 openspec/changes/upgrade-github-repository-skills/design.md create mode 100644 openspec/changes/upgrade-github-repository-skills/proposal.md create mode 100644 openspec/changes/upgrade-github-repository-skills/specs/github-repository-upgrades/spec.md create mode 100644 openspec/changes/upgrade-github-repository-skills/tasks.md diff --git a/cli/src/commands/help.ts b/cli/src/commands/help.ts index 01628efbed..ead2823d63 100644 --- a/cli/src/commands/help.ts +++ b/cli/src/commands/help.ts @@ -50,11 +50,13 @@ export const commands = { ] }, repository: { - summary: 'Install current published skills from a GitHub repository', - usage: 'skillhub repository install [--scope ] [--agent ] [--dir ] [--registry ] [--token ] [--json]', + summary: 'Install, check or upgrade skills from a GitHub repository', + usage: 'skillhub repository [--scope (install only)] [--agent ] [--dir ] [--registry ] [--token ] [--check (upgrade only)] [--json]', examples: [ 'skillhub repository install 123456 --scope project --agent codex', - 'skillhub repository install 123456 --dir ./skills --json' + 'skillhub repository install 123456 --dir ./skills --json', + 'skillhub repository check 123456 --json', + 'skillhub repository upgrade 123456 --agent codex --check' ] }, suite: { diff --git a/cli/src/commands/repository.ts b/cli/src/commands/repository.ts index 4ce792b7a9..70a175d035 100644 --- a/cli/src/commands/repository.ts +++ b/cli/src/commands/repository.ts @@ -8,21 +8,39 @@ import { EXIT } from '../shared/constants' import { CliError } from '../shared/errors' import { computeStrictIsTTY } from '../shared/tty' import { resolveEffectiveScope, defaultPromptScope, type InstallCommandOptions } from './install' +import { planRepositoryUpgrades, executeRepositoryUpgrades } from '../services/repository-upgrade-service' +import { renderUpgradePlan, renderUpgradeResult } from './upgrade' -export type RepositoryCommandOptions = Omit +export type RepositoryCommandOptions = Omit & { check?: boolean } export async function repositoryCommand(action: string, repositoryId: string, options: RepositoryCommandOptions): Promise { - if (action !== 'install') throw new CliError('repository action must be "install"', EXIT.usage) + if (!['install', 'check', 'upgrade'].includes(action)) throw new CliError('repository action must be "install", "check" or "upgrade"', EXIT.usage) repositoryId = String(repositoryId) if (!/^[1-9]\d*$/.test(repositoryId) || BigInt(repositoryId) > 9223372036854775807n) { throw new CliError('repository ID must be a positive integer from the repository page', EXIT.usage) } + if (action !== 'install' && options.scope !== undefined) throw new CliError('use --agent or --dir to filter installed targets; --scope is for installation', EXIT.usage) + if (action === 'install' && options.check) throw new CliError('use repository check to inspect installed skills', EXIT.usage) const isTTY = computeStrictIsTTY({ stdinIsTTY: process.stdin.isTTY === true, stdoutIsTTY: process.stdout.isTTY === true, json: Boolean(options.json) }) - const scope = await resolveEffectiveScope(options, { isTTY, promptScope: defaultPromptScope }) + const scope = action === 'install' ? await resolveEffectiveScope(options, { isTTY, promptScope: defaultPromptScope }) : undefined const registry = resolveRegistry(options, process.env, await new ConfigStore().read()) const token = resolveToken(options, process.env, await new CredentialsStore().getToken(registry)) const plan = await new SkillHubClient(registry, token).repositoryInstallPlan(repositoryId) + if (action !== 'install') { + const tokenForRegistry = async () => token + const upgrades = await planRepositoryUpgrades(plan, { registry, agents: options.agent, dir: options.dir, tokenForRegistry }) + const check = action === 'check' || Boolean(options.check) + const result = check ? undefined : await executeRepositoryUpgrades(upgrades, { tokenForRegistry }) + const output = check ? renderUpgradePlan(upgrades, { check: true, executed: false }, Boolean(options.json)) + : renderUpgradeResult(upgrades, result!, Boolean(options.json), upgrades.blocked) + if (upgrades.blocked > 0 || result && result.failed > 0) { + process.stdout.write(`${output}\n`) + throw new CliError('repository update contains protected or failed skills; inspect per-target results', + result?.items.find(item => item.action === 'failed')?.exitCode ?? EXIT.validation) + } + return output + } const targets = await resolveInstallTargets({ cwd: process.cwd(), scope, dir: options.dir, agents: options.agent ?? [], json: Boolean(options.json), interactive: isTTY }) const result = await installRepositoryPlan(plan, { registry, token, targets }) diff --git a/cli/src/commands/upgrade.ts b/cli/src/commands/upgrade.ts index 0fba3fcb77..ac6bf224a6 100644 --- a/cli/src/commands/upgrade.ts +++ b/cli/src/commands/upgrade.ts @@ -61,7 +61,7 @@ export async function upgradeCommand(coordinates: string[], options: UpgradeComm return output } -function renderUpgradePlan( +export function renderUpgradePlan( plan: UpgradePlan, state: { check: boolean; executed: boolean }, json: boolean @@ -96,7 +96,7 @@ function renderUpgradePlan( ].join('\n') } -export function renderUpgradeResult(plan: UpgradePlan, result: UpgradeExecutionResult, json: boolean): string { +export function renderUpgradeResult(plan: UpgradePlan, result: UpgradeExecutionResult, json: boolean, blocked = 0): string { // Execution returns one row per plan position, in order. Coordinates can repeat at different versions. const items = plan.items.map((item, index) => ({ coordinate: item.coordinate, @@ -112,13 +112,14 @@ export function renderUpgradeResult(plan: UpgradePlan, result: UpgradeExecutionR if (json) { return JSON.stringify({ - ok: result.failed === 0, + ok: result.failed === 0 && blocked === 0, check: false, summary: { upgraded: result.upgraded, unchanged: result.unchanged, failed: result.failed, - notAttempted: result.notAttempted + notAttempted: result.notAttempted, + ...(blocked ? { blocked } : {}) }, items }) diff --git a/cli/src/index.ts b/cli/src/index.ts index 0d09a2a876..e437d0380b 100644 --- a/cli/src/index.ts +++ b/cli/src/index.ts @@ -292,12 +292,13 @@ cli }) cli - .command('repository ', 'Install published skills from a GitHub repository') + .command('repository ', 'Install, check or upgrade skills from a GitHub repository') .option('--scope ', 'Install scope: user or project') .option('--agent ', 'Agent profile (repeatable)') .option('--dir ', 'Install directory') .option('--registry ', 'Registry URL') .option('--token ', 'API token') + .option('--check', 'Show the repository upgrade plan without writing') .option('--json', 'Output JSON') .action((action: string, repositoryId: string, options: RepositoryCommandOptions & { agent?: string | string[] }) => runCommand(() => repositoryCommand(action, repositoryId, { ...options, agent: toArray(options.agent) }), Boolean(options.json))) diff --git a/cli/src/services/repository-upgrade-service.ts b/cli/src/services/repository-upgrade-service.ts new file mode 100644 index 0000000000..23d4b79824 --- /dev/null +++ b/cli/src/services/repository-upgrade-service.ts @@ -0,0 +1,57 @@ +import type { RepositoryInstallPlan } from '../clients/skillhub-client' +import { InventoryStore } from '../stores/inventory-store' +import { EXIT } from '../shared/constants' +import { CliError } from '../shared/errors' +import { readInstalledSkillMetadata, sameInstalledSkillSource } from './installed-skill-metadata' +import { MAX_UPGRADE_SELECTION, matchesTargetFilters, planSkillUpgrades, executeSkillUpgradePlan, + type UpgradeSelectionOptions, type UpgradePlan, type UpgradeExecutionResult } from './upgrade-service' + +type RepositoryUpgradeOptions = Omit & { registry: string } + +export async function planRepositoryUpgrades(remote: RepositoryInstallPlan, options: RepositoryUpgradeOptions): Promise { + const inventory = await new InventoryStore(options.home).read() + const members = new Map(remote.members.map(member => [member.slug, member])) + const items: UpgradePlan['items'] = [] + const coordinates: string[] = [] + for (const item of inventory.items) { + if (item.namespace !== 'github' || item.registry.replace(/\/+$/, '') !== options.registry.replace(/\/+$/, '')) continue + const targets = item.targets.filter(target => matchesTargetFilters(target, options.agents, options.dir)) + if (!targets.length) continue + if (members.has(item.slug)) { + coordinates.push(`@github/${item.slug}`) + continue + } + // Local provenance is only a discovery hint for unavailable members, never upgrade authority. + for (const target of targets) { + const metadata = await readInstalledSkillMetadata(target.installDir) + if (metadata.status !== 'valid' || !sameInstalledSkillSource(metadata.metadata, item) + || metadata.metadata.sourceRepositoryId !== remote.repositoryId) continue + items.push({ coordinate: `@github/${item.slug}`, registry: item.registry, currentVersion: target.version, + action: 'blocked', reason: 'no longer in the accessible published repository plan; local files are preserved', + changedFiles: [], targets: [{ agent: target.agent, dir: target.installDir }], + inventoryItem: { ...item, targets: [target] }, selectedTargets: [target], expectedTargetFiles: {}, allowTargetDrift: false }) + } + } + if (!coordinates.length && !items.length) throw new CliError('no installed skills match this repository and target selection; no files changed', EXIT.usage) + for (let offset = 0; offset < coordinates.length; offset += MAX_UPGRADE_SELECTION) { + const plan = await planSkillUpgrades({ ...options, coordinates: coordinates.slice(offset, offset + MAX_UPGRADE_SELECTION), + force: false, resolveVersion: async item => { + const member = members.get(item.slug) + if (!member) throw new CliError('repository member is not in the pinned plan', EXIT.validation) + return member + } }) + items.push(...plan.items) + } + return { items, blocked: items.filter(item => item.action === 'blocked').length, + upgrades: items.filter(item => item.action === 'upgrade').length, unchanged: items.filter(item => item.action === 'unchanged').length } +} + +export async function executeRepositoryUpgrades(plan: UpgradePlan, options: Pick): Promise { + const safeItems = plan.items.filter(item => item.action !== 'blocked') + const executed = await executeSkillUpgradePlan({ ...plan, items: safeItems, blocked: 0 }, options) + let position = 0 + return { ...executed, notAttempted: executed.notAttempted + plan.blocked, + items: plan.items.map(item => item.action === 'blocked' + ? { coordinate: item.coordinate, action: 'not-attempted' as const, reason: item.reason ?? 'protected local installation' } + : executed.items[position++]!) } +} diff --git a/cli/src/services/upgrade-service.ts b/cli/src/services/upgrade-service.ts index 55cf98b230..14c4b15915 100644 --- a/cli/src/services/upgrade-service.ts +++ b/cli/src/services/upgrade-service.ts @@ -12,7 +12,7 @@ import { installSkill } from './install-service' import { readInstalledSkillMetadata, sameInstalledSkillSource } from './installed-skill-metadata' import { compareSkillVersions } from './skill-version-order' -const MAX_UPGRADE_SELECTION = 50 +export const MAX_UPGRADE_SELECTION = 50 export interface UpgradeSelectionOptions { coordinates: string[] @@ -23,6 +23,8 @@ export interface UpgradeSelectionOptions { force: boolean home?: string tokenForRegistry: (registry: string) => Promise + /** Internal source adapter; a repository invocation supplies its already pinned releases. */ + resolveVersion?: (item: InventoryItem) => Promise } export type UpgradePlanAction = 'upgrade' | 'unchanged' | 'blocked' @@ -102,8 +104,8 @@ export async function planSkillUpgrades(options: UpgradeSelectionOptions): Promi try { await assertDirectTargetOwnership(inventory, selection.targets.map(target => target.installDir)) const token = await options.tokenForRegistry(selection.item.registry) - resolved = await new SkillHubClient(selection.item.registry, token) - .resolve(selection.item.namespace, selection.item.slug) + resolved = options.resolveVersion ? await options.resolveVersion(selection.item) + : await new SkillHubClient(selection.item.registry, token).resolve(selection.item.namespace, selection.item.slug) } catch (error) { items.push({ ...base, @@ -388,7 +390,7 @@ async function inspectTargets(item: InventoryItem, targets: InventoryTarget[]): } } -function matchesTargetFilters(target: InventoryTarget, agents?: string[], dir?: string): boolean { +export function matchesTargetFilters(target: InventoryTarget, agents?: string[], dir?: string): boolean { if (agents?.length && !agents.includes(target.agent)) return false if (!dir) return true const filterPath = resolve(dir) diff --git a/cli/test/integration/repository-upgrade-command.test.ts b/cli/test/integration/repository-upgrade-command.test.ts new file mode 100644 index 0000000000..21e2789bc9 --- /dev/null +++ b/cli/test/integration/repository-upgrade-command.test.ts @@ -0,0 +1,131 @@ +import { afterEach, expect, test } from 'bun:test' +import { createHash } from 'node:crypto' +import { readFile, rm, writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import { zipSync, strToU8 } from 'fflate' +import { createTempHome } from '../helpers/temp-env' +import { runCli } from '../helpers/run-cli' +import type { RepositoryInstallPlan } from '../../src/clients/skillhub-client' + +const servers: Array> = [] +const dirs: string[] = [] +afterEach(async () => { + servers.splice(0).forEach(server => server.stop(true)) + await Promise.all(dirs.splice(0).map(dir => rm(dir, { recursive: true, force: true }))) +}) +async function fixture(count = 2) { + const env = await createTempHome() + dirs.push(env.home, env.cwd) + const archives = new Map() + const requests: string[] = [] + const plan: RepositoryInstallPlan = { repositoryId: '42', owner: 'fixture', name: 'repo', members: [] } + const add = (slug: string, version: string) => { + const bytes = strToU8(`# ${slug} ${version}`) + const hash = createHash('sha256').update(bytes).digest('hex') + const old = plan.members.find(member => member.slug === slug) + const id = old?.skillId ?? plan.members.length + 1 + const member = { skillId: id, namespace: 'github' as const, slug, displayName: slug, version, versionId: id + Number(version[0]) * 100, + fingerprint: 'sha256:' + createHash('sha256').update(`SKILL.md:${hash}\n`).digest('hex'), + downloadUrl: `/api/cli/v1/skills/github/${slug}/versions/${version}/download` } + archives.set(member.downloadUrl, new Uint8Array(zipSync({ 'SKILL.md': bytes })).buffer) + if (old) plan.members[plan.members.indexOf(old)] = member + else plan.members.push(member) + } + for (let i = 0; i < count; i++) add(`skill-${i}`, '1.0.0') + let denied = '' + const server = Bun.serve({ hostname: '127.0.0.1', port: 0, fetch(request) { + const path = new URL(request.url).pathname + requests.push(path) + if (request.headers.get('Authorization') !== 'Bearer fake_read_token') return Response.json({ msg: 'denied' }, { status: 403 }) + if (path.endsWith('/42/install-plan')) return Response.json({ data: plan }) + if (denied && path.includes(denied)) return Response.json({ msg: 'unavailable' }, { status: 403 }) + if (archives.has(path)) return new Response(archives.get(path)!.slice(0)) + return Response.json({ msg: 'do not resolve latest again' }, { status: 500 }) + } }) + servers.push(server) + const target = join(env.cwd, 'skills') + const run = (action: string, extra: string[] = []) => runCli(['repository', action, '42', '--dir', target, '--registry', server.url.origin, '--json', ...extra], + { HOME: env.home, USERPROFILE: env.home, SKILLHUB_TOKEN: 'fake_read_token' }) + const metadata = async (slug: string) => JSON.parse(await readFile(join(target, slug, '.skillhub/metadata.json'), 'utf8')) + return { env, plan, requests, target, run, add, metadata, deny: (slug: string) => { denied = slug } } +} + +test('check is read-only and upgrade pins only existing members, never new upstream skills', async () => { + const f = await fixture(1) + expect((await f.run('install')).exitCode).toBe(0) + f.add('skill-0', '2.0.0') + f.add('new-member', '1.0.0') + const checked = await f.run('check') + expect(checked.exitCode).toBe(0) + expect(JSON.parse(checked.stdout).summary).toEqual({ upgrades: 1, unchanged: 0, blocked: 0 }) + expect((await f.metadata('skill-0')).version).toBe('1.0.0') + const upgraded = await f.run('upgrade') + expect(upgraded.exitCode).toBe(0) + expect(JSON.parse(upgraded.stdout).summary.upgraded).toBe(1) + expect((await f.metadata('skill-0')).version).toBe('2.0.0') + expect((await f.metadata('skill-0')).sourceRepositoryId).toBe('42') + expect(await Bun.file(join(f.target, 'new-member/SKILL.md')).exists()).toBe(false) + expect(f.requests.some(path => path.includes('/resolve'))).toBe(false) +}) + +test('local changes remain protected while an independent safe member upgrades', async () => { + const f = await fixture() + expect((await f.run('install')).exitCode).toBe(0) + f.add('skill-0', '2.0.0'); f.add('skill-1', '2.0.0') + await writeFile(join(f.target, 'skill-0/SKILL.md'), '# my edits') + const result = await f.run('upgrade') + expect(result.exitCode).toBe(6) + const output = JSON.parse(result.stdout) + expect(output.ok).toBe(false) + expect(output.summary).toMatchObject({ upgraded: 1, blocked: 1, notAttempted: 1 }) + expect(await readFile(join(f.target, 'skill-0/SKILL.md'), 'utf8')).toBe('# my edits') + expect((await f.metadata('skill-0')).version).toBe('1.0.0') + expect((await f.metadata('skill-1')).version).toBe('2.0.0') +}) + +test('no-longer-listed repository members are reported and preserved without guessing private server state', async () => { + const f = await fixture() + expect((await f.run('install')).exitCode).toBe(0) + f.plan.members = f.plan.members.filter(member => member.slug !== 'skill-1') + const result = await f.run('check') + expect(result.exitCode).toBe(6) + const output = JSON.parse(result.stdout) + expect(output.summary).toMatchObject({ unchanged: 1, blocked: 1 }) + expect(output.items.find((item: { coordinate: string }) => item.coordinate === '@github/skill-1').reason).toContain('local files are preserved') + expect((await f.metadata('skill-1')).version).toBe('1.0.0') +}) + +test('legacy metadata without repository provenance remains readable and upgradeable', async () => { + const f = await fixture(1) + expect((await f.run('install')).exitCode).toBe(0) + const metadata = await f.metadata('skill-0') + delete metadata.sourceRepositoryId + await writeFile(join(f.target, 'skill-0/.skillhub/metadata.json'), JSON.stringify(metadata)) + f.add('skill-0', '2.0.0') + expect((await f.run('upgrade', ['--check'])).exitCode).toBe(0) + expect((await f.metadata('skill-0')).version).toBe('1.0.0') + expect((await f.run('upgrade')).exitCode).toBe(0) + expect((await f.metadata('skill-0')).version).toBe('2.0.0') +}) + +test('partial download failure retains committed upgrades and fails without lying about remaining work', async () => { + const f = await fixture() + expect((await f.run('install')).exitCode).toBe(0) + f.add('skill-0', '2.0.0'); f.add('skill-1', '2.0.0'); f.deny('skill-1') + const result = await f.run('upgrade') + expect(result.exitCode).toBe(2) + expect(JSON.parse(result.stdout).summary).toMatchObject({ upgraded: 1, failed: 1 }) + expect((await f.metadata('skill-0')).version).toBe('2.0.0') + expect((await f.metadata('skill-1')).version).toBe('1.0.0') + expect(result.stdout + result.stderr).not.toContain('fake_read_token') +}) + +test('repository checks cover more than the individual command selection limit without re-resolving', async () => { + const f = await fixture(51) + expect((await f.run('install')).exitCode).toBe(0) + const start = f.requests.length + const result = await f.run('check') + expect(result.exitCode).toBe(0) + expect(JSON.parse(result.stdout).summary).toEqual({ upgrades: 0, unchanged: 51, blocked: 0 }) + expect(f.requests.slice(start)).toEqual(['/api/cli/v1/github-repositories/42/install-plan']) +}, 30000) diff --git a/openspec/changes/upgrade-github-repository-skills/.openspec.yaml b/openspec/changes/upgrade-github-repository-skills/.openspec.yaml new file mode 100644 index 0000000000..4ee7b3f00e --- /dev/null +++ b/openspec/changes/upgrade-github-repository-skills/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-20 diff --git a/openspec/changes/upgrade-github-repository-skills/design.md b/openspec/changes/upgrade-github-repository-skills/design.md new file mode 100644 index 0000000000..a30a9a4c5e --- /dev/null +++ b/openspec/changes/upgrade-github-repository-skills/design.md @@ -0,0 +1,29 @@ +# Design + +## Context + +#1103 提供当前可用版本的完整清单。CLI 已有 `planSkillUpgrades`、`executeSkillUpgradePlan` 和安全本地 inventory;原版升级每次最多选择 50 个坐标。本实现作为 #1103 后的独立堆叠 PR,只增加仓库范围编排。 + +## Decisions + +- 用服务器当前清单与指定 registry 下的本地 inventory 求交集,不爬取分页详情、不推测 Suite、也不只比较提交 SHA。 +- 升级规划增加内部精确版本 resolver 注入,默认升级行为保持不变。仓库编排将大选择分成不超过 50 个坐标的规划块,始终复用首次取得的固定版本清单,合并实际逐目标规划,不能重新解析 latest。 +- 各技能 metadata 的可选 sourceRepositoryId 仅用于提示“曾来自本仓库、当前已不可用”的本地条目;更新资格仍以服务端清单为准。缺该提示的历史直接安装仍能按已验证的当前成员匹配。无法证明历史来源且当前也无法匹配时不猜测、不改文件。 +- 预期保护项保留为 blocked/not-attempted;从可执行集合排除后复用已有升级执行器。整体有保护项或失败时返回非零,同时准确保留独立成功项。执行器遇到意外失败仍沿用原有停止后续执行和逐目标回滚规则,不宣称跨文件系统事务。 +- 不提供仓库批量 force。用户明确核查单个技能后仍可选择既有单技能升级能力。 +- 网页安装面板只切换三种命令:安装、检查已安装更新、升级已安装技能。更新检查说明本地才知道安装情况,不增加远端安装状态 API 或“落后 N 项”徽标。 + +## Alternatives + +将仓库自动创建 Suite 会改变领域语义和审核、版本关系,因此不采用。新建仓库安装账本能记成员历史,但当前逐技能 metadata 已能保存必要来源提示,额外状态和迁移成本不值得。仅逐个调用普通 upgrade 会在执行过程中重解析 latest,破坏本次固定版本,所以复用其规划和执行两段而非循环执行命令。 + +## Risks / Trade-offs + +- 整个仓库清单不可读时无法安全匹配 → 请求失败且不写文件,不能由本地来源提示绕过权限。 +- 旧 metadata 没有可靠来源 → 只处理当前已验证交集,其余留在本地,不编造归属。 +- 规划后再次撤权、改文件或改 inventory → 原下载端、指纹及 CAS 再校验;执行失败结果保留。 +- 部分更新成功意味着本地并非同一提交 → 这是独立技能的允许状态,输出具体版本,不加虚假的提交锁步约束。 + +## Migration Plan + +无数据库或 inventory schema 迁移。升级 CLI 即可使用;旧 metadata 保持可读。回滚 CLI 不删除已安装文件。与 #1103 按顺序合入,分别保留验证范围与 PR。 diff --git a/openspec/changes/upgrade-github-repository-skills/proposal.md b/openspec/changes/upgrade-github-repository-skills/proposal.md new file mode 100644 index 0000000000..e40e7c36d5 --- /dev/null +++ b/openspec/changes/upgrade-github-repository-skills/proposal.md @@ -0,0 +1,25 @@ +# Proposal + +## Why + +Issue #1110 的实际需求是发现已安装技能的更新并安全批量升级。按已确认的产品边界,仓库成员可以来自不同提交,不应将提交不同直接称为异常,也不应由网页推测用户的本地安装状态。 + +## What Changes + +- 增加 `repository check` 和 `repository upgrade`,基于 #1103 当前可用清单核对既有逐技能 inventory、版本与指纹。 +- 保护本地修改、Suite/共享归属和失效来源;明确不可升级与部分失败,不自动增删成员。 +- 网页补检查和升级命令入口及对应原型;保留独立安装、快照和 Suite 行为。 + +## Capabilities + +### New Capabilities + +- `github-repository-upgrades`: 已安装仓库技能的只读检查、精确版本升级及保护反馈。 + +### Modified Capabilities + +无。 + +## Impact + +依赖 #1103 的只读清单;修改 CLI 升级编排与命令、网页命令入口和用户文档。无新数据库/API、仓库账本、安装遥测或全仓事务。不实施原提案中的自动 Suite、提交锁步、审核重新分组或空间强制策略。 diff --git a/openspec/changes/upgrade-github-repository-skills/specs/github-repository-upgrades/spec.md b/openspec/changes/upgrade-github-repository-skills/specs/github-repository-upgrades/spec.md new file mode 100644 index 0000000000..1b2e5454bf --- /dev/null +++ b/openspec/changes/upgrade-github-repository-skills/specs/github-repository-upgrades/spec.md @@ -0,0 +1,51 @@ +## Purpose + +通过本地 CLI 检查仓库来源技能的已安装版本和更新,并在保持原有文件、安装归属和权限边界的前提下升级。它帮助使用者维护独立技能,不将不同提交误判为损坏,不引入仓库安装账本,也不让网页推断本地状态。 + +## ADDED Requirements + +### Requirement: REQ-1 Installed members only +The CLI SHALL match the repository's current accessible published plan against existing local per-skill inventory from the selected registry and target scope. It MUST NOT automatically install new members or delete local members absent from that plan. + +#### Scenario: Newly added and removed members +- **WHEN** A is installed, B is a new upstream member, and a previously repository-installed C is absent from the current plan +- **THEN** A is checked, B is not installed, and C remains untouched with an unavailable/no-longer-listed explanation based on local provenance without guessing its hidden server state. + +### Requirement: REQ-2 Version and content comparison +The CLI SHALL detect updates using exact version and content fingerprint with existing version ordering. Different upstream commit IDs alone MUST NOT generate an inconsistency warning. One invocation MUST reuse its resolved versions throughout execution. + +#### Scenario: Mixed commits with unchanged content +- **WHEN** installed skills match the eligible versions and fingerprints but came from different commits +- **THEN** they are reported unchanged rather than inconsistent. + +### Requirement: REQ-3 Protect local state and other owners +The CLI SHALL retain existing target locks, ownership, baseline checks, compare-and-swap inventory and rollback protections. Repository upgrades MUST NOT implicitly force local modifications or bypass Suite/shared ownership, disabled-state or source-identity guards. + +#### Scenario: Local edits or another owner +- **WHEN** one target has local edits, is Suite-managed or cannot be safely maintained +- **THEN** that target is reported blocked and unchanged; independently safe targets can upgrade and the overall result is nonzero with explicit protected/not-attempted outcomes. + +#### Scenario: Change after planning +- **WHEN** files, ownership or inventory change after the upgrade plan is built +- **THEN** execution rechecks the bound baseline and rejects unsafe replacement without reporting a false success. + +### Requirement: REQ-4 Historical metadata compatibility +The CLI SHALL continue reading legacy per-skill inventory and metadata. Optional repository provenance MUST NOT act as an authority or fabricated file baseline. Missing provenance MUST NOT cause data deletion or a forced metadata migration. + +#### Scenario: Existing direct installation without repository provenance +- **WHEN** a legacy/direct local Skill matches a current verified repository member and has a valid upgrade baseline +- **THEN** it can be checked normally without requiring a repository ledger; unsafe legacy paths or missing baselines remain blocked by existing protections. + +### Requirement: REQ-5 Honest check and execution results +The CLI SHALL support a read-only check and report unchanged, upgradeable, blocked, failed and not-attempted outcomes. Unexpected partial failures MUST return nonzero and preserve completed successes with correct inventory. JSON stdout MUST remain one parseable result object. + +#### Scenario: Download failure during upgrade +- **WHEN** an exact-version download fails after an earlier target upgraded +- **THEN** completed work remains correct, failed/unattempted work is explicit, and the command returns nonzero without claiming all-or-nothing rollback. + +### Requirement: REQ-6 Web describes local operations accurately +The Web SHALL offer copyable repository check and upgrade commands without reporting local installed counts, local drift or executing filesystem changes. Install, current-member upgrade and complete snapshot ZIP MUST remain distinguishable. + +#### Scenario: Web user chooses update check +- **WHEN** the user selects the check action on a repository page +- **THEN** the copied command performs a local read-only check, and the page explains that only CLI can compare local installations. diff --git a/openspec/changes/upgrade-github-repository-skills/tasks.md b/openspec/changes/upgrade-github-repository-skills/tasks.md new file mode 100644 index 0000000000..14650ebad7 --- /dev/null +++ b/openspec/changes/upgrade-github-repository-skills/tasks.md @@ -0,0 +1,22 @@ +# Tasks + +## 1. CLI 检查和升级 + +- [ ] 1.1 复用普通升级规划及精确版本 resolver,分块覆盖完整成员;测试证明无新装、无删除、旧 metadata 可读及版本固定。 +- [ ] 1.2 增加 repository check/upgrade 命令与可读/JSON 结果;测试证明本地改动保护、失效来源保留、部分成功和非零退出码。 +- [ ] 1.3 更新 CLI 帮助和中英文文档;CLI lint/typecheck/test/build 通过。 + +## 2. Web 与原型 + +- [ ] 2.1 在原型中补命令选择和本地更新说明,回读并核对未虚构本地状态。 +- [ ] 2.2 实现命令选择及翻译,交互测试、类型/构建/样式检查通过。 + +## 3. 综合交付 + +- [ ] 3.1 刷新基线后审查精确差异,记录兼容、来源、并发和失败恢复边界。 +- [ ] 3.2 与 #1103 共用一套精确版本本地镜像,验证真实 Token、CLI 安装后检查升级、受限目标及 Ego 页面操作;保留实际结果及限制。 +- [ ] 3.3 更新独立堆叠 Draft PR 和 OpenSpec,严格校验通过;未完成门禁保留未完成状态。 + +## Workflow follow-up + +- 获得合并授权并完成交付后归档,不自动合并或删除人工预览。 From 169fe60d152e25a0a31dafeeadb072f96d680e10 Mon Sep 17 00:00:00 2001 From: XiaoSeS <87064762+XiaoSeS@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:13:42 +0800 Subject: [PATCH 2/4] feat(web): offer repository install and local update commands Signed-off-by: XiaoSeS <87064762+XiaoSeS@users.noreply.github.com> --- cli/README.md | 16 +++++++++++++++- docs/skillhub/en/guide/cli.md | 12 ++++++++++++ docs/skillhub/guide/cli.md | 14 ++++++++++++++ .../github-repository-install.test.tsx | 19 +++++++++++++++++++ .../github-sync/github-repository-install.tsx | 11 ++++++++++- web/src/i18n/locales/en.json | 9 ++++++++- web/src/i18n/locales/ko.json | 9 ++++++++- web/src/i18n/locales/ru.json | 9 ++++++++- web/src/i18n/locales/zh.json | 9 ++++++++- 9 files changed, 102 insertions(+), 6 deletions(-) diff --git a/cli/README.md b/cli/README.md index 2dc015c04d..c3f0180574 100644 --- a/cli/README.md +++ b/cli/README.md @@ -682,4 +682,18 @@ The CLI resolves all currently accessible, published, download-ready members onc Each member uses normal Skill installation locks, fingerprint checks, ownership protection and inventory. This creates neither a Suite nor a repository installation ledger. Existing directories are never overwritten by this batch command; no batch `--force` is accepted. Successful members remain installed if another fails. The output lists every attempted member, counts installed/skipped/failed, and returns nonzero on partial failure or no usable plan. In `--json` mode stdout is one result object; a nonzero command additionally writes its standard error object to stderr. Excluded private/unpublished members are not counted as successful or as a disclosed skip count. -A complete historical snapshot ZIP is a separate download: every pinned snapshot member must be available. Batch installation does not promise that all members belong to one commit. Use individual upgrades for existing skills; repository-scoped update checks and upgrades are tracked separately in #1110. +A complete historical snapshot ZIP is a separate download: every pinned snapshot member must be available. Batch installation does not promise that all members belong to one commit. Use the repository-scoped check and upgrade commands below for existing installations. + +## Check and upgrade installed repository skills + +```bash +skillhub repository check 123456 --registry https://skillhub.example.com --json +skillhub repository upgrade 123456 --agent codex --registry https://skillhub.example.com --check +skillhub repository upgrade 123456 --agent codex --registry https://skillhub.example.com +``` + +`check` and `upgrade --check` are read-only. `--agent` and/or `--dir` filter existing targets; `--scope` applies only to installation. New upstream members are not automatically installed. Local files for removed, hidden or unavailable members are not deleted. A per-Skill provenance hint lets the CLI explain that a previously installed member no longer appears in the accessible published plan without guessing why it is hidden. Older metadata without this hint stays readable and can match verified current members. + +Checks compare exact versions and content fingerprints, not commit equality. Each invocation fetches the repository plan once and pins all selected releases. Existing source, ownership, local-change, disabled-state, lock and inventory protections remain in effect. No repository batch `--force` is offered. Protected targets remain unchanged while safe targets may upgrade; the overall result is nonzero if anything is protected or fails. A runtime failure preserves completed work and reports subsequent unattempted targets. The CLI does not claim a single transaction across every skill directory. + +The Web page offers these commands but cannot inspect installed local files or display an installed drift count. These operations create no Suite, repository installation ledger, server installation telemetry or lockstep commit policy. Existing registry download quotas still apply. diff --git a/docs/skillhub/en/guide/cli.md b/docs/skillhub/en/guide/cli.md index 76a97b8746..8c80df9352 100644 --- a/docs/skillhub/en/guide/cli.md +++ b/docs/skillhub/en/guide/cli.md @@ -784,3 +784,15 @@ skillhub repository install 123456 --scope project --agent codex --registry http Requires the repository install-plan API. Public content can be read anonymously; a supplied Token requires `skill:read` and remains subject to account and namespace permissions. A single plan pins all currently accessible, published, downloadable member versions and fingerprints (up to 1000). Versions may come from different commits; a newer pending revision does not block an older usable publication. Excluded private or unpublished details and counts are not disclosed. The Web list is a preview; the CLI resolves a fresh plan when run. No batch `--force` is supported. Existing directories remain protected, successful members survive partial failures, and a partial failure returns a nonzero exit code with per-member results. This reuses individual installation records without creating a Suite or repository installation ledger. Complete snapshot ZIP downloads remain separate and require every pinned snapshot member to be available. + +### Check and upgrade installed repository skills + +```bash +skillhub repository check 123456 --registry https://skillhub.example.com --json +skillhub repository upgrade 123456 --agent codex --registry https://skillhub.example.com --check +skillhub repository upgrade 123456 --agent codex --registry https://skillhub.example.com +``` + +Checks are read-only. Use `--agent` and/or `--dir` to filter existing targets; `--scope` is installation-only. Compare exact versions and fingerprints rather than commit equality. Do not add new upstream members or delete local files for removed/unavailable members. Legacy metadata stays readable without a forced migration. + +Local edits, other owners, disabled state, source checks, locks and inventory consistency remain protected. Safe targets can upgrade independently while protected targets remain unchanged. Any protected or failed item makes the overall result nonzero, with explicit per-target results. Runtime failure retains completed work and reports later unattempted targets. No batch `--force`, cross-directory atomicity, new repository installation ledger or server installation telemetry is introduced. Existing download quotas apply. The Web offers commands only and cannot know local installation or drift counts. diff --git a/docs/skillhub/guide/cli.md b/docs/skillhub/guide/cli.md index 79cf2db9d7..19b05868bb 100644 --- a/docs/skillhub/guide/cli.md +++ b/docs/skillhub/guide/cli.md @@ -735,3 +735,17 @@ skillhub repository install 123456 --scope project --agent codex --registry http 默认保护已有目录,不支持批量 `--force`。成员逐个安装:部分失败时已成功成员保留,结果逐项报告,并以非零退出码结束;不会伪报整仓成功。复用原有逐技能安装记录,不自动创建套件,也不增加仓库安装账本。 完整快照 ZIP 仍是另一个入口,要求该快照内每个固定成员均可下载;它与可能混合提交的日常批量安装不同。 + +### 检查和升级已安装的仓库技能 + +```bash +skillhub repository check 123456 --registry https://skillhub.example.com --json +skillhub repository upgrade 123456 --agent codex --registry https://skillhub.example.com --check +skillhub repository upgrade 123456 --agent codex --registry https://skillhub.example.com +``` + +`check` 和 `upgrade --check` 不写文件。`--agent`、`--dir` 筛选已有目标;`--scope` 仅用于首次安装。按版本和指纹比较,不要求成员来自同一提交。只升级已有成员,不补装上游新增技能,不删除已移除或不可用成员的本地文件。历史 metadata 缺少仓库来源提示仍可读取,不强制迁移;当前可用成员的资格来自服务端真实绑定。 + +本地修改、共享/Suite 归属、禁用状态、来源冲突仍按现有保护规则处理。受保护项保留,其他安全项可以独立升级;有保护项或失败时整体非零退出并逐项解释。意外失败时保留已完成项并停止后续升级,不宣称整仓文件系统事务。批量操作不提供 `--force`,仍遵循现有下载限额。 + +网页只提供命令,不知道你的本地安装情况,也不会显示推测的“落后 N 项”。 diff --git a/web/src/features/github-sync/github-repository-install.test.tsx b/web/src/features/github-sync/github-repository-install.test.tsx index 898705058b..561b8edc93 100644 --- a/web/src/features/github-sync/github-repository-install.test.tsx +++ b/web/src/features/github-sync/github-repository-install.test.tsx @@ -68,6 +68,25 @@ it('preserves command and visible error when clipboard access fails', async () = expect(screen.getByText(/skillhub repository install 42/)).toBeTruthy() }) +it('offers local-only check and upgrade commands without an installation scope or force flag', async () => { + mocks.fetch.mockResolvedValue(plan) + mocks.copy.mockResolvedValue(undefined) + setup() + fireEvent.click(screen.getByRole('button', { name: 'githubCatalog.installOpen' })) + await screen.findByText('Alpha') + for (const action of ['check', 'upgrade']) { + const choice = screen.getByRole('button', { name: `githubCatalog.repositoryCommandActions.${action}` }) + fireEvent.click(choice) + expect(choice.getAttribute('aria-pressed')).toBe('true') + expect(screen.getByText('githubCatalog.repositoryUpdateHint')).toBeTruthy() + fireEvent.click(screen.getByRole('button', { name: 'copyButton.copy' })) + await waitFor(() => expect(mocks.copy).toHaveBeenLastCalledWith(expect.stringContaining(`repository ${action} 42`))) + const command = mocks.copy.mock.calls.at(-1)?.[0] + expect(command).not.toContain('--scope') + expect(command).not.toContain('--force') + } +}) + it('shows pending state and ignores a late result while collapsed', async () => { let complete: (value: typeof plan) => void = () => {} mocks.fetch.mockReturnValue(new Promise(resolve => { complete = resolve })) diff --git a/web/src/features/github-sync/github-repository-install.tsx b/web/src/features/github-sync/github-repository-install.tsx index b2e6c05d9c..33f225c592 100644 --- a/web/src/features/github-sync/github-repository-install.tsx +++ b/web/src/features/github-sync/github-repository-install.tsx @@ -15,6 +15,7 @@ export function GithubRepositoryInstall({ repositoryId }: { repositoryId: string const [open, setOpen] = useState(false) const [copied, setCopied] = useState(false) const [copyFailed, setCopyFailed] = useState(false) + const [commandAction, setCommandAction] = useState<'install' | 'check' | 'upgrade'>('install') const id = useId() const plan = useQuery({ queryKey: ['skills', 'github-repository-install', user?.userId, repositoryId], @@ -28,7 +29,7 @@ export function GithubRepositoryInstall({ repositoryId }: { repositoryId: string const registry = new URL(buildApiUrl('/'), window.location.origin).href.replace(/\/$/, '') // Do not emit shell metacharacters from runtime configuration into copied commands. const command = /^[a-zA-Z0-9:/._~-]+$/.test(registry) - ? `skillhub repository install ${repositoryId} --scope project --registry "${registry}"` : '' + ? `skillhub repository ${commandAction} ${repositoryId}${commandAction === 'install' ? ' --scope project' : ''} --registry "${registry}"` : '' return
@@ -71,6 +72,13 @@ export function GithubRepositoryInstall({ repositoryId }: { repositoryId: string

{t('githubCatalog.installCommand')}

+
+ {(['install', 'check', 'upgrade'] as const).map(action => )} +
{command ?
{command}
}
} diff --git a/web/src/i18n/locales/en.json b/web/src/i18n/locales/en.json index 92a9db9b78..34bda897d8 100644 --- a/web/src/i18n/locales/en.json +++ b/web/src/i18n/locales/en.json @@ -116,7 +116,14 @@ "installCommand": "Run in your terminal", "installRegistryInvalid": "The site address cannot safely be embedded in a command. Set the CLI registry manually.", "installCopyFailed": "Copy failed. Select and copy the command manually.", - "installLocalHint": "Requires SkillHub CLI. Log in first for restricted content. The CLI resolves and pins versions when it runs and asks you to choose an Agent. This page does not write local files." + "installLocalHint": "Requires SkillHub CLI. Log in first for restricted content. The CLI resolves and pins versions when it runs and asks you to choose an Agent. This page does not write local files.", + "repositoryCommandAction": "Local operation", + "repositoryCommandActions": { + "install": "Install skills", + "check": "Check updates", + "upgrade": "Upgrade installed skills" + }, + "repositoryUpdateHint": "Only matching installed skills are compared. New members are not added and local files are not deleted. Modified, shared or unavailable targets are protected and explained; partial completion is not reported as full success." }, "landing": { "hero": { diff --git a/web/src/i18n/locales/ko.json b/web/src/i18n/locales/ko.json index e2313c9353..6a07356db6 100644 --- a/web/src/i18n/locales/ko.json +++ b/web/src/i18n/locales/ko.json @@ -106,7 +106,14 @@ "installCommand": "터미널에서 실행", "installRegistryInvalid": "사이트 주소를 명령에 안전하게 포함할 수 없습니다. CLI에서 레지스트리를 직접 지정하세요.", "installCopyFailed": "복사하지 못했습니다. 명령을 직접 선택해 복사하세요.", - "installLocalHint": "SkillHub CLI가 필요합니다. 제한된 콘텐츠는 먼저 로그인하세요. CLI 실행 시 버전을 고정하고 Agent를 선택합니다. 이 페이지는 로컬 파일을 쓰지 않습니다." + "installLocalHint": "SkillHub CLI가 필요합니다. 제한된 콘텐츠는 먼저 로그인하세요. CLI 실행 시 버전을 고정하고 Agent를 선택합니다. 이 페이지는 로컬 파일을 쓰지 않습니다.", + "repositoryCommandAction": "로컬 작업", + "repositoryCommandActions": { + "install": "스킬 설치", + "check": "업데이트 확인", + "upgrade": "설치된 스킬 업그레이드" + }, + "repositoryUpdateHint": "일치하는 로컬 스킬만 비교합니다. 새 항목을 추가하거나 로컬 파일을 삭제하지 않습니다. 수정되었거나 공유 중인 대상, 사용할 수 없는 대상은 보호하고 결과를 설명합니다." }, "landing": { "hero": { diff --git a/web/src/i18n/locales/ru.json b/web/src/i18n/locales/ru.json index fd01bf276d..d62b38032d 100644 --- a/web/src/i18n/locales/ru.json +++ b/web/src/i18n/locales/ru.json @@ -106,7 +106,14 @@ "installCommand": "Выполнить в терминале", "installRegistryInvalid": "Адрес сайта нельзя безопасно вставить в команду. Укажите реестр вручную в CLI.", "installCopyFailed": "Не удалось скопировать. Выделите и скопируйте команду вручную.", - "installLocalHint": "Требуется SkillHub CLI. Для закрытого содержимого сначала войдите. CLI фиксирует версии при запуске и предлагает выбрать Agent. Эта страница не записывает локальные файлы." + "installLocalHint": "Требуется SkillHub CLI. Для закрытого содержимого сначала войдите. CLI фиксирует версии при запуске и предлагает выбрать Agent. Эта страница не записывает локальные файлы.", + "repositoryCommandAction": "Локальная операция", + "repositoryCommandActions": { + "install": "Установить навыки", + "check": "Проверить обновления", + "upgrade": "Обновить установленные" + }, + "repositoryUpdateHint": "Сравниваются только установленные навыки. Новые элементы не добавляются, локальные файлы не удаляются. Изменённые, общие и недоступные цели защищены с пояснением; частичное выполнение не считается полным успехом." }, "landing": { "hero": { diff --git a/web/src/i18n/locales/zh.json b/web/src/i18n/locales/zh.json index cf31429803..2477ec2b68 100644 --- a/web/src/i18n/locales/zh.json +++ b/web/src/i18n/locales/zh.json @@ -116,7 +116,14 @@ "installCommand": "在终端运行", "installRegistryInvalid": "站点地址无法安全生成为命令,请在 CLI 中手动指定 registry。", "installCopyFailed": "复制失败,请手动选择命令复制。", - "installLocalHint": "需要已安装 SkillHub CLI。受限内容请先登录;CLI 执行时重新解析并固定版本,选择目标 Agent,本页不会写入本地文件。" + "installLocalHint": "需要已安装 SkillHub CLI。受限内容请先登录;CLI 执行时重新解析并固定版本,选择目标 Agent,本页不会写入本地文件。", + "repositoryCommandAction": "操作方式", + "repositoryCommandActions": { + "install": "安装技能", + "check": "检查更新", + "upgrade": "升级已有技能" + }, + "repositoryUpdateHint": "只比较本地已有的对应技能,不补装新增成员、不删除本地文件。修改、共享归属或不可用项会保留并说明;部分完成不会显示为全部成功。" }, "landing": { "hero": { From 97158eea9d9112efa462ed671b48359b791e59e1 Mon Sep 17 00:00:00 2001 From: XiaoSeS <87064762+XiaoSeS@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:29:25 +0800 Subject: [PATCH 3/4] fix(cli): order GitHub releases safely and preflight disabled targets Signed-off-by: XiaoSeS <87064762+XiaoSeS@users.noreply.github.com> --- cli/README.md | 2 + .../services/repository-upgrade-service.ts | 16 ++++- cli/src/services/upgrade-service.ts | 7 +- .../repository-upgrade-command.test.ts | 70 +++++++++++++++++-- .../design.md | 4 +- .../specs/github-repository-upgrades/spec.md | 6 +- 6 files changed, 94 insertions(+), 11 deletions(-) diff --git a/cli/README.md b/cli/README.md index b7826fdcda..8ba53aa171 100644 --- a/cli/README.md +++ b/cli/README.md @@ -699,3 +699,5 @@ skillhub repository upgrade 123456 --agent codex --registry https://skillhub.exa Checks compare exact versions and content fingerprints, not commit equality. Each invocation fetches the repository plan once and pins all selected releases. Existing source, ownership, local-change, disabled-state, lock and inventory protections remain in effect. No repository batch `--force` is offered. Protected targets remain unchanged while safe targets may upgrade; the overall result is nonzero if anything is protected or fails. A runtime failure preserves completed work and reports subsequent unattempted targets. The CLI does not claim a single transaction across every skill directory. The Web page offers these commands but cannot inspect installed local files or display an installed drift count. These operations create no Suite, repository installation ledger, server installation telemetry or lockstep commit policy. Existing registry download quotas still apply. + +GitHub sync release strings contain content hashes and ingestion IDs rather than sortable upstream SemVer. Repository checks use the validated same-source metadata version ID as the creation-order baseline. Exact matching versions/fingerprints are unchanged; older metadata lacking a reliable ordering ID is protected when a different release must be compared. No hash-lexical fallback or forced migration is used. Disabled targets requiring an update are protected during planning; enabled independent targets can proceed. diff --git a/cli/src/services/repository-upgrade-service.ts b/cli/src/services/repository-upgrade-service.ts index 23d4b79824..d52bb83051 100644 --- a/cli/src/services/repository-upgrade-service.ts +++ b/cli/src/services/repository-upgrade-service.ts @@ -6,7 +6,7 @@ import { readInstalledSkillMetadata, sameInstalledSkillSource } from './installe import { MAX_UPGRADE_SELECTION, matchesTargetFilters, planSkillUpgrades, executeSkillUpgradePlan, type UpgradeSelectionOptions, type UpgradePlan, type UpgradeExecutionResult } from './upgrade-service' -type RepositoryUpgradeOptions = Omit & { registry: string } +type RepositoryUpgradeOptions = Omit & { registry: string } export async function planRepositoryUpgrades(remote: RepositoryInstallPlan, options: RepositoryUpgradeOptions): Promise { const inventory = await new InventoryStore(options.home).read() @@ -39,8 +39,20 @@ export async function planRepositoryUpgrades(remote: RepositoryInstallPlan, opti const member = members.get(item.slug) if (!member) throw new CliError('repository member is not in the pinned plan', EXIT.validation) return member + }, compareVersions: async (item, resolved) => { + const current = await readInstalledSkillMetadata(item.targets[0]!.installDir) + if (current.status !== 'valid' || !sameInstalledSkillSource(current.metadata, item) + || current.metadata.version !== item.targets[0]!.version + || current.metadata.fingerprint !== item.targets[0]!.fingerprint) return 'unknown' + if (current.metadata.version === resolved.version && current.metadata.fingerprint === resolved.fingerprint) return 'same' + // GitHub versions embed a content hash, not a sortable SemVer publication sequence. + // Within one verified source Skill, version IDs preserve creation order (including reverts). + const versionId = current.metadata.versionId + if (!Number.isSafeInteger(versionId) || !versionId || versionId <= 0) return 'unknown' + return resolved.versionId === versionId ? 'same' : resolved.versionId > versionId ? 'remote-newer' : 'remote-older' } }) - items.push(...plan.items) + items.push(...plan.items.map(item => item.action === 'upgrade' && item.selectedTargets.some(target => target.installationState === 'disabled') + ? { ...item, action: 'blocked' as const, reason: 'disabled installation is protected; use the native transactional manager' } : item)) } return { items, blocked: items.filter(item => item.action === 'blocked').length, upgrades: items.filter(item => item.action === 'upgrade').length, unchanged: items.filter(item => item.action === 'unchanged').length } diff --git a/cli/src/services/upgrade-service.ts b/cli/src/services/upgrade-service.ts index 14c4b15915..d1922f9663 100644 --- a/cli/src/services/upgrade-service.ts +++ b/cli/src/services/upgrade-service.ts @@ -10,7 +10,7 @@ import { diffSkillFiles, snapshotSkillDirectory } from './skill-fingerprint' import { snapshotInstalledSkillDirectory } from './installed-skill-snapshot' import { installSkill } from './install-service' import { readInstalledSkillMetadata, sameInstalledSkillSource } from './installed-skill-metadata' -import { compareSkillVersions } from './skill-version-order' +import { compareSkillVersions, type SkillVersionOrder } from './skill-version-order' export const MAX_UPGRADE_SELECTION = 50 @@ -25,6 +25,8 @@ export interface UpgradeSelectionOptions { tokenForRegistry: (registry: string) => Promise /** Internal source adapter; a repository invocation supplies its already pinned releases. */ resolveVersion?: (item: InventoryItem) => Promise + /** Source-specific ordering; ordinary upgrades retain the SemVer comparator. */ + compareVersions?: (item: InventoryItem, resolved: ResolveResponse) => Promise } export type UpgradePlanAction = 'upgrade' | 'unchanged' | 'blocked' @@ -163,7 +165,8 @@ export async function planSkillUpgrades(options: UpgradeSelectionOptions): Promi continue } - const versionOrder = compareSkillVersions(selection.targets[0]!.version, resolved.version) + const versionOrder = options.compareVersions ? await options.compareVersions(selection.item, resolved) + : compareSkillVersions(selection.targets[0]!.version, resolved.version) if (versionOrder === 'remote-older') { items.push({ ...base, diff --git a/cli/test/integration/repository-upgrade-command.test.ts b/cli/test/integration/repository-upgrade-command.test.ts index 21e2789bc9..d2886ac8ea 100644 --- a/cli/test/integration/repository-upgrade-command.test.ts +++ b/cli/test/integration/repository-upgrade-command.test.ts @@ -1,6 +1,6 @@ import { afterEach, expect, test } from 'bun:test' import { createHash } from 'node:crypto' -import { readFile, rm, writeFile } from 'node:fs/promises' +import { readFile, rename, rm, writeFile } from 'node:fs/promises' import { join } from 'node:path' import { zipSync, strToU8 } from 'fflate' import { createTempHome } from '../helpers/temp-env' @@ -19,14 +19,14 @@ async function fixture(count = 2) { const archives = new Map() const requests: string[] = [] const plan: RepositoryInstallPlan = { repositoryId: '42', owner: 'fixture', name: 'repo', members: [] } - const add = (slug: string, version: string) => { + const add = (slug: string, version: string, versionId?: number) => { const bytes = strToU8(`# ${slug} ${version}`) const hash = createHash('sha256').update(bytes).digest('hex') const old = plan.members.find(member => member.slug === slug) const id = old?.skillId ?? plan.members.length + 1 - const member = { skillId: id, namespace: 'github' as const, slug, displayName: slug, version, versionId: id + Number(version[0]) * 100, + const member = { skillId: id, namespace: 'github' as const, slug, displayName: slug, version, versionId: versionId ?? id + Number(version[0]) * 100, fingerprint: 'sha256:' + createHash('sha256').update(`SKILL.md:${hash}\n`).digest('hex'), - downloadUrl: `/api/cli/v1/skills/github/${slug}/versions/${version}/download` } + downloadUrl: `/api/cli/v1/skills/github/${encodeURIComponent(slug)}/versions/${encodeURIComponent(version)}/download` } archives.set(member.downloadUrl, new Uint8Array(zipSync({ 'SKILL.md': bytes })).buffer) if (old) plan.members[plan.members.indexOf(old)] = member else plan.members.push(member) @@ -129,3 +129,65 @@ test('repository checks cover more than the individual command selection limit w expect(JSON.parse(result.stdout).summary).toEqual({ upgrades: 0, unchanged: 51, blocked: 0 }) expect(f.requests.slice(start)).toEqual(['/api/cli/v1/github-repositories/42/install-plan']) }, 30000) + +const githubVersion = (hash: string, ingestion: string) => `0.0.0-g${hash.repeat(40)}-${ingestion.repeat(16)}` + +test('real GitHub versions follow verified creation order in both hash directions and on upstream revert', async () => { + for (const [before, after] of [['f', '1'], ['1', 'f']]) { + const f = await fixture(1) + f.add('skill-0', githubVersion(before!, '1'), 101) + expect((await f.run('install')).exitCode).toBe(0) + f.add('skill-0', githubVersion(after!, '2'), 201) + expect((await f.run('upgrade')).exitCode).toBe(0) + expect((await f.metadata('skill-0')).versionId).toBe(201) + // Returning to old content is a distinct later ingestion, not a downgrade. + f.add('skill-0', githubVersion(before!, '3'), 301) + expect((await f.run('upgrade')).exitCode).toBe(0) + expect((await f.metadata('skill-0')).versionId).toBe(301) + const unchanged = await f.run('check') + expect(unchanged.exitCode).toBe(0) + expect(JSON.parse(unchanged.stdout).summary.unchanged).toBe(1) + } +}) + +test('an older remote GitHub release cannot be mistaken for an upgrade by hash ordering', async () => { + const f = await fixture(1) + f.add('skill-0', githubVersion('1', '2'), 201) + expect((await f.run('install')).exitCode).toBe(0) + f.add('skill-0', githubVersion('f', '1'), 101) + const result = await f.run('upgrade') + expect(result.exitCode).toBe(6) + expect(JSON.parse(result.stdout).summary.blocked).toBe(1) + expect((await f.metadata('skill-0')).versionId).toBe(201) +}) + +test('legacy GitHub metadata without ordering evidence is protected without forced migration', async () => { + const f = await fixture(1) + f.add('skill-0', githubVersion('1', '1'), 101) + expect((await f.run('install')).exitCode).toBe(0) + const old = await f.metadata('skill-0') + delete old.versionId + await writeFile(join(f.target, 'skill-0/.skillhub/metadata.json'), JSON.stringify(old)) + expect((await f.run('check')).exitCode).toBe(0) // Exact version/fingerprint needs no ordering migration. + f.add('skill-0', githubVersion('f', '2'), 201) + expect((await f.run('upgrade')).exitCode).toBe(6) + expect((await f.metadata('skill-0')).version).toBe(old.version) + expect((await f.metadata('skill-0')).versionId).toBeUndefined() +}) + +test('disabled members are planned as protected while independent enabled members upgrade', async () => { + const f = await fixture() + expect((await f.run('install')).exitCode).toBe(0) + await rename(join(f.target, 'skill-0/SKILL.md'), join(f.target, 'skill-0/SKILL.md.disabled')) + f.add('skill-0', '2.0.0'); f.add('skill-1', '2.0.0') + const checked = await f.run('check') + expect(checked.exitCode).toBe(6) + expect(JSON.parse(checked.stdout).summary).toEqual({ upgrades: 1, unchanged: 0, blocked: 1 }) + const result = await f.run('upgrade') + expect(result.exitCode).toBe(6) + expect(JSON.parse(result.stdout).summary).toMatchObject({ upgraded: 1, blocked: 1, failed: 0 }) + expect(await Bun.file(join(f.target, 'skill-0/SKILL.md.disabled')).exists()).toBe(true) + expect(await Bun.file(join(f.target, 'skill-0/SKILL.md')).exists()).toBe(false) + expect((await f.metadata('skill-0')).version).toBe('1.0.0') + expect((await f.metadata('skill-1')).version).toBe('2.0.0') +}) diff --git a/openspec/changes/upgrade-github-repository-skills/design.md b/openspec/changes/upgrade-github-repository-skills/design.md index a30a9a4c5e..58127b9853 100644 --- a/openspec/changes/upgrade-github-repository-skills/design.md +++ b/openspec/changes/upgrade-github-repository-skills/design.md @@ -7,9 +7,9 @@ ## Decisions - 用服务器当前清单与指定 registry 下的本地 inventory 求交集,不爬取分页详情、不推测 Suite、也不只比较提交 SHA。 -- 升级规划增加内部精确版本 resolver 注入,默认升级行为保持不变。仓库编排将大选择分成不超过 50 个坐标的规划块,始终复用首次取得的固定版本清单,合并实际逐目标规划,不能重新解析 latest。 +- 升级规划增加内部精确版本 resolver 与来源专属排序器注入,默认单技能升级仍使用既有 SemVer 行为。真实 GitHub 版本为 `0.0.0-g<内容摘要>-`,哈希没有新旧顺序;仓库升级在同一 registry/namespace/slug、版本及指纹基线已核实的 metadata 中读取正整数 versionId,按同源版本创建序列判断,不将它误称为发布时间。精确版本/指纹相同时直接 unchanged;旧 metadata 缺可靠 versionId 且需要排序时保守 blocked,不做哈希排序回退或强制迁移。仓库编排将大选择分成不超过 50 个坐标的规划块,始终复用首次取得的固定版本清单,合并实际逐目标规划,不能重新解析 latest。 - 各技能 metadata 的可选 sourceRepositoryId 仅用于提示“曾来自本仓库、当前已不可用”的本地条目;更新资格仍以服务端清单为准。缺该提示的历史直接安装仍能按已验证的当前成员匹配。无法证明历史来源且当前也无法匹配时不猜测、不改文件。 -- 预期保护项保留为 blocked/not-attempted;从可执行集合排除后复用已有升级执行器。整体有保护项或失败时返回非零,同时准确保留独立成功项。执行器遇到意外失败仍沿用原有停止后续执行和逐目标回滚规则,不宣称跨文件系统事务。 +- 需要更新的 disabled 目标在规划阶段即归入 blocked,不让可预知的原生事务限制变成执行失败。预期保护项保留为 blocked/not-attempted;从可执行集合排除后复用已有升级执行器。整体有保护项或失败时返回非零,同时准确保留独立成功项。执行器遇到意外失败仍沿用原有停止后续执行和逐目标回滚规则,不宣称跨文件系统事务。 - 不提供仓库批量 force。用户明确核查单个技能后仍可选择既有单技能升级能力。 - 网页安装面板只切换三种命令:安装、检查已安装更新、升级已安装技能。更新检查说明本地才知道安装情况,不增加远端安装状态 API 或“落后 N 项”徽标。 diff --git a/openspec/changes/upgrade-github-repository-skills/specs/github-repository-upgrades/spec.md b/openspec/changes/upgrade-github-repository-skills/specs/github-repository-upgrades/spec.md index 1b2e5454bf..d1cbefe75a 100644 --- a/openspec/changes/upgrade-github-repository-skills/specs/github-repository-upgrades/spec.md +++ b/openspec/changes/upgrade-github-repository-skills/specs/github-repository-upgrades/spec.md @@ -12,12 +12,16 @@ The CLI SHALL match the repository's current accessible published plan against e - **THEN** A is checked, B is not installed, and C remains untouched with an unavailable/no-longer-listed explanation based on local provenance without guessing its hidden server state. ### Requirement: REQ-2 Version and content comparison -The CLI SHALL detect updates using exact version and content fingerprint with existing version ordering. Different upstream commit IDs alone MUST NOT generate an inconsistency warning. One invocation MUST reuse its resolved versions throughout execution. +The CLI SHALL detect updates using exact version, content fingerprint and verified same-source release creation order for hash-based GitHub versions. Different upstream commit IDs alone MUST NOT generate an inconsistency warning. One invocation MUST reuse its resolved versions throughout execution. #### Scenario: Mixed commits with unchanged content - **WHEN** installed skills match the eligible versions and fingerprints but came from different commits - **THEN** they are reported unchanged rather than inconsistent. +#### Scenario: Real GitHub hash versions and historical ordering evidence +- **WHEN** a later same-source version ID has a hash that sorts lower, or an old local record has no reliable ordering ID +- **THEN** the later known release remains upgradeable independently of hash order, and the unknown historical ordering is blocked without forced migration; exact matching version/fingerprint remains unchanged. + ### Requirement: REQ-3 Protect local state and other owners The CLI SHALL retain existing target locks, ownership, baseline checks, compare-and-swap inventory and rollback protections. Repository upgrades MUST NOT implicitly force local modifications or bypass Suite/shared ownership, disabled-state or source-identity guards. From 9f7e2d98cb3c17a0a836b1f8d6a05634a4d31e99 Mon Sep 17 00:00:00 2001 From: XiaoSeS <87064762+XiaoSeS@users.noreply.github.com> Date: Fri, 20 Nov 2026 16:41:18 +0800 Subject: [PATCH 4/4] fix(cli): isolate unverifiable installed targets during upgrade planning Signed-off-by: XiaoSeS <87064762+XiaoSeS@users.noreply.github.com> --- cli/src/services/upgrade-service.ts | 13 +++++++++++- .../repository-upgrade-command.test.ts | 20 ++++++++++++++++++- 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/cli/src/services/upgrade-service.ts b/cli/src/services/upgrade-service.ts index d1922f9663..71e92012fa 100644 --- a/cli/src/services/upgrade-service.ts +++ b/cli/src/services/upgrade-service.ts @@ -127,7 +127,18 @@ export async function planSkillUpgrades(options: UpgradeSelectionOptions): Promi continue } - const inspection = await inspectTargets(selection.item, selection.targets) + let inspection: Awaited> + try { + inspection = await inspectTargets(selection.item, selection.targets) + } catch { + items.push({ + ...base, + remoteVersion: resolved.version, + action: 'blocked', + reason: 'installed target could not be safely verified; local files were kept' + }) + continue + } const hardConflict = inspection.hardConflicts[0] if (hardConflict) { items.push({ diff --git a/cli/test/integration/repository-upgrade-command.test.ts b/cli/test/integration/repository-upgrade-command.test.ts index d2886ac8ea..ac5fac56bb 100644 --- a/cli/test/integration/repository-upgrade-command.test.ts +++ b/cli/test/integration/repository-upgrade-command.test.ts @@ -181,7 +181,7 @@ test('disabled members are planned as protected while independent enabled member await rename(join(f.target, 'skill-0/SKILL.md'), join(f.target, 'skill-0/SKILL.md.disabled')) f.add('skill-0', '2.0.0'); f.add('skill-1', '2.0.0') const checked = await f.run('check') - expect(checked.exitCode).toBe(6) + expect(checked.exitCode, checked.stderr).toBe(6) expect(JSON.parse(checked.stdout).summary).toEqual({ upgrades: 1, unchanged: 0, blocked: 1 }) const result = await f.run('upgrade') expect(result.exitCode).toBe(6) @@ -191,3 +191,21 @@ test('disabled members are planned as protected while independent enabled member expect((await f.metadata('skill-0')).version).toBe('1.0.0') expect((await f.metadata('skill-1')).version).toBe('2.0.0') }) + +test('an unverifiable disabled target is blocked without aborting safe members', async () => { + const f = await fixture() + expect((await f.run('install')).exitCode).toBe(0) + await rename(join(f.target, 'skill-0/SKILL.md'), join(f.target, 'skill-0/SKILL.md.disabled')) + const old = await f.metadata('skill-0') + await writeFile(join(f.target, 'skill-0/.skillhub/metadata.json'), JSON.stringify({ ...old, agent: 'different-agent' })) + f.add('skill-0', '2.0.0'); f.add('skill-1', '2.0.0') + const checked = await f.run('check') + expect(checked.exitCode, checked.stderr).toBe(6) + expect(JSON.parse(checked.stdout).summary).toEqual({ upgrades: 1, unchanged: 0, blocked: 1 }) + const result = await f.run('upgrade') + expect(result.exitCode, result.stderr).toBe(6) + expect(JSON.parse(result.stdout).summary).toMatchObject({ upgraded: 1, blocked: 1, failed: 0 }) + expect(await readFile(join(f.target, 'skill-0/SKILL.md.disabled'), 'utf8')).toBe('# skill-0 1.0.0') + expect((await f.metadata('skill-0')).version).toBe('1.0.0') + expect((await f.metadata('skill-1')).version).toBe('2.0.0') +})