@algotao/uiscope 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -79,13 +79,19 @@ From your **application repo** root:
79
79
  npx -y @algotao/uiscope install
80
80
  ```
81
81
 
82
- Copies the [`uiscope-ux-optimize`](skills/uiscope-ux-optimize/SKILL.md) skill to `.cursor/skills/`. User-wide install: `npx -y @algotao/uiscope install --global` (`~/.cursor/skills`).
82
+ Installs [`uiscope-ux-optimize`](skills/uiscope-ux-optimize/SKILL.md) to agent skill directories (default **auto** detect), using the same layout as [`npx skills`](https://github.com/vercel-labs/skills/blob/main/docs/agents.md) (e.g. Cursor project `.agents/skills/`, Codex/Pi `.agents/skills/`, Claude `.claude/skills/`; Cursor global `~/.cursor/skills/`).
83
+
84
+ ```bash
85
+ npx -y @algotao/uiscope install -a cursor,codex,pi
86
+ npx -y @algotao/uiscope install -g
87
+ npx -y @algotao/uiscope install agents
88
+ ```
83
89
 
84
90
  Other marketplaces:
85
91
 
86
92
  ```bash
87
- npx skills add AlgoTao-dev/uiscope
88
- pi install git:github.com/AlgoTao-dev/uiscope
93
+ npx skills add AlgoTao-dev/UIScope
94
+ pi install npm:@algotao/uiscope
89
95
  ```
90
96
 
91
97
  List options: `npx -y @algotao/uiscope install --help`.
@@ -148,7 +154,7 @@ After install use `uiscope …`; otherwise `npx -y @algotao/uiscope …` with th
148
154
 
149
155
  | Subcommand | Description |
150
156
  | --- | --- |
151
- | `install` | Install Agent skill to `.cursor/skills` (`--global` for home dir) |
157
+ | `install` | Install skill to multiple agents (`-a` / `--all` / `agents`; `-g` global; default auto) |
152
158
  | `tree` | Component nesting (library / wrapper / HTML) |
153
159
  | `styles` | Whitelist class override counts and trace chains |
154
160
  | `facets` | Facets + **core-ux** contract checks |
package/README.zh-CN.md CHANGED
@@ -79,16 +79,23 @@
79
79
  npx -y @algotao/uiscope install
80
80
  ```
81
81
 
82
- 将 [`uiscope-ux-optimize`](skills/uiscope-ux-optimize/SKILL.md) 安装到 `.cursor/skills/`。用户级:`npx -y @algotao/uiscope install --global`(`~/.cursor/skills`)。
82
+ 将 [`uiscope-ux-optimize`](skills/uiscope-ux-optimize/SKILL.md) 安装到当前机器上已识别的 Agent 目录(默认 **auto**)。路径与 [Vercel `npx skills`](https://github.com/vercel-labs/skills/blob/main/docs/agents.md) 一致,例如 Cursor 项目级 `.agents/skills/`、Codex/Pi `.agents/skills/`、Claude Code `.claude/skills/`;Cursor 用户级 `~/.cursor/skills/`。
83
83
 
84
- 其他来源:
84
+ ```bash
85
+ npx -y @algotao/uiscope install -a cursor,codex,pi # 指定 Agent
86
+ npx -y @algotao/uiscope install -g # 用户级 auto
87
+ npx -y @algotao/uiscope install agents # 列出全部 id 与路径
88
+ npx -y @algotao/uiscope install -a cursor-legacy # 仅旧版 .cursor/skills
89
+ ```
90
+
91
+ 其他来源(同 [Modern Web Guidance](https://github.com/googlechrome/modern-web-guidance)):
85
92
 
86
93
  ```bash
87
- npx skills add AlgoTao-dev/uiscope
88
- pi install git:github.com/AlgoTao-dev/uiscope
94
+ npx skills add AlgoTao-dev/UIScope
95
+ pi install npm:@algotao/uiscope
89
96
  ```
90
97
 
91
- 说明:`npx -y @algotao/uiscope install --help`。
98
+ 说明:`npx -y @algotao/uiscope install`(无子参数时等同 `install --help` 提示)。
92
99
 
93
100
  ### 不添加 devDependency 的扫描
94
101
 
@@ -109,6 +116,8 @@ uiscope all --root app --fail-on-warn
109
116
  | 全量门禁 | `uiscope all --root <dir> --fail-on-warn` |
110
117
  | 设计库默认项 | `uiscope all --preset <id> --root <dir>` |
111
118
  | 仅用 CLI 旗标 | 追加 `--no-config` |
119
+ | 库无关(不自动 preset) | `uiscope ux --no-auto-preset` |
120
+ | 自动组件库扩展 | 扫描 `package.json` 依赖 → 各 preset 的 `detectPackages` / `@algotao/preset-<id>`;stderr 打印 `auto-preset` |
112
121
 
113
122
  `--json` 输出中的 `stats` 片段示例(仅示意结构):
114
123
 
@@ -148,7 +157,7 @@ uiscope -h
148
157
 
149
158
  | 子命令 | 说明 |
150
159
  | --- | --- |
151
- | `install` | 安装 Agent 技能到 `.cursor/skills`(`--global` 为用户目录) |
160
+ | `install` | 安装技能到多 Agent(`-a` / `--all` / `agents`;`-g` 用户级;默认 auto) |
152
161
  | `tree` | 组件嵌套(库 / 封装 / HTML) |
153
162
  | `styles` | 白名单 class 重载统计与溯源链 |
154
163
  | `facets` | 切面 + **core-ux** 契约 |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@algotao/uiscope",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "displayName": "UIScope",
5
5
  "description": "Static Vue/React UI scan: component trees, style overrides, UX facets, and agent skill install.",
6
6
  "type": "module",
package/plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
3
3
  "name": "uiscope-ux-optimize",
4
- "version": "0.1.0",
4
+ "version": "0.1.2",
5
5
  "description": "UIScope — static Vue/React UI scan plus agent skill for UX and architecture optimization",
6
6
  "homepage": "https://github.com/AlgoTao-dev/UIScope",
7
7
  "repository": "https://github.com/AlgoTao-dev/UIScope",
package/presets/README.md CHANGED
@@ -8,4 +8,4 @@ Put import sources, whitelist, roles, and default thresholds in the preset’s `
8
8
  | --- | --- | --- |
9
9
  | `ocpui/` | `ocpui` | Builtin optional preset (Vue consumer narrowing, whitelist, auto `libraryRoots` when available) |
10
10
 
11
- To add a library: copy a folder, implement `UiscopePreset` (`src/config/preset-types.ts`). Site wrappers and skin globs stay in CLI flags or optional app config—not in generic core.
11
+ To add a library: copy a folder, implement `UiscopePreset` (`src/config/preset-types.ts`). Set `detectPackages` so CLI auto-preset can enable this id from `package.json` dependencies. Alternatively publish `npm:@algotao/preset-<id>`; installing that package also auto-enables `<id>`. Site wrappers and skin globs stay in CLI flags or optional app config—not in generic core.
@@ -98,6 +98,7 @@ const OCPUI_CONFIG_PATCH = {
98
98
 
99
99
  const preset: UiscopePreset = {
100
100
  id: 'ocpui',
101
+ detectPackages: ['@ocpui/vue', '@ocpui/scan', '@ocpui/core', '@ocpui/vue-admin'],
101
102
  libraryImportSources: ['@ocpui/vue', '@ocpui/vue/', '~/components/ui/ocp'],
102
103
  styleWhitelist: OCPUI_STYLE_WHITELIST,
103
104
  componentRoles: OCPUI_COMPONENT_ROLES,
@@ -17,13 +17,16 @@ description: >-
17
17
 
18
18
  ## 安装本技能
19
19
 
20
- 在**应用仓库根目录**:
20
+ 在**应用仓库根目录**(多 Agent,路径对齐 [skills.sh / Vercel skills](https://github.com/vercel-labs/skills/blob/main/docs/agents.md)):
21
21
 
22
22
  ```bash
23
- npx -y @algotao/uiscope install
23
+ npx -y @algotao/uiscope install # auto:检测本机已配置的 Agent
24
+ npx -y @algotao/uiscope install -a cursor,codex,pi
25
+ npx -y @algotao/uiscope install -g # 用户级
26
+ npx -y @algotao/uiscope install agents # 列出全部 agent id
24
27
  ```
25
28
 
26
- 用户级:`npx -y @algotao/uiscope install --global`。亦可 `npx skills add AlgoTao-dev/uiscope`。
29
+ 亦可:`npx skills add AlgoTao-dev/UIScope`、`pi install npm:@algotao/uiscope`(同 [Modern Web Guidance](https://github.com/googlechrome/modern-web-guidance))。
27
30
 
28
31
  ## CLI 与执行入口
29
32
 
@@ -58,7 +61,16 @@ uiscope ux --root <dir> --enhance-all --out <repo>/.local/<name>.md
58
61
  uiscope all --config <path-to-style-audit.config.ts> --json > .local/uiscope-style-audit.json
59
62
  ```
60
63
 
61
- `--out` 生成同名 `.json`。**跨文件对比**优先 JSON 或完整 Markdown;**单目录快览**可用终端摘要。参数与配置见 npm 包内 `README.md`、`uiscope -h`。若项目通过 **`presets: ['<id>']`**(包内 `presets/<id>/` 或外置模块)接入设计库,在配置或 CLI 中声明即可,本技能不假定具体库名。
64
+ `--out` 生成同名 `.json`。**跨文件对比**优先 JSON 或完整 Markdown;**单目录快览**可用终端摘要。参数与配置见 npm 包内 `README.md`、`uiscope -h`。
65
+
66
+ **组件库 preset(推荐由 CLI 自动处理,技能不写死库名)**
67
+
68
+ - 未指定 `--preset` 且未在 `uiscope.config.*` 里声明时,CLI **默认**扫描 `package.json` 依赖:命中各 preset 的 `detectPackages` 或 `@algotao/preset-<id>` 即启用,stderr 打印 `auto-preset: …`(内核不写死库名)。
69
+ - **库无关**全量扫描:`uiscope ux --root <dir> --no-auto-preset`(可与 `--no-config` 联用)。
70
+ - **显式覆盖**:`--preset <id>` 或配置文件 `presets`。
71
+ - **关闭自动**:`package.json` 内 `"uiscope": { "autoPreset": false }`。
72
+
73
+ Agent 优先执行带上述默认行为的 `npx -y @algotao/uiscope …`,勿在技能正文里硬编码单一组件库命令。
62
74
 
63
75
  大报告勿整文件读入上下文:先 `uiscope read --file <.json>` 看条数,再 `--section uxFindings --offset <n> --limit <m>`;或对 `.md` 用 `--lines start-end`。程序化 API 见 README「程序化 API」。
64
76
 
@@ -0,0 +1,17 @@
1
+ # Skill runner
2
+
3
+ This directory ships with the agent skill, not the full UIScope scanner.
4
+
5
+ | File | Role |
6
+ | --- | --- |
7
+ | `uiscope.mjs` | Forwards argv to `@algotao/uiscope` CLI (`bin/uiscope.js`) when the package is installed in the project |
8
+
9
+ **Without** a local `devDependency`, agents should run:
10
+
11
+ ```bash
12
+ npx -y @algotao/uiscope <subcommand> …
13
+ ```
14
+
15
+ Scan logic, presets, and reports live in the npm package; the skill body (`../SKILL.md`) describes workflow and guardrails.
16
+
17
+ **Updates** (CLI only, not in SKILL.md): `uiscope install` compares `.uiscope-version` in the skill folder and refreshes when the running CLI is newer; `uiscope version --check` queries npm; `install --force` overwrites regardless.
@@ -7,14 +7,17 @@ import { fileURLToPath } from 'node:url';
7
7
 
8
8
  const scriptDir = path.dirname(fileURLToPath(import.meta.url));
9
9
 
10
- function resolvePackageRoot() {
10
+ function resolveCliPath() {
11
11
  const require = createRequire(import.meta.url);
12
12
  try {
13
- return path.dirname(require.resolve('@algotao/uiscope/package.json'));
13
+ return require.resolve('@algotao/uiscope/bin/uiscope.js');
14
14
  } catch {
15
+ const fromPkgSkill = path.resolve(scriptDir, '../../../..');
16
+ const nested = path.join(fromPkgSkill, 'bin/uiscope.js');
17
+ if (fs.existsSync(nested)) return nested;
15
18
  const fromSkillLayout = path.resolve(scriptDir, '../../..');
16
19
  if (fs.existsSync(path.join(fromSkillLayout, 'bin/uiscope.js'))) {
17
- return fromSkillLayout;
20
+ return path.join(fromSkillLayout, 'bin/uiscope.js');
18
21
  }
19
22
  throw new Error(
20
23
  [
@@ -26,7 +29,7 @@ function resolvePackageRoot() {
26
29
  }
27
30
  }
28
31
 
29
- const cli = path.join(resolvePackageRoot(), 'bin/uiscope.js');
32
+ const cli = resolveCliPath();
30
33
  const child = spawnSync(process.execPath, [cli, ...process.argv.slice(2)], {
31
34
  stdio: 'inherit',
32
35
  cwd: process.cwd(),
@@ -0,0 +1,64 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { afterEach, describe, expect, it } from 'vitest';
5
+ import { detectPresetsFromProject, resolveAutoPresets } from '../config/detect-presets.js';
6
+
7
+ describe('detect presets', () => {
8
+ const dirs: string[] = [];
9
+ afterEach(() => {
10
+ for (const d of dirs) fs.rmSync(d, { recursive: true, force: true });
11
+ dirs.length = 0;
12
+ });
13
+
14
+ it('detects ocpui from @ocpui/vue via preset detectPackages', async () => {
15
+ const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'uiscope-detect-'));
16
+ dirs.push(cwd);
17
+ fs.writeFileSync(
18
+ path.join(cwd, 'package.json'),
19
+ JSON.stringify({ dependencies: { '@ocpui/vue': '1.0.0' } }),
20
+ );
21
+ await expect(detectPresetsFromProject(cwd)).resolves.toEqual(['ocpui']);
22
+ });
23
+
24
+ it('detects preset id from @algotao/preset-* dependency', async () => {
25
+ const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'uiscope-detect-'));
26
+ dirs.push(cwd);
27
+ fs.writeFileSync(
28
+ path.join(cwd, 'package.json'),
29
+ JSON.stringify({ devDependencies: { '@algotao/preset-acme': '0.0.1' } }),
30
+ );
31
+ await expect(detectPresetsFromProject(cwd)).resolves.toEqual(['acme']);
32
+ });
33
+
34
+ it('skips auto when --no-auto-preset', async () => {
35
+ const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'uiscope-detect-'));
36
+ dirs.push(cwd);
37
+ fs.writeFileSync(
38
+ path.join(cwd, 'package.json'),
39
+ JSON.stringify({ dependencies: { '@ocpui/vue': '1.0.0' } }),
40
+ );
41
+ const r = await resolveAutoPresets({
42
+ cwd,
43
+ existingPresets: [],
44
+ cliPresets: [],
45
+ noAutoPreset: true,
46
+ });
47
+ expect(r.presets).toEqual([]);
48
+ expect(r.autoApplied).toEqual([]);
49
+ });
50
+
51
+ it('respects package.json uiscope.autoPreset=false', async () => {
52
+ const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'uiscope-detect-'));
53
+ dirs.push(cwd);
54
+ fs.writeFileSync(
55
+ path.join(cwd, 'package.json'),
56
+ JSON.stringify({
57
+ dependencies: { '@ocpui/vue': '1.0.0' },
58
+ uiscope: { autoPreset: false },
59
+ }),
60
+ );
61
+ const r = await resolveAutoPresets({ cwd, existingPresets: [], cliPresets: [], noAutoPreset: false });
62
+ expect(r.autoApplied).toEqual([]);
63
+ });
64
+ });
@@ -17,22 +17,41 @@ describe('install skill', () => {
17
17
  tmpRoots.length = 0;
18
18
  });
19
19
 
20
- it('copies skill into project .cursor/skills', () => {
20
+ it('copies skill into default multi-agent project paths', async () => {
21
21
  const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'uiscope-install-'));
22
22
  tmpRoots.push(cwd);
23
- const code = runInstallSkill(cwd, { dryRun: false });
23
+ const code = await runInstallSkill(cwd, { dryRun: false, agents: ['cursor', 'codex'] });
24
24
  expect(code).toBe(0);
25
- const skillMd = path.join(cwd, '.cursor/skills/uiscope-ux-optimize/SKILL.md');
26
- expect(fs.existsSync(skillMd)).toBe(true);
27
- expect(fs.readFileSync(skillMd, 'utf8')).toContain('uiscope-ux-optimize');
25
+ const agentsSkillMd = path.join(cwd, '.agents/skills/uiscope-ux-optimize/SKILL.md');
26
+ expect(fs.existsSync(agentsSkillMd)).toBe(true);
27
+ expect(fs.readFileSync(agentsSkillMd, 'utf8')).toContain('uiscope-ux-optimize');
28
28
  });
29
29
 
30
- it('dry-run does not write files', () => {
30
+ it('supports cursor-legacy .cursor/skills path', async () => {
31
+ const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'uiscope-install-legacy-'));
32
+ tmpRoots.push(cwd);
33
+ const code = await runInstallSkill(cwd, { agents: ['cursor-legacy'] });
34
+ expect(code).toBe(0);
35
+ expect(fs.existsSync(path.join(cwd, '.cursor/skills/uiscope-ux-optimize/SKILL.md'))).toBe(true);
36
+ });
37
+
38
+ it('dry-run does not write files', async () => {
31
39
  const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'uiscope-install-dry-'));
32
40
  tmpRoots.push(cwd);
33
- const code = runInstallSkill(cwd, { dryRun: true });
41
+ const code = await runInstallSkill(cwd, { dryRun: true, agents: ['pi'] });
34
42
  expect(code).toBe(0);
35
- expect(fs.existsSync(path.join(cwd, '.cursor/skills/uiscope-ux-optimize'))).toBe(false);
43
+ expect(fs.existsSync(path.join(cwd, '.agents/skills/uiscope-ux-optimize'))).toBe(false);
44
+ });
45
+
46
+ it('skips re-copy when skill stamp matches current version', async () => {
47
+ const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'uiscope-install-skip-'));
48
+ tmpRoots.push(cwd);
49
+ expect(await runInstallSkill(cwd, { agents: ['pi'], checkUpdate: false })).toBe(0);
50
+ const skillDir = path.join(cwd, '.agents/skills/uiscope-ux-optimize');
51
+ const mtime1 = fs.statSync(path.join(skillDir, 'SKILL.md')).mtimeMs;
52
+ expect(await runInstallSkill(cwd, { agents: ['pi'], checkUpdate: false })).toBe(0);
53
+ const mtime2 = fs.statSync(path.join(skillDir, 'SKILL.md')).mtimeMs;
54
+ expect(mtime2).toBe(mtime1);
36
55
  });
37
56
 
38
57
  it('skill source exists in package', () => {
@@ -0,0 +1,18 @@
1
+ import path from 'node:path';
2
+ import { describe, expect, it } from 'vitest';
3
+ import { collectInstallDestinations } from '../cli/install-targets.js';
4
+
5
+ describe('install targets', () => {
6
+ it('dedupes codex and pi to one .agents/skills destination', () => {
7
+ const cwd = path.join('tmp', 'proj');
8
+ const dests = collectInstallDestinations(['codex', 'pi', 'cursor'], false, cwd, 'uiscope-ux-optimize');
9
+ const expectDest = path.join(cwd, '.agents/skills/uiscope-ux-optimize');
10
+ const agentsRoot = dests.find((d) => path.normalize(d.destDir) === path.normalize(expectDest));
11
+ expect(agentsRoot).toBeDefined();
12
+ expect(agentsRoot!.agentIds).toEqual(expect.arrayContaining(['codex', 'pi', 'cursor']));
13
+ const agentsSkillPaths = dests.filter((d) =>
14
+ path.normalize(d.destDir).includes(path.normalize('.agents/skills')),
15
+ );
16
+ expect(agentsSkillPaths.length).toBe(1);
17
+ });
18
+ });
@@ -0,0 +1,53 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { afterEach, describe, expect, it } from 'vitest';
7
+ import { runInstallSkill } from '../cli/install-skill.js';
8
+
9
+ const pkgRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
10
+
11
+ describe('skill forwarder uiscope.mjs', () => {
12
+ const tmpRoots: string[] = [];
13
+
14
+ afterEach(() => {
15
+ for (const root of tmpRoots) {
16
+ fs.rmSync(root, { recursive: true, force: true });
17
+ }
18
+ tmpRoots.length = 0;
19
+ });
20
+
21
+ it(
22
+ 'forwards to published-layout CLI after npm install',
23
+ async () => {
24
+ const packDir = fs.mkdtempSync(path.join(os.tmpdir(), 'uiscope-pack-'));
25
+ tmpRoots.push(packDir);
26
+ const pack = spawnSync('npm', ['pack', '--pack-destination', packDir], {
27
+ cwd: pkgRoot,
28
+ encoding: 'utf8',
29
+ shell: true,
30
+ });
31
+ expect(pack.status).toBe(0);
32
+ const tgz = pack.stdout
33
+ .trim()
34
+ .split(/\r?\n/)
35
+ .filter((l) => l.endsWith('.tgz'))
36
+ .pop();
37
+ expect(tgz).toBeTruthy();
38
+
39
+ const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'uiscope-fwd-'));
40
+ tmpRoots.push(cwd);
41
+ expect(spawnSync('npm', ['init', '-y'], { cwd, shell: true }).status).toBe(0);
42
+ const install = spawnSync('npm', ['install', path.join(packDir, tgz!)], { cwd, shell: true });
43
+ expect(install.status).toBe(0);
44
+
45
+ expect(await runInstallSkill(cwd, { agents: ['pi'] })).toBe(0);
46
+ const script = path.join(cwd, '.agents/skills/uiscope-ux-optimize/scripts/uiscope.mjs');
47
+ const r = spawnSync(process.execPath, [script, '--help'], { cwd, encoding: 'utf8' });
48
+ expect(r.status, r.stderr).toBe(0);
49
+ expect(r.stdout).toContain('uiscope [install');
50
+ },
51
+ 120_000,
52
+ );
53
+ });
@@ -0,0 +1,41 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { afterEach, describe, expect, it } from 'vitest';
5
+ import { isSemverGreater } from '../cli/package-version.js';
6
+ import {
7
+ planSkillUpdates,
8
+ readSkillInstallVersion,
9
+ writeSkillInstallVersion,
10
+ } from '../cli/skill-install-stamp.js';
11
+ import { readPackageVersion } from '../cli/package-version.js';
12
+
13
+ describe('skill install stamp', () => {
14
+ const dirs: string[] = [];
15
+ afterEach(() => {
16
+ for (const d of dirs) fs.rmSync(d, { recursive: true, force: true });
17
+ dirs.length = 0;
18
+ });
19
+
20
+ it('skips copy when stamp matches current package version', () => {
21
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'uiscope-stamp-'));
22
+ dirs.push(dir);
23
+ writeSkillInstallVersion(dir, readPackageVersion());
24
+ const plan = planSkillUpdates([dir], false);
25
+ expect(plan[0]!.needsUpdate).toBe(false);
26
+ });
27
+
28
+ it('plans update when stamp is older', () => {
29
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'uiscope-stamp-'));
30
+ dirs.push(dir);
31
+ writeSkillInstallVersion(dir, '0.0.1');
32
+ const plan = planSkillUpdates([dir], false);
33
+ expect(plan[0]!.needsUpdate).toBe(true);
34
+ expect(readSkillInstallVersion(dir)).toBe('0.0.1');
35
+ });
36
+
37
+ it('semver greater', () => {
38
+ expect(isSemverGreater('0.1.2', '0.1.1')).toBe(true);
39
+ expect(isSemverGreater('0.1.1', '0.1.1')).toBe(false);
40
+ });
41
+ });
@@ -0,0 +1,54 @@
1
+ import { cliTag } from './brand.js';
2
+ import { isSemverGreater, readPackageVersion } from './package-version.js';
3
+
4
+ const NPM_REGISTRY = 'https://registry.npmjs.org';
5
+ const PACKAGE_NAME = '@algotao/uiscope';
6
+
7
+ export async function fetchNpmLatestVersion(
8
+ packageName = PACKAGE_NAME,
9
+ timeoutMs = 4_000,
10
+ ): Promise<string | undefined> {
11
+ const encoded = packageName.replace('/', '%2f');
12
+ const controller = new AbortController();
13
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
14
+ try {
15
+ const res = await fetch(`${NPM_REGISTRY}/${encoded}`, {
16
+ signal: controller.signal,
17
+ headers: { accept: 'application/json' },
18
+ });
19
+ if (!res.ok) return undefined;
20
+ const body = (await res.json()) as { 'dist-tags'?: { latest?: string } };
21
+ return body['dist-tags']?.latest;
22
+ } catch {
23
+ return undefined;
24
+ } finally {
25
+ clearTimeout(timer);
26
+ }
27
+ }
28
+
29
+ export async function printVersionStatus(checkRegistry: boolean): Promise<number> {
30
+ const current = readPackageVersion();
31
+ console.log(`${cliTag('version')} @algotao/uiscope ${current}`);
32
+ if (!checkRegistry) return 0;
33
+ const latest = await fetchNpmLatestVersion();
34
+ if (!latest) {
35
+ console.log(`${cliTag('version')} registry 未响应(可稍后重试)`);
36
+ return 0;
37
+ }
38
+ console.log(`${cliTag('version')} npm latest ${latest}`);
39
+ if (isSemverGreater(latest, current)) {
40
+ console.log(`${cliTag('version')} 有新版本 → npx -y @algotao/uiscope@${latest} install`);
41
+ return 0;
42
+ }
43
+ console.log(`${cliTag('version')} 当前已是最新发行版`);
44
+ return 0;
45
+ }
46
+
47
+ export async function warnIfNewerOnRegistry(scope: string): Promise<void> {
48
+ const current = readPackageVersion();
49
+ const latest = await fetchNpmLatestVersion();
50
+ if (!latest || !isSemverGreater(latest, current)) return;
51
+ console.log(
52
+ `${cliTag(scope)} npm 已有较新版本 ${latest}(当前 CLI ${current})→ npx -y @algotao/uiscope@${latest} install`,
53
+ );
54
+ }
@@ -1,15 +1,28 @@
1
1
  import fs from 'node:fs';
2
- import os from 'node:os';
3
2
  import path from 'node:path';
4
3
  import { fileURLToPath } from 'node:url';
4
+ import { warnIfNewerOnRegistry } from './check-update.js';
5
5
  import { cliTag } from './brand.js';
6
+ import { readPackageVersion } from './package-version.js';
7
+ import { planSkillUpdates, writeSkillInstallVersion } from './skill-install-stamp.js';
8
+ import {
9
+ collectInstallDestinations,
10
+ formatAgentTable,
11
+ knownAgentIds,
12
+ resolveInstallAgentIds,
13
+ } from './install-targets.js';
6
14
 
7
- const REPO = 'https://github.com/AlgoTao-dev/uiscope';
15
+ const REPO_SLUG = 'AlgoTao-dev/UIScope';
8
16
  const SKILL_DIR = 'uiscope-ux-optimize';
9
17
 
10
18
  export type InstallSkillOptions = {
11
19
  global?: boolean;
12
20
  dryRun?: boolean;
21
+ agents?: string[];
22
+ allAgents?: boolean;
23
+ listAgents?: boolean;
24
+ force?: boolean;
25
+ checkUpdate?: boolean;
13
26
  };
14
27
 
15
28
  function packageRoot(): string {
@@ -20,13 +33,6 @@ function skillSourceDir(): string {
20
33
  return path.join(packageRoot(), 'skills', SKILL_DIR);
21
34
  }
22
35
 
23
- function defaultTargetDir(global: boolean, cwd: string): string {
24
- const base = global
25
- ? path.join(os.homedir(), '.cursor', 'skills')
26
- : path.join(cwd, '.cursor', 'skills');
27
- return path.join(base, SKILL_DIR);
28
- }
29
-
30
36
  function copyDir(src: string, dest: string): void {
31
37
  fs.mkdirSync(dest, { recursive: true });
32
38
  for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
@@ -37,54 +43,160 @@ function copyDir(src: string, dest: string): void {
37
43
  }
38
44
  }
39
45
 
46
+ function writeSkillTo(dest: string, src: string): void {
47
+ if (fs.existsSync(dest)) {
48
+ for (const entry of fs.readdirSync(dest)) {
49
+ fs.rmSync(path.join(dest, entry), { recursive: true, force: true });
50
+ }
51
+ }
52
+ copyDir(src, dest);
53
+ }
54
+
40
55
  export function printInstallHints(): void {
41
- console.log(`${cliTag('install')} Agent skill — ${REPO}`);
56
+ console.log(`${cliTag('install')} Agent skill — https://github.com/${REPO_SLUG}`);
42
57
  console.log('');
43
- console.log('This package (recommended):');
44
- console.log(' npx -y @algotao/uiscope install # .cursor/skills in current project');
45
- console.log(' npx -y @algotao/uiscope install --global # ~/.cursor/skills');
58
+ console.log('Multi-agent (built-in, same paths as npx skills):');
59
+ console.log(' npx -y @algotao/uiscope install # auto-detect agents in this project');
60
+ console.log(' npx -y @algotao/uiscope install -g # auto-detect in home directory');
61
+ console.log(' npx -y @algotao/uiscope install -a cursor,codex,pi,claude-code');
62
+ console.log(' npx -y @algotao/uiscope install --all # every supported agent path (deduped)');
63
+ console.log(' npx -y @algotao/uiscope install agents # list agent ids and paths');
64
+ console.log(' npx -y @algotao/uiscope install --force # re-copy even if skill version matches');
65
+ console.log(' npx -y @algotao/uiscope version --check # compare CLI vs npm latest');
46
66
  console.log('');
47
- console.log('Alternative registries:');
48
- console.log(' npx skills add AlgoTao-dev/uiscope');
49
- console.log(` pi install git:github.com/AlgoTao-dev/uiscope`);
67
+ console.log('Ecosystem installers (Modern Web Guidance style):');
68
+ console.log(` npx skills add ${REPO_SLUG}`);
69
+ console.log(' pi install npm:@algotao/uiscope');
70
+ console.log(` pi install git:github.com/${REPO_SLUG}`);
50
71
  console.log('');
51
- console.log('After install, agents use the skill to run `uiscope` / `npx -y @algotao/uiscope …` on your app.');
72
+ console.log('After install, run `uiscope` / `npx -y @algotao/uiscope …` on your app.');
52
73
  console.log(`Skill source: skills/${SKILL_DIR}/SKILL.md`);
53
74
  }
54
75
 
55
- export function runInstallSkill(cwd: string, options: InstallSkillOptions): number {
76
+ export function printAgentTable(): void {
77
+ console.log(formatAgentTable());
78
+ console.log('');
79
+ console.log(`Known ids (${knownAgentIds().length}): ${knownAgentIds().join(', ')}`);
80
+ }
81
+
82
+ export async function runInstallSkill(cwd: string, options: InstallSkillOptions): Promise<number> {
83
+ if (options.listAgents) {
84
+ printAgentTable();
85
+ return 0;
86
+ }
87
+
56
88
  const src = skillSourceDir();
57
89
  if (!fs.existsSync(path.join(src, 'SKILL.md'))) {
58
90
  console.error(`${cliTag('install')} skill source missing: ${src}`);
59
- console.error('Run from the npm package, or: npx skills add AlgoTao-dev/uiscope');
91
+ console.error(`Run from the npm package, or: npx skills add ${REPO_SLUG}`);
60
92
  return 1;
61
93
  }
62
94
 
63
- const dest = defaultTargetDir(Boolean(options.global), cwd);
64
- if (options.dryRun) {
65
- console.log(`${cliTag('install')} dry-run: ${src} → ${dest}`);
66
- return 0;
95
+ let agentIds: string[];
96
+ try {
97
+ agentIds = resolveInstallAgentIds(options.agents, Boolean(options.allAgents), Boolean(options.global), cwd);
98
+ } catch (e) {
99
+ console.error(`${cliTag('install')} ${e instanceof Error ? e.message : String(e)}`);
100
+ console.error(`${cliTag('install')} Run: npx -y @algotao/uiscope install agents`);
101
+ return 1;
67
102
  }
68
103
 
69
- if (fs.existsSync(dest)) {
70
- for (const entry of fs.readdirSync(dest)) {
71
- const p = path.join(dest, entry);
72
- fs.rmSync(p, { recursive: true, force: true });
104
+ const destinations = collectInstallDestinations(agentIds, Boolean(options.global), cwd, SKILL_DIR);
105
+ if (destinations.length === 0) {
106
+ console.error(`${cliTag('install')} no install destinations resolved`);
107
+ return 1;
108
+ }
109
+
110
+ const scope = options.global ? 'global' : 'project';
111
+ const currentVersion = readPackageVersion();
112
+ console.log(`${cliTag('install')} scope=${scope} agents=${agentIds.join(', ')} cli@${currentVersion}`);
113
+
114
+ const destDirs = destinations.map((d) => d.destDir);
115
+ const plans = planSkillUpdates(destDirs, Boolean(options.force));
116
+
117
+ for (const { destDir, agentIds: destAgents } of destinations) {
118
+ const plan = plans.find((p) => p.skillDestDir === destDir);
119
+ if (options.dryRun) {
120
+ const action = plan?.needsUpdate ? 'refresh' : 'skip (up to date)';
121
+ console.log(`${cliTag('install')} dry-run: ${src} → ${destDir} (${destAgents.join(', ')}) ${action}`);
122
+ continue;
123
+ }
124
+ if (plan && !plan.needsUpdate) {
125
+ console.log(
126
+ `${cliTag('install')} up to date → ${destDir} (skill ${plan.installedVersion}) [${destAgents.join(', ')}]`,
127
+ );
128
+ continue;
73
129
  }
130
+ if (plan?.installedVersion) {
131
+ console.log(`${cliTag('install')} update ${plan.installedVersion} → ${currentVersion} → ${destDir}`);
132
+ }
133
+ writeSkillTo(destDir, src);
134
+ writeSkillInstallVersion(destDir, currentVersion);
135
+ console.log(`${cliTag('install')} installed → ${destDir} [${destAgents.join(', ')}]`);
74
136
  }
75
137
 
76
- copyDir(src, dest);
77
- console.log(`${cliTag('install')} installed → ${dest}`);
78
- console.log(`${cliTag('install')} scan: npx -y @algotao/uiscope ux --root <dir>`);
138
+ if (!options.dryRun) {
139
+ console.log(`${cliTag('install')} scan: npx -y @algotao/uiscope ux --root <dir>`);
140
+ if (options.checkUpdate !== false) {
141
+ await warnIfNewerOnRegistry('install');
142
+ }
143
+ }
79
144
  return 0;
80
145
  }
81
146
 
82
147
  export function parseInstallArgs(argv: string[]): InstallSkillOptions {
83
148
  let global = false;
84
149
  let dryRun = false;
85
- for (const arg of argv) {
86
- if (arg === '--global' || arg === '-g') global = true;
87
- if (arg === '--dry-run') dryRun = true;
150
+ let allAgents = false;
151
+ let listAgents = false;
152
+ let force = false;
153
+ let checkUpdate = true;
154
+ const agents: string[] = [];
155
+
156
+ for (let i = 0; i < argv.length; i++) {
157
+ const arg = argv[i]!;
158
+ if (arg === '--global' || arg === '-g') {
159
+ global = true;
160
+ continue;
161
+ }
162
+ if (arg === '--dry-run') {
163
+ dryRun = true;
164
+ continue;
165
+ }
166
+ if (arg === '--all') {
167
+ allAgents = true;
168
+ continue;
169
+ }
170
+ if (arg === '--force' || arg === '-f') {
171
+ force = true;
172
+ continue;
173
+ }
174
+ if (arg === '--no-check-update') {
175
+ checkUpdate = false;
176
+ continue;
177
+ }
178
+ if (arg === 'agents' || arg === 'list-agents') {
179
+ listAgents = true;
180
+ continue;
181
+ }
182
+ if (arg === '--agent' || arg === '-a') {
183
+ const next = argv[++i];
184
+ if (next) agents.push(next);
185
+ continue;
186
+ }
187
+ if (arg.startsWith('--agent=')) {
188
+ agents.push(arg.slice('--agent='.length));
189
+ continue;
190
+ }
88
191
  }
89
- return { global, dryRun };
192
+
193
+ return {
194
+ global,
195
+ dryRun,
196
+ agents: agents.length ? agents : undefined,
197
+ allAgents,
198
+ listAgents,
199
+ force,
200
+ checkUpdate,
201
+ };
90
202
  }
@@ -0,0 +1,185 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+
5
+ /** Paths align with https://github.com/vercel-labs/skills/blob/main/docs/agents.md */
6
+ export type AgentSkillsLayout = {
7
+ id: string;
8
+ projectSkillsRoot: string;
9
+ globalSkillsRoot: string;
10
+ };
11
+
12
+ export const AGENT_SKILL_LAYOUTS: AgentSkillsLayout[] = [
13
+ { id: 'aider-desk', projectSkillsRoot: '.aider-desk/skills', globalSkillsRoot: '.aider-desk/skills' },
14
+ { id: 'amp', projectSkillsRoot: '.agents/skills', globalSkillsRoot: '.config/agents/skills' },
15
+ { id: 'replit', projectSkillsRoot: '.agents/skills', globalSkillsRoot: '.config/agents/skills' },
16
+ { id: 'universal', projectSkillsRoot: '.agents/skills', globalSkillsRoot: '.config/agents/skills' },
17
+ { id: 'antigravity', projectSkillsRoot: '.agents/skills', globalSkillsRoot: '.gemini/config/skills' },
18
+ { id: 'antigravity-cli', projectSkillsRoot: '.agents/skills', globalSkillsRoot: '.gemini/config/skills' },
19
+ { id: 'astrbot', projectSkillsRoot: 'data/skills', globalSkillsRoot: '.astrbot/data/skills' },
20
+ { id: 'autohand-code', projectSkillsRoot: '.autohand/skills', globalSkillsRoot: '.autohand/skills' },
21
+ { id: 'augment', projectSkillsRoot: '.augment/skills', globalSkillsRoot: '.augment/skills' },
22
+ { id: 'bob', projectSkillsRoot: '.bob/skills', globalSkillsRoot: '.bob/skills' },
23
+ { id: 'claude-code', projectSkillsRoot: '.claude/skills', globalSkillsRoot: '.claude/skills' },
24
+ { id: 'openclaw', projectSkillsRoot: 'skills', globalSkillsRoot: '.openclaw/skills' },
25
+ { id: 'cline', projectSkillsRoot: '.agents/skills', globalSkillsRoot: '.agents/skills' },
26
+ { id: 'codex', projectSkillsRoot: '.agents/skills', globalSkillsRoot: '.agents/skills' },
27
+ { id: 'dexto', projectSkillsRoot: '.agents/skills', globalSkillsRoot: '.agents/skills' },
28
+ { id: 'fx', projectSkillsRoot: '.agents/skills', globalSkillsRoot: '.agents/skills' },
29
+ { id: 'kimi-code-cli', projectSkillsRoot: '.agents/skills', globalSkillsRoot: '.agents/skills' },
30
+ { id: 'loaf', projectSkillsRoot: '.agents/skills', globalSkillsRoot: '.agents/skills' },
31
+ { id: 'pi', projectSkillsRoot: '.agents/skills', globalSkillsRoot: '.agents/skills' },
32
+ { id: 'sarvam-code', projectSkillsRoot: '.agents/skills', globalSkillsRoot: '.agents/skills' },
33
+ { id: 'warp', projectSkillsRoot: '.agents/skills', globalSkillsRoot: '.agents/skills' },
34
+ { id: 'zed', projectSkillsRoot: '.agents/skills', globalSkillsRoot: '.agents/skills' },
35
+ { id: 'codearts-agent', projectSkillsRoot: '.codeartsdoer/skills', globalSkillsRoot: '.codeartsdoer/skills' },
36
+ { id: 'codebuddy', projectSkillsRoot: '.codebuddy/skills', globalSkillsRoot: '.codebuddy/skills' },
37
+ { id: 'codemaker', projectSkillsRoot: '.codemaker/skills', globalSkillsRoot: '.codemaker/skills' },
38
+ { id: 'codestudio', projectSkillsRoot: '.codestudio/skills', globalSkillsRoot: '.codestudio/skills' },
39
+ { id: 'command-code', projectSkillsRoot: '.commandcode/skills', globalSkillsRoot: '.commandcode/skills' },
40
+ { id: 'continue', projectSkillsRoot: '.continue/skills', globalSkillsRoot: '.continue/skills' },
41
+ { id: 'cortex', projectSkillsRoot: '.cortex/skills', globalSkillsRoot: '.snowflake/cortex/skills' },
42
+ { id: 'crush', projectSkillsRoot: '.crush/skills', globalSkillsRoot: '.config/crush/skills' },
43
+ { id: 'cursor', projectSkillsRoot: '.agents/skills', globalSkillsRoot: '.cursor/skills' },
44
+ { id: 'cursor-legacy', projectSkillsRoot: '.cursor/skills', globalSkillsRoot: '.cursor/skills' },
45
+ { id: 'deepagents', projectSkillsRoot: '.agents/skills', globalSkillsRoot: '.deepagents/agent/skills' },
46
+ { id: 'devin', projectSkillsRoot: '.devin/skills', globalSkillsRoot: '.config/devin/skills' },
47
+ { id: 'droid', projectSkillsRoot: '.agents/skills', globalSkillsRoot: '.factory/skills' },
48
+ { id: 'firebender', projectSkillsRoot: '.agents/skills', globalSkillsRoot: '.firebender/skills' },
49
+ { id: 'forgecode', projectSkillsRoot: '.forge/skills', globalSkillsRoot: '.forge/skills' },
50
+ { id: 'gemini-cli', projectSkillsRoot: '.agents/skills', globalSkillsRoot: '.gemini/skills' },
51
+ { id: 'github-copilot', projectSkillsRoot: '.agents/skills', globalSkillsRoot: '.copilot/skills' },
52
+ { id: 'goose', projectSkillsRoot: '.goose/skills', globalSkillsRoot: '.config/goose/skills' },
53
+ { id: 'grok', projectSkillsRoot: '.grok/skills', globalSkillsRoot: '.grok/skills' },
54
+ { id: 'hermes-agent', projectSkillsRoot: '.hermes/skills', globalSkillsRoot: '.hermes/skills' },
55
+ { id: 'inference-sh', projectSkillsRoot: '.inferencesh/skills', globalSkillsRoot: '.inferencesh/skills' },
56
+ { id: 'jazz', projectSkillsRoot: '.jazz/skills', globalSkillsRoot: '.jazz/skills' },
57
+ { id: 'junie', projectSkillsRoot: '.junie/skills', globalSkillsRoot: '.junie/skills' },
58
+ { id: 'iflow-cli', projectSkillsRoot: '.iflow/skills', globalSkillsRoot: '.iflow/skills' },
59
+ { id: 'kilo', projectSkillsRoot: '.agents/skills', globalSkillsRoot: '.kilo/skills' },
60
+ { id: 'kimchi', projectSkillsRoot: '.kimchi/skills', globalSkillsRoot: '.config/kimchi/harness/skills' },
61
+ { id: 'kiro-cli', projectSkillsRoot: '.kiro/skills', globalSkillsRoot: '.kiro/skills' },
62
+ { id: 'kode', projectSkillsRoot: '.kode/skills', globalSkillsRoot: '.kode/skills' },
63
+ { id: 'lingma', projectSkillsRoot: '.lingma/skills', globalSkillsRoot: '.lingma/skills' },
64
+ { id: 'mcpjam', projectSkillsRoot: '.mcpjam/skills', globalSkillsRoot: '.mcpjam/skills' },
65
+ { id: 'minimax-code', projectSkillsRoot: '.minimax/skills', globalSkillsRoot: '.minimax/skills' },
66
+ { id: 'mistral-vibe', projectSkillsRoot: '.vibe/skills', globalSkillsRoot: '.vibe/skills' },
67
+ { id: 'moxby', projectSkillsRoot: '.moxby/skills', globalSkillsRoot: '.moxby/skills' },
68
+ { id: 'mux', projectSkillsRoot: '.mux/skills', globalSkillsRoot: '.mux/skills' },
69
+ { id: 'opencode', projectSkillsRoot: '.agents/skills', globalSkillsRoot: '.config/opencode/skills' },
70
+ { id: 'openhands', projectSkillsRoot: '.openhands/skills', globalSkillsRoot: '.openhands/skills' },
71
+ { id: 'ona', projectSkillsRoot: '.ona/skills', globalSkillsRoot: '.ona/skills' },
72
+ { id: 'posit-assistant', projectSkillsRoot: '.posit/assistant/skills', globalSkillsRoot: '.posit/assistant/skills' },
73
+ { id: 'qoder', projectSkillsRoot: '.qoder/skills', globalSkillsRoot: '.qoder/skills' },
74
+ { id: 'qoder-cn', projectSkillsRoot: '.qoder/skills', globalSkillsRoot: '.qoder-cn/skills' },
75
+ { id: 'qwen-code', projectSkillsRoot: '.qwen/skills', globalSkillsRoot: '.qwen/skills' },
76
+ { id: 'reasonix', projectSkillsRoot: '.reasonix/skills', globalSkillsRoot: '.reasonix/skills' },
77
+ { id: 'rovodev', projectSkillsRoot: '.rovodev/skills', globalSkillsRoot: '.rovodev/skills' },
78
+ { id: 'roo', projectSkillsRoot: '.roo/skills', globalSkillsRoot: '.roo/skills' },
79
+ { id: 'tabnine-cli', projectSkillsRoot: '.tabnine/agent/skills', globalSkillsRoot: '.tabnine/agent/skills' },
80
+ { id: 'terramind', projectSkillsRoot: '.terramind/skills', globalSkillsRoot: '.terramind/skills' },
81
+ { id: 'tinycloud', projectSkillsRoot: '.tinycloud/skills', globalSkillsRoot: '.tinycloud/skills' },
82
+ { id: 'trae', projectSkillsRoot: '.trae/skills', globalSkillsRoot: '.trae/skills' },
83
+ { id: 'trae-cn', projectSkillsRoot: '.trae/skills', globalSkillsRoot: '.trae-cn/skills' },
84
+ { id: 'windsurf', projectSkillsRoot: '.windsurf/skills', globalSkillsRoot: '.codeium/windsurf/skills' },
85
+ { id: 'zcode', projectSkillsRoot: '.zcode/skills', globalSkillsRoot: '.zcode/skills' },
86
+ { id: 'zencoder', projectSkillsRoot: '.zencoder/skills', globalSkillsRoot: '.zencoder/skills' },
87
+ { id: 'zenflow', projectSkillsRoot: '.zencoder/skills', globalSkillsRoot: '.zencoder/skills' },
88
+ { id: 'neovate', projectSkillsRoot: '.neovate/skills', globalSkillsRoot: '.neovate/skills' },
89
+ { id: 'pochi', projectSkillsRoot: '.pochi/skills', globalSkillsRoot: '.pochi/skills' },
90
+ { id: 'promptscript', projectSkillsRoot: '.agents/skills', globalSkillsRoot: '.agents/skills' },
91
+ { id: 'adal', projectSkillsRoot: '.adal/skills', globalSkillsRoot: '.adal/skills' },
92
+ ];
93
+
94
+ const LAYOUT_BY_ID = new Map(AGENT_SKILL_LAYOUTS.map((a) => [a.id, a]));
95
+
96
+ const DEFAULT_AUTO_AGENTS = ['cursor', 'codex', 'pi', 'claude-code', 'github-copilot'] as const;
97
+
98
+ export function knownAgentIds(): string[] {
99
+ return AGENT_SKILL_LAYOUTS.map((a) => a.id);
100
+ }
101
+
102
+ export function resolveAgentLayouts(agentIds: string[]): AgentSkillsLayout[] {
103
+ const out: AgentSkillsLayout[] = [];
104
+ for (const id of agentIds) {
105
+ const layout = LAYOUT_BY_ID.get(id);
106
+ if (!layout) throw new Error(`Unknown agent id: ${id}`);
107
+ out.push(layout);
108
+ }
109
+ return out;
110
+ }
111
+
112
+ function markerExists(base: string, skillsRoot: string, global: boolean, agentId: string): boolean {
113
+ if (!global && skillsRoot === 'skills' && agentId === 'openclaw') {
114
+ return fs.existsSync(path.join(base, '.openclaw'));
115
+ }
116
+ const top = skillsRoot.split('/')[0]!;
117
+ if (!top || top === '.' || top === skillsRoot) {
118
+ return false;
119
+ }
120
+ return fs.existsSync(path.join(base, top));
121
+ }
122
+
123
+ function detectAgents(cwd: string, global: boolean): string[] {
124
+ const home = os.homedir();
125
+ const found = new Set<string>();
126
+ for (const layout of AGENT_SKILL_LAYOUTS) {
127
+ const rel = global ? layout.globalSkillsRoot : layout.projectSkillsRoot;
128
+ const base = global ? home : cwd;
129
+ if (markerExists(base, rel, global, layout.id)) found.add(layout.id);
130
+ }
131
+ if (found.size > 0) return [...found];
132
+ return [...DEFAULT_AUTO_AGENTS];
133
+ }
134
+
135
+ export function resolveInstallAgentIds(input: string[] | undefined, all: boolean, global: boolean, cwd: string): string[] {
136
+ if (all) return knownAgentIds();
137
+ const tokens = input?.length ? input : ['auto'];
138
+ if (tokens.length === 1 && tokens[0] === 'auto') return detectAgents(cwd, global);
139
+ const flat = tokens.flatMap((t) => t.split(',').map((s) => s.trim()).filter(Boolean));
140
+ const unknown = flat.filter((id) => !LAYOUT_BY_ID.has(id));
141
+ if (unknown.length) throw new Error(`Unknown agent id(s): ${unknown.join(', ')}`);
142
+ return flat;
143
+ }
144
+
145
+ export type InstallDestination = {
146
+ destDir: string;
147
+ agentIds: string[];
148
+ };
149
+
150
+ export function collectInstallDestinations(
151
+ agentIds: string[],
152
+ global: boolean,
153
+ cwd: string,
154
+ skillDirName: string,
155
+ ): InstallDestination[] {
156
+ const home = os.homedir();
157
+ const byDest = new Map<string, string[]>();
158
+ for (const id of agentIds) {
159
+ const layout = LAYOUT_BY_ID.get(id)!;
160
+ const skillsRoot = global ? layout.globalSkillsRoot : layout.projectSkillsRoot;
161
+ const base = global ? home : cwd;
162
+ const destDir = path.join(base, skillsRoot, skillDirName);
163
+ const list = byDest.get(destDir) ?? [];
164
+ list.push(id);
165
+ byDest.set(destDir, list);
166
+ }
167
+ if (!global && agentIds.includes('cursor') && !agentIds.includes('cursor-legacy')) {
168
+ const legacy = path.join(cwd, '.cursor/skills', skillDirName);
169
+ const agentsRoot = path.join(cwd, '.agents/skills', skillDirName);
170
+ if (legacy !== agentsRoot && fs.existsSync(path.join(cwd, '.cursor'))) {
171
+ const list = byDest.get(legacy) ?? [];
172
+ if (!list.includes('cursor-legacy')) list.push('cursor-legacy');
173
+ byDest.set(legacy, list);
174
+ }
175
+ }
176
+ return [...byDest.entries()].map(([destDir, ids]) => ({ destDir, agentIds: ids }));
177
+ }
178
+
179
+ export function formatAgentTable(): string {
180
+ const lines = ['Agent id | project skills root | global skills root', '--- | --- | ---'];
181
+ for (const a of AGENT_SKILL_LAYOUTS) {
182
+ lines.push(`${a.id} | ${a.projectSkillsRoot} | ${a.globalSkillsRoot}`);
183
+ }
184
+ return lines.join('\n');
185
+ }
package/src/cli/main.ts CHANGED
@@ -34,15 +34,18 @@ import {
34
34
  defaultConfigHintBasename,
35
35
  defaultMaintenanceReportBasename,
36
36
  } from './brand.js';
37
+ import { resolveAutoPresets } from '../config/detect-presets.js';
38
+ import { printVersionStatus } from './check-update.js';
37
39
  import { parseInstallArgs, printInstallHints, runInstallSkill } from './install-skill.js';
38
40
 
39
41
  function printHelp() {
40
42
  const cmd = cliBrandName();
41
43
  console.log(`用法:
42
- ${cmd} [install|tree|styles|facets|ux|all|report|read] [选项]
44
+ ${cmd} [install|version|tree|styles|facets|ux|all|report|read] [选项]
43
45
 
44
46
  子命令:
45
- install 安装 Agent skill(uiscope-ux-optimize)到 .cursor/skills;--global 装到用户目录
47
+ install 安装技能到多 Agent 目录(-a/--agent、--all、agents 列表;默认 auto);-g 用户级;过期自动刷新
48
+ version 显示 CLI 版本;--check 对比 npm latest
46
49
  tree 组件嵌套树(roots 下 Vue;配置了 libraryImportSources 时默认收窄消费方)
47
50
  styles 样式重载 + 溯源链
48
51
  facets UI/UX 切面 + 核心 UX 契约(core-ux)
@@ -59,6 +62,7 @@ function printHelp() {
59
62
  --library-consumers-only 仅扫描消费设计库的文件(需 libraryImportSources)
60
63
  --framework <vue|react> 参与扫描的框架(可重复;默认 vue+react)
61
64
  --preset <id|@pkg> 组件库扩展(可重复;短 id → presets/<id>/ 或外置 @algotao/preset-<id>)
65
+ --no-auto-preset 不根据 package.json 依赖自动启用 preset(默认会检测)
62
66
  --json JSON 输出
63
67
  --threshold <n> 样式 overrideRuleCount(等同 thresholds.style)
64
68
  --config <file> 显式加载配置文件
@@ -90,8 +94,9 @@ function printHelp() {
90
94
  }
91
95
 
92
96
  function parseArgs(argv: string[]) {
93
- let mode: ScanMode | 'report' | 'read' | 'install' = 'all';
97
+ let mode: ScanMode | 'report' | 'read' | 'install' | 'version' = 'all';
94
98
  let installArgv: string[] = [];
99
+ let versionCheckRegistry = false;
95
100
  const roots: string[] = [];
96
101
  let failOnWarn = false;
97
102
  let onlyLibraryConsumers: boolean | undefined;
@@ -121,6 +126,7 @@ function parseArgs(argv: string[]) {
121
126
  let noWarnOrphanStyles = false;
122
127
  const frameworks: UiscopeFramework[] = [];
123
128
  const presets: string[] = [];
129
+ let noAutoPreset = false;
124
130
 
125
131
  for (let i = 0; i < argv.length; i++) {
126
132
  const arg = argv[i];
@@ -129,6 +135,10 @@ function parseArgs(argv: string[]) {
129
135
  installArgv = argv.slice(i + 1);
130
136
  break;
131
137
  }
138
+ if (arg === 'version') {
139
+ mode = 'version';
140
+ continue;
141
+ }
132
142
  if (
133
143
  arg === 'tree'
134
144
  || arg === 'styles'
@@ -188,6 +198,10 @@ function parseArgs(argv: string[]) {
188
198
  if (next) presets.push(next);
189
199
  continue;
190
200
  }
201
+ if (arg === '--no-auto-preset') {
202
+ noAutoPreset = true;
203
+ continue;
204
+ }
191
205
  if (arg === '--library-consumers-only') {
192
206
  onlyLibraryConsumers = true;
193
207
  continue;
@@ -282,6 +296,10 @@ function parseArgs(argv: string[]) {
282
296
  if (next != null && next !== '') facetLimit = Number(next);
283
297
  continue;
284
298
  }
299
+ if (arg === '--check') {
300
+ versionCheckRegistry = true;
301
+ continue;
302
+ }
285
303
  if (arg === '--help' || arg === '-h') {
286
304
  printHelp();
287
305
  process.exit(0);
@@ -322,6 +340,8 @@ function parseArgs(argv: string[]) {
322
340
  noWarnOrphanStyles,
323
341
  frameworks,
324
342
  presets,
343
+ noAutoPreset,
344
+ versionCheckRegistry,
325
345
  };
326
346
  }
327
347
 
@@ -341,13 +361,17 @@ async function main() {
341
361
  const args = parseArgs(process.argv.slice(2));
342
362
  const cwd = process.cwd();
343
363
 
364
+ if (args.mode === 'version') {
365
+ process.exit(await printVersionStatus(args.versionCheckRegistry));
366
+ }
367
+
344
368
  if (args.mode === 'install') {
345
369
  const helpWanted = process.argv.slice(2).some((a) => a === '-h' || a === '--help');
346
370
  if (helpWanted) {
347
371
  printInstallHints();
348
372
  process.exit(0);
349
373
  }
350
- process.exit(runInstallSkill(cwd, args.installOpts ?? {}));
374
+ process.exit(await runInstallSkill(cwd, args.installOpts ?? {}));
351
375
  }
352
376
 
353
377
  if (args.enhanceInvalid.length) {
@@ -433,8 +457,18 @@ async function main() {
433
457
  }
434
458
 
435
459
  let base = await resolveBaseScanConfig(cwd, args.configFile, args.noConfig);
436
- if (args.presets.length) {
437
- base = mergeConfig(base, { presets: [...new Set([...(base.presets ?? []), ...args.presets])] });
460
+ const configPresets = base.presets ?? [];
461
+ const presetPlan = await resolveAutoPresets({
462
+ cwd,
463
+ existingPresets: configPresets,
464
+ cliPresets: args.presets,
465
+ noAutoPreset: args.noAutoPreset,
466
+ });
467
+ if (presetPlan.autoApplied.length && !args.quiet && !args.json) {
468
+ console.error(`${cliTag()} auto-preset: ${presetPlan.autoApplied.join(', ')}`);
469
+ }
470
+ if (presetPlan.presets.length) {
471
+ base = mergeConfig(base, { presets: presetPlan.presets });
438
472
  }
439
473
  if (args.frameworks.length) {
440
474
  base = mergeConfig(base, { frameworks: args.frameworks });
@@ -0,0 +1,28 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+
5
+ const PKG_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
6
+
7
+ export function packageRoot(): string {
8
+ return PKG_ROOT;
9
+ }
10
+
11
+ export function readPackageVersion(): string {
12
+ const raw = JSON.parse(fs.readFileSync(path.join(PKG_ROOT, 'package.json'), 'utf8')) as { version?: string };
13
+ return raw.version ?? '0.0.0';
14
+ }
15
+
16
+ /** 仅比较 numeric semver 段(满足本包 x.y.z) */
17
+ export function isSemverGreater(a: string, b: string): boolean {
18
+ const pa = a.split('.').map((x) => Number.parseInt(x, 10) || 0);
19
+ const pb = b.split('.').map((x) => Number.parseInt(x, 10) || 0);
20
+ const len = Math.max(pa.length, pb.length);
21
+ for (let i = 0; i < len; i++) {
22
+ const da = pa[i] ?? 0;
23
+ const db = pb[i] ?? 0;
24
+ if (da > db) return true;
25
+ if (da < db) return false;
26
+ }
27
+ return false;
28
+ }
@@ -0,0 +1,31 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { readPackageVersion } from './package-version.js';
4
+
5
+ export const SKILL_VERSION_STAMP = '.uiscope-version';
6
+
7
+ export function readSkillInstallVersion(skillDestDir: string): string | undefined {
8
+ const file = path.join(skillDestDir, SKILL_VERSION_STAMP);
9
+ if (!fs.existsSync(file)) return undefined;
10
+ return fs.readFileSync(file, 'utf8').trim() || undefined;
11
+ }
12
+
13
+ export function writeSkillInstallVersion(skillDestDir: string, version: string): void {
14
+ fs.writeFileSync(path.join(skillDestDir, SKILL_VERSION_STAMP), `${version}\n`, 'utf8');
15
+ }
16
+
17
+ export type SkillUpdatePlan = {
18
+ skillDestDir: string;
19
+ installedVersion?: string;
20
+ needsUpdate: boolean;
21
+ };
22
+
23
+ /** 对比已安装技能戳与当前 CLI 包版本,决定是否刷新副本 */
24
+ export function planSkillUpdates(destDirs: string[], force: boolean): SkillUpdatePlan[] {
25
+ const current = readPackageVersion();
26
+ return destDirs.map((skillDestDir) => {
27
+ const installedVersion = readSkillInstallVersion(skillDestDir);
28
+ const needsUpdate = force || !installedVersion || installedVersion !== current;
29
+ return { skillDestDir, installedVersion, needsUpdate };
30
+ });
31
+ }
@@ -0,0 +1,113 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { listBuiltinPresetIds, resolvePreset } from './resolve-presets.js';
4
+
5
+ const ALGOTAO_PRESET_PKG_PREFIX = '@algotao/preset-';
6
+
7
+ export type PackageUiscopeMeta = {
8
+ autoPreset?: boolean;
9
+ presets?: string[];
10
+ };
11
+
12
+ function readPackageJson(cwd: string): Record<string, unknown> | null {
13
+ const file = path.join(cwd, 'package.json');
14
+ if (!fs.existsSync(file)) return null;
15
+ try {
16
+ return JSON.parse(fs.readFileSync(file, 'utf8')) as Record<string, unknown>;
17
+ } catch {
18
+ return null;
19
+ }
20
+ }
21
+
22
+ export function readPackageUiscopeMeta(cwd: string): PackageUiscopeMeta | undefined {
23
+ const pkg = readPackageJson(cwd);
24
+ const raw = pkg?.uiscope;
25
+ if (!raw || typeof raw !== 'object') return undefined;
26
+ return raw as PackageUiscopeMeta;
27
+ }
28
+
29
+ function collectDependencyNames(pkg: Record<string, unknown>): Set<string> {
30
+ const names = new Set<string>();
31
+ for (const key of ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies'] as const) {
32
+ const block = pkg[key];
33
+ if (block && typeof block === 'object') {
34
+ for (const name of Object.keys(block as Record<string, string>)) names.add(name);
35
+ }
36
+ }
37
+ return names;
38
+ }
39
+
40
+ function detectPresetIdsFromAlgotaPackages(deps: Set<string>): string[] {
41
+ const found: string[] = [];
42
+ for (const name of deps) {
43
+ if (name.startsWith(ALGOTAO_PRESET_PKG_PREFIX)) {
44
+ const id = name.slice(ALGOTAO_PRESET_PKG_PREFIX.length);
45
+ if (id) found.push(id);
46
+ }
47
+ }
48
+ return found;
49
+ }
50
+
51
+ function depsMatchSignals(deps: Set<string>, signals: readonly string[] | undefined): boolean {
52
+ if (!signals?.length) return false;
53
+ return signals.some((p) => deps.has(p));
54
+ }
55
+
56
+ /**
57
+ * 根据 package.json 依赖 + 各 preset 的 detectPackages 自动推断 preset id。
58
+ */
59
+ export async function detectPresetsFromProject(cwd: string): Promise<string[]> {
60
+ const pkg = readPackageJson(cwd);
61
+ if (!pkg) return [];
62
+ const deps = collectDependencyNames(pkg);
63
+ const found = new Set<string>(detectPresetIdsFromAlgotaPackages(deps));
64
+
65
+ for (const id of listBuiltinPresetIds()) {
66
+ try {
67
+ const preset = await resolvePreset(cwd, id);
68
+ if (depsMatchSignals(deps, preset.detectPackages)) {
69
+ found.add(preset.id);
70
+ }
71
+ } catch {
72
+ /* 内置 preset 在当前环境不可加载时跳过 */
73
+ }
74
+ }
75
+
76
+ return [...found].sort();
77
+ }
78
+
79
+ export type ResolveAutoPresetsInput = {
80
+ cwd: string;
81
+ existingPresets: readonly string[];
82
+ cliPresets: readonly string[];
83
+ noAutoPreset: boolean;
84
+ };
85
+
86
+ export type ResolveAutoPresetsResult = {
87
+ presets: string[];
88
+ autoApplied: string[];
89
+ skippedReason?: string;
90
+ };
91
+
92
+ export async function resolveAutoPresets(input: ResolveAutoPresetsInput): Promise<ResolveAutoPresetsResult> {
93
+ const manual = [...new Set([...input.existingPresets, ...input.cliPresets])];
94
+ if (manual.length > 0) {
95
+ return { presets: manual, autoApplied: [], skippedReason: 'explicit-or-config-presets' };
96
+ }
97
+ if (input.noAutoPreset) {
98
+ return { presets: [], autoApplied: [], skippedReason: 'no-auto-preset' };
99
+ }
100
+
101
+ const meta = readPackageUiscopeMeta(input.cwd);
102
+ if (meta?.autoPreset === false) {
103
+ return { presets: meta.presets ?? [], autoApplied: [], skippedReason: 'package.json uiscope.autoPreset=false' };
104
+ }
105
+
106
+ const detected = await detectPresetsFromProject(input.cwd);
107
+ const fromMeta = meta?.presets ?? [];
108
+ const merged = [...new Set([...detected, ...fromMeta])];
109
+ return {
110
+ presets: merged,
111
+ autoApplied: detected,
112
+ };
113
+ }
@@ -5,6 +5,11 @@ import type { UxComponentRole } from '../manifest/library-ux-taxonomy.js';
5
5
  /** 组件库扩展 preset:合并进 UiscopeConfig,不侵入业务仓库 */
6
6
  export interface UiscopePreset {
7
7
  id: string;
8
+ /**
9
+ * package.json 依赖名命中时自动启用本 preset(与 CLI auto-preset 联用)。
10
+ * 新组件库在各自 preset 模块声明,勿在 core 硬编码库名。
11
+ */
12
+ detectPackages?: string[];
8
13
  /** 与 config.libraryImportSources 并集 */
9
14
  libraryImportSources?: string[];
10
15
  styleWhitelist?: readonly LibraryStyleWhitelistEntry[];
@@ -12,6 +12,21 @@ import { resolveAutoLibraryRoots } from './resolve-preset-library-roots.js';
12
12
 
13
13
  const CORE_PKG_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
14
14
 
15
+ export function listBuiltinPresetIds(): string[] {
16
+ const presetsDir = path.join(CORE_PKG_ROOT, 'presets');
17
+ if (!fs.existsSync(presetsDir)) return [];
18
+ return fs
19
+ .readdirSync(presetsDir, { withFileTypes: true })
20
+ .filter(
21
+ (d) =>
22
+ d.isDirectory()
23
+ && !d.name.startsWith('.')
24
+ && fs.existsSync(path.join(presetsDir, d.name, 'index.ts')),
25
+ )
26
+ .map((d) => d.name)
27
+ .sort();
28
+ }
29
+
15
30
  function builtinPresetFile(presetId: string): string | undefined {
16
31
  const file = path.join(CORE_PKG_ROOT, 'presets', presetId, 'index.ts');
17
32
  return fs.existsSync(file) ? file : undefined;