@antelopejs/dms 0.18.0 → 0.18.1

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 (60) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/README.md +3 -3
  3. package/bin/control/backend-records.test.mjs +276 -0
  4. package/bin/control/backend.mjs +212 -0
  5. package/bin/control/backend.test.mjs +325 -0
  6. package/bin/control/base.mjs +3 -7
  7. package/bin/control/browser-client.mjs +6 -4
  8. package/bin/control/browser.mjs +173 -36
  9. package/bin/control/build-cache.mjs +394 -0
  10. package/bin/control/build-cache.test.mjs +270 -0
  11. package/bin/control/build-inputs.mjs +172 -0
  12. package/bin/control/build-key-refusals.test.mjs +138 -0
  13. package/bin/control/build-key.mjs +479 -0
  14. package/bin/control/build-key.test.mjs +392 -0
  15. package/bin/control/build-layout.test.mjs +314 -0
  16. package/bin/control/commands-stack.mjs +46 -6
  17. package/bin/control/commands-verify.mjs +9 -2
  18. package/bin/control/doctor.mjs +87 -16
  19. package/bin/control/forwarder.mjs +86 -0
  20. package/bin/control/forwarder.test.mjs +141 -0
  21. package/bin/control/frontend-check.mjs +54 -0
  22. package/bin/control/frontend-workspace.mjs +150 -0
  23. package/bin/control/frontend-workspace.test.mjs +133 -0
  24. package/bin/control/helpers/env.mjs +21 -0
  25. package/bin/control/helpers/evidence.mjs +13 -0
  26. package/bin/control/helpers/fake-run.mjs +290 -0
  27. package/bin/control/helpers/key-fixture.mjs +82 -0
  28. package/bin/control/helpers/pids.mjs +27 -0
  29. package/bin/control/helpers/repo.mjs +13 -0
  30. package/bin/control/helpers/tree.mjs +40 -0
  31. package/bin/control/identity.mjs +238 -0
  32. package/bin/control/identity.test.mjs +166 -0
  33. package/bin/control/journey.mjs +64 -16
  34. package/bin/control/journey.test.mjs +60 -2
  35. package/bin/control/namespaces.test.mjs +211 -0
  36. package/bin/control/options.mjs +2 -0
  37. package/bin/control/pid-guard.test.mjs +202 -0
  38. package/bin/control/prepared-workspace.mjs +20 -0
  39. package/bin/control/processes.mjs +122 -33
  40. package/bin/control/processes.test.mjs +255 -0
  41. package/bin/control/renderer.test.mjs +2 -1
  42. package/bin/control/run-copy.mjs +77 -0
  43. package/bin/control/run-state.mjs +142 -16
  44. package/bin/control/stack.mjs +259 -210
  45. package/bin/control/tab.mjs +13 -6
  46. package/bin/control/tab.test.mjs +444 -0
  47. package/bin/control/timing.mjs +244 -0
  48. package/bin/control/timing.test.mjs +197 -0
  49. package/bin/control/verify/decode.mjs +34 -21
  50. package/bin/control/verify/decode.test.mjs +39 -0
  51. package/bin/control/verify/doors.test.mjs +2 -0
  52. package/bin/control/verify/map.mjs +57 -7
  53. package/bin/control/verify/map.test.mjs +264 -0
  54. package/bin/control/verify/skill.mjs +12 -3
  55. package/bin/control/verify/types.mjs +2 -2
  56. package/bin/control/verify/verdict.mjs +37 -7
  57. package/bin/dms-control.mjs +14 -6
  58. package/frontend-vue/layers/dms-layout/app/components/layout/DashboardSearch.vue +24 -1
  59. package/package.json +1 -1
  60. package/skills/dms-project/SKILL.md +6 -3
@@ -0,0 +1,290 @@
1
+ import assert from "node:assert/strict";
2
+ import { spawn } from "node:child_process";
3
+ import {
4
+ mkdirSync,
5
+ mkdtempSync,
6
+ readdirSync,
7
+ readFileSync,
8
+ rmSync,
9
+ symlinkSync,
10
+ writeFileSync,
11
+ } from "node:fs";
12
+ import { createServer, get } from "node:http";
13
+ import { tmpdir } from "node:os";
14
+ import { dirname, join } from "node:path";
15
+ import { setTimeout as sleep } from "node:timers/promises";
16
+ import { arrayOf, decode, isNumber, isString, objectOf } from "../json.mjs";
17
+ import { isSameProcess, startTimeOf } from "../identity.mjs";
18
+ import { freePort } from "../processes.mjs";
19
+ import { backendsFolder, createRunFolders, saveRun } from "../run-state.mjs";
20
+ import { down } from "../stack.mjs";
21
+
22
+ /** How many runs the tests made, which tells their databases apart */
23
+ let runs = 0;
24
+ const REGISTRY_WAIT_MS = 10_000;
25
+
26
+ /** A backend that answers every request with its pid and the database it was started on, and reports both to the test's registry once it listens. */
27
+ const FAKE_BACKEND = `
28
+ const http = require("node:http");
29
+ const self = JSON.stringify({ pid: process.pid, database: process.env.MONGO_DATABASE });
30
+ const server = http.createServer((request, response) => {
31
+ response.setHeader("content-type", "application/json");
32
+ response.end(self);
33
+ });
34
+ server.listen(Number(process.env.PORT), "127.0.0.1", () => {
35
+ const report = http.request(process.env.FAKE_REGISTRY, { method: "POST" });
36
+ report.on("error", () => undefined);
37
+ report.end(self);
38
+ });
39
+ `;
40
+
41
+ /** A MongoDB driver that records the databases dropped through it. */
42
+ const FAKE_DRIVER = `
43
+ const dropped = [];
44
+ Object.defineProperty(globalThis, "fakeMongoDropped", { value: dropped, configurable: true });
45
+ class MongoClient {
46
+ async connect() {}
47
+ async close() {}
48
+ db(name) {
49
+ return { admin: () => ({}), dropDatabase: async () => { dropped.push(name); } };
50
+ }
51
+ }
52
+ module.exports = { MongoClient };
53
+ `;
54
+
55
+ const PLAYGROUND_FILES = {
56
+ "package.json": "{}",
57
+ "node_modules/@antelopejs/core/package.json": '{"name":"@antelopejs/core"}',
58
+ "node_modules/@antelopejs/core/dist/core/cli/index.js": FAKE_BACKEND,
59
+ "node_modules/@antelopejs/dms-frontend/package.json":
60
+ '{"name":"@antelopejs/dms-frontend"}',
61
+ "node_modules/mongodb-memory-server-core/package.json":
62
+ '{"name":"mongodb-memory-server-core","main":"index.js"}',
63
+ "node_modules/mongodb-memory-server-core/index.js": "",
64
+ "node_modules/mongodb/package.json": '{"name":"mongodb","main":"index.js"}',
65
+ "node_modules/mongodb/index.js": FAKE_DRIVER,
66
+ };
67
+
68
+ const isServed = objectOf({ pid: isNumber, database: isString });
69
+ const isDropped = arrayOf(isString);
70
+
71
+ /** @type {{ pid: number, database: string, startTime: number | null }[]} Every fake backend the tests started, in the order they listened, with the start time that tells it from a later process given its pid */
72
+ const started = [];
73
+
74
+ const registry = createServer((request, response) => {
75
+ let body = "";
76
+ request.on("data", (chunk) => {
77
+ body += String(chunk);
78
+ });
79
+ request.on("end", () => {
80
+ /** @type {unknown} */
81
+ const parsed = JSON.parse(body);
82
+ const backend = decode(isServed, parsed, "a report", "a pid and database");
83
+ started.push({ ...backend, startTime: startTimeOf(backend.pid) });
84
+ response.end();
85
+ });
86
+ });
87
+ const registryPort = await freePort();
88
+ await new Promise((resolve) =>
89
+ registry.listen(registryPort, "127.0.0.1", resolve),
90
+ );
91
+ registry.unref();
92
+
93
+ /**
94
+ * The backend started on `database`, once it listens. Fails the test when
95
+ * none does, so no test signals a pid it made up.
96
+ *
97
+ * @param {string} database The database
98
+ * @returns {Promise<{ pid: number, database: string }>} The backend
99
+ */
100
+ export async function startedOn(database) {
101
+ const deadline = Date.now() + REGISTRY_WAIT_MS;
102
+ for (;;) {
103
+ const backend = started.findLast((entry) => entry.database === database);
104
+ if (backend) {
105
+ assert.ok(backend.pid > 1, "a backend reports a real pid");
106
+ return backend;
107
+ }
108
+ assert.ok(Date.now() < deadline, `a backend starts on ${database}`);
109
+ await sleep(20);
110
+ }
111
+ }
112
+
113
+ /**
114
+ * A process of the test's own that is no backend, stopped after the test.
115
+ *
116
+ * @param {import("node:test").TestContext} t The test
117
+ * @param {NodeJS.ProcessEnv} [env] Its environment, such as the database of a backend, as the dashboard has it
118
+ * @returns {number} Its pid
119
+ */
120
+ export function bystander(t, env = process.env) {
121
+ const child = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], {
122
+ stdio: "ignore",
123
+ env,
124
+ });
125
+ t.after(() => child.kill());
126
+ assert.ok(child.pid !== undefined && child.pid > 1, "the bystander started");
127
+ return child.pid;
128
+ }
129
+
130
+ /** @returns {number[]} The pids of the fake backends that still run, each only while its pid still runs that backend */
131
+ export function running() {
132
+ return started
133
+ .filter((backend) => isSameProcess(backend))
134
+ .map((backend) => backend.pid)
135
+ .toSorted((a, b) => a - b);
136
+ }
137
+
138
+ /**
139
+ * A run whose playground starts the fake backend, with no process yet, and
140
+ * the files a build writes: the module's `dist`, the `dist` of a workspace
141
+ * package the playground links, the playground's `dist` and its project
142
+ * build, which `up` records as the run's build folders. `down` stops what
143
+ * the test started.
144
+ *
145
+ * @param {import("node:test").TestContext} t The test
146
+ * @returns {Promise<import("../run-state.mjs").RunState>} The run
147
+ */
148
+ export async function newRun(t) {
149
+ const parent = mkdtempSync(join(tmpdir(), "dms-control-backend-test-"));
150
+ const playground = join(parent, "playground");
151
+ for (const [path, content] of Object.entries(PLAYGROUND_FILES)) {
152
+ mkdirSync(dirname(join(playground, path)), { recursive: true });
153
+ writeFileSync(join(playground, path), content);
154
+ }
155
+ for (const file of buildFiles(parent)) rebuild(file);
156
+ symlinkSync(
157
+ join(parent, "interface"),
158
+ join(playground, "node_modules/@antelopejs/interface-t"),
159
+ );
160
+ const paths = createRunFolders(join(parent, "run"));
161
+ const apiPort = await freePort();
162
+ runs += 1;
163
+ const prefix = `verify_t${runs}`;
164
+ const state = {
165
+ ...paths,
166
+ id: "t",
167
+ createdAt: new Date().toISOString(),
168
+ environment: "docs",
169
+ playground,
170
+ moduleRoot: parent,
171
+ repo: null,
172
+ headSha: null,
173
+ baseRef: "origin/main",
174
+ skill: null,
175
+ apiPort,
176
+ webPort: 0,
177
+ smtpPort: 0,
178
+ mail: join(paths.evidence, "mail"),
179
+ apiUrl: `http://127.0.0.1:${apiPort}`,
180
+ webUrl: "http://127.0.0.1:0",
181
+ databasePrefix: prefix,
182
+ database: prefix,
183
+ mongoUrl: "",
184
+ ownsMongo: false,
185
+ secrets: {},
186
+ adminPassword: "",
187
+ extraEnv: { FAKE_REGISTRY: `http://127.0.0.1:${registryPort}` },
188
+ processes: [],
189
+ accounts: {},
190
+ tokens: {},
191
+ ready: true,
192
+ runPlayground: playground,
193
+ buildRoots: buildFiles(parent).map((file) => dirname(file)),
194
+ };
195
+ saveRun(state);
196
+ t.after(async () => {
197
+ await down(state);
198
+ rmSync(parent, { recursive: true, force: true });
199
+ });
200
+ return state;
201
+ }
202
+
203
+ /**
204
+ * Who answers through the run's API port, on a connection of its own.
205
+ *
206
+ * @param {import("../run-state.mjs").RunState} state The run
207
+ * @returns {Promise<{ pid: number, database: string }>} The backend's pid and database
208
+ */
209
+ export function served(state) {
210
+ return new Promise((resolve, reject) => {
211
+ const request = get(
212
+ `${state.apiUrl}/api/onboarding/informations`,
213
+ { agent: false },
214
+ (response) => {
215
+ let body = "";
216
+ response.on("data", (chunk) => {
217
+ body += String(chunk);
218
+ });
219
+ response.on("end", () => {
220
+ /** @type {unknown} */
221
+ const parsed = JSON.parse(body);
222
+ resolve(decode(isServed, parsed, "the answer", "a pid and database"));
223
+ });
224
+ },
225
+ );
226
+ request.on("error", reject);
227
+ });
228
+ }
229
+
230
+ /** @returns {string[]} The databases dropped so far */
231
+ export function dropped() {
232
+ /** @type {unknown} */
233
+ const recorded = Object.getOwnPropertyDescriptor(
234
+ globalThis,
235
+ "fakeMongoDropped",
236
+ )?.value;
237
+ return decode(isDropped, recorded ?? [], "fakeMongoDropped", "names");
238
+ }
239
+
240
+ /**
241
+ * The files a build of the run writes, one per build input.
242
+ *
243
+ * @param {string} parent The folder of the module, which holds the playground
244
+ * @returns {string[]} The files
245
+ */
246
+ export function buildFiles(parent) {
247
+ return [
248
+ join(parent, "dist/index.js"),
249
+ join(parent, "interface/dist/index.js"),
250
+ join(parent, "playground/dist/index.js"),
251
+ join(parent, "playground/.antelope/build/build.json"),
252
+ ];
253
+ }
254
+
255
+ /** @param {string} file A file a build writes */
256
+ export function rebuild(file) {
257
+ mkdirSync(dirname(file), { recursive: true });
258
+ writeFileSync(file, `built at ${new Date().toISOString()}\n`);
259
+ }
260
+
261
+ /**
262
+ * Rewrites every backend record of the run without its start time, as this
263
+ * branch wrote them before it recorded one.
264
+ *
265
+ * @param {import("../run-state.mjs").RunState} state The run
266
+ * @returns {number} How many records held a start time
267
+ */
268
+ export function withoutStartTimes(state) {
269
+ const folder = backendsFolder(state.dir);
270
+ let rewritten = 0;
271
+ for (const name of readdirSync(folder)) {
272
+ const file = join(folder, name);
273
+ const record = readFileSync(file, "utf8");
274
+ const without = record.replace(/,"startTime":\d+/, "");
275
+ if (without !== record) rewritten += 1;
276
+ writeFileSync(file, without);
277
+ }
278
+ return rewritten;
279
+ }
280
+
281
+ /**
282
+ * The run's `run.json` as the file holds it, so a test can tell whether a
283
+ * command changed it.
284
+ *
285
+ * @param {string} dir The run root
286
+ * @returns {string} The file's text
287
+ */
288
+ export function storedRun(dir) {
289
+ return readFileSync(join(dir, "run.json"), "utf8");
290
+ }
@@ -0,0 +1,82 @@
1
+ import { mkdtempSync, rmSync, symlinkSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { buildInputs, buildKey, sourceNames } from "../build-key.mjs";
5
+ import { write } from "./repo.mjs";
6
+
7
+ /**
8
+ * An installed dms-frontend, a checkout whose playground pnpm installed
9
+ * (its `node_modules` links into the checkout root's store, whose lockfile
10
+ * and install records sit beside it), and a project whose workspace a run
11
+ * set up at `<run>/.dms-frontend` with its own web URL: a template, a
12
+ * module's copied page, the registry the setup generated (which names the
13
+ * workspace's folder and the run's URL), the install record, the lockfile
14
+ * and the installed modules. The project's `node_modules` links to the
15
+ * playground's, as the run's copy does.
16
+ *
17
+ * @param {import("node:test").TestContext} t The test
18
+ */
19
+ export function fixture(t) {
20
+ const dir = mkdtempSync(join(tmpdir(), "dms-control-build-key-test-"));
21
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
22
+ const frontend = join(dir, "dms-frontend");
23
+ write(join(frontend, "package.json"), '{"version":"0.10.0"}');
24
+ write(join(frontend, "dist", "index.js"), "build();\n");
25
+ write(join(frontend, "templates", "vue", "main.ts"), "mount();\n");
26
+ const checkout = join(dir, "checkout");
27
+ write(join(checkout, "pnpm-lock.yaml"), "zod: 3.24.4\n");
28
+ write(join(checkout, "node_modules", ".pnpm", "lock.yaml"), "zod: 3.24.4\n");
29
+ write(
30
+ join(checkout, "node_modules", ".modules.yaml"),
31
+ "hoistedDependencies: {}\npendingBuilds:\n - .\nprunedAt: Sat, 07 Nov 2026 01:24:21 GMT\nlayoutVersion: 5\n",
32
+ );
33
+ const modules = join(checkout, "playground", "node_modules");
34
+ write(join(modules, ".bin", "tsc"), "tsc\n");
35
+ write(join(modules, "@types", ".keep"), "");
36
+ symlinkSync(
37
+ "../../node_modules/.pnpm/zod@3.24.4/node_modules/zod",
38
+ join(modules, "zod"),
39
+ );
40
+ /**
41
+ * @param {string} name
42
+ * @param {number} port
43
+ */
44
+ const prepare = (name, port) => {
45
+ const project = join(dir, name);
46
+ const workspace = join(project, ".dms-frontend");
47
+ const webUrl = `http://127.0.0.1:${port}`;
48
+ write(join(project, "package.json"), "{}");
49
+ symlinkSync(modules, join(project, "node_modules"));
50
+ write(join(workspace, "main.ts"), "mount();\n");
51
+ write(
52
+ join(workspace, "frontend-modules", "layer", "page.vue"),
53
+ "<template>one</template>\n",
54
+ );
55
+ write(
56
+ join(workspace, "generated-frontend-modules.json"),
57
+ JSON.stringify({ root: join(workspace, "frontend-modules"), webUrl }),
58
+ );
59
+ write(join(workspace, ".deps-hash"), "a\n");
60
+ write(join(workspace, "pnpm-lock.yaml"), "vue: 3.5.0\n");
61
+ write(join(workspace, "node_modules", "vue", "index.js"), "vue();\n");
62
+ const run = { environment: "docs", extraEnv: {}, webUrl };
63
+ /** @type {import("../build-key.mjs").PreparedWorkspace} */
64
+ const prepared = {
65
+ project,
66
+ workspace,
67
+ names: sourceNames(workspace),
68
+ installed: workspace,
69
+ };
70
+ return { project, workspace, run, prepared };
71
+ };
72
+ return { dir, frontend, checkout, modules, prepare };
73
+ }
74
+
75
+ /**
76
+ * @param {string} frontend
77
+ * @param {{ run: import("../build-key.mjs").KeyedRun, prepared: import("../build-key.mjs").PreparedWorkspace }} side
78
+ * @returns {string}
79
+ */
80
+ export function keyOf(frontend, side) {
81
+ return buildKey(buildInputs(side.run, frontend, side.prepared));
82
+ }
@@ -0,0 +1,27 @@
1
+ import { readFileSync, writeFileSync } from "node:fs";
2
+
3
+ const NS_LAST_PID = "/proc/sys/kernel/ns_last_pid";
4
+
5
+ /**
6
+ * Whether the test may choose the next pid, which only a process that owns
7
+ * its PID namespace can, as under `unshare -Ur --pid`.
8
+ *
9
+ * @returns {boolean} True when `ns_last_pid` takes a write
10
+ */
11
+ export function canChoosePid() {
12
+ try {
13
+ writeFileSync(NS_LAST_PID, readFileSync(NS_LAST_PID, "utf8"));
14
+ return true;
15
+ } catch {
16
+ return false;
17
+ }
18
+ }
19
+
20
+ /**
21
+ * Makes `pid` the next one the kernel gives a new process, once it is free.
22
+ *
23
+ * @param {number} pid The pid
24
+ */
25
+ export function chooseNextPid(pid) {
26
+ writeFileSync(NS_LAST_PID, String(pid - 1));
27
+ }
@@ -0,0 +1,13 @@
1
+ import { mkdirSync, writeFileSync } from "node:fs";
2
+ import { dirname } from "node:path";
3
+
4
+ /**
5
+ * Writes `text` to `file`, creating its folder.
6
+ *
7
+ * @param {string} file The file
8
+ * @param {string} text Its content
9
+ */
10
+ export function write(file, text) {
11
+ mkdirSync(dirname(file), { recursive: true });
12
+ writeFileSync(file, text);
13
+ }
@@ -0,0 +1,40 @@
1
+ import { existsSync, readdirSync, readFileSync, readlinkSync } from "node:fs";
2
+ import { join } from "node:path";
3
+
4
+ /**
5
+ * What a folder holds, for a test to compare: each file's text and each
6
+ * symbolic link's target (as `-> target`), by path, or null when the folder
7
+ * does not exist.
8
+ *
9
+ * @param {string} folder The folder
10
+ * @returns {Record<string, string> | null} Its content
11
+ */
12
+ export function treeOf(folder) {
13
+ if (!existsSync(folder)) return null;
14
+ /** @type {Record<string, string>} */
15
+ const content = {};
16
+ /** @param {string} prefix */
17
+ const walk = (prefix) => {
18
+ for (const entry of readdirSync(join(folder, prefix), {
19
+ withFileTypes: true,
20
+ })) {
21
+ const name = join(prefix, entry.name);
22
+ const path = join(folder, name);
23
+ if (entry.isSymbolicLink()) content[name] = `-> ${readlinkSync(path)}`;
24
+ else if (entry.isDirectory()) walk(name);
25
+ else content[name] = readFileSync(path, "utf8");
26
+ }
27
+ };
28
+ walk("");
29
+ return content;
30
+ }
31
+
32
+ /**
33
+ * The names a folder holds.
34
+ *
35
+ * @param {string} folder The folder
36
+ * @returns {string[]} Its entries, sorted
37
+ */
38
+ export function namesIn(folder) {
39
+ return readdirSync(folder).sort();
40
+ }
@@ -0,0 +1,238 @@
1
+ import { existsSync, readdirSync, readFileSync, readlinkSync } from "node:fs";
2
+
3
+ const MAX_PID = 2 ** 31 - 1;
4
+
5
+ /** @type {("pid" | "time")[]} The namespaces a recorded pid and start time hold in: the PID namespace numbers a process, and the time namespace offsets its start time. */
6
+ const NAMESPACE_KINDS = ["pid", "time"];
7
+
8
+ /** @typedef {{ pid?: string, time?: string }} Namespaces The namespaces a process runs in, as `/proc/self/ns` names them, such as `pid:[4026531836]` */
9
+
10
+ /** The index of the start time, field 22 of `/proc/<pid>/stat`, among the fields after the command name, which start at field 3. */
11
+ const START_TIME_FIELD = 19;
12
+
13
+ /** The length of a clock tick in /proc: USER_HZ is 100 on every architecture Node runs on. */
14
+ const MS_PER_TICK = 10;
15
+
16
+ const MS_PER_SECOND = 1000;
17
+
18
+ /** How far the kernel start of a process may sit from the time a record without a start time says the run started it: `/proc/stat` gives the boot time to the second, and a loaded host can take a moment between the start and the record. */
19
+ const START_TOLERANCE_MS = 5_000;
20
+
21
+ /**
22
+ * Whether `pid` names one process a signal may target: a whole number above
23
+ * 1 that fits a signed 32-bit process id. `kill(-1)` reaches every process
24
+ * of the user, `kill(0)` the caller's own process group, and `kill(-pid)` on
25
+ * 1 is `kill(-1)`.
26
+ *
27
+ * @param {unknown} pid The value to check
28
+ * @returns {pid is number} True for a whole number above 1
29
+ */
30
+ export function isSignalable(pid) {
31
+ return Number.isInteger(pid) && Number(pid) > 1 && Number(pid) <= MAX_PID;
32
+ }
33
+
34
+ /**
35
+ * Throws unless `pid` names one process a signal may target, so no caller
36
+ * can turn a missing or corrupt PID into a signal to every process.
37
+ *
38
+ * @param {unknown} pid The value to check
39
+ * @throws {TypeError} When it is not a whole number above 1
40
+ */
41
+ export function assertSignalable(pid) {
42
+ if (!isSignalable(pid)) {
43
+ throw new TypeError(
44
+ `refusing to signal pid ${String(pid)}: not a process id above 1`,
45
+ );
46
+ }
47
+ }
48
+
49
+ /**
50
+ * Whether a process with this PID exists.
51
+ *
52
+ * @param {number} pid The process id
53
+ * @returns {boolean} True while it runs
54
+ */
55
+ export function isAlive(pid) {
56
+ if (!isSignalable(pid)) return false;
57
+ try {
58
+ process.kill(pid, 0);
59
+ return true;
60
+ } catch {
61
+ return false;
62
+ }
63
+ }
64
+
65
+ /**
66
+ * Whether a process with this PID runs: it exists and is not a finished
67
+ * zombie. A killed process that nothing reaps stays a zombie; once its last
68
+ * thread has exited it holds no socket and runs no code. Its main thread
69
+ * shows as a zombie while other threads still exit and still hold its
70
+ * sockets, so that one still runs. Without `/proc`, existing is running.
71
+ *
72
+ * @param {number} pid The process id
73
+ * @returns {boolean} True while it runs
74
+ */
75
+ export function isRunning(pid) {
76
+ if (!isAlive(pid)) return false;
77
+ try {
78
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
79
+ const zombie = stat.slice(stat.lastIndexOf(")") + 2).split(" ")[0] === "Z";
80
+ return !zombie || readdirSync(`/proc/${pid}/task`).length > 1;
81
+ } catch {
82
+ return isAlive(pid);
83
+ }
84
+ }
85
+
86
+ /**
87
+ * When the kernel started `pid`, in clock ticks since boot (field 22 of
88
+ * `/proc/<pid>/stat`), or `null` when no such process exists.
89
+ *
90
+ * @param {number} pid The process id
91
+ * @returns {number | null} Its start time
92
+ */
93
+ export function startTimeOf(pid) {
94
+ try {
95
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
96
+ const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
97
+ const ticks = Number(fields[START_TIME_FIELD]);
98
+ return Number.isSafeInteger(ticks) ? ticks : null;
99
+ } catch {
100
+ return null;
101
+ }
102
+ }
103
+
104
+ /** @returns {number | null} The pid `/proc/self/stat` gives this process, or `null` without one */
105
+ function pidInProc() {
106
+ try {
107
+ const stat = readFileSync("/proc/self/stat", "utf8");
108
+ return Number(stat.slice(0, stat.indexOf(" ")));
109
+ } catch {
110
+ return null;
111
+ }
112
+ }
113
+
114
+ /**
115
+ * Whether this system has a /proc at all. Without one, as on macOS, nothing
116
+ * records start times and a process is told apart by its pid alone, as
117
+ * dms-control always did there.
118
+ *
119
+ * @returns {boolean} True when `/proc/self` exists
120
+ */
121
+ function hasProc() {
122
+ return existsSync("/proc/self");
123
+ }
124
+
125
+ /**
126
+ * Throws unless /proc belongs to this process's PID namespace, the only
127
+ * place a start time tells a recorded process from another that holds its
128
+ * pid now. A system with no /proc at all passes: there the pid alone names
129
+ * a process. In a PID namespace that mounted no /proc of its own, as under
130
+ * `unshare --pid` without `--mount-proc`, `/proc/<pid>` is whichever process
131
+ * of another namespace has that number.
132
+ *
133
+ * @throws When `/proc/self` exists but `/proc/self/stat` names another pid or cannot be read
134
+ */
135
+ export function assertOwnProc() {
136
+ if (!hasProc()) return;
137
+ const shown = pidInProc();
138
+ if (shown === process.pid) return;
139
+ const seen =
140
+ shown === null
141
+ ? "/proc/self/stat cannot be read"
142
+ : `/proc shows this process as pid ${shown}, not ${process.pid}`;
143
+ throw new Error(
144
+ `${seen}: /proc is not this PID namespace's, so no process the run recorded can be told from another that holds its pid now; nothing was started or signalled. Run dms-control where /proc belongs to its PID namespace, such as under unshare --mount-proc`,
145
+ );
146
+ }
147
+
148
+ /**
149
+ * @param {"pid" | "time"} kind
150
+ * @returns {string | undefined}
151
+ */
152
+ function namespaceOf(kind) {
153
+ try {
154
+ return readlinkSync(`/proc/self/ns/${kind}`);
155
+ } catch {
156
+ return undefined;
157
+ }
158
+ }
159
+
160
+ /**
161
+ * The PID and time namespaces this process runs in. A kind the kernel does
162
+ * not have, or a system with no /proc, leaves its field out.
163
+ *
164
+ * @returns {Namespaces} The namespaces
165
+ */
166
+ export function currentNamespaces() {
167
+ return { pid: namespaceOf("pid"), time: namespaceOf("time") };
168
+ }
169
+
170
+ /**
171
+ * Throws unless this process runs in every namespace a run recorded when it
172
+ * started. Each pid and start time the run recorded names a process only in
173
+ * those namespaces: elsewhere every record would look gone, and a command
174
+ * would forget processes that still run. A run that recorded none, as an
175
+ * earlier dms-control or a system with no /proc wrote it, passes.
176
+ *
177
+ * @param {Namespaces | undefined} recorded The namespaces the run was started in
178
+ * @throws When one of them is not this process's
179
+ */
180
+ export function assertSameNamespaces(recorded) {
181
+ const current = currentNamespaces();
182
+ const differ = NAMESPACE_KINDS.filter(
183
+ (kind) =>
184
+ recorded?.[kind] !== undefined && recorded[kind] !== current[kind],
185
+ );
186
+ if (recorded === undefined || differ.length === 0) return;
187
+ const kinds = differ.map((kind) => (kind === "pid" ? "PID" : kind));
188
+ const run = differ.map((kind) => recorded[kind]).join(", ");
189
+ const here = differ.map((kind) => current[kind] ?? "unknown").join(", ");
190
+ throw new Error(
191
+ `this run was started in another ${kinds.join(" and ")} namespace (run: ${run}; here: ${here}); run this command there`,
192
+ );
193
+ }
194
+
195
+ /**
196
+ * Whether the kernel started a process `ticks` after boot within a few
197
+ * seconds of `startedAt`.
198
+ *
199
+ * @param {number} ticks The kernel start time, in clock ticks since boot
200
+ * @param {string | undefined} startedAt When the run says it started the process, as an ISO time
201
+ * @returns {boolean} True when both name the same moment
202
+ */
203
+ function startedAround(ticks, startedAt) {
204
+ try {
205
+ const btime = /^btime (\d+)$/m.exec(readFileSync("/proc/stat", "utf8"));
206
+ const started = Number(btime?.[1]) * MS_PER_SECOND + ticks * MS_PER_TICK;
207
+ return (
208
+ Math.abs(started - Date.parse(startedAt ?? "")) <= START_TOLERANCE_MS
209
+ );
210
+ } catch {
211
+ return false;
212
+ }
213
+ }
214
+
215
+ /**
216
+ * Whether `record` still names the process the run started: its pid runs,
217
+ * and the kernel started that process at the time recorded with it, so a
218
+ * pid the system has since given to another process is not taken for it. A
219
+ * record with no start time, as an earlier dms-control wrote, names the
220
+ * process only while the kernel started it within a few seconds of the
221
+ * record's `startedAt`. On a system with no /proc, a running pid names it.
222
+ *
223
+ * @param {{ pid: number, startTime?: number | null, startedAt?: string }} record A process the run recorded
224
+ * @returns {boolean} True while that process runs
225
+ * @throws When /proc is not this PID namespace's, before it reads any record
226
+ */
227
+ export function isSameProcess(record) {
228
+ assertOwnProc();
229
+ if (!isSignalable(record.pid)) return false;
230
+ if (!hasProc()) return isAlive(record.pid);
231
+ if (!isRunning(record.pid)) return false;
232
+ const ticks = startTimeOf(record.pid);
233
+ const recorded = record.startTime ?? null;
234
+ if (ticks === null) return false;
235
+ return recorded === null
236
+ ? startedAround(ticks, record.startedAt)
237
+ : ticks === recorded;
238
+ }