polishup-cli 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,177 +1,167 @@
1
1
  # PolishUp
2
2
 
3
- An agent skill for research-informed creation, refinement, and review across fields. Preserve user intent and project conventions; research methods and quality criteria suited to the task.
3
+ An agent skill for writing, design, code, and more.
4
4
 
5
- Bundled knowledge covers the domains below. Other fields, such as 3D work, data analysis, and learning materials, use task-specific research and appropriate checks, not a claim of complete specialist expertise.
5
+ PolishUp is an agent skill for creating, refining, and reviewing work. It helps address **AI slop**: generic writing, repetitive interface designs, unsupported claims, and unnecessarily complicated code.
6
6
 
7
- | Domain | Guidance |
8
- | --- | --- |
9
- | [Writing](skills/polishup/references/writing/index.md) | Purpose, evidence, structure, language, voice, accessibility, and revision |
10
- | [UI/UX Design](skills/polishup/references/ui-ux/index.md) | Research, navigation, interaction, visual design, responsiveness, accessibility, and evaluation |
11
- | [Code](skills/polishup/references/code/index.md) | Readability, simplicity, correctness, and proportionate verification |
12
-
13
- ## Installation
7
+ It uses relevant research and professional guidance while respecting your goals and existing project conventions.
14
8
 
15
- ### Local installer
9
+ ## What it covers
16
10
 
17
- With Node.js 22 or newer, open a terminal in the PolishUp checkout or extracted installer package:
18
-
19
- ```text
20
- npm start
21
- ```
11
+ | Area | Focus |
12
+ | --- | --- |
13
+ | [Writing](skills/polishup/references/writing/index.md) | Clear, specific communication with sound evidence, structure, and an appropriate voice |
14
+ | [UI/UX Design](skills/polishup/references/ui-ux/index.md) | Usable interfaces with coherent visual design, accessible interactions, and responsive layouts |
15
+ | [Code](skills/polishup/references/code/index.md) | Readable, maintainable implementations without unnecessary complexity |
22
16
 
23
- Choose one or more harnesses and project or personal scope. `install` is an optional alias for the same setup. Project scope uses the nearest Git root, or the current directory without Git. Running from the PolishUp checkout selects that checkout, not another project.
17
+ For other fields, PolishUp uses task-specific research and checks. Guidance loads on demand, using your agent's available tools without requiring a particular model, framework, MCP server, or hook.
24
18
 
25
- This runs the local installer without downloading PolishUp from npm. To target another project, run `node "<path-to-polishup>/cli/index.mjs"` from that project's directory instead.
19
+ An optional [color helper](skills/polishup/references/colors.md) supports contrast checks and palette exploration.
26
20
 
27
- The installer supports the nine harnesses below and custom destinations. It checks conflicts, preserves backups outside skill discovery, and displays the affected paths. Shared project locations are written once; failures in independent targets are reported separately.
21
+ ## Installation
28
22
 
29
- Use `--help` for optional flags. `--dry-run` previews changes; `--agent` and `--scope` support noninteractive use. Choose `--agent manual --destination <path> --scope project|user` for a custom folder ending in `polishup`. This copies files without registering discovery. `--replace` explicitly backs up and replaces conflicting content.
23
+ Requires **Node.js 22 or newer**. Choose either option below and run the installer from the project where you want to use PolishUp.
30
24
 
31
- ### npm installer
25
+ ### Run with npx
32
26
 
33
- With Node.js 22 or newer, run from the destination project:
27
+ Use the installer without installing the CLI globally:
34
28
 
35
- ```text
29
+ ```sh
36
30
  npx polishup-cli
37
31
  ```
38
32
 
39
- The npm package is named `polishup-cli`; the skill, plugin and executable remain `polishup`. No npm account is needed to install a public package.
33
+ ### Install with npm
40
34
 
41
- ### Manual installation
35
+ Install the CLI once, then use the shorter `polishup` command:
42
36
 
43
- Copy the complete `skills/polishup/` directory to one destination below. Preserve `SKILL.md`, `LICENSE.txt`, `references/`, `scripts/`, notices and relative paths; avoid an extra nested `skills/polishup/` inside the destination. Copying and reading the skill needs no runtime or package manager. The optional executable helper needs Node.js 22+.
37
+ ```sh
38
+ npm install -g polishup-cli
39
+ polishup
40
+ ```
44
41
 
45
- | Harness | Project skill directory | Default personal skill directory |
46
- | --- | --- | --- |
47
- | [Codex](https://developers.openai.com/codex/skills) | `.agents/skills/polishup/` | `~/.agents/skills/polishup/` |
48
- | [Claude Code](https://code.claude.com/docs/en/skills) | `.claude/skills/polishup/` | `~/.claude/skills/polishup/` |
49
- | [OpenCode](https://opencode.ai/docs/skills/) | `.opencode/skills/polishup/` | `~/.config/opencode/skills/polishup/` |
50
- | [Cursor](https://cursor.com/docs/skills) | `.cursor/skills/polishup/` | `~/.cursor/skills/polishup/` |
51
- | [Oh My Pi (OMP)](https://github.com/can1357/oh-my-pi/blob/main/docs/skills.md) | `.omp/skills/polishup/` | `~/.omp/agent/skills/polishup/` |
52
- | [Gemini CLI](https://geminicli.com/docs/cli/skills/) | `.gemini/skills/polishup/` | `~/.gemini/skills/polishup/` |
53
- | [GitHub Copilot](https://docs.github.com/en/copilot/concepts/customizations/agent-skills) | `.github/skills/polishup/` | `~/.copilot/skills/polishup/` |
54
- | [Antigravity](https://antigravity.google/docs/skills) | `.agents/skills/polishup/` | `~/.gemini/config/skills/polishup/` |
55
- | [Hermes](https://github.com/NousResearch/hermes-agent/blob/main/agent/skill_utils.py) | `.agents/skills/polishup/` | `<effective Hermes home>/skills/polishup/` |
42
+ Both options open the same installer. Choose your agent, select project or personal installation, and review the destinations before confirming. Installing the CLI alone does not install the skill into your agent. Project installation applies to the nearest Git project, or the current folder when there is no Git repository.
56
43
 
57
- `~` means your home directory. These are default locations; the installer honors the following overrides for personal scope:
44
+ The installer supports Codex, Claude Code, OpenCode, Cursor, Oh My Pi, Gemini CLI, GitHub Copilot, Antigravity, and Hermes, plus custom destinations. It runs on Windows, macOS, and Linux, subject to your agent's platform support.
58
45
 
59
- - Codex: an existing `CODEX_HOME` selects its backward-compatible `skills/` location. Claude uses `CLAUDE_CONFIG_DIR`; OpenCode uses `OPENCODE_CONFIG_DIR` or its `XDG_CONFIG_HOME` location.
60
- - Gemini: `<GEMINI_CLI_HOME>/.gemini/skills/polishup/`; relative home overrides resolve from the working directory.
61
- - OMP: set `PI_CODING_AGENT_DIR` for a custom agent directory, or choose a manual destination when its profile location is unresolved.
62
- - Hermes: honors `HERMES_HOME` and `HERMES_DATA_DIR_SUFFIX`; default homes are `~/.hermes` on POSIX and `%LOCALAPPDATA%/hermes` on Windows. `--profile` selects an existing named personal profile. Project discovery requires a trusted Git project; installation does not grant trust.
46
+ Reload your agent's skills or start a new session after installation. Discovery and available commands depend on the agent.
63
47
 
64
- For OpenCode's `/polishup` command, also copy `.opencode/commands/polishup.md` into the corresponding project or personal `commands/` directory. The installer does this automatically. No JavaScript plugin is needed for the skill or command.
48
+ <details>
49
+ <summary>Other installation methods</summary>
65
50
 
66
- The source checkout also includes seven generated native skill copies at the project locations above. They offer direct-copy routes to the same knowledge. Cloning the checkout does not install them into unrelated projects.
51
+ ### From source
67
52
 
68
- ### Native plugins
69
-
70
- These alternatives require the source checkout. Plugin manifests are not included in the standalone npm archive, and the local installer does not register or enable plugins.
53
+ ```sh
54
+ git clone https://github.com/fachriaziz/polishup.git
55
+ cd polishup
56
+ npm ci --ignore-scripts
57
+ npm start
58
+ ```
71
59
 
72
- | Host | Source route |
73
- | --- | --- |
74
- | Claude Code | `.claude-plugin/plugin.json`; load locally with `claude --plugin-dir "<path-to-polishup>"` |
75
- | Codex | Root `plugin.json`, `.codex-plugin/plugin.json`, and `.agents/plugins/marketplace.json`; register the root as a local marketplace, then add `polishup@polishup-local` through the host |
76
- | Antigravity | `.antigravity-plugin/plugin.json`; use its documented plugin manager |
77
- | Cursor and OMP | Portable `plugin.json` is present; native plugin installation and activation remain unverified |
60
+ This runs the local installer. Choose personal installation to use PolishUp across your projects. Project installation targets this checkout; to install into another project, run `node "<path-to-polishup>/cli/index.mjs"` from that project's folder.
78
61
 
79
- ## Usage
62
+ ### Manual installation
80
63
 
81
- State the task, target, and constraints:
64
+ Copy the complete `skills/polishup/` folder into your agent's skills directory, keeping its contents and relative paths intact. For example, Claude Code project skills use `.claude/skills/polishup/`.
82
65
 
83
- - "Use PolishUp to draft a product announcement from these facts."
84
- - "Use PolishUp to refine this interface. Preserve its visual identity."
85
- - "Use PolishUp to review this function. Report findings without editing it."
86
- - "Use PolishUp to plan a Blender product render. Research methods for my version and delivery requirements."
66
+ Reading the skill requires no Node.js or Python. The optional color helper requires Node.js 22+. For OpenCode's `/polishup` command, also copy `.opencode/commands/polishup.md` into the matching commands directory; the installer handles this automatically.
87
67
 
88
- Review reports findings without editing the target. Refine preserves satisfactory work; Create produces new work; Redesign changes the agreed aspects. These are optional action labels on one skill.
68
+ ### Native plugins
89
69
 
90
- Type native invocations in the agent prompt, not the OS terminal:
70
+ The source checkout also includes native plugin manifests. These are separate from the npm skill installer:
91
71
 
92
- | Harness | Invocation |
72
+ | Agent | Installation |
93
73
  | --- | --- |
94
- | Codex | `$polishup review ...`, or select it in the skills menu |
95
- | Claude Code, OpenCode, Antigravity | `/polishup review ...`; Claude plugin skills use the host's namespace |
96
- | Cursor | Type `/` and select `polishup` in Agent chat |
97
- | OMP | `/skill:polishup ...` when skill commands are enabled; otherwise request it by name |
98
- | Hermes | `/skill polishup`, then state the task |
99
- | Gemini CLI and supported Copilot clients | Request PolishUp by name; approve native activation when prompted |
74
+ | Claude Code | Load the checkout with `claude --plugin-dir "<path-to-polishup>"` |
75
+ | Codex | Add the checkout as a local plugin marketplace, then install `polishup@polishup-local` |
76
+ | Antigravity | Install the checkout through its plugin manager |
100
77
 
101
- PolishUp requires initial research into applicable methods, quality criteria, and documented failures. Depth follows the task; evidence already checked for it can be reused. Research supports decisions and does not replace checking the actual result. When current research cannot be accessed, the agent must disclose the limitation and avoid unsupported claims.
78
+ Use one installation method per agent and scope to avoid duplicate copies.
102
79
 
103
- Domain rules and topic references apply selectively. Interface styling restrictions do not govern standalone 3D work or other visual media. The Markdown skill requires no particular model, framework, interpreter, MCP server, or hook; research and artifact checks use available tools. Discovery and available commands depend on the host. Personal installation does not automatically reach cloud or remote sessions.
80
+ </details>
104
81
 
105
- ## Update and uninstall
82
+ ## Using the skill
106
83
 
107
- For a Git checkout, pull the current source and run the local installer again to apply it to the selected destinations:
84
+ In your agent's chat, name PolishUp and describe the task:
108
85
 
109
86
  ```text
110
- git pull
111
- npm start
87
+ Use PolishUp to write a product announcement from these facts.
112
88
  ```
113
89
 
114
- For npm installations, run `npx polishup-cli update` from the destination project. This checks the registry for a newer installer before applying managed changes. Use `npx polishup-cli uninstall` to remove a registered installation.
90
+ ```text
91
+ Use PolishUp to refine this dashboard. Preserve its visual identity and workflows.
92
+ ```
115
93
 
116
- For a checkout or extracted package, use `npm start -- uninstall`. The CLI selects a single registered consumer automatically or asks you to choose among registered consumers. Unmanaged folders require explicit harness selection; custom destinations require `--agent manual --destination <path> --scope project|user`.
94
+ ```text
95
+ Use PolishUp to review this function for unnecessary complexity. Report findings without editing it.
96
+ ```
117
97
 
118
- Keep the displayed backup paths and inspect interrupted-operation locks before removing them. Uninstalling one registered Codex, Antigravity, or Hermes project consumer retains shared files while another registered consumer remains. Other readers of compatible paths cannot be enumerated.
98
+ Ask it to create new work, refine existing work, review without editing, or redesign specified parts. Refinement preserves existing meaning, identity, and behavior outside the requested changes.
119
99
 
120
- For manual updates, preserve customizations outside discovery roots and replace the complete selected skill. For manual removal, delete or move that exact directory outside discovery roots; renaming it within a scanned directory may leave it discoverable. Instructions already loaded can remain in the current session.
100
+ These requests go in your agent's chat, not your terminal. You can also use its supported skill shortcuts:
121
101
 
122
- Use the original manager for manager-owned installations. Avoid installing the same skill through several routes in one scope without a concrete need.
102
+ | Agent | Invocation |
103
+ | --- | --- |
104
+ | Codex | `$polishup review ...` |
105
+ | Claude Code, OpenCode, Antigravity | `/polishup review ...` |
106
+ | Cursor | Type `/` and select `polishup` in Agent chat |
107
+ | Oh My Pi | `/skill:polishup ...` when skill commands are enabled |
108
+ | Hermes | `/skill polishup`, then describe the task |
109
+ | Gemini CLI, supported Copilot clients | Request PolishUp by name and approve activation if prompted |
123
110
 
124
- ## Optional tools
111
+ Plugin installations may use a namespaced command. Available shortcuts depend on the agent and installation method.
125
112
 
126
- PolishUp uses suitable tools already available in the harness or project. Its [tools reference](skills/polishup/references/tools.md) guides scoped inspection, checks and evidence reporting. No browser provider, MCP, hooks or setup document is required.
113
+ Default anti-slop rules guide new choices without authorizing unrelated rewrites or redesigns. State any specific style preferences in your request.
127
114
 
128
- The complete skill includes a ready-to-run helper for color-pair checking, five harmony methods, constrained role adjustment and an optional static preview. Node.js 22+ is required; no global CLI, npm dependencies or build step is needed to use it. From this package directory:
115
+ ## CLI commands
129
116
 
130
- ```text
131
- node skills/polishup/scripts/color.mjs check "#222222" "#ffffff" --json
132
- node skills/polishup/scripts/color.mjs generate --input palette.json --preview preview.html --json
133
- ```
117
+ Run these commands in your terminal. The examples use the globally installed CLI; with npx, replace `polishup` with `npx polishup-cli`, for example `npx polishup-cli update`.
134
118
 
135
- For an installed skill, use its actual absolute `scripts/color.mjs` path. The optional package CLI, `node cli/index.mjs color ...`, uses the same prepared implementation. Read [Color Tools](skills/polishup/references/colors.md) for inputs and limits and preserve the [bundled dependency notice](skills/polishup/scripts/NOTICE.txt). Output is report-only except for an explicitly requested new preview. Color checks do not establish full accessibility or design quality.
136
-
137
- ## Troubleshooting
138
-
139
- - **Skill not listed:** check the complete references tree, exact `SKILL.md` filename and case, selected scope/profile, duplicate copies, and host permissions. Refresh through the host's supported mechanism.
140
- - **Conflict or unsafe path:** inspect local changes and backups. Use the intended physical path instead of a symlink/junction. Do not remove ownership markers or locks to force replacement.
141
- - **Native discovery unavailable:** provide the installed `SKILL.md` path and ask the agent to read it and only relevant linked references. Supply the texts directly if file access is unavailable. This does not register native discovery.
142
- - **Windows PowerShell blocks npm:** use `npm.cmd` for development commands; no execution-policy change is needed. Quote paths containing spaces and preserve Unicode filenames.
143
- - **Custom Hermes path fails:** POSIX variable names are case-sensitive; Windows expansion is case-insensitive. `%NAME%` expansion is Windows-only; `$NAME` and `${NAME}` are also supported. Undefined referenced variables stop installation.
119
+ | Command | Purpose |
120
+ | --- | --- |
121
+ | `polishup` | Open guided installation or manage existing installations |
122
+ | `polishup install` | Start installation setup directly |
123
+ | `polishup update` | Check for a newer published release and update installed skills |
124
+ | `polishup uninstall` | Remove an installer-managed skill installation |
125
+ | `polishup color check <foreground> <background>` | Check a color pair's contrast ratio |
126
+ | `polishup color generate --input <file>` | Generate palette candidates from a JSON file |
127
+ | `polishup --help` | Show installer options and examples |
128
+ | `polishup --version` | Show the CLI version |
144
129
 
145
- To check loading, request a review of a supplied paragraph without editing it. Inspect exposed skill events or file-read records where available. Installed files, a listed skill, loaded instructions, and applied references are separate observations; an answer mentioning PolishUp proves none of them alone.
130
+ Run installation management commands from the target project. `update` applies the published release to selected skill installations; to also replace your globally installed CLI, rerun `npm install -g polishup-cli`.
146
131
 
147
- ## Development
132
+ <details>
133
+ <summary>Optional flags and color examples</summary>
148
134
 
149
- Run development commands from the `polishup` directory in the source checkout. Install locked dependencies once before development checks. Edit knowledge only in `skills/polishup/`, then synchronize native copies and run checks:
135
+ Choose agents and preview a project installation without writing files:
150
136
 
151
- ```text
152
- npm ci --ignore-scripts
153
- npm run sync
154
- npm test
137
+ ```sh
138
+ polishup install --agent codex,claude --scope project --dry-run
155
139
  ```
156
140
 
157
- `npm run sync` prepares the helper and notices, then updates the repository's native skill copies. Edit helper logic in `cli/color.mjs`, `cli/palette.mjs`, and `cli/color-entry.mjs`; do not hand-edit the prepared `skills/polishup/scripts/` files. The native exporter protects unmarked, locally edited, extra, or linked files. Preserve intended customizations before regeneration; missing generated files can be restored. `npm test` checks prepared-helper and full-tree freshness before the tests. `npm run check` performs those freshness checks without changing files. Existing complete skill copies are ready to use without rebuilding.
141
+ Use `--scope user` for personal installation, `--plain` for text menus, or `--no-input` with explicit target options for noninteractive use. Run `polishup --help` for custom destinations, Hermes profiles, and replacement options.
158
142
 
159
- Plugin manifests point to the canonical source. Destinations live in `cli/hosts.mjs`; the authored OpenCode command lives in `.opencode/commands/polishup.md`. The `.polishup-export.json` marker identifies a generated native copy, not an installer-owned installation.
143
+ Check a color pair:
160
144
 
161
- Inspect the npm payload without publishing:
145
+ ```sh
146
+ polishup color check "#222222" "#ffffff" --json
147
+ ```
162
148
 
163
- ```text
164
- npm pack --dry-run --json --ignore-scripts
149
+ Generate a palette from `palette.json`, optionally creating a new preview file:
150
+
151
+ ```sh
152
+ polishup color generate --input palette.json --preview preview.html --json
165
153
  ```
166
154
 
167
- To create an archive, omit `--dry-run` and add `--pack-destination <existing-output-directory>`. npm needs a writable cache. The package includes the complete skill and prepared helper, four installer CLI modules, OpenCode command, README, and package metadata. Color.js and esbuild are development dependencies only. Tests, helper source/build tooling, native exports, source manifests, and development records are excluded. No `dist/` directory or install-time compilation is used.
155
+ Read [Color Tools](skills/polishup/references/colors.md) for the JSON format, supported methods, and limits. Color checks do not establish complete accessibility.
156
+
157
+ </details>
168
158
 
169
- Notable user-facing changes belong in the source checkout's `CHANGELOG.md`. Routine internal cleanup and research notes are not release notes.
159
+ For a source checkout, run `git pull`, then `npm ci --ignore-scripts` and `npm start` to apply the updated copy. Update or remove manual and plugin installations through their original installation method.
170
160
 
171
- ## Project status
161
+ ## Help
172
162
 
173
- The installer targets Windows, Linux, and macOS, subject to host availability. The [Checks workflow](https://github.com/fachriaziz/polishup/actions/workflows/checks.yml) runs installer and package checks on all three OS families using Node.js 22; inspect the latest run for results. Mechanical checks do not establish automatic activation, output quality, token savings, or cross-harness effectiveness.
163
+ If the skill is missing, check the installation destination and refresh your agent's skills. For questions or problems, [open an issue](https://github.com/fachriaziz/polishup/issues).
174
164
 
175
165
  ## License
176
166
 
177
- [MIT](LICENSE), copyright (c) 2026 fachriaziz. Standalone skill copies include `LICENSE.txt`; the bundled Color.js helper retains its [third-party notice](skills/polishup/scripts/NOTICE.txt).
167
+ [MIT](LICENSE). The color helper includes a [third-party notice](skills/polishup/scripts/NOTICE.txt).
@@ -0,0 +1,75 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+
5
+ const COMMANDS = {
6
+ codex: ['codex'], claude: ['claude'], opencode: ['opencode'], cursor: ['cursor', 'cursor-agent'],
7
+ omp: ['omp'], gemini: ['gemini'], copilot: ['copilot'], antigravity: ['agy', 'antigravity'], hermes: ['hermes'],
8
+ };
9
+
10
+ export function detectHarnesses({ home = os.homedir(), cwd = process.cwd(), env = process.env, platform = process.platform } = {}, { fileSystem = fs } = {}) {
11
+ const windows = platform === 'win32';
12
+ const paths = windows ? path.win32 : path.posix;
13
+ const get = name => env[name] ?? (windows ? Object.entries(env).find(([key]) => key.toLowerCase() === name.toLowerCase())?.[1] : undefined);
14
+ const kind = (file, directory = false) => {
15
+ try { const stat = fileSystem.statSync(file); return directory ? stat.isDirectory() : stat.isFile(); }
16
+ catch { return false; }
17
+ };
18
+ const executable = file => {
19
+ if (!kind(file)) return false;
20
+ if (windows) return true;
21
+ try { fileSystem.accessSync(file, fs.constants.X_OK); return true; }
22
+ catch { return false; }
23
+ };
24
+ const directories = (get('PATH') || '').split(windows ? ';' : ':')
25
+ .map(value => value.trim().replace(/^"(.*)"$/, '$1')).filter(value => paths.isAbsolute(value));
26
+ const extensions = windows ? (get('PATHEXT') || '.COM;.EXE;.BAT;.CMD').split(';')
27
+ .filter(value => /^\.[a-z0-9]+$/i.test(value)).map(value => value.toLowerCase()) : [''];
28
+ const find = commands => {
29
+ for (const directory of directories) for (const command of commands) for (const extension of extensions) {
30
+ const file = paths.join(directory, `${command}${extension}`);
31
+ if (executable(file)) return file;
32
+ }
33
+ };
34
+ const configured = value => value ? paths.resolve(cwd, value) : undefined;
35
+ const local = get('LOCALAPPDATA') || paths.join(home, 'AppData', 'Local');
36
+ const programFiles = [get('ProgramFiles'), get('ProgramFiles(x86)')].filter(Boolean);
37
+ const results = {};
38
+ for (const [agent, commands] of Object.entries(COMMANDS)) {
39
+ let evidence = find(commands);
40
+ // `agent` is a generic name: only accept an identifiable Cursor installation path.
41
+ if (!evidence && agent === 'cursor') {
42
+ const launcher = find(['agent']);
43
+ if (launcher) {
44
+ try { if (/cursor[-_ ]?agent|[\\/]cursor[\\/]/i.test(fileSystem.realpathSync(launcher))) evidence = launcher; }
45
+ catch { /* A broken or unreadable launcher is not detected. */ }
46
+ }
47
+ }
48
+ const appFiles = windows ? {
49
+ cursor: [paths.join(local, 'Programs', 'cursor', 'Cursor.exe'), ...programFiles.map(root => paths.join(root, 'Cursor', 'Cursor.exe'))],
50
+ antigravity: [paths.join(local, 'agy', 'bin', 'agy.exe')],
51
+ } : {};
52
+ if (!evidence) evidence = (appFiles[agent] || []).find(executable);
53
+ if (!evidence && platform === 'darwin' && agent === 'cursor') {
54
+ evidence = ['/Applications/Cursor.app', paths.join(home, 'Applications', 'Cursor.app')].find(file => kind(file, true));
55
+ }
56
+ if (evidence) { results[agent] = { status: 'detected', evidence }; continue; }
57
+ const own = name => [paths.join(cwd, name), paths.join(home, name)];
58
+ const configDirectories = {
59
+ codex: [configured(get('CODEX_HOME')), ...own('.codex')],
60
+ claude: [configured(get('CLAUDE_CONFIG_DIR')), ...own('.claude')],
61
+ opencode: [configured(get('OPENCODE_CONFIG_DIR')), ...own('.opencode'), paths.join(get('XDG_CONFIG_HOME') || paths.join(home, '.config'), 'opencode')],
62
+ cursor: own('.cursor'), omp: [configured(get('PI_CODING_AGENT_DIR')), ...own('.omp')],
63
+ gemini: [], copilot: [paths.join(home, '.copilot')],
64
+ antigravity: [paths.join(home, '.gemini', 'config'), paths.join(home, '.gemini', 'antigravity')],
65
+ hermes: [configured(get('HERMES_HOME')), windows ? paths.join(local, `hermes${get('HERMES_DATA_DIR_SUFFIX') || ''}`) : paths.join(home, `.hermes${get('HERMES_DATA_DIR_SUFFIX') || ''}`)],
66
+ };
67
+ evidence = configDirectories[agent].filter(Boolean).find(file => kind(file, true));
68
+ if (!evidence && agent === 'gemini') {
69
+ evidence = [paths.join(cwd, '.gemini', 'settings.json'), paths.resolve(cwd, get('GEMINI_CLI_HOME') || home, '.gemini', 'settings.json')].find(file => kind(file));
70
+ }
71
+ if (!evidence && agent === 'copilot') evidence = [paths.join(cwd, '.github', 'copilot-instructions.md')].find(file => kind(file));
72
+ results[agent] = evidence ? { status: 'configured', evidence } : { status: 'not-detected' };
73
+ }
74
+ return results;
75
+ }
package/cli/hosts.mjs CHANGED
@@ -22,7 +22,7 @@ export function getStorageGroup(agent, scope) {
22
22
  const PROFILE_NAME = /^[a-z0-9][a-z0-9_-]{0,63}$/;
23
23
  const RESERVED_PROFILES = new Set(['hermes', 'default', 'test', 'tmp', 'root', 'sudo']);
24
24
 
25
- function projectRootFor(cwd) {
25
+ export function projectRootFor(cwd) {
26
26
  let current = path.resolve(cwd);
27
27
  while (true) {
28
28
  if (fs.existsSync(path.join(current, '.git'))) return current;
@@ -88,6 +88,16 @@ function hermesTargetHome({ home, env, cwd, platform, profile }) {
88
88
  return { home: defaultHome, profile: 'default' };
89
89
  }
90
90
 
91
+ export function hermesProfiles({ home = os.homedir(), env = process.env, cwd = process.cwd(), platform = process.platform } = {}) {
92
+ const configured = hermesTargetHome({ home, env, cwd, platform }).home;
93
+ const root = path.basename(path.dirname(configured)) === 'profiles' ? path.dirname(path.dirname(configured)) : configured;
94
+ try {
95
+ return fs.readdirSync(path.join(root, 'profiles'), { withFileTypes: true })
96
+ .filter(entry => entry.isDirectory() && PROFILE_NAME.test(entry.name) && !RESERVED_PROFILES.has(entry.name))
97
+ .map(entry => entry.name).sort();
98
+ } catch (error) { if (error.code === 'ENOENT') return []; throw error; }
99
+ }
100
+
91
101
  export function getTarget({ agent, scope, cwd = process.cwd(), home = os.homedir(), env = process.env, profile, platform = process.platform }) {
92
102
  const definition = HOSTS[agent];
93
103
  if (!definition) throw new Error(`Unknown agent: ${agent}`);
package/cli/index.mjs CHANGED
@@ -4,9 +4,10 @@ import os from 'node:os';
4
4
  import path from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import { parseArgs } from 'node:util';
7
- import { createInterface } from 'node:readline/promises';
8
- import { AGENTS, loadPayload, getManualTarget, getTarget, inspect, plan, apply } from './installations.mjs';
7
+ import { AGENTS, loadPayload, getManualTarget, getTarget, plan, apply } from './installations.mjs';
9
8
  import { checkUpdate, forwardedTargetArgs, runNewVersion } from './update.mjs';
9
+ import { BACK, createPrompts } from './prompts.mjs';
10
+ import { selectSetup } from './menu.mjs';
10
11
 
11
12
  const packageRoot = fileURLToPath(new URL('../', import.meta.url));
12
13
  const metadata = JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf8'));
@@ -15,7 +16,7 @@ const HELP = `PolishUp ${metadata.version}
15
16
 
16
17
  Usage: ${helpCommand} [install|update|uninstall|color] [options]
17
18
 
18
- install Guided setup (also used when no command is given)
19
+ install Guided setup (the default for a new installation)
19
20
  update Update an existing installation
20
21
  uninstall Remove an installation
21
22
  color check|generate Check color pairs or generate palette candidates
@@ -27,6 +28,8 @@ Choose the harness and location in the menu. Flags are optional:
27
28
  --destination <path> Set a custom manual skill folder (must end in polishup)
28
29
  --dry-run Show changes without writing files
29
30
  --replace Back up and replace modified or unmanaged files
31
+ --plain Use numbered text menus without styling
32
+ --no-input Disable prompts; supply explicit target options
30
33
  --help Show this help
31
34
  --version Show the installer package version
32
35
 
@@ -71,175 +74,170 @@ async function main() {
71
74
  const { values, positionals } = parseArgs({ allowPositionals: true, options: {
72
75
  agent: { type: 'string' }, scope: { type: 'string' }, profile: { type: 'string' }, destination: { type: 'string' }, 'dry-run': { type: 'boolean' },
73
76
  replace: { type: 'boolean' }, help: { type: 'boolean', short: 'h' }, version: { type: 'boolean' },
77
+ plain: { type: 'boolean' }, 'no-input': { type: 'boolean' },
74
78
  } });
75
- const action = positionals[0] || 'install';
79
+ let action = positionals[0] || 'install';
76
80
  if (positionals.length > 1 || !['install', 'update', 'uninstall'].includes(action)) throw new Error(`Unknown command: ${positionals.join(' ')}. Run polishup --help.`);
77
81
  if (values.help) { console.log(HELP); return; }
78
82
  if (values.version) { console.log(metadata.version); return; }
79
83
  let agents = parseAgents(values.agent);
80
84
  if (values.profile && agents.length === 0) agents = ['hermes'];
85
+ if (values.destination && agents.length === 0) agents = ['manual'];
81
86
  if (values.scope && !['project', 'user'].includes(values.scope)) throw new Error('Choose --scope project or user.');
82
- if (values.profile && agents.some(agent => agent !== 'hermes' && agent !== 'manual')) throw new Error('--profile only applies to Hermes targets.');
87
+ if (values.profile && !agents.includes('hermes')) throw new Error('--profile only applies to Hermes targets.');
83
88
  if (values.profile && values.scope && values.scope !== 'user') throw new Error('--profile requires --scope user.');
84
89
  if (values.profile && !values.scope) values.scope = 'user';
85
90
  if (values.destination && agents.length && !agents.includes('manual')) throw new Error('--destination requires --agent manual.');
86
- if (agents.includes('manual') && !values.destination && !process.stdin.isTTY) throw new Error('--agent manual requires --destination <path>.');
87
-
88
- let reader;
89
- const ask = async question => {
90
- if (!process.stdin.isTTY) throw new Error('An interactive terminal is required, or supply --agent and --scope.');
91
- reader ??= createInterface({ input: process.stdin, output: process.stdout });
92
- const controller = new AbortController();
93
- const cancel = () => controller.abort();
94
- reader.once('SIGINT', cancel);
95
- try { return (await reader.question(question, { signal: controller.signal })).trim(); }
96
- catch (error) { if (error.name === 'AbortError' || error.code === 'ERR_USE_AFTER_CLOSE') throw new Error('Cancelled.'); throw error; }
97
- finally { reader.removeListener('SIGINT', cancel); }
98
- };
99
- const choose = async (label, choices) => {
100
- console.log(label);
101
- choices.forEach((item, i) => console.log(` ${i + 1}. ${item.label}`));
102
- const answer = await ask('Choose a number: ');
103
- const selected = choices[Number(answer) - 1];
104
- if (!selected) throw new Error('No valid choice selected. Nothing was changed.');
105
- return selected.value;
106
- };
91
+ const ui = await createPrompts({ plain: values.plain, noInput: values['no-input'] });
107
92
 
108
93
  try {
109
- let scope = values.scope;
110
- if (action !== 'install' && agents.length === 0) {
111
- const candidates = Object.keys(AGENTS).filter(agent => agent !== 'manual').flatMap(agent => ['project', 'user'].map(candidateScope => {
112
- try { return getTarget({ agent, scope: candidateScope, profile: agent === 'hermes' && candidateScope === 'user' ? values.profile : undefined }); }
113
- catch { return null; }
114
- })).filter(target => target && (!values.profile || target.agent === 'hermes') && (!scope || target.scope === scope) && fs.existsSync(target.skillDir))
115
- .filter(target => {
116
- try { return inspect(target).hasTarget; }
117
- // Explicit selection reports invalid receipts or ownership conflicts before any change.
118
- catch { return false; }
119
- });
120
- if (candidates.length === 1) { agents = [candidates[0].agent]; scope ||= candidates[0].scope; }
121
- else if (candidates.length > 1 && process.stdin.isTTY) {
122
- const selected = await choose('Choose an existing installation:', candidates.map(target => ({
123
- label: `${AGENTS[target.agent]} (${target.scope}): ${target.skillDir}`, value: target,
124
- })));
125
- agents = [selected.agent];
126
- scope ||= selected.scope;
94
+ ui.intro(`PolishUp ${metadata.version}`);
95
+ const request = { action, explicitAction: positionals.length > 0, agents: [...agents], values: { ...values } };
96
+ let draft;
97
+ while (true) {
98
+ const selection = await selectSetup({ ...request, ui, resume: draft });
99
+ for (const issue of selection.issues || []) console.error(`Needs attention: ${issue.target.skillDir}: ${issue.error.message}`);
100
+ if (selection.action === 'exit') return;
101
+ if (selection.action === 'details') {
102
+ for (const { target, state } of selection.installations) {
103
+ const changed = state.changed.length + state.extra.length + Number(state.commandChanged ||
104
+ (target.commandFile && state.consumer?.commandHash && !state.commandHash));
105
+ console.log(`${AGENTS[target.agent]} | ${target.scope}${target.profile ? ` | profile ${target.profile}` : ''} | ${state.receipt.version}`);
106
+ console.log(` ${target.skillDir}`);
107
+ console.log(` ${changed ? 'Local changes found; replacement requires approval.' : 'Managed files match their installation record.'}`);
108
+ }
109
+ console.log('Local file inspection only; harness activation and registry updates were not checked.');
110
+ const next = await ui.choose('Installation details', [{ value: 'exit', label: 'Exit' }], { back: true });
111
+ if (next === BACK) { draft = undefined; continue; }
112
+ if (selection.issues.length) process.exitCode = 1;
113
+ return;
127
114
  }
128
- }
129
- if (!agents.length || !scope) {
130
- if (!process.stdin.isTTY) throw new Error('Supply --agent and --scope outside an interactive terminal.');
131
- if (!agents.length) agents = [await choose('Choose a harness:', Object.entries(AGENTS).map(([value, label]) => ({ value, label })))];
132
- scope ||= await choose('Where should PolishUp be available?', [
133
- { value: 'project', label: `This project (${process.cwd()})` },
134
- { value: 'user', label: `All my projects (${os.homedir()})` },
135
- ]);
136
- }
137
- if (values.profile && !agents.includes('hermes')) throw new Error('--profile requires Hermes in the selected --agent list.');
138
- if (values.destination && !agents.includes('manual')) throw new Error('--destination requires --agent manual.');
139
- if (agents.includes('manual') && !values.destination) values.destination = await ask('Custom skill folder path (the final folder must be named polishup): ');
140
- if (action === 'install' && !values.agent && process.stdin.isTTY) {
141
- while (agents.length < Object.keys(AGENTS).length) {
142
- const answer = await ask('Install for another harness too? [y/N] ');
143
- if (!/^y(es)?$/i.test(answer)) break;
144
- const remaining = Object.entries(AGENTS).filter(([agent]) => !agents.includes(agent));
145
- agents.push(await choose('Choose another harness:', remaining.map(([value, label]) => ({ value, label }))));
115
+ action = selection.action;
116
+ agents = selection.agents;
117
+ const scope = selection.scope;
118
+ values.profile = selection.profile;
119
+ values.destination = selection.destination;
120
+ if (values.profile && !agents.includes('hermes')) throw new Error('--profile requires Hermes in the selected --agent list.');
121
+ if (values.destination && !agents.includes('manual')) throw new Error('--destination requires --agent manual.');
122
+ const payload = loadPayload(packageRoot);
123
+ const entries = [];
124
+ for (const agent of agents) {
125
+ try { entries.push({ targets: [agent === 'manual'
126
+ ? getManualTarget({ destination: values.destination, scope })
127
+ : getTarget({ agent, scope, profile: agent === 'hermes' ? values.profile : undefined })] }); }
128
+ catch (error) { entries.push({ targets: [], label: `${AGENTS[agent]} (${scope})`, error }); }
146
129
  }
147
- }
148
- const payload = loadPayload(packageRoot);
149
- const entries = [];
150
- for (const agent of agents) {
151
- try { entries.push({ targets: [agent === 'manual'
152
- ? getManualTarget({ destination: values.destination, scope })
153
- : getTarget({ agent, scope, profile: agent === 'hermes' ? values.profile : undefined })] }); }
154
- catch (error) { entries.push({ targets: [], label: `${AGENTS[agent]} (${scope})`, error }); }
155
- }
156
- for (const group of groupTargets(entries.flatMap(entry => entry.targets))) {
157
- try {
158
- const operation = plan(group[0], payload, action, { selectedConsumers: group.map(target => target.consumer) });
159
- entries.push({ targets: group, operation });
160
- } catch (error) { entries.push({ targets: group, error }); }
161
- }
162
- const prepared = entries.filter(entry => entry.operation || entry.error);
163
- const valid = prepared.filter(entry => entry.operation);
164
- const failedBeforeApply = prepared.filter(entry => entry.error);
165
- console.log(`PolishUp ${metadata.version} | ${action} | ${scope}`);
166
- for (const entry of failedBeforeApply) console.log(`${entry.label || entry.targets.map(target => AGENTS[target.agent]).join(' + ')}: failed to prepare: ${entry.error.message}`);
167
- for (const entry of valid) {
168
- const { operation, targets } = entry;
169
- const names = targets.map(target => AGENTS[target.agent]).join(' + ');
170
- const target = operation.target;
171
- console.log(`${names} | ${operation.kind} | ${target.agent === 'hermes' && target.profile ? `profile ${target.profile} | ` : ''}${target.skillDir}`);
172
- console.log(` Installed: ${operation.current.receipt?.version || (operation.current.exists ? 'unmanaged' : 'not installed')} | Available: ${payload.version} (${payload.revision.slice(0, 12)})`);
173
- if (operation.conflicts.length) console.log(` Conflicts: ${operation.conflicts.join('; ')}`);
174
- for (const noteTarget of targets.filter(item => item.discoveryNote)) console.log(` ${AGENTS[noteTarget.agent]}: ${noteTarget.discoveryNote}`);
175
- for (const consumer of operation.current.consumers) {
176
- if (!targets.some(item => item.agent === consumer.agent && item.scope === consumer.scope && item.profile === consumer.profile)) {
177
- console.log(` Other registered consumer: ${AGENTS[consumer.agent]} (${consumer.scope}${consumer.profile ? `, ${consumer.profile}` : ''})`);
178
- }
130
+ for (const group of groupTargets(entries.flatMap(entry => entry.targets))) {
131
+ try {
132
+ const operation = plan(group[0], payload, action, { selectedConsumers: group.map(target => target.consumer) });
133
+ entries.push({ targets: group, operation });
134
+ } catch (error) { entries.push({ targets: group, error }); }
179
135
  }
180
- for (const targetWithCommand of targets.filter(item => item.commandFile)) {
181
- console.log(` OpenCode command: ${targetWithCommand.commandFile}`);
182
- const base = scope === 'project' ? process.cwd() : os.homedir();
183
- for (const folder of ['.agents', '.claude']) {
184
- const compatible = path.join(base, folder, 'skills', 'polishup');
185
- if (fs.existsSync(compatible)) console.log(` Also present: ${compatible}. The selected OpenCode location takes precedence.`);
136
+ const prepared = entries.filter(entry => entry.operation || entry.error);
137
+ const valid = prepared.filter(entry => entry.operation);
138
+ const failedBeforeApply = prepared.filter(entry => entry.error);
139
+ console.log(`PolishUp ${metadata.version} | ${action} | ${scope}`);
140
+ for (const entry of failedBeforeApply) console.log(`${entry.label || entry.targets.map(target => AGENTS[target.agent]).join(' + ')}: failed to prepare: ${entry.error.message}`);
141
+ for (const entry of valid) {
142
+ const { operation, targets } = entry;
143
+ const names = targets.map(target => AGENTS[target.agent]).join(' + ');
144
+ const target = operation.target;
145
+ console.log(`${names} | ${operation.kind} | ${target.agent === 'hermes' && target.profile ? `profile ${target.profile} | ` : ''}${target.skillDir}`);
146
+ console.log(` Installed: ${operation.current.receipt?.version || (operation.current.exists ? 'unmanaged' : 'not installed')} | Available: ${payload.version} (${payload.revision.slice(0, 12)})`);
147
+ if (operation.conflicts.length) console.log(` Conflicts: ${operation.conflicts.join('; ')}`);
148
+ for (const noteTarget of targets.filter(item => item.discoveryNote)) console.log(` ${AGENTS[noteTarget.agent]}: ${noteTarget.discoveryNote}`);
149
+ for (const consumer of operation.current.consumers) {
150
+ if (!targets.some(item => item.agent === consumer.agent && item.scope === consumer.scope && item.profile === consumer.profile)) {
151
+ console.log(` Other registered consumer: ${AGENTS[consumer.agent]} (${consumer.scope}${consumer.profile ? `, ${consumer.profile}` : ''})`);
152
+ }
153
+ }
154
+ for (const targetWithCommand of targets.filter(item => item.commandFile)) {
155
+ console.log(` OpenCode command: ${targetWithCommand.commandFile}`);
156
+ const base = scope === 'project' ? target.projectRoot : os.homedir();
157
+ for (const folder of ['.agents', '.claude']) {
158
+ const compatible = path.join(base, folder, 'skills', 'polishup');
159
+ if (fs.existsSync(compatible)) console.log(` Also present: ${compatible}. The selected OpenCode location takes precedence.`);
160
+ }
186
161
  }
187
162
  }
188
- }
189
163
 
190
- if (action === 'update') {
191
- const release = await checkUpdate(metadata);
192
- if (release.kind === 'local') console.log('Local build: checking bundled files. Public registry updates are disabled until publication.');
193
- if (release.kind === 'newer') {
194
- console.log(`Installer ${release.version} is available.`);
195
- if (values['dry-run']) { console.log('Dry run: the newer package was not downloaded or executed.'); return; }
196
- const forwarded = forwardedTargetArgs({ agents, scope, profile: values.profile, destination: values.destination, replace: values.replace });
197
- reader?.close();
198
- reader = null;
199
- await runNewVersion(release.version, forwarded);
164
+ if (action === 'update') {
165
+ const release = await checkUpdate(metadata);
166
+ if (release.kind === 'local') console.log('Local build: checking bundled files. Public registry updates are disabled until publication.');
167
+ if (release.kind === 'newer') {
168
+ console.log(`Installer ${release.version} is available.`);
169
+ if (values['dry-run']) { console.log('Dry run: the newer package was not downloaded or executed.'); return; }
170
+ const forwarded = forwardedTargetArgs({ agents, scope, profile: values.profile, destination: values.destination,
171
+ replace: values.replace, plain: values.plain, noInput: values['no-input'] });
172
+ ui.close();
173
+ await runNewVersion(release.version, forwarded);
174
+ return;
175
+ }
176
+ }
177
+ if (values['dry-run']) {
178
+ for (const entry of valid) apply(entry.operation, { dryRun: true });
179
+ console.log('Dry run: no files were written.');
180
+ if (failedBeforeApply.length) process.exitCode = 1;
200
181
  return;
201
182
  }
202
- }
203
- if (values['dry-run']) {
204
- for (const entry of valid) apply(entry.operation, { dryRun: true });
205
- console.log('Dry run: no files were written.');
206
- if (failedBeforeApply.length) process.exitCode = 1;
207
- return;
208
- }
209
- let replace = values.replace || false;
210
- if (!replace && valid.some(entry => entry.operation.conflicts.length) && process.stdin.isTTY) {
211
- replace = /^y(es)?$/i.test(await ask('Back up and replace/remove only the conflicting targets? [y/N] '));
212
- }
213
- if (process.stdin.isTTY && !(values.agent && values.scope)) {
214
- if (!/^y(es)?$/i.test(await ask(`Apply the prepared changes to ${valid.length} target location(s)? [y/N] `))) {
215
- console.log('Cancelled. No files changed.'); return;
183
+ let replace = values.replace || false;
184
+ if (!replace && valid.some(entry => entry.operation.conflicts.length) && ui.interactive) {
185
+ const choice = await ui.choose('Local changes require a decision', [
186
+ { value: 'replace', label: 'Back up and replace/remove conflicting targets' },
187
+ { value: 'skip', label: 'Skip conflicting targets' },
188
+ { value: 'cancel', label: 'Cancel' },
189
+ ], { back: selection.canGoBack });
190
+ if (choice === BACK) { draft = selection; continue; }
191
+ if (choice === 'cancel') { console.log('Cancelled. No files changed.'); return; }
192
+ replace = choice === 'replace';
216
193
  }
217
- }
218
- let failed = failedBeforeApply.length > 0;
219
- for (const entry of valid) {
220
- const { operation, targets } = entry;
221
- const names = targets.map(target => AGENTS[target.agent]).join(' + ');
222
- if (operation.kind === 'none') { console.log(`${names}: already up to date or not installed.`); continue; }
223
- if (operation.conflicts.length && !replace) {
224
- console.log(`${names}: skipped because conflicts were not approved for replacement.`);
225
- failed = true;
226
- continue;
194
+ const pending = valid.filter(entry => entry.operation.kind !== 'none' && (!entry.operation.conflicts.length || replace));
195
+ if (ui.interactive && selection.canGoBack && (pending.length || failedBeforeApply.length)) {
196
+ const choice = await ui.choose('Review changes', [
197
+ ...(pending.length ? [{ value: 'apply', label: `${action === 'uninstall' ? 'Remove' : action === 'update' ? 'Update' : 'Install'} ${pending.length} target location(s)` }] : []),
198
+ { value: 'cancel', label: 'Cancel' },
199
+ ], { back: true });
200
+ if (choice === BACK) { draft = selection; continue; }
201
+ if (choice === 'cancel') {
202
+ console.log('Cancelled. No files changed.'); return;
203
+ }
227
204
  }
228
- try {
229
- const result = apply(operation, { replace });
230
- console.log(`${names}: ${action === 'uninstall' ? result.detached ? 'association removed; shared files retained' : 'removed' : 'installed and verified'}.`);
231
- if (result.backup) console.log(` Previous files retained at: ${result.backup}`);
232
- if (action !== 'uninstall') for (const target of targets) console.log(` In ${AGENTS[target.agent]}: ${target.invocation}`);
233
- } catch (error) {
234
- console.log(`${names}: failed: ${error.message}`);
235
- failed = true;
205
+ let failed = failedBeforeApply.length > 0;
206
+ let changed = 0, unchanged = 0, skipped = 0, failedCount = failedBeforeApply.length;
207
+ for (const entry of valid) {
208
+ const { operation, targets } = entry;
209
+ const names = targets.map(target => AGENTS[target.agent]).join(' + ');
210
+ if (operation.kind === 'none') {
211
+ unchanged++;
212
+ console.log(`${names}: ${action === 'uninstall' ? 'not installed' : 'unchanged; already up to date'}.`);
213
+ continue;
214
+ }
215
+ if (operation.conflicts.length && !replace) {
216
+ console.log(`${names}: skipped because conflicts were not approved for replacement.`);
217
+ failed = true;
218
+ skipped++;
219
+ continue;
220
+ }
221
+ try {
222
+ const result = apply(operation, { replace });
223
+ changed++;
224
+ console.log(`${names}: ${action === 'uninstall' ? result.detached ? 'association removed; shared files retained' : 'removed' : operation.current.exists ? 'updated and verified' : 'installed and verified'}.`);
225
+ if (result.backup) console.log(` Previous files retained at: ${result.backup}`);
226
+ if (action !== 'uninstall') for (const target of targets) console.log(` In ${AGENTS[target.agent]}: ${target.invocation}`);
227
+ } catch (error) {
228
+ console.log(`${names}: failed: ${error.message}`);
229
+ failed = true;
230
+ failedCount++;
231
+ }
236
232
  }
233
+ console.log(`Result: ${changed} changed, ${unchanged} unchanged, ${skipped} skipped, ${failedCount} failed.`);
234
+ if (changed && action !== 'uninstall') {
235
+ console.log('Refresh skills or start a new session if a harness does not show the change. File verification does not prove activation.');
236
+ }
237
+ if (failed) process.exitCode = 1;
238
+ return;
237
239
  }
238
- if (valid.some(entry => entry.operation.kind !== 'none' && entry.operation.conflicts.length === 0) && action !== 'uninstall') {
239
- console.log('Refresh skills or start a new session if a harness does not show the change. File verification does not prove activation.');
240
- }
241
- if (failed) process.exitCode = 1;
242
- } finally { reader?.close(); }
240
+ } finally { ui.close(); }
243
241
  }
244
242
 
245
243
  main().catch(error => {
@@ -253,4 +251,14 @@ main().catch(error => {
253
251
  }
254
252
  console.error(`PolishUp: ${error.message}`);
255
253
  process.exitCode = error.message === 'Cancelled.' ? 130 : 1;
254
+ }).finally(async () => {
255
+ // Windows console reads can survive readline cleanup after revisiting prompts.
256
+ // Finish only after the command and its output are complete, including updater children.
257
+ if (process.platform === 'win32' && process.stdin.isTTY) {
258
+ await Promise.all([process.stdout, process.stderr].map(stream => new Promise(resolve => {
259
+ if (stream.destroyed || !stream.writable) resolve();
260
+ else stream.write('', resolve);
261
+ })));
262
+ process.exit(process.exitCode ?? 0);
263
+ }
256
264
  });
package/cli/menu.mjs ADDED
@@ -0,0 +1,124 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { AGENTS, getTarget, getManualTarget, inspect } from './installations.mjs';
5
+ import { projectRootFor, hermesProfiles } from './hosts.mjs';
6
+ import { BACK } from './prompts.mjs';
7
+ import { detectHarnesses } from './detection.mjs';
8
+
9
+ const contextFor = context => ({ cwd: process.cwd(), home: os.homedir(), env: process.env, platform: process.platform, ...context });
10
+
11
+ export function findInstallations(context = {}) {
12
+ const options = contextFor(context);
13
+ const installations = [], issues = [], seen = new Set(), failedPaths = new Set();
14
+ for (const agent of Object.keys(AGENTS).filter(agent => agent !== 'manual')) {
15
+ for (const scope of options.scope ? [options.scope] : ['project', 'user']) {
16
+ let profiles = [undefined];
17
+ if (agent === 'hermes' && scope === 'user') {
18
+ try { profiles = options.profile ? [options.profile] : [undefined, ...hermesProfiles(options)]; }
19
+ catch { /* Explicit Hermes selection reports profile-resolution errors. */ }
20
+ }
21
+ for (const profile of profiles) {
22
+ let target;
23
+ try { target = getTarget({ ...options, agent, scope, profile }); }
24
+ catch { continue; }
25
+ if (!fs.existsSync(target.skillDir)) continue;
26
+ const directory = options.platform === 'win32' ? target.skillDir.toLowerCase() : target.skillDir;
27
+ const key = `${agent}:${scope}:${directory}`;
28
+ if (seen.has(key)) continue;
29
+ seen.add(key);
30
+ try {
31
+ const state = inspect(target);
32
+ if (state.hasTarget) installations.push({ target, state, profile });
33
+ } catch (error) {
34
+ if (!failedPaths.has(directory)) { issues.push({ target, error }); failedPaths.add(directory); }
35
+ }
36
+ }
37
+ }
38
+ }
39
+ return { installations, issues };
40
+ }
41
+
42
+ export function harnessChoices(context = {}, found = { installations: [] }) {
43
+ context = contextFor(context);
44
+ const detected = detectHarnesses({ ...context, cwd: projectRootFor(context.cwd) });
45
+ const choices = Object.entries(AGENTS).map(([value, label]) => {
46
+ const scopes = [...new Set(found.installations.filter(entry => entry.target.agent === value).map(entry => entry.target.scope))];
47
+ return { value, label: `${label}${detected[value]?.status === 'detected' ? ' (Detected)' : ''}`,
48
+ ...(scopes.length ? { hint: `PolishUp installed: ${scopes.join(', ')}` } : {}) };
49
+ });
50
+ const rank = choice => choice.value === 'manual' ? 2 : detected[choice.value]?.status === 'detected' ? 0 : 1;
51
+ return choices.sort((left, right) => rank(left) - rank(right));
52
+ }
53
+
54
+ export async function selectSetup({ action = 'install', explicitAction = false, agents = [], values = {}, ui, context = {}, resume }) {
55
+ context = contextFor(context);
56
+ const found = (!agents.length || ui.interactive) ? findInstallations({ ...context, scope: values.scope, profile: values.profile }) : { installations: [], issues: [] };
57
+ const state = { action, agents: [...agents], scope: values.scope, profile: values.profile, destination: values.destination, ...resume };
58
+ const existingMode = () => state.action !== 'install' && !agents.length && found.installations.length > 0;
59
+ const selectExisting = entry => { state.agents = [entry.target.agent]; state.scope = entry.target.scope; state.profile = entry.profile; };
60
+ const selection = () => ({ action: state.action, agents: state.agents, scope: state.scope,
61
+ profile: state.scope === 'user' && state.agents.includes('hermes') ? state.profile : undefined,
62
+ destination: state.agents.includes('manual') ? state.destination : undefined, issues: found.issues });
63
+ if (!ui.interactive) {
64
+ if (existingMode() && found.installations.length === 1 && !found.issues.length) selectExisting(found.installations[0]);
65
+ if (!state.agents.length || !state.scope) throw new Error('Supply --agent and --scope outside an interactive terminal.');
66
+ if (state.agents.includes('manual') && !state.destination) throw new Error('--agent manual requires --destination <path> when input is disabled.');
67
+ return selection();
68
+ }
69
+ const rootMenu = !explicitAction && !agents.length && !values.destination && !values.profile && Boolean(found.installations.length || found.issues.length);
70
+ const profileStep = () => state.agents.includes('hermes') && state.scope === 'user' && !values.profile && !existingMode();
71
+ const profilesAvailable = () => {
72
+ if (!profileStep()) return false;
73
+ try { return hermesProfiles(context).length > 0; }
74
+ catch { return true; }
75
+ };
76
+ const steps = [
77
+ { enabled: () => rootMenu, run: opts => ui.choose('What would you like to do?', [
78
+ { value: 'install', label: 'Install' }, { value: 'update', label: 'Update' },
79
+ { value: 'uninstall', label: 'Uninstall' }, { value: 'details', label: 'View installation details' }, { value: 'exit', label: 'Exit' },
80
+ ], { ...opts, initialValue: state.action }), save: value => { state.action = value; } },
81
+ { enabled: existingMode, run: opts => ui.choose('Choose an existing installation', found.installations.map(entry => ({
82
+ value: entry, label: `${AGENTS[entry.target.agent]} (${entry.target.scope}${entry.target.profile ? `, ${entry.target.profile}` : ''})`, hint: entry.target.skillDir,
83
+ })), { ...opts, initialValue: found.installations.find(entry => entry.target.agent === state.agents[0] && entry.target.scope === state.scope && entry.profile === state.profile) }), save: selectExisting },
84
+ { enabled: () => !agents.length && !existingMode(), run: opts => ui.multi('Select harnesses', harnessChoices(context, found),
85
+ { ...opts, initialValues: state.agents }), save: value => { state.agents = value; } },
86
+ { enabled: () => !values.scope && !existingMode(), run: opts => ui.choose('Where should PolishUp be available?', [
87
+ { value: 'project', label: 'This project', hint: projectRootFor(context.cwd) },
88
+ { value: 'user', label: 'Personal installation', hint: context.home },
89
+ ], { ...opts, initialValue: state.scope }), save: value => { state.scope = value; } },
90
+ { enabled: () => state.agents.includes('manual') && !values.destination,
91
+ run: opts => ui.text('Custom skill folder path (must end in polishup)', { ...opts, initialValue: state.destination, validate(value) {
92
+ try { getManualTarget({ ...context, destination: value, scope: state.scope }); }
93
+ catch (error) { return error.message; }
94
+ } }), save: value => { state.destination = value; } },
95
+ { enabled: profilesAvailable, run: opts => {
96
+ const configured = getTarget({ ...context, agent: 'hermes', scope: 'user' });
97
+ return ui.choose('Choose a Hermes profile', [{ value: '', label: 'Current location', hint: configured.configRoot },
98
+ ...hermesProfiles(context).map(value => ({ value, label: value }))], { ...opts, initialValue: state.profile || '' });
99
+ }, save: value => { state.profile = value || undefined; } },
100
+ ];
101
+ const available = () => steps.flatMap((step, index) => step.enabled() ? [index] : []);
102
+ let index = resume ? available().at(-1) : available()[0];
103
+ while (index !== undefined && index < steps.length) {
104
+ if (!steps[index].enabled()) { index++; continue; }
105
+ const previous = available().filter(value => value < index).at(-1);
106
+ let value;
107
+ try { value = await steps[index].run({ back: previous !== undefined }); }
108
+ catch (error) {
109
+ if (error.message === 'Cancelled.') throw error;
110
+ if (!['EACCES', 'EPERM', 'ENOENT', 'ENOTDIR', 'ELOOP'].includes(error.code) && !/^HERMES_HOME|^Hermes profile|^Invalid Hermes/.test(error.message)) throw error;
111
+ value = await ui.choose(`Cannot continue: ${error.message}`, [{ value: 'retry', label: 'Retry' }], { back: true });
112
+ if (value === 'retry') continue;
113
+ }
114
+ if (value === BACK) {
115
+ if (previous === undefined) throw new Error('Cancelled.');
116
+ index = previous;
117
+ continue;
118
+ }
119
+ steps[index].save(value);
120
+ if (state.action === 'exit' || state.action === 'details') return { action: state.action, ...found };
121
+ index++;
122
+ }
123
+ return { ...selection(), canGoBack: available().length > 0 };
124
+ }
@@ -0,0 +1,166 @@
1
+ import { createInterface } from 'node:readline';
2
+ import { styleText } from 'node:util';
3
+
4
+ const enabled = value => Boolean(value && value !== '0' && value !== 'false');
5
+ const cancelled = () => new Error('Cancelled.');
6
+ export const BACK = Symbol('back');
7
+
8
+ export async function createPrompts({ input = process.stdin, output = process.stdout, env = process.env, plain = false, noInput = false } = {}) {
9
+ const interactive = Boolean(input.isTTY && !noInput && !enabled(env.CI));
10
+ let rich, core;
11
+ if (interactive && output.isTTY && !plain && !env.NO_COLOR && env.TERM !== 'dumb' && !enabled(env.ACCESSIBLE)) {
12
+ try { rich = await import('@clack/prompts'); core = await import('@clack/core'); }
13
+ catch (error) {
14
+ if (error.code !== 'ERR_MODULE_NOT_FOUND' || !error.message.includes('@clack/prompts')) throw error;
15
+ output.write('Using text menus. Run npm ci in the checkout to enable keyboard menus.\n');
16
+ }
17
+ }
18
+ let reader, lines, aborted = false, activeBack = false;
19
+ const write = message => output.write(`${message}\n`);
20
+ const interrupt = () => { aborted = true; reader?.close(); };
21
+ const plainEscape = (_value, key) => {
22
+ if (activeBack && key?.name === 'escape') {
23
+ reader.write(null, { ctrl: true, name: 'u' });
24
+ reader.emit('line', BACK);
25
+ }
26
+ };
27
+ const terminal = Boolean(input.isTTY && output.isTTY && typeof input.setRawMode === 'function');
28
+ const footer = (kind, back) => [
29
+ ...(kind !== 'text' ? [rich ? '↑/↓: Move' : 'Numbers: Select'] : []),
30
+ ...(kind === 'multi' && rich ? ['Space: Select'] : []),
31
+ 'Enter: Continue', ...(back ? [terminal || rich ? 'Esc: Back' : kind === 'text' ? ':back: Back' : 'b: Back'] : []), 'Ctrl+C: Cancel',
32
+ ];
33
+ const ask = async (message, back = false) => {
34
+ if (!interactive) throw new Error('Supply --agent and --scope outside an interactive terminal, or when input is disabled.');
35
+ if (aborted) throw cancelled();
36
+ if (!reader) {
37
+ reader = createInterface({ input, output,
38
+ terminal, crlfDelay: Infinity, escapeCodeTimeout: 50 });
39
+ lines = reader[Symbol.asyncIterator]();
40
+ reader.on('SIGINT', interrupt);
41
+ process.on('SIGINT', interrupt);
42
+ input.on('keypress', plainEscape);
43
+ }
44
+ activeBack = back;
45
+ if (reader.terminal) { reader.setPrompt(`${message}: `); reader.prompt(); }
46
+ else output.write(`${message}: `);
47
+ const result = await lines.next();
48
+ activeBack = false;
49
+ if (result.done || aborted) throw cancelled();
50
+ return result.value === BACK ? BACK : result.value.trim();
51
+ };
52
+ const result = async (run, back = false) => {
53
+ let goBack = false;
54
+ const keypress = (_value, key) => { goBack = key?.name === 'escape'; };
55
+ if (back) input.on('keypress', keypress);
56
+ try {
57
+ const value = await run();
58
+ if (rich.isCancel(value)) { if (back && goBack) return BACK; throw cancelled(); }
59
+ return value;
60
+ } finally { input.removeListener('keypress', keypress); }
61
+ };
62
+ const options = choices => choices.map(({ value, label, hint }) => ({ value, label, ...(hint ? { hint } : {}) }));
63
+ const richPrompt = async ({ kind, message, choices, back, initialValue, initialValues, validate }) => {
64
+ const paint = (format, text) => styleText(format, text, { validateStream: false });
65
+ const Prompt = kind === 'text' ? core.TextPrompt : kind === 'multi' ? core.MultiSelectPrompt : core.SelectPrompt;
66
+ const instructions = rich.formatInstructionFooter(output, footer(kind, back), true);
67
+ const controller = new AbortController();
68
+ const abort = () => controller.abort();
69
+ const endKey = (_value, key) => { if (key?.ctrl && key.name === 'd') queueMicrotask(abort); };
70
+ const prompt = new Prompt({ input, output, signal: controller.signal, ...(choices ? { options: options(choices) } : {}),
71
+ initialValue, initialValues, defaultValue: kind === 'text' ? initialValue : undefined,
72
+ validate: validate || (kind === 'multi' ? value => value?.length ? undefined : 'Select at least one harness.' : undefined),
73
+ render() {
74
+ const title = `${rich.symbol(this.state)} ${message}\n`;
75
+ if (this.state === 'submit' || this.state === 'cancel') {
76
+ const summary = kind === 'text' ? this.value || '' : choices.filter(choice => kind === 'multi'
77
+ ? this.value?.includes(choice.value) : choice.value === this.value).map(choice => choice.label).join(', ');
78
+ return `${title}${rich.S_BAR} ${paint('dim', summary)}`;
79
+ }
80
+ const body = kind === 'text' ? [this.userInputWithCursor] : rich.limitOptions({
81
+ options: this.options, cursor: this.cursor, output, columnPadding: 3, rowPadding: instructions.length + 4,
82
+ style: (choice, focused) => {
83
+ const selected = kind === 'multi' && this.value?.includes(choice.value);
84
+ const marker = kind === 'multi' ? selected ? rich.S_CHECKBOX_SELECTED : rich.S_CHECKBOX_INACTIVE
85
+ : focused ? rich.S_RADIO_ACTIVE : rich.S_RADIO_INACTIVE;
86
+ const row = `${marker} ${choice.label}${focused && choice.hint ? ` (${choice.hint})` : ''}`;
87
+ return focused ? paint(['cyanBright', 'bold'], `> ${row}`) : ` ${paint(selected ? 'green' : 'dim', row)}`;
88
+ },
89
+ });
90
+ const error = this.state === 'error' ? String(this.error).split('\n').map(line => `${rich.S_BAR} ${paint('yellow', line)}`) : [];
91
+ return [title.trimEnd(), ...body.map(line => `${rich.S_BAR} ${line}`), ...error, ...instructions].join('\n');
92
+ },
93
+ });
94
+ input.once('end', abort);
95
+ input.once('close', abort);
96
+ input.on('keypress', endKey);
97
+ try {
98
+ if (input.readableEnded || input.destroyed) abort();
99
+ return await prompt.prompt();
100
+ } finally {
101
+ input.removeListener('end', abort);
102
+ input.removeListener('close', abort);
103
+ input.removeListener('keypress', endKey);
104
+ }
105
+ };
106
+ const choose = async (message, choices, { multiple = false, back = false, initialValue, initialValues = [] } = {}) => {
107
+ if (!choices.length) throw new Error('No available choices. Supply an explicit target instead.');
108
+ if (!interactive) throw new Error('Supply --agent and --scope outside an interactive terminal.');
109
+ if (rich) {
110
+ return result(() => richPrompt({ kind: multiple ? 'multi' : 'select', message, choices, back, initialValue, initialValues }), back);
111
+ }
112
+ write(message);
113
+ choices.forEach((item, i) => write(` ${i + 1}. ${item.label}${item.hint ? ` (${item.hint})` : ''}${(multiple ? initialValues.includes(item.value) : item.value === initialValue) ? ' [selected]' : ''}`));
114
+ if (multiple ? initialValues.length : initialValue !== undefined) write('Enter keeps the previous selection.');
115
+ write(footer(multiple ? 'multi' : 'select', back).join(' | '));
116
+ while (true) {
117
+ const answer = await ask(multiple ? 'Choose numbers separated by commas' : 'Choose a number', back);
118
+ if (answer === BACK) return BACK;
119
+ if (back && /^(b|:back)$/i.test(answer)) return BACK;
120
+ if (/^(q|:cancel)$/i.test(answer)) throw cancelled();
121
+ if (!answer && (multiple ? initialValues.length : initialValue !== undefined)) return multiple ? [...initialValues] : initialValue;
122
+ const parts = answer.split(',').map(part => part.trim());
123
+ const indexes = parts.map(part => Number(part) - 1);
124
+ if (parts.every(part => /^[1-9]\d*$/.test(part)) && (multiple || parts.length === 1) &&
125
+ new Set(indexes).size === indexes.length && indexes.every(index => index < choices.length)) {
126
+ const values = indexes.map(index => choices[index].value);
127
+ return multiple ? values : values[0];
128
+ }
129
+ write(`Enter ${multiple ? 'valid, distinct numbers' : 'a valid number'} from 1 to ${choices.length}, or press Ctrl+C to cancel.`);
130
+ }
131
+ };
132
+ return {
133
+ interactive,
134
+ intro(message) { if (interactive) { if (rich) rich.intro(message, { output }); else write(`${message}\n`); } },
135
+ choose,
136
+ multi(message, choices, options = {}) { return choose(message, choices, { ...options, multiple: true }); },
137
+ async text(message, { validate = value => value ? undefined : 'Enter a value.', back = false, initialValue } = {}) {
138
+ const check = value => value === ':cancel' || (back && value === ':back') ? undefined : validate(value);
139
+ if (rich) {
140
+ const value = await result(() => richPrompt({ kind: 'text', message, initialValue, validate: check, back }), back);
141
+ if (value === BACK || (back && value === ':back')) return BACK;
142
+ if (value === ':cancel') throw cancelled();
143
+ return value;
144
+ }
145
+ write(message);
146
+ write(footer('text', back).join(' | '));
147
+ while (true) {
148
+ const value = await ask(`Path${initialValue ? ` [${initialValue}]` : ''}`, back);
149
+ if (value === BACK) return BACK;
150
+ const answer = value || initialValue || '';
151
+ if (back && answer === ':back') return BACK;
152
+ if (answer === ':cancel') throw cancelled();
153
+ const error = validate(answer);
154
+ if (!error) return answer;
155
+ write(error);
156
+ }
157
+ },
158
+ close() {
159
+ reader?.close();
160
+ input.pause();
161
+ input.unref?.();
162
+ input.removeListener('keypress', plainEscape);
163
+ process.removeListener('SIGINT', interrupt);
164
+ },
165
+ };
166
+ }
package/cli/update.mjs CHANGED
@@ -24,10 +24,11 @@ export function updateInvocation(version, args, npmCli) {
24
24
  `--package=${PACKAGE_NAME}@${version}`, '--', 'polishup', 'update', ...args] };
25
25
  }
26
26
 
27
- export function forwardedTargetArgs({ agent, agents, scope, profile, destination, replace = false }) {
27
+ export function forwardedTargetArgs({ agent, agents, scope, profile, destination, replace = false, plain = false, noInput = false }) {
28
28
  const selected = agents ?? (agent ? [agent] : []);
29
29
  return ['--agent', selected.join(','), '--scope', scope, ...(profile ? ['--profile', profile] : []),
30
- ...(destination ? ['--destination', destination] : []), ...(replace ? ['--replace'] : [])];
30
+ ...(destination ? ['--destination', destination] : []), ...(replace ? ['--replace'] : []),
31
+ ...(plain ? ['--plain'] : []), ...(noInput ? ['--no-input'] : [])];
31
32
  }
32
33
 
33
34
  function findNpmCli(env) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "polishup-cli",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Research-informed guidance for better AI work across writing, design, code, and more.",
5
5
  "author": "fachriaziz",
6
6
  "homepage": "https://github.com/fachriaziz/polishup#readme",
@@ -37,6 +37,9 @@
37
37
  ".opencode/commands/polishup.md",
38
38
  "cli/index.mjs",
39
39
  "cli/hosts.mjs",
40
+ "cli/detection.mjs",
41
+ "cli/menu.mjs",
42
+ "cli/prompts.mjs",
40
43
  "cli/installations.mjs",
41
44
  "cli/update.mjs"
42
45
  ],
@@ -49,5 +52,9 @@
49
52
  "devDependencies": {
50
53
  "colorjs.io": "0.7.1",
51
54
  "esbuild": "0.28.2"
55
+ },
56
+ "dependencies": {
57
+ "@clack/core": "1.6.0",
58
+ "@clack/prompts": "1.9.0"
52
59
  }
53
60
  }
@@ -13,7 +13,7 @@ node "<absolute-skill-path>/scripts/color.mjs" check "#222222" "#ffffff" --json
13
13
  node "<absolute-skill-path>/scripts/color.mjs" generate --input "<palette.json>" --json
14
14
  ```
15
15
 
16
- Keep caller-relative input paths relative to the caller. Do not assume package-cache locations. `node "<package>/cli/index.mjs" color ...` is an optional wrapper over the same prepared implementation. The current private package is unpublished; do not fetch an unrelated registry package named PolishUp. Complete manual, native and installer copies carry the helper; reading instructions alone does not supply file access or a runtime.
16
+ Keep caller-relative input paths relative to the caller. Do not assume package-cache locations. The optional `polishup-cli` package exposes the same helper through `polishup color ...` or `node "<package>/cli/index.mjs" color ...`. Complete manual, native and installer copies carry the helper; reading instructions alone does not supply file access or a runtime.
17
17
 
18
18
  ## Check a pair
19
19
 
@@ -5605,7 +5605,7 @@ async function runColorCommand(args) {
5605
5605
  var toolVersion, engineVersion, init_color2 = __esm({
5606
5606
  "cli/color.mjs"() {
5607
5607
  init_src();
5608
- toolVersion = "0.1.0", engineVersion = "0.7.1";
5608
+ toolVersion = "0.2.0", engineVersion = "0.7.1";
5609
5609
  }
5610
5610
  });
5611
5611