@guiho/runx 0.2.7 → 0.4.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.
Files changed (86) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/DOCS.md +127 -128
  3. package/README.md +56 -75
  4. package/devops/build-binaries.ts +44 -62
  5. package/devops/devops.xdocs.md +8 -5
  6. package/devops/install.ps1 +182 -152
  7. package/devops/install.sh +197 -262
  8. package/devops/installers.spec.ts +31 -0
  9. package/devops/verify-release-assets.ts +17 -0
  10. package/docs/docs.xdocs.md +3 -1
  11. package/docs/plans/plans.xdocs.md +7 -0
  12. package/docs/plans/rfc-0034-cli-compliance-migration.md +586 -0
  13. package/docs/plans/upgrade-reliability-implementation.md +95 -0
  14. package/docs/reviews/implementation/implementation.xdocs.md +2 -0
  15. package/docs/reviews/implementation/rfc-0034-cli-compliance-migration-review.md +59 -0
  16. package/docs/reviews/plans/plans.xdocs.md +6 -0
  17. package/docs/reviews/plans/rfc-0034-cli-compliance-migration-review.md +80 -0
  18. package/docs/reviews/plans/upgrade-reliability-implementation-review.md +65 -0
  19. package/docs/superpowers/specs/2026-07-15-upgrade-reliability-design.md +662 -0
  20. package/docs/superpowers/specs/specs.xdocs.md +24 -0
  21. package/docs/superpowers/superpowers.xdocs.md +21 -0
  22. package/docs/todo/rfc-0034-cli-compliance-migration-implementation.md +58 -0
  23. package/docs/todo/rfc-0034-cli-compliance-migration.md +151 -0
  24. package/docs/todo/todo.xdocs.md +6 -2
  25. package/docs/validation/rfc-0034-cli-compliance-migration.md +67 -0
  26. package/docs/validation/upgrade-reliability.md +124 -0
  27. package/docs/validation/validation.xdocs.md +5 -0
  28. package/library/agents.d.ts +28 -4
  29. package/library/agents.d.ts.map +1 -1
  30. package/library/agents.js +143 -41
  31. package/library/cli.d.ts.map +1 -1
  32. package/library/cli.js +296 -334
  33. package/library/configuration.d.ts +57 -0
  34. package/library/configuration.d.ts.map +1 -0
  35. package/library/configuration.js +111 -0
  36. package/library/embedded-resources.d.ts +6 -1
  37. package/library/embedded-resources.d.ts.map +1 -1
  38. package/library/embedded-resources.js +10 -4
  39. package/library/executor.d.ts +5 -1
  40. package/library/executor.d.ts.map +1 -1
  41. package/library/executor.js +10 -10
  42. package/library/help.d.ts +8 -4
  43. package/library/help.d.ts.map +1 -1
  44. package/library/help.js +70 -46
  45. package/library/init.d.ts +8 -27
  46. package/library/init.d.ts.map +1 -1
  47. package/library/init.js +37 -159
  48. package/library/manifest.d.ts +4 -43
  49. package/library/manifest.d.ts.map +1 -1
  50. package/library/manifest.js +4 -125
  51. package/library/path-utils.d.ts +13 -0
  52. package/library/path-utils.d.ts.map +1 -0
  53. package/library/path-utils.js +82 -0
  54. package/library/recovery.d.ts +7 -0
  55. package/library/recovery.d.ts.map +1 -0
  56. package/library/recovery.js +23 -0
  57. package/library/release-catalog.d.ts +32 -0
  58. package/library/release-catalog.d.ts.map +1 -0
  59. package/library/release-catalog.js +124 -0
  60. package/library/self-management.d.ts +24 -4
  61. package/library/self-management.d.ts.map +1 -1
  62. package/library/self-management.js +279 -99
  63. package/library/storage.d.ts +13 -0
  64. package/library/storage.d.ts.map +1 -0
  65. package/library/storage.js +38 -0
  66. package/library/types.d.ts +11 -16
  67. package/library/types.d.ts.map +1 -1
  68. package/library/types.js +3 -0
  69. package/library/update-cache.d.ts +21 -0
  70. package/library/update-cache.d.ts.map +1 -0
  71. package/library/update-cache.js +68 -0
  72. package/library/upgrade-reporting.d.ts +11 -0
  73. package/library/upgrade-reporting.d.ts.map +1 -0
  74. package/library/upgrade-reporting.js +67 -0
  75. package/library/upgrade-types.d.ts +72 -0
  76. package/library/upgrade-types.d.ts.map +1 -0
  77. package/library/upgrade-types.js +3 -0
  78. package/package.json +6 -3
  79. package/scripts/runx-bin.mjs +49 -0
  80. package/scripts/runx-bin.spec.ts +62 -0
  81. package/scripts/scripts.xdocs.md +3 -3
  82. package/skills/guiho-s-runx/SKILL.md +64 -59
  83. package/skills/guiho-s-runx/guiho-s-runx.xdocs.md +7 -4
  84. package/skills/skills.xdocs.md +1 -1
  85. package/docs/todo/implement-runx-alpha.md +0 -36
  86. package/scripts/runx-bin.ts +0 -24
package/library/cli.js CHANGED
@@ -1,16 +1,21 @@
1
1
  /**
2
2
  * @copyright Copyright © 2026 GUIHO Technologies as represented by Cristóvão GUIHO. All Rights Reserved.
3
3
  */
4
- import { resolve } from 'node:path';
4
+ import { Type } from '@sinclair/typebox';
5
+ import { Value } from '@sinclair/typebox/value';
5
6
  import { defineCommand, renderUsage, runCommand as runCittyCommand } from 'citty';
6
- import { installAgentInstructions, installAgentSkill } from './agents.js';
7
+ import { applyAgentInstructions, installAgentSkill, listAgentPrompts, listAgentSkills, removeAgentInstructions, showAgentInstructions, showAgentPrompt, showAgentSkill, uninstallAgentSkill, updateAgentInstructions, updateAgentSkill, } from './agents.js';
7
8
  import { RunXError } from './errors.js';
8
9
  import { runCommand } from './executor.js';
9
- import { readVersion, showHelpDocs, showHelpTree, showHome } from './help.js';
10
+ import { readVersion, renderHelpDocs, renderHelpTree } from './help.js';
10
11
  import { initializeRunXManifest } from './init.js';
11
12
  import { readManifest, resolveCommand } from './manifest.js';
13
+ import { resolvePath } from './path-utils.js';
12
14
  import { renderDescription, renderExecutionPlan, renderJson, renderList } from './render.js';
13
- import { checkForLatestVersion, listAvailableVersions, uninstallSelf, upgradeSelf } from './self-management.js';
15
+ import { fetchReleaseCatalog, resolveUpgradePlatform } from './release-catalog.js';
16
+ import { checkForLatestVersion, uninstallSelf, upgradeSelf } from './self-management.js';
17
+ import { readCachedUpdateNotice, runUpdateWorker, spawnUpdateWorker } from './update-cache.js';
18
+ import { renderReleaseCatalog, renderUpgradeEvent, renderUpgradeHeading, renderUpgradePlan, renderUpgradeResult } from './upgrade-reporting.js';
14
19
  export { runCli, runCliWithErrorHandling, runxCommand, };
15
20
  class CliHandled extends Error {
16
21
  }
@@ -22,207 +27,202 @@ class CliUsageError extends Error {
22
27
  this.usage = usage;
23
28
  }
24
29
  }
25
- const commonArgs = {
26
- cwd: { type: 'string', description: 'Resolve the manifest from this directory.', valueHint: 'path' },
27
- file: { type: 'string', description: 'Use this runx.yaml file.', valueHint: 'path' },
28
- format: { type: 'string', description: 'Select text or JSON output.', valueHint: 'text|json', default: 'text' },
29
- verbose: { type: 'boolean', description: 'Enable additional diagnostics.' },
30
- 'help-tree': { type: 'boolean', description: 'Show the complete command hierarchy.' },
31
- 'help-docs': { type: 'boolean', description: 'Show manifest and agent guidance.' },
30
+ const formatSchema = Type.Union([Type.Literal('text'), Type.Literal('json')]);
31
+ const archSchema = Type.Union([Type.Literal('x64'), Type.Literal('arm64')]);
32
+ const variantSchema = Type.Union([Type.Literal('baseline'), Type.Literal('default'), Type.Literal('modern')]);
33
+ const positiveIntegerSchema = Type.Integer({ minimum: 1 });
34
+ const helpArgs = {
32
35
  help: { type: 'boolean', alias: 'h', description: 'Show command help.' },
33
- version: { type: 'boolean', alias: 'v', description: 'Show the RunX version.' },
36
+ 'help-tree': { type: 'boolean', description: 'Show this command hierarchy.' },
37
+ 'help-tree-depth': { type: 'string', valueHint: 'positive-integer', description: 'Limit help-tree recursion depth.' },
38
+ 'help-docs': { type: 'boolean', description: 'Emit Markdown documentation for this command.' },
34
39
  };
35
- const runArgs = {
36
- ...commonArgs,
37
- 'dry-run': { type: 'boolean', description: 'Show the action without executing it.' },
38
- yes: { type: 'boolean', description: 'Approve a confirmation-gated command.' },
40
+ const catalogArgs = {
41
+ cwd: { type: 'string', valueHint: 'path', description: 'Use this effective working directory.' },
42
+ config: { type: 'string', valueHint: 'path', description: 'Use this runx.yaml configuration file.' },
43
+ format: { type: 'string', valueHint: 'text|json', default: 'text', description: 'Select output format.' },
44
+ verbose: { type: 'boolean', description: 'Enable diagnostics.' },
45
+ ...helpArgs,
39
46
  };
40
- const agentInstallArgs = {
41
- ...commonArgs,
42
- tool: { type: 'string', description: 'Select agents, claude, or all.', valueHint: 'agents|claude|all' },
43
- };
44
- const selfManagementArgs = {
45
- ...commonArgs,
46
- 'dry-run': { type: 'boolean', description: 'Show the action without changing the executable.' },
47
- };
48
- const rootArgs = {
49
- ...runArgs,
50
- tool: agentInstallArgs.tool,
51
- };
52
- const knownArgumentKeys = new Set([
53
- '_',
54
- 'cwd',
55
- 'file',
56
- 'format',
57
- 'verbose',
58
- 'dryRun',
59
- 'dry-run',
60
- 'yes',
61
- 'tool',
62
- 'helpTree',
63
- 'help-tree',
64
- 'helpDocs',
65
- 'help-docs',
66
- 'help',
67
- 'h',
68
- 'version',
69
- 'v',
70
- ]);
71
- const createCommandTree = () => {
72
- const state = { globalArgs: { _: [] }, usageCommand: {} };
73
- const listCommand = defineCommand({
74
- meta: { name: 'runx list', description: 'List commands in a RunX manifest.' },
75
- args: commonArgs,
76
- setup: withCommandHelp(state),
77
- run: async () => listCommands(resolveOptions(state.globalArgs)),
78
- });
79
- const describeCommandDefinition = defineCommand({
80
- meta: { name: 'runx describe', description: 'Describe one manifest command.' },
81
- args: {
82
- selector: { type: 'positional', description: 'Command UID, group/id, index, or unambiguous ID.' },
83
- ...commonArgs,
84
- },
85
- setup: withCommandHelp(state),
86
- run: async ({ args }) => {
87
- if (!args.selector)
88
- throw await missingSelector(state);
89
- await describeCommand(args.selector, resolveOptions(state.globalArgs));
90
- },
91
- });
92
- const runCommandDefinition = createRunCommand(state);
93
- const checkCommand = defineCommand({
94
- meta: { name: 'runx check', description: 'Validate a RunX manifest without executing it.' },
95
- args: commonArgs,
96
- setup: withCommandHelp(state),
97
- run: async () => checkManifest(resolveOptions(state.globalArgs)),
98
- });
99
- const initCommand = defineCommand({
100
- meta: { name: 'runx init', description: 'Interactively create an empty RunX manifest.' },
101
- args: commonArgs,
102
- setup: withCommandHelp(state),
103
- run: async () => initializeProject(state.globalArgs),
104
- });
105
- const agentsInstallCommand = defineCommand({
106
- meta: { name: 'runx agents install', description: 'Install the bundled RunX skill.' },
107
- args: {
108
- scope: { type: 'positional', description: 'Install locally or globally.', default: 'local', valueHint: 'local|global' },
109
- ...agentInstallArgs,
110
- },
111
- setup: withCommandHelp(state),
112
- run: async ({ args }) => runAgentsInstall(args.scope, resolveOptions(state.globalArgs), state.globalArgs),
113
- });
114
- const agentsInstructionsCommand = defineCommand({
115
- meta: { name: 'runx agents instructions', description: 'Install or refresh managed RunX agent instructions.' },
116
- args: commonArgs,
117
- setup: withCommandHelp(state),
118
- run: async () => runAgentsInstructions(resolveOptions(state.globalArgs)),
119
- });
120
- const agentsCommand = defineCommand({
121
- meta: { name: 'runx agents', description: 'Manage the bundled RunX agent integration.' },
122
- args: agentInstallArgs,
123
- subCommands: {
124
- install: agentsInstallCommand,
125
- instructions: agentsInstructionsCommand,
126
- },
127
- setup: withCommandHelp(state),
128
- });
129
- const upgradeApplyCommand = defineCommand({
130
- meta: { name: 'runx upgrade', description: 'Upgrade a native RunX executable.', hidden: true },
131
- args: selfManagementArgs,
132
- setup: withCommandHelp(state),
133
- run: async () => runUpgrade(resolveOptions(state.globalArgs), state.globalArgs),
47
+ function createCommandTree() {
48
+ const state = { args: { _: [] }, command: {}, commands: new Map() };
49
+ const leaf = (name, description, args, run) => {
50
+ const command = defineCommand({ meta: { name, description }, args: { ...args, ...helpArgs }, setup: helpSetup(state), run });
51
+ state.commands.set(name.replace(/^runx(?:\s+|$)/, ''), command);
52
+ return command;
53
+ };
54
+ const list = leaf('runx list', 'List commands in a RunX configuration.', catalogArgs, async () => listCommands(options(state.args)));
55
+ const describe = leaf('runx describe', 'Describe one catalog command without execution.', {
56
+ selector: { type: 'positional', description: 'UID, group/id, index, or unambiguous ID.' },
57
+ ...catalogArgs,
58
+ }, async ({ args }) => {
59
+ if (!args.selector)
60
+ throw await usageError(state, 'Missing required positional argument: SELECTOR');
61
+ await describeCommand(String(args.selector), options(state.args));
134
62
  });
135
- const upgradeCheckCommand = defineCommand({
136
- meta: { name: 'runx upgrade check', description: 'Check whether a newer RunX release is available.' },
137
- args: commonArgs,
138
- setup: withCommandHelp(state),
139
- run: async () => runUpgradeCheck(resolveOptions(state.globalArgs)),
63
+ const run = leaf('runx run', 'Execute one selected catalog command.', {
64
+ selector: { type: 'positional', description: 'UID, group/id, index, or unambiguous ID.' },
65
+ ...catalogArgs,
66
+ 'dry-run': { type: 'boolean', description: 'Print the execution plan without spawning.' },
67
+ yes: { type: 'boolean', description: 'Approve a confirmation-gated command.' },
68
+ }, async ({ args }) => {
69
+ if (!args.selector)
70
+ throw await usageError(state, 'Missing required positional argument: SELECTOR');
71
+ await runSelected(String(args.selector), options(state.args), state.args);
140
72
  });
141
- const upgradeListCommand = defineCommand({
142
- meta: { name: 'runx upgrade list', description: 'List recent RunX release versions.' },
143
- args: commonArgs,
144
- setup: withCommandHelp(state),
145
- run: async () => runUpgradeList(resolveOptions(state.globalArgs)),
73
+ const check = leaf('runx check', 'Validate a RunX configuration without execution.', catalogArgs, async () => checkManifest(options(state.args)));
74
+ const init = leaf('runx init', 'Create a new YAML RunX configuration.', catalogArgs, async () => {
75
+ const result = await initializeRunXManifest({ cwd: options(state.args).cwd, config: options(state.args).config });
76
+ write(state.args.format === 'json' ? renderJson(result) : `created: ${result.path}\n`);
146
77
  });
147
- const upgradeCommand = defineCommand({
148
- meta: { name: 'runx upgrade', description: 'Inspect or upgrade a native RunX executable.' },
149
- args: selfManagementArgs,
150
- default: '_apply',
151
- subCommands: {
152
- _apply: upgradeApplyCommand,
153
- check: upgradeCheckCommand,
154
- list: upgradeListCommand,
155
- },
156
- setup: withCommandHelp(state),
78
+ const skillInstall = leaf('runx agent skill install', 'Install the bundled skill into both global tool locations.', {
79
+ cwd: catalogArgs.cwd, local: { type: 'boolean', description: 'Use project-local tool directories.' }, format: catalogArgs.format,
80
+ }, async () => agentMutation('installed', installAgentSkill, state.args));
81
+ const skillUninstall = leaf('runx agent skill uninstall', 'Remove the bundled skill from both tool locations.', {
82
+ cwd: catalogArgs.cwd, local: { type: 'boolean', description: 'Use project-local tool directories.' }, format: catalogArgs.format,
83
+ }, async () => agentMutation('removed', uninstallAgentSkill, state.args));
84
+ const skillUpdate = leaf('runx agent skill update', 'Refresh the bundled skill in both tool locations.', {
85
+ cwd: catalogArgs.cwd, local: { type: 'boolean', description: 'Use project-local tool directories.' }, format: catalogArgs.format,
86
+ }, async () => agentMutation('updated', updateAgentSkill, state.args));
87
+ const skillList = leaf('runx agent skill list', 'List bundled RunX skills.', {
88
+ filter: { type: 'string', valueHint: 'keyword', description: 'Filter skill metadata.' }, format: catalogArgs.format,
89
+ }, () => writeFormatted(listAgentSkills(state.args.filter), state.args));
90
+ const skillShow = leaf('runx agent skill show', 'Show metadata for one bundled skill.', {
91
+ id: { type: 'positional', description: 'Bundled skill ID.' }, format: catalogArgs.format,
92
+ }, async ({ args }) => {
93
+ if (!args.id)
94
+ throw await usageError(state, 'Missing required positional argument: ID');
95
+ writeFormatted(await showAgentSkill(String(args.id)), state.args);
157
96
  });
158
- const uninstallCommand = defineCommand({
159
- meta: { name: 'runx uninstall', description: 'Uninstall a native RunX executable.' },
160
- args: selfManagementArgs,
161
- setup: withCommandHelp(state),
162
- run: async () => runUninstall(resolveOptions(state.globalArgs), state.globalArgs),
97
+ const skill = group('runx agent skill', 'Manage the bundled RunX skill.', { install: skillInstall, uninstall: skillUninstall, update: skillUpdate, list: skillList, show: skillShow }, state);
98
+ const instructionApply = leaf('runx agent instruction apply', 'Apply the managed instruction block.', { cwd: catalogArgs.cwd, format: catalogArgs.format }, async () => instructionMutation('updated', applyAgentInstructions, state.args));
99
+ const instructionRemove = leaf('runx agent instruction remove', 'Remove the managed instruction block.', { cwd: catalogArgs.cwd, format: catalogArgs.format }, async () => instructionMutation('removed', removeAgentInstructions, state.args));
100
+ const instructionUpdate = leaf('runx agent instruction update', 'Replace stale managed instruction content.', { cwd: catalogArgs.cwd, format: catalogArgs.format }, async () => instructionMutation('updated', updateAgentInstructions, state.args));
101
+ const instructionShow = leaf('runx agent instruction show', 'Print the raw instruction template.', {}, async () => write(await showAgentInstructions()));
102
+ const instruction = group('runx agent instruction', 'Manage RunX instruction blocks.', { apply: instructionApply, remove: instructionRemove, update: instructionUpdate, show: instructionShow }, state);
103
+ const promptList = leaf('runx agent prompt list', 'List bundled RunX prompts.', {
104
+ names: { type: 'boolean', description: 'Print prompt names only.' }, format: catalogArgs.format,
105
+ }, () => writeFormatted(listAgentPrompts(Boolean(state.args.names)), state.args));
106
+ const promptShow = leaf('runx agent prompt show', 'Print one raw bundled prompt.', {
107
+ id: { type: 'positional', description: 'Bundled prompt ID.' },
108
+ }, async ({ args }) => {
109
+ if (!args.id)
110
+ throw await usageError(state, 'Missing required positional argument: ID');
111
+ write(await showAgentPrompt(String(args.id)));
163
112
  });
164
- const homeCommand = defineCommand({
165
- meta: { name: 'runx', description: 'Show the RunX home page.', hidden: true },
166
- args: rootArgs,
167
- setup: withCommandHelp(state),
168
- run: () => write(showHome()),
113
+ const prompt = group('runx agent prompt', 'Inspect bundled agent prompts.', { list: promptList, show: promptShow }, state);
114
+ const agent = group('runx agent', 'Manage RunX agent integration.', { skill, instruction, prompt }, state);
115
+ const upgradeApply = leaf('runx upgrade', 'Upgrade the canonical native RunX executable.', {
116
+ version: { type: 'string', valueHint: 'version', description: 'Select an exact release version.' },
117
+ arch: { type: 'string', valueHint: 'x64|arm64', description: 'Select target architecture.' },
118
+ variant: { type: 'string', valueHint: 'baseline|default|modern', description: 'Select x64 binary variant.' },
119
+ 'dry-run': { type: 'boolean', description: 'Plan without mutation.' },
120
+ format: catalogArgs.format,
121
+ }, async () => runUpgrade(options(state.args), state.args));
122
+ upgradeApply.meta = { ...upgradeApply.meta, hidden: true };
123
+ const upgradeCheck = leaf('runx upgrade check', 'Check whether a newer stable release exists.', {
124
+ format: catalogArgs.format,
125
+ }, async () => {
126
+ const result = await checkForLatestVersion();
127
+ writeFormatted(result, state.args);
169
128
  });
170
- const staticSubCommands = Object.assign(Object.create(null), {
171
- _home: homeCommand,
172
- list: listCommand,
173
- describe: describeCommandDefinition,
174
- run: runCommandDefinition,
175
- check: checkCommand,
176
- init: initCommand,
177
- agents: agentsCommand,
178
- upgrade: upgradeCommand,
179
- uninstall: uninstallCommand,
129
+ const upgradeList = leaf('runx upgrade list', 'List RunX releases newest first.', {
130
+ page: { type: 'string', valueHint: 'positive-integer', description: 'Select result page.' },
131
+ 'per-page': { type: 'string', valueHint: 'positive-integer', description: 'Select page size.' },
132
+ 'pre-releases': { type: 'boolean', description: 'Include prerelease versions.' },
133
+ arch: { type: 'string', valueHint: 'x64|arm64', description: 'Select target architecture.' },
134
+ variant: { type: 'string', valueHint: 'baseline|default|modern', description: 'Select x64 variant.' },
135
+ format: catalogArgs.format,
136
+ }, async () => runUpgradeList(state.args));
137
+ const upgrade = group('runx upgrade', 'Inspect or upgrade a native RunX executable.', { _apply: upgradeApply, check: upgradeCheck, list: upgradeList }, state, '_apply');
138
+ const uninstall = leaf('runx uninstall', 'Uninstall the native RunX executable.', {
139
+ 'dry-run': { type: 'boolean', description: 'Print the target without deleting it.' }, format: catalogArgs.format,
140
+ }, async () => {
141
+ const result = await uninstallSelf(Boolean(state.args.dryRun));
142
+ writeFormatted(result, state.args);
180
143
  });
181
- const usageCommands = new Map([
182
- ['list', listCommand],
183
- ['describe', describeCommandDefinition],
184
- ['run', runCommandDefinition],
185
- ['r', runCommandDefinition],
186
- ['check', checkCommand],
187
- ['init', initCommand],
188
- ['agents', agentsCommand],
189
- ['agents install', agentsInstallCommand],
190
- ['agents instructions', agentsInstructionsCommand],
191
- ['upgrade', upgradeCommand],
192
- ['upgrade check', upgradeCheckCommand],
193
- ['upgrade list', upgradeListCommand],
194
- ['uninstall', uninstallCommand],
195
- ]);
196
- const subCommands = createSelectorCompatibleCommands(staticSubCommands, state);
197
- const command = defineCommand({
198
- meta: {
199
- name: 'runx',
200
- version: readVersion(),
201
- description: 'A documented, local command catalog for runx.yaml manifests.',
202
- },
203
- args: rootArgs,
204
- default: '_home',
205
- subCommands,
144
+ const root = defineCommand({
145
+ meta: { name: 'runx', version: readVersion(), description: 'A documented local command catalog for runx.yaml.' },
146
+ args: { version: { type: 'boolean', alias: 'v', description: 'Show the RunX version.' }, ...helpArgs },
147
+ subCommands: { list, describe, run, check, init, agent, upgrade, uninstall },
206
148
  setup: async (context) => {
207
- state.globalArgs = context.args;
208
- state.usageCommand = resolveUsageCommand(context.args._, usageCommands, state);
209
- await validateArguments(context, state);
210
- if (state.globalArgs.version || state.globalArgs.v)
211
- return handleOutput(`${readVersion()}\n`);
212
- if (state.globalArgs.helpTree)
213
- return handleOutput(`${showHelpTree()}\n`);
214
- if (state.globalArgs.helpDocs)
215
- return handleOutput(showHelpDocs());
216
- if (state.globalArgs.help || state.globalArgs.h)
217
- return handleUsage(state.usageCommand);
149
+ state.args = context.args;
150
+ state.command = resolveHelpCommand(state);
151
+ await validateInvocation(state);
152
+ if (state.args.v || state.args.version === true)
153
+ return handled(`${readVersion()}\n`);
154
+ await handleHelp(state);
155
+ },
156
+ run: ({ args }) => {
157
+ if (args._.length === 0)
158
+ write(`Hello Windows - runx v${readVersion()}\n`);
218
159
  },
219
160
  });
220
- state.usageCommand = command;
221
- return { command, state };
222
- };
161
+ state.commands.set('', root);
162
+ state.command = root;
163
+ return { command: root, state };
164
+ }
165
+ async function validateInvocation(state) {
166
+ const first = state.args._[0];
167
+ const topLevel = new Set(['list', 'describe', 'run', 'check', 'init', 'agent', 'upgrade', 'uninstall']);
168
+ if (first && !topLevel.has(first))
169
+ throw await usageError(state, `Unknown command: ${first}`);
170
+ const allowed = new Set(['_', 'h', 'v']);
171
+ for (const command of state.commands.values()) {
172
+ for (const key of Object.keys(command.args ?? {})) {
173
+ allowed.add(key);
174
+ allowed.add(key.replace(/-([a-z])/g, (_, character) => character.toUpperCase()));
175
+ }
176
+ }
177
+ const unknown = Object.keys(state.args).find((key) => !allowed.has(key));
178
+ if (unknown)
179
+ throw await usageError(state, `Unknown option: --${unknown.replace(/[A-Z]/g, (character) => `-${character.toLowerCase()}`)}`);
180
+ }
181
+ function group(name, description, subCommands, state, defaultCommand) {
182
+ const command = defineCommand({ meta: { name, description }, args: helpArgs, subCommands, ...(defaultCommand ? { default: defaultCommand } : {}), setup: helpSetup(state) });
183
+ state.commands.set(name.replace(/^runx(?:\s+|$)/, ''), command);
184
+ return command;
185
+ }
186
+ function helpSetup(state) {
187
+ return async (context) => {
188
+ state.args = context.args;
189
+ state.command = context.cmd;
190
+ await handleHelp(state);
191
+ };
192
+ }
193
+ async function handleHelp(state) {
194
+ if (state.args.helpDocs)
195
+ return handled(renderHelpDocs(state.command));
196
+ if (state.args.helpTree || state.args.helpTreeDepth) {
197
+ const depth = state.args.helpTreeDepth ? positiveInteger(state.args.helpTreeDepth, '--help-tree-depth') : Number.POSITIVE_INFINITY;
198
+ return handled(renderHelpTree(state.command, depth));
199
+ }
200
+ if (state.args.help || state.args.h)
201
+ return handled(`${await renderUsage(state.command)}\n`);
202
+ }
203
+ function resolveHelpCommand(state) {
204
+ const tokens = state.args._.filter((token) => !token.startsWith('-'));
205
+ for (let length = tokens.length; length > 0; length -= 1) {
206
+ const command = state.commands.get(tokens.slice(0, length).join(' '));
207
+ if (command)
208
+ return command;
209
+ }
210
+ return state.commands.get('') ?? state.command;
211
+ }
223
212
  const { command: runxCommand } = createCommandTree();
224
213
  async function runCli(rawArgs = process.argv.slice(2)) {
214
+ if (rawArgs.length === 1 && rawArgs[0] === '--check-updates-worker') {
215
+ await runUpdateWorker();
216
+ return;
217
+ }
225
218
  const { command, state } = createCommandTree();
219
+ const cleanOutput = rawArgs.some((arg) => ['-h', '--help', '-v', '--version', '--help-tree', '--help-docs'].includes(arg) || arg.startsWith('--help-tree-depth'));
220
+ if (!cleanOutput && rawArgs.length > 0) {
221
+ const notice = await readCachedUpdateNotice(rawArgs.includes('--verbose'));
222
+ if (notice)
223
+ process.stderr.write(`${notice}\n`);
224
+ }
225
+ spawnUpdateWorker();
226
226
  try {
227
227
  await runCittyCommand(command, { rawArgs });
228
228
  }
@@ -231,9 +231,8 @@ async function runCli(rawArgs = process.argv.slice(2)) {
231
231
  return;
232
232
  if (error instanceof CliUsageError)
233
233
  throw error;
234
- if (isCittyUsageError(error)) {
235
- throw new CliUsageError(error.message, await renderUsage(state.usageCommand));
236
- }
234
+ if (error instanceof Error && error.name === 'CLIError')
235
+ throw new CliUsageError(error.message, await renderUsage(state.command));
237
236
  throw error;
238
237
  }
239
238
  }
@@ -244,174 +243,137 @@ async function runCliWithErrorHandling(rawArgs) {
244
243
  catch (error) {
245
244
  if (error instanceof CliUsageError) {
246
245
  process.stderr.write(`${error.usage}\n\nerror: ${error.message}\n`);
247
- process.exitCode = 1;
248
- return;
246
+ process.exitCode = 2;
249
247
  }
250
- if (error instanceof RunXError) {
248
+ else if (error instanceof RunXError) {
251
249
  process.stderr.write(`error: ${error.message}\n`);
252
250
  process.exitCode = error.exitCode;
253
- return;
254
251
  }
255
- process.stderr.write(`error: ${error instanceof Error ? error.message : 'Unexpected failure.'}\n`);
256
- process.exitCode = 1;
257
- }
258
- }
259
- function createRunCommand(state, selectorDefault) {
260
- return defineCommand({
261
- meta: {
262
- name: selectorDefault ? 'runx <selector>' : 'runx run',
263
- alias: selectorDefault ? undefined : 'r',
264
- description: selectorDefault ? 'Run a selector using the root shorthand.' : 'Run one manifest command.',
265
- },
266
- args: selectorDefault
267
- ? runArgs
268
- : {
269
- selector: { type: 'positional', description: 'Command UID, group/id, index, or unambiguous ID.' },
270
- ...runArgs,
271
- },
272
- setup: withCommandHelp(state),
273
- run: async ({ args }) => {
274
- const selector = selectorDefault ?? (typeof args.selector === 'string' ? args.selector : undefined);
275
- if (!selector)
276
- throw await missingSelector(state);
277
- await runSelectedCommand(selector, resolveOptions(state.globalArgs), state.globalArgs);
278
- },
279
- });
280
- }
281
- function createSelectorCompatibleCommands(commands, state) {
282
- const aliases = new Set(['r']);
283
- return new Proxy(commands, {
284
- has: (target, property) => {
285
- if (typeof property !== 'string')
286
- return Reflect.has(target, property);
287
- if (aliases.has(property))
288
- return false;
289
- return true;
290
- },
291
- get: (target, property, receiver) => {
292
- if (typeof property !== 'string' || Reflect.has(target, property))
293
- return Reflect.get(target, property, receiver);
294
- return createRunCommand(state, property);
295
- },
296
- });
297
- }
298
- function resolveUsageCommand(positionals, commands, state) {
299
- const name = positionals[0];
300
- if (!name)
301
- return state.usageCommand;
302
- if (!commands.has(name))
303
- return createRunCommand(state, name);
304
- for (let length = positionals.length; length > 0; length -= 1) {
305
- const command = commands.get(positionals.slice(0, length).join(' '));
306
- if (command)
307
- return command;
252
+ else {
253
+ process.stderr.write(`error: ${error instanceof Error ? error.message : 'Unexpected failure.'}\n`);
254
+ process.exitCode = 1;
255
+ }
308
256
  }
309
- return commands.get(name);
310
257
  }
311
- function withCommandHelp(state) {
312
- return (context) => {
313
- state.usageCommand = context.cmd;
314
- };
258
+ async function load(optionsValue) {
259
+ const loaded = await readManifest(optionsValue.cwd, optionsValue.config);
260
+ const message = `configuration file loaded: ${loaded.path}\n`;
261
+ if (optionsValue.format === 'json')
262
+ process.stderr.write(message);
263
+ else
264
+ write(message);
265
+ return loaded;
315
266
  }
316
- async function missingSelector(state) {
317
- return new CliUsageError('Missing required positional argument: SELECTOR', await renderUsage(state.usageCommand));
267
+ async function listCommands(optionsValue) {
268
+ const { manifest, path } = await load(optionsValue);
269
+ write(optionsValue.format === 'json' ? renderJson({ manifestPath: path, manifest }) : renderList(manifest, path));
318
270
  }
319
- async function validateArguments(context, state) {
320
- const unknown = Object.keys(context.args).find((key) => !knownArgumentKeys.has(key));
321
- if (!unknown)
322
- return;
323
- throw new CliUsageError(`Unknown option --${unknown}`, await renderUsage(state.usageCommand));
324
- }
325
- async function handleUsage(command) {
326
- return handleOutput(`${await renderUsage(command)}\n`);
327
- }
328
- function handleOutput(value) {
329
- write(value);
330
- throw new CliHandled();
331
- }
332
- async function listCommands(options) {
333
- const { manifest, path } = await readManifest(options.cwd, options.file);
334
- write(options.format === 'json' ? renderJson({ manifestPath: path, manifest }) : renderList(manifest, path));
335
- }
336
- async function describeCommand(selector, options) {
337
- const { manifest, path } = await readManifest(options.cwd, options.file);
271
+ async function describeCommand(selector, optionsValue) {
272
+ const { manifest, path } = await load(optionsValue);
338
273
  const command = resolveCommand(manifest, path, selector);
339
- write(options.format === 'json' ? renderJson(command) : renderDescription(command));
274
+ write(optionsValue.format === 'json' ? renderJson(command) : renderDescription(command));
340
275
  }
341
- async function checkManifest(options) {
342
- const { manifest, path } = await readManifest(options.cwd, options.file);
276
+ async function checkManifest(optionsValue) {
277
+ const { manifest, path } = await load(optionsValue);
343
278
  const result = { valid: true, manifestPath: path, commandCount: manifest.commands.length, groups: Object.keys(manifest.groups) };
344
- write(options.format === 'json' ? renderJson(result) : `valid: true\nmanifest: ${path}\ncommands: ${result.commandCount}\n`);
279
+ write(optionsValue.format === 'json' ? renderJson(result) : `valid: true\nmanifest: ${path}\ncommands: ${result.commandCount}\n`);
345
280
  }
346
- async function initializeProject(args) {
347
- if (args.file) {
348
- throw new RunXError('runx init does not support --file. It always creates runx.yaml in --cwd or the current directory.');
349
- }
350
- if (args.format === 'json') {
351
- throw new RunXError('runx init does not support --format json because initialization is an interactive terminal workflow.');
352
- }
353
- await initializeRunXManifest({ cwd: resolve(args.cwd ?? process.cwd()) });
354
- }
355
- async function runSelectedCommand(selector, options, args) {
356
- const { manifest, path } = await readManifest(options.cwd, options.file);
281
+ async function runSelected(selector, optionsValue, args) {
282
+ const { manifest, path } = await load(optionsValue);
357
283
  const command = resolveCommand(manifest, path, selector);
358
284
  if (args.dryRun) {
359
- write(options.format === 'json' ? renderJson({ dryRun: true, command }) : renderExecutionPlan(command));
285
+ write(optionsValue.format === 'json' ? renderJson({ dryRun: true, command }) : renderExecutionPlan(command));
360
286
  return;
361
287
  }
362
- if (command.confirm === 'always' && !args.yes) {
363
- throw new RunXError(`Command ${command.uid} requires confirmation. Review it with \`runx describe ${command.uid}\` and rerun with --yes when authorized.`);
364
- }
365
- if (options.format === 'text')
288
+ if (command.confirm === 'always' && !args.yes)
289
+ throw new RunXError(`Command ${command.uid} requires confirmation. Rerun with --yes only after authorization.`, 2);
290
+ if (optionsValue.format === 'text')
366
291
  write(`Running ${command.uid} (${command.selector})\n`);
367
292
  process.exitCode = await runCommand(command);
368
293
  }
369
- async function runAgentsInstall(scopeValue, options, args) {
370
- const scope = scopeValue;
371
- if (scope !== 'local' && scope !== 'global')
372
- throw new RunXError('Agent scope must be local or global.');
373
- const tool = (args.tool ?? 'agents');
374
- if (!['agents', 'claude', 'all'].includes(tool))
375
- throw new RunXError('Agent tool must be agents, claude, or all.');
376
- const installed = await installAgentSkill(scope, tool, options.cwd);
377
- write(options.format === 'json' ? renderJson({ installed }) : `${installed.map((path) => `installed: ${path}`).join('\n')}\n`);
294
+ async function agentMutation(label, action, args) {
295
+ try {
296
+ const paths = await action(args.local ? 'local' : 'global', resolvePath(args.cwd ?? process.cwd()));
297
+ writeFormatted({ [label]: paths }, args);
298
+ }
299
+ catch (error) {
300
+ if (error instanceof RunXError)
301
+ throw error;
302
+ throw new RunXError(`Agent skill mutation failed: ${error instanceof Error ? error.message : String(error)}`, 5);
303
+ }
378
304
  }
379
- async function runAgentsInstructions(options) {
380
- const path = await installAgentInstructions(options.cwd);
381
- write(options.format === 'json' ? renderJson({ instructions: path }) : `updated: ${path}\n`);
305
+ async function instructionMutation(label, action, args) {
306
+ try {
307
+ const paths = await action(resolvePath(args.cwd ?? process.cwd()));
308
+ writeFormatted({ [label]: paths }, args);
309
+ }
310
+ catch (error) {
311
+ if (error instanceof RunXError)
312
+ throw error;
313
+ throw new RunXError(`Agent instruction mutation failed: ${error instanceof Error ? error.message : String(error)}`, 5);
314
+ }
382
315
  }
383
- async function runUpgradeCheck(options) {
384
- const result = await checkForLatestVersion();
385
- write(options.format === 'json' ? renderJson(result) : `current: ${result.currentVersion}\nlatest: ${result.latestVersion}\nupdate_available: ${result.updateAvailable}\n`);
316
+ async function runUpgradeList(args) {
317
+ const requestedArch = args.arch ? decode(archSchema, args.arch, '--arch') : process.arch;
318
+ const platform = resolveUpgradePlatform(process.platform, requestedArch);
319
+ const variant = decode(variantSchema, args.variant ?? 'baseline', '--variant');
320
+ const page = positiveInteger(args.page ?? '1', '--page');
321
+ const perPage = positiveInteger(args.perPage ?? '20', '--per-page');
322
+ const catalog = await fetchReleaseCatalog({ ...platform, variant, currentVersion: readVersion() });
323
+ const filtered = args.preReleases ? catalog.releases : catalog.releases.filter((release) => !release.prerelease);
324
+ const paged = { ...catalog, releases: filtered.slice((page - 1) * perPage, page * perPage) };
325
+ write(options(args).format === 'json' ? renderJson(paged) : renderReleaseCatalog(paged));
386
326
  }
387
- async function runUpgradeList(options) {
388
- const versions = await listAvailableVersions();
389
- write(options.format === 'json' ? renderJson({ versions }) : `${versions.join('\n')}\n`);
327
+ async function runUpgrade(optionsValue, args) {
328
+ if (args.arch)
329
+ decode(archSchema, args.arch, '--arch');
330
+ if (args.variant)
331
+ decode(variantSchema, args.variant, '--variant');
332
+ const text = optionsValue.format === 'text';
333
+ if (text)
334
+ write(renderUpgradeHeading());
335
+ const result = await upgradeSelf({
336
+ dryRun: Boolean(args.dryRun),
337
+ requestedVersion: typeof args.version === 'string' ? args.version : undefined,
338
+ arch: args.arch,
339
+ variant: args.variant,
340
+ onPlan: text ? (plan) => write(renderUpgradePlan(plan)) : undefined,
341
+ onEvent: text ? (event) => write(renderUpgradeEvent(event)) : undefined,
342
+ });
343
+ write(text ? renderUpgradeResult(result) : renderJson(result));
344
+ if (result.outcome === 'failed' || result.outcome === 'rolled-back')
345
+ process.exitCode = result.error?.code.includes('download') ? 4 : 5;
390
346
  }
391
- async function runUpgrade(options, args) {
392
- const result = await upgradeSelf(Boolean(args.dryRun));
393
- if (options.format === 'json')
394
- return write(renderJson(result));
395
- const summary = `current: ${result.currentVersion}\ntarget: ${result.latestVersion}\n`;
396
- write(result.upToDate ? `${summary}Already up to date.\n` : `${summary}path: ${result.executablePath}\n${result.scheduled ? 'scheduled: true\n' : ''}`);
347
+ function options(args) {
348
+ const format = decode(formatSchema, args.format ?? 'text', '--format');
349
+ return { cwd: resolvePath(args.cwd ?? process.cwd()), config: args.config, format: format, verbose: Boolean(args.verbose) };
397
350
  }
398
- async function runUninstall(options, args) {
399
- const result = await uninstallSelf(Boolean(args.dryRun));
400
- write(options.format === 'json' ? renderJson(result) : `path: ${result.executablePath}\n${result.dryRun ? 'dry_run: true\n' : result.scheduled ? 'scheduled: true\n' : 'uninstalled: true\n'}`);
351
+ function decode(schema, value, flag) {
352
+ try {
353
+ return Value.Decode(schema, value);
354
+ }
355
+ catch {
356
+ throw new RunXError(`Invalid ${flag} value: ${String(value)}`, 2);
357
+ }
401
358
  }
402
- function resolveOptions(args) {
403
- const format = args.format ?? 'text';
404
- if (format !== 'text' && format !== 'json')
405
- throw new RunXError('Invalid --format value. Expected text or json.');
406
- return {
407
- cwd: resolve(args.cwd ?? process.cwd()),
408
- file: args.file,
409
- format: format,
410
- verbose: Boolean(args.verbose),
411
- };
359
+ function positiveInteger(value, flag) {
360
+ const number = Number(value);
361
+ try {
362
+ return Value.Decode(positiveIntegerSchema, number);
363
+ }
364
+ catch {
365
+ throw new RunXError(`${flag} must be a positive integer.`, 2);
366
+ }
367
+ }
368
+ async function usageError(state, message) {
369
+ return new CliUsageError(message, await renderUsage(state.command));
412
370
  }
413
- function isCittyUsageError(error) {
414
- return error instanceof Error && error.name === 'CLIError';
371
+ function writeFormatted(value, args) {
372
+ write(options(args).format === 'json' ? renderJson(value) : `${typeof value === 'string' ? value : JSON.stringify(value, null, 2)}\n`);
373
+ }
374
+ function handled(value) {
375
+ write(value.endsWith('\n') ? value : `${value}\n`);
376
+ throw new CliHandled();
415
377
  }
416
378
  function write(value) {
417
379
  process.stdout.write(value);