@antelopejs/tooling-configs 0.3.3 → 0.3.5

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.
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
- import { i as parseManifest, r as packageManager } from "../package-BRTjkzt5.mjs";
2
+ import { i as parseManifest, r as packageManager } from "../package-CqqBgE8Y.mjs";
3
3
  import { t as runCli } from "../cli-4Tv71vYk.mjs";
4
4
  import { c as repositoryRoot, l as resolveRevision } from "../files-DJ0TeaTU.mjs";
5
5
  import { a as DIRECTORY_LINK, c as revisionCounts, d as describeAllowance, f as fillStars, i as stampProof, l as allowedByGlob, o as compareRevisions, p as recordVerdict, u as createAddedPolicy } from "../proof-stamp-DDDC0J6l.mjs";
6
- import { a as outputRoot, i as loadTypeScript, n as isExportPath, o as packagesAt, r as isTestSource, s as unpublishedAt, t as emitPackage } from "../typescript-CM0LrVP7.mjs";
6
+ import { a as outputRoot, i as loadTypeScript, n as isExportPath, o as packagesAt, r as isTestSource, s as unpublishedAt, t as emitPackage } from "../typescript-DAgQIAAR.mjs";
7
7
  import { createRequire } from "node:module";
8
8
  import { copyFileSync, cpSync, existsSync, globSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
9
9
  import { basename, dirname, isAbsolute, join, parse, posix, relative, resolve } from "node:path";
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import "../ceilings-B7KayYIG.mjs";
3
- import { i as parseManifest, r as packageManager } from "../package-BRTjkzt5.mjs";
3
+ import { i as parseManifest, r as packageManager } from "../package-CqqBgE8Y.mjs";
4
4
  import { n as runCliAsync } from "../cli-4Tv71vYk.mjs";
5
5
  import { c as repositoryRoot } from "../files-DJ0TeaTU.mjs";
6
6
  import { t as accepting } from "../ports-DGP6bPJy.mjs";
@@ -196,6 +196,8 @@ const CHECK_STEPS = [
196
196
  "suppressions",
197
197
  "sync:check"
198
198
  ];
199
+ /** The step that runs after the others, never beside them: tests often hold time limits that CPU contention would break. */
200
+ const RUNS_ALONE = "test";
199
201
  /** The environment variable naming, comma-separated, the steps `runChecks` leaves to another CI job. */
200
202
  const CHECKS_SKIP_ENV = "ANTELOPEJS_CHECKS_SKIP";
201
203
  function skippedNames(setting) {
@@ -203,13 +205,9 @@ function skippedNames(setting) {
203
205
  }
204
206
  async function runSteps(root, manifest, steps, signal) {
205
207
  const manager = packageManager(manifest);
206
- const failures = [];
207
- for (const step of steps) {
208
- if (signal?.aborted) break;
209
- if (!manifest.scripts?.[step]) {
210
- failures.push(`[${step}] Missing package.json script "${step}". Run antelopejs-sync.\n`);
211
- continue;
212
- }
208
+ const runStep = async (step) => {
209
+ if (signal?.aborted) return [];
210
+ if (!manifest.scripts?.[step]) return [`[${step}] Missing package.json script "${step}". Run antelopejs-sync.\n`];
213
211
  const result = await runCommand(manager, ["run", step], {
214
212
  cwd: root,
215
213
  env: {
@@ -218,19 +216,23 @@ async function runSteps(root, manifest, steps, signal) {
218
216
  },
219
217
  signal
220
218
  });
221
- if (result.status !== 0) failures.push(`[${step}]\n${result.output}`);
222
- }
223
- return failures;
219
+ return result.status === 0 ? [] : [`[${step}]\n${result.output}`];
220
+ };
221
+ const failures = /* @__PURE__ */ new Map();
222
+ await Promise.all(steps.filter((step) => step !== RUNS_ALONE).map(async (step) => failures.set(step, await runStep(step))));
223
+ if (steps.includes(RUNS_ALONE)) failures.set(RUNS_ALONE, await runStep(RUNS_ALONE));
224
+ return steps.flatMap((step) => failures.get(step) ?? []);
224
225
  }
225
226
  function summary(failures, passed, skipped) {
226
227
  return `${failures.join("\n")}Checks: ${passed} passed, ${failures.length} failed${skipped ? `, ${skipped} skipped` : ""}.\n`;
227
228
  }
228
229
  /**
229
- * Runs every check step and reports only what failed. `skipSetting` is the comma-separated value of
230
+ * Runs every check step except `test` at the same time, then `test` alone, and reports only what failed, each step's
231
+ * output buffered and listed in step order whichever step finishes first. `skipSetting` is the comma-separated value of
230
232
  * `ANTELOPEJS_CHECKS_SKIP`: the steps it names are not run and are counted as skipped, never as passed, and a name that
231
233
  * is not a step fails the run before any step starts so a typo cannot skip nothing. Unless `services` is false, the
232
234
  * services of `.github/compose.yml` are started before the steps when `test` runs, and removed after them if the run created them, also when a step fails or
233
- * `signal` aborts the run; an aborted run stops the running step and reports `interrupted`.
235
+ * `signal` aborts the run; an aborted run stops every running step and reports `interrupted`.
234
236
  */
235
237
  async function runChecks(root, options = {}) {
236
238
  const { skipSetting = "", services = true, signal } = options;
@@ -2,7 +2,7 @@
2
2
  import { t as runCli } from "../cli-4Tv71vYk.mjs";
3
3
  import { c as repositoryRoot } from "../files-DJ0TeaTU.mjs";
4
4
  import { c as revisionCounts, i as stampProof, o as compareRevisions } from "../proof-stamp-DDDC0J6l.mjs";
5
- import { o as packagesAt, t as emitPackage } from "../typescript-CM0LrVP7.mjs";
5
+ import { o as packagesAt, t as emitPackage } from "../typescript-DAgQIAAR.mjs";
6
6
  import { copyFileSync, mkdirSync } from "node:fs";
7
7
  import { dirname, join, relative } from "node:path";
8
8
  //#region src/guardrails/comment-proof.ts
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { c as object, d as optTime, f as parseJson, h as time, i as isObject, l as optNum, m as strings, n as children, o as list, p as str, r as flag, s as num, t as child, u as optStr } from "../json-CG2L7YFl.mjs";
3
3
  import { n as runCliAsync } from "../cli-4Tv71vYk.mjs";
4
- import { c as ciRenovateSyncCallers, d as RENOVATE_PRESET, i as CI_RENOVATE_SYNC_REF, n as CI_NODE_REF, r as CI_PATH, s as ciNodeCallers, t as CI_CONTEXT, u as RENOVATE_CONFIGS } from "../ci-workflow-CXcAZj6g.mjs";
4
+ import { c as ciRenovateSyncCallers, d as RENOVATE_PRESET, i as CI_RENOVATE_SYNC_REF, n as CI_NODE_REF, r as CI_PATH, s as ciNodeCallers, t as CI_CONTEXT, u as RENOVATE_CONFIGS } from "../ci-workflow-C4mQ8QSp.mjs";
5
5
  import { i as ghToken, n as createApi, t as ApiError } from "../api-CCOiLN3w.mjs";
6
6
  import { parseArgs } from "node:util";
7
7
  import { inflateRawSync } from "node:zlib";
@@ -26,7 +26,11 @@ function workflowRun(value) {
26
26
  startedAt: optTime(source, "run_started_at") ?? created,
27
27
  updatedAt: time(source, "updated_at"),
28
28
  url: str(source, "html_url"),
29
- headSha: optStr(source, "head_sha") ?? ""
29
+ headSha: optStr(source, "head_sha") ?? "",
30
+ referencedWorkflows: (source.referenced_workflows === null ? [] : children(source, "referenced_workflows")).map((workflow) => ({
31
+ path: str(workflow, "path"),
32
+ sha: optStr(workflow, "sha") ?? ""
33
+ }))
30
34
  };
31
35
  }
32
36
  function checkRuns(value) {
@@ -183,6 +187,7 @@ var GardenContext = class {
183
187
  closed = new Memo();
184
188
  commitTimes = new Memo();
185
189
  cleanups = new Memo();
190
+ pathChanges = new Memo();
186
191
  constructor(api) {
187
192
  this.api = api;
188
193
  }
@@ -284,6 +289,13 @@ var GardenContext = class {
284
289
  return time(child(child(body, "commit"), "committer"), "date");
285
290
  });
286
291
  }
292
+ /** When the newest commit of the branch that touched the path was committed, in milliseconds; undefined when none did. */
293
+ lastChange(repo, path, branch) {
294
+ return this.pathChanges.get(`${repo.name}:${branch}:${path}`, async () => {
295
+ const [newest] = list(await this.api.json(`/repos/${ORG}/${repo.name}/commits?path=${path}&sha=${encodeURIComponent(branch)}&per_page=1`), "commits");
296
+ return newest === void 0 ? void 0 : time(child(child(object(newest, "commit"), "commit"), "committer"), "date");
297
+ });
298
+ }
287
299
  /** Whether GitHub deletes a pull request's head branch once it merges. */
288
300
  deletesBranchOnMerge(repo) {
289
301
  return this.cleanups.get(repo.name, async () => {
@@ -530,6 +542,7 @@ async function perRepo(repos, scan) {
530
542
  //#region src/garden/checks/ci-health.ts
531
543
  const DAY$4 = 864e5;
532
544
  const WORKFLOW = "ci.yml";
545
+ const CALLER = `.github/workflows/${WORKFLOW}`;
533
546
  const RECENT_RUNS = 10;
534
547
  const MIN_BASELINE = 5;
535
548
  const RELATIVE_LIMIT = 1.2;
@@ -568,21 +581,61 @@ async function red(context, repo) {
568
581
  subject: branch
569
582
  }, `${WORKFLOW} has been red on ${branch} since ${new Date(since.createdAt).toISOString()}: ${since.url}`, `${WORKFLOW} is green on ${branch}.`)];
570
583
  }
584
+ /** A reusable workflow path without its `@ref`, e.g. `AntelopeJS/.github/.github/workflows/ci-node.yml`. */
585
+ function workflowPath(path) {
586
+ return path.split("@")[0];
587
+ }
588
+ /** The repository's own file for a workflow it calls from itself; GitHub pins such a call to the run's head commit, so its sha changes on every push. */
589
+ function ownFile(repo, path) {
590
+ const prefix = `${ORG}/${repo.name}/`;
591
+ const bare = workflowPath(path);
592
+ return bare.startsWith(prefix) ? bare.slice(prefix.length) : void 0;
593
+ }
594
+ function signature(repo, run) {
595
+ return [...new Set(run.referencedWorkflows.filter(({ path }) => ownFile(repo, path) === void 0).map(({ path, sha }) => `${workflowPath(path)} ${sha}`))].sort().join("\n");
596
+ }
597
+ function sameWorkflows(repo, runs) {
598
+ if (runs.length === 0) return {
599
+ runs: [],
600
+ since: void 0
601
+ };
602
+ const current = signature(repo, runs[0]);
603
+ const end = runs.findIndex((run) => signature(repo, run) !== current);
604
+ if (end === -1) return {
605
+ runs: [...runs],
606
+ since: void 0
607
+ };
608
+ return {
609
+ runs: runs.slice(0, end),
610
+ since: runs[end - 1].createdAt
611
+ };
612
+ }
613
+ /** The newest commit time of the caller and of every workflow file of its own that the newest run called. */
614
+ async function callerChange(context, repo, branch, newest) {
615
+ const files = /* @__PURE__ */ new Set([CALLER, ...(newest?.referencedWorkflows ?? []).map(({ path }) => ownFile(repo, path)).filter((file) => file !== void 0)]);
616
+ let latest = 0;
617
+ for (const file of files) latest = Math.max(latest, await context.lastChange(repo, file, branch) ?? 0);
618
+ return latest;
619
+ }
571
620
  async function slow(context, repo) {
572
621
  const branch = await context.targetBranch(repo);
573
622
  const runs = await context.workflowRuns(repo, WORKFLOW, branch);
574
- const horizon = context.api.now().getTime() - 30 * DAY$4;
575
- const passed = (runs ?? []).filter((run) => run.conclusion === "success" && run.createdAt >= horizon);
576
- const baseline = passed.slice(RECENT_RUNS).map(duration);
577
- if (passed.length <= RECENT_RUNS || baseline.length < MIN_BASELINE) return [];
578
- const recent = median(passed.slice(0, RECENT_RUNS).map(duration));
623
+ if (runs === void 0) return [];
624
+ const passed = runs.filter((run) => run.conclusion === "success");
625
+ const cutoff = Math.max(context.api.now().getTime() - 30 * DAY$4, await callerChange(context, repo, branch, passed[0]));
626
+ const streak = sameWorkflows(repo, passed.filter((run) => run.createdAt >= cutoff));
627
+ const window = streak.runs;
628
+ const baseline = window.slice(RECENT_RUNS).map(duration);
629
+ if (window.length <= RECENT_RUNS || baseline.length < MIN_BASELINE) return [];
630
+ const recent = median(window.slice(0, RECENT_RUNS).map(duration));
579
631
  const usual = median(baseline);
580
632
  if (recent <= usual * RELATIVE_LIMIT && recent <= usual + ABSOLUTE_LIMIT_SECONDS) return [];
633
+ const since = new Date(Math.max(cutoff, streak.since ?? 0)).toISOString();
581
634
  return [finding({
582
635
  repo: repo.name,
583
636
  check: "ci-duration",
584
637
  subject: branch
585
- }, `The median of the last ${RECENT_RUNS} ${WORKFLOW} runs on ${branch} is ${Math.round(recent)} s against ${Math.round(usual)} s over the previous 30 days.`, `The median is within 20% and 60 s of the 30-day baseline.`)];
638
+ }, `The median of the last ${RECENT_RUNS} ${WORKFLOW} runs on ${branch} is ${Math.round(recent)} s against ${Math.round(usual)} s over the earlier runs since ${since}, the latest of 30 days ago, the last change to ${CALLER} or a workflow file of this repository it calls, and the last change to the shared workflows it calls.`, `The median is within 20% and 60 s of the baseline since the last change to what ${WORKFLOW} runs.`)];
586
639
  }
587
640
  const redBranch = {
588
641
  id: "red-branch",
@@ -590,6 +643,12 @@ const redBranch = {
590
643
  return perRepo(await context.scope(), (repo) => red(context, repo));
591
644
  }
592
645
  };
646
+ /**
647
+ * Flags a repository whose last 10 successful `ci.yml` runs on the target branch take longer than the runs before them.
648
+ * The baseline starts after the last change to what CI runs, so a check added on purpose is accepted: it begins at the
649
+ * newest commit touching `.github/workflows/ci.yml` and at the newest unbroken streak of runs that called the same
650
+ * reusable workflow commits. Too few runs since then is no finding while the baseline refills.
651
+ */
593
652
  const ciDuration = {
594
653
  id: "ci-duration",
595
654
  async run(context) {
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { n as runCliAsync } from "../cli-4Tv71vYk.mjs";
3
+ import { a as isServerRole, l as unmarked, o as leaseEnv, s as leaseMarker } from "../env-DT0UJNeL.mjs";
3
4
  import { a as closeServer, c as LOCK_PORT, d as isRole, f as leaseHome, i as claimPort, l as PORT_ROLES, m as parseRecord, n as bindable, o as listenerPids, p as leaseId, r as chooseBlock, s as listensOn, t as accepting, u as isLeaseId } from "../ports-DGP6bPJy.mjs";
4
5
  import { accessSync, closeSync, constants, mkdirSync, openSync, readFileSync, readSync, readdirSync, realpathSync, renameSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";
5
6
  import { delimiter, join } from "node:path";
@@ -7,39 +8,6 @@ import { execFileSync, spawn } from "node:child_process";
7
8
  import { homedir } from "node:os";
8
9
  import { parseArgs } from "node:util";
9
10
  import { setTimeout } from "node:timers/promises";
10
- //#region src/lease/env.ts
11
- function isServerRole(value) {
12
- return value === "api" || value === "web";
13
- }
14
- /**
15
- * The environment `run` hands its command: `parent` without `PORT`, plus the lease's variables.
16
- * `PORT` comes back only for `as`, because one shell-wide `PORT` makes the backend and the
17
- * dashboard bind the same port. `DMS_MONGO_URL` in `parent` replaces the lease's own mongod.
18
- * `DMS_API_BASE_URL` stays unset. A backend whose config hard-codes its port falls back to a free
19
- * one and records it in `.antelope/dev.json`, and `ajs dms dev` reads that file only without it.
20
- */
21
- function leaseEnv(lease, parent, as) {
22
- const { record, dir } = lease;
23
- const { ports } = record;
24
- const { PORT: _inherited, ...env } = parent;
25
- Object.assign(env, {
26
- ANTELOPEJS_LEASE: record.id,
27
- ANTELOPEJS_LEASE_DIR: dir,
28
- DMS_BACK_PORT: String(ports.api),
29
- DMS_FRONT_PORT: String(ports.web),
30
- DMS_INSPECT_PORT: String(ports.inspect),
31
- DMS_SMTP_PORT: String(ports.smtp),
32
- DMS_CLIENT_BASE_URL: `http://localhost:${ports.web}`,
33
- MONGO_URL: parent.DMS_MONGO_URL || `mongodb://127.0.0.1:${ports.mongo}`,
34
- MONGO_DATABASE: `dms_${record.id}`,
35
- DMS_BACK_LOG: join(dir, "logs", "back.log"),
36
- DMS_FRONT_LOG: join(dir, "logs", "front.log"),
37
- TMPDIR: join(dir, "tmp")
38
- });
39
- if (as !== void 0) env.PORT = String(ports[as]);
40
- return env;
41
- }
42
- //#endregion
43
11
  //#region src/lease/exec.ts
44
12
  const SHELL = "/bin/sh";
45
13
  const DEFAULT_PATH = "/bin:/usr/bin";
@@ -150,10 +118,72 @@ function launch(command, env) {
150
118
  ], env) : process.execve(verdict.file, [name, ...args], env);
151
119
  }
152
120
  //#endregion
121
+ //#region src/lease/procs.ts
122
+ const STAT_AFTER_COMM = 2;
123
+ const STAT_PPID = 1;
124
+ const STAT_PGID = 2;
125
+ const STAT_START = 19;
126
+ const DEAD_STATES = /* @__PURE__ */ new Set(["Z", "X"]);
127
+ function fromProc(pid) {
128
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
129
+ const fields = stat.slice(stat.lastIndexOf(")") + STAT_AFTER_COMM).split(" ");
130
+ if (DEAD_STATES.has(fields[0] ?? "")) return void 0;
131
+ return {
132
+ pid,
133
+ start: `${readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim()}:${fields[STAT_START]}`,
134
+ uid: statSync(`/proc/${pid}`).uid,
135
+ pgid: Number(fields[STAT_PGID]),
136
+ ppid: Number(fields[STAT_PPID])
137
+ };
138
+ }
139
+ function fromPs(pid) {
140
+ const [uid, pgid, ppid, state, ...started] = execFileSync("ps", [
141
+ "-o",
142
+ "uid=,pgid=,ppid=,stat=,lstart=",
143
+ "-p",
144
+ String(pid)
145
+ ], {
146
+ encoding: "utf8",
147
+ stdio: [
148
+ "ignore",
149
+ "pipe",
150
+ "ignore"
151
+ ]
152
+ }).trim().split(/\s+/u);
153
+ if (state === void 0 || DEAD_STATES.has(state.slice(0, 1))) return void 0;
154
+ return {
155
+ pid,
156
+ start: started.join(" "),
157
+ uid: Number(uid),
158
+ pgid: Number(pgid),
159
+ ppid: Number(ppid)
160
+ };
161
+ }
162
+ /**
163
+ * The identity of the live process `pid`; `undefined` when it does not exist, is a zombie, or the
164
+ * platform cannot tell (anything but Linux and macOS).
165
+ */
166
+ function identify(pid) {
167
+ if (!Number.isInteger(pid) || pid <= 0) return void 0;
168
+ try {
169
+ if (process.platform === "linux") return fromProc(pid);
170
+ if (process.platform === "darwin") return fromPs(pid);
171
+ } catch {
172
+ return;
173
+ }
174
+ }
175
+ /**
176
+ * Throws unless `pid` is an integer above 1. `process.kill` reads 0 as the caller's own process group, a negative number
177
+ * as a group or, for -1, every process this user owns, and 1 is init, so none of them may reach a signal.
178
+ */
179
+ function assertSignallable(pid) {
180
+ if (!Number.isInteger(pid) || pid <= 1) throw new Error(`antelopejs-lease: refusing to signal pid ${String(pid)}`);
181
+ }
182
+ //#endregion
153
183
  //#region src/lease/mongo.ts
154
184
  const READY_TIMEOUT_MS = 3e4;
155
- const KILL_WAIT_MS = 2e3;
156
- const POLL_MS = 50;
185
+ const KILL_WAIT_MS$1 = 2e3;
186
+ const POLL_MS$1 = 50;
157
187
  const CACHED_BINARY = /^mongod-.+-(\d+)\.(\d+)\.(\d+)$/u;
158
188
  function executable(path) {
159
189
  try {
@@ -230,12 +260,13 @@ function serves(pid, dbpath) {
230
260
  return commandLine(pid).includes(dbpath);
231
261
  }
232
262
  /** Waits for the process itself: mongod empties `mongod.lock` before it exits. */
233
- async function untilGone(pid, dbpath, ms) {
263
+ async function untilGone$1(pid, dbpath, ms) {
234
264
  const deadline = Date.now() + ms;
235
- while (serves(pid, dbpath) && Date.now() < deadline) await setTimeout(POLL_MS);
265
+ while (serves(pid, dbpath) && Date.now() < deadline) await setTimeout(POLL_MS$1);
236
266
  return !serves(pid, dbpath);
237
267
  }
238
- function signal(pid, name) {
268
+ function signal$1(pid, name) {
269
+ assertSignallable(pid);
239
270
  try {
240
271
  process.kill(pid, name);
241
272
  } catch {
@@ -250,12 +281,12 @@ async function stopMongod(dbpath, graceMs) {
250
281
  const pid = mongodPid(dbpath);
251
282
  if (pid === void 0) return;
252
283
  if (graceMs > 0) {
253
- signal(pid, "SIGTERM");
254
- if (await untilGone(pid, dbpath, graceMs)) return;
284
+ signal$1(pid, "SIGTERM");
285
+ if (await untilGone$1(pid, dbpath, graceMs)) return;
255
286
  }
256
- signal(pid, "SIGKILL");
257
- if (await untilGone(pid, dbpath, KILL_WAIT_MS)) return;
258
- throw new Error(`antelopejs-lease: mongod ${pid} was still running ${KILL_WAIT_MS / 1e3} s after SIGKILL`);
287
+ signal$1(pid, "SIGKILL");
288
+ if (await untilGone$1(pid, dbpath, KILL_WAIT_MS$1)) return;
289
+ throw new Error(`antelopejs-lease: mongod ${pid} was still running ${KILL_WAIT_MS$1 / 1e3} s after SIGKILL`);
259
290
  }
260
291
  async function holder(port) {
261
292
  const pids = listenerPids(port);
@@ -297,7 +328,7 @@ async function ready(port, paths, exited) {
297
328
  if (pid !== void 0 && await listensOn(pid, port)) return;
298
329
  if (pid === void 0 && !starting(paths.dbpath)) break;
299
330
  }
300
- await setTimeout(POLL_MS);
331
+ await setTimeout(POLL_MS$1);
301
332
  }
302
333
  throw new Error(`antelopejs-lease: mongod did not answer on port ${port}${await holder(port)}; see ${paths.log}`);
303
334
  }
@@ -306,7 +337,8 @@ async function ready(port, paths, exited) {
306
337
  * With `--fork`, mongod daemonizes itself, and the process this call starts exits once the server
307
338
  * accepts connections. The server is never a child of this process, nor of the command `run`
308
339
  * becomes, which would keep it as a zombie after `down`. Two callers at once are safe: mongod locks its dbpath, so the second exits and both wait
309
- * for the first.
340
+ * for the first. mongod gets no `ANTELOPEJS_LEASE`, even when the caller runs under another
341
+ * worktree's lease, so only `down` of its own lease stops it.
310
342
  */
311
343
  async function ensureMongod(port, paths, env) {
312
344
  if (mongodPid(paths.dbpath) !== void 0) return ready(port, paths, () => true);
@@ -327,7 +359,8 @@ async function ensureMongod(port, paths, env) {
327
359
  "--fork"
328
360
  ], {
329
361
  detached: true,
330
- stdio: "ignore"
362
+ stdio: "ignore",
363
+ env: unmarked(process.env)
331
364
  });
332
365
  let exited = false;
333
366
  started.once("exit", () => exited = true);
@@ -486,7 +519,7 @@ async function removeLease(dir) {
486
519
  });
487
520
  }
488
521
  function running(pid) {
489
- if (!Number.isInteger(pid) || pid <= 0) return false;
522
+ if (!Number.isInteger(pid) || pid <= 1) return false;
490
523
  try {
491
524
  process.kill(pid, 0);
492
525
  return true;
@@ -604,6 +637,98 @@ function openLease(home, worktree, mongo) {
604
637
  });
605
638
  }
606
639
  //#endregion
640
+ //#region src/lease/stop.ts
641
+ const GRACE_MS = 5e3;
642
+ const KILL_WAIT_MS = 2e3;
643
+ const POLL_MS = 50;
644
+ const ROUNDS = 3;
645
+ /** This process and its ancestors, which no stop may signal. */
646
+ function ancestry() {
647
+ const pids = /* @__PURE__ */ new Set([process.pid]);
648
+ let at = identify(process.pid);
649
+ while (at !== void 0 && !pids.has(at.ppid)) {
650
+ pids.add(at.ppid);
651
+ at = identify(at.ppid);
652
+ }
653
+ return pids;
654
+ }
655
+ function procEntries(pid, file) {
656
+ try {
657
+ return readFileSync(`/proc/${pid}/${file}`, "utf8").split("\0");
658
+ } catch {
659
+ return [];
660
+ }
661
+ }
662
+ /**
663
+ * The live processes of this user whose environment holds `marker`, except `shield`. The start time
664
+ * is read before and after the environment, so the environment read belongs to the process found.
665
+ */
666
+ function discover(marker, shield) {
667
+ const uid = process.getuid?.();
668
+ return readdirSync("/proc").filter((name) => /^\d+$/u.test(name)).map(Number).flatMap((pid) => {
669
+ const found = identify(pid);
670
+ if (found === void 0 || found.uid !== uid || shield.has(pid)) return [];
671
+ if (!procEntries(pid, "environ").includes(marker)) return [];
672
+ const command = procEntries(pid, "cmdline").join(" ");
673
+ if (identify(pid)?.start !== found.start) return [];
674
+ return [{
675
+ pid,
676
+ start: found.start,
677
+ command: command.replace(/\s+/gu, " ").trim()
678
+ }];
679
+ });
680
+ }
681
+ /** Whether `target` is still the process it was found as. A zombie has exited. */
682
+ function alive(target) {
683
+ return identify(target.pid)?.start === target.start;
684
+ }
685
+ function signal(target, name) {
686
+ assertSignallable(target.pid);
687
+ if (!alive(target)) return;
688
+ try {
689
+ process.kill(target.pid, name);
690
+ } catch {
691
+ return;
692
+ }
693
+ }
694
+ async function untilGone(targets, ms) {
695
+ const deadline = Date.now() + ms;
696
+ let left = targets.filter(alive);
697
+ while (left.length > 0 && Date.now() < deadline) {
698
+ await setTimeout(POLL_MS);
699
+ left = left.filter(alive);
700
+ }
701
+ return left;
702
+ }
703
+ async function terminate(found, report) {
704
+ for (const target of found) signal(target, "SIGTERM");
705
+ const stubborn = await untilGone(found, GRACE_MS);
706
+ for (const target of stubborn) signal(target, "SIGKILL");
707
+ const survivors = await untilGone(stubborn, KILL_WAIT_MS);
708
+ for (const target of found) if (!survivors.includes(target)) report(`stopped pid ${target.pid} (${target.command})`);
709
+ if (survivors.length > 0) throw new Error(`antelopejs-lease: pid ${survivors.map((target) => target.pid).join(", ")} still running ${KILL_WAIT_MS / 1e3} s after SIGKILL`);
710
+ }
711
+ /**
712
+ * Stops every process of this user whose environment holds `ANTELOPEJS_LEASE=<id>`, which `run`
713
+ * exports and every descendant inherits, except this process and its ancestors. Signals each pid
714
+ * alone, never a group: SIGTERM, a few seconds to exit, then SIGKILL, with the start time checked
715
+ * again before each signal so a pid the system reused is never signalled. Scans again after each
716
+ * pass, for processes forked meanwhile. Calls `report` with one line per process that stopped, and
717
+ * throws when one outlives the kill or new ones keep appearing. Linux only: it reads `/proc`.
718
+ */
719
+ async function stopOwn(id, report) {
720
+ if (process.platform !== "linux") throw new Error("antelopejs-lease: down --stop reads /proc and runs on Linux only; stop your servers with their own stop command, then run down");
721
+ const marker = leaseMarker(id);
722
+ const shield = ancestry();
723
+ for (let round = 0; round < ROUNDS; round += 1) {
724
+ const found = discover(marker, shield);
725
+ if (found.length === 0) return;
726
+ await terminate(found, report);
727
+ }
728
+ const left = discover(marker, shield);
729
+ if (left.length > 0) throw new Error(`antelopejs-lease: pid ${left.map((target) => target.pid).join(", ")} of this lease appeared after ${ROUNDS} rounds of --stop`);
730
+ }
731
+ //#endregion
607
732
  //#region src/lease/commands.ts
608
733
  const DOWN_GRACE_MS = 1e4;
609
734
  const DAY_MS = 864e5;
@@ -687,20 +812,29 @@ function statusTable(rows) {
687
812
  const widths = cells[0]?.map((_, column) => Math.max(...cells.map((line) => line[column]?.length ?? 0)));
688
813
  return cells.map((line) => line.map((cell, column) => cell.padEnd(widths?.[column] ?? 0)).join(" ").trimEnd()).map((line) => `${line}\n`).join("");
689
814
  }
815
+ function stillListens(record, busy, stopped) {
816
+ const ports = busy.join(" and ");
817
+ if (!stopped) return /* @__PURE__ */ new Error(`antelopejs-lease: port ${ports} of this lease still listens; stop what this worktree started with antelopejs-lease down --stop, or pass --force to tear down anyway`);
818
+ const pids = busy.flatMap(listenerPids);
819
+ const holder = pids.length > 0 ? `pid ${pids.join(", ")}` : "a process this user cannot inspect";
820
+ return /* @__PURE__ */ new Error(`antelopejs-lease: port ${ports} of this lease still listens after --stop, held by ${holder} without ${leaseMarker(record.id)} in its environment, so not started by this lease and left running; pass --force to tear down anyway`);
821
+ }
690
822
  /**
691
- * Tears down this worktree's lease: stops its mongod and deletes its data, logs and tmp. Refuses
692
- * while its api or web port accepts, unless `force`. Does nothing when there is no lease.
823
+ * Tears down this worktree's lease: stops its mongod and deletes its data, logs and tmp. With
824
+ * `stop`, first stops the processes the lease started. Refuses while its api or web port accepts,
825
+ * unless `force`. Does nothing when there is no lease.
693
826
  */
694
- async function down(env, force) {
827
+ async function down(env, options) {
695
828
  const worktree = locateWorktree(process.cwd());
696
829
  const entry = readEntries(leaseHome(env)).find((candidate) => candidate.id === worktree.id);
697
830
  if (entry === void 0) return;
698
831
  if (entry.parsed?.kind === "foreign") throw foreignRecord(entry.dir);
699
- const ports = entry.parsed?.kind === "current" ? entry.parsed.record.ports : void 0;
700
- if (ports !== void 0 && !force) {
832
+ const record = entry.parsed?.kind === "current" ? entry.parsed.record : void 0;
833
+ if (record !== void 0 && options.stop !== void 0) await stopOwn(record.id, options.stop);
834
+ if (record !== void 0 && !options.force) {
701
835
  const busy = [];
702
- for (const port of [ports.api, ports.web]) if (await accepting(port)) busy.push(port);
703
- if (busy.length > 0) throw new Error(`antelopejs-lease: port ${busy.join(" and ")} of this lease still listens; stop the servers first (for dms-dev.sh: antelopejs-lease run -- bash <path to dms-dev.sh> stop), or pass --force`);
836
+ for (const port of [record.ports.api, record.ports.web]) if (await accepting(port)) busy.push(port);
837
+ if (busy.length > 0) throw stillListens(record, busy, options.stop !== void 0);
704
838
  }
705
839
  await stopMongod(mongodPaths(entry.dir).dbpath, DOWN_GRACE_MS);
706
840
  await withRegistryLock(() => removeLease(entry.dir));
@@ -719,7 +853,7 @@ async function gc(env, idleDays) {
719
853
  }
720
854
  //#endregion
721
855
  //#region src/bin/lease.ts
722
- const USAGE = "usage: antelopejs-lease run [--as api|web] -- <command...> | status [--json] | down [--force] | gc [--idle <days>]";
856
+ const USAGE = "usage: antelopejs-lease run [--as api|web] -- <command...> | status [--json] | down [--stop] [--force] | gc [--idle <days>]";
723
857
  const DEFAULT_IDLE_DAYS = 14;
724
858
  const MIN_IDLE_DAYS = 1;
725
859
  function usage(problem) {
@@ -743,12 +877,23 @@ async function statusVerb(args) {
743
877
  process.stdout.write(values.json ? `${JSON.stringify(rows, null, 2)}\n` : statusTable(rows));
744
878
  return 0;
745
879
  }
880
+ /** `down --stop` can stop the reader of its own output, such as a `| tee` in the same lease; losing that output must not abort the teardown. */
881
+ function ignoreBrokenPipe(error) {
882
+ if (error.code !== "EPIPE") throw error;
883
+ }
746
884
  async function downVerb(args) {
747
885
  const { values } = parseArgs({
748
886
  args,
749
- options: { force: { type: "boolean" } }
887
+ options: {
888
+ force: { type: "boolean" },
889
+ stop: { type: "boolean" }
890
+ }
891
+ });
892
+ if (values.stop === true) process.stdout.on("error", ignoreBrokenPipe);
893
+ await down(process.env, {
894
+ force: values.force === true,
895
+ stop: values.stop === true ? (line) => process.stdout.write(`${line}\n`) : void 0
750
896
  });
751
- await down(process.env, values.force === true);
752
897
  return 0;
753
898
  }
754
899
  async function gcVerb(args) {
@@ -3,7 +3,7 @@ import { c as parseCeilings, l as readCeilings, t as CEILINGS_FILE } from "../ce
3
3
  import { n as renamedPaths } from "../renames-L2owF5GD.mjs";
4
4
  import { t as runCli } from "../cli-4Tv71vYk.mjs";
5
5
  import { c as repositoryRoot, l as resolveRevision, s as repositoryPath, t as LINT_CONFIG } from "../files-DJ0TeaTU.mjs";
6
- import { n as ratchet, r as withPreviousTree } from "../ratchet-BAcLRYuM.mjs";
6
+ import { n as ratchet, r as withPreviousTree } from "../ratchet-Q-JXuZIX.mjs";
7
7
  import { t as lintDiagnostics } from "../oxlint-DIV-lLSS.mjs";
8
8
  import { d as stagedAdditions, f as stagedChanges, u as previousLine } from "../suppression-budget-C0SkPO5R.mjs";
9
9
  import { n as suppressionBase } from "../suppression-base-9L8dlMQK.mjs";