@orkestrel/scaffold 0.0.134 → 0.0.136

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-parallel/scripts/lane.js +777 -83
  2. package/dist/agents/skills/orkestrel-publish/scripts/wave.js +327 -21
  3. package/dist/bin/main.js +254 -36
  4. package/dist/bin/main.js.map +1 -1
  5. package/dist/host/AGENTS.md +2 -2
  6. package/dist/host/agents/orchestration.md +2 -2
  7. package/dist/host/agents/skills/orkestrel-parallel/SKILL.md +1 -1
  8. package/dist/host/agents/skills/orkestrel-parallel/scripts/lane.ts +983 -123
  9. package/dist/host/agents/skills/orkestrel-publish/references/release.md +1 -0
  10. package/dist/host/agents/skills/orkestrel-publish/references/wave.md +22 -5
  11. package/dist/host/agents/skills/orkestrel-publish/scripts/wave.ts +403 -32
  12. package/dist/host/claude/agents/orkestrel.md +17 -17
  13. package/dist/host/claude/agents/reviewer.md +1 -1
  14. package/dist/host/claude/rules/architecture.md +1 -1
  15. package/dist/host/claude/rules/documentation.md +1 -1
  16. package/dist/host/claude/rules/patterns.md +4 -2
  17. package/dist/host/claude/rules/workspace.md +73 -67
  18. package/dist/host/configs/helpers.ts +109 -73
  19. package/dist/host/dotfiles/oxlintrc.json +1 -57
  20. package/dist/host/guides/agent.md +989 -395
  21. package/dist/host/guides/contract.md +198 -163
  22. package/dist/host/guides/database.md +978 -503
  23. package/dist/host/guides/indexeddb.md +80 -66
  24. package/dist/host/guides/middleware.md +5 -5
  25. package/dist/host/guides/ollama.md +41 -42
  26. package/dist/host/guides/relation.md +56 -32
  27. package/dist/host/guides/scaffold.md +185 -107
  28. package/dist/host/guides/sqlite.md +44 -23
  29. package/dist/host/guides/study.md +12 -12
  30. package/dist/host/guides/test.md +163 -47
  31. package/dist/host/guides/toolbox.md +127 -81
  32. package/dist/host/guides/workspace.md +21 -14
  33. package/dist/host/manifest.json +30 -30
  34. package/dist/host/scripts/browsers.sh +0 -0
  35. package/dist/host/scripts/codex.sh +0 -0
  36. package/dist/host/scripts/cursor.sh +0 -0
  37. package/dist/host/scripts/deps.sh +0 -0
  38. package/dist/host/scripts/npm.sh +0 -0
  39. package/dist/host/scripts/ollama.sh +0 -0
  40. package/dist/host/tests/config.test.ts +237 -115
  41. package/dist/src/core/index.cjs +591 -218
  42. package/dist/src/core/index.cjs.map +1 -1
  43. package/dist/src/core/index.d.cts +248 -29
  44. package/dist/src/core/index.d.ts +248 -29
  45. package/dist/src/core/index.js +581 -216
  46. package/dist/src/core/index.js.map +1 -1
  47. package/dist/src/server/index.cjs +18 -8
  48. package/dist/src/server/index.cjs.map +1 -1
  49. package/dist/src/server/index.d.cts +4 -3
  50. package/dist/src/server/index.d.ts +4 -3
  51. package/dist/src/server/index.js +19 -9
  52. package/dist/src/server/index.js.map +1 -1
  53. package/package.json +3 -3
@@ -1,10 +1,10 @@
1
1
  import { spawn, spawnSync } from 'node:child_process';
2
2
  import { createHash, randomUUID } from 'node:crypto';
3
3
  import { once } from 'node:events';
4
- import { existsSync, linkSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync, } from 'node:fs';
4
+ import { existsSync, linkSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync, } from 'node:fs';
5
5
  import { connect, createServer } from 'node:net';
6
6
  import { constants, hostname, setPriority, userInfo } from 'node:os';
7
- import { basename, dirname, extname, isAbsolute, join } from 'node:path';
7
+ import { basename, dirname, extname, isAbsolute, join, resolve as resolvePath, sep, } from 'node:path';
8
8
  import { createInterface } from 'node:readline';
9
9
  import { fileURLToPath } from 'node:url';
10
10
  import { parseArgs } from 'node:util';
@@ -65,6 +65,13 @@ export const TOKEN_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[
65
65
  export const TICKET_PATTERN = /^(\d+)\.ticket$/u;
66
66
  /** Matches one snapshot row: process id, parent id, and creation time in milliseconds. */
67
67
  export const ROW_PATTERN = /^(\d+) (\d+) (\d+)$/u;
68
+ /** Names the directory where a Linux host publishes its process table. */
69
+ export const PROCESS_TABLE = '/proc';
70
+ /**
71
+ * Lists the process-table states of a member that has exited and that its parent has not reaped:
72
+ * `Z` for a zombie, and `X` for a process the kernel is releasing.
73
+ */
74
+ export const ENDED_STATES = ['Z', 'X'];
68
75
  /** Lists the signals that interrupt a lane on a host that delivers them. */
69
76
  export const STOP_SIGNALS = ['SIGINT', 'SIGTERM', 'SIGHUP'];
70
77
  /**
@@ -106,6 +113,29 @@ export const OUTCOME_SUFFIX = '.json';
106
113
  export const ENDED_WIDTH = 15;
107
114
  /** Holds the count of latest records the light reading takes, which is also the count each key keeps. */
108
115
  export const RECENT_RUNS = 3;
116
+ /** Holds the age in milliseconds past which a history key is pruned. */
117
+ export const HISTORY_AGE_MS = 7 * 24 * 60 * 60 * 1000;
118
+ /** Holds the count of history keys kept, the latest by their newest record. */
119
+ export const HISTORY_KEYS = 512;
120
+ /**
121
+ * Holds the longest wait in milliseconds for a sampler to ready before its holder starts the command
122
+ * unmeasured.
123
+ *
124
+ * @remarks
125
+ * The wait outlasts a sampler's start on a loaded host, and it bounds what a sampler that neither
126
+ * readies nor exits costs the lane.
127
+ */
128
+ export const READY_MS = 5000;
129
+ /**
130
+ * Holds the longest wait in milliseconds for a sampler's handover sample and for its exit after its
131
+ * stdin closes.
132
+ *
133
+ * @remarks
134
+ * A warm process query answered in about 140 ms on the Windows host measured 2026-11-12, so the wait
135
+ * outlasts a query on a loaded host, and it bounds what a sampler that hangs after it readied costs
136
+ * the lane at handover.
137
+ */
138
+ export const HANDOVER_MS = 5000;
109
139
  /** Holds the pause in milliseconds between two samples of a holder's tree. */
110
140
  export const SAMPLE_MS = 1000;
111
141
  /** Holds the exit code of a light run its holder ended at a threshold. */
@@ -158,6 +188,41 @@ export const BROWSER_PROJECT = /(?:^|:)(?:browser|vue)$/u;
158
188
  export const DOTTED_FLAG = /^--[^=.]+\.[^=]+$/u;
159
189
  /** Lists the package managers whose verbs and scripts a seed reads. */
160
190
  export const MANAGERS = ['npm', 'pnpm', 'yarn', 'bun'];
191
+ /** Lists the package-manager verbs that run a tool, which a seed reads through to the tool. */
192
+ export const EXEC_VERBS = ['exec', 'x', 'dlx'];
193
+ /** Lists, by tool, the exec flags that take a separate value, so a seed reads no flag value as the tool. */
194
+ export const EXEC_VALUE_FLAGS = Object.freeze({
195
+ npm: Object.freeze(['--package', '-p', '--workspace', '-w']),
196
+ npx: Object.freeze(['--package', '-p', '--workspace', '-w']),
197
+ pnpm: Object.freeze(['--package']),
198
+ pnpx: Object.freeze(['--package']),
199
+ yarn: Object.freeze(['--package']),
200
+ bun: Object.freeze(['--package']),
201
+ bunx: Object.freeze(['--package']),
202
+ });
203
+ /**
204
+ * Lists, by package manager, the flags before the verb that take a separate value, so a seed reads no
205
+ * flag value as the verb.
206
+ *
207
+ * @remarks
208
+ * npm's `-w` names a workspace and takes a value; pnpm's `-w` is the boolean `--workspace-root`.
209
+ */
210
+ export const MANAGER_VALUE_FLAGS = Object.freeze({
211
+ npm: Object.freeze(['--prefix', '--workspace', '-w']),
212
+ pnpm: Object.freeze(['--dir', '-C', '--filter', '-F']),
213
+ yarn: Object.freeze(['--cwd']),
214
+ bun: Object.freeze(['--cwd']),
215
+ });
216
+ /** Lists the tools that run another tool the way `npx` does. */
217
+ export const NPX_TOOLS = ['npx', 'pnpx', 'bunx'];
218
+ /** Lists the `npm exec` and `npx` flags that run inline shell text, which names no tool a seed reads. */
219
+ export const EXEC_INLINE_FLAGS = ['-c', '--call'];
220
+ /** Holds the tool name of the falsify skill's `mutate` script, whose run a seed reads by its wrapped command. */
221
+ export const MUTATION_TOOL = 'mutate';
222
+ /** Holds the `mutate` flag that names the edits file, which a run's key leaves out. */
223
+ export const MUTATION_FLAG = '--edits';
224
+ /** Holds the `mutate` flag that writes saved originals back, which edits source and wraps no command. */
225
+ export const RESTORE_FLAG = '--restore';
161
226
  /** Lists the tools a seed reads heavy by name: the release chain's step runner. */
162
227
  export const HEAVY_TOOLS = ['steps'];
163
228
  /** Lists the Vitest flags that take a separate value, so a seed reads no flag value as a file. */
@@ -191,8 +256,21 @@ export const CHECK_SCRIPT = /^(?:check|typecheck|type-check)(?::|$)|:check$/u;
191
256
  export const SCOPED_SCRIPT = /^test:/u;
192
257
  /** Matches one sampler row: process id, parent id, creation time in milliseconds, CPU time in 100 ns units, and private bytes. */
193
258
  export const GAUGE_PATTERN = /^(\d+) (\d+) (\d+) (\d+) (\d+)$/u;
194
- /** Holds the PowerShell text that prints one line of rows per sample until its stdin closes. */
195
- export const SAMPLER_COMMAND = `$i=[Console]::OpenStandardInput();$b=New-Object byte[] 1;$t=$i.ReadAsync($b,0,1);while(-not $t.IsCompleted){$r=Get-CimInstance Win32_Process -Property ProcessId,ParentProcessId,CreationDate,KernelModeTime,UserModeTime,PrivatePageCount | Where-Object { $_.CreationDate } | ForEach-Object { '{0} {1} {2} {3} {4}' -f $_.ProcessId,$_.ParentProcessId,([DateTimeOffset]$_.CreationDate).ToUnixTimeMilliseconds(),($_.KernelModeTime+$_.UserModeTime),$_.PrivatePageCount };[Console]::Out.WriteLine($r -join ';');[Console]::Out.Flush();Start-Sleep -Milliseconds ${String(SAMPLE_MS)}}`;
259
+ /** Holds the line a sampler prints when its first process query has run, which readies it. */
260
+ export const READY_LINE = 'ready';
261
+ /** Holds the byte a holder writes to its sampler to ask for one sample at once. */
262
+ export const SAMPLE_BYTE = 's';
263
+ /**
264
+ * Holds the PowerShell text of a sampler.
265
+ *
266
+ * @remarks
267
+ * The child runs one process query, the one a sample runs, so its first sample answers warm, and
268
+ * prints {@link READY_LINE}. Until the first byte it waits on its
269
+ * stdin with no timer. Each byte on its stdin starts one sample at once, and after the first byte it
270
+ * also samples every {@link SAMPLE_MS}. A sample prints one line: `1` for a sample a byte asked for or `0`, a `|`,
271
+ * and the rows separated by semicolons. The child exits when its stdin closes.
272
+ */
273
+ export const SAMPLER_COMMAND = `$i=[Console]::OpenStandardInput();$b=New-Object byte[] 1;$t=$i.ReadAsync($b,0,1);$null=Get-CimInstance Win32_Process -Property ProcessId,ParentProcessId,CreationDate,KernelModeTime,UserModeTime,PrivatePageCount;[Console]::Out.WriteLine('${READY_LINE}');[Console]::Out.Flush();$a=$false;$q=0;$d=-1;while($true){if($a){$r=Get-CimInstance Win32_Process -Property ProcessId,ParentProcessId,CreationDate,KernelModeTime,UserModeTime,PrivatePageCount | Where-Object { $_.CreationDate } | ForEach-Object { '{0} {1} {2} {3} {4}' -f $_.ProcessId,$_.ParentProcessId,([DateTimeOffset]$_.CreationDate).ToUnixTimeMilliseconds(),($_.KernelModeTime+$_.UserModeTime),$_.PrivatePageCount };[Console]::Out.WriteLine([string]$q+'|'+($r -join ';'));[Console]::Out.Flush();$q=0};if($t.Wait($d)){if($t.Status -ne 'RanToCompletion' -or $t.Result -eq 0){break};$a=$true;$q=1;$d=${String(SAMPLE_MS)};$t=$i.ReadAsync($b,0,1)}}`;
196
274
  /**
197
275
  * Holds a process's endpoint, whose existence is the process's liveness.
198
276
  *
@@ -395,7 +473,8 @@ export function isTicket(value) {
395
473
  'arrived' in value &&
396
474
  typeof value.arrived === 'string' &&
397
475
  (!('light' in value) || isUsage(value.light)) &&
398
- (!('solo' in value) || typeof value.solo === 'boolean'));
476
+ (!('solo' in value) || typeof value.solo === 'boolean') &&
477
+ (!('edits' in value) || typeof value.edits === 'boolean'));
399
478
  }
400
479
  /**
401
480
  * Checks whether a value is a footprint.
@@ -577,9 +656,11 @@ export function removeFile(path) {
577
656
  * @param light - The footprint a light ticket counts, or undefined for a heavy ticket.
578
657
  * @param solo - If `true`, marks a ticket that waits out every earlier light ticket; if `false`, omits
579
658
  * the field.
580
- * @returns The complete ticket, carrying `light` and `solo` only when they are set.
659
+ * @param edits - If `true`, marks a `mutate` run that edits source in its working directory; if
660
+ * `false`, omits the field.
661
+ * @returns The complete ticket, carrying `light`, `solo`, and `edits` only when they are set.
581
662
  */
582
- export function buildTicket(token, label, light, solo = false) {
663
+ export function buildTicket(token, label, light, solo = false, edits = false) {
583
664
  return {
584
665
  protocol: PROTOCOL,
585
666
  token,
@@ -591,6 +672,7 @@ export function buildTicket(token, label, light, solo = false) {
591
672
  arrived: new Date().toISOString(),
592
673
  ...(light === undefined ? {} : { light }),
593
674
  ...(solo ? { solo } : {}),
675
+ ...(edits ? { edits } : {}),
594
676
  };
595
677
  }
596
678
  /**
@@ -671,14 +753,99 @@ export function readOutcomes(root, key) {
671
753
  * @param key - The command's key.
672
754
  * @param name - The record's name.
673
755
  * @param outcome - The record.
756
+ * @returns True when the write created the key's directory; false when the key existed.
674
757
  */
675
758
  export function writeOutcome(root, key, name, outcome) {
676
759
  const directory = join(root, HISTORY_DIRECTORY, key);
677
- mkdirSync(directory, { recursive: true });
760
+ const created = mkdirSync(directory, { recursive: true }) !== undefined;
678
761
  writeFileSync(join(directory, name), JSON.stringify(outcome), { flag: 'wx' });
679
762
  for (const stale of readOutcomeNames(root, key).slice(0, -RECENT_RUNS)) {
680
763
  removeFile(join(directory, stale));
681
764
  }
765
+ return created;
766
+ }
767
+ /**
768
+ * Reads when a history key was last written.
769
+ *
770
+ * @param root - The queue root.
771
+ * @param key - The key.
772
+ * @returns The end time its newest record's name opens with; the directory's modification time when
773
+ * it holds no record; `gone` when the entry no longer exists; `unread` when the host refuses to list
774
+ * it, as it does for a file that is no directory.
775
+ */
776
+ export function readKeyTime(root, key) {
777
+ try {
778
+ const newest = readOutcomeNames(root, key).at(-1);
779
+ if (newest !== undefined)
780
+ return Number(newest.slice(0, ENDED_WIDTH));
781
+ return statSync(join(root, HISTORY_DIRECTORY, key)).mtimeMs;
782
+ }
783
+ catch (error) {
784
+ return readCode(error) === 'ENOENT' ? 'gone' : 'unread';
785
+ }
786
+ }
787
+ /**
788
+ * Lists the names under the history directory.
789
+ *
790
+ * @param root - The queue root.
791
+ * @returns The names, empty when the directory is absent; undefined when the host refuses to list it.
792
+ */
793
+ export function readHistoryNames(root) {
794
+ try {
795
+ return readNames(join(root, HISTORY_DIRECTORY));
796
+ }
797
+ catch {
798
+ return undefined;
799
+ }
800
+ }
801
+ /**
802
+ * Removes one history key inside the removal budget.
803
+ *
804
+ * @param root - The queue root.
805
+ * @param key - The key.
806
+ * @returns True when the key is gone; false when the host refused the removal.
807
+ */
808
+ export function removeKey(root, key) {
809
+ try {
810
+ rmSync(join(root, HISTORY_DIRECTORY, key), {
811
+ recursive: true,
812
+ force: true,
813
+ maxRetries: REMOVAL_RETRIES,
814
+ retryDelay: REMOVAL_DELAY_MS,
815
+ });
816
+ return true;
817
+ }
818
+ catch {
819
+ return false;
820
+ }
821
+ }
822
+ /**
823
+ * Prunes the history to the keys written inside {@link HISTORY_AGE_MS}, at most the
824
+ * {@link HISTORY_KEYS} written last.
825
+ *
826
+ * @remarks
827
+ * The prune throws nothing, so it never changes the lane's exit: a name the host refuses to list or
828
+ * remove stays and is reported as skipped.
829
+ *
830
+ * @param root - The queue root.
831
+ * @param now - The current time in epoch milliseconds.
832
+ * @returns The keys removed, and the names skipped: `history` itself when it cannot be listed.
833
+ */
834
+ export function pruneHistory(root, now) {
835
+ const names = readHistoryNames(root);
836
+ if (names === undefined)
837
+ return { removed: [], skipped: [HISTORY_DIRECTORY] };
838
+ const times = names.map((key) => ({ key, time: readKeyTime(root, key) }));
839
+ const unread = times.flatMap((item) => (item.time === 'unread' ? [item.key] : []));
840
+ const results = times
841
+ .flatMap((item) => (typeof item.time === 'number' ? [{ key: item.key, time: item.time }] : []))
842
+ .toSorted((left, right) => right.time - left.time)
843
+ .filter((item, index) => index >= HISTORY_KEYS || item.time < now - HISTORY_AGE_MS)
844
+ .map((item) => ({ key: item.key, removed: removeKey(root, item.key) }));
845
+ return {
846
+ removed: results.flatMap((item) => (item.removed ? [item.key] : [])),
847
+ skipped: [...unread, ...results.flatMap((item) => (item.removed ? [] : [item.key]))],
848
+ };
682
849
  }
683
850
  /**
684
851
  * Reads the average cores a run used.
@@ -791,10 +958,12 @@ export function readToolName(path) {
791
958
  return name.replace(/-cli$/u, '');
792
959
  }
793
960
  /**
794
- * Reads the tool a command runs and the tool's arguments, past Node and `npx`.
961
+ * Reads the tool a command runs and the tool's arguments, past Node, `npx`, `pnpx`, `bunx`, and a
962
+ * package manager's `exec`, `x`, or `dlx` verb.
795
963
  *
796
964
  * @param command - The command and its arguments.
797
- * @returns The tool's name followed by its arguments; empty for inline Node code or no script.
965
+ * @returns The tool's name followed by its arguments; empty for inline Node code, inline exec text,
966
+ * or no script.
798
967
  */
799
968
  export function readTool(command) {
800
969
  const [executable, ...rest] = command;
@@ -809,12 +978,147 @@ export function readTool(command) {
809
978
  }
810
979
  return readTool(rest.slice(script));
811
980
  }
812
- if (name === 'npx') {
813
- const tool = rest.findIndex((argument) => !argument.startsWith('-'));
814
- return tool === -1 ? [] : readTool(rest.slice(tool));
981
+ if (NPX_TOOLS.includes(name))
982
+ return readExecTool(rest, EXEC_VALUE_FLAGS[name]);
983
+ if (MANAGERS.includes(name)) {
984
+ const flags = MANAGER_VALUE_FLAGS[name] ?? [];
985
+ const verb = rest.findIndex((argument, index) => !argument.startsWith('-') && !flags.includes(rest[index - 1] ?? ''));
986
+ if (EXEC_VERBS.includes(rest[verb] ?? '')) {
987
+ return readExecTool(rest.slice(verb + 1), EXEC_VALUE_FLAGS[name]);
988
+ }
815
989
  }
816
990
  return [name, ...rest];
817
991
  }
992
+ /**
993
+ * Reads the tool an `npx` or `npm exec` call runs, from the arguments after the verb.
994
+ *
995
+ * @remarks
996
+ * The tool is the first argument before a bare `--` that is neither a flag nor the value of a
997
+ * listed flag, else the first argument after the bare `--`. A flag {@link EXEC_INLINE_FLAGS} names
998
+ * before the tool runs shell text instead.
999
+ *
1000
+ * @param args - The arguments after `npx` or after the exec verb.
1001
+ * @param valueFlags - The flags that take a separate value, from {@link EXEC_VALUE_FLAGS}. Default:
1002
+ * none.
1003
+ * @returns The tool's name followed by its arguments; empty for inline text or no tool.
1004
+ */
1005
+ export function readExecTool(args, valueFlags = []) {
1006
+ const end = args.indexOf('--');
1007
+ const named = args.findIndex((argument, index) => (end === -1 || index < end) &&
1008
+ !argument.startsWith('-') &&
1009
+ !valueFlags.includes(args[index - 1] ?? ''));
1010
+ const start = named !== -1 ? named : end === -1 ? -1 : end + 1;
1011
+ if (start === -1 || start >= args.length)
1012
+ return [];
1013
+ const inline = args
1014
+ .slice(0, start)
1015
+ .some((flag) => EXEC_INLINE_FLAGS.includes(flag) ||
1016
+ EXEC_INLINE_FLAGS.some((name) => flag.startsWith(`${name}=`)));
1017
+ return inline ? [] : readTool(args.slice(start));
1018
+ }
1019
+ /**
1020
+ * Checks whether a command is a `mutate --restore` run, which writes source files back.
1021
+ *
1022
+ * @param command - The command and its arguments.
1023
+ * @returns True for a `mutate` call with its restore flag before any bare `--`; false otherwise.
1024
+ */
1025
+ export function matchesRestore(command) {
1026
+ const [tool, ...args] = readTool(command);
1027
+ if (tool !== MUTATION_TOOL)
1028
+ return false;
1029
+ const end = args.indexOf('--');
1030
+ return (end === -1 ? args : args.slice(0, end)).some((flag) => flag === RESTORE_FLAG || flag.startsWith(`${RESTORE_FLAG}=`));
1031
+ }
1032
+ /**
1033
+ * Extracts the command a `mutate` run wraps.
1034
+ *
1035
+ * @param command - The command and its arguments.
1036
+ * @returns The arguments after the run's own bare `--`; undefined for any other command, or a
1037
+ * `mutate` call with no edits file or no wrapped command.
1038
+ */
1039
+ export function extractMutation(command) {
1040
+ const [tool, ...args] = readTool(command);
1041
+ if (tool !== MUTATION_TOOL)
1042
+ return undefined;
1043
+ const end = args.indexOf('--');
1044
+ if (end === -1)
1045
+ return undefined;
1046
+ const edits = args
1047
+ .slice(0, end)
1048
+ .some((flag) => flag === MUTATION_FLAG || flag.startsWith(`${MUTATION_FLAG}=`));
1049
+ const wrapped = args.slice(end + 1);
1050
+ return edits && wrapped.length > 0 ? wrapped : undefined;
1051
+ }
1052
+ /**
1053
+ * Normalizes a command to the arguments its key hashes.
1054
+ *
1055
+ * @remarks
1056
+ * A `mutate` run names a fresh edits file each time, so its key leaves the edits flag and its value
1057
+ * out, and every run of one wrapped command from one directory shares a key. The cut reads only the
1058
+ * script's own flags, between the script and its own bare `--`, so a launcher's `--` before the
1059
+ * script moves nothing.
1060
+ *
1061
+ * @param command - The command and its arguments.
1062
+ * @returns A `mutate` run without its edits flag and value; any other command unchanged.
1063
+ */
1064
+ export function normalizeCommand(command) {
1065
+ if (extractMutation(command) === undefined)
1066
+ return command;
1067
+ const start = command.length - readTool(command).length + 1;
1068
+ const end = command.indexOf('--', start);
1069
+ return command.filter((argument, index) => index < start ||
1070
+ index >= end ||
1071
+ !(argument === MUTATION_FLAG ||
1072
+ argument.startsWith(`${MUTATION_FLAG}=`) ||
1073
+ command[index - 1] === MUTATION_FLAG));
1074
+ }
1075
+ /**
1076
+ * Normalizes a working directory for the comparison that decides whether two tickets share it.
1077
+ *
1078
+ * @remarks
1079
+ * Every side of the comparison passes through this one function. It reads the real path through
1080
+ * `realpathSync.native`, which returns the name and the case the file system stores, so two
1081
+ * spellings of one directory compare equal without folding case.
1082
+ *
1083
+ * @param path - The directory.
1084
+ * @returns The real path; the resolved path when it cannot be read, as for a vanished directory.
1085
+ */
1086
+ export function normalizeDirectory(path) {
1087
+ try {
1088
+ return realpathSync.native(path);
1089
+ }
1090
+ catch {
1091
+ return resolvePath(path);
1092
+ }
1093
+ }
1094
+ /**
1095
+ * Checks whether two working directories share source.
1096
+ *
1097
+ * @remarks
1098
+ * Both sides pass through {@link normalizeDirectory}, so a child directory, such as a check run from
1099
+ * `packages/a`, shares source with a mutation at the checkout root, and the reverse.
1100
+ *
1101
+ * @param left - One directory.
1102
+ * @param right - The other directory.
1103
+ * @returns True when the two normalize to one directory or one sits inside the other at a separator
1104
+ * boundary; false otherwise.
1105
+ */
1106
+ export function sharesDirectory(left, right) {
1107
+ const one = normalizeDirectory(left);
1108
+ const other = normalizeDirectory(right);
1109
+ return one === other || matchesInside(one, other) || matchesInside(other, one);
1110
+ }
1111
+ /**
1112
+ * Checks whether a normalized path sits inside another at a separator boundary.
1113
+ *
1114
+ * @param inner - The path that might sit inside.
1115
+ * @param outer - The path that might contain it.
1116
+ * @returns True when `inner` opens with `outer` and a separator; false otherwise, the same path
1117
+ * included.
1118
+ */
1119
+ export function matchesInside(inner, outer) {
1120
+ return inner.startsWith(outer.endsWith(sep) ? outer : `${outer}${sep}`);
1121
+ }
818
1122
  /**
819
1123
  * Reads the positional arguments of a command, skipping each value of a value-taking flag.
820
1124
  *
@@ -872,7 +1176,8 @@ export function readVitestSeed(args) {
872
1176
  *
873
1177
  * @remarks
874
1178
  * Heavy wins: a word that names a journey, a study, a capture, a live-service run, or the release
875
- * chain seeds heavy wherever it appears, before any light kind is read.
1179
+ * chain seeds heavy wherever it appears, before any light kind is read. A `mutate --restore` run,
1180
+ * which writes source files back and wraps no command, seeds heavy.
876
1181
  *
877
1182
  * @param command - The command and its arguments.
878
1183
  * @returns The seeded lane, or undefined when no kind names the command.
@@ -883,10 +1188,10 @@ export function readSeed(command) {
883
1188
  const [tool, ...args] = readTool(command);
884
1189
  if (tool === undefined)
885
1190
  return undefined;
886
- if (HEAVY_TOOLS.includes(tool))
1191
+ if (HEAVY_TOOLS.includes(tool) || matchesRestore(command))
887
1192
  return 'heavy';
888
1193
  if (MANAGERS.includes(tool)) {
889
- const [verb, script] = readOperands(args, []);
1194
+ const [verb, script] = readOperands(args, MANAGER_VALUE_FLAGS[tool] ?? []);
890
1195
  if (verb === undefined)
891
1196
  return undefined;
892
1197
  if (HEAVY_VERBS.includes(verb))
@@ -957,7 +1262,10 @@ export function linkStage(root, token) {
957
1262
  * @remarks
958
1263
  * The two listings are separate, because one listing can miss both a ticket linked and a stage file
959
1264
  * removed while it runs. A stage file absent from the first listing belongs to a process whose own
960
- * listing sees this ticket, or to a ticket the second listing sees.
1265
+ * listing sees this ticket, or to a ticket the second listing sees. A ticket holds only when the
1266
+ * directory rule of {@link decideDirectory} names no ticket to wait on and its own lane's rule admits
1267
+ * it. Every rule names only an earlier ticket, and an earlier ticket can only leave, so no two tickets
1268
+ * wait on each other and no cycle of waits can form.
961
1269
  *
962
1270
  * @param root - The queue root.
963
1271
  * @param sequence - This process's sequence.
@@ -977,17 +1285,44 @@ export function decideTurn(root, sequence, token, limits) {
977
1285
  }
978
1286
  const own = entries[position]?.ticket;
979
1287
  const earlier = entries.slice(0, position);
1288
+ const shared = own === undefined ? undefined : decideDirectory(earlier, own);
1289
+ if (shared !== undefined)
1290
+ return shared;
980
1291
  return own?.light === undefined || limits === undefined
981
1292
  ? decideHeavy(earlier, own?.solo === true)
982
1293
  : decideLight(root, earlier, own.light, limits);
983
1294
  }
1295
+ /**
1296
+ * Decides which earlier ticket the directory rule makes a ticket wait on, whatever its lane.
1297
+ *
1298
+ * @remarks
1299
+ * Every ticket waits on the nearest earlier ticket that carries `edits` and shares its working
1300
+ * directory, because a `mutate` run edits source that ticket reads. A ticket that carries `edits`
1301
+ * also waits on the nearest earlier ticket of its working directory in either lane, and on an
1302
+ * earlier ticket it cannot read, which might share the directory; that wait refuses. The rule names
1303
+ * only earlier tickets, which can only leave, so it adds no cycle of waits. {@link normalizeDirectory}
1304
+ * reads both sides of every comparison.
1305
+ *
1306
+ * @param earlier - The tickets before this one, in arrival order.
1307
+ * @param own - This process's ticket.
1308
+ * @returns The ticket to wait on; undefined when the rule names none.
1309
+ */
1310
+ export function decideDirectory(earlier, own) {
1311
+ const entry = earlier.findLast((item) => {
1312
+ if (item.ticket === undefined)
1313
+ return own.edits === true;
1314
+ return ((own.edits === true || item.ticket.edits === true) &&
1315
+ sharesDirectory(own.cwd, item.ticket.cwd));
1316
+ });
1317
+ return entry === undefined ? undefined : { state: 'behind', entry };
1318
+ }
984
1319
  /**
985
1320
  * Decides what a heavy ticket does next.
986
1321
  *
987
1322
  * @remarks
988
1323
  * A heavy ticket waits on the nearest earlier ticket that is not light, an unreadable one included. A
989
1324
  * `--solo` ticket waits on the nearest earlier ticket of either lane, so it holds with no light
990
- * holder beside it.
1325
+ * holder beside it. The rule names only an earlier ticket, so it adds no cycle of waits.
991
1326
  *
992
1327
  * @param earlier - The tickets before this one, in arrival order.
993
1328
  * @param solo - If `true`, waits on light tickets too; if `false`, passes them.
@@ -1019,7 +1354,11 @@ export function decideLight(root, earlier, light, limits) {
1019
1354
  return { state: 'behind', entry: unread };
1020
1355
  const lights = earlier.filter((entry) => entry.ticket?.light !== undefined);
1021
1356
  const solos = earlier.filter((entry) => entry.ticket?.solo === true);
1022
- const pending = lights.flatMap((entry) => readRun(root, entry.sequence) === 'absent' ? [entry.sequence] : []);
1357
+ const pending = lights.flatMap((entry) => {
1358
+ const blocked = entry.ticket !== undefined &&
1359
+ decideDirectory(earlier.slice(0, earlier.indexOf(entry)), entry.ticket) !== undefined;
1360
+ return !blocked && readRun(root, entry.sequence) === 'absent' ? [entry.sequence] : [];
1361
+ });
1023
1362
  const usages = lights.flatMap((entry) => entry.ticket?.light === undefined ? [] : [entry.ticket.light]);
1024
1363
  const fits = usages.length === 0 || fitsBudget([...usages, light], limits);
1025
1364
  return solos.length === 0 && pending.length === 0 && fits
@@ -1147,19 +1486,175 @@ export function selectMembers(rows, seeds, floor, ceiling) {
1147
1486
  return [...members.values()];
1148
1487
  }
1149
1488
  /**
1150
- * Reads whether a process group still has a member.
1489
+ * Parses one process-table `stat` line into its state and its process group.
1151
1490
  *
1491
+ * @remarks
1492
+ * The command name sits in parentheses and can hold spaces and parentheses itself, so the fields
1493
+ * are read after the last `)`: the state, the parent id, then the group id.
1494
+ *
1495
+ * @param text - The content of `/proc/<pid>/stat`.
1496
+ * @returns The state and the group, or undefined when the text does not have that form.
1497
+ */
1498
+ export function parseStat(text) {
1499
+ const close = text.lastIndexOf(')');
1500
+ if (close === -1)
1501
+ return undefined;
1502
+ const [state, , group] = text.slice(close + 2).split(' ');
1503
+ return state === undefined || state === '' || group === undefined || !/^\d+$/u.test(group)
1504
+ ? undefined
1505
+ : { state, group: Number(group) };
1506
+ }
1507
+ /**
1508
+ * Lists the entries of one process-table directory.
1509
+ *
1510
+ * @param path - The directory.
1511
+ * @returns The entry names, or undefined when the listing fails.
1512
+ */
1513
+ export function readListing(path) {
1514
+ try {
1515
+ return readdirSync(path);
1516
+ }
1517
+ catch {
1518
+ return undefined;
1519
+ }
1520
+ }
1521
+ /**
1522
+ * Reads one thread's state from its own process-table entry.
1523
+ *
1524
+ * @param pid - The process id, as its process-table entry names it.
1525
+ * @param tid - The thread id, as the process's `task` listing names it.
1526
+ * @param table - The process table's root. Default: {@link PROCESS_TABLE}.
1527
+ * @returns The task keyed `<pid>/<tid>`, or undefined when its `stat` cannot be read or parsed.
1528
+ */
1529
+ export function readTask(pid, tid, table = PROCESS_TABLE) {
1530
+ try {
1531
+ const stat = parseStat(readFileSync(join(table, pid, 'task', tid, 'stat'), 'utf8'));
1532
+ return stat === undefined ? undefined : { id: `${pid}/${tid}`, state: stat.state };
1533
+ }
1534
+ catch {
1535
+ return undefined;
1536
+ }
1537
+ }
1538
+ /**
1539
+ * Reads the state of every thread of one process from the process table.
1540
+ *
1541
+ * @param pid - The process id, as its process-table entry names it.
1542
+ * @returns One task per thread, keyed `<pid>/<tid>`, or undefined when the `task` listing fails,
1543
+ * lists no thread, or holds a thread whose `stat` cannot be read: what the reading cannot read
1544
+ * counts as present.
1545
+ * @param table - The process table's root. Default: {@link PROCESS_TABLE}.
1546
+ */
1547
+ export function readThreads(pid, table = PROCESS_TABLE) {
1548
+ const tids = readListing(join(table, pid, 'task'));
1549
+ if (tids === undefined || tids.length === 0)
1550
+ return undefined;
1551
+ const tasks = tids.map((tid) => readTask(pid, tid, table));
1552
+ return tasks.includes(undefined)
1553
+ ? undefined
1554
+ : tasks.flatMap((task) => (task === undefined ? [] : [task]));
1555
+ }
1556
+ /**
1557
+ * Reads the threads of one process-table entry when it belongs to a process group.
1558
+ *
1559
+ * @param name - The process id, as the process-table listing names it.
1152
1560
  * @param group - The group id.
1153
- * @returns The group id while the host reports the group; empty when it reports none.
1561
+ * @returns The entry's threads when it belongs to the group, none when it belongs to another group
1562
+ * or its `stat` is gone (`ENOENT`, a process that ended), or undefined when its `stat` cannot be
1563
+ * read for any other reason or cannot be parsed, or its threads cannot be read.
1564
+ * @param table - The process table's root. Default: {@link PROCESS_TABLE}.
1154
1565
  */
1155
- export function readGroup(group) {
1566
+ export function readMember(name, group, table = PROCESS_TABLE) {
1567
+ try {
1568
+ const stat = parseStat(readFileSync(join(table, name, 'stat'), 'utf8'));
1569
+ if (stat === undefined)
1570
+ return undefined;
1571
+ return stat.group === group ? readThreads(name, table) : [];
1572
+ }
1573
+ catch (error) {
1574
+ return readCode(error) === 'ENOENT' ? [] : undefined;
1575
+ }
1576
+ }
1577
+ /**
1578
+ * Reads every thread of every member of a process group from the process table.
1579
+ *
1580
+ * @param group - The group id.
1581
+ * @returns One task per thread of each member, or undefined when the host publishes no process
1582
+ * table, the table cannot be listed, or any entry cannot be read; a process whose `stat` is gone
1583
+ * is skipped.
1584
+ * @param table - The process table's root. Default: {@link PROCESS_TABLE}.
1585
+ */
1586
+ export function readTasks(group, table = PROCESS_TABLE) {
1587
+ if (!existsSync(join(table, 'self', 'stat')))
1588
+ return undefined;
1589
+ const names = readListing(table);
1590
+ if (names === undefined)
1591
+ return undefined;
1592
+ const members = names
1593
+ .filter((name) => /^\d+$/u.test(name))
1594
+ .map((name) => readMember(name, group, table));
1595
+ return members.includes(undefined)
1596
+ ? undefined
1597
+ : members.flatMap((member) => (member === undefined ? [] : member));
1598
+ }
1599
+ /**
1600
+ * Checks whether two readings of one group show the same threads, every one of them exited.
1601
+ *
1602
+ * @remarks
1603
+ * A thread read as exited cannot start another process or thread after that read, so every process
1604
+ * that joined the group and every thread created before the first reading finished exists when the
1605
+ * second listing starts. A second reading of the same tasks therefore leaves none of them out, and a
1606
+ * member that forked between its listing and its read shows up as a task the first reading lacks.
1607
+ * An empty reading reads as not ended, because the probe signal reached a member the table did not
1608
+ * show, as a table from another PID namespace does.
1609
+ *
1610
+ * @param first - The first reading.
1611
+ * @param second - The reading taken after the first finished.
1612
+ * @returns True if both readings hold at least one task, list the same task ids, and show every
1613
+ * task as {@link ENDED_STATES}; false otherwise.
1614
+ */
1615
+ export function matchesEnded(first, second) {
1616
+ return (first.length > 0 &&
1617
+ first
1618
+ .map((task) => task.id)
1619
+ .toSorted()
1620
+ .join(' ') ===
1621
+ second
1622
+ .map((task) => task.id)
1623
+ .toSorted()
1624
+ .join(' ') &&
1625
+ [...first, ...second].every((task) => ENDED_STATES.includes(task.state)));
1626
+ }
1627
+ /**
1628
+ * Reads whether a process group still has a member that has not exited.
1629
+ *
1630
+ * @remarks
1631
+ * A signal reaches a zombie, so a group whose members have all exited still answers the probe
1632
+ * signal until their parent reaps them, which an init that does not reap as a child ends leaves
1633
+ * for later. Where the host publishes a process table, a group reads as ended when two readings
1634
+ * taken one after the other show the same threads of its members, every one {@link ENDED_STATES},
1635
+ * per {@link matchesEnded}. A zombie whose threads have all exited holds no CPU, memory, or file
1636
+ * handle; a process whose main thread exited while another thread runs shows `Z` for itself and
1637
+ * reads as present through that thread. A host without that table, and a reading that cannot read
1638
+ * part of it, read such a group as present.
1639
+ *
1640
+ * @param group - The group id.
1641
+ * @param read - Takes one reading of the group's threads; undefined means the reading could not
1642
+ * read the table. Default: {@link readTasks}.
1643
+ * @returns The group id while the host reports a member that has not exited or the reading
1644
+ * cannot read the table; empty when it reports none.
1645
+ */
1646
+ export function readGroup(group, read = readTasks) {
1156
1647
  try {
1157
1648
  process.kill(-group, 0);
1158
- return [group];
1159
1649
  }
1160
1650
  catch (error) {
1161
1651
  return readCode(error) === 'ESRCH' ? [] : [group];
1162
1652
  }
1653
+ const first = read(group);
1654
+ if (first === undefined)
1655
+ return [group];
1656
+ const second = read(group);
1657
+ return second !== undefined && matchesEnded(first, second) ? [] : [group];
1163
1658
  }
1164
1659
  /**
1165
1660
  * Reads the members of one run's process tree.
@@ -1178,9 +1673,20 @@ export function readTree(run, ceiling) {
1178
1673
  if (process.platform !== 'win32')
1179
1674
  return readGroup(run.launcher);
1180
1675
  const rows = readSnapshot();
1181
- return rows === undefined
1182
- ? undefined
1183
- : selectMembers(rows, run.command === undefined ? [run.launcher] : [run.launcher, run.command], run.started - CLOCK_ALLOWANCE_MS, ceiling).map((row) => row.pid);
1676
+ return rows === undefined ? undefined : selectTree(rows, run, ceiling);
1677
+ }
1678
+ /**
1679
+ * Selects the members of one run's process tree from a Windows snapshot.
1680
+ *
1681
+ * @param rows - The snapshot.
1682
+ * @param run - The run record.
1683
+ * @param ceiling - The latest creation date a row of an exited seed can carry.
1684
+ * @returns The members' ids, or undefined when the record names no launcher.
1685
+ */
1686
+ export function selectTree(rows, run, ceiling) {
1687
+ if (run.launcher === undefined)
1688
+ return undefined;
1689
+ return selectMembers(rows, run.command === undefined ? [run.launcher] : [run.launcher, run.command], run.started - CLOCK_ALLOWANCE_MS, ceiling).map((row) => row.pid);
1184
1690
  }
1185
1691
  /**
1186
1692
  * Kills each listed member.
@@ -1439,6 +1945,18 @@ export function waitForClose(child) {
1439
1945
  child.once('close', (code) => resolve(code ?? undefined));
1440
1946
  });
1441
1947
  }
1948
+ /**
1949
+ * Waits for a started launcher to exit, which precedes the close of its streams.
1950
+ *
1951
+ * @param child - The started launcher.
1952
+ * @returns When it exited or failed, in epoch milliseconds.
1953
+ */
1954
+ export function waitForExit(child) {
1955
+ return new Promise((resolve) => {
1956
+ child.once('error', () => resolve(Date.now()));
1957
+ child.once('exit', () => resolve(Date.now()));
1958
+ });
1959
+ }
1442
1960
  /**
1443
1961
  * Writes a run record, leaving an unwritten id to the handover reading.
1444
1962
  *
@@ -1495,6 +2013,36 @@ export function parseGauges(line) {
1495
2013
  ];
1496
2014
  });
1497
2015
  }
2016
+ /**
2017
+ * Waits for a promise within a bound.
2018
+ *
2019
+ * @param promise - The promise.
2020
+ * @param budget - The longest wait in milliseconds.
2021
+ * @returns The promise's value; undefined when the budget runs out first.
2022
+ */
2023
+ export async function waitForBound(promise, budget) {
2024
+ const timer = Promise.withResolvers();
2025
+ const handle = setTimeout(() => timer.resolve(undefined), budget);
2026
+ try {
2027
+ return await Promise.race([promise, timer.promise]);
2028
+ }
2029
+ finally {
2030
+ clearTimeout(handle);
2031
+ }
2032
+ }
2033
+ /**
2034
+ * Parses one sample line of a sampler.
2035
+ *
2036
+ * @param line - One line of the sampler's stdout: `1` or `0`, a `|`, and the rows.
2037
+ * @returns Whether a byte asked for the sample, with its gauges; undefined for a line without the
2038
+ * marker, such as {@link READY_LINE}.
2039
+ */
2040
+ export function parseSample(line) {
2041
+ const split = line.indexOf('|');
2042
+ if (split === -1)
2043
+ return undefined;
2044
+ return { requested: line.slice(0, split) === '1', gauges: parseGauges(line.slice(split + 1)) };
2045
+ }
1498
2046
  /**
1499
2047
  * Folds one sample's members into a tally.
1500
2048
  *
@@ -1555,12 +2103,12 @@ export function lowerPriority(pid) {
1555
2103
  * @param key - The command's key.
1556
2104
  * @param name - The record's name.
1557
2105
  * @param outcome - The record.
1558
- * @returns True when the record was written; false otherwise.
2106
+ * @returns True when the write created the key's directory; false when the key existed or the host
2107
+ * refused the write.
1559
2108
  */
1560
2109
  export function tryWriteOutcome(root, key, name, outcome) {
1561
2110
  try {
1562
- writeOutcome(root, key, name, outcome);
1563
- return true;
2111
+ return writeOutcome(root, key, name, outcome);
1564
2112
  }
1565
2113
  catch {
1566
2114
  return false;
@@ -1570,32 +2118,46 @@ export function tryWriteOutcome(root, key, name, outcome) {
1570
2118
  * Samples one holder's process tree through one PowerShell child at below-normal priority.
1571
2119
  *
1572
2120
  * @remarks
1573
- * The child exits when its stdin closes, which {@link Sampler.stop} and the end of this process both
1574
- * do. A threshold, given for a light run, calls the breach handler once, on the first sample whose
1575
- * memory or process count passes it.
2121
+ * The child starts at arrival and readies while the ticket waits, so a holder starts its command
2122
+ * only after the child can answer at once. A {@link Sampler.sample} call starts one sample at once;
2123
+ * after the first, the child also samples every {@link SAMPLE_MS}. The child exits when its stdin
2124
+ * closes, which {@link Sampler.stop} and the end of this process both do. A threshold, given for a
2125
+ * light run, calls the breach handler once with the launcher's id, on the first sample before
2126
+ * {@link Sampler.seal} whose memory or process count passes it.
1576
2127
  */
1577
2128
  export class Sampler {
1578
2129
  #child;
1579
2130
  #closed;
1580
- #floor;
2131
+ #ready = Promise.withResolvers();
2132
+ #waiters = new Map();
1581
2133
  #threshold;
1582
2134
  #breach;
1583
2135
  #seeds = [];
2136
+ #floor;
2137
+ #ceiling;
1584
2138
  #tally = { cpu: new Map(), memory: 0, processes: 0 };
1585
2139
  #breached = false;
2140
+ #asked = 0;
2141
+ #answered = 0;
1586
2142
  /**
1587
2143
  * Starts the sampler.
1588
2144
  *
1589
- * @param floor - The earliest creation date the tree can carry.
1590
2145
  * @param threshold - The light run's threshold, or undefined for a heavy run.
1591
- * @param breach - Called once when a sample passes the threshold.
2146
+ * @param breach - Called once with the launcher's id when a sample passes the threshold. The
2147
+ * launcher is the one seed the lane holds a live handle on until it exits, so ending its tree
2148
+ * reaches the command and never a reused id.
2149
+ * @param command - The PowerShell text the child runs, for a proof. Default: {@link SAMPLER_COMMAND}.
1592
2150
  */
1593
- constructor(floor, threshold, breach) {
1594
- this.#floor = floor;
2151
+ constructor(threshold, breach, command = SAMPLER_COMMAND) {
1595
2152
  this.#threshold = threshold;
1596
2153
  this.#breach = breach;
1597
- this.#child = spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', SAMPLER_COMMAND], { stdio: ['pipe', 'pipe', 'ignore'], windowsHide: true });
1598
- this.#closed = waitForClose(this.#child).then(() => undefined);
2154
+ this.#child = spawn('powershell.exe', ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', command], { stdio: ['pipe', 'pipe', 'ignore'], windowsHide: true });
2155
+ this.#closed = waitForClose(this.#child).then(() => {
2156
+ this.#ready.resolve(false);
2157
+ for (const resolve of this.#waiters.values())
2158
+ resolve(undefined);
2159
+ this.#waiters.clear();
2160
+ });
1599
2161
  this.#child.stdin?.on('error', () => undefined);
1600
2162
  if (this.#child.pid !== undefined)
1601
2163
  lowerPriority(this.#child.pid);
@@ -1617,43 +2179,135 @@ export class Sampler {
1617
2179
  get breached() {
1618
2180
  return this.#breached;
1619
2181
  }
2182
+ /**
2183
+ * Waits until the child can sample at once, within a budget.
2184
+ *
2185
+ * @param budget - The longest wait in milliseconds.
2186
+ * @returns A promise of true when the child readied; false when it ended first or the budget ran out.
2187
+ */
2188
+ async ready(budget) {
2189
+ return (await waitForBound(this.#ready.promise, budget)) ?? false;
2190
+ }
1620
2191
  /**
1621
2192
  * Names the ids whose trees later samples read.
1622
2193
  *
1623
2194
  * @param seeds - The launcher id and, once known, the command id.
2195
+ * @param floor - The earliest creation date the tree can carry.
1624
2196
  */
1625
- seed(seeds) {
2197
+ seed(seeds, floor) {
1626
2198
  this.#seeds = seeds;
2199
+ this.#floor = floor;
2200
+ }
2201
+ /**
2202
+ * Marks the launcher's exit: a later sample reads no member created after it and triggers no
2203
+ * breach, so a reused id after the exit is never ended.
2204
+ *
2205
+ * @param ceiling - When the launcher exited, in epoch milliseconds.
2206
+ */
2207
+ seal(ceiling) {
2208
+ this.#ceiling = ceiling;
2209
+ }
2210
+ /**
2211
+ * Starts one sample at once.
2212
+ *
2213
+ * @param budget - The longest wait in milliseconds for the answer. Default: no bound.
2214
+ * @returns A promise of every row the sample read, taken after this call; undefined when the
2215
+ * child ends first, cannot take the request, or does not answer within the budget.
2216
+ */
2217
+ sample(budget) {
2218
+ const stdin = this.#child.stdin;
2219
+ if (stdin === null ||
2220
+ stdin.writableEnded ||
2221
+ this.#child.pid === undefined ||
2222
+ this.#child.exitCode !== null ||
2223
+ this.#child.signalCode !== null) {
2224
+ return Promise.resolve(undefined);
2225
+ }
2226
+ this.#asked += 1;
2227
+ const answer = Promise.withResolvers();
2228
+ this.#waiters.set(this.#asked, answer.resolve);
2229
+ stdin.write(SAMPLE_BYTE);
2230
+ return budget === undefined ? answer.promise : waitForBound(answer.promise, budget);
2231
+ }
2232
+ /**
2233
+ * Samples back to back until a time or an abort, one sample after the previous one answers.
2234
+ *
2235
+ * @param until - The epoch millisecond after which no further sample starts.
2236
+ * @param signal - Ends the burst after the sample in flight.
2237
+ * @returns A promise that resolves when the burst ends.
2238
+ */
2239
+ async burst(until, signal) {
2240
+ const rows = await this.sample();
2241
+ if (rows === undefined || signal.aborted || Date.now() >= until)
2242
+ return;
2243
+ await this.burst(until, signal);
1627
2244
  }
1628
2245
  /**
1629
- * Closes the sampler's stdin, which ends it.
2246
+ * Closes the sampler's stdin, which ends it, and ends the child at once when it has not exited
2247
+ * within {@link HANDOVER_MS}.
1630
2248
  *
1631
2249
  * @returns A promise that resolves when the sampler has exited.
1632
2250
  */
1633
- stop() {
2251
+ async stop() {
2252
+ this.#child.stdin?.end();
2253
+ const exited = await waitForBound(this.#closed.then(() => true), HANDOVER_MS);
2254
+ if (exited === undefined)
2255
+ await this.destroy();
2256
+ }
2257
+ /**
2258
+ * Ends the child at once, for a sampler that did not ready and might not read its stdin.
2259
+ *
2260
+ * @returns A promise that resolves when the child has exited.
2261
+ */
2262
+ destroy() {
1634
2263
  this.#child.stdin?.end();
2264
+ this.#child.kill();
1635
2265
  return this.#closed;
1636
2266
  }
2267
+ // A sample a byte asked for answers the oldest open request, because the child answers bytes in order.
1637
2268
  #read(line) {
1638
- const members = selectMembers(parseGauges(line), this.#seeds, this.#floor, Date.now());
2269
+ if (line === READY_LINE) {
2270
+ this.#ready.resolve(true);
2271
+ return;
2272
+ }
2273
+ const sample = parseSample(line);
2274
+ if (sample === undefined)
2275
+ return;
2276
+ if (sample.requested) {
2277
+ this.#answered += 1;
2278
+ this.#waiters.get(this.#answered)?.(sample.gauges);
2279
+ this.#waiters.delete(this.#answered);
2280
+ }
2281
+ if (this.#floor === undefined)
2282
+ return;
2283
+ const members = selectMembers(sample.gauges, this.#seeds, this.#floor, this.#ceiling ?? Date.now());
1639
2284
  this.#tally = tallySample(this.#tally, members);
1640
2285
  const threshold = this.#threshold;
1641
2286
  if (threshold === undefined ||
2287
+ this.#ceiling !== undefined ||
1642
2288
  this.#breached ||
1643
2289
  (this.#tally.memory <= threshold.memory && this.#tally.processes <= threshold.processes)) {
1644
2290
  return;
1645
2291
  }
2292
+ const [launcher] = this.#seeds;
2293
+ if (launcher === undefined)
2294
+ return;
1646
2295
  this.#breached = true;
1647
- this.#breach();
2296
+ this.#breach(launcher);
1648
2297
  }
1649
2298
  }
1650
2299
  /**
1651
2300
  * Runs the command as the holder, reads the tree at handover, and releases.
1652
2301
  *
1653
2302
  * @remarks
1654
- * A measured holder samples its tree and writes the run's record before it releases, so the
1655
- * command's next arrival reads it. A light holder lowers its own priority before the spawn, and ends
1656
- * its tree when a sample passes the threshold.
2303
+ * A measured holder starts its command after its sampler readies, samples the tree back to back
2304
+ * through the command's first {@link SAMPLE_MS} and once every {@link SAMPLE_MS} after, reads the
2305
+ * handover through one more sample, and writes the run's record before it releases, so the command's
2306
+ * next arrival reads it. When that sample lists a member, the handover reads, kills, and reads again
2307
+ * through fresh snapshots, each a second PowerShell. A sampler that does not ready within
2308
+ * {@link READY_MS} is destroyed, and the command runs unmeasured and records nothing. A record that
2309
+ * opened a key prunes the history after the release. A light holder lowers its own priority before
2310
+ * the spawn, and ends its tree when a sample passes the threshold.
1657
2311
  *
1658
2312
  * @param options - The run.
1659
2313
  * @param launcher - The launcher's path.
@@ -1661,17 +2315,24 @@ export class Sampler {
1661
2315
  * @param measure - What a measured holder needs, or undefined when no limits apply.
1662
2316
  * @param token - This process's endpoint, which holds after the run record exists and leaves before
1663
2317
  * the run record is removed.
2318
+ * @param sampler - The measured holder's sampler, started at arrival; the caller stops it.
1664
2319
  * @returns The launcher's code; 1 when a signal ended it; 69 when a light run passed its threshold;
1665
2320
  * 70 when the tree still reads as present or the ticket could not be removed; 75 when the launcher
1666
2321
  * could not start, the priority could not be lowered, or the run record could not be written.
1667
2322
  */
1668
- export async function runHolder(options, launcher, sequence, measure, token) {
2323
+ export async function runHolder(options, launcher, sequence, measure, token, sampler) {
1669
2324
  const { root } = options;
1670
2325
  if (measure?.light !== undefined && !lowerPriority(process.pid)) {
1671
2326
  releaseTicket(root, sequence);
1672
2327
  console.error('lane: the host refused the light run its below-normal priority');
1673
2328
  return 75;
1674
2329
  }
2330
+ const measured = sampler !== undefined && (await sampler.ready(READY_MS));
2331
+ if (sampler !== undefined && !measured) {
2332
+ await sampler.destroy();
2333
+ console.error(`lane: the sampler did not ready within ${String(READY_MS)} ms; ${quote(options.label)} runs unmeasured`);
2334
+ }
2335
+ const active = measured ? sampler : undefined;
1675
2336
  const started = Date.now();
1676
2337
  if (!tryWriteRun(root, sequence, { started, launcher: undefined, command: undefined })) {
1677
2338
  const refusal = releaseTicket(root, sequence);
@@ -1688,12 +2349,15 @@ export async function runHolder(options, launcher, sequence, measure, token) {
1688
2349
  return 75;
1689
2350
  }
1690
2351
  tryWriteRun(root, sequence, { started, launcher: id, command: undefined });
1691
- const sampler = measure === undefined
1692
- ? undefined
1693
- : new Sampler(started - CLOCK_ALLOWANCE_MS, measure.light === undefined ? undefined : measure.limits.threshold, () => killMembers([id]));
1694
- sampler?.seed([id]);
2352
+ const floor = started - CLOCK_ALLOWANCE_MS;
2353
+ const early = new AbortController();
2354
+ active?.seed([id], floor);
1695
2355
  const unwatch = watchSignals(() => killMembers([id]));
1696
2356
  const closed = waitForClose(child);
2357
+ const exited = waitForExit(child).then((at) => {
2358
+ active?.seal(at);
2359
+ return at;
2360
+ });
1697
2361
  if (child.stdout !== null) {
1698
2362
  const lines = createInterface({ input: child.stdout, crlfDelay: Infinity });
1699
2363
  lines.on('error', () => undefined);
@@ -1703,22 +2367,34 @@ export async function runHolder(options, launcher, sequence, measure, token) {
1703
2367
  if (command === undefined)
1704
2368
  return;
1705
2369
  tryWriteRun(root, sequence, { started, launcher: id, command });
1706
- sampler?.seed([id, command]);
2370
+ active?.seed([id, command], floor);
2371
+ void active?.burst(Date.now() + SAMPLE_MS, early.signal);
1707
2372
  });
1708
2373
  }
1709
2374
  const code = await closed;
2375
+ const ended = await exited;
2376
+ early.abort();
1710
2377
  unwatch();
1711
- const ended = Date.now();
1712
- const stopped = sampler?.stop();
1713
2378
  const run = readRun(root, sequence);
1714
- const sweep = run === 'absent' || run === 'unread'
2379
+ const rows = typeof run === 'object' ? await active?.sample(HANDOVER_MS) : undefined;
2380
+ const hung = active !== undefined && typeof run === 'object' && rows === undefined;
2381
+ if (hung) {
2382
+ await active.destroy();
2383
+ console.error(`lane: the sampler did not answer the handover within ${String(HANDOVER_MS)} ms; ${quote(options.label)} records nothing`);
2384
+ }
2385
+ const quick = rows !== undefined && typeof run === 'object' ? selectTree(rows, run, ended) : undefined;
2386
+ const sweep = typeof run !== 'object'
1715
2387
  ? { gone: false, members: [] }
1716
- : sweepTree(() => readTree(run, ended), killMembers, KILL_BUDGET);
1717
- const breached = sampler?.breached === true;
2388
+ : quick?.length === 0
2389
+ ? { gone: true, members: [] }
2390
+ : sweepTree(() => readTree(run, ended), killMembers, KILL_BUDGET);
2391
+ const stopped = active?.stop();
2392
+ const breached = active?.breached === true;
1718
2393
  const result = !sweep.gone ? HELD_CODE : breached ? BREACH_CODE : (code ?? 1);
1719
- if (measure !== undefined && sampler !== undefined) {
1720
- tryWriteOutcome(root, measure.key, renderOutcomeName(ended, measure.token), buildOutcome(sampler.tally, ended - started, result));
1721
- }
2394
+ const opened = measure !== undefined &&
2395
+ active !== undefined &&
2396
+ !hung &&
2397
+ tryWriteOutcome(root, measure.key, renderOutcomeName(ended, measure.token), buildOutcome(active.tally, ended - started, result));
1722
2398
  if (!sweep.gone) {
1723
2399
  console.error(`lane: the tree of ${quote(options.label)} still reads as ${sweep.members.length === 0 ? 'unread' : `present: ${sweep.members.join(', ')}`}; the lane stays held by ${renderName(sequence, TICKET_SUFFIX)} and ${renderName(sequence, RUN_SUFFIX)} under ${root}`);
1724
2400
  await stopped;
@@ -1726,6 +2402,10 @@ export async function runHolder(options, launcher, sequence, measure, token) {
1726
2402
  }
1727
2403
  token?.leave();
1728
2404
  const refusal = releaseTicket(root, sequence);
2405
+ const prune = opened ? pruneHistory(root, Date.now()) : undefined;
2406
+ if (prune !== undefined && prune.skipped.length > 0) {
2407
+ console.error(`lane: the history prune under ${root} skipped ${String(prune.skipped.length)} entries it could not list or remove, such as ${quote(prune.skipped.join(', '))}`);
2408
+ }
1729
2409
  await stopped;
1730
2410
  if (refusal !== undefined) {
1731
2411
  console.error(`lane: removing ${renderName(sequence, TICKET_SUFFIX)} reported ${refusal}`);
@@ -1741,7 +2421,9 @@ export async function runHolder(options, launcher, sequence, measure, token) {
1741
2421
  *
1742
2422
  * @remarks
1743
2423
  * A host other than Windows has no sampler, so it measures nothing and every ticket there is heavy.
1744
- * A `--solo` run is heavy whatever its command reads.
2424
+ * A `--solo` run is heavy whatever its command reads. A `mutate` run is keyed without its edits
2425
+ * file and seeded by its wrapped command; {@link decideDirectory} keeps it apart from the tickets of
2426
+ * its working directory.
1745
2427
  *
1746
2428
  * @param options - The run.
1747
2429
  * @param token - This process's token.
@@ -1757,10 +2439,12 @@ export function readMeasure(options, token) {
1757
2439
  }
1758
2440
  if (limits === 'absent' || limits === 'unread')
1759
2441
  return undefined;
1760
- const key = renderKey(realpathSync(process.cwd()), options.command);
1761
- const light = options.solo
1762
- ? undefined
1763
- : classifyLight(readSeed(options.command), readOutcomes(options.root, key), limits);
2442
+ const key = renderKey(normalizeDirectory(process.cwd()), normalizeCommand(options.command));
2443
+ if (options.solo)
2444
+ return { limits, key, token, light: undefined };
2445
+ const mutation = extractMutation(options.command);
2446
+ const seed = readSeed(mutation ?? options.command);
2447
+ const light = classifyLight(seed, readOutcomes(options.root, key), limits);
1764
2448
  return { limits, key, token, light };
1765
2449
  }
1766
2450
  /**
@@ -1777,24 +2461,33 @@ export async function enterLane(options, launcher, tokenId, token) {
1777
2461
  try {
1778
2462
  mkdirSync(root, { recursive: true });
1779
2463
  const measure = readMeasure(options, tokenId);
1780
- await token.listen(renderEndpoint(root, tokenId));
1781
- writeStage(root, buildTicket(tokenId, options.label, measure?.light, options.solo));
1782
- const sequence = linkStage(root, tokenId);
1783
- removeFile(join(root, `${tokenId}${STAGE_SUFFIX}`));
1784
- token.publish();
1785
- const unwatch = watchSignals(() => {
2464
+ const sampler = measure === undefined
2465
+ ? undefined
2466
+ : new Sampler(measure.light === undefined ? undefined : measure.limits.threshold, (pid) => killMembers([pid]));
2467
+ try {
2468
+ await token.listen(renderEndpoint(root, tokenId));
2469
+ const edits = extractMutation(options.command) !== undefined || matchesRestore(options.command);
2470
+ writeStage(root, buildTicket(tokenId, options.label, measure?.light, options.solo, edits));
2471
+ const sequence = linkStage(root, tokenId);
2472
+ removeFile(join(root, `${tokenId}${STAGE_SUFFIX}`));
2473
+ token.publish();
2474
+ const unwatch = watchSignals(() => {
2475
+ removeFile(join(root, renderName(sequence, TICKET_SUFFIX)));
2476
+ removeFile(renderEndpoint(root, tokenId));
2477
+ process.exit(75);
2478
+ });
2479
+ const refusal = await waitForTurn(root, sequence, tokenId, measure?.limits);
2480
+ unwatch();
2481
+ if (refusal === undefined) {
2482
+ return await runHolder(options, launcher, sequence, measure, token, sampler);
2483
+ }
1786
2484
  removeFile(join(root, renderName(sequence, TICKET_SUFFIX)));
1787
- removeFile(renderEndpoint(root, tokenId));
1788
- process.exit(75);
1789
- });
1790
- const refusal = await waitForTurn(root, sequence, tokenId, measure?.limits);
1791
- unwatch();
1792
- if (refusal === undefined) {
1793
- return await runHolder(options, launcher, sequence, measure, token);
2485
+ console.error(`lane: ${refusal}`);
2486
+ return 75;
2487
+ }
2488
+ finally {
2489
+ await sampler?.stop();
1794
2490
  }
1795
- removeFile(join(root, renderName(sequence, TICKET_SUFFIX)));
1796
- console.error(`lane: ${refusal}`);
1797
- return 75;
1798
2491
  }
1799
2492
  catch (error) {
1800
2493
  console.error(`lane: the queue under ${root} refused the run: ${String(error)}`);
@@ -1833,6 +2526,7 @@ export async function readStatusRow(root, entry) {
1833
2526
  pid: ticket?.pid,
1834
2527
  light: ticket?.light !== undefined,
1835
2528
  solo: ticket?.solo === true,
2529
+ edits: ticket?.edits === true,
1836
2530
  };
1837
2531
  if (ticket === undefined || describeForeign(ticket) !== undefined) {
1838
2532
  return { ...fields, state: 'unread', holding: false };
@@ -1867,7 +2561,7 @@ export function renderStatus(status) {
1867
2561
  return [
1868
2562
  `holder: ${status.holder === undefined ? 'none' : quote(status.holder.label ?? 'unread')}`,
1869
2563
  `light: ${lights.length === 0 ? 'none' : lights.map((row) => quote(row.label ?? 'unread')).join(', ')}`,
1870
- ...status.tickets.map((row) => `${renderName(row.sequence, TICKET_SUFFIX)} ${row.state} ${renderLane(row)}${row.holding ? ' holding' : ''} ${quote(row.label ?? 'unread')} pid ${String(row.pid)}`),
2564
+ ...status.tickets.map((row) => `${renderName(row.sequence, TICKET_SUFFIX)} ${row.state} ${renderLane(row)}${row.edits ? ' edits' : ''}${row.holding ? ' holding' : ''} ${quote(row.label ?? 'unread')} pid ${String(row.pid)}`),
1871
2565
  ].join('\n');
1872
2566
  }
1873
2567
  /**