pi-durable-subagents 1.5.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/README.md +69 -14
  3. package/dist/agent/capabilities.js +5 -4
  4. package/dist/agent/child/live.js +2 -1
  5. package/dist/agent/exact/capture.js +3 -2
  6. package/dist/agent/main/snapshots.js +10 -9
  7. package/dist/agent/main.js +2 -1
  8. package/dist/cli/chaos/stack.js +53 -21
  9. package/dist/cli/control.js +4 -3
  10. package/dist/cli/doctor.js +3 -1
  11. package/dist/cli/drill/index.js +35 -17
  12. package/dist/cli/hold.js +221 -16
  13. package/dist/cli/restart.js +14 -2
  14. package/dist/cli/service.js +77 -2
  15. package/dist/cli/smoke.js +10 -6
  16. package/dist/compat/agents.js +46 -13
  17. package/dist/events/log.js +33 -11
  18. package/dist/kernel/cache.js +3 -2
  19. package/dist/kernel/fsx.js +203 -0
  20. package/dist/kernel/ids.js +11 -0
  21. package/dist/kernel/journal.js +42 -25
  22. package/dist/kernel/mailbox.js +7 -4
  23. package/dist/orchestrator/engine.js +49 -46
  24. package/dist/orchestrator/evaluator-client.js +11 -3
  25. package/dist/orchestrator/executor/command.js +21 -6
  26. package/dist/orchestrator/executor/effects/gate.js +291 -56
  27. package/dist/orchestrator/executor/effects/index.js +3 -4
  28. package/dist/orchestrator/executor/effects/output.js +9 -5
  29. package/dist/orchestrator/executor/effects/prepare.js +69 -35
  30. package/dist/orchestrator/executor/effects/worktree-path.js +102 -0
  31. package/dist/orchestrator/executor/ended.js +7 -3
  32. package/dist/orchestrator/executor/index.js +221 -63
  33. package/dist/orchestrator/executor/memory.js +15 -0
  34. package/dist/orchestrator/executor/session.js +4 -3
  35. package/dist/orchestrator/executor/sweep.js +34 -1
  36. package/dist/orchestrator/executor/worktree.js +7 -1
  37. package/dist/orchestrator/main.js +4 -2
  38. package/dist/orchestrator/reader-ledger.js +3 -2
  39. package/dist/orchestrator/settled.js +2 -1
  40. package/dist/orchestrator/snapshot.js +29 -22
  41. package/dist/orchestrator/stats.js +2 -1
  42. package/dist/orchestrator/store.js +3 -2
  43. package/dist/platform/cmdline.js +3 -0
  44. package/dist/platform/command.js +184 -20
  45. package/dist/platform/containment.js +204 -40
  46. package/dist/platform/job.js +1404 -0
  47. package/dist/platform/launch.js +157 -23
  48. package/dist/platform/lease.js +351 -32
  49. package/dist/platform/lock.js +464 -16
  50. package/dist/platform/proctable.js +31 -2
  51. package/dist/platform/windows.js +642 -0
  52. package/dist/requests.js +1 -1
  53. package/dist/ui/data.js +7 -6
  54. package/dist/ui/session.js +6 -5
  55. package/package.json +3 -3
@@ -0,0 +1,1404 @@
1
+ // Windows command attempts run inside a kernel-owned group: a Job Object created for one attempt, whose only handle is
2
+ // held by a small owner process and never inherited. The command's wrapper is created suspended, assigned to the group
3
+ // and only then resumed, so nothing it starts can ever be outside the group; with JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE the
4
+ // kernel terminates every process left in the group when that handle closes, which happens when the wrapper ends, when
5
+ // the owner is killed, and when the owner crashes. A command attempt therefore cannot outlive its wrapper by a
6
+ // descendant, and the orchestrator (or a successor that adopted the attempt) can never start a second attempt while
7
+ // processes of the first can still act.
8
+ //
9
+ // The owner is a standalone .NET Framework winexe compiled from the C# below with the C# compiler that ships with every
10
+ // supported Windows (csc.exe under %SystemRoot%\Microsoft.NET\Framework64 or Framework, v4.0.30319): Node has no Job
11
+ // Object API, and this adds no npm dependency and no file to the package. A PowerShell helper was tried first and does
12
+ // not work: a detached spawn gives it no console, and PowerShell 5.1 (and pwsh) then quietly exit 0 without running a
13
+ // script (PowerShell#28383; Windows CI 45039418985 measured it), while a non-detached child lands in libuv's
14
+ // kill-with-parent job and would end the attempt with the orchestrator. A compiled winexe has neither problem: it needs
15
+ // no console, Node spawns it detached with windowsHide, and the group's handle lives in it rather than in the
16
+ // orchestrator. A cmd.exe relay or a two-process handle handoff would each add a visible window or a second owner; this
17
+ // keeps one process.
18
+ //
19
+ // Each launch compiles into its own private directory inside the attempt directory (a fresh random name), so a stale
20
+ // executable from an earlier attempt can never be picked up, and nothing is shared between attempts or calls. The
21
+ // compilation is the expensive part of a command start, so it is staged (prepareJob) *before* the attempt's durable
22
+ // intent is recorded: bounded and cancellable, and until it finishes the attempt directory holds only inert files (a source
23
+ // file, an executable, the spec) and the journal holds no intent, so an orchestrator that dies while the compiler runs
24
+ // leaves nothing that can act and an attempt that is unambiguously prelaunch. A stop, a retirement or the orchestrator's
25
+ // exit during the compilation cancels it (the compiler process is ended and what it wrote is removed) and is never
26
+ // recorded as a failure of the attempt. The executor's proceed/stop gate is still called once more, after the
27
+ // preparation and immediately before the spawn (no await between the two), so a revocation during the compilation starts
28
+ // nothing. A missing compiler, a compiler failure or a missing executable fails the start closed: no group, no wrapper,
29
+ // no command, and the recorded reason travels with the attempt -- kill-on-close and the single-rerun semantics are never
30
+ // weakened.
31
+ //
32
+ // The spec is ASCII lines of base64-encoded UTF-16LE fields (jobSpecText), so no code page, quoting rule, BOM or unpaired
33
+ // surrogate can change a Unicode path, a curly quote or an environment value; the owner turns every line back into its
34
+ // exact UTF-16 code units -- each byte pair is one char, never through a decoder fallback that could substitute -- and
35
+ // refuses a field that is not a whole number of code units, or that carries a NUL. The C# source is ASCII-only for the
36
+ // same reason: csc.exe reads a file without a byte order mark in the ANSI code page.
37
+ //
38
+ // Observation is fail-closed: before a group exists the orchestrator waits for the owner's `group` record (the suspended
39
+ // child's pid, written before the child may run) and starts no attempt when it does not arrive or cannot be read; the
40
+ // owner never resumes the child unless CreateJobObject, SetInformationJobObject, CreateProcess,
41
+ // AssignProcessToJobObject and IsProcessInJob all succeeded, and it writes `start-error` when they did not. The owner's
42
+ // own identity is recorded with the attempt, so its absence from the process table proves the group is closed.
43
+ //
44
+ // The handshake has two windows a crash or a slow machine can cut into, and both must keep a second attempt from starting
45
+ // while the first can still act. The first is the owner's own startup: no group record and no wrapper exist yet, so the
46
+ // attempt is found by the tag in the owner's command line (`DSA_EXEC=<id>`, the same tag a POSIX command carries in its
47
+ // environment) -- the owner is passed it in its argv, never only in an environment a Windows process table cannot read.
48
+ // The second is the failure path: a handshake that cannot be completed ends the owner and reports a refusal only once the
49
+ // owner has ended (its exit closes the group's only handle, so nothing of the attempt can act); when the end cannot be
50
+ // confirmed -- the kill failed, or the owner is still there at the deadline -- the attempt is adopted instead
51
+ // (JobSpawned.uncertain), its identity travels to the orchestrator, and the call keeps the attempt tracked, so nothing
52
+ // starts a second attempt until a scan finds the first one gone.
53
+ import { execFile, spawn } from "node:child_process";
54
+ import { randomBytes } from "node:crypto";
55
+ import { closeSync, existsSync, openSync, readFileSync } from "node:fs";
56
+ import { mkdir, open, readFile, rename, rm, writeFile } from "node:fs/promises";
57
+ import { join } from "node:path";
58
+ import { setTimeout as delay } from "node:timers/promises";
59
+ import { retryWinSharing, retryWinSharingSync, writeFileAtomic } from "../kernel/fsx.js";
60
+ import { dword, helperEnv, isWinStart, killProcess, sameCreation, systemRoot, winProcessRows, winTag, winTagArg } from "./windows.js";
61
+ export { sameCreation };
62
+ /** The owner type: exported for the packaging check (the compiled name carries it; nothing separate is shipped). */
63
+ export const JOB_HOST_MARKER = "DsaJob";
64
+ /** The owner's source: compiled per launch into the attempt's private host directory, never written as a package file. */
65
+ export const JOB_HOST_SOURCE = `using System;
66
+ using System.Globalization;
67
+ using System.IO;
68
+ using System.Runtime.InteropServices;
69
+ using System.Text;
70
+
71
+ public static class DsaJob
72
+ {
73
+ const uint CREATE_SUSPENDED = 0x00000004;
74
+ const uint CREATE_UNICODE_ENVIRONMENT = 0x00000400;
75
+ const uint DETACHED_PROCESS = 0x00000008;
76
+ const uint CREATE_NEW_PROCESS_GROUP = 0x00000200;
77
+ const uint STARTF_USESTDHANDLES = 0x00000100;
78
+ // The wrapper inherits the three standard handles by name (a one-entry proc-thread attribute list), never "every
79
+ // inheritable handle this host happens to hold".
80
+ const uint EXTENDED_STARTUPINFO_PRESENT = 0x00080000;
81
+ const int PROC_THREAD_ATTRIBUTE_HANDLE_LIST = 0x00020002;
82
+ const int JobObjectBasicAccountingInformation = 1;
83
+ const int JobObjectExtendedLimitInformation = 9;
84
+ const uint JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x00002000;
85
+ const int STD_INPUT_HANDLE = -10;
86
+ const int STD_OUTPUT_HANDLE = -11;
87
+ const int STD_ERROR_HANDLE = -12;
88
+ const uint DUPLICATE_SAME_ACCESS = 0x00000002;
89
+ const uint MOVEFILE_REPLACE_EXISTING = 0x00000001;
90
+ const int ERROR_ACCESS_DENIED = 5;
91
+ const int ERROR_INVALID_HANDLE = 6;
92
+ const int ERROR_SHARING_VIOLATION = 32;
93
+ const int ERROR_LOCK_VIOLATION = 33;
94
+ const int ERROR_BUSY = 170;
95
+ const uint GENERIC_READ = 0x80000000;
96
+ const uint FILE_APPEND_DATA = 0x00000004;
97
+ const uint FILE_SHARE_READ = 0x00000001;
98
+ const uint FILE_SHARE_WRITE = 0x00000002;
99
+ const uint FILE_SHARE_DELETE = 0x00000004;
100
+ const uint OPEN_EXISTING = 3;
101
+ const uint OPEN_ALWAYS = 4;
102
+ const uint FILE_ATTRIBUTE_NORMAL = 0x00000080;
103
+ const uint WAIT_OBJECT_0 = 0x00000000;
104
+ const uint WAIT_TIMEOUT = 0x00000102;
105
+ static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
106
+
107
+ [StructLayout(LayoutKind.Sequential)]
108
+ struct SECURITY_ATTRIBUTES
109
+ {
110
+ public int nLength;
111
+ public IntPtr lpSecurityDescriptor;
112
+ public int bInheritHandle;
113
+ }
114
+
115
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
116
+ struct STARTUPINFO
117
+ {
118
+ public int cb;
119
+ public string lpReserved;
120
+ public string lpDesktop;
121
+ public string lpTitle;
122
+ public int dwX;
123
+ public int dwY;
124
+ public int dwXSize;
125
+ public int dwYSize;
126
+ public int dwXCountChars;
127
+ public int dwYCountChars;
128
+ public int dwFillAttribute;
129
+ public int dwFlags;
130
+ public short wShowWindow;
131
+ public short cbReserved2;
132
+ public IntPtr lpReserved2;
133
+ public IntPtr hStdInput;
134
+ public IntPtr hStdOutput;
135
+ public IntPtr hStdError;
136
+ }
137
+
138
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
139
+ struct STARTUPINFOEX
140
+ {
141
+ public STARTUPINFO StartupInfo;
142
+ public IntPtr lpAttributeList;
143
+ }
144
+
145
+ [StructLayout(LayoutKind.Sequential)]
146
+ struct PROCESS_INFORMATION
147
+ {
148
+ public IntPtr hProcess;
149
+ public IntPtr hThread;
150
+ public int dwProcessId;
151
+ public int dwThreadId;
152
+ }
153
+
154
+ [StructLayout(LayoutKind.Sequential)]
155
+ struct JOBOBJECT_BASIC_LIMIT_INFORMATION
156
+ {
157
+ public long PerProcessUserTimeLimit;
158
+ public long PerJobUserTimeLimit;
159
+ public uint LimitFlags;
160
+ public UIntPtr MinimumWorkingSetSize;
161
+ public UIntPtr MaximumWorkingSetSize;
162
+ public uint ActiveProcessLimit;
163
+ public UIntPtr Affinity;
164
+ public uint PriorityClass;
165
+ public uint SchedulingClass;
166
+ }
167
+
168
+ [StructLayout(LayoutKind.Sequential)]
169
+ struct IO_COUNTERS
170
+ {
171
+ public ulong ReadOperationCount;
172
+ public ulong WriteOperationCount;
173
+ public ulong OtherOperationCount;
174
+ public ulong ReadTransferCount;
175
+ public ulong WriteTransferCount;
176
+ public ulong OtherTransferCount;
177
+ }
178
+
179
+ [StructLayout(LayoutKind.Sequential)]
180
+ struct JOBOBJECT_EXTENDED_LIMIT_INFORMATION
181
+ {
182
+ public JOBOBJECT_BASIC_LIMIT_INFORMATION BasicLimitInformation;
183
+ public IO_COUNTERS IoInfo;
184
+ public UIntPtr ProcessMemoryLimit;
185
+ public UIntPtr JobMemoryLimit;
186
+ public UIntPtr PeakProcessMemoryUsed;
187
+ public UIntPtr PeakJobMemoryUsed;
188
+ }
189
+
190
+ [StructLayout(LayoutKind.Sequential)]
191
+ struct JOBOBJECT_BASIC_ACCOUNTING_INFORMATION
192
+ {
193
+ public long TotalUserTime;
194
+ public long TotalKernelTime;
195
+ public long ThisPeriodTotalUserTime;
196
+ public long ThisPeriodTotalKernelTime;
197
+ public uint TotalPageFaultCount;
198
+ public uint TotalProcesses;
199
+ public uint ActiveProcesses;
200
+ public uint TotalTerminatedProcesses;
201
+ }
202
+
203
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
204
+ static extern IntPtr CreateJobObjectW(IntPtr attributes, string name);
205
+ [DllImport("kernel32.dll", SetLastError = true)]
206
+ static extern bool SetInformationJobObject(IntPtr job, int infoClass, ref JOBOBJECT_EXTENDED_LIMIT_INFORMATION info, uint length);
207
+ [DllImport("kernel32.dll", SetLastError = true)]
208
+ static extern bool QueryInformationJobObject(IntPtr job, int infoClass, out JOBOBJECT_BASIC_ACCOUNTING_INFORMATION info, uint length, IntPtr returnLength);
209
+ [DllImport("kernel32.dll", SetLastError = true)]
210
+ static extern bool TerminateJobObject(IntPtr job, uint exitCode);
211
+ [DllImport("kernel32.dll", SetLastError = true)]
212
+ static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);
213
+ [DllImport("kernel32.dll", SetLastError = true)]
214
+ static extern bool IsProcessInJob(IntPtr process, IntPtr job, out bool result);
215
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
216
+ static extern bool CreateProcessW(string application, string commandLine, IntPtr processAttributes, IntPtr threadAttributes,
217
+ bool inheritHandles, uint flags, IntPtr environment, string currentDirectory, ref STARTUPINFOEX startup, out PROCESS_INFORMATION info);
218
+ [DllImport("kernel32.dll", SetLastError = true)]
219
+ static extern bool InitializeProcThreadAttributeList(IntPtr list, int count, int flags, ref IntPtr size);
220
+ [DllImport("kernel32.dll", SetLastError = true)]
221
+ static extern bool UpdateProcThreadAttribute(IntPtr list, uint flags, IntPtr attribute, IntPtr value, IntPtr size, IntPtr previous, IntPtr returnSize);
222
+ [DllImport("kernel32.dll")]
223
+ static extern void DeleteProcThreadAttributeList(IntPtr list);
224
+ [DllImport("kernel32.dll", SetLastError = true)]
225
+ static extern uint ResumeThread(IntPtr thread);
226
+ [DllImport("kernel32.dll", SetLastError = true)]
227
+ static extern uint WaitForSingleObject(IntPtr handle, uint milliseconds);
228
+ [DllImport("kernel32.dll", SetLastError = true)]
229
+ static extern bool GetExitCodeProcess(IntPtr process, out uint exitCode);
230
+ [DllImport("kernel32.dll", SetLastError = true)]
231
+ static extern bool TerminateProcess(IntPtr process, uint exitCode);
232
+ [DllImport("kernel32.dll", SetLastError = true)]
233
+ static extern bool CloseHandle(IntPtr handle);
234
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
235
+ static extern IntPtr CreateFileW(string name, uint access, uint share, ref SECURITY_ATTRIBUTES attributes, uint disposition, uint flags, IntPtr template);
236
+ [DllImport("kernel32.dll")]
237
+ static extern IntPtr GetCurrentProcess();
238
+ [DllImport("kernel32.dll")]
239
+ static extern uint GetCurrentProcessId();
240
+ [DllImport("kernel32.dll", SetLastError = true)]
241
+ static extern bool GetProcessTimes(IntPtr process, out long creation, out long exit, out long kernel, out long user);
242
+ [DllImport("kernel32.dll", SetLastError = true)]
243
+ static extern IntPtr GetStdHandle(int nStdHandle);
244
+ [DllImport("kernel32.dll", SetLastError = true)]
245
+ static extern bool SetStdHandle(int nStdHandle, IntPtr hHandle);
246
+ [DllImport("kernel32.dll", SetLastError = true)]
247
+ static extern bool DuplicateHandle(IntPtr hSourceProcessHandle, IntPtr hSourceHandle, IntPtr hTargetProcessHandle,
248
+ out IntPtr lpTargetHandle, uint dwDesiredAccess, bool bInheritHandle, uint dwOptions);
249
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
250
+ static extern bool MoveFileExW(string existingFileName, string newFileName, uint flags);
251
+ [DllImport("kernel32.dll")]
252
+ static extern void Sleep(uint milliseconds);
253
+
254
+ /** argv[0] is the attempt directory, argv[1] (ignored) the attempt's DSA_EXEC tag: a process-table scan finds
255
+ * the attempt by that tag while this host is starting, before it writes its group record. 126 means no directory,
256
+ * 125 a failure this host recorded in start-error; otherwise the wrapper's own exit status, the whole DWORD. */
257
+ public static int Main(string[] args)
258
+ {
259
+ if (args == null || args.Length < 1 || String.IsNullOrEmpty(args[0])) return 126;
260
+ string dir = args[0];
261
+ // Before anything else: its absence says this program never got to run; its identity is from this live handle.
262
+ try { WriteAtomic(Path.Combine(dir, "helper-begin"), ProcessIdentity(unchecked((int)GetCurrentProcessId()), GetCurrentProcess())); } catch (Exception) { }
263
+ string application, workingDirectory, logPath;
264
+ string[] arguments, environment;
265
+ try { ReadSpec(dir, out application, out workingDirectory, out logPath, out arguments, out environment); }
266
+ catch (Exception failure)
267
+ {
268
+ Fail(dir, "job spec", 0, failure.GetType().Name + ": " + failure.Message);
269
+ return 125;
270
+ }
271
+ // The wrapper's status is the kernel's DWORD and nothing else: a status above 0x7fffffff stays that status
272
+ // instead of turning into this host's own failure code. 125/126 are only ever written by a host that recorded
273
+ // why it did not get to run (or did not get) the wrapper, so a caller can tell the two apart.
274
+ uint status;
275
+ return Run(dir, application, arguments, workingDirectory, logPath, environment, out status) ? unchecked((int)status) : 125;
276
+ }
277
+
278
+ /** The attempt's spec: ASCII lines, one base64-encoded UTF-16LE field each, so no code page, quoting rule or
279
+ * surrogate can change it (Field decodes each one to its exact code units). DSAJOB1, exe, cwd, log, argument count,
280
+ * arguments, environment count, NAME=value entries. */
281
+ static void ReadSpec(string dir, out string application, out string workingDirectory, out string logPath, out string[] arguments, out string[] environment)
282
+ {
283
+ string path = Path.Combine(dir, "job.json");
284
+ string[] lines = File.ReadAllLines(path, Encoding.ASCII);
285
+ int at = 0;
286
+ if (lines.Length < 5 || lines[at++] != "DSAJOB1") throw new FormatException("unknown job spec header");
287
+ application = Field(lines[at++]);
288
+ workingDirectory = Field(lines[at++]);
289
+ logPath = Field(lines[at++]);
290
+ arguments = Fields(lines, ref at);
291
+ environment = Fields(lines, ref at);
292
+ if (at != lines.Length) throw new FormatException("trailing job spec fields");
293
+ try { File.Delete(path); } catch (Exception) { }
294
+ }
295
+
296
+ static string[] Fields(string[] lines, ref int at)
297
+ {
298
+ if (at >= lines.Length) throw new FormatException("truncated job spec");
299
+ int count;
300
+ if (!Int32.TryParse(lines[at++], NumberStyles.Integer, CultureInfo.InvariantCulture, out count) || count < 0 || count > 1048576)
301
+ throw new FormatException("bad job spec count");
302
+ if (lines.Length - at < count) throw new FormatException("truncated job spec fields");
303
+ string[] values = new string[count];
304
+ for (int i = 0; i < count; i++) values[i] = Field(lines[at++]);
305
+ return values;
306
+ }
307
+
308
+ static string Field(string line)
309
+ {
310
+ byte[] bytes = Convert.FromBase64String(line);
311
+ // A field is a whole number of UTF-16 code units, and jobSpecText wrote each pair as the code unit itself. An
312
+ // odd byte count is not a string any Win32 API could receive: refuse the spec instead of keeping the even
313
+ // prefix (a silently truncated path or argument). Nothing has been started yet.
314
+ if ((bytes.Length & 1) != 0) throw new FormatException("a job spec field is not a whole number of UTF-16 code units");
315
+ // Each byte pair is one char, copied as such: no decoding fallback can replace an unpaired surrogate the caller
316
+ // meant to pass, and the field reaches Win32 exactly as the caller wrote it.
317
+ char[] units = new char[bytes.Length / 2];
318
+ if (units.Length > 0) Buffer.BlockCopy(bytes, 0, units, 0, bytes.Length);
319
+ string value = new string(units);
320
+ // A NUL would end the field where a Win32 API (CreateProcess, the environment block) reads it, so a path or an
321
+ // argument would silently become a shorter one. Refuse the spec instead: nothing has been started yet.
322
+ if (value.IndexOf((char)0) >= 0) throw new FormatException("a job spec field contains a NUL character");
323
+ return value;
324
+ }
325
+
326
+ /** Run the wrapper inside a new group. True means the wrapper ran and the returned status is the full exit code the
327
+ * kernel gave it; false means this host failed, wrote start-error and started nothing (or killed what it started). */
328
+ static bool Run(string dir, string application, string[] arguments, string workingDirectory, string logPath, string[] environment, out uint status)
329
+ {
330
+ status = 0;
331
+ IntPtr job = IntPtr.Zero, output = IntPtr.Zero, errorHandle = IntPtr.Zero, input = IntPtr.Zero, block = IntPtr.Zero;
332
+ IntPtr list = IntPtr.Zero, inheritable = IntPtr.Zero;
333
+ // DeleteProcThreadAttributeList takes only a list InitializeProcThreadAttributeList produced.
334
+ bool listReady = false;
335
+ PROCESS_INFORMATION child = new PROCESS_INFORMATION();
336
+ bool started = false;
337
+ try
338
+ {
339
+ job = CreateJobObjectW(IntPtr.Zero, null);
340
+ if (job == IntPtr.Zero) return Fail(dir, "CreateJobObject", Marshal.GetLastWin32Error());
341
+ JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION();
342
+ limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
343
+ if (!SetInformationJobObject(job, JobObjectExtendedLimitInformation, ref limits, (uint)Marshal.SizeOf(typeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION))))
344
+ return Fail(dir, "SetInformationJobObject", Marshal.GetLastWin32Error());
345
+
346
+ SECURITY_ATTRIBUTES inherit = new SECURITY_ATTRIBUTES();
347
+ inherit.nLength = Marshal.SizeOf(typeof(SECURITY_ATTRIBUTES));
348
+ inherit.bInheritHandle = 1;
349
+ if (String.IsNullOrEmpty(logPath))
350
+ {
351
+ string stepName;
352
+ if (!OpenInheritedOrNul(STD_INPUT_HANDLE, GENERIC_READ, ref inherit, out input, out stepName))
353
+ return Fail(dir, stepName, Marshal.GetLastWin32Error());
354
+ if (!OpenInheritedOrNul(STD_OUTPUT_HANDLE, FILE_APPEND_DATA, ref inherit, out output, out stepName))
355
+ return Fail(dir, stepName, Marshal.GetLastWin32Error());
356
+ if (!OpenInheritedOrNul(STD_ERROR_HANDLE, FILE_APPEND_DATA, ref inherit, out errorHandle, out stepName))
357
+ return Fail(dir, stepName, Marshal.GetLastWin32Error());
358
+ }
359
+ else
360
+ {
361
+ // Two independent handles, one for stdout and one for stderr, each opened for append only (FILE_APPEND_DATA
362
+ // without FILE_WRITE_DATA): the kernel sends every write of each stream to the current end of the file, so
363
+ // the two streams interleave in the log without either overwriting the other. A shared handle or a seek to
364
+ // the end would let one stream's buffered output land on the other's (or on an earlier attempt's) bytes.
365
+ output = CreateFileW(logPath, FILE_APPEND_DATA, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, ref inherit, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, IntPtr.Zero);
366
+ if (output == INVALID_HANDLE_VALUE) return Fail(dir, "CreateFile " + logPath, Marshal.GetLastWin32Error());
367
+ errorHandle = CreateFileW(logPath, FILE_APPEND_DATA, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, ref inherit, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, IntPtr.Zero);
368
+ if (errorHandle == INVALID_HANDLE_VALUE) return Fail(dir, "CreateFile " + logPath, Marshal.GetLastWin32Error());
369
+ // stdin is empty: the command can never read from this host's (absent) console.
370
+ input = CreateFileW("NUL", GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, ref inherit, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, IntPtr.Zero);
371
+ if (input == INVALID_HANDLE_VALUE) return Fail(dir, "CreateFile NUL", Marshal.GetLastWin32Error());
372
+ }
373
+
374
+ // inheritHandles is true because the wrapper needs its standard handles, so the handle list is what says
375
+ // which: without it the child inherits every inheritable handle this host holds (the .NET runtime and the
376
+ // host that started it may keep some open), and a descriptor the command never asked for would reach it.
377
+ // The list names exactly the three standard handles, so the command's handle set is the one declared here.
378
+ IntPtr listSize = IntPtr.Zero;
379
+ InitializeProcThreadAttributeList(IntPtr.Zero, 1, 0, ref listSize);
380
+ if (listSize == IntPtr.Zero) return Fail(dir, "InitializeProcThreadAttributeList", Marshal.GetLastWin32Error());
381
+ list = Marshal.AllocHGlobal(listSize);
382
+ if (!InitializeProcThreadAttributeList(list, 1, 0, ref listSize))
383
+ return Fail(dir, "InitializeProcThreadAttributeList", Marshal.GetLastWin32Error());
384
+ listReady = true;
385
+ // The list is an array of HANDLEs; the three are the ones the child's STARTUPINFO names below.
386
+ inheritable = Marshal.AllocHGlobal(3 * IntPtr.Size);
387
+ Marshal.WriteIntPtr(inheritable, 0, input);
388
+ Marshal.WriteIntPtr(inheritable, IntPtr.Size, output);
389
+ Marshal.WriteIntPtr(inheritable, IntPtr.Size * 2, errorHandle);
390
+ if (!UpdateProcThreadAttribute(list, 0, new IntPtr(PROC_THREAD_ATTRIBUTE_HANDLE_LIST), inheritable, new IntPtr(3 * IntPtr.Size), IntPtr.Zero, IntPtr.Zero))
391
+ return Fail(dir, "UpdateProcThreadAttribute", Marshal.GetLastWin32Error());
392
+
393
+ STARTUPINFOEX startup = new STARTUPINFOEX();
394
+ // With EXTENDED_STARTUPINFO_PRESENT the size is the extended structure's, not STARTUPINFO's.
395
+ startup.StartupInfo.cb = Marshal.SizeOf(typeof(STARTUPINFOEX));
396
+ startup.StartupInfo.dwFlags = (int)STARTF_USESTDHANDLES;
397
+ startup.StartupInfo.hStdInput = input;
398
+ startup.StartupInfo.hStdOutput = output;
399
+ startup.StartupInfo.hStdError = errorHandle;
400
+ startup.lpAttributeList = list;
401
+ block = EnvironmentBlock(environment);
402
+ uint flags = CREATE_SUSPENDED | CREATE_UNICODE_ENVIRONMENT | DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP | EXTENDED_STARTUPINFO_PRESENT;
403
+ if (!CreateProcessW(application, CommandLine(application, arguments), IntPtr.Zero, IntPtr.Zero, true, flags, block,
404
+ workingDirectory, ref startup, out child))
405
+ return Fail(dir, "CreateProcess " + application, Marshal.GetLastWin32Error());
406
+ started = true;
407
+ // The child holds its own copies now, so this host's are closed at once instead of when the command ends:
408
+ // the output file and NUL are open for exactly as long as the kernel needed to hand them over, and a stopped
409
+ // command never leaves its log held open by a process that only started it. The attribute list is done too.
410
+ CloseHandle(input); input = IntPtr.Zero;
411
+ CloseHandle(output); output = IntPtr.Zero;
412
+ CloseHandle(errorHandle); errorHandle = IntPtr.Zero;
413
+ if (String.IsNullOrEmpty(logPath)) ReleaseOwnStdHandles();
414
+ DeleteProcThreadAttributeList(list); listReady = false;
415
+ Marshal.FreeHGlobal(list); list = IntPtr.Zero;
416
+ Marshal.FreeHGlobal(inheritable); inheritable = IntPtr.Zero;
417
+
418
+ // The wrapper is still suspended: nothing it could start runs before it belongs to the group.
419
+ if (!AssignProcessToJobObject(job, child.hProcess))
420
+ {
421
+ TerminateProcess(child.hProcess, 1);
422
+ return Fail(dir, "AssignProcessToJobObject", Marshal.GetLastWin32Error());
423
+ }
424
+ bool assigned;
425
+ if (!IsProcessInJob(child.hProcess, job, out assigned) || !assigned)
426
+ {
427
+ TerminateProcess(child.hProcess, 1);
428
+ return Fail(dir, "IsProcessInJob", Marshal.GetLastWin32Error());
429
+ }
430
+ // Before the child's first instruction: the orchestrator waits for this record before it counts the attempt.
431
+ WriteAtomic(Path.Combine(dir, "group"), GroupRecord(child.dwProcessId, child.hProcess));
432
+ if (ResumeThread(child.hThread) == 0xFFFFFFFF)
433
+ {
434
+ TerminateProcess(child.hProcess, 1);
435
+ return Fail(dir, "ResumeThread", Marshal.GetLastWin32Error());
436
+ }
437
+ string stopPath = Path.Combine(dir, "stop");
438
+ bool stopped = false;
439
+ for (;;)
440
+ {
441
+ uint waited = WaitForSingleObject(child.hProcess, 50);
442
+ if (waited == WAIT_OBJECT_0) break;
443
+ if (waited != WAIT_TIMEOUT) return Fail(dir, "WaitForSingleObject", Marshal.GetLastWin32Error());
444
+ if (File.Exists(stopPath)) { stopped = true; break; }
445
+ }
446
+ uint code = 1;
447
+ if (!stopped && !GetExitCodeProcess(child.hProcess, out code)) return Fail(dir, "GetExitCodeProcess", Marshal.GetLastWin32Error());
448
+ DrainJob(job);
449
+ if (!stopped)
450
+ {
451
+ // The record and the returned status carry the whole DWORD, above 0x7fffffff included: it is the wrapper's.
452
+ WriteAtomic(Path.Combine(dir, "group-end"), @"{""status"":" + code.ToString(CultureInfo.InvariantCulture) + "}");
453
+ }
454
+ status = code;
455
+ return true;
456
+ }
457
+ catch (Exception failure)
458
+ {
459
+ if (started) TerminateProcess(child.hProcess, 1);
460
+ return Fail(dir, "job host", 0, failure.GetType().Name + ": " + failure.Message);
461
+ }
462
+ finally
463
+ {
464
+ if (child.hThread != IntPtr.Zero) CloseHandle(child.hThread);
465
+ if (child.hProcess != IntPtr.Zero) CloseHandle(child.hProcess);
466
+ if (input != IntPtr.Zero && input != INVALID_HANDLE_VALUE) CloseHandle(input);
467
+ if (output != IntPtr.Zero && output != INVALID_HANDLE_VALUE) CloseHandle(output);
468
+ if (errorHandle != IntPtr.Zero && errorHandle != INVALID_HANDLE_VALUE) CloseHandle(errorHandle);
469
+ if (listReady) DeleteProcThreadAttributeList(list);
470
+ if (list != IntPtr.Zero) Marshal.FreeHGlobal(list);
471
+ if (inheritable != IntPtr.Zero) Marshal.FreeHGlobal(inheritable);
472
+ if (block != IntPtr.Zero) Marshal.FreeHGlobal(block);
473
+ // The group's only handle (non-inherited): closing it kills every process the command left behind.
474
+ if (job != IntPtr.Zero) CloseHandle(job);
475
+ }
476
+ }
477
+
478
+ static bool OpenInheritedOrNul(int stdWhich, uint nulAccess, ref SECURITY_ATTRIBUTES inherit, out IntPtr handle, out string stepName)
479
+ {
480
+ handle = IntPtr.Zero;
481
+ stepName = "DuplicateHandle";
482
+ IntPtr raw = GetStdHandle(stdWhich);
483
+ if (raw != IntPtr.Zero && raw != INVALID_HANDLE_VALUE)
484
+ {
485
+ IntPtr current = GetCurrentProcess();
486
+ if (DuplicateHandle(current, raw, current, out handle, 0, true, DUPLICATE_SAME_ACCESS))
487
+ return true;
488
+ int err = Marshal.GetLastWin32Error();
489
+ if (err != ERROR_INVALID_HANDLE) return false;
490
+ }
491
+ stepName = "CreateFile NUL";
492
+ handle = CreateFileW("NUL", nulAccess, FILE_SHARE_READ | FILE_SHARE_WRITE, ref inherit, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, IntPtr.Zero);
493
+ return handle != INVALID_HANDLE_VALUE;
494
+ }
495
+
496
+ static void ReleaseOwnStdHandles()
497
+ {
498
+ IntPtr hIn = GetStdHandle(STD_INPUT_HANDLE);
499
+ IntPtr hOut = GetStdHandle(STD_OUTPUT_HANDLE);
500
+ IntPtr hErr = GetStdHandle(STD_ERROR_HANDLE);
501
+ SetStdHandle(STD_INPUT_HANDLE, IntPtr.Zero);
502
+ SetStdHandle(STD_OUTPUT_HANDLE, IntPtr.Zero);
503
+ SetStdHandle(STD_ERROR_HANDLE, IntPtr.Zero);
504
+ if (hIn != IntPtr.Zero && hIn != INVALID_HANDLE_VALUE) CloseHandle(hIn);
505
+ if (hOut != IntPtr.Zero && hOut != INVALID_HANDLE_VALUE && hOut != hIn) CloseHandle(hOut);
506
+ if (hErr != IntPtr.Zero && hErr != INVALID_HANDLE_VALUE && hErr != hIn && hErr != hOut) CloseHandle(hErr);
507
+ }
508
+
509
+ static void DrainJob(IntPtr job)
510
+ {
511
+ TerminateJobObject(job, 1);
512
+ uint size = (uint)Marshal.SizeOf(typeof(JOBOBJECT_BASIC_ACCOUNTING_INFORMATION));
513
+ int start = Environment.TickCount;
514
+ for (;;)
515
+ {
516
+ JOBOBJECT_BASIC_ACCOUNTING_INFORMATION info;
517
+ if (!QueryInformationJobObject(job, JobObjectBasicAccountingInformation, out info, size, IntPtr.Zero)) break;
518
+ if (info.ActiveProcesses == 0) break;
519
+ if (unchecked(Environment.TickCount - start) >= 5000) break;
520
+ Sleep(10);
521
+ }
522
+ }
523
+
524
+ /** Record why this host did not start the wrapper and answer false (see Run): the negative return this code used to
525
+ * carry could be confused with a wrapper status above 0x7fffffff. */
526
+ static bool Fail(string dir, string what, int code)
527
+ {
528
+ return Fail(dir, what, code, null);
529
+ }
530
+
531
+ static bool Fail(string dir, string what, int code, string detail)
532
+ {
533
+ string text = what + " failed (error " + code.ToString(CultureInfo.InvariantCulture) + ")" + (detail == null ? "" : ": " + detail);
534
+ try { WriteAtomic(Path.Combine(dir, "start-error"), text); } catch (Exception) { }
535
+ return false;
536
+ }
537
+
538
+ static bool IsTransientSharingError(int win32Error)
539
+ {
540
+ return win32Error == ERROR_ACCESS_DENIED || win32Error == ERROR_SHARING_VIOLATION ||
541
+ win32Error == ERROR_LOCK_VIOLATION || win32Error == ERROR_BUSY;
542
+ }
543
+
544
+ static bool IsTransientSharingException(Exception error)
545
+ {
546
+ if (error is UnauthorizedAccessException) return true;
547
+ IOException io = error as IOException;
548
+ if (io == null) return false;
549
+ int code = Marshal.GetHRForException(io) & 0xFFFF;
550
+ return IsTransientSharingError(code);
551
+ }
552
+
553
+ static void WriteAtomic(string path, string text)
554
+ {
555
+ string temporary = path + ".tmp";
556
+ int deadline = unchecked(Environment.TickCount + 2500);
557
+ try
558
+ {
559
+ for (int attempt = 0; ; attempt++)
560
+ {
561
+ try { File.WriteAllText(temporary, text); break; }
562
+ catch (Exception error)
563
+ {
564
+ if (!IsTransientSharingException(error) || attempt >= 25) throw;
565
+ int left = unchecked(deadline - Environment.TickCount);
566
+ if (left <= 0) throw;
567
+ int wait = (attempt + 1) * 10;
568
+ if (wait > 100) wait = 100;
569
+ if (wait > left) wait = left;
570
+ Sleep((uint)wait);
571
+ }
572
+ }
573
+ for (int attempt = 0; ; attempt++)
574
+ {
575
+ if (MoveFileExW(temporary, path, MOVEFILE_REPLACE_EXISTING)) return;
576
+ int err = Marshal.GetLastWin32Error();
577
+ if (!IsTransientSharingError(err) || attempt >= 25)
578
+ throw new IOException("MoveFileExW failed (error " + err.ToString(CultureInfo.InvariantCulture) + ")");
579
+ int left = unchecked(deadline - Environment.TickCount);
580
+ if (left <= 0)
581
+ throw new IOException("MoveFileExW failed (error " + err.ToString(CultureInfo.InvariantCulture) + ")");
582
+ int wait = (attempt + 1) * 10;
583
+ if (wait > 100) wait = 100;
584
+ if (wait > left) wait = left;
585
+ Sleep((uint)wait);
586
+ }
587
+ }
588
+ catch (Exception)
589
+ {
590
+ try { File.Delete(temporary); } catch (Exception) { }
591
+ throw;
592
+ }
593
+ }
594
+
595
+ static string ProcessStart(IntPtr process)
596
+ {
597
+ long creation, exit, kernel, user;
598
+ if (!GetProcessTimes(process, out creation, out exit, out kernel, out user) || creation <= 0) return "";
599
+ try { return DateTime.FromFileTime((creation / 10) * 10).Ticks.ToString(CultureInfo.InvariantCulture); }
600
+ catch (Exception) { return ""; }
601
+ }
602
+
603
+ static string ProcessIdentity(int pid, IntPtr process)
604
+ {
605
+ return @"{""pid"":" + pid.ToString(CultureInfo.InvariantCulture) + @",""start"":""" + ProcessStart(process) + @"""}";
606
+ }
607
+
608
+ static string GroupRecord(int pid, IntPtr process)
609
+ {
610
+ return @"{""pid"":" + pid.ToString(CultureInfo.InvariantCulture) + @",""start"":""" + ProcessStart(process) +
611
+ @""",""group"":" + ProcessIdentity(unchecked((int)GetCurrentProcessId()), GetCurrentProcess()) + "}";
612
+ }
613
+
614
+ /** The child's environment (CREATE_UNICODE_ENVIRONMENT): its variables, then the empty terminator. */
615
+ static IntPtr EnvironmentBlock(string[] pairs)
616
+ {
617
+ StringBuilder text = new StringBuilder();
618
+ if (pairs != null)
619
+ foreach (string pair in pairs)
620
+ if (!String.IsNullOrEmpty(pair)) { text.Append(pair); text.Append((char)0); }
621
+ if (text.Length == 0) text.Append((char)0);
622
+ text.Append((char)0);
623
+ return Marshal.StringToHGlobalUni(text.ToString());
624
+ }
625
+
626
+ /** An argv as a CreateProcess command line, by the quoting rules CommandLineToArgvW (and the C runtime) parse.
627
+ * Preserves pre-quoted cmd.exe /d /s /c "..." batch invocations verbatim (matching Node's windowsVerbatimArguments). */
628
+ static string CommandLine(string application, string[] arguments)
629
+ {
630
+ StringBuilder text = new StringBuilder(Quote(application));
631
+ if (arguments != null && arguments.Length == 4
632
+ && String.Equals(Path.GetFileName(application), "cmd.exe", StringComparison.OrdinalIgnoreCase)
633
+ && arguments[0] == "/d" && arguments[1] == "/s" && arguments[2] == "/c"
634
+ && arguments[3].Length >= 2 && arguments[3][0] == '"' && arguments[3][arguments[3].Length - 1] == '"')
635
+ {
636
+ return text.Append(" /d /s /c ").Append(arguments[3]).ToString();
637
+ }
638
+ if (arguments != null) foreach (string argument in arguments) text.Append(' ').Append(Quote(argument));
639
+ return text.ToString();
640
+ }
641
+
642
+ static string Quote(string argument)
643
+ {
644
+ if (argument.Length > 0 && argument.IndexOfAny(new char[] { ' ', (char)9, (char)10, (char)11, '"' }) < 0) return argument;
645
+ StringBuilder text = new StringBuilder(((char)34).ToString());
646
+ int backslashes = 0;
647
+ for (int i = 0; i < argument.Length; i++)
648
+ {
649
+ char c = argument[i];
650
+ if (c == (char)92) { backslashes++; continue; }
651
+ if (c == '"') { text.Append((char)92, backslashes * 2 + 1); text.Append('"'); backslashes = 0; continue; }
652
+ if (backslashes > 0) { text.Append((char)92, backslashes); backslashes = 0; }
653
+ text.Append(c);
654
+ }
655
+ if (backslashes > 0) text.Append((char)92, backslashes * 2);
656
+ text.Append('"');
657
+ return text.ToString();
658
+ }
659
+ }
660
+ `;
661
+ /** The compiled owner executable's file name inside the per-launch directory. */
662
+ export const JOB_HOST_EXE = "DsaJob.exe";
663
+ /** The source file's name inside the per-launch directory (inert: kept as evidence, never executed). */
664
+ export const JOB_HOST_SOURCE_FILE = "DsaJob.cs";
665
+ /** The per-launch directory's prefix inside the attempt directory. */
666
+ export const JOB_HOST_PREFIX = "job-host-";
667
+ /** The owner's own stderr (its diagnostics when the program itself cannot run; empty otherwise). */
668
+ export const JOB_HOST_LOG = "host.log";
669
+ /** Written by this process when the owner ends: its exit code -- the whole DWORD, normalized as every status here is,
670
+ * so it agrees with the group record and with what a caller observes -- or why it could not be spawned, for the failure
671
+ * reason. The owner cannot report this itself -- it is the process that ended. */
672
+ export const JOB_HOST_EXIT = "host-exit";
673
+ /** What the owner reads: the program, argv, cwd, output file and complete environment of the attempt's wrapper. */
674
+ export const JOB_SPEC = "job.json";
675
+ /** The spec's first line: the owner refuses a file it does not recognize. */
676
+ export const JOB_SPEC_HEADER = "DSAJOB1";
677
+ /** Written (atomically) after the wrapper is in the group and before it may run: `{"pid":<wrapper pid>}`. */
678
+ export const JOB_GROUP = "group";
679
+ /** Written when the owner saw the wrapper end: `{"status":<wrapper exit status>}`. */
680
+ export const JOB_END = "group-end";
681
+ /** Written (atomically) when the owner could not start the wrapper: a short reason for the failed attempt. */
682
+ export const JOB_ERROR = "start-error";
683
+ /** Written (atomically) by a caller requesting a controlled stop so the owner calls DrainJob and exits without `group-end`. */
684
+ export const JOB_STOP = "stop";
685
+ /** Written by the owner's first statement: its absence proves the program never ran (a launcher problem, not a failure
686
+ * of this attempt), which is what a bare "the owner ended" otherwise hides. */
687
+ export const JOB_BEGIN = "helper-begin";
688
+ /** How much of an evidence file a failure reason may read; a reason is a line, never a dump. */
689
+ const REASON_BYTES = 1000;
690
+ /** How much of it a failure reason may quote, and how long the whole reason may get. */
691
+ const EVIDENCE_LIMIT = 200;
692
+ const REASON_LIMIT = 300;
693
+ /** Compiling the owner on a loaded runner: bounded, in the foreground, and finished before anything is started. */
694
+ export const JOB_COMPILE_TIMEOUT_MS = 60_000;
695
+ /** Publishing the compiler's output under its final name: a scanner or indexer may hold the fresh file for a moment, so a
696
+ * transient rename failure is retried for this long before it is reported. */
697
+ const JOB_PUBLISH_MS = 5_000;
698
+ const JOB_PUBLISH_RETRY_MS = 100;
699
+ /** Process creation plus the owner's startup on a loaded runner; an owner that has not reported a group by then started
700
+ * nothing. Measured after the spawn, so the compilation is not part of it. */
701
+ const JOB_START_TIMEOUT_MS = 30_000;
702
+ /** How long an owner that cannot be confirmed retired is given to end before its attempt is adopted instead. */
703
+ const JOB_HOST_END_MS = 5_000;
704
+ /** Caps the retries of a failed process-table observation: past it the attempt is adopted rather than refused. */
705
+ const JOB_OBSERVE_MS = 10_000;
706
+ /** The .NET Framework whose C# compiler every supported Windows ships. */
707
+ const FRAMEWORK_VERSION = "v4.0.30319";
708
+ /** The wrapper's environment as the owner receives it: one ordered `NAME=value` list. Windows variable names are
709
+ * case-insensitive, so names that differ only in case name one variable: the first spelling wins, with its position in
710
+ * the list, so the block is ordered and has no duplicates the kernel could resolve differently from the caller. A name
711
+ * that cannot be written is dropped (empty, or with `=` in it) instead of corrupting the block. */
712
+ export function jobEnv(env) {
713
+ const seen = new Set(), pairs = [];
714
+ for (const [name, value] of Object.entries(env)) {
715
+ if (!name || name.includes("=") || value === undefined)
716
+ continue;
717
+ const fold = name.toUpperCase();
718
+ if (seen.has(fold))
719
+ continue;
720
+ seen.add(fold);
721
+ pairs.push(`${name}=${value}`);
722
+ }
723
+ return pairs;
724
+ }
725
+ /** The spec as text this module writes itself: the header, then one base64-encoded UTF-16LE field per line (exe, cwd,
726
+ * log, the argument count and arguments, the environment count and entries). Base64 is ASCII, so job.json decodes
727
+ * identically under any code page, and UTF-16LE carries every JS string -- a curly quote, an emoji, even an unpaired
728
+ * surrogate -- unchanged: the owner turns every line back with Convert.FromBase64String and takes each byte pair as one
729
+ * code unit, and refuses a field that is not a whole number of them. */
730
+ export function jobSpecText(launch) {
731
+ const env = jobEnv(launch.env);
732
+ const lines = [JOB_SPEC_HEADER, field(launch.exe), field(launch.cwd), field(launch.log), String(launch.args.length),
733
+ ...launch.args.map(field), String(env.length), ...env.map(field)];
734
+ return `${lines.join("\n")}\n`;
735
+ }
736
+ const field = (text) => Buffer.from(text, "utf16le").toString("base64");
737
+ /** `value` as JSON text of ASCII bytes only: like JSON.stringify, but every code unit outside 0x20..0x7e is escaped (each
738
+ * half of a surrogate pair on its own, which JSON allows and parses back into the same pair). Used for the owner's exit
739
+ * record, which this process writes itself. */
740
+ export function asciiJson(value) {
741
+ if (value === null)
742
+ return "null";
743
+ if (typeof value === "boolean")
744
+ return value ? "true" : "false";
745
+ if (typeof value === "number") {
746
+ if (!Number.isFinite(value))
747
+ throw new TypeError(`not JSON: ${value}`);
748
+ return String(value);
749
+ }
750
+ if (typeof value === "string")
751
+ return asciiString(value);
752
+ if (Array.isArray(value))
753
+ return `[${value.map(item => asciiJson(item)).join(",")}]`;
754
+ if (typeof value === "object") {
755
+ const entries = Object.entries(value).filter(([, item]) => item !== undefined);
756
+ return `{${entries.map(([name, item]) => `${asciiString(name)}:${asciiJson(item)}`).join(",")}}`;
757
+ }
758
+ throw new TypeError(`not JSON: ${typeof value}`);
759
+ }
760
+ const ASCII_ESCAPES = { '"': '\\"', "\\": "\\\\", "\b": "\\b", "\f": "\\f", "\n": "\\n", "\r": "\\r", "\t": "\\t" };
761
+ function asciiString(text) {
762
+ let out = '"';
763
+ for (let at = 0; at < text.length; at += 1) {
764
+ const unit = text.charCodeAt(at);
765
+ out += unit === 0x22 || unit === 0x5c ? ASCII_ESCAPES[text[at]]
766
+ : unit < 0x20 || unit > 0x7e ? `\\u${unit.toString(16).padStart(4, "0")}`
767
+ : text[at];
768
+ }
769
+ return `${out}"`;
770
+ }
771
+ /** The C# compiler candidates for this environment and architecture, in preference order: every supported Windows ships
772
+ * the .NET Framework 4 compiler under Framework64 (x64 or ARM64) and Framework (x86). An ia32 host prefers the 32-bit
773
+ * one; everything else the 64-bit one, with the other as a fallback (both produce a runnable owner). Absolute paths
774
+ * only: %SystemRoot% is read from the environment, never the current directory or a PATH entry. */
775
+ export function frameworkCompilerCandidates(env = process.env, arch = process.arch) {
776
+ const root = systemRoot(env);
777
+ const names = arch === "ia32" ? ["Framework", "Framework64"] : ["Framework64", "Framework"];
778
+ return names.map(name => join(root, "Microsoft.NET", name, FRAMEWORK_VERSION, "csc.exe"));
779
+ }
780
+ /** The first candidate that exists. Nothing found is a fail-closed error (the caller starts no command): the compiler is
781
+ * verified by the compilation itself, which runs before any process of the attempt exists. `exists` is a test seam. */
782
+ export function frameworkCompiler(env = process.env, arch = process.arch, exists = existsSync) {
783
+ const candidates = frameworkCompilerCandidates(env, arch);
784
+ for (const candidate of candidates)
785
+ if (exists(candidate))
786
+ return candidate;
787
+ throw new Error(`the Windows .NET Framework C# compiler is unavailable (searched ${candidates.join(", ")})`);
788
+ }
789
+ /** A fresh owner directory for one launch: the attempt directory plus a random name, so an executable compiled by an
790
+ * earlier launch is never found, let alone run, and two launches never share host files. */
791
+ export function jobHostPaths(dir) {
792
+ const host = join(dir, `${JOB_HOST_PREFIX}${process.pid.toString(36)}-${randomBytes(8).toString("hex")}`);
793
+ return { dir: host, exe: join(host, JOB_HOST_EXE), source: join(host, JOB_HOST_SOURCE_FILE) };
794
+ }
795
+ /** A preparation cancelled while it ran: a stop, a retirement, a suspension or the orchestrator's exit arrived during the
796
+ * compilation. Nothing of the attempt exists (no group, no wrapper, no command) and nothing of it was recorded, so this is
797
+ * not a failure of the attempt and must never be sealed as one. */
798
+ export class JobPrepareCancelled extends Error {
799
+ constructor() { super("the command job host preparation was cancelled"); this.name = "JobPrepareCancelled"; }
800
+ }
801
+ /** Whether `error` is such a cancellation (the caller decides what canceled it: a stop seals stopped, a retirement or an
802
+ * exit ends the run and the call resumes on recovery). */
803
+ export const prepareCancelled = (error) => error instanceof JobPrepareCancelled || error?.name === "JobPrepareCancelled";
804
+ /** Prepare one launch without starting anything: clear an earlier attempt's evidence from the directory, compile the owner
805
+ * (bounded and cancellable: a crash or a cancellation leaves only inert files, and a cancellation removes even those),
806
+ * and write the spec the owner reads. A rejection is either fail-closed (`JOB_ERROR` recorded, the attempt cannot start)
807
+ * or a {@link JobPrepareCancelled} (nothing was recorded and nothing stays). */
808
+ export async function prepareJob(dir, launch, options = {}) {
809
+ // Evidence of an earlier attempt in the same directory must never be read as this attempt's.
810
+ for (const name of [JOB_BEGIN, JOB_GROUP, JOB_END, JOB_ERROR, JOB_STOP, JOB_HOST_EXIT, JOB_HOST_LOG])
811
+ await rm(join(dir, name), { force: true });
812
+ const host = await compileJobHost(dir, { ...(options.compiler ? { compiler: options.compiler } : {}),
813
+ ...(options.compileMs ? { timeoutMs: options.compileMs } : {}), ...(options.signal ? { signal: options.signal } : {}),
814
+ ...(options.publish ? { publish: options.publish } : {}) });
815
+ const release = async () => { await rm(host.dir, { recursive: true, force: true }); await rm(join(dir, JOB_SPEC), { force: true }); };
816
+ if (options.signal?.aborted) {
817
+ await release();
818
+ throw new JobPrepareCancelled();
819
+ }
820
+ await writeFile(join(dir, JOB_SPEC), jobSpecText(launch));
821
+ return { host, dir, release };
822
+ }
823
+ /** Compile the owner into the launch's private directory with the Windows framework compiler: foreground and bounded (no
824
+ * command is started, so a starter that dies here leaves only inert files), and fail-closed (a missing compiler, a
825
+ * compiler failure or a missing executable throws before anything of the attempt exists). `signal` cancels it: the
826
+ * compiler is ended, what it wrote is removed and the rejection is a {@link JobPrepareCancelled}, which is not a failure
827
+ * of the attempt (nothing of it exists, and it is never recorded as one). A cancellation during the publication of the
828
+ * compiler's output is the same cancellation: the retries stop at once, what the compiler wrote is removed and nothing is
829
+ * recorded as a publish failure. */
830
+ export async function compileJobHost(dir, options = {}) {
831
+ const paths = jobHostPaths(dir), signal = options.signal;
832
+ await mkdir(paths.dir, { recursive: true });
833
+ /** A cancelled preparation leaves nothing behind: no compiled owner, no source, no reason (nothing failed). */
834
+ const cancelled = async () => {
835
+ await rm(paths.dir, { recursive: true, force: true }).catch(() => { });
836
+ return new JobPrepareCancelled();
837
+ };
838
+ if (signal?.aborted)
839
+ throw await cancelled();
840
+ await writeFile(paths.source, JOB_HOST_SOURCE, "utf8");
841
+ const compiler = options.compiler ?? frameworkCompiler(), timeoutMs = options.timeoutMs ?? JOB_COMPILE_TIMEOUT_MS;
842
+ // Only ASCII relative names reach the compiler, and it runs in the launch's own directory: the attempt directory (which
843
+ // may be Unicode or curly-quoted) is the process's working directory, which Windows passes as UTF-16, so no path
844
+ // argument needs a code-page conversion. The output is built beside the final name and renamed only after the compiler
845
+ // exits cleanly, so a killed or failed compiler can never leave a half-written executable that a later start would run.
846
+ const build = "DsaJob.build.exe";
847
+ let stdout = "", stderr = "";
848
+ try {
849
+ try {
850
+ await new Promise((resolve, reject) => {
851
+ execFile(compiler, ["/nologo", "/codepage:65001", "/target:winexe", `/out:${build}`, JOB_HOST_SOURCE_FILE], { cwd: paths.dir, timeout: timeoutMs, windowsHide: true, env: helperEnv(), maxBuffer: 1024 * 1024, encoding: "utf8",
852
+ ...(signal ? { signal } : {}) }, (error, out, err) => { stdout = String(out ?? ""); stderr = String(err ?? ""); if (error)
853
+ reject(error);
854
+ else
855
+ resolve(); });
856
+ });
857
+ }
858
+ catch (error) {
859
+ // A compiler this process ended because the start was cancelled wrote nothing that counts, and the start was never
860
+ // recorded: this is not the attempt's failure, so it is not written to the attempt either.
861
+ if (signal?.aborted || prepareCancelled(error))
862
+ throw await cancelled();
863
+ throw new Error(compilerFailure(compiler, error, stdout, stderr));
864
+ }
865
+ if (signal?.aborted)
866
+ throw await cancelled();
867
+ // The executable is the one just produced: the directory is new, so this cannot be a stale binary (a compiler that
868
+ // reports success without writing it is a failure, never a reason to look elsewhere).
869
+ try {
870
+ await (options.publish ?? publishBuild)(join(paths.dir, build), paths.exe, { ...(signal ? { signal } : {}) });
871
+ }
872
+ catch (error) {
873
+ // A publication ended by the cancellation is the cancellation (nothing was started, nothing is recorded): only a
874
+ // publish that failed on its own is fail-closed.
875
+ if (prepareCancelled(error) || signal?.aborted)
876
+ throw await cancelled();
877
+ throw error;
878
+ }
879
+ if (signal?.aborted)
880
+ throw await cancelled();
881
+ if (!existsSync(paths.exe))
882
+ throw new Error(`the Windows .NET Framework compiler wrote no executable at ${paths.exe}`);
883
+ }
884
+ catch (error) {
885
+ if (prepareCancelled(error))
886
+ throw error;
887
+ const reason = String(error?.message ?? error);
888
+ await writeFileAtomic(join(dir, JOB_ERROR), clip(oneLine(reason), REASON_LIMIT), { encoding: "utf8" }).catch(() => { });
889
+ throw new Error(reason);
890
+ }
891
+ return paths;
892
+ }
893
+ /** Publish the compiler's output under its final name: the rename is atomic, so a retry can never expose a half-written
894
+ * executable, and Windows scanners and indexers hold a fresh file for a moment (a transient code). A failure that stays
895
+ * is reported with its own reason, and only a build file that is genuinely absent reads as "wrote no executable" --
896
+ * reporting every rename failure that way hides the real cause. `signal` cancels it: the retries and their delay end at
897
+ * once with a {@link JobPrepareCancelled}, which is a cancellation and never a publish failure (the caller removes what
898
+ * the compiler wrote). `renameFile` and the timings are test seams. */
899
+ export async function publishBuild(build, exe, options = {}) {
900
+ const renameFile = options.renameFile ?? rename, retryMs = options.retryMs ?? JOB_PUBLISH_RETRY_MS, budgetMs = options.timeoutMs ?? JOB_PUBLISH_MS, signal = options.signal, end = Date.now() + budgetMs;
901
+ /** A cancelled publication is not a failure to publish: nothing is recorded about it and the output is not needed. */
902
+ const cancelled = () => new JobPrepareCancelled();
903
+ for (;;) {
904
+ if (signal?.aborted)
905
+ throw cancelled();
906
+ let failure;
907
+ try {
908
+ await renameFile(build, exe);
909
+ }
910
+ catch (error) {
911
+ failure = error;
912
+ }
913
+ if (failure === undefined) {
914
+ // The rename succeeded, but a cancellation that arrived while it ran still wins: nothing may follow it (the caller
915
+ // removes what the compiler wrote).
916
+ if (signal?.aborted)
917
+ throw cancelled();
918
+ return;
919
+ }
920
+ // A rename that failed while the start was cancelled is that cancellation, not its own reason: the classification
921
+ // below (absent, transient, otherwise) describes a publish the attempt still needs, and it is not needed here.
922
+ if (signal?.aborted)
923
+ throw cancelled();
924
+ const reason = String(failure?.message ?? failure);
925
+ if (absent(failure))
926
+ throw new Error(`the Windows .NET Framework compiler wrote no executable for ${exe}`);
927
+ if (!transientRead(failure))
928
+ throw new Error(`the Windows .NET Framework compiler output could not be published as ${exe}: ${reason}`);
929
+ if (Date.now() + retryMs >= end)
930
+ throw new Error(`the Windows .NET Framework compiler output could not be published as ${exe} within ${budgetMs} ms: ${reason}`);
931
+ // The retry delay is woken by the signal: a cancellation does not wait out the rest of the budget.
932
+ if (!await wokenBy(retryMs, signal))
933
+ throw cancelled();
934
+ }
935
+ }
936
+ /** Wait `ms`, or end at once when `signal` aborts: a cancelled preparation wakes promptly instead of sitting out a retry
937
+ * delay (which is bounded only by the publish budget). Resolves false when the signal aborted first. */
938
+ function wokenBy(ms, signal) {
939
+ if (!signal)
940
+ return delay(ms).then(() => true);
941
+ if (signal.aborted)
942
+ return Promise.resolve(false);
943
+ return new Promise(resolve => {
944
+ let settled = false, timer;
945
+ const done = (waited) => {
946
+ if (settled)
947
+ return;
948
+ settled = true;
949
+ clearTimeout(timer);
950
+ signal.removeEventListener("abort", aborted);
951
+ resolve(waited);
952
+ };
953
+ const aborted = () => done(false);
954
+ timer = setTimeout(() => done(true), ms);
955
+ signal.addEventListener("abort", aborted, { once: true });
956
+ // An abort between the check above and the listener: the event would never reach it.
957
+ if (signal.aborted)
958
+ done(false);
959
+ });
960
+ }
961
+ /** What a failed compiler run says: its bounded own words, whether it timed out, and its exit status. */
962
+ function compilerFailure(compiler, error, stdout, stderr) {
963
+ const failure = error;
964
+ const note = failure.killed ? "timed out" : failure.code !== undefined ? `exit ${String(failure.code)}`
965
+ : String(failure.signal ?? failure.message ?? error);
966
+ const output = oneLine(String(stderr || stdout || ""));
967
+ return `the Windows .NET Framework compiler ${compiler} failed (${note})${output ? `: ${clip(output, EVIDENCE_LIMIT)}` : ""}`;
968
+ }
969
+ /** The owner's argv: the attempt directory whose records and spec it uses (an argument, not a script path or a written-in
970
+ * path), then the attempt's versioned tag(s), which the C# ignores and a process-table scan reads while the owner starts. */
971
+ export function jobHostArgv(dir, exec, hold) {
972
+ return [dir, ...(exec ? [winTagArg("DSA_EXEC", exec)] : []), ...(hold ? [winTagArg("DSA_HOLD", hold)] : [])];
973
+ }
974
+ function matchesOwnerTag(command, launch) {
975
+ if (launch.exec && winTag(command, "DSA_EXEC") !== launch.exec)
976
+ return false;
977
+ if (launch.hold && winTag(command, "DSA_HOLD") !== launch.hold)
978
+ return false;
979
+ return true;
980
+ }
981
+ /** A read that failed because the owner holds the file for a moment (or is renaming it onto the name): not a failure. */
982
+ export function transientRead(error) {
983
+ return ["EBUSY", "EPERM", "EACCES", "EAGAIN", "EMFILE", "ENFILE"].includes(error?.code ?? "");
984
+ }
985
+ const absent = (error) => error?.code === "ENOENT";
986
+ function parseGroupText(text) {
987
+ let parsed;
988
+ try {
989
+ parsed = JSON.parse(text);
990
+ }
991
+ catch {
992
+ throw new Error(`the command job group record cannot be read: ${text.slice(0, 200)}`);
993
+ }
994
+ if (!Number.isInteger(parsed.pid) || parsed.pid <= 0)
995
+ throw new Error(`the command job group record is not a pid: ${text.slice(0, 200)}`);
996
+ const start = typeof parsed.start === "string" && parsed.start ? parsed.start : undefined;
997
+ const rawGroup = parsed.group && typeof parsed.group === "object"
998
+ ? parsed.group : undefined;
999
+ const group = rawGroup && Number.isInteger(rawGroup.pid) && rawGroup.pid > 0 &&
1000
+ typeof rawGroup.start === "string" && rawGroup.start
1001
+ ? { pid: rawGroup.pid, start: rawGroup.start } : undefined;
1002
+ return { pid: parsed.pid, ...(start ? { start } : {}), ...(group ? { group } : {}) };
1003
+ }
1004
+ /** The group record written before ResumeThread (with legacy `{"pid":<n>}` compatibility); undefined while not ready. */
1005
+ export async function readGroupRecord(dir, options = {}) {
1006
+ const readFn = options.readFile ?? ((path) => readFile(path, "utf8"));
1007
+ let text;
1008
+ try {
1009
+ text = await retryWinSharing(() => readFn(join(dir, JOB_GROUP)), { timeoutMs: 250, maxAttempts: 6, ...options });
1010
+ }
1011
+ catch (error) {
1012
+ if (absent(error) || transientRead(error))
1013
+ return undefined;
1014
+ throw error;
1015
+ }
1016
+ return parseGroupText(text);
1017
+ }
1018
+ /** Synchronous group-record reader for lease liveness checks; distinguishes transient rename locks from absence. */
1019
+ export function readGroupRecordStateSync(dir) {
1020
+ let text;
1021
+ try {
1022
+ text = readFileSync(join(dir, JOB_GROUP), "utf8");
1023
+ }
1024
+ catch (error) {
1025
+ if (absent(error))
1026
+ return { state: "absent" };
1027
+ if (transientRead(error))
1028
+ return { state: "transient" };
1029
+ return { state: "absent" };
1030
+ }
1031
+ try {
1032
+ return { state: "ready", record: parseGroupText(text) };
1033
+ }
1034
+ catch {
1035
+ return { state: "absent" };
1036
+ }
1037
+ }
1038
+ /** Synchronous group-record reader for recovery/sweep callers (`gateJobProcesses`); retries briefly on Windows
1039
+ * transient sharing locks (unlike {@link readGroupRecordStateSync}, which stays single-shot non-blocking for leases). */
1040
+ export function readGroupRecordSync(dir, options = {}) {
1041
+ const readFn = options.readFile ?? ((path) => readFileSync(path, "utf8"));
1042
+ let text;
1043
+ try {
1044
+ text = retryWinSharingSync(() => readFn(join(dir, JOB_GROUP)), { timeoutMs: 250, maxAttempts: 5, ...options });
1045
+ }
1046
+ catch {
1047
+ return undefined;
1048
+ }
1049
+ try {
1050
+ return parseGroupText(text);
1051
+ }
1052
+ catch {
1053
+ return undefined;
1054
+ }
1055
+ }
1056
+ function parseBeginText(text) {
1057
+ try {
1058
+ const parsed = JSON.parse(text);
1059
+ return Number.isInteger(parsed.pid) && parsed.pid > 0 && typeof parsed.start === "string" && parsed.start
1060
+ ? { pid: parsed.pid, start: parsed.start } : undefined;
1061
+ }
1062
+ catch {
1063
+ return undefined;
1064
+ }
1065
+ }
1066
+ /** The owner's handle-recorded creation identity from `helper-begin` (undefined when absent or legacy `"begin"`). */
1067
+ export async function readBeginIdentity(dir, options = {}) {
1068
+ const readFn = options.readFile ?? ((path) => readFile(path, "utf8"));
1069
+ let text;
1070
+ try {
1071
+ text = await retryWinSharing(() => readFn(join(dir, JOB_BEGIN)), { timeoutMs: 500, maxAttempts: 10, ...options });
1072
+ }
1073
+ catch {
1074
+ return undefined;
1075
+ }
1076
+ return parseBeginText(text);
1077
+ }
1078
+ export function readBeginIdentitySync(dir, options = {}) {
1079
+ try {
1080
+ const readFn = options.readFile ?? ((path) => readFileSync(path, "utf8"));
1081
+ return parseBeginText(retryWinSharingSync(() => readFn(join(dir, JOB_BEGIN)), { timeoutMs: 500, maxAttempts: 10, ...options }));
1082
+ }
1083
+ catch {
1084
+ return undefined;
1085
+ }
1086
+ }
1087
+ export function readGroupEndSync(dir, options = {}) {
1088
+ try {
1089
+ const readFn = options.readFile ?? ((path) => readFileSync(path, "utf8"));
1090
+ const parsed = JSON.parse(retryWinSharingSync(() => readFn(join(dir, JOB_END)), { timeoutMs: 1_000, maxAttempts: 15, ...options }));
1091
+ return typeof parsed.status === "number" && Number.isInteger(parsed.status) && parsed.status >= 0 && parsed.status <= 0xffffffff
1092
+ ? { status: parsed.status } : undefined;
1093
+ }
1094
+ catch {
1095
+ return undefined;
1096
+ }
1097
+ }
1098
+ export function readStartErrorSync(dir, options = {}) {
1099
+ try {
1100
+ const readFn = options.readFile ?? ((path) => readFileSync(path, "utf8"));
1101
+ const text = retryWinSharingSync(() => readFn(join(dir, JOB_ERROR)), { timeoutMs: 500, maxAttempts: 10, ...options }).trim();
1102
+ return text || undefined;
1103
+ }
1104
+ catch {
1105
+ return undefined;
1106
+ }
1107
+ }
1108
+ /** Ask a live job owner (`DsaJob.exe`) to drain its Job Object (`DrainJob`) and exit without writing `group-end`. */
1109
+ export async function requestJobStop(dir) {
1110
+ await writeFileAtomic(join(dir, JOB_STOP), "stop", {
1111
+ encoding: "utf8",
1112
+ timeoutMs: 2_500,
1113
+ maxAttempts: 25,
1114
+ }).catch(() => { });
1115
+ }
1116
+ /** One process-table observation, retried for a while: a PowerShell/CIM read fails transiently on a loaded machine, and
1117
+ * a failed observation must never be read as "no process" (that would let a second attempt start). */
1118
+ async function observeWithin(observe, budgetMs) {
1119
+ const end = Date.now() + Math.max(250, budgetMs);
1120
+ for (;;) {
1121
+ try {
1122
+ return await observe();
1123
+ }
1124
+ catch (error) {
1125
+ if (Date.now() + 250 >= end)
1126
+ throw error;
1127
+ await delay(250);
1128
+ }
1129
+ }
1130
+ }
1131
+ /** Start `launch` inside a new Windows Job Object (see the module comment). Prepares the owner first (a staged preparation
1132
+ * is used as given; otherwise it is staged here: bounded, no process of the attempt exists until it finishes; a compiler
1133
+ * failure throws, fail-closed), then calls `proceed` once more and spawns the owner immediately. Resolves undefined when
1134
+ * `proceed` refuses after the preparation. Rejects -- with no attempt started -- when the owner cannot create the group,
1135
+ * assign the suspended child before it runs, or report it back in time, and its end is confirmed. When an attempt cannot
1136
+ * be refused (the owner did not end), it resolves with JobSpawned.uncertain: the attempt was started and is adopted,
1137
+ * never silently dropped. */
1138
+ export async function spawnInJob(dir, launch, options = {}) {
1139
+ // A staged preparation was made before the attempt's durable intent (prepareJob clears the earlier evidence and writes
1140
+ // the spec); one this call stages itself does the same here.
1141
+ const host = (options.prepared ?? await prepareJob(dir, launch, { ...(options.compiler ? { compiler: options.compiler } : {}),
1142
+ ...(options.compileMs ? { compileMs: options.compileMs } : {}), ...(options.signal ? { signal: options.signal } : {}),
1143
+ ...(options.publish ? { publish: options.publish } : {}) })).host;
1144
+ // The owner's stderr is a file by default (it outlives the orchestrator and nothing drains it); `hold` passes its own stdio.
1145
+ const errors = options.stdio ? undefined : openSync(join(dir, JOB_HOST_LOG), "a");
1146
+ let helper;
1147
+ try {
1148
+ // The executor's last check, after the preparation and immediately before the spawn: no await follows it, so a stop
1149
+ // or retirement that revoked the permission during the compilation starts no process.
1150
+ if (options.proceed && !options.proceed())
1151
+ return undefined;
1152
+ helper = spawn(host.exe, jobHostArgv(dir, launch.exec, launch.hold), { detached: true, stdio: options.stdio ?? ["ignore", "ignore", errors], windowsHide: true, env: helperEnv() });
1153
+ }
1154
+ finally {
1155
+ if (errors !== undefined)
1156
+ closeSync(errors);
1157
+ }
1158
+ let ended = false;
1159
+ const killOwner = () => !ended && helper.exitCode === null && helper.signalCode === null && helper.kill("SIGKILL");
1160
+ const requestStop = async () => {
1161
+ if (ended)
1162
+ return;
1163
+ await requestJobStop(dir);
1164
+ };
1165
+ options.onOwnerSpawned?.(killOwner);
1166
+ let recordedExit;
1167
+ // The owner's end is durably written to JOB_HOST_EXIT before `exited` resolves, and every path that formats a
1168
+ // failure reason awaits `exited` once `ended` is set so exit evidence never races the rejection message. Published
1169
+ // atomically (temp-then-rename with bounded Windows sharing retries, never a direct target write that could expose
1170
+ // partial JSON to concurrent readers).
1171
+ const exited = new Promise(resolve => {
1172
+ const done = (record) => {
1173
+ ended = true;
1174
+ recordedExit ??= writeFileAtomic(join(dir, JOB_HOST_EXIT), record, {
1175
+ encoding: "utf8",
1176
+ timeoutMs: 2_500,
1177
+ maxAttempts: 25,
1178
+ }).catch(() => { }).finally(resolve);
1179
+ };
1180
+ helper.once("exit", (code, signal) => { done(asciiJson({ code: code === null ? null : dword(code), signal })); });
1181
+ helper.once("error", error => { done(asciiJson({ error: String(error?.message ?? error) })); });
1182
+ });
1183
+ const defaultEndHelper = async (pid) => {
1184
+ if (!ended && helper.exitCode === null && helper.signalCode === null && helper.kill("SIGKILL"))
1185
+ return;
1186
+ if (ended)
1187
+ return;
1188
+ const began = await readBeginIdentity(dir);
1189
+ if (began && began.pid === pid && isWinStart(began.start))
1190
+ await killProcess({ pid, start: began.start });
1191
+ };
1192
+ const observe = options.observe ?? (() => winProcessRows()), endHelper = options.endHelper ?? defaultEndHelper, endMs = options.endMs ?? JOB_HOST_END_MS, observeMs = options.observeMs ?? JOB_OBSERVE_MS;
1193
+ const helperPid = helper.pid;
1194
+ /** Refuse only with a confirmed retirement; otherwise adopt the attempt (see the module comment). The owner is this
1195
+ * process's own child, so while it has not ended its pid cannot have been reused: nothing is killed by a bare pid,
1196
+ * and an exit during observation never binds a reused pid. */
1197
+ const refuse = async (reason, knownGroup) => {
1198
+ let failure = "";
1199
+ if (!ended && helperPid !== undefined) {
1200
+ try {
1201
+ await endHelper(helperPid);
1202
+ }
1203
+ catch (error) {
1204
+ failure = `; ending the owner failed (${String(error?.message ?? error)})`;
1205
+ }
1206
+ }
1207
+ if (ended)
1208
+ await exited;
1209
+ else
1210
+ await Promise.race([exited, delay(endMs)]);
1211
+ if (ended)
1212
+ await exited;
1213
+ // The owner ended: its exit closed the group's only handle, so nothing of this attempt can act. Run none of it.
1214
+ if (ended)
1215
+ throw new Error(`${reason}${await startError(dir)}${failure}`);
1216
+ // Not confirmed: the owner may still create the group and run the wrapper. Adopt it instead, with its validated or
1217
+ // handle-persisted identity (its argv tag finds it otherwise), so the attempt is tracked and never duplicated.
1218
+ const group = knownGroup ?? await readGroupRecord(dir).catch(() => undefined);
1219
+ const began = group?.group ?? await readBeginIdentity(dir);
1220
+ const expectedOwnerStart = helperPid !== undefined && began?.pid === helperPid ? began.start : undefined;
1221
+ let rows;
1222
+ try {
1223
+ if (helperPid !== undefined)
1224
+ rows = await observe();
1225
+ }
1226
+ catch { /* unobservable: fall back to the handle-recorded identity and the owner's argv tag */ }
1227
+ if (ended) {
1228
+ await exited;
1229
+ throw new Error(`${reason}${await startError(dir)}${failure}`);
1230
+ }
1231
+ let start = expectedOwnerStart ?? "";
1232
+ if (rows && helperPid !== undefined) {
1233
+ const row = rows.find(item => item.pid === helperPid);
1234
+ if (row) {
1235
+ if (expectedOwnerStart !== undefined) {
1236
+ start = sameCreation(row.start, expectedOwnerStart) ? row.start : expectedOwnerStart;
1237
+ }
1238
+ else if (matchesOwnerTag(row.command, launch)) {
1239
+ start = row.start;
1240
+ }
1241
+ }
1242
+ }
1243
+ // The owner outlives this process by design (the command must): its end is a wake-up, never a held event loop.
1244
+ if (options.unref !== false)
1245
+ helper.unref();
1246
+ return { pid: helperPid ?? 0, start, uncertain: `${reason}${await startError(dir)}${failure}`, killOwner, requestStop, exited };
1247
+ };
1248
+ try {
1249
+ await new Promise((resolve, reject) => { helper.once("spawn", resolve); helper.once("error", reject); });
1250
+ }
1251
+ catch (error) {
1252
+ return refuse(`the command job host could not start (${String(error?.message ?? error)})`);
1253
+ }
1254
+ // The handshake: the group record appears before the wrapper may run, and a file the owner holds for a moment is not a
1255
+ // failure -- it is still starting or renaming the record onto its name.
1256
+ const timeoutMs = options.timeoutMs ?? JOB_START_TIMEOUT_MS, deadline = Date.now() + timeoutMs;
1257
+ let recorded;
1258
+ try {
1259
+ for (;;) {
1260
+ recorded = await readGroupRecord(dir);
1261
+ if (recorded !== undefined)
1262
+ break;
1263
+ if (ended) {
1264
+ await exited;
1265
+ recorded = await readGroupRecord(dir);
1266
+ if (recorded !== undefined)
1267
+ break;
1268
+ throw new Error("the command job host ended before the command could start");
1269
+ }
1270
+ if (Date.now() >= deadline)
1271
+ throw new Error(`the command job host reported no group within ${timeoutMs} ms`);
1272
+ await delay(10);
1273
+ }
1274
+ }
1275
+ catch (error) {
1276
+ return refuse(String(error?.message ?? error), recorded);
1277
+ }
1278
+ const pid = recorded.pid;
1279
+ // One process-table observation for both identities, validated against the handle-recorded creation times from the
1280
+ // owner so an early wrapper/owner exit followed by pid reuse can never bind an unrelated process.
1281
+ let rows;
1282
+ try {
1283
+ rows = await observeWithin(observe, Math.min(observeMs, deadline - Date.now()));
1284
+ }
1285
+ catch (error) {
1286
+ return refuse(`the command job group could not be observed (${String(error?.message ?? error)})`, recorded);
1287
+ }
1288
+ if (ended) {
1289
+ if (options.unref !== false)
1290
+ helper.unref();
1291
+ return { pid, start: "", killOwner, requestStop, exited };
1292
+ }
1293
+ const began = recorded.group ?? await readBeginIdentity(dir);
1294
+ const expectedOwnerStart = helperPid !== undefined && began?.pid === helperPid ? began.start : undefined;
1295
+ const ownerRow = helperPid === undefined ? undefined : rows.find(row => row.pid === helperPid);
1296
+ const ownerReplaced = Boolean(ownerRow && expectedOwnerStart !== undefined && !sameCreation(ownerRow.start, expectedOwnerStart));
1297
+ let helperStart = "";
1298
+ if (helperPid !== undefined && !ownerReplaced) {
1299
+ if (ownerRow) {
1300
+ if (expectedOwnerStart !== undefined)
1301
+ helperStart = ownerRow.start;
1302
+ else if (matchesOwnerTag(ownerRow.command, launch))
1303
+ helperStart = ownerRow.start;
1304
+ }
1305
+ else if (expectedOwnerStart !== undefined && !existsSync(join(dir, JOB_END))) {
1306
+ helperStart = expectedOwnerStart;
1307
+ }
1308
+ }
1309
+ const childRow = ownerReplaced ? undefined : rows.find(row => row.pid === pid);
1310
+ // Whether the owner recorded the wrapper's end (group-end). Without it the wrapper's exit was never recorded (the owner
1311
+ // was ended while the wrapper ran, say), so the only identity of the attempt is the creation time the owner took from
1312
+ // the wrapper's own process handle before it resumed it (the group record).
1313
+ const endRecorded = existsSync(join(dir, JOB_END));
1314
+ let start = "";
1315
+ if (childRow) {
1316
+ if (recorded.start !== undefined) {
1317
+ // The observed row is the wrapper only when its ticks are the recorded instance's. A row that disagrees is another
1318
+ // process that reused the pid: its ticks are never taken. Without an end record that row also proves the wrapper
1319
+ // exited, so the handle-recorded identity is the attempt's -- recorded as is, never replaced by the recycled row.
1320
+ start = sameCreation(childRow.start, recorded.start) ? childRow.start : endRecorded ? "" : recorded.start;
1321
+ }
1322
+ else if (!endRecorded &&
1323
+ ((helperPid !== undefined && childRow.ppid === helperPid) || (!!launch.exec && winTag(childRow.command, "DSA_EXEC") === launch.exec))) {
1324
+ start = childRow.start;
1325
+ }
1326
+ }
1327
+ else if (!ownerReplaced && recorded.start !== undefined && !endRecorded) {
1328
+ start = recorded.start;
1329
+ }
1330
+ if (options.unref !== false)
1331
+ helper.unref(); // the owner outlives this process by design: its end is a wake-up, never a held event loop
1332
+ return { pid, start, ...(helperPid !== undefined && helperStart ? { group: { pid: helperPid, start: helperStart } } : {}), killOwner, requestStop, exited };
1333
+ }
1334
+ /** The reason an owner left, when it left one, appended to the failure a call reports: whether it ever ran, why its
1335
+ * process ended, and the bounded first line of what it wrote. Nothing to say is "".
1336
+ * Bounded and credential-free: an evidence file contributes one clipped line, and the value of a variable whose name
1337
+ * says it holds a secret is redacted -- the owner may quote what the caller handed it. */
1338
+ export async function startError(dir) {
1339
+ const [error, log, exit, began] = await Promise.all([
1340
+ read(join(dir, JOB_ERROR), "head"), read(join(dir, JOB_HOST_LOG), "tail"),
1341
+ read(join(dir, JOB_HOST_EXIT), "head"), existsSync(join(dir, JOB_BEGIN)),
1342
+ ]);
1343
+ const notes = [];
1344
+ const end = endRecord(exit);
1345
+ if (end?.error)
1346
+ notes.push(`the job host could not be started (${oneLine(end.error)})`);
1347
+ else if (end?.code !== undefined)
1348
+ notes.push(began ? `the job host exited with code ${end.code}`
1349
+ : `the job host exited with code ${end.code} before it reported starting`);
1350
+ // A recorded failure is a message (quoted from its start); the owner's own log is quoted from its end, where the
1351
+ // newest lines are. Either way it is one clipped line, with credential-shaped values redacted: the owner may quote
1352
+ // back what the caller handed it (the compiler quotes the paths it was given).
1353
+ const evidence = clip(redact(oneLine(error || log)), EVIDENCE_LIMIT, error ? "head" : "tail");
1354
+ const reason = [evidence, notes.join(", ")].filter(Boolean).join("; ");
1355
+ return reason ? `: ${clip(reason, REASON_LIMIT)}` : "";
1356
+ }
1357
+ /** What the recorded end of the owner says (undefined when it recorded nothing readable). */
1358
+ function endRecord(text) {
1359
+ if (!text.trim())
1360
+ return undefined;
1361
+ let record;
1362
+ try {
1363
+ record = JSON.parse(text);
1364
+ }
1365
+ catch {
1366
+ return undefined;
1367
+ }
1368
+ if (typeof record.error === "string" && record.error)
1369
+ return { error: record.error };
1370
+ const code = typeof record.code === "number" && Number.isInteger(record.code) ? record.code : undefined;
1371
+ const signal = typeof record.signal === "string" && record.signal ? record.signal : undefined;
1372
+ return code === undefined && signal === undefined ? undefined : { code, signal };
1373
+ }
1374
+ /** At most {@link REASON_BYTES} of a file -- its beginning (a message) or its end (a log's newest lines) -- as UTF-8.
1375
+ * "" when the file is absent or transiently unreadable after bounded retries, so evidence never grows a reason. */
1376
+ async function read(path, part) {
1377
+ const file = await retryWinSharing(() => open(path, "r"), { timeoutMs: 1_000, maxAttempts: 15 })
1378
+ .catch((error) => { if (absent(error) || transientRead(error))
1379
+ return undefined; throw error; });
1380
+ if (!file)
1381
+ return "";
1382
+ try {
1383
+ const { size } = await file.stat(), length = Math.min(size, REASON_BYTES);
1384
+ if (length <= 0)
1385
+ return "";
1386
+ const buffer = Buffer.alloc(length);
1387
+ await file.read(buffer, 0, length, part === "head" ? 0 : size - length);
1388
+ return buffer.toString("utf8").replace(/^\uFEFF/, "");
1389
+ }
1390
+ finally {
1391
+ await file.close();
1392
+ }
1393
+ }
1394
+ /** Shapes a failure reason never repeats: an assignment to a name that says it holds a secret, and user info in a URL. */
1395
+ const SECRETS = [
1396
+ [/([A-Za-z0-9_.-]*(?:KEY|TOKEN|SECRET|PASS|PASSWORD|CREDENTIAL|AUTH|COOKIE|SESSION)[A-Za-z0-9_.-]*\s*[=:]\s*)(?:"[^"]*"|'[^']*'|(?:(?:bearer|basic|token|digest)\s+)?[^\s"',;]+)/gi, "$1<redacted>"],
1397
+ [/([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^\s/@]+@/g, "$1<redacted>@"],
1398
+ ];
1399
+ function redact(text) { let out = text; for (const [pattern, instead] of SECRETS)
1400
+ out = out.replace(pattern, instead); return out; }
1401
+ const oneLine = (text) => text.replace(/\s+/g, " ").trim();
1402
+ /** At most `limit` characters, keeping the beginning (a message) or the end (a log's newest lines). */
1403
+ const clip = (text, limit, part = "head") => text.length <= limit ? text
1404
+ : part === "head" ? `${text.slice(0, limit - 1)}…` : `…${text.slice(-(limit - 1))}`;