@ws-rush/hedo 0.0.0-stage → 0.1.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/GLOSSARY.md ADDED
@@ -0,0 +1,35 @@
1
+ # He
2
+
3
+ He discovers user-authored workflows and runs a selected workflow on demand.
4
+
5
+ ## Language
6
+
7
+ **Workflow**:
8
+ A user-authored process describing steps, decisions, and work to perform.
9
+ _Avoid_: Extension, plugin
10
+
11
+ **Workflow package**:
12
+ An installable collection of one or more workflows shared and managed together.
13
+ _Avoid_: Extension, plugin
14
+
15
+ **Standalone workflow**:
16
+ A workflow provided independently of an installed workflow package.
17
+
18
+ **Workflow name**:
19
+ The identifier used to select a workflow.
20
+ _Avoid_: Workflow path
21
+
22
+ **Qualified workflow name**:
23
+ A workflow name that includes its package name to identify which package provides it.
24
+
25
+ **Run**:
26
+ A single execution of a workflow. The workflow is the process definition; a run is one occurrence of that process.
27
+
28
+ **Run completion**:
29
+ The normal end of a run. Completion is distinct from whether the workflow's business result describes success or failure.
30
+
31
+ **Run failure**:
32
+ An error that prevents a run from completing normally. A completed workflow describing an unsuccessful business result is not automatically a run failure.
33
+
34
+ **Run cancellation**:
35
+ User-requested termination of a run. Cancellation does not reverse work already performed.
package/README.md CHANGED
@@ -1,3 +1,185 @@
1
- # Temporary Holding Version
1
+ # He
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ He discovers and runs user-authored XState workflows from `~/.he/` and installed workflow packages.
4
+
5
+ ```sh
6
+ he list
7
+ he do hello
8
+ ```
9
+
10
+ The npm package is [`@ws-rush/hedo`](https://www.npmjs.com/package/@ws-rush/hedo). The source repository is [`ws-rush/he-do`](https://github.com/ws-rush/he-do).
11
+
12
+ ## Installation
13
+
14
+ He requires Node.js **22.19.0 or later**.
15
+
16
+ ```sh
17
+ npm install --global @ws-rush/hedo
18
+ ```
19
+
20
+ To install from a source checkout instead:
21
+
22
+ ```sh
23
+ npm ci
24
+ npm install --global .
25
+ ```
26
+
27
+ For development, use `node bin/he.mjs list` or `node bin/he.mjs do hello`.
28
+
29
+ npm must be on `PATH` for npm package installation and Git dependency installation. Git must be on `PATH` for Git sources. Standalone workflows and local-directory registration do not require either command.
30
+
31
+ ## Commands
32
+
33
+ `he list` prints workflow names in alphabetical order without importing or executing their code. If no workflows exist, it prints `No workflows found` and exits successfully.
34
+
35
+ `he do hello` selects a workflow and runs its default-exported actor logic in the foreground. A standalone `hello` workflow is `~/.he/hello.ts`. The workflow directory is independent of the working directory. Listing and execution do not create it automatically.
36
+
37
+ Standalone workflow names are exact, case-sensitive filenames without the final `.ts` suffix. They are not paths. Discovery includes only visible, regular `.ts` files directly inside `~/.he/`. Declaration files, symlinks, directories, hidden files, and filenames containing backslashes are ignored. Supporting modules can live in subdirectories or elsewhere.
38
+
39
+ `he add <source>` installs or registers a workflow package globally for the current user. `he remove <source>` removes its registration and any He-managed installation. `he packages` lists registered package sources and their paths. No command installs into the current project, and `--local` is not supported.
40
+
41
+ ## Workflow packages
42
+
43
+ A workflow package declares its workflow entry files in `package.json`:
44
+
45
+ ```json
46
+ {
47
+ "name": "@acme/workflows",
48
+ "version": "1.0.0",
49
+ "type": "module",
50
+ "files": ["src"],
51
+ "he": {
52
+ "workflows": {
53
+ "sync": "./src/sync.ts",
54
+ "cleanup": "./src/cleanup.ts"
55
+ }
56
+ }
57
+ }
58
+ ```
59
+
60
+ The workflow map is non-empty. Each entry names a file inside the package. Entry paths cannot escape the package root, including through symlinks. He reads this declaration without importing workflow code. Each entry uses the same default-export contract as a standalone workflow. Include the entry files and their helpers in the published npm tarball.
61
+
62
+ Adding an npm or Git source permits package installation scripts to execute with your permissions. Only add sources you trust.
63
+
64
+ Supported source forms include:
65
+
66
+ ```sh
67
+ he add npm:@acme/workflows
68
+ he add 'npm:@acme/workflows@^1.2.0'
69
+ he add npm:@acme/workflows@next
70
+ he add ./my-workflows
71
+ he add git:github.com/acme/workflows
72
+ he add git:github.com/acme/workflows@v1.2.0
73
+ he add https://github.com/acme/workflows.git
74
+ ```
75
+
76
+ npm and Git packages live in He-managed storage under `~/.he`, not the system npm global prefix. npm installs runtime dependencies. Git installation installs production dependencies when the repository has a `package.json`. Automatic peer dependency installation is disabled. Installation permits npm lifecycle scripts, including scripts supplied by dependencies.
77
+
78
+ Local directories load in place. He does not copy them or install their dependencies. Install dependencies in the local project yourself. Changes to local workflow files are available on the next invocation.
79
+
80
+ He preserves the requested source, version selector, or Git ref. Listing and running never install or refresh packages. Repeat `he add <source>` to refresh an installation. There is no separate update command.
81
+
82
+ Package workflow names include their package name:
83
+
84
+ ```sh
85
+ he list
86
+ he do @acme/workflows:sync
87
+ he do sync
88
+ he packages
89
+ he remove npm:@acme/workflows
90
+ ```
91
+
92
+ The short form works when exactly one package provides that workflow name. If several packages provide the name, He reports the qualified choices. A standalone workflow retains its short name and takes precedence over package short names. A standalone filename that exactly matches a qualified package workflow name causes a naming conflict. Rename one of those workflows rather than silently hiding it.
93
+
94
+ Installed sources must have distinct package names. Re-adding the same source updates that registration. To replace a package with a different source that has the same package name, remove the previous source first. npm removal identifies the package independently of its version selector. Git removal identifies the repository independently of its ref. Removing a local source never deletes its directory.
95
+
96
+ The [workflow-package example](examples/workflow-package/README.md) provides two entry files and commands for local development.
97
+
98
+ ## Workflow module
99
+
100
+ A minimal workflow at `~/.he/hello.ts` is:
101
+
102
+ ```ts
103
+ import { createMachine } from '@he/xstate';
104
+
105
+ export default createMachine({
106
+ initial: 'done',
107
+ states: {
108
+ done: { type: 'final' },
109
+ },
110
+ });
111
+ ```
112
+
113
+ Export ordinary XState actor logic, not a factory, promise, or already-created actor. He creates, observes, and starts one root actor. Other supported logic forms, including `createAsyncLogic`, use the same default-export contract.
114
+
115
+ Workflows gather their own input through Node APIs, files, environment variables, or interactive prompts such as Node readline. He supplies no root actor input or custom prompt API. Non-TTY runs are allowed. The workflow decides how to handle piped input and EOF.
116
+
117
+ The [contact-import example](examples/contact-import/contact-import.ts) includes serial prompts, column mapping, duplicate decisions, approval, batches, retries, and simulated ambiguous remote commits. Its CSV files and remote service are disposable fixtures, not production integrations.
118
+
119
+ ## Runtime and imports
120
+
121
+ He pins **XState `6.0.0-alpha.65`** and **jiti `2.7.0`**. Workflows use the v6 alpha APIs, including `createAsyncLogic`, rather than v5 APIs such as `fromPromise`.
122
+
123
+ Workflows that use only supplied XState and Node built-ins need no local `package.json`, `node_modules`, TypeScript configuration, or build step. Import the supplied API through `@he/xstate` or its public subpaths:
124
+
125
+ - `@he/xstate/fsm`
126
+ - `@he/xstate/graph`
127
+ - `@he/xstate/actors`
128
+ - `@he/xstate/durable`
129
+ - `@he/xstate/validation`
130
+
131
+ He uses jiti virtual modules with `tryNative: false` and `moduleCache: false`. Local helpers follow jiti's importer-relative resolution. The pinned jiti transformer determines supported TypeScript syntax and module interoperability. Loading does not perform semantic typechecking or configure editor types. jiti may write a transform cache.
132
+
133
+ Additional npm dependencies are optional. Installed npm and Git workflow packages manage them during `he add`. Standalone workflows and local-directory packages remain author-managed. Authors can maintain a shared `package.json` and `node_modules` under `~/.he/`. Helpers elsewhere resolve their dependencies from their own location. Missing dependencies produce loading errors, not automatic installs.
134
+
135
+ The supplied mapping applies to imports controlled by jiti. A compiled helper with a missing physical `@he/xstate` package can use jiti's transformed fallback. Successful native dependency loading and explicit `createRequire` calls are not universally intercepted. Native fallback may execute top-level code before retrying it. A third-party bare `xstate` import does not request `@he/xstate` and has no supplied-version guarantee.
136
+
137
+ Editor configuration and optional semantic checking remain author-managed. They must resolve `@he/xstate` to the matching real XState declarations and appropriate Node declarations. Runtime mapping alone does not configure an editor.
138
+
139
+ ## Outcomes and resources
140
+
141
+ | Outcome | Exit code |
142
+ | --- | --- |
143
+ | Root actor completes normally | 0 |
144
+ | Discovery, loading, validation, startup, or execution fails | 1 |
145
+ | User cancels the run with Ctrl+C / SIGINT | 130 |
146
+ | Process receives SIGTERM (e.g. Docker stop or `kill <pid>`) | 143 |
147
+
148
+ A final state named `failed` or output such as `{ success: false }` still counts as normal completion. He does not interpret business-result fields. An abnormal root stop is a run failure.
149
+
150
+ He prints no automatic progress, transitions, context, or final actor output. Workflows print their own messages. Runner diagnostics go to stderr with the relevant stage and workflow context. Code exceptions retain available error messages and stacks.
151
+
152
+ There is no overall run timeout. He keeps an active run alive even when its actor has no pending Node I/O. Normal completion and failure release the runner's wait resources and allow natural Node exit. There is no normal-completion watchdog. Author-leaked timers, sockets, or interfaces can keep the process alive.
153
+
154
+ The first Ctrl+C records cancellation and stops the root actor. Cancellation during import prevents later root startup. A second interrupt or five seconds without exit forces code 130. Cooperative cleanup can exit sooner. The cancellation deadline requires a responsive JavaScript event loop.
155
+
156
+ SIGTERM stops the root actor and reserves one second for log drainage before forcing exit with code 143, even if author resources remain open. SIGTERM during import prevents later root startup; it also applies during post-completion drainage. Repeated SIGTERM does not reset the deadline. SIGTERM during Ctrl+C cleanup switches to this one-second shutdown; Ctrl+C during SIGTERM cleanup forces exit immediately with code 143. The deadline requires a responsive JavaScript event loop, and the signal must reach the Node process (container entrypoints must forward it).
157
+
158
+ Workflow authors own directly created resources and cleanup. Use async actor abort signals and `finally` paths. Stop does not universally cancel promises, close interfaces, kill child processes, or undo effects.
159
+
160
+ Direct terminal readline users must forward interface SIGINT to the installed process handler:
161
+
162
+ ```ts
163
+ const interrupt = () => process.emit('SIGINT', 'SIGINT');
164
+ rl.on('SIGINT', interrupt);
165
+ ```
166
+
167
+ Remove that bridge during cleanup. Abort or settle pending questions on EOF or close, and close the interface explicitly. Closing readline alone need not settle a pending question. The contact-import example implements these paths.
168
+
169
+ ## Development checks
170
+
171
+ ```sh
172
+ npm test
173
+ npm run test:reference
174
+ npm run test:acceptance
175
+ ```
176
+
177
+ `npm test` runs isolated subprocess checks. The reference checks require Python 3 and a Linux controlling terminal. The Linux acceptance driver also packs and npm-installs the CLI in a disposable directory, then repeats the checks against that installed copy. Set `HE_EVIDENCE_DIR` to retain its logs.
178
+
179
+ Linux, macOS, and native Windows are the intended CLI platforms. Initial acceptance evidence covers Linux only. macOS and Windows remain unverified.
180
+
181
+ ## Execution boundaries
182
+
183
+ Workflows and package installation scripts are trusted code with the user's permissions, not sandboxed programs. Only install packages and dependencies you trust. Importing a workflow executes top-level code before export validation. Cancellation does not roll back work already performed.
184
+
185
+ Background runs, durable execution, saved progress, and resume are out of scope. See [GLOSSARY.md](GLOSSARY.md) for project terminology.
package/bin/he.mjs ADDED
@@ -0,0 +1,56 @@
1
+ #!/usr/bin/env node
2
+ import { homedir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import metadata from '../package.json' with { type: 'json' };
5
+ import { packageStore } from '../src/packages.mjs';
6
+ import { report, WorkflowError } from '../src/errors.mjs';
7
+ import { run } from '../src/run.mjs';
8
+
9
+ const usage = 'Usage: he add <source>\n he remove <source>\n he packages\n he list\n he do <workflow>\n he --help\n he --version';
10
+
11
+ /** @param {string[]} argv */
12
+ async function main(argv) {
13
+ if (argv.length === 1 && ['help', '--help', '-h'].includes(argv[0])) {
14
+ console.log(usage);
15
+ return;
16
+ }
17
+ if (argv.length === 1 && ['version', '--version', '-v'].includes(argv[0])) {
18
+ console.log(metadata.version);
19
+ return;
20
+ }
21
+ const [command, name] = argv;
22
+ const selector = name && !name.includes('\\') && (!name.includes('/') || /^@[^/]+\/[^/:]+:[^/]+$/.test(name));
23
+ if (!(['list', 'packages'].includes(command) && argv.length === 1)
24
+ && !(['add', 'remove'].includes(command) && argv.length === 2 && name)
25
+ && !(command === 'do' && argv.length === 2 && selector)) {
26
+ throw new WorkflowError('usage', usage);
27
+ }
28
+ const packages = packageStore({ directory: join(homedir(), '.he'), cwd: process.cwd() });
29
+ if (command === 'add') {
30
+ const added = await packages.add(name);
31
+ console.log(`${added.source}\t${added.root}`);
32
+ return;
33
+ }
34
+ if (command === 'remove') {
35
+ console.log(await packages.remove(name) ? `Removed ${name}` : `Package not registered: ${name}`);
36
+ return;
37
+ }
38
+ if (command === 'packages') {
39
+ const installed = await packages.list();
40
+ console.log(installed.length ? installed.map(item => `${item.source}\t${item.root}`).join('\n') : 'No packages installed');
41
+ return;
42
+ }
43
+ const catalog = await packages.catalog();
44
+ if (command === 'list') {
45
+ console.log(catalog.workflows.length ? catalog.workflows.map(workflow => workflow.name).join('\n') : 'No workflows found');
46
+ return;
47
+ }
48
+ await run(catalog.select(name));
49
+ }
50
+
51
+ try {
52
+ await main(process.argv.slice(2));
53
+ } catch (error) {
54
+ process.exitCode = 1;
55
+ report(error);
56
+ }
@@ -0,0 +1,259 @@
1
+ import { createMachine, createAsyncLogic, types } from '@he/xstate';
2
+ import { createInterface } from 'node:readline/promises';
3
+ import { readFile } from 'node:fs/promises';
4
+ import { setTimeout as delay } from 'node:timers/promises';
5
+ import { randomUUID } from 'node:crypto';
6
+ import { fileURLToPath } from 'node:url';
7
+
8
+ type Contact = { name: string; email: string; company: string };
9
+ type Mode = 'clean' | 'transient' | 'lost' | 'slow' | 'fatal';
10
+ type Prompt = { text: string; choices?: string[]; fallback?: string };
11
+
12
+ // Closing readline alone does not settle an outstanding question.
13
+ const question = createAsyncLogic<string, Prompt>({
14
+ run: async ({ input, signal }) => {
15
+ signal.throwIfAborted();
16
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
17
+ const closed = new AbortController();
18
+ const close = () => closed.abort(new Error('Input closed before an answer (EOF).'));
19
+ const interrupt = () => process.emit('SIGINT', 'SIGINT');
20
+ const abort = () => rl.close();
21
+ rl.on('close', close);
22
+ rl.on('SIGINT', interrupt);
23
+ signal.addEventListener('abort', abort, { once: true });
24
+ try {
25
+ while (true) {
26
+ const answer = (await rl.question(input.text, {
27
+ signal: AbortSignal.any([signal, closed.signal]),
28
+ })).trim() || input.fallback || '';
29
+ if (!input.choices || input.choices.includes(answer)) return answer;
30
+ console.log(`Choose: ${input.choices.join(' / ')}`);
31
+ }
32
+ } catch (error) {
33
+ if (!signal.aborted && closed.signal.aborted) throw closed.signal.reason;
34
+ throw error;
35
+ } finally {
36
+ signal.removeEventListener('abort', abort);
37
+ rl.off('SIGINT', interrupt);
38
+ rl.off('close', close);
39
+ rl.close();
40
+ }
41
+ },
42
+ });
43
+
44
+ function createService() {
45
+ const records = new Map<string, Contact>([
46
+ ['ada@example.com', { name: 'Ada OLD', email: 'ada@example.com', company: 'OldCo' }],
47
+ ['ben@example.com', { name: 'Ben OLD', email: 'ben@example.com', company: 'OldCo' }],
48
+ ]);
49
+ const applied = new Map<string, number>();
50
+ const attempts = new Map<string, number>();
51
+ const journal: string[] = [];
52
+ console.log('CONTACT_IMPORT ' + JSON.stringify({ event: 'service', records: [...records.values()] }));
53
+ return {
54
+ records, applied, attempts, journal,
55
+ async lookup(signal: AbortSignal) {
56
+ console.log('Looking up existing contacts...');
57
+ await delay(150, undefined, { signal });
58
+ return new Map(records);
59
+ },
60
+ async upload(key: string, rows: Contact[], batch: number, mode: Mode, signal: AbortSignal) {
61
+ const attempt = (attempts.get(key) || 0) + 1;
62
+ attempts.set(key, attempt);
63
+ if (applied.has(key)) {
64
+ journal.push(`batch ${batch}: replayed receipt, no extra writes`);
65
+ console.log('CONTACT_IMPORT ' + JSON.stringify({ event: 'replay', key, batch, writes: applied.get(key) }));
66
+ return applied.get(key)!;
67
+ }
68
+ await delay(mode === 'slow' ? 15000 : 200, undefined, { signal });
69
+ if (batch === 2 && mode === 'fatal') throw new Error('Permission denied: not retryable');
70
+ if (batch === 2 && mode === 'transient' && attempt === 1) {
71
+ journal.push('batch 2: rejected before commit');
72
+ throw new Error('Temporary service failure');
73
+ }
74
+ signal.throwIfAborted();
75
+ for (const row of rows) records.set(row.email, row);
76
+ applied.set(key, rows.length);
77
+ journal.push(`batch ${batch}: committed ${rows.length} writes`);
78
+ console.log('CONTACT_IMPORT ' + JSON.stringify({ event: 'commit', key, batch, writes: rows.length, records: [...records.values()] }));
79
+ if (batch === 2 && mode === 'lost' && attempt === 1) {
80
+ console.log('SIMULATED: batch 2 committed remotely; its response is delayed/lost.');
81
+ await delay(1500, undefined, { signal });
82
+ throw new Error('Response lost; commit outcome unknown to the importer');
83
+ }
84
+ return rows.length;
85
+ },
86
+ };
87
+ }
88
+
89
+ type Service = ReturnType<typeof createService>;
90
+ type Table = { headers: string[]; rows: string[][] };
91
+ type Context = {
92
+ mode: Mode; file: string; table: Table; mapping: string[];
93
+ service: Service; runId: string; pending: Contact[]; duplicates: Contact[];
94
+ invalid: string[]; skipped: number; cursor: number; confirmed: number;
95
+ failure: string; result: string;
96
+ };
97
+
98
+ const load = createAsyncLogic<Table, string>({
99
+ run: async ({ input, signal }) => {
100
+ const text = await readFile(input, { encoding: 'utf8', signal });
101
+ if (text.includes('"')) throw new Error('Example CSV does not support quoted fields.');
102
+ const [head, ...lines] = text.trim().split(/\r?\n/);
103
+ const headers = head.split(',').map(s => s.trim());
104
+ if (!head || new Set(headers).size !== headers.length) throw new Error('Invalid CSV header.');
105
+ return { headers, rows: lines.map(line => line.split(',').map(s => s.trim())) };
106
+ },
107
+ });
108
+
109
+ const reconcile = createAsyncLogic<{
110
+ pending: Contact[]; duplicates: Contact[]; invalid: string[];
111
+ }, Context>({
112
+ run: async ({ input, signal }) => {
113
+ const indexes = input.mapping.map(name => input.table.headers.indexOf(name));
114
+ if (indexes.length !== 3 || new Set(indexes).size !== 3 || indexes.some(i => i < 0)) {
115
+ throw new Error('Map three distinct existing columns, in name,email,company order.');
116
+ }
117
+ const existing = await input.service.lookup(signal);
118
+ const pending: Contact[] = [], duplicates: Contact[] = [], invalid: string[] = [];
119
+ const seen = new Set<string>();
120
+ for (const [i, row] of input.table.rows.entries()) {
121
+ const [name, email, company] = indexes.map(index => row[index] || '');
122
+ const normalized = email.toLowerCase();
123
+ if (row.length !== input.table.headers.length || !name || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
124
+ invalid.push(`row ${i + 2}: missing name, malformed email, or wrong column count`);
125
+ continue;
126
+ }
127
+ if (seen.has(normalized)) {
128
+ invalid.push(`row ${i + 2}: repeated email in source (${normalized})`);
129
+ continue;
130
+ }
131
+ seen.add(normalized);
132
+ const contact = { name, email: normalized, company };
133
+ (existing.has(normalized) ? duplicates : pending).push(contact);
134
+ }
135
+ return { pending, duplicates, invalid };
136
+ },
137
+ });
138
+
139
+ const upload = createAsyncLogic<number, Context>({
140
+ run: async ({ input, signal }) => {
141
+ const batch = input.cursor / 2 + 1;
142
+ console.log(`Uploading batch ${batch} (${Math.min(2, input.pending.length - input.cursor)} contacts)...`);
143
+ try {
144
+ return await input.service.upload(
145
+ `${input.runId}:${batch}`, input.pending.slice(input.cursor, input.cursor + 2),
146
+ batch, input.mode, signal,
147
+ );
148
+ } finally {
149
+ if (signal.aborted) console.log('Upload cancelled. A remote commit may already have happened; no rollback.');
150
+ }
151
+ },
152
+ });
153
+
154
+ export default createMachine({
155
+ schemas: { context: types<Context>() },
156
+ context: () => ({
157
+ mode: 'clean', file: '', table: { headers: [], rows: [] }, mapping: [],
158
+ service: createService(), runId: randomUUID(), pending: [], duplicates: [], invalid: [],
159
+ skipped: 0, cursor: 0, confirmed: 0, failure: '', result: '',
160
+ }),
161
+ initial: 'scenario',
162
+ states: {
163
+ scenario: {
164
+ invoke: {
165
+ src: question,
166
+ input: { text: 'Scenario [clean/transient/lost/slow/fatal] (clean): ',
167
+ choices: ['clean', 'transient', 'lost', 'slow', 'fatal'], fallback: 'clean' },
168
+ onDone: ({ event }) => ({ target: 'file', context: { mode: event.output as Mode } }),
169
+ },
170
+ },
171
+ file: {
172
+ invoke: {
173
+ src: question,
174
+ input: { text: 'CSV path (contacts.csv): ', fallback: fileURLToPath(new URL('./contacts.csv', import.meta.url)) },
175
+ onDone: ({ event }) => ({ target: 'load', context: { file: event.output } }),
176
+ },
177
+ },
178
+ load: {
179
+ invoke: {
180
+ src: load, input: ({ context }) => context.file,
181
+ onDone: ({ event }, enq) => {
182
+ enq(() => console.log(`Columns: ${event.output.headers.join(',')}`));
183
+ return { target: 'mapping', context: { table: event.output } };
184
+ },
185
+ },
186
+ },
187
+ mapping: {
188
+ invoke: {
189
+ src: question,
190
+ input: { text: 'Map columns in name,email,company order (name,email,company): ', fallback: 'name,email,company' },
191
+ onDone: ({ event }) => ({ target: 'reconcile', context: { mapping: event.output.split(',').map(s => s.trim()) } }),
192
+ },
193
+ },
194
+ reconcile: {
195
+ invoke: {
196
+ src: reconcile, input: ({ context }) => context,
197
+ onDone: ({ event }) => ({ target: 'nextDuplicate', context: event.output }),
198
+ },
199
+ },
200
+ nextDuplicate: {
201
+ type: 'choice',
202
+ choice: ({ context }) => ({ target: context.duplicates.length ? 'duplicate' : 'approval' }),
203
+ },
204
+ duplicate: {
205
+ invoke: {
206
+ src: question,
207
+ input: ({ context }) => ({ text: `Existing ${context.duplicates[0].email}: update/skip? `, choices: ['update', 'skip'] }),
208
+ onDone: ({ context, event }) => ({ target: 'nextDuplicate', context: {
209
+ pending: event.output === 'update' ? [...context.pending, context.duplicates[0]] : context.pending,
210
+ duplicates: context.duplicates.slice(1), skipped: context.skipped + (event.output === 'skip' ? 1 : 0),
211
+ } }),
212
+ },
213
+ },
214
+ approval: {
215
+ invoke: {
216
+ src: question,
217
+ input: ({ context }) => ({
218
+ text: `Review: ${context.pending.length} writes, ${context.skipped} skipped, ${context.invalid.length} invalid.\n${context.invalid.join('\n')}\nUpload? yes/no: `,
219
+ choices: ['yes', 'no'],
220
+ }),
221
+ onDone: ({ context, event }) => ({
222
+ target: event.output === 'yes' && context.pending.length ? 'upload' : 'finished',
223
+ context: { result: event.output === 'no' ? 'declined' : 'complete' },
224
+ }),
225
+ },
226
+ },
227
+ upload: {
228
+ invoke: {
229
+ src: upload, input: ({ context }) => context,
230
+ onDone: ({ context, event }, enq) => {
231
+ enq(() => console.log('CONTACT_IMPORT ' + JSON.stringify({
232
+ event: 'receipt', key: `${context.runId}:${context.cursor / 2 + 1}`,
233
+ batch: context.cursor / 2 + 1, confirmed: context.confirmed + event.output,
234
+ })));
235
+ return {
236
+ target: context.cursor + 2 < context.pending.length ? 'upload' : 'finished', reenter: true,
237
+ context: { cursor: context.cursor + 2, confirmed: context.confirmed + event.output, result: 'complete' },
238
+ };
239
+ },
240
+ onError: ({ context, event }) => {
241
+ if (context.mode === 'fatal') throw event.error;
242
+ return { target: 'recovery', context: { failure: String(event.error) } };
243
+ },
244
+ },
245
+ },
246
+ recovery: {
247
+ invoke: {
248
+ src: question,
249
+ input: ({ context }) => ({ text: `${context.failure}\n${context.confirmed} writes confirmed. retry/stop? `, choices: ['retry', 'stop'] }),
250
+ onDone: ({ event }) => ({ target: event.output === 'retry' ? 'upload' : 'finished', context: { result: 'partial' } }),
251
+ },
252
+ },
253
+ finished: {
254
+ type: 'final',
255
+ output: ({ context }) => ({ success: context.result === 'complete', result: context.result, confirmed: context.confirmed }),
256
+ entry: ({ context }, enq) => enq(() => console.log(`Result: ${context.result}; confirmed writes: ${context.confirmed}. No rollback or saved resume.`)),
257
+ },
258
+ },
259
+ });
@@ -0,0 +1,9 @@
1
+ name,email,company
2
+ Ada NEW,ada@example.com,NewCo
3
+ Ben NEW,ben@example.com,NewCo
4
+ Cy,cy@example.com,Example
5
+ Dee,dee@example.com,Example
6
+ Eli,eli@example.com,Example
7
+ Fay,fay@example.com,Example
8
+ Bad,bad-address,Example
9
+ Cy duplicate,CY@example.com,Other
@@ -0,0 +1,6 @@
1
+ organization,email_address,full_name
2
+ NewCo,ada@example.com,Ada NEW
3
+ Example,cy@example.com,Cy
4
+ Example,dee@example.com,Dee
5
+ Example,eli@example.com,Eli
6
+ Example,fay@example.com,Fay
@@ -0,0 +1,38 @@
1
+ # Run a local workflow package
2
+
3
+ This package provides `hello` and `goodbye` workflows. Both use the XState runtime supplied by He.
4
+
5
+ 1. From the He repository root, register the package.
6
+
7
+ ```sh
8
+ he add ./examples/workflow-package
9
+ ```
10
+
11
+ 2. List the package and its workflows.
12
+
13
+ ```sh
14
+ he packages
15
+ he list
16
+ ```
17
+
18
+ 3. Run a workflow by its qualified name.
19
+
20
+ ```sh
21
+ he do @he/example-workflows:hello
22
+ ```
23
+
24
+ The workflow prints `Hello from a workflow package.` and completes. If no standalone workflow or other package uses `hello`, `he do hello` selects the same workflow.
25
+
26
+ 4. Edit `src/hello.ts` and run it again. Local packages load directly from their source directory.
27
+
28
+ 5. Remove the registration.
29
+
30
+ ```sh
31
+ he remove ./examples/workflow-package
32
+ ```
33
+
34
+ He leaves the example directory intact.
35
+
36
+ To add an npm dependency, install it in this directory and import it from a workflow or helper. He does not install dependencies for local-directory sources.
37
+
38
+ To publish your own package, choose a unique package name and include the workflow files in the npm tarball. Keep the `he.workflows` map in `package.json`. See the [workflow package reference](../../README.md#workflow-packages) for source forms, naming, and installation behavior.
@@ -0,0 +1,14 @@
1
+ {
2
+ "name": "@he/example-workflows",
3
+ "version": "1.0.0",
4
+ "type": "module",
5
+ "files": [
6
+ "src"
7
+ ],
8
+ "he": {
9
+ "workflows": {
10
+ "hello": "./src/hello.ts",
11
+ "goodbye": "./src/goodbye.ts"
12
+ }
13
+ }
14
+ }
@@ -0,0 +1,11 @@
1
+ import { createMachine } from '@he/xstate';
2
+
3
+ export default createMachine({
4
+ initial: 'done',
5
+ states: {
6
+ done: {
7
+ entry: () => console.log('Goodbye from a workflow package.'),
8
+ type: 'final',
9
+ },
10
+ },
11
+ });
@@ -0,0 +1,11 @@
1
+ import { createMachine } from '@he/xstate';
2
+
3
+ export default createMachine({
4
+ initial: 'done',
5
+ states: {
6
+ done: {
7
+ entry: () => console.log('Hello from a workflow package.'),
8
+ type: 'final',
9
+ },
10
+ },
11
+ });
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "@ws-rush/hedo",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "publishConfig": {
5
+ "access": "public"
6
+ },
7
+ "type": "module",
8
+ "description": "Discover and run user-authored XState workflows",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/ws-rush/he-do.git"
12
+ },
13
+ "homepage": "https://github.com/ws-rush/he-do#readme",
14
+ "bugs": {
15
+ "url": "https://github.com/ws-rush/he-do/issues"
16
+ },
17
+ "engines": {
18
+ "node": ">=22.19.0"
19
+ },
20
+ "bin": {
21
+ "he": "bin/he.mjs"
22
+ },
23
+ "files": [
24
+ "bin",
25
+ "src",
26
+ "examples",
27
+ "README.md",
28
+ "GLOSSARY.md"
29
+ ],
30
+ "scripts": {
31
+ "test": "node --test test/cli.test.mjs test/packages.test.mjs",
32
+ "test:reference": "python3 test/reference.py",
33
+ "test:acceptance": "node scripts/acceptance.mjs"
34
+ },
35
+ "dependencies": {
36
+ "jiti": "2.7.0",
37
+ "xstate": "6.0.0-alpha.65"
38
+ }
39
+ }
package/src/errors.mjs ADDED
@@ -0,0 +1,21 @@
1
+ export class WorkflowError extends Error {
2
+ constructor(stage, message, options = {}) {
3
+ super(message, Object.hasOwn(options, 'cause') ? { cause: options.cause } : undefined);
4
+ this.name = 'WorkflowError';
5
+ this.stage = stage;
6
+ this.workflow = options.workflow;
7
+ }
8
+ }
9
+
10
+ /** Expected failures stay short; code exceptions retain their original stack and cause. */
11
+ export function report(error) {
12
+ if (!(error instanceof WorkflowError)) {
13
+ console.error(error);
14
+ return;
15
+ }
16
+ const context = error.workflow
17
+ ? ` workflow ${JSON.stringify(error.workflow.name)} (${error.workflow.path})`
18
+ : '';
19
+ console.error(`he:${context} ${error.stage}: ${error.message}`);
20
+ if (Object.hasOwn(error, 'cause')) console.error(error.cause);
21
+ }
package/src/load.mjs ADDED
@@ -0,0 +1,55 @@
1
+ import { createJiti } from 'jiti';
2
+ import * as xstate from 'xstate';
3
+ import * as fsm from 'xstate/fsm';
4
+ import * as graph from 'xstate/graph';
5
+ import * as actors from 'xstate/actors';
6
+ import * as durable from 'xstate/durable';
7
+ import * as validation from 'xstate/validation';
8
+ import { WorkflowError } from './errors.mjs';
9
+
10
+ const hostModules = {
11
+ xstate,
12
+ 'xstate/fsm': fsm,
13
+ 'xstate/graph': graph,
14
+ 'xstate/actors': actors,
15
+ 'xstate/durable': durable,
16
+ 'xstate/validation': validation,
17
+ };
18
+ // Jiti's registry lookup includes inherited properties, so keep the prototype empty.
19
+ const virtualModules = Object.assign(Object.create(null), Object.fromEntries(
20
+ Object.entries(hostModules).map(([name, namespace]) => [`@he/${name}`, namespace]),
21
+ ));
22
+
23
+ /** @param {import('./workflows.mjs').Workflow} workflow
24
+ * @returns {Promise<import('xstate').AnyActorLogic>} */
25
+ export async function loadLogic(workflow) {
26
+ let namespace;
27
+ try {
28
+ const jiti = createJiti(import.meta.url, {
29
+ virtualModules,
30
+ tryNative: false,
31
+ moduleCache: false,
32
+ // Require an explicit default rather than jiti's fallback to the whole module.
33
+ interopDefault: false,
34
+ });
35
+ namespace = await jiti.import(workflow.path);
36
+ } catch (cause) {
37
+ throw new WorkflowError('loading', 'Could not load workflow module', { workflow, cause });
38
+ }
39
+
40
+ let logic;
41
+ let valid;
42
+ try {
43
+ logic = namespace != null && Object.hasOwn(namespace, 'default') ? namespace.default : undefined;
44
+ valid = logic !== null && typeof logic === 'object'
45
+ && typeof logic.then !== 'function'
46
+ && ['transition', 'initialTransition', 'getInitialSnapshot', 'getPersistedSnapshot']
47
+ .every(method => typeof logic[method] === 'function');
48
+ } catch (cause) {
49
+ throw new WorkflowError('export validation', 'Could not inspect default export', { workflow, cause });
50
+ }
51
+ if (!valid) {
52
+ throw new WorkflowError('export validation', 'Expected a default-exported XState actor logic object', { workflow });
53
+ }
54
+ return logic;
55
+ }
@@ -0,0 +1,388 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { lstat, mkdir, open, readFile, realpath, rename, rm, stat, unlink, writeFile } from 'node:fs/promises';
4
+ import { isAbsolute, join, relative, resolve, sep } from 'node:path';
5
+ import { fileURLToPath, pathToFileURL } from 'node:url';
6
+ import { WorkflowError } from './errors.mjs';
7
+ import { discover } from './workflows.mjs';
8
+
9
+ const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
10
+ const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
11
+ const packageName = value => typeof value === 'string' && value.length <= 214
12
+ && /^(?:@[a-z0-9._-]+\/[a-z0-9._-]+|[a-z0-9][a-z0-9._-]*)$/.test(value)
13
+ && value.replace(/^@/, '').split('/').every(part => part !== '.' && part !== '..')
14
+ && !['node_modules', 'favicon.ico'].includes(value);
15
+ const simpleName = value => /^[a-zA-Z0-9_-][a-zA-Z0-9._-]*$/.test(value);
16
+ const absolutePath = value => typeof value === 'string' && !value.includes('\0') && isAbsolute(value) && resolve(value) === value;
17
+ const inside = (root, path) => {
18
+ const rel = relative(root, path);
19
+ return rel !== '' && rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
20
+ };
21
+ const problem = message => new WorkflowError('packages', message);
22
+
23
+ function remoteSource(requested) {
24
+ if (typeof requested !== 'string' || !requested || /[\0\r\n]/.test(requested) || requested.startsWith('-')) {
25
+ throw problem('Invalid package source');
26
+ }
27
+ if (requested.startsWith('npm:')) {
28
+ const match = /^(?<name>@[^/@]+\/[^/@]+|[^/@]+)(?:@(?<selector>.+))?$/.exec(requested.slice(4));
29
+ const name = match?.groups.name;
30
+ const selector = match?.groups.selector ?? 'latest';
31
+ if (!packageName(name) || !/^[a-zA-Z0-9_*^~<>=|.+ -]+$/.test(selector)) {
32
+ throw problem(`Invalid npm source ${JSON.stringify(requested)}`);
33
+ }
34
+ return { kind: 'npm', id: `npm:${name}`, requested, name, selector };
35
+ }
36
+ if (!/^(?:git:|https:\/\/|ssh:\/\/|git@)/.test(requested)) return null;
37
+ let input = requested.startsWith('git:') ? requested.slice(4) : requested;
38
+ let url;
39
+ let path;
40
+ let identity;
41
+ const scp = /^(?:([^@/\s]+)@)?([a-zA-Z0-9.-]+):(.+)$/.exec(input);
42
+ if (!input.includes('://') && scp) {
43
+ path = scp[3];
44
+ url = `${scp[1] ?? 'git'}@${scp[2]}:`;
45
+ identity = `${scp[2].toLowerCase()}/`;
46
+ } else {
47
+ if (!input.includes('://')) input = `https://${input}`;
48
+ if (input.split('/').some(part => /^(?:\.|%2e){1,2}$/i.test(part))) {
49
+ throw problem(`Invalid Git repository path ${JSON.stringify(requested)}`);
50
+ }
51
+ let parsed;
52
+ try { parsed = new URL(input); } catch { throw problem(`Invalid Git source ${JSON.stringify(requested)}`); }
53
+ if (!['https:', 'ssh:', 'file:'].includes(parsed.protocol) || parsed.password || parsed.search || parsed.hash) {
54
+ throw problem(`Unsupported Git URL ${JSON.stringify(requested)}`);
55
+ }
56
+ path = parsed.pathname;
57
+ if (parsed.protocol === 'file:') {
58
+ if (!requested.startsWith('git:file:///') || parsed.hostname) throw problem('Local Git URLs require git:file:///absolute/path');
59
+ url = 'file://';
60
+ identity = 'file://';
61
+ } else {
62
+ if (!parsed.hostname) throw problem('Git URL requires a host');
63
+ url = `${parsed.protocol}//${parsed.username ? `${parsed.username}@` : ''}${parsed.host}`;
64
+ const port = parsed.port && !(parsed.protocol === 'ssh:' && parsed.port === '22') ? `:${parsed.port}` : '';
65
+ identity = `${parsed.hostname.toLowerCase()}${port}/`;
66
+ }
67
+ }
68
+ const delimiter = path.indexOf('@');
69
+ const ref = delimiter < 0 ? null : path.slice(delimiter + 1);
70
+ path = delimiter < 0 ? path : path.slice(0, delimiter);
71
+ if (!path || /[\s\\\0]/.test(path) || path.split('/').some(part => part === '.' || part === '..') || (ref !== null
72
+ && (!ref || ref.startsWith('-') || /[\s\\\0~^:?*\[]/.test(ref) || ref.includes('..') || ref.includes('@{')))) {
73
+ throw problem(`Invalid Git repository or ref ${JSON.stringify(requested)}`);
74
+ }
75
+ let repository = path.replace(/^\/+|\/+$/g, '').replace(/\.git$/, '');
76
+ if (!repository) throw problem('Git repository path is empty');
77
+ if (identity === 'file://') {
78
+ let local;
79
+ try { local = fileURLToPath(`${url}${path}`); } catch { throw problem('Invalid local Git URL'); }
80
+ repository = pathToFileURL(resolve(local)).href;
81
+ } else repository = identity + repository;
82
+ return { kind: 'git', id: `git:${repository}`, requested, url: url + path, ref };
83
+ }
84
+
85
+ async function source(requested, cwd) {
86
+ const remote = remoteSource(requested);
87
+ if (remote) return remote;
88
+ const locator = resolve(cwd, requested);
89
+ let root;
90
+ try {
91
+ root = await realpath(locator);
92
+ if (!(await stat(root)).isDirectory()) throw new Error('Not a directory');
93
+ } catch (cause) {
94
+ throw new WorkflowError('packages', `Cannot read local package ${locator}`, { cause });
95
+ }
96
+ return { kind: 'local', id: `local:${root}`, requested, root, locator };
97
+ }
98
+
99
+ async function directories(root, paths, create = false) {
100
+ for (const path of [root, ...paths]) {
101
+ if (create) {
102
+ try { await mkdir(path, { mode: 0o700 }); } catch (error) { if (error.code !== 'EEXIST') throw error; }
103
+ }
104
+ let info;
105
+ try { info = await (path === root ? stat : lstat)(path); } catch (error) {
106
+ if (!create && error.code === 'ENOENT') return false;
107
+ throw error;
108
+ }
109
+ if (!info.isDirectory() || info.isSymbolicLink()) throw problem(`Unsafe package directory ${path}. Expected a real directory, not a symlink`);
110
+ }
111
+ return true;
112
+ }
113
+
114
+ async function regularFile(path) {
115
+ const info = await lstat(path);
116
+ if (!info.isFile() || info.isSymbolicLink()) throw problem(`Expected a regular file at ${path}`);
117
+ }
118
+
119
+ async function manifest(root, expected) {
120
+ try {
121
+ const data = JSON.parse(await readFile(join(root, 'package.json'), 'utf8'));
122
+ if (!object(data) || !packageName(data.name)) throw new Error('Invalid package name');
123
+ if (expected && data.name !== expected) throw new Error(`Package name changed or mismatched. Expected ${expected}, found ${data.name}. Remove and re-add to change names`);
124
+ if (!object(data.he) || !Object.hasOwn(data.he, 'workflows') || !object(data.he.workflows)
125
+ || Object.keys(data.he.workflows).length === 0) throw new Error('Expected a nonempty he.workflows object');
126
+ const canonical = await realpath(root);
127
+ const workflows = [];
128
+ for (const [name, entry] of Object.entries(data.he.workflows)) {
129
+ if (!simpleName(name)) throw new Error(`Invalid workflow name ${JSON.stringify(name)}`);
130
+ if (typeof entry !== 'string' || !entry || /[\\\0]/.test(entry) || /^(?:[a-zA-Z]:|\/)/.test(entry)
131
+ || entry.split('/').includes('..')) throw new Error(`Unsafe workflow entry ${JSON.stringify(entry)}`);
132
+ const path = resolve(root, entry);
133
+ if (!inside(root, path) || !inside(canonical, await realpath(path)) || !(await stat(path)).isFile()) {
134
+ throw new Error(`Workflow entry must be a file inside its package. Found ${JSON.stringify(entry)}`);
135
+ }
136
+ workflows.push({ name, path });
137
+ }
138
+ return { name: data.name, workflows };
139
+ } catch (cause) {
140
+ throw new WorkflowError('packages', `Cannot read workflow manifest in ${root}`, { cause });
141
+ }
142
+ }
143
+
144
+ async function command(binary, args, cwd) {
145
+ return new Promise((accept, reject) => {
146
+ const child = spawn(binary, args, {
147
+ cwd, env: { ...process.env, GIT_TERMINAL_PROMPT: '0' }, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true,
148
+ });
149
+ let stdout = '';
150
+ let stderr = '';
151
+ child.stdout.setEncoding('utf8');
152
+ child.stderr.setEncoding('utf8');
153
+ child.stdout.on('data', chunk => { stdout = (stdout + chunk).slice(-65_536); });
154
+ child.stderr.on('data', chunk => { stderr = (stderr + chunk).slice(-65_536); });
155
+ child.once('error', cause => reject(new WorkflowError('packages', `Cannot execute ${binary}`, { cause })));
156
+ child.once('close', (code, signal) => {
157
+ if (code === 0) accept(stdout.trim());
158
+ else reject(problem(`${binary} failed with ${signal ? `signal ${signal}` : `code ${code}`}\n${stderr || stdout}`));
159
+ });
160
+ });
161
+ }
162
+
163
+ export function packageStore({ directory, cwd }) {
164
+ const home = resolve(directory);
165
+ const storage = join(home, 'packages');
166
+ const generations = join(storage, 'installed');
167
+ const registryPath = join(storage, 'registry.json');
168
+ const lockPath = join(storage, 'mutation.lock');
169
+ const parents = [storage];
170
+ const generationPath = record => join(generations, record.generation);
171
+ const rootPath = record => record.source.kind === 'local' ? record.source.root
172
+ : join(generationPath(record), record.source.kind === 'npm' ? `node_modules/${record.source.name}` : 'checkout');
173
+ const view = record => ({ source: record.source.requested, name: record.name, root: rootPath(record) });
174
+
175
+ async function registry() {
176
+ let raw = null;
177
+ try {
178
+ if (await directories(home, parents)) {
179
+ try {
180
+ await regularFile(registryPath);
181
+ raw = await readFile(registryPath, 'utf8');
182
+ } catch (error) { if (error.code !== 'ENOENT') throw error; }
183
+ }
184
+ if (raw === null) return { raw, records: Object.create(null) };
185
+ const data = JSON.parse(raw);
186
+ if (!object(data) || data.version !== 1 || !object(data.records)) throw new Error('Unsupported registry shape or version');
187
+ const names = new Set();
188
+ for (const [id, record] of Object.entries(data.records)) {
189
+ if (!object(record) || !object(record.source) || !packageName(record.name)) throw new Error('Invalid installed record');
190
+ const s = record.source;
191
+ if (s.kind === 'local') {
192
+ if (typeof s.requested !== 'string' || !s.requested || !absolutePath(s.root) || !absolutePath(s.locator)
193
+ || s.id !== `local:${s.root}` || Object.hasOwn(record, 'generation')) throw new Error('Invalid local record');
194
+ } else {
195
+ const parsed = remoteSource(s.requested);
196
+ if (!parsed || Object.keys(parsed).length !== Object.keys(s).length
197
+ || !Object.entries(parsed).every(([key, value]) => s[key] === value)
198
+ || typeof record.generation !== 'string' || !uuid.test(record.generation)
199
+ || (s.kind === 'npm' && s.name !== record.name)) throw new Error('Invalid managed record');
200
+ }
201
+ if (id !== s.id || names.has(record.name)) throw new Error('Duplicate package name or invalid source identity');
202
+ names.add(record.name);
203
+ }
204
+ return { raw, records: data.records };
205
+ } catch (cause) {
206
+ throw new WorkflowError('packages', `Cannot read package registry ${registryPath}. Repair the registry before changing packages`, { cause });
207
+ }
208
+ }
209
+
210
+ async function publish(records) {
211
+ await directories(home, parents);
212
+ const temporary = join(storage, `registry-${randomUUID()}.tmp`);
213
+ try {
214
+ await writeFile(temporary, `${JSON.stringify({ version: 1, records }, null, 2)}\n`, { flag: 'wx', mode: 0o600 });
215
+ await rename(temporary, registryPath);
216
+ } catch (error) {
217
+ await rm(temporary, { force: true }).catch(() => {});
218
+ throw error;
219
+ }
220
+ }
221
+
222
+ async function mutate(action) {
223
+ await directories(home, parents, true);
224
+ let handle;
225
+ try { handle = await open(lockPath, 'wx', 0o600); } catch (error) {
226
+ if (error.code !== 'EEXIST') throw error;
227
+ throw problem(`Package mutation lock exists at ${lockPath}. Another add/remove may be running. If its owner stopped, inspect the lock and remove it manually only after all installers have stopped`);
228
+ }
229
+ const owned = await handle.stat();
230
+ try {
231
+ await handle.writeFile(JSON.stringify({ pid: process.pid, nonce: randomUUID() }));
232
+ const { records } = await registry();
233
+ return await action(records);
234
+ } finally {
235
+ await handle.close();
236
+ const current = await lstat(lockPath);
237
+ if (!current.isFile() || current.ino !== owned.ino || current.dev !== owned.dev) throw problem(`Package lock ownership changed at ${lockPath}`);
238
+ await unlink(lockPath);
239
+ }
240
+ }
241
+
242
+ async function ownedGeneration(record) {
243
+ if (!await directories(home, [...parents, generations, generationPath(record)])) return null;
244
+ const marker = join(generationPath(record), '.he-owned.json');
245
+ try {
246
+ await regularFile(marker);
247
+ const data = JSON.parse(await readFile(marker, 'utf8'));
248
+ if (data.version !== 1 || data.id !== record.source.id || data.generation !== record.generation) throw new Error('Ownership marker does not match');
249
+ } catch (cause) {
250
+ throw new WorkflowError('packages', `Refusing to delete unowned installation ${generationPath(record)}`, { cause });
251
+ }
252
+ return generationPath(record);
253
+ }
254
+
255
+ async function discard(record) {
256
+ const path = await ownedGeneration(record);
257
+ if (path !== null) await rm(path, { recursive: true });
258
+ }
259
+
260
+ async function packageManifest(record, expected) {
261
+ if (record.source.kind !== 'local') {
262
+ const path = await ownedGeneration(record);
263
+ if (path === null) throw problem(`Missing installation for ${record.source.requested}. Re-add the package or remove its registration`);
264
+ if (!inside(await realpath(path), await realpath(rootPath(record)))) throw problem('Installed package root escapes its generation');
265
+ }
266
+ return manifest(rootPath(record), expected);
267
+ }
268
+
269
+ async function add(requested) {
270
+ const s = await source(requested, cwd);
271
+ return mutate(async records => {
272
+ const previous = records[s.id];
273
+ if (previous && previous.source.kind !== 'local') await ownedGeneration(previous);
274
+ const record = s.kind === 'local' ? { source: s, name: '' }
275
+ : { source: s, name: '', generation: randomUUID() };
276
+ if (s.kind !== 'local') {
277
+ await directories(home, [...parents, generations], true);
278
+ await mkdir(generationPath(record), { mode: 0o700 });
279
+ await writeFile(join(generationPath(record), '.he-owned.json'), JSON.stringify({ version: 1, id: s.id, generation: record.generation }), { flag: 'wx' });
280
+ }
281
+ try {
282
+ const flags = ['--legacy-peer-deps', '--ignore-scripts=false', '--no-audit', '--no-fund'];
283
+ if (s.kind === 'npm') {
284
+ const path = generationPath(record);
285
+ await writeFile(join(path, 'package.json'), '{"private":true}');
286
+ await command('npm', ['install', '--prefix', path, ...flags, `${s.name}@${s.selector}`], path);
287
+ } else if (s.kind === 'git') {
288
+ const root = rootPath(record);
289
+ await command('git', ['clone', '--no-checkout', '--', s.url, root], generationPath(record));
290
+ let commit;
291
+ if (s.ref === null) commit = await command('git', ['rev-parse', '--verify', 'HEAD^{commit}'], root);
292
+ else {
293
+ try { commit = await command('git', ['rev-parse', '--verify', '--end-of-options', `${s.ref}^{commit}`], root); }
294
+ catch { commit = await command('git', ['rev-parse', '--verify', '--end-of-options', `refs/remotes/origin/${s.ref.replace(/^refs\/heads\//, '')}^{commit}`], root); }
295
+ }
296
+ await command('git', ['checkout', '--detach', commit, '--'], root);
297
+ await command('npm', ['install', '--omit=dev', ...flags], root);
298
+ }
299
+ const data = await packageManifest(record, previous?.name ?? (s.kind === 'npm' ? s.name : undefined));
300
+ record.name = data.name;
301
+ for (const [id, other] of Object.entries(records)) {
302
+ if (id !== s.id && other.name === record.name) throw problem(`Package ${record.name} is already registered from ${other.source.requested}. Remove it before switching sources`);
303
+ }
304
+ records[s.id] = record;
305
+ await publish(records);
306
+ } catch (error) {
307
+ if (s.kind !== 'local') {
308
+ try { await discard(record); } catch (cleanup) { error.message += `\nCandidate cleanup refused. ${cleanup.message}`; }
309
+ }
310
+ throw error;
311
+ }
312
+ if (previous && previous.source.kind !== 'local') {
313
+ try { await discard(previous); }
314
+ catch (error) { console.error(`he: Package refreshed, but old installation cleanup failed. ${error.message}`); }
315
+ }
316
+ return view(record);
317
+ });
318
+ }
319
+
320
+ async function remove(requested) {
321
+ const remote = remoteSource(requested);
322
+ const snapshot = await registry();
323
+ if (!Object.keys(snapshot.records).length && !await directories(home, parents)) return false;
324
+ return mutate(async records => {
325
+ const locator = resolve(cwd, requested);
326
+ let record = Object.values(records).find(item => item.source.kind === 'local'
327
+ && (item.source.locator === locator || item.source.root === locator));
328
+ if (remote) record = records[remote.id];
329
+ else if (!record) {
330
+ try { record = records[`local:${await realpath(locator)}`]; }
331
+ catch (error) { if (error.code !== 'ENOENT') throw error; }
332
+ }
333
+ if (!record) return false;
334
+ if (record.source.kind !== 'local') await ownedGeneration(record);
335
+ delete records[record.source.id];
336
+ await publish(records);
337
+ if (record.source.kind !== 'local') await discard(record);
338
+ return true;
339
+ });
340
+ }
341
+
342
+ async function catalog() {
343
+ let snapshot = await registry();
344
+ let packages;
345
+ for (let attempt = 0; ; attempt++) {
346
+ try {
347
+ packages = [];
348
+ for (const record of Object.values(snapshot.records)) packages.push({ record, data: await packageManifest(record, record.name) });
349
+ break;
350
+ } catch (error) {
351
+ let current;
352
+ try { current = await registry(); } catch { throw error; }
353
+ if (attempt !== 0 || current.raw === snapshot.raw) throw error;
354
+ snapshot = current;
355
+ }
356
+ }
357
+ const standalone = new Map((await discover(home)).map(workflow => [workflow.name, workflow]));
358
+ const qualified = new Map();
359
+ const short = new Map();
360
+ for (const { record, data } of packages) {
361
+ for (const workflow of data.workflows) {
362
+ const name = `${record.name}:${workflow.name}`;
363
+ if (standalone.has(name)) throw problem(`Workflow naming conflict for ${name}. Rename the standalone file to use this package`);
364
+ qualified.set(name, { ...workflow, name });
365
+ const candidates = short.get(workflow.name) ?? [];
366
+ candidates.push(name);
367
+ short.set(workflow.name, candidates);
368
+ }
369
+ }
370
+ const workflows = [...standalone.values(), ...qualified.values()].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
371
+ return {
372
+ workflows,
373
+ select(name) {
374
+ if (qualified.has(name)) return qualified.get(name);
375
+ if (standalone.has(name)) return standalone.get(name);
376
+ const candidates = (short.get(name) ?? []).sort();
377
+ if (candidates.length === 1) return qualified.get(candidates[0]);
378
+ if (candidates.length > 1) throw problem(`Workflow ${JSON.stringify(name)} is ambiguous. Choose ${candidates.join(', ')}`);
379
+ throw new WorkflowError('discovery', `Workflow ${JSON.stringify(name)} not found`);
380
+ },
381
+ };
382
+ }
383
+
384
+ return {
385
+ add, remove, catalog,
386
+ async list() { return Object.values((await registry()).records).map(view).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0); },
387
+ };
388
+ }
package/src/run.mjs ADDED
@@ -0,0 +1,141 @@
1
+ import { createActor } from 'xstate';
2
+ import { loadLogic } from './load.mjs';
3
+ import { report, WorkflowError } from './errors.mjs';
4
+
5
+ /** @typedef {'loading'|'actor startup'|'execution'} RunStage */
6
+ /** @typedef {{kind: 'live', stage: RunStage} |
7
+ * {kind: 'terminal', result: 0|1} | {kind: 'cancelling', code: 130|143}} RunState */
8
+
9
+ /** Own one foreground root and retain signal handlers through natural post-terminal drainage.
10
+ * @param {import('./workflows.mjs').Workflow} workflow */
11
+ export async function run(workflow) {
12
+ /** @type {RunState} */
13
+ let state = { kind: 'live', stage: 'loading' };
14
+ /** @type {ReturnType<typeof createActor> | undefined} */
15
+ let root;
16
+ /** @type {{unsubscribe(): void} | undefined} */
17
+ let subscription;
18
+ let keepalive = setInterval(() => {}, 2 ** 30);
19
+ let deadline;
20
+ const stdin = process.stdin;
21
+ const initialRaw = stdin.isRaw;
22
+ let release;
23
+ const outcome = new Promise(resolve => { release = resolve; });
24
+
25
+ function releaseWait() {
26
+ const owned = keepalive;
27
+ keepalive = undefined;
28
+ clearInterval(owned);
29
+ release();
30
+ }
31
+
32
+ function releaseSubscription() {
33
+ const owned = subscription;
34
+ subscription = undefined;
35
+ try { owned?.unsubscribe(); } catch {}
36
+ }
37
+
38
+ function stopRoot() {
39
+ const owned = root;
40
+ root = undefined;
41
+ try { owned?.stop(); } catch {}
42
+ }
43
+
44
+ function restoreTerminal(forced = false) {
45
+ if (stdin.isTTY && typeof stdin.setRawMode === 'function'
46
+ && (forced || state.kind === 'cancelling') && stdin.isRaw !== initialRaw) {
47
+ try { stdin.setRawMode(initialRaw ?? false); } catch { /* The terminal may already be closed. */ }
48
+ }
49
+ }
50
+
51
+ function forceExit() {
52
+ restoreTerminal(true);
53
+ process.exit(state.kind === 'cancelling' ? state.code : 130);
54
+ }
55
+
56
+ const interrupt = () => cancel(130);
57
+ const terminate = () => cancel(143);
58
+
59
+ /** @param {130|143} code */
60
+ function cancel(code) {
61
+ if (state.kind === 'cancelling') {
62
+ if (code === 130) return forceExit();
63
+ if (state.code === 143) return;
64
+ }
65
+ state = { kind: 'cancelling', code };
66
+ process.exitCode = code;
67
+ releaseWait();
68
+ clearTimeout(deadline);
69
+ deadline = setTimeout(forceExit, code === 143 ? 1_000 : 5_000);
70
+ // SIGTERM reserves a full second for log drainage, even without other I/O.
71
+ if (code === 130) deadline.unref();
72
+ stopRoot();
73
+ queueMicrotask(releaseSubscription);
74
+ restoreTerminal();
75
+ }
76
+
77
+ /** @param {0|1} result @param {unknown} [failure] */
78
+ function finish(result, failure) {
79
+ if (state.kind !== 'live') return;
80
+ const stage = state.stage;
81
+ state = { kind: 'terminal', result };
82
+ process.exitCode = result;
83
+ releaseWait();
84
+ releaseSubscription();
85
+ if (result === 1) {
86
+ report(failure instanceof WorkflowError ? failure
87
+ : new WorkflowError(stage, 'Workflow failed', { workflow, cause: failure }));
88
+ stopRoot();
89
+ }
90
+ }
91
+
92
+ function complete() {
93
+ if (state.kind !== 'live') return;
94
+ try {
95
+ const snapshot = root.getSnapshot();
96
+ if (snapshot.status === 'done') finish(0);
97
+ else if (snapshot.status === 'error') finish(1, snapshot.error);
98
+ else finish(1, new WorkflowError('execution', 'Root actor stopped without completing', { workflow }));
99
+ } catch (cause) {
100
+ finish(1, cause);
101
+ }
102
+ }
103
+
104
+ function cleanup() {
105
+ process.removeListener('SIGINT', interrupt);
106
+ process.removeListener('SIGTERM', terminate);
107
+ clearTimeout(deadline);
108
+ clearInterval(keepalive);
109
+ releaseSubscription();
110
+ restoreTerminal();
111
+ }
112
+
113
+ process.on('SIGINT', interrupt);
114
+ process.on('SIGTERM', terminate);
115
+ process.once('exit', cleanup);
116
+
117
+ void (async () => {
118
+ const logic = await loadLogic(workflow);
119
+ if (state.kind !== 'live') return;
120
+ state = { kind: 'live', stage: 'actor startup' };
121
+ const actor = createActor(logic);
122
+ root = actor;
123
+ const observation = actor.subscribe({ error: error => finish(1, error), complete });
124
+ if (state.kind === 'live') subscription = observation;
125
+ else {
126
+ stopRoot();
127
+ try { observation.unsubscribe(); } catch {}
128
+ return;
129
+ }
130
+ actor.start();
131
+ if (state.kind !== 'live') return;
132
+ state = { kind: 'live', stage: 'execution' };
133
+ const status = actor.getSnapshot().status;
134
+ if (status !== 'active') complete();
135
+ })().catch(error => {
136
+ finish(1, error);
137
+ if (state.kind === 'cancelling') stopRoot();
138
+ });
139
+
140
+ await outcome;
141
+ }
@@ -0,0 +1,22 @@
1
+ import { readdir } from 'node:fs/promises';
2
+ import { join, resolve } from 'node:path';
3
+ import { WorkflowError } from './errors.mjs';
4
+
5
+ /** @typedef {{name: string, path: string}} Workflow */
6
+
7
+ /** @param {string} directory @returns {Promise<Workflow[]>} */
8
+ export async function discover(directory) {
9
+ const absolute = resolve(directory);
10
+ let entries;
11
+ try {
12
+ entries = await readdir(absolute, { withFileTypes: true });
13
+ } catch (cause) {
14
+ if (cause.code === 'ENOENT') return [];
15
+ throw new WorkflowError('discovery', `Cannot read workflow directory ${absolute}`, { cause });
16
+ }
17
+ return entries
18
+ .filter(entry => entry.isFile() && !entry.name.startsWith('.') && !/[\\/]/.test(entry.name)
19
+ && entry.name.endsWith('.ts') && !entry.name.endsWith('.d.ts'))
20
+ .map(entry => ({ name: entry.name.slice(0, -3), path: join(absolute, entry.name) }))
21
+ .sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
22
+ }