@orkestrel/scaffold 0.0.124 → 0.0.126

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 (53) hide show
  1. package/dist/agents/skills/orkestrel-publish/scripts/steps.js +523 -0
  2. package/dist/agents/skills/orkestrel-publish/scripts/wave.js +70 -11
  3. package/dist/bin/main.js +51 -18
  4. package/dist/bin/main.js.map +1 -1
  5. package/dist/host/agents/orchestration.md +7 -2
  6. package/dist/host/agents/platforms/windows.md +9 -1
  7. package/dist/host/agents/skills/orkestrel-dispatch/SKILL.md +1 -1
  8. package/dist/host/agents/skills/orkestrel-falsify/SKILL.md +1 -1
  9. package/dist/host/agents/skills/orkestrel-falsify/references/brief.md +1 -0
  10. package/dist/host/agents/skills/orkestrel-harden/references/methods.md +32 -4
  11. package/dist/host/agents/skills/orkestrel-journey/SKILL.md +18 -19
  12. package/dist/host/agents/skills/orkestrel-parallel/SKILL.md +1 -0
  13. package/dist/host/agents/skills/orkestrel-parallel/references/codex.md +2 -1
  14. package/dist/host/agents/skills/orkestrel-parallel/references/t3.md +5 -1
  15. package/dist/host/agents/skills/orkestrel-publish/SKILL.md +1 -0
  16. package/dist/host/agents/skills/orkestrel-publish/references/release.md +2 -2
  17. package/dist/host/agents/skills/orkestrel-publish/references/wave.md +23 -6
  18. package/dist/host/agents/skills/orkestrel-publish/scripts/steps.ts +654 -0
  19. package/dist/host/agents/skills/orkestrel-publish/scripts/wave.ts +79 -14
  20. package/dist/host/claude/agents/orkestrel.md +28 -28
  21. package/dist/host/claude/rules/patterns.md +1 -1
  22. package/dist/host/claude/rules/portability.md +2 -0
  23. package/dist/host/claude/rules/quality.md +6 -1
  24. package/dist/host/claude/rules/tests.md +6 -1
  25. package/dist/host/claude/rules/workspace.md +8 -3
  26. package/dist/host/guides/agent.md +575 -346
  27. package/dist/host/guides/brief.md +52 -48
  28. package/dist/host/guides/browser.md +2 -2
  29. package/dist/host/guides/interpret.md +531 -155
  30. package/dist/host/guides/mcp.md +183 -61
  31. package/dist/host/guides/ndjson.md +4 -3
  32. package/dist/host/guides/ollama.md +125 -68
  33. package/dist/host/guides/program.md +117 -39
  34. package/dist/host/guides/qualifier.md +110 -59
  35. package/dist/host/guides/rater.md +85 -32
  36. package/dist/host/guides/scaffold.md +49 -22
  37. package/dist/host/guides/study.md +596 -489
  38. package/dist/host/guides/toolbox.md +159 -80
  39. package/dist/host/guides/workflow.md +44 -25
  40. package/dist/host/manifest.json +41 -35
  41. package/dist/src/core/index.cjs +12 -10
  42. package/dist/src/core/index.cjs.map +1 -1
  43. package/dist/src/core/index.d.cts +3 -1
  44. package/dist/src/core/index.d.ts +3 -1
  45. package/dist/src/core/index.js +12 -10
  46. package/dist/src/core/index.js.map +1 -1
  47. package/dist/src/server/index.cjs +23 -11
  48. package/dist/src/server/index.cjs.map +1 -1
  49. package/dist/src/server/index.d.cts +10 -6
  50. package/dist/src/server/index.d.ts +10 -6
  51. package/dist/src/server/index.js +23 -11
  52. package/dist/src/server/index.js.map +1 -1
  53. package/package.json +7 -7
@@ -0,0 +1,654 @@
1
+ // Derive a release chain from the manifest's `prepublishOnly` script and run it, so a release names
2
+ // every step it leaves out. Run from the package root:
3
+ // node .agents/skills/orkestrel-publish/scripts/steps.ts --journal DIR [--omit NAME=REASON ...] [--no-ci] [--dry-run] [--json]
4
+ // The script splits `prepublishOnly` on `&&` and reads each segment as `npm test`, `npm run NAME`, or
5
+ // `npm run NAME -- ARGS...`; any other segment or shell operator is refused by name, because the
6
+ // script can then state no complete step list. The plan opens with `ci` (`npm ci --ignore-scripts`)
7
+ // and `clean` (`npm run clean`), then the derived steps in script order, each named from its script
8
+ // with every character `chain.ts` refuses in a step name replaced by `-`. A name that repeats, or the
9
+ // name `omitted`, whose journal would overwrite `omitted.txt`, is refused, case-folded because a
10
+ // journal file name folds on Windows. `--omit`, which repeats, leaves one derived step out for a
11
+ // non-empty one-line reason; `ci` and `clean` are not omittable through it. On Windows `ci` is left
12
+ // out when a `.node`, `.dll`, or `.exe` file under `node_modules` refuses a write-mode open at chain start,
13
+ // and `--no-ci` leaves `ci` out with the reason `--no-ci`. The script writes the plan to
14
+ // `DIR/plan.json` and every omitted step to `DIR/omitted.txt`, prints each omitted step on its own
15
+ // line, and runs the sibling `chain.ts` with stdio inherited and `npm_config_prefer_online=true`
16
+ // merged into its environment. `--dry-run` prints the steps and omissions, writes nothing, and runs
17
+ // nothing; `--json`, which `--dry-run` must accompany, prints them as one JSON value.
18
+ // Exit with the chain's code: 0 when every step exited 0, the failing step's code when one did not,
19
+ // 2 when a step or the chain cannot start. Exit 2 when the journal cannot be written, 64 on usage,
20
+ // and 65 when no complete step list can be derived or an `--omit` names no derived step. A step
21
+ // exiting 65 reads alike with that refusal.
22
+ import { spawnSync } from 'node:child_process'
23
+ import {
24
+ closeSync,
25
+ existsSync,
26
+ mkdirSync,
27
+ openSync,
28
+ readdirSync,
29
+ readFileSync,
30
+ realpathSync,
31
+ writeFileSync,
32
+ } from 'node:fs'
33
+ import { dirname, extname, join } from 'node:path'
34
+ import { fileURLToPath } from 'node:url'
35
+
36
+ /** Lists the flags that take a value. */
37
+ export const VALUE_FLAGS: readonly string[] = ['--journal', '--omit']
38
+
39
+ /** Lists every flag the script reads, value flags and switches alike. */
40
+ export const FLAGS: readonly string[] = [...VALUE_FLAGS, '--no-ci', '--dry-run', '--json']
41
+
42
+ /** Holds the usage line printed when a call names no journal or gives a malformed flag. */
43
+ export const USAGE =
44
+ 'usage: steps.ts --journal DIR [--omit NAME=REASON ...] [--no-ci] [--dry-run] [--json]'
45
+
46
+ /** Matches a step name `chain.ts` accepts. */
47
+ export const STEP_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/u
48
+
49
+ /** Matches every character `chain.ts` refuses in a step name. */
50
+ export const REFUSED_CHARACTER = /[^A-Za-z0-9._-]/gu
51
+
52
+ /**
53
+ * Matches one token of a segment.
54
+ *
55
+ * @remarks
56
+ * The characters admitted carry no meaning to `sh` or `cmd.exe`, so a token reaches npm unchanged and
57
+ * every shell operator, quote, and expansion falls outside the admitted language.
58
+ */
59
+ export const SEGMENT_TOKEN = /^[A-Za-z0-9@+=:,./_-]+$/u
60
+
61
+ /** Matches a native file a process can hold loaded, by its extension. */
62
+ export const NATIVE_FILE = /\.(?:node|dll|exe)$/iu
63
+
64
+ /** Names the file extension of the running script, which the sibling chain shares. */
65
+ export const EXTENSION = extname(fileURLToPath(import.meta.url))
66
+
67
+ /** Holds the path of the sibling `chain` script of the `orkestrel-dispatch` skill. */
68
+ export const CHAIN = fileURLToPath(
69
+ new URL(`../../orkestrel-dispatch/scripts/chain${EXTENSION}`, import.meta.url),
70
+ )
71
+
72
+ /** Lists the steps every plan opens with, per the layer preparation `wave.md` fixes. */
73
+ export const OPENERS: readonly Segment[] = [
74
+ { name: 'ci', args: ['ci', '--ignore-scripts'] },
75
+ { name: 'clean', args: ['run', 'clean'] },
76
+ ]
77
+
78
+ /** Lists the case-folded names no derived step can take. */
79
+ export const RESERVED: readonly string[] = ['ci', 'clean', 'omitted']
80
+
81
+ /** Describes one step before npm is resolved: its name and npm's arguments. */
82
+ export interface Segment {
83
+ readonly name: string
84
+ readonly args: readonly string[]
85
+ }
86
+
87
+ /** Describes what a manifest yields: its derived steps, or every problem that stopped them. */
88
+ export interface Derivation {
89
+ readonly segments: readonly Segment[]
90
+ readonly problems: readonly string[]
91
+ }
92
+
93
+ /** Describes one step left out of a plan and why. */
94
+ export interface Omission {
95
+ readonly name: string
96
+ readonly reason: string
97
+ }
98
+
99
+ /** Describes a native file that refused a write-mode open and the code it refused with. */
100
+ export interface HeldFile {
101
+ readonly path: string
102
+ readonly code: string
103
+ }
104
+
105
+ /** Describes how to start npm without the `shell` spawn option. */
106
+ export interface NpmCommand {
107
+ readonly file: string
108
+ readonly prefix: readonly string[]
109
+ }
110
+
111
+ /** Describes one entry of the plan `chain.ts` reads. */
112
+ export interface Step {
113
+ readonly name: string
114
+ readonly command: string
115
+ readonly args: readonly string[]
116
+ }
117
+
118
+ /** Describes a function that throws when a file refuses a write-mode open. */
119
+ export type OpenFunction = (path: string) => void
120
+
121
+ /**
122
+ * Checks whether a value is a non-null, non-array object.
123
+ *
124
+ * @param value - The value to inspect.
125
+ * @returns True if the value is an object other than null or an array; false otherwise.
126
+ */
127
+ export function isRecord(value: unknown): value is Record<string, unknown> {
128
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
129
+ }
130
+
131
+ /**
132
+ * Quotes an untrusted text for a diagnostic, JSON-encoded and cut to a bounded length.
133
+ *
134
+ * @param text - The text to quote.
135
+ * @returns The JSON string literal of the text, ending in an ellipsis inside the quotes when cut.
136
+ */
137
+ export function quote(text: string): string {
138
+ return JSON.stringify(text.length > 80 ? `${text.slice(0, 80)}…` : text)
139
+ }
140
+
141
+ /**
142
+ * Parses a JSON text without throwing.
143
+ *
144
+ * @param text - The text to parse.
145
+ * @returns The parsed value, or undefined when the text is not JSON.
146
+ */
147
+ export function parseJson(text: string): unknown {
148
+ try {
149
+ return JSON.parse(text)
150
+ } catch {
151
+ return undefined
152
+ }
153
+ }
154
+
155
+ /**
156
+ * Reads the value after each occurrence of a flag.
157
+ *
158
+ * @param argv - The arguments after the script path.
159
+ * @param name - The flag, such as `--omit`.
160
+ * @returns One member per occurrence, undefined where the flag is last or a value opens with `--`.
161
+ */
162
+ export function readValues(
163
+ argv: readonly string[],
164
+ name: string,
165
+ ): ReadonlyArray<string | undefined> {
166
+ return argv.flatMap((argument, index) => {
167
+ if (argument !== name) return []
168
+ const value = argv[index + 1]
169
+ return [value === undefined || value.startsWith('--') ? undefined : value]
170
+ })
171
+ }
172
+
173
+ /**
174
+ * Names the value flags a caller gave with no value.
175
+ *
176
+ * @param argv - The arguments after the script path.
177
+ * @param names - The flags that take a value.
178
+ * @returns Each named flag with an occurrence that is last or followed by another flag.
179
+ */
180
+ export function readMissingFlags(
181
+ argv: readonly string[],
182
+ names: readonly string[],
183
+ ): readonly string[] {
184
+ return names.filter((name) => readValues(argv, name).includes(undefined))
185
+ }
186
+
187
+ /**
188
+ * Names the flags a caller gave that the script does not read.
189
+ *
190
+ * @remarks
191
+ * A `--flag=value` argument is unknown, because the script reads no such form. The script passes no
192
+ * command on, so a bare `--` is unknown too, and the scan stops there and reads nothing after it.
193
+ *
194
+ * @param argv - The arguments after the script path.
195
+ * @param flags - Every flag the script reads, value flags and switches alike.
196
+ * @returns Each argument that opens with `--` and is not a read flag, in argument order.
197
+ */
198
+ export function readUnknownFlags(
199
+ argv: readonly string[],
200
+ flags: readonly string[],
201
+ ): readonly string[] {
202
+ const end = argv.indexOf('--')
203
+ return (end === -1 ? argv : argv.slice(0, end + 1)).filter(
204
+ (argument) => argument.startsWith('--') && !flags.includes(argument),
205
+ )
206
+ }
207
+
208
+ /**
209
+ * Names the arguments no flag reads as its value.
210
+ *
211
+ * @param argv - The arguments after the script path.
212
+ * @param names - The flags that take a value.
213
+ * @returns Each argument that neither opens with `--` nor follows a value flag.
214
+ */
215
+ export function readStrayArguments(
216
+ argv: readonly string[],
217
+ names: readonly string[],
218
+ ): readonly string[] {
219
+ return argv.filter(
220
+ (argument, index) => !argument.startsWith('--') && !names.includes(argv[index - 1] ?? ''),
221
+ )
222
+ }
223
+
224
+ /**
225
+ * Parses one `--omit` value.
226
+ *
227
+ * @param text - The value, such as `test-distribution=the registry refuses this host`.
228
+ * @returns The omission, or undefined when the name or the reason is empty, or the reason spans lines
229
+ * and so cannot stay one line of `omitted.txt`.
230
+ */
231
+ export function parseOmission(text: string): Omission | undefined {
232
+ const at = text.indexOf('=')
233
+ const reason = text.slice(at + 1).trim()
234
+ if (at <= 0 || reason === '' || /[\r\n]/u.test(reason)) return undefined
235
+ return { name: text.slice(0, at), reason }
236
+ }
237
+
238
+ /**
239
+ * Reads the first usage problem in the arguments.
240
+ *
241
+ * @param argv - The arguments after the script path.
242
+ * @returns The refusal to print, or undefined when the arguments are well formed.
243
+ */
244
+ export function readUsageProblem(argv: readonly string[]): string | undefined {
245
+ const unknown = readUnknownFlags(argv, FLAGS)
246
+ if (unknown.length > 0) return `${unknown.join(', ')} is not a flag this script reads; ${USAGE}`
247
+ const missing = readMissingFlags(argv, VALUE_FLAGS)
248
+ if (missing.length > 0) return `${missing.join(', ')} given with no value; ${USAGE}`
249
+ const strays = readStrayArguments(argv, VALUE_FLAGS)
250
+ if (strays.length > 0) return `${strays.map(quote).join(', ')} is not read by a flag; ${USAGE}`
251
+ if (readValues(argv, '--journal').length === 0) return USAGE
252
+ if (argv.includes('--json') && !argv.includes('--dry-run')) {
253
+ return `--json reads only with --dry-run, because the chain prints to standard output; ${USAGE}`
254
+ }
255
+ const values = readValues(argv, '--omit').flatMap((value) => (value === undefined ? [] : [value]))
256
+ const malformed = values.filter((value) => parseOmission(value) === undefined)
257
+ if (malformed.length > 0) {
258
+ return `--omit takes NAME=REASON with a non-empty one-line reason, given ${malformed.map(quote).join(', ')}`
259
+ }
260
+ const names = values.map((value) => value.slice(0, value.indexOf('=')))
261
+ const repeated = [...new Set(names.filter((name, index) => names.indexOf(name) !== index))]
262
+ if (repeated.length > 0) {
263
+ return `--omit names a step more than once: ${repeated.map(quote).join(', ')}`
264
+ }
265
+ return undefined
266
+ }
267
+
268
+ /**
269
+ * Reads the given `--omit` values as omissions.
270
+ *
271
+ * @param argv - Arguments that `readUsageProblem` found no problem in.
272
+ * @returns One omission per occurrence, in argument order.
273
+ */
274
+ export function readOmissions(argv: readonly string[]): readonly Omission[] {
275
+ return readValues(argv, '--omit').flatMap((value) => {
276
+ const omission = value === undefined ? undefined : parseOmission(value)
277
+ return omission === undefined ? [] : [omission]
278
+ })
279
+ }
280
+
281
+ /**
282
+ * Parses one segment of `prepublishOnly`.
283
+ *
284
+ * @remarks
285
+ * The admitted language is `npm test`, `npm run NAME`, and `npm run NAME -- ARGS...` with at least one
286
+ * argument, in tokens that spaces or tabs separate. A line break is refused as a shell command
287
+ * separator, and every token outside `SEGMENT_TOKEN` is refused as a shell operator.
288
+ *
289
+ * @param text - The segment's text.
290
+ * @returns The named step, or undefined when the segment falls outside the admitted language.
291
+ */
292
+ export function parseSegment(text: string): Segment | undefined {
293
+ const tokens = text.trim().split(/[ \t]+/u)
294
+ if (!tokens.every((token) => SEGMENT_TOKEN.test(token))) return undefined
295
+ const [npm, verb, script, separator, ...rest] = tokens
296
+ if (npm !== 'npm') return undefined
297
+ if (verb === 'test') return tokens.length === 2 ? { name: 'test', args: ['test'] } : undefined
298
+ if (verb !== 'run' || script === undefined) return undefined
299
+ const name = script.replace(REFUSED_CHARACTER, '-')
300
+ if (separator === undefined) return { name, args: ['run', script] }
301
+ return separator === '--' && rest.length > 0
302
+ ? { name, args: ['run', script, '--', ...rest] }
303
+ : undefined
304
+ }
305
+
306
+ /**
307
+ * Derives the named steps of a `prepublishOnly` script.
308
+ *
309
+ * @param script - The script's text.
310
+ * @returns The steps in script order, or every problem in the script: a segment outside the admitted
311
+ * language, a name `chain.ts` would refuse, and a name that repeats or is reserved.
312
+ */
313
+ export function deriveSegments(script: string): Derivation {
314
+ const parts = script.split('&&').map((text) => ({ text, segment: parseSegment(text) }))
315
+ const segments = parts.flatMap((part) => (part.segment === undefined ? [] : [part.segment]))
316
+ const names = [...RESERVED, ...segments.map((segment) => segment.name.toLowerCase())]
317
+ const repeated = [...new Set(names.filter((name, index) => names.indexOf(name) !== index))]
318
+ const problems = [
319
+ ...parts
320
+ .filter((part) => part.segment === undefined)
321
+ .map(
322
+ (part) =>
323
+ `prepublishOnly segment ${quote(part.text.trim())} is not \`npm test\`, \`npm run NAME\`, or \`npm run NAME -- ARGS...\`, so no complete step list can be derived`,
324
+ ),
325
+ ...segments
326
+ .filter((segment) => !STEP_NAME.test(segment.name))
327
+ .map(
328
+ (segment) =>
329
+ `prepublishOnly script ${quote(segment.args[1] ?? segment.name)} gives the step name ${quote(segment.name)}, which does not open with a letter or digit`,
330
+ ),
331
+ ...repeated.map(
332
+ (name) =>
333
+ `the step name ${quote(name)} repeats or is reserved: ${RESERVED.join(', ')} and every derived name are one use each`,
334
+ ),
335
+ ]
336
+ return problems.length > 0 ? { segments: [], problems } : { segments, problems: [] }
337
+ }
338
+
339
+ /**
340
+ * Derives the named steps of the manifest in a directory.
341
+ *
342
+ * @param root - The package root.
343
+ * @returns The derived steps, or the problems, a missing manifest and a missing script among them.
344
+ */
345
+ export function readDerivation(root: string): Derivation {
346
+ const path = join(root, 'package.json')
347
+ if (!existsSync(path)) return { segments: [], problems: [`no package.json in ${quote(root)}`] }
348
+ const manifest = parseJson(readFileSync(path, 'utf8'))
349
+ const scripts = isRecord(manifest) ? manifest.scripts : undefined
350
+ const script = isRecord(scripts) ? scripts.prepublishOnly : undefined
351
+ return typeof script === 'string'
352
+ ? deriveSegments(script)
353
+ : { segments: [], problems: ['package.json holds no string at scripts.prepublishOnly'] }
354
+ }
355
+
356
+ /**
357
+ * Lists the problems of omissions against the steps a manifest derives.
358
+ *
359
+ * @param omissions - The omissions the caller gave.
360
+ * @param segments - The derived steps; `ci` and `clean` are not among them.
361
+ * @returns One refusal per omission that matches no derived step, listing the valid names.
362
+ */
363
+ export function readOmissionProblems(
364
+ omissions: readonly Omission[],
365
+ segments: readonly Segment[],
366
+ ): readonly string[] {
367
+ const valid = segments.map((segment) => segment.name)
368
+ return omissions
369
+ .filter((omission) => !valid.includes(omission.name))
370
+ .map(
371
+ (omission) =>
372
+ `--omit ${quote(omission.name)} matches no derived step; the valid names are ${valid.join(', ')}`,
373
+ )
374
+ }
375
+
376
+ /**
377
+ * Opens a file in write mode and closes it, writing no byte.
378
+ *
379
+ * @param path - The file to open.
380
+ * @throws A system error when the file refuses the open.
381
+ */
382
+ export function openWritable(path: string): void {
383
+ closeSync(openSync(path, 'r+'))
384
+ }
385
+
386
+ /**
387
+ * Lists the native files under a tree.
388
+ *
389
+ * @param root - The directory to walk, where a missing directory holds no file.
390
+ * @returns The path of each regular file with a `.node`, `.dll`, or `.exe` extension; a link is not followed.
391
+ */
392
+ export function collectNative(root: string): readonly string[] {
393
+ if (!existsSync(root)) return []
394
+ return readdirSync(root, { recursive: true, withFileTypes: true })
395
+ .filter((entry) => entry.isFile() && NATIVE_FILE.test(entry.name))
396
+ .map((entry) => join(entry.parentPath, entry.name))
397
+ }
398
+
399
+ /**
400
+ * Lists the native files under a tree that refuse a write-mode open at this moment.
401
+ *
402
+ * @remarks
403
+ * The check branches on `process.platform` because the behavior is platform-defined. Windows refuses
404
+ * to delete a loaded image, so `npm ci` stops at `EPERM` on a held file and leaves a partial tree, and
405
+ * a loaded image refuses a write-mode open with `EBUSY`. A host outside Windows unlinks a mapped
406
+ * file, so the check does not run there. Any refused open counts as held, whatever its code, and the
407
+ * omission names the code. A process whose working directory sits under the tree also stops `npm ci`,
408
+ * and this read cannot see it.
409
+ *
410
+ * @param root - The directory to walk.
411
+ * @param open - The opener. Default: `openWritable`.
412
+ * @param platform - The host platform. Default: `process.platform`.
413
+ * @returns Each file that refused, with the code it refused with; empty off `win32`.
414
+ */
415
+ export function readHolders(
416
+ root: string,
417
+ open: OpenFunction = openWritable,
418
+ platform: string = process.platform,
419
+ ): readonly HeldFile[] {
420
+ if (platform !== 'win32') return []
421
+ return collectNative(root).flatMap((path) => {
422
+ try {
423
+ open(path)
424
+ return []
425
+ } catch (error) {
426
+ const code = isRecord(error) && typeof error.code === 'string' ? error.code : 'unknown'
427
+ return [{ path, code }]
428
+ }
429
+ })
430
+ }
431
+
432
+ /**
433
+ * Reads whether this chain leaves `ci` out.
434
+ *
435
+ * @remarks
436
+ * `--no-ci` wins and reads no holder.
437
+ *
438
+ * @param disabled - If `true`, the caller gave `--no-ci`; if `false`, the holders decide.
439
+ * @param read - The holder reading, taken when `disabled` is false.
440
+ * @returns The omission of `ci` as a one-member list, or an empty list when `ci` runs.
441
+ */
442
+ export function readCiOmissions(
443
+ disabled: boolean,
444
+ read: () => readonly HeldFile[],
445
+ ): readonly Omission[] {
446
+ if (disabled) return [{ name: 'ci', reason: '--no-ci' }]
447
+ const held = read()
448
+ if (held.length === 0) return []
449
+ const paths = held.map((file) => `${file.path} (${file.code})`).join(', ')
450
+ return [{ name: 'ci', reason: `held by a running process: ${paths}` }]
451
+ }
452
+
453
+ /**
454
+ * Lists the steps a chain runs.
455
+ *
456
+ * @param segments - The derived steps.
457
+ * @param omitted - The steps to leave out.
458
+ * @returns The openers then the derived steps, in order, without the omitted ones.
459
+ */
460
+ export function selectSegments(
461
+ segments: readonly Segment[],
462
+ omitted: readonly Omission[],
463
+ ): readonly Segment[] {
464
+ const names = new Set(omitted.map((omission) => omission.name))
465
+ return [...OPENERS, ...segments].filter((segment) => !names.has(segment.name))
466
+ }
467
+
468
+ /**
469
+ * Resolves how a plan starts npm.
470
+ *
471
+ * @remarks
472
+ * The `npm-cli.js` entry beside the Node binary starts with no shell on every host. Where it is
473
+ * absent, Windows starts the `npm` shim, a `.cmd` file, through the interpreter it needs, because
474
+ * `chain.ts` spawns with no shell; `cmd.exe` is platform-defined, and every token that reaches it
475
+ * matched `SEGMENT_TOKEN`. Another host starts `npm` by name.
476
+ *
477
+ * @param binary - The Node binary. Default: `process.execPath`.
478
+ * @param platform - The host platform. Default: `process.platform`.
479
+ * @returns The file to spawn and the arguments that precede npm's own.
480
+ */
481
+ export function resolveNpm(
482
+ binary: string = process.execPath,
483
+ platform: string = process.platform,
484
+ ): NpmCommand {
485
+ const cli = join(dirname(binary), 'node_modules', 'npm', 'bin', 'npm-cli.js')
486
+ if (existsSync(cli)) return { file: binary, prefix: [cli] }
487
+ return platform === 'win32'
488
+ ? { file: 'cmd.exe', prefix: ['/d', '/s', '/c', 'npm'] }
489
+ : { file: 'npm', prefix: [] }
490
+ }
491
+
492
+ /**
493
+ * Builds the plan `chain.ts` reads.
494
+ *
495
+ * @param segments - The steps to run, in order.
496
+ * @param npm - How the plan starts npm.
497
+ * @returns One plan entry per step.
498
+ */
499
+ export function buildPlan(segments: readonly Segment[], npm: NpmCommand): readonly Step[] {
500
+ return segments.map((segment) => ({
501
+ name: segment.name,
502
+ command: npm.file,
503
+ args: [...npm.prefix, ...segment.args],
504
+ }))
505
+ }
506
+
507
+ /**
508
+ * Formats the line printed and written for one omitted step.
509
+ *
510
+ * @param omission - The omitted step.
511
+ * @returns `omitted NAME: REASON`.
512
+ */
513
+ export function formatOmission(omission: Omission): string {
514
+ return `omitted ${omission.name}: ${omission.reason}`
515
+ }
516
+
517
+ /**
518
+ * Formats the line a dry run prints for one step.
519
+ *
520
+ * @param segment - The step.
521
+ * @returns `step NAME: npm ARGS`.
522
+ */
523
+ export function formatSegment(segment: Segment): string {
524
+ return `step ${segment.name}: npm ${segment.args.join(' ')}`
525
+ }
526
+
527
+ /**
528
+ * Writes the plan and the omissions into the journal directory.
529
+ *
530
+ * @param journal - The journal directory, created when absent.
531
+ * @param plan - The plan entries.
532
+ * @param omitted - The omitted steps; an empty list writes an empty file, so no earlier run's list
533
+ * stays behind.
534
+ * @returns The reason the write failed, or undefined when it succeeded.
535
+ */
536
+ export function writeJournal(
537
+ journal: string,
538
+ plan: readonly Step[],
539
+ omitted: readonly Omission[],
540
+ ): string | undefined {
541
+ try {
542
+ mkdirSync(journal, { recursive: true })
543
+ writeFileSync(join(journal, 'plan.json'), `${JSON.stringify(plan, null, '\t')}\n`)
544
+ writeFileSync(
545
+ join(journal, 'omitted.txt'),
546
+ omitted.map((omission) => `${formatOmission(omission)}\n`).join(''),
547
+ )
548
+ return undefined
549
+ } catch (error) {
550
+ return error instanceof Error ? error.message : String(error)
551
+ }
552
+ }
553
+
554
+ /**
555
+ * Lays added variables over an inherited environment by case-folded name.
556
+ *
557
+ * @remarks
558
+ * A Windows environment block folds names by case, so an inherited `NPM_CONFIG_PREFER_ONLINE` would
559
+ * outrank an added `npm_config_prefer_online`; every inherited variable whose lower-cased name an
560
+ * added variable claims is dropped first.
561
+ *
562
+ * @param inherited - The environment the child would inherit.
563
+ * @param added - The variables to set.
564
+ * @returns The inherited variables no added name claims, followed by the added variables.
565
+ */
566
+ export function mergeEnv(
567
+ inherited: Readonly<Record<string, string | undefined>>,
568
+ added: Readonly<Record<string, string>>,
569
+ ): Record<string, string | undefined> {
570
+ const claimed = new Set(Object.keys(added).map((name) => name.toLowerCase()))
571
+ return {
572
+ ...Object.fromEntries(
573
+ Object.entries(inherited).filter(([name]) => !claimed.has(name.toLowerCase())),
574
+ ),
575
+ ...added,
576
+ }
577
+ }
578
+
579
+ /**
580
+ * Runs the sibling chain over the plan in a journal directory, its stdio inherited.
581
+ *
582
+ * @param journal - The journal directory that holds `plan.json`.
583
+ * @returns The chain's exit code, or 2 when it cannot start or a signal ended it.
584
+ */
585
+ export function runChain(journal: string): number {
586
+ const result = spawnSync(
587
+ process.execPath,
588
+ [CHAIN, '--plan', join(journal, 'plan.json'), '--journal', journal],
589
+ {
590
+ stdio: 'inherit',
591
+ env: mergeEnv(process.env, { npm_config_prefer_online: 'true' }),
592
+ windowsHide: true,
593
+ shell: false,
594
+ },
595
+ )
596
+ if (result.status !== null) return result.status
597
+ console.error(
598
+ `steps: the chain did not finish: ${result.error?.message ?? String(result.signal)}`,
599
+ )
600
+ return 2
601
+ }
602
+
603
+ /**
604
+ * Runs the script on its arguments.
605
+ *
606
+ * @param argv - The arguments after the script path.
607
+ * @returns The exit code: the chain's on a run, 0 on a dry run, 2 when the journal cannot be written
608
+ * or the chain cannot start, 64 on usage, 65 when no complete step list can be derived or an `--omit`
609
+ * names no derived step.
610
+ */
611
+ export function main(argv: readonly string[]): number {
612
+ const usage = readUsageProblem(argv)
613
+ const [journal] = readValues(argv, '--journal')
614
+ if (usage !== undefined || journal === undefined) {
615
+ console.error(`steps: ${usage ?? USAGE}`)
616
+ return 64
617
+ }
618
+ const derivation = readDerivation(process.cwd())
619
+ const omissions = readOmissions(argv)
620
+ const problems = [
621
+ ...derivation.problems,
622
+ ...(derivation.problems.length > 0 ? [] : readOmissionProblems(omissions, derivation.segments)),
623
+ ]
624
+ if (problems.length > 0) {
625
+ console.error(`steps: ${problems.join('; ')}`)
626
+ return 65
627
+ }
628
+ const omitted = [
629
+ ...readCiOmissions(argv.includes('--no-ci'), () => readHolders('node_modules')),
630
+ ...omissions,
631
+ ]
632
+ const selected = selectSegments(derivation.segments, omitted)
633
+ const plan = buildPlan(selected, resolveNpm())
634
+ if (argv.includes('--json')) {
635
+ console.log(JSON.stringify({ steps: plan, omitted }))
636
+ return 0
637
+ }
638
+ const lines = omitted.map((omission) => formatOmission(omission))
639
+ if (argv.includes('--dry-run')) {
640
+ console.log([...selected.map((segment) => formatSegment(segment)), ...lines].join('\n'))
641
+ return 0
642
+ }
643
+ const failure = writeJournal(journal, plan, omitted)
644
+ if (failure !== undefined) {
645
+ console.error(`steps: cannot write the journal ${quote(journal)}: ${failure}`)
646
+ return 2
647
+ }
648
+ for (const line of lines) console.log(line)
649
+ return runChain(journal)
650
+ }
651
+
652
+ if (process.argv[1] !== undefined && realpathSync(process.argv[1]) === import.meta.filename) {
653
+ process.exitCode = main(process.argv.slice(2))
654
+ }