@mostra/runtime 0.2.0 → 0.3.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 (58) hide show
  1. package/dist/bin.js +7 -7
  2. package/dist/bin.js.map +1 -1
  3. package/dist/builder/child/main.js +18 -17
  4. package/dist/builder/child/main.js.map +1 -1
  5. package/dist/{child-xrHmytks.js → child-BQc3arf7.js} +5 -2
  6. package/dist/{child-xrHmytks.js.map → child-BQc3arf7.js.map} +1 -1
  7. package/dist/deps/child/install.js +9 -6
  8. package/dist/deps/child/install.js.map +1 -1
  9. package/dist/files-KxzOxckl.js +674 -0
  10. package/dist/files-KxzOxckl.js.map +1 -0
  11. package/dist/index.d.ts +2 -0
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +2 -2
  14. package/dist/{instance-CzBkUyHu.js → instance-DiKSe7s6.js} +1148 -737
  15. package/dist/instance-DiKSe7s6.js.map +1 -0
  16. package/package.json +5 -5
  17. package/src/bin.ts +4 -10
  18. package/src/builder/child/dev.ts +4 -3
  19. package/src/builder/child/plugins.ts +12 -7
  20. package/src/builder/child/spa.ts +15 -9
  21. package/src/builder/index.ts +3 -6
  22. package/src/deps/child/install.ts +3 -2
  23. package/src/deps/index.ts +21 -16
  24. package/src/deps/warm.ts +3 -16
  25. package/src/faults.ts +9 -2
  26. package/src/gateway/capabilities.ts +2 -2
  27. package/src/home/acquire.ts +27 -11
  28. package/src/home/paths.ts +45 -135
  29. package/src/home/platform.ts +17 -9
  30. package/src/home/record.ts +3 -3
  31. package/src/home/settings.ts +5 -16
  32. package/src/instance/index.ts +31 -7
  33. package/src/ledger/index.ts +5 -27
  34. package/src/platform/control.ts +409 -0
  35. package/src/platform/directories.ts +212 -0
  36. package/src/platform/environment.ts +64 -0
  37. package/src/platform/files.ts +368 -0
  38. package/src/platform/helper.ts +152 -0
  39. package/src/{processes → platform}/identity.ts +40 -8
  40. package/src/platform/index.ts +46 -0
  41. package/src/platform/launch.ts +373 -0
  42. package/src/processes/child.ts +4 -1
  43. package/src/processes/environment.ts +22 -3
  44. package/src/processes/index.ts +2 -1
  45. package/src/processes/manager.ts +76 -179
  46. package/src/protocol-server/client.ts +19 -18
  47. package/src/protocol-server/server.ts +75 -54
  48. package/src/publish/publisher.ts +16 -9
  49. package/src/publish/source.ts +7 -4
  50. package/src/registry/store.ts +7 -65
  51. package/src/secrets/index.ts +2 -2
  52. package/src/service/unit.ts +3 -2
  53. package/src/verify/index.ts +5 -3
  54. package/src/verify/typecheck.ts +3 -2
  55. package/src/workers/launcher.ts +3 -1
  56. package/dist/instance-CzBkUyHu.js.map +0 -1
  57. package/dist/types-NjNy7gXX.js +0 -57
  58. package/dist/types-NjNy7gXX.js.map +0 -1
@@ -0,0 +1,368 @@
1
+ /**
2
+ * File operations whose semantics differ between POSIX and Windows (FAILURE_MODEL §3, RT-10):
3
+ *
4
+ * - **Renames.** Windows refuses to replace or move a file another process has open without
5
+ * sharing deletion, and antivirus scanners and the search indexer open new files for a moment
6
+ * after they are written. A rename that meets a sharing violation is tried again for a short
7
+ * while (`EPERM`, `EACCES`, `EBUSY`), never weakened into a copy: the step stays atomic or fails.
8
+ * - **Syncing.** Windows syncs a file only through a handle open for writing.
9
+ * - **Directory links.** A directory symlink needs a privilege most Windows users don't hold;
10
+ * junctions need none, and Node.js and pnpm resolve through them like symlinks.
11
+ * - **Sealing.** A sealed version is read-only for everyone (0444 files and 0555 directories on
12
+ * POSIX; on Windows an access list granting only reading, applied by the helper). Its owner can
13
+ * always unseal it, as on POSIX.
14
+ * - **Names.** Windows file names are case-insensitive: two names that differ only in case are
15
+ * one file.
16
+ */
17
+ import { closeSync, type Dirent, fsyncSync, openSync, renameSync, statSync } from "node:fs";
18
+ import {
19
+ chmod,
20
+ lstat,
21
+ mkdir,
22
+ readdir,
23
+ readFile,
24
+ readlink,
25
+ realpath,
26
+ rename,
27
+ rm,
28
+ rmdir,
29
+ symlink,
30
+ unlink,
31
+ writeFile,
32
+ } from "node:fs/promises";
33
+ import { join, resolve } from "node:path";
34
+ import { WINDOWS } from "./directories.ts";
35
+ import { runHelperAsync } from "./helper.ts";
36
+
37
+ /** Errors a Windows rename or removal meets while another process briefly holds the file. */
38
+ const TRANSIENT = new Set(["EPERM", "EACCES", "EBUSY", "ENOTEMPTY"]);
39
+ /** How long a rename keeps trying through sharing violations. */
40
+ const RETRY_MS = 3000;
41
+
42
+ const errno = (error: unknown): string | undefined => (error as NodeJS.ErrnoException).code;
43
+
44
+ const sleep = (ms: number): Promise<void> => new Promise((done) => setTimeout(done, ms));
45
+
46
+ function sleepSync(ms: number): void {
47
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
48
+ }
49
+
50
+ /**
51
+ * Renames `from` to `to`, replacing a file at `to` (POSIX `rename`). On Windows a sharing
52
+ * violation is retried with backoff for up to 3 s before it is thrown.
53
+ */
54
+ export async function renamePath(from: string, to: string): Promise<void> {
55
+ const deadline = Date.now() + RETRY_MS;
56
+ for (let wait = 10; ; wait = Math.min(wait * 2, 250)) {
57
+ try {
58
+ await rename(from, to);
59
+ return;
60
+ } catch (error) {
61
+ if (!WINDOWS || !TRANSIENT.has(errno(error) ?? "") || Date.now() >= deadline) throw error;
62
+ await sleep(wait);
63
+ }
64
+ }
65
+ }
66
+
67
+ /** {@link renamePath}, blocking. */
68
+ export function renamePathSync(from: string, to: string): void {
69
+ const deadline = Date.now() + RETRY_MS;
70
+ for (let wait = 10; ; wait = Math.min(wait * 2, 250)) {
71
+ try {
72
+ renameSync(from, to);
73
+ return;
74
+ } catch (error) {
75
+ if (!WINDOWS || !TRANSIENT.has(errno(error) ?? "") || Date.now() >= deadline) throw error;
76
+ sleepSync(wait);
77
+ }
78
+ }
79
+ }
80
+
81
+ /**
82
+ * Syncs a file or a directory to disk. A file that can't be synced fails the caller (its bytes
83
+ * would not be durable); a directory may not support it on some file systems (Windows can't open
84
+ * one this way at all), and only that case is tolerated.
85
+ */
86
+ export function fsyncPath(path: string, directory = false): void {
87
+ if (directory && WINDOWS) {
88
+ // NTFS journals directory changes, and Windows can't sync a directory; it must exist, though.
89
+ statSync(path);
90
+ return;
91
+ }
92
+ let fd: number | undefined;
93
+ try {
94
+ // Windows flushes a file only through a handle that may write (VERIFIED_FACTS, WP-W1).
95
+ fd = openSync(path, WINDOWS ? "r+" : "r");
96
+ fsyncSync(fd);
97
+ } catch (error) {
98
+ const code = errno(error);
99
+ const unsupported = ["EINVAL", "ENOTSUP", "EISDIR", "EPERM", "EACCES"];
100
+ if (!directory || !unsupported.includes(code ?? "")) throw error;
101
+ } finally {
102
+ if (fd !== undefined) closeSync(fd);
103
+ }
104
+ }
105
+
106
+ /**
107
+ * Makes `path` a link to the `node_modules`-like directory `target`: a symlink on POSIX; on
108
+ * Windows a {@link linkFarm}, since a junction to the directory would break the relative links
109
+ * inside it (pnpm's), which Windows resolves against the path they were reached by (VERIFIED_FACTS,
110
+ * WP-W1).
111
+ */
112
+ export async function linkDirectory(target: string, path: string): Promise<void> {
113
+ if (WINDOWS) await linkFarm(target, path);
114
+ else await symlink(target, path, "dir");
115
+ }
116
+
117
+ /** The marker a link farm keeps: what it mirrors, and the entries it mirrored. */
118
+ const FARM_MARKER = ".mostra-link";
119
+
120
+ /** Every entry of a `node_modules`-like directory, scoped ones as `@scope/name`, dot entries left out. */
121
+ async function farmEntries(target: string): Promise<{ name: string; real: string }[]> {
122
+ const names: string[] = [];
123
+ for (const entry of await readdir(target, { withFileTypes: true })) {
124
+ if (entry.name.startsWith(".")) continue;
125
+ if (entry.name.startsWith("@") && entry.isDirectory()) {
126
+ for (const scoped of await readdir(join(target, entry.name)))
127
+ names.push(`${entry.name}/${scoped}`);
128
+ } else names.push(entry.name);
129
+ }
130
+ const entries: { name: string; real: string }[] = [];
131
+ for (const name of names.sort()) {
132
+ try {
133
+ entries.push({ name, real: await realpath(join(target, ...name.split("/"))) });
134
+ } catch {
135
+ // A dangling link brings nothing in, as through a directory link.
136
+ }
137
+ }
138
+ return entries;
139
+ }
140
+
141
+ /**
142
+ * A directory that stands for `target`: one junction per entry, to the entry's real path, so every
143
+ * link inside resolves from where it really is, and a marker naming what it mirrors. Built aside
144
+ * and renamed into place, so `path` is either missing or complete. Used on Windows; it works on
145
+ * POSIX too, where the tests exercise it.
146
+ */
147
+ export async function linkFarm(target: string, path: string): Promise<void> {
148
+ const source = resolve(target);
149
+ const entries = await farmEntries(source);
150
+ const building = `${path}.${process.pid}.${Date.now()}.farm`;
151
+ await mkdir(building, { recursive: true });
152
+ try {
153
+ for (const entry of entries) {
154
+ const at = join(building, ...entry.name.split("/"));
155
+ if (entry.name.includes("/")) await mkdir(join(at, ".."), { recursive: true });
156
+ await symlink(entry.real, at, "junction");
157
+ }
158
+ await writeFile(
159
+ join(building, FARM_MARKER),
160
+ `${JSON.stringify({ target: source, entries })}\n`,
161
+ );
162
+ await renamePath(building, path);
163
+ } catch (error) {
164
+ await removeFarm(building).catch(() => {});
165
+ throw error;
166
+ }
167
+ }
168
+
169
+ /** Removes a link farm's junctions, never what they point to, then its directories. */
170
+ async function removeFarm(path: string): Promise<void> {
171
+ for (const entry of await readdir(path, { withFileTypes: true }).catch(() => [])) {
172
+ const at = join(path, entry.name);
173
+ if (entry.isSymbolicLink()) await unlinkEntry(at);
174
+ else if (entry.isDirectory()) await removeFarm(at);
175
+ else await rm(at, { force: true });
176
+ }
177
+ await rmdir(path);
178
+ }
179
+
180
+ /** Removes one link: on Windows a junction is removed as the directory entry it is. */
181
+ async function unlinkEntry(path: string): Promise<void> {
182
+ try {
183
+ await unlink(path);
184
+ } catch (error) {
185
+ if (!WINDOWS || errno(error) !== "EPERM") throw error;
186
+ await rmdir(path);
187
+ }
188
+ }
189
+
190
+ /**
191
+ * What the directory link `path` stands for, or `undefined` when it is missing, isn't a link, or
192
+ * (a link farm) no longer mirrors its target's current entries.
193
+ */
194
+ export async function linkTarget(path: string): Promise<string | undefined> {
195
+ try {
196
+ const info = await lstat(path);
197
+ if (info.isSymbolicLink()) return resolve(join(path, ".."), await readlink(path));
198
+ if (!info.isDirectory()) return undefined;
199
+ const marker = JSON.parse(await readFile(join(path, FARM_MARKER), "utf8")) as {
200
+ target: string;
201
+ entries: { name: string; real: string }[];
202
+ };
203
+ const now = await farmEntries(marker.target);
204
+ return JSON.stringify(now) === JSON.stringify(marker.entries) ? marker.target : undefined;
205
+ } catch {
206
+ return undefined;
207
+ }
208
+ }
209
+
210
+ /**
211
+ * Points the directory link `path` at `target`, replacing what it pointed at with no moment
212
+ * where `path` is missing on POSIX (a new link renamed over it). Windows can't rename a link over
213
+ * an existing directory entry, so the old link is renamed aside first and removed after.
214
+ */
215
+ export async function replaceDirectoryLink(target: string, path: string): Promise<void> {
216
+ const fresh = `${path}.${process.pid}.${Date.now()}.new`;
217
+ await linkDirectory(target, fresh);
218
+ if (!WINDOWS) {
219
+ await rename(fresh, path);
220
+ return;
221
+ }
222
+ const aside = `${path}.${process.pid}.${Date.now()}.old`;
223
+ let moved = false;
224
+ try {
225
+ await renamePath(path, aside);
226
+ moved = true;
227
+ } catch (error) {
228
+ if (errno(error) !== "ENOENT") {
229
+ await unlinkDirectory(fresh);
230
+ throw error;
231
+ }
232
+ }
233
+ await renamePath(fresh, path);
234
+ if (moved) await unlinkDirectory(aside);
235
+ }
236
+
237
+ /**
238
+ * `path` without the separators it ends in (a loop: a regular expression here is quadratic). On
239
+ * POSIX a backslash is an ordinary character of a name, never a separator.
240
+ */
241
+ function trimSeparators(path: string): string {
242
+ let end = path.length;
243
+ while (end > 0 && (path[end - 1] === "/" || (WINDOWS && path[end - 1] === "\\"))) end--;
244
+ return path.slice(0, end);
245
+ }
246
+
247
+ /** Whether a link points at `target` (paths compared as this file system compares them). */
248
+ export function samePath(a: string, b: string): boolean {
249
+ const normal = (path: string): string =>
250
+ nameKey(trimSeparators(resolve(path.startsWith("\\\\?\\") ? path.slice(4) : path)));
251
+ return normal(a) === normal(b);
252
+ }
253
+
254
+ /**
255
+ * A path as a key for comparison: `/`-separated, without a trailing `/`, and on Windows in lower
256
+ * case, since Windows names compare without case and bundlers spell `C:\x` as `C:/x`. The key has
257
+ * the path's length, so an index found in it holds in the path too.
258
+ */
259
+ export function pathKey(path: string): string {
260
+ // Only Windows spells a separator `\\`; on POSIX it is part of a name (Opus review of WP-W1).
261
+ return nameKey(WINDOWS ? path.replaceAll("\\", "/") : path);
262
+ }
263
+
264
+ /** Whether `file` is `dir` itself or lies under it, however either spells its separators. */
265
+ export function isUnder(file: string, dir: string): boolean {
266
+ const key = pathKey(file);
267
+ const root = trimSeparators(pathKey(dir));
268
+ return key === root || key.startsWith(`${root}/`);
269
+ }
270
+
271
+ /** Removes a link made by {@link linkDirectory}, never what it points to. */
272
+ export async function unlinkDirectory(path: string): Promise<void> {
273
+ let info: Awaited<ReturnType<typeof lstat>>;
274
+ try {
275
+ info = await lstat(path);
276
+ } catch (error) {
277
+ if (errno(error) === "ENOENT") return;
278
+ throw error;
279
+ }
280
+ if (info.isDirectory() && !info.isSymbolicLink()) await removeFarm(path);
281
+ else await unlinkEntry(path);
282
+ }
283
+
284
+ /** Calls `visit` for every entry under `dir`, children before their directory. */
285
+ async function walk(
286
+ dir: string,
287
+ visit: (path: string, isDirectory: boolean) => Promise<void>,
288
+ ): Promise<void> {
289
+ const entries: Dirent[] = await readdir(dir, { withFileTypes: true });
290
+ for (const entry of entries) {
291
+ const path = join(dir, entry.name);
292
+ if (entry.isDirectory()) await walk(path, visit);
293
+ await visit(path, entry.isDirectory());
294
+ }
295
+ }
296
+
297
+ /**
298
+ * Makes a tree read-only and syncs it to disk. On POSIX the top directory is left writable when
299
+ * `keepTop` is set, since renaming a directory needs write access to it; on Windows the whole tree
300
+ * is synced first and sealed in one step after it is in place ({@link sealPlaced}).
301
+ */
302
+ export async function sealTree(dir: string, keepTop = false): Promise<void> {
303
+ if (WINDOWS) {
304
+ await walk(dir, async (path, isDirectory) => {
305
+ if (!isDirectory) fsyncPath(path);
306
+ });
307
+ return;
308
+ }
309
+ await walk(dir, async (path, isDirectory) => {
310
+ await chmod(path, isDirectory ? 0o555 : 0o444);
311
+ fsyncPath(path, isDirectory);
312
+ });
313
+ if (!keepTop) await chmod(dir, 0o555);
314
+ fsyncPath(dir, true);
315
+ }
316
+
317
+ /**
318
+ * Finishes sealing a tree that is in its final place: on POSIX its top directory becomes 0555; on
319
+ * Windows the whole tree gets the read-only access list (moving a sealed directory would need the
320
+ * delete right the seal withholds).
321
+ */
322
+ export async function sealPlaced(dir: string): Promise<void> {
323
+ if (WINDOWS) {
324
+ await runHelperAsync(["seal", dir]);
325
+ return;
326
+ }
327
+ await chmod(dir, 0o555);
328
+ fsyncPath(dir, true);
329
+ }
330
+
331
+ /** Removes a tree, sealed or not. Missing trees are fine. Links inside are removed, never followed. */
332
+ export async function removeTree(dir: string): Promise<void> {
333
+ let info: Awaited<ReturnType<typeof lstat>>;
334
+ try {
335
+ info = await lstat(dir);
336
+ } catch {
337
+ return;
338
+ }
339
+ if (info.isDirectory() && !WINDOWS) {
340
+ await chmod(dir, 0o755);
341
+ await walk(dir, async (path, isDirectory) => {
342
+ if (isDirectory) await chmod(path, 0o755);
343
+ }).catch(() => {});
344
+ }
345
+ const deadline = Date.now() + RETRY_MS;
346
+ let unsealed = false;
347
+ for (let wait = 10; ; wait = Math.min(wait * 2, 250)) {
348
+ try {
349
+ await rm(dir, { recursive: true, force: true });
350
+ return;
351
+ } catch (error) {
352
+ if (!WINDOWS || !TRANSIENT.has(errno(error) ?? "") || Date.now() >= deadline) throw error;
353
+ // A sealed version refuses deletion until its access list is the owner's again; only
354
+ // sealed trees need it, and they hold no links the reset could follow.
355
+ if (!unsealed && info.isDirectory()) {
356
+ unsealed = true;
357
+ await runHelperAsync(["unseal", dir]).catch(() => {});
358
+ continue;
359
+ }
360
+ await sleep(wait);
361
+ }
362
+ }
363
+ }
364
+
365
+ /** The form under which two file names are the same name on this file system. */
366
+ export function nameKey(name: string): string {
367
+ return WINDOWS ? name.toLowerCase() : name;
368
+ }
@@ -0,0 +1,152 @@
1
+ /**
2
+ * Running `mostra-win`, the Windows platform helper (`crates/mostra-win`, WP-W1): finding it and
3
+ * reading its one-line JSON answers. The runtime asks it for what Node.js can't do on Windows:
4
+ * owner-only access control, process identity by creation time, the child gate and reaping, and
5
+ * the owner-only control pipe. Only this module's Windows code calls it.
6
+ */
7
+ import { execFileSync, spawn } from "node:child_process";
8
+ import { existsSync, readFileSync } from "node:fs";
9
+ import { dirname, join, resolve } from "node:path";
10
+ import { fileURLToPath } from "node:url";
11
+ import { createDiagnostic, RpcError } from "@mostra/protocol";
12
+
13
+ /** The name `bundle.json` gives a runtime bundle (D142). */
14
+ const BUNDLE_NAME = "mostra-runtime-bundle";
15
+
16
+ /** The directory of `@mostra/runtime`'s `package.json`, wherever the code runs from. */
17
+ export function runtimeRoot(): string {
18
+ let dir = dirname(fileURLToPath(import.meta.url));
19
+ for (;;) {
20
+ const manifest = join(dir, "package.json");
21
+ if (existsSync(manifest)) {
22
+ const { name } = JSON.parse(readFileSync(manifest, "utf8")) as { name?: string };
23
+ if (name === "@mostra/runtime") return dir;
24
+ }
25
+ const parent = dirname(dir);
26
+ if (parent === dir) throw new Error("Couldn't find @mostra/runtime's package.json.");
27
+ dir = parent;
28
+ }
29
+ }
30
+
31
+ /** The runtime bundle the runtime sits in (four levels above its package), if any. */
32
+ function enclosingBundle(root: string): string | undefined {
33
+ const bundle = resolve(root, "..", "..", "..", "..");
34
+ try {
35
+ const info = JSON.parse(readFileSync(join(bundle, "bundle.json"), "utf8")) as {
36
+ name?: unknown;
37
+ };
38
+ return info.name === BUNDLE_NAME ? bundle : undefined;
39
+ } catch {
40
+ return undefined;
41
+ }
42
+ }
43
+
44
+ let located: string | undefined;
45
+
46
+ /**
47
+ * The helper's path: `MOSTRA_WIN_HELPER`; else the runtime bundle's `bin/mostra-win.exe`; else,
48
+ * in a development checkout, the one Cargo built (`target/release`, then `target/debug`). Throws
49
+ * `MOSTRA_ENV_HELPER_MISSING` when none exists.
50
+ */
51
+ export function helperPath(env: NodeJS.ProcessEnv = process.env): string {
52
+ const override = env["MOSTRA_WIN_HELPER"];
53
+ if (override) {
54
+ if (!existsSync(override))
55
+ throw missing(`MOSTRA_WIN_HELPER names ${override}, which doesn't exist.`);
56
+ return override;
57
+ }
58
+ if (located !== undefined) return located;
59
+ const root = runtimeRoot();
60
+ const bundle = enclosingBundle(root);
61
+ const candidates =
62
+ bundle !== undefined
63
+ ? [join(bundle, "bin", "mostra-win.exe")]
64
+ : ["release", "debug"].map((profile) =>
65
+ resolve(root, "..", "..", "target", profile, "mostra-win.exe"),
66
+ );
67
+ const found = candidates.find((candidate) => existsSync(candidate));
68
+ if (found === undefined) {
69
+ throw missing(`Mostra's Windows helper isn't installed; looked for ${candidates.join(", ")}.`);
70
+ }
71
+ located = found;
72
+ return found;
73
+ }
74
+
75
+ function missing(message: string): RpcError {
76
+ return new RpcError(createDiagnostic("MOSTRA_ENV_HELPER_MISSING", { message }));
77
+ }
78
+
79
+ /** What the helper answers. */
80
+ type Answer<T> =
81
+ | { readonly ok: true; readonly result: T }
82
+ | { readonly ok: false; readonly error: { readonly message: string; readonly os?: number } };
83
+
84
+ /** A failure the helper reported, with the Windows error code when there is one. */
85
+ export class HelperError extends Error {
86
+ readonly os: number | undefined;
87
+ constructor(command: string, message: string, os: number | undefined) {
88
+ super(`mostra-win ${command}: ${message}`);
89
+ this.os = os;
90
+ }
91
+ }
92
+
93
+ function parse<T>(command: string, stdout: string): T {
94
+ const line = stdout.trim().split("\n").at(-1) ?? "";
95
+ let answer: Answer<T>;
96
+ try {
97
+ answer = JSON.parse(line) as Answer<T>;
98
+ } catch {
99
+ throw new HelperError(
100
+ command,
101
+ `answered something that isn't JSON: ${line.slice(0, 200)}`,
102
+ undefined,
103
+ );
104
+ }
105
+ if (!answer.ok)
106
+ throw new HelperError(command, answer.error.message, answer.error.os ?? undefined);
107
+ return answer.result;
108
+ }
109
+
110
+ /** Runs a helper command and returns its result; for the calls that must finish before going on. */
111
+ export function runHelper<T>(args: readonly string[]): T {
112
+ const helper = helperPath();
113
+ let stdout: string;
114
+ try {
115
+ stdout = execFileSync(helper, args, {
116
+ encoding: "utf8",
117
+ windowsHide: true,
118
+ stdio: ["ignore", "pipe", "pipe"],
119
+ });
120
+ } catch (error) {
121
+ const failed = error as { stdout?: string; message: string };
122
+ if (failed.stdout) return parse<T>(args[0] ?? "", failed.stdout);
123
+ throw new HelperError(args[0] ?? "", failed.message, undefined);
124
+ }
125
+ return parse<T>(args[0] ?? "", stdout);
126
+ }
127
+
128
+ /** Runs a helper command without blocking the event loop. */
129
+ export function runHelperAsync<T>(args: readonly string[]): Promise<T> {
130
+ const helper = helperPath();
131
+ return new Promise((resolvePromise, reject) => {
132
+ const child = spawn(helper, args, { windowsHide: true, stdio: ["ignore", "pipe", "pipe"] });
133
+ let stdout = "";
134
+ let stderr = "";
135
+ child.stdout.setEncoding("utf8");
136
+ child.stderr.setEncoding("utf8");
137
+ child.stdout.on("data", (chunk: string) => {
138
+ stdout += chunk;
139
+ });
140
+ child.stderr.on("data", (chunk: string) => {
141
+ stderr += chunk;
142
+ });
143
+ child.once("error", reject);
144
+ child.once("close", () => {
145
+ try {
146
+ resolvePromise(parse<T>(args[0] ?? "", stdout || stderr));
147
+ } catch (error) {
148
+ reject(error);
149
+ }
150
+ });
151
+ });
152
+ }
@@ -3,7 +3,9 @@
3
3
  * reused, so a process is identified by its PID plus an opaque start time: the boot it started in
4
4
  * and when it started within that boot. Linux reads `/proc/<pid>/stat` (start ticks since boot)
5
5
  * and the boot ID; macOS reads `ps -o lstart` (seconds) and `kern.boottime` (VERIFIED_FACTS,
6
- * WP-02). Zombies count as gone: they have exited and only wait for their parent.
6
+ * WP-02); Windows asks the helper for the creation time (`GetProcessTimes`, 100 ns units since
7
+ * 1601, so absolute across boots), written `win/<creation time>` (VERIFIED_FACTS, WP-W1). Zombies,
8
+ * and Windows processes that exited but whose object a handle still keeps, count as gone.
7
9
  *
8
10
  * Seconds are enough on macOS (issue #8): XNU hands out PIDs in order from the last one, up to
9
11
  * 99,999, then from 100, skipping any PID still used as a process, process group or session
@@ -13,22 +15,28 @@
13
15
  */
14
16
  import { execFile } from "node:child_process";
15
17
  import { readdir, readFile } from "node:fs/promises";
18
+ import { runHelperAsync } from "./helper.ts";
19
+
20
+ /** The boot part of every Windows start time: creation times are absolute. */
21
+ const WINDOWS_BOOT = "win";
16
22
 
17
23
  /** One running process as the operating system reports it. */
18
24
  export interface ProcessInfo {
19
25
  readonly pid: number;
20
- /** Its process group. */
26
+ /** Its process group; on Windows, where processes have none, its own PID. */
21
27
  readonly pgid: number;
22
28
  /** `<boot>/<start>`: opaque, but comparable with {@link startedNoEarlier} within one boot. */
23
29
  readonly startTime: string;
24
30
  }
25
31
 
26
32
  /** Splits a start time into its boot and its position within the boot. */
27
- function parts(startTime: string): { boot: string; at: number } | undefined {
33
+ function parts(startTime: string): { boot: string; at: bigint } | undefined {
28
34
  const slash = startTime.lastIndexOf("/");
29
35
  if (slash <= 0) return undefined;
30
- const at = Number(startTime.slice(slash + 1));
31
- return Number.isSafeInteger(at) ? { boot: startTime.slice(0, slash), at } : undefined;
36
+ const text = startTime.slice(slash + 1);
37
+ // Seconds on macOS, ticks on Linux, 100 ns units since 1601 on Windows (past 2^53).
38
+ if (!/^\d+$/.test(text)) return undefined;
39
+ return { boot: startTime.slice(0, slash), at: BigInt(text) };
32
40
  }
33
41
 
34
42
  /** Whether two start times belong to the same boot of the machine. */
@@ -126,9 +134,10 @@ function run(file: string, args: readonly string[]): Promise<{ code: number; std
126
134
 
127
135
  let cachedBoot: Promise<string> | undefined;
128
136
 
129
- /** The identity of the current boot of this machine. */
137
+ /** The identity of the current boot of this machine (on Windows a constant: times are absolute). */
130
138
  export function bootId(): Promise<string> {
131
139
  cachedBoot ??= (async () => {
140
+ if (process.platform === "win32") return WINDOWS_BOOT;
132
141
  if (process.platform === "linux") {
133
142
  return (await readFile("/proc/sys/kernel/random/boot_id", "utf8")).trim();
134
143
  }
@@ -140,8 +149,20 @@ export function bootId(): Promise<string> {
140
149
  return cachedBoot;
141
150
  }
142
151
 
152
+ interface WindowsProcess {
153
+ readonly pid: number;
154
+ readonly ppid?: number;
155
+ readonly startTime?: string;
156
+ }
157
+
143
158
  /** Reads one process, or `undefined` when no process has that PID. */
144
159
  export async function readProcess(pid: number): Promise<ProcessInfo | undefined> {
160
+ if (process.platform === "win32") {
161
+ const [entry] = await runHelperAsync<WindowsProcess[]>(["identity", String(pid)]);
162
+ return entry?.startTime === undefined
163
+ ? undefined
164
+ : { pid, pgid: pid, startTime: entry.startTime };
165
+ }
145
166
  const boot = await bootId();
146
167
  if (process.platform === "linux") {
147
168
  try {
@@ -161,8 +182,19 @@ export async function readProcess(pid: number): Promise<ProcessInfo | undefined>
161
182
  return line === undefined ? undefined : parsePsLine(line, boot);
162
183
  }
163
184
 
164
- /** Lists every process the user can see. */
165
- export async function listProcesses(): Promise<ProcessInfo[]> {
185
+ /**
186
+ * Lists every process the user can see. On Windows each carries its parent's PID (`ppid`), which
187
+ * may name a process that has since exited and whose PID was reused.
188
+ */
189
+ export async function listProcesses(): Promise<(ProcessInfo & { readonly ppid?: number })[]> {
190
+ if (process.platform === "win32") {
191
+ const entries = await runHelperAsync<WindowsProcess[]>(["processes"]);
192
+ return entries.flatMap((entry) =>
193
+ entry.startTime === undefined
194
+ ? []
195
+ : [{ pid: entry.pid, pgid: entry.pid, startTime: entry.startTime, ppid: entry.ppid ?? 0 }],
196
+ );
197
+ }
166
198
  const boot = await bootId();
167
199
  if (process.platform === "linux") {
168
200
  const entries = (await readdir("/proc")).filter((name) => /^\d+$/.test(name));
@@ -0,0 +1,46 @@
1
+ /**
2
+ * The platform layer (WP-W1, RT-10): the one module that knows which operating system the runtime
3
+ * runs on. Every difference between POSIX and Windows lives here: where homes live, owner-only
4
+ * directories, the control endpoint, process identity, starting, ending and reaping children,
5
+ * and the file operations whose semantics differ. Other modules ask it; none of them reads
6
+ * `process.platform` (a test keeps it so). Windows work goes through `mostra-win`, the helper in
7
+ * `crates/mostra-win`.
8
+ */
9
+ export {
10
+ ControlConnectError,
11
+ type ControlListener,
12
+ connectControl,
13
+ controlEndpoint,
14
+ type LaunchPipe,
15
+ listenControl,
16
+ } from "./control.ts";
17
+ export {
18
+ defaultHome,
19
+ OS,
20
+ ownedDirectory,
21
+ type PreparedDirectory,
22
+ pathsOf,
23
+ type RuntimeDirChoice,
24
+ runtimeDirFor,
25
+ socketPathLimit,
26
+ WINDOWS,
27
+ } from "./directories.ts";
28
+ export { baseEnvironment, WINDOWS_SYSTEM_VARIABLES } from "./environment.ts";
29
+ export {
30
+ fsyncPath,
31
+ isUnder,
32
+ linkDirectory,
33
+ linkTarget,
34
+ nameKey,
35
+ pathKey,
36
+ removeTree,
37
+ renamePath,
38
+ renamePathSync,
39
+ replaceDirectoryLink,
40
+ samePath,
41
+ sealPlaced,
42
+ sealTree,
43
+ } from "./files.ts";
44
+ export { helperPath, runtimeRoot } from "./helper.ts";
45
+ export { isSameProcess, listProcesses, readProcess } from "./identity.ts";
46
+ export { adoptable, launch, reapRecorded } from "./launch.ts";