polishup-cli 0.0.0-stage → 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/.opencode/commands/polishup.md +6 -0
- package/LICENSE +21 -0
- package/README.md +167 -3
- package/cli/detection.mjs +75 -0
- package/cli/hosts.mjs +181 -0
- package/cli/index.mjs +264 -0
- package/cli/installations.mjs +300 -0
- package/cli/menu.mjs +124 -0
- package/cli/prompts.mjs +166 -0
- package/cli/update.mjs +58 -0
- package/package.json +60 -6
- package/skills/polishup/LICENSE.txt +21 -0
- package/skills/polishup/SKILL.md +84 -0
- package/skills/polishup/references/code/implementation.md +43 -0
- package/skills/polishup/references/code/index.md +13 -0
- package/skills/polishup/references/code/rules.md +24 -0
- package/skills/polishup/references/colors.md +65 -0
- package/skills/polishup/references/research.md +50 -0
- package/skills/polishup/references/tools.md +57 -0
- package/skills/polishup/references/ui-ux/accessibility.md +136 -0
- package/skills/polishup/references/ui-ux/art-direction.md +127 -0
- package/skills/polishup/references/ui-ux/audio-and-video.md +121 -0
- package/skills/polishup/references/ui-ux/data-visualization.md +130 -0
- package/skills/polishup/references/ui-ux/design-ethics.md +98 -0
- package/skills/polishup/references/ui-ux/design-evaluation.md +123 -0
- package/skills/polishup/references/ui-ux/design-systems.md +110 -0
- package/skills/polishup/references/ui-ux/foundations.md +23 -0
- package/skills/polishup/references/ui-ux/index.md +29 -0
- package/skills/polishup/references/ui-ux/information-architecture.md +132 -0
- package/skills/polishup/references/ui-ux/interaction-design.md +155 -0
- package/skills/polishup/references/ui-ux/motion-design.md +110 -0
- package/skills/polishup/references/ui-ux/performance.md +109 -0
- package/skills/polishup/references/ui-ux/responsive-design.md +98 -0
- package/skills/polishup/references/ui-ux/rules.md +36 -0
- package/skills/polishup/references/ui-ux/ux-research.md +110 -0
- package/skills/polishup/references/ui-ux/visual-design.md +147 -0
- package/skills/polishup/references/writing/accessibility-and-inclusion.md +57 -0
- package/skills/polishup/references/writing/content-and-evidence.md +83 -0
- package/skills/polishup/references/writing/content-structure.md +94 -0
- package/skills/polishup/references/writing/foundations.md +19 -0
- package/skills/polishup/references/writing/index.md +17 -0
- package/skills/polishup/references/writing/language-and-style.md +83 -0
- package/skills/polishup/references/writing/multilingual-writing.md +51 -0
- package/skills/polishup/references/writing/purpose-audience-context.md +72 -0
- package/skills/polishup/references/writing/review-and-revision.md +81 -0
- package/skills/polishup/references/writing/rules.md +26 -0
- package/skills/polishup/references/writing/voice-and-tone.md +72 -0
- package/skills/polishup/scripts/NOTICE.txt +27 -0
- package/skills/polishup/scripts/color.mjs +5626 -0
package/cli/index.mjs
ADDED
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
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 { parseArgs } from 'node:util';
|
|
7
|
+
import { AGENTS, loadPayload, getManualTarget, getTarget, plan, apply } from './installations.mjs';
|
|
8
|
+
import { checkUpdate, forwardedTargetArgs, runNewVersion } from './update.mjs';
|
|
9
|
+
import { BACK, createPrompts } from './prompts.mjs';
|
|
10
|
+
import { selectSetup } from './menu.mjs';
|
|
11
|
+
|
|
12
|
+
const packageRoot = fileURLToPath(new URL('../', import.meta.url));
|
|
13
|
+
const metadata = JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf8'));
|
|
14
|
+
const helpCommand = metadata.private ? 'node "<path-to-polishup>/cli/index.mjs"' : `npx ${metadata.name}`;
|
|
15
|
+
const HELP = `PolishUp ${metadata.version}
|
|
16
|
+
|
|
17
|
+
Usage: ${helpCommand} [install|update|uninstall|color] [options]
|
|
18
|
+
|
|
19
|
+
install Guided setup (the default for a new installation)
|
|
20
|
+
update Update an existing installation
|
|
21
|
+
uninstall Remove an installation
|
|
22
|
+
color check|generate Check color pairs or generate palette candidates
|
|
23
|
+
|
|
24
|
+
Choose the harness and location in the menu. Flags are optional:
|
|
25
|
+
--agent <id[,id...]> Select one or more harnesses (for example codex,claude)
|
|
26
|
+
--scope project|user Select the installation scope
|
|
27
|
+
--profile <name> Select an existing Hermes user profile
|
|
28
|
+
--destination <path> Set a custom manual skill folder (must end in polishup)
|
|
29
|
+
--dry-run Show changes without writing files
|
|
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
|
|
33
|
+
--help Show this help
|
|
34
|
+
--version Show the installer package version
|
|
35
|
+
|
|
36
|
+
Examples:
|
|
37
|
+
${helpCommand}
|
|
38
|
+
${helpCommand} update
|
|
39
|
+
${helpCommand} uninstall
|
|
40
|
+
${helpCommand} install --agent codex,claude --scope project
|
|
41
|
+
${helpCommand} install --agent manual --destination ./custom/skills/polishup --scope project
|
|
42
|
+
|
|
43
|
+
${metadata.private
|
|
44
|
+
? 'Replace <path-to-polishup> with the absolute package directory. Run from the destination project.\nThis build is unpublished; registry updates are disabled.'
|
|
45
|
+
: 'Registry updates are enabled.'}
|
|
46
|
+
`;
|
|
47
|
+
|
|
48
|
+
function parseAgents(value) {
|
|
49
|
+
if (value === undefined) return [];
|
|
50
|
+
const agents = value.split(',').map(item => item.trim());
|
|
51
|
+
if (!agents.length || agents.some(agent => !agent)) throw new Error('Use comma-separated harness IDs without empty entries.');
|
|
52
|
+
const unknown = agents.filter(agent => !Object.hasOwn(AGENTS, agent));
|
|
53
|
+
if (unknown.length) throw new Error(`Unknown harness: ${unknown.join(', ')}. Choose --agent ${Object.keys(AGENTS).join(', ')}.`);
|
|
54
|
+
if (new Set(agents).size !== agents.length) throw new Error('List each harness only once in --agent.');
|
|
55
|
+
return agents;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function groupTargets(targets) {
|
|
59
|
+
const groups = new Map();
|
|
60
|
+
for (const target of targets) {
|
|
61
|
+
const key = path.resolve(target.skillDir);
|
|
62
|
+
if (!groups.has(key)) groups.set(key, []);
|
|
63
|
+
groups.get(key).push(target);
|
|
64
|
+
}
|
|
65
|
+
return [...groups.values()];
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function main() {
|
|
69
|
+
if (process.argv[2] === 'color') {
|
|
70
|
+
const { runCli } = await import('../skills/polishup/scripts/color.mjs');
|
|
71
|
+
process.exitCode = await runCli(process.argv.slice(3));
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
const { values, positionals } = parseArgs({ allowPositionals: true, options: {
|
|
75
|
+
agent: { type: 'string' }, scope: { type: 'string' }, profile: { type: 'string' }, destination: { type: 'string' }, 'dry-run': { type: 'boolean' },
|
|
76
|
+
replace: { type: 'boolean' }, help: { type: 'boolean', short: 'h' }, version: { type: 'boolean' },
|
|
77
|
+
plain: { type: 'boolean' }, 'no-input': { type: 'boolean' },
|
|
78
|
+
} });
|
|
79
|
+
let action = positionals[0] || 'install';
|
|
80
|
+
if (positionals.length > 1 || !['install', 'update', 'uninstall'].includes(action)) throw new Error(`Unknown command: ${positionals.join(' ')}. Run polishup --help.`);
|
|
81
|
+
if (values.help) { console.log(HELP); return; }
|
|
82
|
+
if (values.version) { console.log(metadata.version); return; }
|
|
83
|
+
let agents = parseAgents(values.agent);
|
|
84
|
+
if (values.profile && agents.length === 0) agents = ['hermes'];
|
|
85
|
+
if (values.destination && agents.length === 0) agents = ['manual'];
|
|
86
|
+
if (values.scope && !['project', 'user'].includes(values.scope)) throw new Error('Choose --scope project or user.');
|
|
87
|
+
if (values.profile && !agents.includes('hermes')) throw new Error('--profile only applies to Hermes targets.');
|
|
88
|
+
if (values.profile && values.scope && values.scope !== 'user') throw new Error('--profile requires --scope user.');
|
|
89
|
+
if (values.profile && !values.scope) values.scope = 'user';
|
|
90
|
+
if (values.destination && agents.length && !agents.includes('manual')) throw new Error('--destination requires --agent manual.');
|
|
91
|
+
const ui = await createPrompts({ plain: values.plain, noInput: values['no-input'] });
|
|
92
|
+
|
|
93
|
+
try {
|
|
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;
|
|
114
|
+
}
|
|
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 }); }
|
|
129
|
+
}
|
|
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 }); }
|
|
135
|
+
}
|
|
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
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
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;
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
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';
|
|
193
|
+
}
|
|
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
|
+
}
|
|
204
|
+
}
|
|
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
|
+
}
|
|
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;
|
|
239
|
+
}
|
|
240
|
+
} finally { ui.close(); }
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
main().catch(error => {
|
|
244
|
+
if (process.argv[2] === 'color') {
|
|
245
|
+
if (process.argv.includes('--json')) console.log(JSON.stringify({ schemaVersion: 1,
|
|
246
|
+
operation: `color.${process.argv[3] || 'unknown'}`, toolVersion: metadata.version,
|
|
247
|
+
status: 'error', message: error.message }));
|
|
248
|
+
else console.error(`PolishUp: ${error.message}`);
|
|
249
|
+
process.exitCode = 2;
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
console.error(`PolishUp: ${error.message}`);
|
|
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
|
+
}
|
|
264
|
+
});
|
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { HOSTS, getManualTarget, getTarget, getStorageGroup } from './hosts.mjs';
|
|
7
|
+
|
|
8
|
+
export const AGENTS = Object.fromEntries(Object.entries(HOSTS).map(([key, host]) => [key, host.label]));
|
|
9
|
+
export { getManualTarget, getTarget };
|
|
10
|
+
export const PACKAGE_NAME = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).name;
|
|
11
|
+
const RECEIPT = '.polishup-install.json';
|
|
12
|
+
const hash = value => createHash('sha256').update(value).digest('hex');
|
|
13
|
+
const exists = file => fs.existsSync(file);
|
|
14
|
+
const command = fs.readFileSync(assertSafePath(fileURLToPath(new URL('../.opencode/commands/polishup.md', import.meta.url))), 'utf8').replace(/\r\n/g, '\n');
|
|
15
|
+
|
|
16
|
+
export function assertSafePath(destination) {
|
|
17
|
+
const absolute = path.resolve(destination);
|
|
18
|
+
const { root } = path.parse(absolute);
|
|
19
|
+
let current = root;
|
|
20
|
+
for (const part of absolute.slice(root.length).split(path.sep).filter(Boolean)) {
|
|
21
|
+
current = path.join(current, part);
|
|
22
|
+
try {
|
|
23
|
+
if (fs.lstatSync(current).isSymbolicLink()) throw new Error(`Refusing a symbolic link or junction: ${current}`);
|
|
24
|
+
} catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
25
|
+
}
|
|
26
|
+
return absolute;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function safeRelative(file) {
|
|
30
|
+
return typeof file === 'string' && file.length > 0 && !file.includes('\\') &&
|
|
31
|
+
!file.includes(':') && !file.startsWith('/') && file.split('/').every(p => p && p !== '.' && p !== '..');
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function filesIn(directory, prefix = '') {
|
|
35
|
+
assertSafePath(directory);
|
|
36
|
+
const files = {};
|
|
37
|
+
for (const entry of fs.readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
38
|
+
const relative = prefix + entry.name;
|
|
39
|
+
if (!safeRelative(relative)) throw new Error(`Unsafe file path: ${relative}`);
|
|
40
|
+
if (entry.isSymbolicLink()) throw new Error(`Refusing a symbolic link: ${path.join(directory, entry.name)}`);
|
|
41
|
+
if (entry.isDirectory()) Object.assign(files, filesIn(path.join(directory, entry.name), `${relative}/`));
|
|
42
|
+
else if (entry.isFile()) files[relative] = fs.readFileSync(path.join(directory, entry.name));
|
|
43
|
+
else throw new Error(`Unsupported file type: ${relative}`);
|
|
44
|
+
}
|
|
45
|
+
return files;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function loadPayload(packageRoot) {
|
|
49
|
+
packageRoot = assertSafePath(packageRoot);
|
|
50
|
+
const metadata = JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf8'));
|
|
51
|
+
const skillRoot = assertSafePath(path.join(packageRoot, 'skills', 'polishup'));
|
|
52
|
+
const files = { 'SKILL.md': fs.readFileSync(assertSafePath(path.join(skillRoot, 'SKILL.md'))) };
|
|
53
|
+
const license = path.join(skillRoot, 'LICENSE.txt');
|
|
54
|
+
if (fs.existsSync(license)) files['LICENSE.txt'] = fs.readFileSync(assertSafePath(license));
|
|
55
|
+
Object.assign(files, filesIn(path.join(skillRoot, 'references'), 'references/'));
|
|
56
|
+
const scripts = path.join(skillRoot, 'scripts');
|
|
57
|
+
if (fs.existsSync(scripts)) Object.assign(files, filesIn(scripts, 'scripts/'));
|
|
58
|
+
const hashes = Object.fromEntries(Object.keys(files).sort().map(file => [file, hash(files[file])]));
|
|
59
|
+
if (metadata.name !== PACKAGE_NAME || !/^\d+\.\d+\.\d+$/.test(metadata.version)) throw new Error('Invalid PolishUp package identity.');
|
|
60
|
+
return { version: metadata.version, files, hashes, revision: hash(JSON.stringify(hashes)), packageRoot, skillRoot };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function readReceipt(file) {
|
|
64
|
+
let receipt;
|
|
65
|
+
try { receipt = JSON.parse(fs.readFileSync(file, 'utf8')); }
|
|
66
|
+
catch { throw new Error(`Invalid installation receipt: ${file}. Preserve the folder and inspect it before replacing it.`); }
|
|
67
|
+
const validFiles = receipt.files && Object.hasOwn(receipt.files, 'SKILL.md') &&
|
|
68
|
+
Object.entries(receipt.files).every(([p, digest]) => safeRelative(p) && /^[a-f0-9]{64}$/.test(digest));
|
|
69
|
+
const validLegacy = receipt.schema === 1 && Object.hasOwn(AGENTS, receipt.agent) && ['project', 'user'].includes(receipt.scope) &&
|
|
70
|
+
(!receipt.commandHash || /^[a-f0-9]{64}$/.test(receipt.commandHash));
|
|
71
|
+
const validCurrent = receipt.schema === 2 && typeof receipt.storageGroup === 'string' && Array.isArray(receipt.consumers) &&
|
|
72
|
+
receipt.consumers.length > 0 && receipt.consumers.every(consumer => Object.hasOwn(AGENTS, consumer.agent) &&
|
|
73
|
+
['project', 'user'].includes(consumer.scope) &&
|
|
74
|
+
(consumer.profile === null || typeof consumer.profile === 'string') &&
|
|
75
|
+
(!consumer.commandHash || /^[a-f0-9]{64}$/.test(consumer.commandHash)));
|
|
76
|
+
if ((!validLegacy && !validCurrent) || receipt.name !== 'polishup' || !validFiles ||
|
|
77
|
+
!/^\d+\.\d+\.\d+$/.test(receipt.version)) {
|
|
78
|
+
throw new Error(`Invalid receipt or receipt path: ${file}`);
|
|
79
|
+
}
|
|
80
|
+
return receipt;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function inspect(target) {
|
|
84
|
+
for (const file of [target.skillDir, target.stateRoot, ...(target.commandFile ? [target.commandFile] : [])]) assertSafePath(file);
|
|
85
|
+
const present = exists(target.skillDir);
|
|
86
|
+
const files = present ? filesIn(target.skillDir) : {};
|
|
87
|
+
const receiptPath = path.join(target.skillDir, RECEIPT);
|
|
88
|
+
const receipt = present && exists(receiptPath) ? readReceipt(receiptPath) : null;
|
|
89
|
+
let consumers = [];
|
|
90
|
+
if (receipt?.schema === 1) {
|
|
91
|
+
consumers = [{ agent: receipt.agent, scope: receipt.scope, profile: receipt.profile ?? null,
|
|
92
|
+
...(receipt.commandHash ? { commandHash: receipt.commandHash } : {}) }];
|
|
93
|
+
const sameTarget = receipt.agent === target.agent && receipt.scope === target.scope && (receipt.profile ?? null) === target.profile;
|
|
94
|
+
const compatibleLegacy = target.storageGroup === 'agents-project' && getStorageGroup(receipt.agent, receipt.scope) === 'agents-project';
|
|
95
|
+
if (!sameTarget && !compatibleLegacy) throw new Error(`Installation ownership differs from the selected target: ${target.skillDir}`);
|
|
96
|
+
} else if (receipt?.schema === 2) {
|
|
97
|
+
if (receipt.storageGroup !== target.storageGroup) throw new Error(`Installation ownership differs from the selected target: ${target.skillDir}`);
|
|
98
|
+
consumers = receipt.consumers;
|
|
99
|
+
if (new Set(consumers.map(consumerId)).size !== consumers.length) throw new Error(`Duplicate consumers in installation receipt: ${receiptPath}`);
|
|
100
|
+
}
|
|
101
|
+
delete files[RECEIPT];
|
|
102
|
+
const hashes = Object.fromEntries(Object.keys(files).sort().map(file => [file, hash(files[file])]));
|
|
103
|
+
const commandHash = target.commandFile && exists(target.commandFile) ? hash(fs.readFileSync(target.commandFile)) : null;
|
|
104
|
+
const changed = receipt ? Object.keys(receipt.files).filter(file => hashes[file] !== receipt.files[file]) : [];
|
|
105
|
+
const extra = receipt ? Object.keys(hashes).filter(file => !Object.hasOwn(receipt.files, file)) : [];
|
|
106
|
+
const consumer = consumers.find(item => consumerId(item) === consumerId(target.consumer));
|
|
107
|
+
const expectedCommandHash = consumer?.commandHash ?? (receipt?.schema === 1 && consumer ? receipt.commandHash : null);
|
|
108
|
+
const commandChanged = Boolean(commandHash && (!consumer || commandHash !== expectedCommandHash));
|
|
109
|
+
return { exists: present, receipt, hashes, commandHash, changed, extra,
|
|
110
|
+
consumers, consumer, hasTarget: Boolean(consumer), commandChanged,
|
|
111
|
+
signature: hash(JSON.stringify({ hashes, commandHash, receipt })) };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function consumerId(consumer) {
|
|
115
|
+
return `${consumer.agent}:${consumer.scope}:${consumer.profile ?? ''}`;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export function compareVersions(a, b) {
|
|
119
|
+
const left = a.split('.').map(Number), right = b.split('.').map(Number);
|
|
120
|
+
for (let i = 0; i < 3; i++) if (left[i] !== right[i]) return left[i] > right[i] ? 1 : -1;
|
|
121
|
+
return 0;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export function plan(target, payload, action = 'install', { selectedConsumers = [target.consumer] } = {}) {
|
|
125
|
+
if (!['install', 'update', 'uninstall'].includes(action)) throw new Error(`Unknown action: ${action}`);
|
|
126
|
+
if (!Array.isArray(selectedConsumers) || selectedConsumers.length === 0 ||
|
|
127
|
+
!selectedConsumers.some(item => consumerId(item) === consumerId(target.consumer)) ||
|
|
128
|
+
new Set(selectedConsumers.map(consumerId)).size !== selectedConsumers.length) {
|
|
129
|
+
throw new Error('Selected installation consumers are invalid.');
|
|
130
|
+
}
|
|
131
|
+
if (selectedConsumers.some(item => !Object.hasOwn(AGENTS, item.agent) || item.scope !== target.scope ||
|
|
132
|
+
(item.profile ?? null) !== (target.profile ?? null) || target.storageGroup !== getStorageGroup(item.agent, item.scope))) {
|
|
133
|
+
throw new Error('Selected installation consumers do not share this target location.');
|
|
134
|
+
}
|
|
135
|
+
const current = inspect(target);
|
|
136
|
+
if (exists(path.join(target.stateRoot, 'lock'))) throw new Error(`Another or interrupted operation holds ${path.join(target.stateRoot, 'lock')}. Inspect it before removing the lock.`);
|
|
137
|
+
const sourceRelative = path.relative(target.skillDir, payload.skillRoot);
|
|
138
|
+
if (sourceRelative === '' || (sourceRelative !== '..' && !sourceRelative.startsWith(`..${path.sep}`) && !path.isAbsolute(sourceRelative))) {
|
|
139
|
+
throw new Error('The source skill cannot replace or remove itself or its containing directory.');
|
|
140
|
+
}
|
|
141
|
+
const selectedIds = new Set(selectedConsumers.map(consumerId));
|
|
142
|
+
const registeredSelection = current.consumers.filter(item => selectedIds.has(consumerId(item)));
|
|
143
|
+
if (action === 'update' && registeredSelection.length === 0) throw new Error(`No selected installation to update at ${target.skillDir}. Run polishup install first.`);
|
|
144
|
+
if (action === 'uninstall' && current.exists && current.receipt && registeredSelection.length === 0) {
|
|
145
|
+
throw new Error(`None of the selected hosts is registered as a consumer of ${target.skillDir}.`);
|
|
146
|
+
}
|
|
147
|
+
const conflicts = [];
|
|
148
|
+
if (current.exists && !current.receipt) conflicts.push('Unmanaged skill folder');
|
|
149
|
+
if (current.changed.length) conflicts.push(`Locally modified or missing files: ${current.changed.join(', ')}`);
|
|
150
|
+
if (current.extra.length) conflicts.push(`Custom files: ${current.extra.join(', ')}`);
|
|
151
|
+
if (current.commandChanged) conflicts.push('Unmanaged or modified OpenCode command');
|
|
152
|
+
if (action !== 'uninstall' && current.receipt && compareVersions(current.receipt.version, payload.version) > 0) conflicts.push('A newer package version is installed; replacement would downgrade it');
|
|
153
|
+
const identical = current.receipt && registeredSelection.length === selectedConsumers.length && current.receipt.schema === 2 &&
|
|
154
|
+
current.receipt.version === payload.version &&
|
|
155
|
+
JSON.stringify(current.hashes) === JSON.stringify(payload.hashes) &&
|
|
156
|
+
(!target.commandFile || current.commandHash === hash(command)) && !conflicts.length;
|
|
157
|
+
const remainingConsumers = current.consumers.filter(item => !selectedIds.has(consumerId(item)));
|
|
158
|
+
const kind = action === 'uninstall'
|
|
159
|
+
? (!current.exists && !current.commandHash ? 'none' : current.receipt && remainingConsumers.length ? 'detach' : 'uninstall')
|
|
160
|
+
: (identical ? 'none' : action);
|
|
161
|
+
return { target, payload, current, conflicts, kind, action, selectedConsumers };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export function apply(operation, { replace = false, dryRun = false } = {}) {
|
|
165
|
+
const { target, payload, current, kind, conflicts, action } = operation;
|
|
166
|
+
if (dryRun) return { changed: false, dryRun: true, conflicts, kind };
|
|
167
|
+
if (conflicts.length && !replace) throw new Error(`Installation conflict: ${conflicts.join('; ')}. Back up and replace only after an explicit choice.`);
|
|
168
|
+
if (kind === 'none') return { changed: false };
|
|
169
|
+
if (kind === 'detach') return detachConsumer(operation);
|
|
170
|
+
assertSafePath(target.stateRoot);
|
|
171
|
+
assertSafePath(path.join(target.stateRoot, 'backups'));
|
|
172
|
+
fs.mkdirSync(target.stateRoot, { recursive: true });
|
|
173
|
+
const lock = path.join(target.stateRoot, 'lock');
|
|
174
|
+
let handle;
|
|
175
|
+
try { handle = fs.openSync(lock, 'wx'); }
|
|
176
|
+
catch (error) {
|
|
177
|
+
if (error.code === 'EEXIST') throw new Error(`Another or interrupted operation holds ${lock}. Inspect it before removing the lock.`);
|
|
178
|
+
throw error;
|
|
179
|
+
}
|
|
180
|
+
const staging = path.join(target.stateRoot, `staging-${randomUUID()}`);
|
|
181
|
+
const backup = path.join(target.stateRoot, 'backups', randomUUID());
|
|
182
|
+
let skillSaved = false, commandSaved = false, skillWritten = false, commandWritten = false;
|
|
183
|
+
let recoveryFailed = false;
|
|
184
|
+
try {
|
|
185
|
+
assertSafePath(backup);
|
|
186
|
+
if (inspect(target).signature !== current.signature) throw new Error('Installation changed after inspection. Run the command again.');
|
|
187
|
+
fs.mkdirSync(staging);
|
|
188
|
+
if (action !== 'uninstall') {
|
|
189
|
+
fs.mkdirSync(path.join(staging, 'skill'));
|
|
190
|
+
for (const [relative, bytes] of Object.entries(payload.files)) {
|
|
191
|
+
const file = path.join(staging, 'skill', relative);
|
|
192
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
193
|
+
fs.writeFileSync(file, bytes);
|
|
194
|
+
}
|
|
195
|
+
const selectedIds = new Set(operation.selectedConsumers.map(consumerId));
|
|
196
|
+
const consumers = current.consumers.filter(item => !selectedIds.has(consumerId(item)));
|
|
197
|
+
for (const selected of operation.selectedConsumers) {
|
|
198
|
+
const next = { ...selected };
|
|
199
|
+
if (target.commandFile && consumerId(selected) === consumerId(target.consumer)) next.commandHash = hash(command);
|
|
200
|
+
consumers.push(next);
|
|
201
|
+
}
|
|
202
|
+
const receipt = { schema: 2, name: 'polishup', version: payload.version, revision: payload.revision,
|
|
203
|
+
storageGroup: target.storageGroup, consumers, files: payload.hashes };
|
|
204
|
+
fs.writeFileSync(path.join(staging, 'skill', RECEIPT), JSON.stringify(receipt, null, 2) + '\n');
|
|
205
|
+
if (target.commandFile) fs.writeFileSync(path.join(staging, 'command.md'), command);
|
|
206
|
+
}
|
|
207
|
+
fs.mkdirSync(backup, { recursive: true });
|
|
208
|
+
if (exists(target.skillDir)) { fs.renameSync(target.skillDir, path.join(backup, 'skill')); skillSaved = true; }
|
|
209
|
+
if (target.commandFile && exists(target.commandFile)) { fs.renameSync(target.commandFile, path.join(backup, 'command.md')); commandSaved = true; }
|
|
210
|
+
if (kind !== 'uninstall') {
|
|
211
|
+
fs.mkdirSync(path.dirname(target.skillDir), { recursive: true });
|
|
212
|
+
fs.renameSync(path.join(staging, 'skill'), target.skillDir);
|
|
213
|
+
skillWritten = true;
|
|
214
|
+
if (target.commandFile) {
|
|
215
|
+
fs.mkdirSync(path.dirname(target.commandFile), { recursive: true });
|
|
216
|
+
fs.renameSync(path.join(staging, 'command.md'), target.commandFile);
|
|
217
|
+
commandWritten = true;
|
|
218
|
+
}
|
|
219
|
+
const installed = inspect(target);
|
|
220
|
+
if (installed.changed.length || installed.extra.length ||
|
|
221
|
+
JSON.stringify(installed.hashes) !== JSON.stringify(payload.hashes) ||
|
|
222
|
+
(target.commandFile && installed.commandHash !== hash(command))) throw new Error('Post-install verification failed.');
|
|
223
|
+
} else if (exists(target.skillDir) || (target.commandFile && exists(target.commandFile))) throw new Error('Removal verification failed.');
|
|
224
|
+
if (!skillSaved && !commandSaved) fs.rmSync(backup, { recursive: true });
|
|
225
|
+
return { changed: true, backup: skillSaved || commandSaved ? backup : null };
|
|
226
|
+
} catch (error) {
|
|
227
|
+
try {
|
|
228
|
+
if (commandWritten) fs.rmSync(target.commandFile);
|
|
229
|
+
if (skillWritten) fs.rmSync(target.skillDir, { recursive: true });
|
|
230
|
+
if (skillSaved) fs.renameSync(path.join(backup, 'skill'), target.skillDir);
|
|
231
|
+
if (commandSaved) fs.renameSync(path.join(backup, 'command.md'), target.commandFile);
|
|
232
|
+
} catch (recoveryError) {
|
|
233
|
+
recoveryFailed = true;
|
|
234
|
+
throw new Error(`${error.message}. Recovery also failed: ${recoveryError.message}. Preserve ${backup} and ${staging}.`);
|
|
235
|
+
}
|
|
236
|
+
throw error;
|
|
237
|
+
} finally {
|
|
238
|
+
fs.closeSync(handle);
|
|
239
|
+
if (!recoveryFailed) {
|
|
240
|
+
fs.rmSync(staging, { recursive: true, force: true });
|
|
241
|
+
fs.rmSync(lock, { force: true });
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function detachConsumer(operation) {
|
|
247
|
+
const { target, current } = operation;
|
|
248
|
+
assertSafePath(target.stateRoot);
|
|
249
|
+
assertSafePath(path.join(target.stateRoot, 'backups'));
|
|
250
|
+
fs.mkdirSync(target.stateRoot, { recursive: true });
|
|
251
|
+
const lock = path.join(target.stateRoot, 'lock');
|
|
252
|
+
let handle;
|
|
253
|
+
try { handle = fs.openSync(lock, 'wx'); }
|
|
254
|
+
catch (error) {
|
|
255
|
+
if (error.code === 'EEXIST') throw new Error(`Another or interrupted operation holds ${lock}. Inspect it before removing the lock.`);
|
|
256
|
+
throw error;
|
|
257
|
+
}
|
|
258
|
+
const receiptPath = path.join(target.skillDir, RECEIPT);
|
|
259
|
+
const staging = path.join(target.stateRoot, `staging-${randomUUID()}`);
|
|
260
|
+
let saved = false, written = false, recoveryFailed = false;
|
|
261
|
+
const backup = path.join(target.stateRoot, 'backups', randomUUID());
|
|
262
|
+
try {
|
|
263
|
+
assertSafePath(backup);
|
|
264
|
+
if (inspect(target).signature !== current.signature) throw new Error('Installation changed after inspection. Run the command again.');
|
|
265
|
+
fs.mkdirSync(backup, { recursive: true });
|
|
266
|
+
const selectedIds = new Set(operation.selectedConsumers.map(consumerId));
|
|
267
|
+
const consumers = current.consumers.filter(item => !selectedIds.has(consumerId(item)));
|
|
268
|
+
const receipt = { ...current.receipt, schema: 2, storageGroup: target.storageGroup, consumers };
|
|
269
|
+
delete receipt.agent;
|
|
270
|
+
delete receipt.scope;
|
|
271
|
+
delete receipt.profile;
|
|
272
|
+
delete receipt.commandHash;
|
|
273
|
+
fs.writeFileSync(staging, JSON.stringify(receipt, null, 2) + '\n');
|
|
274
|
+
fs.renameSync(receiptPath, path.join(backup, RECEIPT));
|
|
275
|
+
saved = true;
|
|
276
|
+
fs.renameSync(staging, receiptPath);
|
|
277
|
+
written = true;
|
|
278
|
+
const verified = inspect(target);
|
|
279
|
+
if (operation.selectedConsumers.some(item => verified.consumers.some(remaining => consumerId(remaining) === consumerId(item))) ||
|
|
280
|
+
verified.consumers.length !== consumers.length) throw new Error('Shared installation update verification failed.');
|
|
281
|
+
fs.rmSync(backup, { recursive: true, force: true });
|
|
282
|
+
return { changed: true, detached: true, remainingConsumers: consumers };
|
|
283
|
+
} catch (error) {
|
|
284
|
+
try {
|
|
285
|
+
if (written) fs.rmSync(receiptPath, { force: true });
|
|
286
|
+
if (saved) fs.renameSync(path.join(backup, RECEIPT), receiptPath);
|
|
287
|
+
} catch (recoveryError) {
|
|
288
|
+
recoveryFailed = true;
|
|
289
|
+
throw new Error(`${error.message}. Recovery also failed: ${recoveryError.message}. Preserve ${backup} and ${staging}.`);
|
|
290
|
+
}
|
|
291
|
+
throw error;
|
|
292
|
+
} finally {
|
|
293
|
+
fs.closeSync(handle);
|
|
294
|
+
if (!recoveryFailed) {
|
|
295
|
+
fs.rmSync(staging, { force: true });
|
|
296
|
+
fs.rmSync(backup, { recursive: true, force: true });
|
|
297
|
+
fs.rmSync(lock, { force: true });
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
}
|