@orkestrel/scaffold 0.0.124 → 0.0.125

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 (46) 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 +5 -5
  4. package/dist/bin/main.js.map +1 -1
  5. package/dist/host/agents/orchestration.md +5 -1
  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/references/brief.md +1 -0
  9. package/dist/host/agents/skills/orkestrel-harden/references/methods.md +30 -2
  10. package/dist/host/agents/skills/orkestrel-parallel/SKILL.md +1 -0
  11. package/dist/host/agents/skills/orkestrel-parallel/references/t3.md +5 -1
  12. package/dist/host/agents/skills/orkestrel-publish/SKILL.md +1 -0
  13. package/dist/host/agents/skills/orkestrel-publish/references/release.md +2 -2
  14. package/dist/host/agents/skills/orkestrel-publish/references/wave.md +23 -6
  15. package/dist/host/agents/skills/orkestrel-publish/scripts/steps.ts +654 -0
  16. package/dist/host/agents/skills/orkestrel-publish/scripts/wave.ts +79 -14
  17. package/dist/host/claude/agents/orkestrel.md +21 -21
  18. package/dist/host/claude/rules/patterns.md +1 -1
  19. package/dist/host/claude/rules/portability.md +2 -0
  20. package/dist/host/claude/rules/quality.md +3 -1
  21. package/dist/host/claude/rules/tests.md +3 -1
  22. package/dist/host/guides/agent.md +349 -244
  23. package/dist/host/guides/brief.md +52 -48
  24. package/dist/host/guides/browser.md +2 -2
  25. package/dist/host/guides/interpret.md +531 -155
  26. package/dist/host/guides/mcp.md +183 -61
  27. package/dist/host/guides/ollama.md +123 -66
  28. package/dist/host/guides/program.md +117 -39
  29. package/dist/host/guides/qualifier.md +110 -59
  30. package/dist/host/guides/rater.md +85 -32
  31. package/dist/host/guides/scaffold.md +13 -5
  32. package/dist/host/guides/study.md +580 -483
  33. package/dist/host/guides/toolbox.md +159 -80
  34. package/dist/host/guides/workflow.md +44 -25
  35. package/dist/host/manifest.json +36 -30
  36. package/dist/src/core/index.cjs +4 -4
  37. package/dist/src/core/index.cjs.map +1 -1
  38. package/dist/src/core/index.js +4 -4
  39. package/dist/src/core/index.js.map +1 -1
  40. package/dist/src/server/index.cjs +23 -11
  41. package/dist/src/server/index.cjs.map +1 -1
  42. package/dist/src/server/index.d.cts +10 -6
  43. package/dist/src/server/index.d.ts +10 -6
  44. package/dist/src/server/index.js +23 -11
  45. package/dist/src/server/index.js.map +1 -1
  46. package/package.json +4 -4
@@ -0,0 +1,523 @@
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 { closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, realpathSync, writeFileSync, } from 'node:fs';
24
+ import { dirname, extname, join } from 'node:path';
25
+ import { fileURLToPath } from 'node:url';
26
+ /** Lists the flags that take a value. */
27
+ export const VALUE_FLAGS = ['--journal', '--omit'];
28
+ /** Lists every flag the script reads, value flags and switches alike. */
29
+ export const FLAGS = [...VALUE_FLAGS, '--no-ci', '--dry-run', '--json'];
30
+ /** Holds the usage line printed when a call names no journal or gives a malformed flag. */
31
+ export const USAGE = 'usage: steps.ts --journal DIR [--omit NAME=REASON ...] [--no-ci] [--dry-run] [--json]';
32
+ /** Matches a step name `chain.ts` accepts. */
33
+ export const STEP_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/u;
34
+ /** Matches every character `chain.ts` refuses in a step name. */
35
+ export const REFUSED_CHARACTER = /[^A-Za-z0-9._-]/gu;
36
+ /**
37
+ * Matches one token of a segment.
38
+ *
39
+ * @remarks
40
+ * The characters admitted carry no meaning to `sh` or `cmd.exe`, so a token reaches npm unchanged and
41
+ * every shell operator, quote, and expansion falls outside the admitted language.
42
+ */
43
+ export const SEGMENT_TOKEN = /^[A-Za-z0-9@+=:,./_-]+$/u;
44
+ /** Matches a native file a process can hold loaded, by its extension. */
45
+ export const NATIVE_FILE = /\.(?:node|dll|exe)$/iu;
46
+ /** Names the file extension of the running script, which the sibling chain shares. */
47
+ export const EXTENSION = extname(fileURLToPath(import.meta.url));
48
+ /** Holds the path of the sibling `chain` script of the `orkestrel-dispatch` skill. */
49
+ export const CHAIN = fileURLToPath(new URL(`../../orkestrel-dispatch/scripts/chain${EXTENSION}`, import.meta.url));
50
+ /** Lists the steps every plan opens with, per the layer preparation `wave.md` fixes. */
51
+ export const OPENERS = [
52
+ { name: 'ci', args: ['ci', '--ignore-scripts'] },
53
+ { name: 'clean', args: ['run', 'clean'] },
54
+ ];
55
+ /** Lists the case-folded names no derived step can take. */
56
+ export const RESERVED = ['ci', 'clean', 'omitted'];
57
+ /**
58
+ * Checks whether a value is a non-null, non-array object.
59
+ *
60
+ * @param value - The value to inspect.
61
+ * @returns True if the value is an object other than null or an array; false otherwise.
62
+ */
63
+ export function isRecord(value) {
64
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
65
+ }
66
+ /**
67
+ * Quotes an untrusted text for a diagnostic, JSON-encoded and cut to a bounded length.
68
+ *
69
+ * @param text - The text to quote.
70
+ * @returns The JSON string literal of the text, ending in an ellipsis inside the quotes when cut.
71
+ */
72
+ export function quote(text) {
73
+ return JSON.stringify(text.length > 80 ? `${text.slice(0, 80)}…` : text);
74
+ }
75
+ /**
76
+ * Parses a JSON text without throwing.
77
+ *
78
+ * @param text - The text to parse.
79
+ * @returns The parsed value, or undefined when the text is not JSON.
80
+ */
81
+ export function parseJson(text) {
82
+ try {
83
+ return JSON.parse(text);
84
+ }
85
+ catch {
86
+ return undefined;
87
+ }
88
+ }
89
+ /**
90
+ * Reads the value after each occurrence of a flag.
91
+ *
92
+ * @param argv - The arguments after the script path.
93
+ * @param name - The flag, such as `--omit`.
94
+ * @returns One member per occurrence, undefined where the flag is last or a value opens with `--`.
95
+ */
96
+ export function readValues(argv, name) {
97
+ return argv.flatMap((argument, index) => {
98
+ if (argument !== name)
99
+ return [];
100
+ const value = argv[index + 1];
101
+ return [value === undefined || value.startsWith('--') ? undefined : value];
102
+ });
103
+ }
104
+ /**
105
+ * Names the value flags a caller gave with no value.
106
+ *
107
+ * @param argv - The arguments after the script path.
108
+ * @param names - The flags that take a value.
109
+ * @returns Each named flag with an occurrence that is last or followed by another flag.
110
+ */
111
+ export function readMissingFlags(argv, names) {
112
+ return names.filter((name) => readValues(argv, name).includes(undefined));
113
+ }
114
+ /**
115
+ * Names the flags a caller gave that the script does not read.
116
+ *
117
+ * @remarks
118
+ * A `--flag=value` argument is unknown, because the script reads no such form. The script passes no
119
+ * command on, so a bare `--` is unknown too, and the scan stops there and reads nothing after it.
120
+ *
121
+ * @param argv - The arguments after the script path.
122
+ * @param flags - Every flag the script reads, value flags and switches alike.
123
+ * @returns Each argument that opens with `--` and is not a read flag, in argument order.
124
+ */
125
+ export function readUnknownFlags(argv, flags) {
126
+ const end = argv.indexOf('--');
127
+ return (end === -1 ? argv : argv.slice(0, end + 1)).filter((argument) => argument.startsWith('--') && !flags.includes(argument));
128
+ }
129
+ /**
130
+ * Names the arguments no flag reads as its value.
131
+ *
132
+ * @param argv - The arguments after the script path.
133
+ * @param names - The flags that take a value.
134
+ * @returns Each argument that neither opens with `--` nor follows a value flag.
135
+ */
136
+ export function readStrayArguments(argv, names) {
137
+ return argv.filter((argument, index) => !argument.startsWith('--') && !names.includes(argv[index - 1] ?? ''));
138
+ }
139
+ /**
140
+ * Parses one `--omit` value.
141
+ *
142
+ * @param text - The value, such as `test-distribution=the registry refuses this host`.
143
+ * @returns The omission, or undefined when the name or the reason is empty, or the reason spans lines
144
+ * and so cannot stay one line of `omitted.txt`.
145
+ */
146
+ export function parseOmission(text) {
147
+ const at = text.indexOf('=');
148
+ const reason = text.slice(at + 1).trim();
149
+ if (at <= 0 || reason === '' || /[\r\n]/u.test(reason))
150
+ return undefined;
151
+ return { name: text.slice(0, at), reason };
152
+ }
153
+ /**
154
+ * Reads the first usage problem in the arguments.
155
+ *
156
+ * @param argv - The arguments after the script path.
157
+ * @returns The refusal to print, or undefined when the arguments are well formed.
158
+ */
159
+ export function readUsageProblem(argv) {
160
+ const unknown = readUnknownFlags(argv, FLAGS);
161
+ if (unknown.length > 0)
162
+ return `${unknown.join(', ')} is not a flag this script reads; ${USAGE}`;
163
+ const missing = readMissingFlags(argv, VALUE_FLAGS);
164
+ if (missing.length > 0)
165
+ return `${missing.join(', ')} given with no value; ${USAGE}`;
166
+ const strays = readStrayArguments(argv, VALUE_FLAGS);
167
+ if (strays.length > 0)
168
+ return `${strays.map(quote).join(', ')} is not read by a flag; ${USAGE}`;
169
+ if (readValues(argv, '--journal').length === 0)
170
+ return USAGE;
171
+ if (argv.includes('--json') && !argv.includes('--dry-run')) {
172
+ return `--json reads only with --dry-run, because the chain prints to standard output; ${USAGE}`;
173
+ }
174
+ const values = readValues(argv, '--omit').flatMap((value) => (value === undefined ? [] : [value]));
175
+ const malformed = values.filter((value) => parseOmission(value) === undefined);
176
+ if (malformed.length > 0) {
177
+ return `--omit takes NAME=REASON with a non-empty one-line reason, given ${malformed.map(quote).join(', ')}`;
178
+ }
179
+ const names = values.map((value) => value.slice(0, value.indexOf('=')));
180
+ const repeated = [...new Set(names.filter((name, index) => names.indexOf(name) !== index))];
181
+ if (repeated.length > 0) {
182
+ return `--omit names a step more than once: ${repeated.map(quote).join(', ')}`;
183
+ }
184
+ return undefined;
185
+ }
186
+ /**
187
+ * Reads the given `--omit` values as omissions.
188
+ *
189
+ * @param argv - Arguments that `readUsageProblem` found no problem in.
190
+ * @returns One omission per occurrence, in argument order.
191
+ */
192
+ export function readOmissions(argv) {
193
+ return readValues(argv, '--omit').flatMap((value) => {
194
+ const omission = value === undefined ? undefined : parseOmission(value);
195
+ return omission === undefined ? [] : [omission];
196
+ });
197
+ }
198
+ /**
199
+ * Parses one segment of `prepublishOnly`.
200
+ *
201
+ * @remarks
202
+ * The admitted language is `npm test`, `npm run NAME`, and `npm run NAME -- ARGS...` with at least one
203
+ * argument, in tokens that spaces or tabs separate. A line break is refused as a shell command
204
+ * separator, and every token outside `SEGMENT_TOKEN` is refused as a shell operator.
205
+ *
206
+ * @param text - The segment's text.
207
+ * @returns The named step, or undefined when the segment falls outside the admitted language.
208
+ */
209
+ export function parseSegment(text) {
210
+ const tokens = text.trim().split(/[ \t]+/u);
211
+ if (!tokens.every((token) => SEGMENT_TOKEN.test(token)))
212
+ return undefined;
213
+ const [npm, verb, script, separator, ...rest] = tokens;
214
+ if (npm !== 'npm')
215
+ return undefined;
216
+ if (verb === 'test')
217
+ return tokens.length === 2 ? { name: 'test', args: ['test'] } : undefined;
218
+ if (verb !== 'run' || script === undefined)
219
+ return undefined;
220
+ const name = script.replace(REFUSED_CHARACTER, '-');
221
+ if (separator === undefined)
222
+ return { name, args: ['run', script] };
223
+ return separator === '--' && rest.length > 0
224
+ ? { name, args: ['run', script, '--', ...rest] }
225
+ : undefined;
226
+ }
227
+ /**
228
+ * Derives the named steps of a `prepublishOnly` script.
229
+ *
230
+ * @param script - The script's text.
231
+ * @returns The steps in script order, or every problem in the script: a segment outside the admitted
232
+ * language, a name `chain.ts` would refuse, and a name that repeats or is reserved.
233
+ */
234
+ export function deriveSegments(script) {
235
+ const parts = script.split('&&').map((text) => ({ text, segment: parseSegment(text) }));
236
+ const segments = parts.flatMap((part) => (part.segment === undefined ? [] : [part.segment]));
237
+ const names = [...RESERVED, ...segments.map((segment) => segment.name.toLowerCase())];
238
+ const repeated = [...new Set(names.filter((name, index) => names.indexOf(name) !== index))];
239
+ const problems = [
240
+ ...parts
241
+ .filter((part) => part.segment === undefined)
242
+ .map((part) => `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`),
243
+ ...segments
244
+ .filter((segment) => !STEP_NAME.test(segment.name))
245
+ .map((segment) => `prepublishOnly script ${quote(segment.args[1] ?? segment.name)} gives the step name ${quote(segment.name)}, which does not open with a letter or digit`),
246
+ ...repeated.map((name) => `the step name ${quote(name)} repeats or is reserved: ${RESERVED.join(', ')} and every derived name are one use each`),
247
+ ];
248
+ return problems.length > 0 ? { segments: [], problems } : { segments, problems: [] };
249
+ }
250
+ /**
251
+ * Derives the named steps of the manifest in a directory.
252
+ *
253
+ * @param root - The package root.
254
+ * @returns The derived steps, or the problems, a missing manifest and a missing script among them.
255
+ */
256
+ export function readDerivation(root) {
257
+ const path = join(root, 'package.json');
258
+ if (!existsSync(path))
259
+ return { segments: [], problems: [`no package.json in ${quote(root)}`] };
260
+ const manifest = parseJson(readFileSync(path, 'utf8'));
261
+ const scripts = isRecord(manifest) ? manifest.scripts : undefined;
262
+ const script = isRecord(scripts) ? scripts.prepublishOnly : undefined;
263
+ return typeof script === 'string'
264
+ ? deriveSegments(script)
265
+ : { segments: [], problems: ['package.json holds no string at scripts.prepublishOnly'] };
266
+ }
267
+ /**
268
+ * Lists the problems of omissions against the steps a manifest derives.
269
+ *
270
+ * @param omissions - The omissions the caller gave.
271
+ * @param segments - The derived steps; `ci` and `clean` are not among them.
272
+ * @returns One refusal per omission that matches no derived step, listing the valid names.
273
+ */
274
+ export function readOmissionProblems(omissions, segments) {
275
+ const valid = segments.map((segment) => segment.name);
276
+ return omissions
277
+ .filter((omission) => !valid.includes(omission.name))
278
+ .map((omission) => `--omit ${quote(omission.name)} matches no derived step; the valid names are ${valid.join(', ')}`);
279
+ }
280
+ /**
281
+ * Opens a file in write mode and closes it, writing no byte.
282
+ *
283
+ * @param path - The file to open.
284
+ * @throws A system error when the file refuses the open.
285
+ */
286
+ export function openWritable(path) {
287
+ closeSync(openSync(path, 'r+'));
288
+ }
289
+ /**
290
+ * Lists the native files under a tree.
291
+ *
292
+ * @param root - The directory to walk, where a missing directory holds no file.
293
+ * @returns The path of each regular file with a `.node`, `.dll`, or `.exe` extension; a link is not followed.
294
+ */
295
+ export function collectNative(root) {
296
+ if (!existsSync(root))
297
+ return [];
298
+ return readdirSync(root, { recursive: true, withFileTypes: true })
299
+ .filter((entry) => entry.isFile() && NATIVE_FILE.test(entry.name))
300
+ .map((entry) => join(entry.parentPath, entry.name));
301
+ }
302
+ /**
303
+ * Lists the native files under a tree that refuse a write-mode open at this moment.
304
+ *
305
+ * @remarks
306
+ * The check branches on `process.platform` because the behavior is platform-defined. Windows refuses
307
+ * to delete a loaded image, so `npm ci` stops at `EPERM` on a held file and leaves a partial tree, and
308
+ * a loaded image refuses a write-mode open with `EBUSY`. A host outside Windows unlinks a mapped
309
+ * file, so the check does not run there. Any refused open counts as held, whatever its code, and the
310
+ * omission names the code. A process whose working directory sits under the tree also stops `npm ci`,
311
+ * and this read cannot see it.
312
+ *
313
+ * @param root - The directory to walk.
314
+ * @param open - The opener. Default: `openWritable`.
315
+ * @param platform - The host platform. Default: `process.platform`.
316
+ * @returns Each file that refused, with the code it refused with; empty off `win32`.
317
+ */
318
+ export function readHolders(root, open = openWritable, platform = process.platform) {
319
+ if (platform !== 'win32')
320
+ return [];
321
+ return collectNative(root).flatMap((path) => {
322
+ try {
323
+ open(path);
324
+ return [];
325
+ }
326
+ catch (error) {
327
+ const code = isRecord(error) && typeof error.code === 'string' ? error.code : 'unknown';
328
+ return [{ path, code }];
329
+ }
330
+ });
331
+ }
332
+ /**
333
+ * Reads whether this chain leaves `ci` out.
334
+ *
335
+ * @remarks
336
+ * `--no-ci` wins and reads no holder.
337
+ *
338
+ * @param disabled - If `true`, the caller gave `--no-ci`; if `false`, the holders decide.
339
+ * @param read - The holder reading, taken when `disabled` is false.
340
+ * @returns The omission of `ci` as a one-member list, or an empty list when `ci` runs.
341
+ */
342
+ export function readCiOmissions(disabled, read) {
343
+ if (disabled)
344
+ return [{ name: 'ci', reason: '--no-ci' }];
345
+ const held = read();
346
+ if (held.length === 0)
347
+ return [];
348
+ const paths = held.map((file) => `${file.path} (${file.code})`).join(', ');
349
+ return [{ name: 'ci', reason: `held by a running process: ${paths}` }];
350
+ }
351
+ /**
352
+ * Lists the steps a chain runs.
353
+ *
354
+ * @param segments - The derived steps.
355
+ * @param omitted - The steps to leave out.
356
+ * @returns The openers then the derived steps, in order, without the omitted ones.
357
+ */
358
+ export function selectSegments(segments, omitted) {
359
+ const names = new Set(omitted.map((omission) => omission.name));
360
+ return [...OPENERS, ...segments].filter((segment) => !names.has(segment.name));
361
+ }
362
+ /**
363
+ * Resolves how a plan starts npm.
364
+ *
365
+ * @remarks
366
+ * The `npm-cli.js` entry beside the Node binary starts with no shell on every host. Where it is
367
+ * absent, Windows starts the `npm` shim, a `.cmd` file, through the interpreter it needs, because
368
+ * `chain.ts` spawns with no shell; `cmd.exe` is platform-defined, and every token that reaches it
369
+ * matched `SEGMENT_TOKEN`. Another host starts `npm` by name.
370
+ *
371
+ * @param binary - The Node binary. Default: `process.execPath`.
372
+ * @param platform - The host platform. Default: `process.platform`.
373
+ * @returns The file to spawn and the arguments that precede npm's own.
374
+ */
375
+ export function resolveNpm(binary = process.execPath, platform = process.platform) {
376
+ const cli = join(dirname(binary), 'node_modules', 'npm', 'bin', 'npm-cli.js');
377
+ if (existsSync(cli))
378
+ return { file: binary, prefix: [cli] };
379
+ return platform === 'win32'
380
+ ? { file: 'cmd.exe', prefix: ['/d', '/s', '/c', 'npm'] }
381
+ : { file: 'npm', prefix: [] };
382
+ }
383
+ /**
384
+ * Builds the plan `chain.ts` reads.
385
+ *
386
+ * @param segments - The steps to run, in order.
387
+ * @param npm - How the plan starts npm.
388
+ * @returns One plan entry per step.
389
+ */
390
+ export function buildPlan(segments, npm) {
391
+ return segments.map((segment) => ({
392
+ name: segment.name,
393
+ command: npm.file,
394
+ args: [...npm.prefix, ...segment.args],
395
+ }));
396
+ }
397
+ /**
398
+ * Formats the line printed and written for one omitted step.
399
+ *
400
+ * @param omission - The omitted step.
401
+ * @returns `omitted NAME: REASON`.
402
+ */
403
+ export function formatOmission(omission) {
404
+ return `omitted ${omission.name}: ${omission.reason}`;
405
+ }
406
+ /**
407
+ * Formats the line a dry run prints for one step.
408
+ *
409
+ * @param segment - The step.
410
+ * @returns `step NAME: npm ARGS`.
411
+ */
412
+ export function formatSegment(segment) {
413
+ return `step ${segment.name}: npm ${segment.args.join(' ')}`;
414
+ }
415
+ /**
416
+ * Writes the plan and the omissions into the journal directory.
417
+ *
418
+ * @param journal - The journal directory, created when absent.
419
+ * @param plan - The plan entries.
420
+ * @param omitted - The omitted steps; an empty list writes an empty file, so no earlier run's list
421
+ * stays behind.
422
+ * @returns The reason the write failed, or undefined when it succeeded.
423
+ */
424
+ export function writeJournal(journal, plan, omitted) {
425
+ try {
426
+ mkdirSync(journal, { recursive: true });
427
+ writeFileSync(join(journal, 'plan.json'), `${JSON.stringify(plan, null, '\t')}\n`);
428
+ writeFileSync(join(journal, 'omitted.txt'), omitted.map((omission) => `${formatOmission(omission)}\n`).join(''));
429
+ return undefined;
430
+ }
431
+ catch (error) {
432
+ return error instanceof Error ? error.message : String(error);
433
+ }
434
+ }
435
+ /**
436
+ * Lays added variables over an inherited environment by case-folded name.
437
+ *
438
+ * @remarks
439
+ * A Windows environment block folds names by case, so an inherited `NPM_CONFIG_PREFER_ONLINE` would
440
+ * outrank an added `npm_config_prefer_online`; every inherited variable whose lower-cased name an
441
+ * added variable claims is dropped first.
442
+ *
443
+ * @param inherited - The environment the child would inherit.
444
+ * @param added - The variables to set.
445
+ * @returns The inherited variables no added name claims, followed by the added variables.
446
+ */
447
+ export function mergeEnv(inherited, added) {
448
+ const claimed = new Set(Object.keys(added).map((name) => name.toLowerCase()));
449
+ return {
450
+ ...Object.fromEntries(Object.entries(inherited).filter(([name]) => !claimed.has(name.toLowerCase()))),
451
+ ...added,
452
+ };
453
+ }
454
+ /**
455
+ * Runs the sibling chain over the plan in a journal directory, its stdio inherited.
456
+ *
457
+ * @param journal - The journal directory that holds `plan.json`.
458
+ * @returns The chain's exit code, or 2 when it cannot start or a signal ended it.
459
+ */
460
+ export function runChain(journal) {
461
+ const result = spawnSync(process.execPath, [CHAIN, '--plan', join(journal, 'plan.json'), '--journal', journal], {
462
+ stdio: 'inherit',
463
+ env: mergeEnv(process.env, { npm_config_prefer_online: 'true' }),
464
+ windowsHide: true,
465
+ shell: false,
466
+ });
467
+ if (result.status !== null)
468
+ return result.status;
469
+ console.error(`steps: the chain did not finish: ${result.error?.message ?? String(result.signal)}`);
470
+ return 2;
471
+ }
472
+ /**
473
+ * Runs the script on its arguments.
474
+ *
475
+ * @param argv - The arguments after the script path.
476
+ * @returns The exit code: the chain's on a run, 0 on a dry run, 2 when the journal cannot be written
477
+ * or the chain cannot start, 64 on usage, 65 when no complete step list can be derived or an `--omit`
478
+ * names no derived step.
479
+ */
480
+ export function main(argv) {
481
+ const usage = readUsageProblem(argv);
482
+ const [journal] = readValues(argv, '--journal');
483
+ if (usage !== undefined || journal === undefined) {
484
+ console.error(`steps: ${usage ?? USAGE}`);
485
+ return 64;
486
+ }
487
+ const derivation = readDerivation(process.cwd());
488
+ const omissions = readOmissions(argv);
489
+ const problems = [
490
+ ...derivation.problems,
491
+ ...(derivation.problems.length > 0 ? [] : readOmissionProblems(omissions, derivation.segments)),
492
+ ];
493
+ if (problems.length > 0) {
494
+ console.error(`steps: ${problems.join('; ')}`);
495
+ return 65;
496
+ }
497
+ const omitted = [
498
+ ...readCiOmissions(argv.includes('--no-ci'), () => readHolders('node_modules')),
499
+ ...omissions,
500
+ ];
501
+ const selected = selectSegments(derivation.segments, omitted);
502
+ const plan = buildPlan(selected, resolveNpm());
503
+ if (argv.includes('--json')) {
504
+ console.log(JSON.stringify({ steps: plan, omitted }));
505
+ return 0;
506
+ }
507
+ const lines = omitted.map((omission) => formatOmission(omission));
508
+ if (argv.includes('--dry-run')) {
509
+ console.log([...selected.map((segment) => formatSegment(segment)), ...lines].join('\n'));
510
+ return 0;
511
+ }
512
+ const failure = writeJournal(journal, plan, omitted);
513
+ if (failure !== undefined) {
514
+ console.error(`steps: cannot write the journal ${quote(journal)}: ${failure}`);
515
+ return 2;
516
+ }
517
+ for (const line of lines)
518
+ console.log(line);
519
+ return runChain(journal);
520
+ }
521
+ if (process.argv[1] !== undefined && realpathSync(process.argv[1]) === import.meta.filename) {
522
+ process.exitCode = main(process.argv.slice(2));
523
+ }
@@ -24,8 +24,19 @@ export const RUNTIME_FIELDS = ['dependencies', 'peerDependencies'];
24
24
  export const RANGE_FIELDS = [...RUNTIME_FIELDS, 'devDependencies'];
25
25
  /** Names the agent file that carries the catalog table. */
26
26
  export const CATALOG = '.claude/agents/orkestrel.md';
27
- /** Holds the text an offline overwrite refusal names. */
28
- export const OFFLINE_REFUSAL = "'catalog' does not take --offline";
27
+ /**
28
+ * Lists the texts that name the catalog step an offline overwrite skips.
29
+ *
30
+ * @remarks
31
+ * The executable is the target's installed release, so a checkout's script also reads the wording an
32
+ * earlier release prints.
33
+ */
34
+ export const OFFLINE_NOTES = [
35
+ 'the catalog reads upstream and --offline reads none',
36
+ "'catalog' does not take --offline",
37
+ ];
38
+ /** Lists the codes a host reports when a process holds a file a move or a removal reaches. */
39
+ export const HELD_CODES = ['EBUSY', 'EPERM'];
29
40
  /**
30
41
  * Names the package whose checkout the vendored host is staged from.
31
42
  *
@@ -468,15 +479,15 @@ export function judgePin(result) {
468
479
  * Judges the overwrite command.
469
480
  *
470
481
  * @param result - The overwrite.
471
- * @param offline - If `true`, an exit of 1 whose note names the catalog refusal passes; if `false`,
472
- * the exit alone decides.
482
+ * @param offline - If `true`, an exit of 1 whose note names the skipped catalog step passes; if
483
+ * `false`, the exit alone decides.
473
484
  * @returns The verdict.
474
485
  */
475
486
  export function judgeOverwrite(result, offline) {
476
487
  if (!offline || result.status !== 1)
477
488
  return readVerdict(result);
478
489
  const note = readString(parseJsonLine(result.stdout), 'note');
479
- return note !== undefined && note.includes(OFFLINE_REFUSAL)
490
+ return note !== undefined && OFFLINE_NOTES.some((text) => note.includes(text))
480
491
  ? { exit: 0, note: 'offline overwrite skipped the catalog step by design' }
481
492
  : { exit: 1, note: describeFailure(result) };
482
493
  }
@@ -710,6 +721,17 @@ export function readRegenerationRefusal(runner) {
710
721
  return 'the target is not the root of its work tree';
711
722
  return undefined;
712
723
  }
724
+ /**
725
+ * Extracts the code that names a held file from a thrown value.
726
+ *
727
+ * @param error - The thrown value.
728
+ * @returns The code when {@link HELD_CODES} lists it, else undefined.
729
+ */
730
+ export function extractHeldCode(error) {
731
+ return isRecord(error) && typeof error.code === 'string' && HELD_CODES.includes(error.code)
732
+ ? error.code
733
+ : undefined;
734
+ }
713
735
  /**
714
736
  * Renames a directory, retrying while the host holds it.
715
737
  *
@@ -724,7 +746,7 @@ export function moveModules(source, target, attempt = 0) {
724
746
  renameSync(source, target);
725
747
  }
726
748
  catch (error) {
727
- if (!isRecord(error) || (error.code !== 'EBUSY' && error.code !== 'EPERM') || attempt >= 9)
749
+ if (extractHeldCode(error) === undefined || attempt >= 9)
728
750
  throw error;
729
751
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 100);
730
752
  moveModules(source, target, attempt + 1);
@@ -776,9 +798,14 @@ export function regenerateLock(runner, step, conflict) {
776
798
  .map((name) => `${name}@${readString(readManifest(join(modules, name)), 'version') ?? 'absent'}`)
777
799
  .join(', ')
778
800
  : undefined;
779
- appendStep(runner, step, 'regenerate lock and modules', [result.note, restored, versions === undefined ? undefined : `installed ${versions}`, cleanup]
801
+ appendStep(runner, step, 'regenerate lock and modules', [
802
+ result.note,
803
+ restored,
804
+ versions === undefined ? undefined : `installed ${versions}`,
805
+ cleanup?.note,
806
+ ]
780
807
  .filter((value) => value !== undefined)
781
- .join('; '), cleanup === undefined ? result.exit : 1);
808
+ .join('; '), cleanup?.exit ?? result.exit);
782
809
  if (result.installed !== undefined)
783
810
  appendResult(runner, step, 'npm install (regenerated)', result.installed, result.duration ?? 0, readVerdict(result.installed));
784
811
  if (result.listed !== undefined)
@@ -826,19 +853,51 @@ export function regenerateTree(target, manifest, before) {
826
853
  * @param target - The target directory.
827
854
  * @param moved - The moved previous tree.
828
855
  * @param backup - The saved lock.
829
- * @returns Nothing on success, else the failure with the backup paths kept.
856
+ * @returns Exit 0 and no note on success, else the verdict {@link judgeCleanup} reaches.
830
857
  */
831
858
  export function discardBackup(target, moved, backup) {
832
859
  try {
833
860
  for (const path of [moved, backup, join(target, 'node_modules')])
834
861
  validateWavePath(target, path);
862
+ }
863
+ catch (error) {
864
+ return judgeCleanup(error, false, backup, moved);
865
+ }
866
+ try {
835
867
  removeTree(moved);
836
- return undefined;
868
+ return { exit: 0, note: undefined };
837
869
  }
838
870
  catch (error) {
839
- return `backup cleanup failed: ${String(error)}; proved installation retained; backups: ${backup}; ${moved}`;
871
+ return judgeCleanup(error, true, backup, moved);
840
872
  }
841
873
  }
874
+ /**
875
+ * Judges a cleanup that failed after a proved regeneration.
876
+ *
877
+ * @remarks
878
+ * The proved installation reads nothing from the moved tree, so a file a process holds there stops
879
+ * neither the step nor the visit.
880
+ *
881
+ * @param failure - The thrown value.
882
+ * @param removing - If `true`, the removal threw and a held file's code passes; if `false`, the path
883
+ * validation threw and every value fails.
884
+ * @param backup - The saved lock.
885
+ * @param moved - The moved previous tree.
886
+ * @returns Exit 0 with a note that names the code for a held file, else exit 1; each note names both
887
+ * backup paths.
888
+ */
889
+ export function judgeCleanup(failure, removing, backup, moved) {
890
+ const code = removing ? extractHeldCode(failure) : undefined;
891
+ return code === undefined
892
+ ? {
893
+ exit: 1,
894
+ note: `backup cleanup failed: ${String(failure)}; proved installation retained; backups: ${backup}; ${moved}`,
895
+ }
896
+ : {
897
+ exit: 0,
898
+ note: `proved installation retained; a held file stopped backup cleanup (${code}): ${String(failure)}; backups: ${backup}; ${moved}`,
899
+ };
900
+ }
842
901
  /**
843
902
  * Restores the previous tree and lock after a failed regeneration.
844
903
  *