@roomi-fields/grillhouse 0.42.0 → 0.43.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.
@@ -5,5 +5,5 @@
5
5
  "author": {
6
6
  "name": "Romain Peyrichou"
7
7
  },
8
- "version": "0.42.0"
8
+ "version": "0.43.0"
9
9
  }
package/CHANGELOG.md CHANGED
@@ -6,6 +6,18 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.43.0] - 2026-11-17
10
+
11
+ - **The day of the board counts the tokens since the day's marker, as it counts the time** (grillhouse-38t): a session still open counted in the day the part of its turns since the marker, but all the tokens of its transcript — a supervisor's session opened days ago read « jour 6 min · 37,0 M » right after `/grillhouse newday` (OSC Bridge). A measure that holds its tokens by minute now counts in the day those of the minutes since the marker (`jetonsDuJour`); a register line without them counts whole in the day it ended, as before. And the time of the supervisor's own session counts neither in the day nor in the cumul, its tokens still do: open for weeks, each of its turns counted from the request to the end of the answer, its waits included — 2 025 h of « travail » for one session of OSC Bridge, where SyntHub's whole cumul read 135 h; the time of the two figures is now the work of the agents and of the circuits. **Action for projects**: none.
12
+
13
+ - **A crate without a test does not turn the pass of its project red** (grillhouse-jhf): the skeleton of a crate (`npx grillhouse paquet`) declares its target of integration tests, `tests/it/main.rs`, with no test in it, as the charter has it; nextest, played on the whole crate, ended in error (« no tests to run »), so two crates born out of the circuit turned red the final pass of every circuit of their project until their own ticket of code entered (OSD, osd-cli and osd-formats, circuit OSD-b91.7). The day of a whole crate now plays nextest with `--no-tests=pass`; a target or a module named that plays no test stays an error. **Action for projects**: none.
14
+
15
+ - **The board writes a duration of an hour or more without spaces, and a billion tokens in G** : « 1h16 », not « 1 h 16 » (`duree` of `scripts/tableau.mjs`), on every line of the board and of the status line; a count of tokens of a billion or more is written « 1,2 G » (`k`), where it read « 1234,5 M », and a count that would round to a thousand of its unit takes the next one. **Action for projects**: none.
16
+
17
+ - **A pass never plays more test processes than the machine has cores, and is cut before the memory runs out** (grillhouse-anz): a heavy pass played half the cores as tasks side by side, each task of tests keeping Vitest's own default, every core — up to 6 × 11 test processes on 12 cores — and read the memory at its start alone. On a project whose test workers weigh 1.5 GB (BPScript, a pass replayed whole after an update), 19 of them took 28 GB, memory and swap ran out and the kernel killed the user's session, every Claude session with it. Besides, the bound of a session of an agent (`GRILLHOUSE_TRAVAILLEURS`, cores ÷ places) never reached the tests: Turborepo's strict mode drops a variable the root's `globalPassThroughEnv` does not name. Three changes: the variable joins `globalPassThroughEnv` (the generator writes it, the guard `turbo-des-paquets` demands it); a pass gives each task of tests the cores shared between the tasks of tests side by side (`travailleursDeLaPasse`: 2 workers on 12 cores and 6 tasks, 12 in all); and the run of Turborepo plays under a watch of the memory (`scripts/garde-de-la-memoire.mjs`, as earlyoom and systemd-oomd), which ends the command and every process it started when the memory available and the free swap fall together under 4 GB, or when the machine waits for its memory half of the time (`/proc/pressure/memory`, `full avg10` at 50 %, which a swap held in memory reaches first) — the pass says why and ends at 75, « à repasser », and a circuit counts that 75 as a replay (`memoire-coupee.txt` in the results of the pass), so that a pass the memory cuts again goes up to the supervisor instead of waiting without end. The share counts the packages that hold tests, not those a pass plays again: on a project of many packages where few replay, each task of tests has fewer workers than the cores left idle would allow, and cargo and pytest take the same bound in a pass (`-j`, `-n`). **Action for projects**: `npx grillhouse maj`, which writes `GRILLHOUSE_TRAVAILLEURS` in the root's `turbo.json`.
18
+
19
+ - **The board says the gesture when the command `bd` is missing** (grillhouse-4t9): a session opened under a Node where Beads is not installed (a global package of npm follows its Node: the move to Node 26 leaves it behind) showed « Tickets illisibles : spawnSync bd ENOENT » on every board, the error of the system and no gesture. The alert now says « la commande bd est absente du PATH de cette séance » with its command (`npm install -g @beads/bd`), as the session start names it under « Manque » ; any other fault of Beads keeps its first line. **Action for projects**: none; after a change of Node, install Beads again under it (`npm install -g @beads/bd`).
20
+
9
21
  ## [0.42.0] - 2026-11-16
10
22
 
11
23
  - **The guard refuses a style script of the root that launches the packages again** (grillhouse-6dt): the root keeps its own files (grillhouse-44b.9), and the guard `turbo-des-paquets` refused a root `lint` or `format:check` that names a file a package holds, but read paths alone; a script that delegates to the packages (`npm run lint --workspaces --if-present`, `-w <paquet>`, `turbo run lint`) names none and passed, so the root task `//#lint` played the style of every package a second time, the packages out of the frame included — BPScript's update went red on « ⛔ //#lint (code 1) », no guard naming the script. The guard now refuses such a script by its name, with the gesture. **Action for projects**: a project whose root `lint` or `format:check` launches its packages removes it, or reduces it to the files of the root; Turborepo plays the script of each package.
@@ -37,7 +37,7 @@ interface publiée…>. Le cadre et l'architecture montent toujours (charte comm
37
37
 
38
38
  ## Commandes
39
39
 
40
- - `npm test` (Turborepo : construction, puis tests ; une tâche dont rien n'a bougé est relue de son cache, `npm run test:forcer` rejoue) · `npm test -- <chemins>` (un lancement ciblé : chaque chemin écrit depuis la racine, joué dans son paquet, avec les constructions dont ses tests dépendent, relues du cache ; ses tests rejouent dès que bouge ce qu'ils importent ; un lancement qui ne joue aucun test échoue ; un test de nuit nommé est refusé, la nuit seule le joue ; une mesure de temps — un banc, un témoin de temps — se joue quand son propre fichier est nommé, sous la mesure du temps) · `npm run verifier` (après la construction, les gardes du cadre, celles du projet — son script `gardes` —, le typage de chaque paquet — son script `typecheck`, ses sources et ses tests —, la mise en forme et le lint de la racine — ses scripts `format:check` et `lint`, joués quand ils existent — et les tests, côte à côte, sous le verrou de la machine, sans aucune mesure de temps, que joue la nuit seule : ce que jouent l'intégration, la file, la CI et la nuit ; mesuré contre le dernier vert, un paquet rejoué joue les tests que Vitest relie aux fichiers changés depuis, tous quand un changement sort de son graphe ; 0 vert, 1 rouge, un délai dépassé compris ; 75 quand l'attente du verrou de la machine ou de place sous /tmp atteint sa borne) · `npm run verifier -- --tout` (la passe complète, chaque test joué pour de vrai : ce que joue la nuit) · `npm run verifier -- --gardes` (les gardes, la mise en forme et le lint, même verdict : ce que joue le relecteur) · `npm run typecheck` · `npm run lint` · `npm run format:check`.
40
+ - `npm test` (Turborepo : construction, puis tests ; une tâche dont rien n'a bougé est relue de son cache, `npm run test:forcer` rejoue) · `npm test -- <chemins>` (un lancement ciblé : chaque chemin écrit depuis la racine, joué dans son paquet, avec les constructions dont ses tests dépendent, relues du cache ; ses tests rejouent dès que bouge ce qu'ils importent ; un lancement qui ne joue aucun test échoue ; un test de nuit nommé est refusé, la nuit seule le joue ; une mesure de temps — un banc, un témoin de temps — se joue quand son propre fichier est nommé, sous la mesure du temps) · `npm run verifier` (après la construction, les gardes du cadre, celles du projet — son script `gardes` —, le typage de chaque paquet — son script `typecheck`, ses sources et ses tests —, la mise en forme et le lint de la racine — ses scripts `format:check` et `lint`, joués quand ils existent — et les tests, côte à côte, sous le verrou de la machine, sans aucune mesure de temps, que joue la nuit seule : ce que jouent l'intégration, la file, la CI et la nuit ; mesuré contre le dernier vert, un paquet rejoué joue les tests que Vitest relie aux fichiers changés depuis, tous quand un changement sort de son graphe ; 0 vert, 1 rouge, un délai dépassé compris ; 75 quand l'attente du verrou de la machine ou de place sous /tmp atteint sa borne, ou quand la veille de la mémoire coupe la passe avant que le système ne tue) · `npm run verifier -- --tout` (la passe complète, chaque test joué pour de vrai : ce que joue la nuit) · `npm run verifier -- --gardes` (les gardes, la mise en forme et le lint, même verdict : ce que joue le relecteur) · `npm run typecheck` · `npm run lint` · `npm run format:check`.
41
41
  - Préfixe des tickets : `<prefixe>-`.
42
42
  - La politique de poussée : la clé `grillhouse.poussee` du `package.json` (`commit` : la branche où
43
43
  part chaque commit, main par défaut ; `nuit` : la branche où la nuit pousse son commit vert ;
@@ -5,7 +5,8 @@
5
5
  "GRILLHOUSE_RESULTATS",
6
6
  "GRILLHOUSE_CHANGEMENTS",
7
7
  "GRILLHOUSE_AVANCEMENT",
8
- "TMPDIR"
8
+ "TMPDIR",
9
+ "GRILLHOUSE_TRAVAILLEURS"
9
10
  ],
10
11
  "tasks": {
11
12
  "build": {
@@ -5,7 +5,8 @@
5
5
  "GRILLHOUSE_RESULTATS",
6
6
  "GRILLHOUSE_CHANGEMENTS",
7
7
  "GRILLHOUSE_AVANCEMENT",
8
- "TMPDIR"
8
+ "TMPDIR",
9
+ "GRILLHOUSE_TRAVAILLEURS"
9
10
  ],
10
11
  "tasks": {
11
12
  "build": {
@@ -963,7 +963,10 @@ nombre de cœurs et si 4 Go au moins sont libres, deux départs étant espacés
963
963
  espacement), garde le rang d'arrivée du circuit (pris à son lancement) et s'arrête à la borne de
964
964
  l'attente du verrou, 75. Chaque séance joue ses tests sur max(1, cœurs ÷ places) travailleurs
965
965
  (`GRILLHOUSE_TRAVAILLEURS`, lu par le module de chaque langage : `maxWorkers` de Vitest, `-j` de
966
- cargo et nextest, `-n` de pytest), sous `nice` et `ionice` ; une passe lourde garde tous les cœurs.
966
+ cargo et nextest, `-n` de pytest), sous `nice` et `ionice` ; la variable atteint chaque tâche par le
967
+ `globalPassThroughEnv` de la racine, que le mode strict de Turborepo exige. Une passe lourde partage
968
+ les cœurs entre ses tâches de tests côte à côte : les processus de tests d'une passe ne dépassent
969
+ jamais le nombre de cœurs.
967
970
  Une passe lourde prend sa place, puis le verrou exclusif de la machine ; une passe ciblée part
968
971
  pendant qu'une passe lourde tient le verrou.
969
972
 
@@ -996,7 +999,14 @@ reprend, comme le serveur de tâches de GNU make. L'attente a une borne, 60 min
996
999
  (`GRILLHOUSE_ATTENTE_MACHINE_MS`), plus longue que la plus longue passe complète mesurée : au-delà,
997
1000
  la mesure s'arrête « à repasser » (code 75), comme `flock -w`. Un verrou tenu par un ancêtre de
998
1001
  celui qui attend est un blocage : l'attente le dit tout de suite et s'arrête, rouge. La passe
999
- borne ses tâches côte à côte à la moitié des cœurs. Ainsi une mesure rend le résultat du code, et
1002
+ borne ses tâches côte à côte à la moitié des cœurs, et les travailleurs de chaque tâche de tests aux
1003
+ cœurs partagés entre elles (`travailleursDeLaPasse`). Elle joue sous la veille de la mémoire
1004
+ (`scripts/garde-de-la-memoire.mjs`, comme earlyoom et systemd-oomd) : quand la mémoire disponible et
1005
+ l'échange libre passent ensemble sous 4 Go, ou que la machine attend sa mémoire la moitié du temps
1006
+ (`/proc/pressure/memory`, `full avg10` à 50 %), la veille arrête la commande et chaque processus
1007
+ qu'elle a lancé ; la passe dit pourquoi et finit « à repasser » (75), avant que le noyau ne tue. Ce
1008
+ 75 n'est pas une attente de la machine : le circuit le compte comme un rejeu (`memoire-coupee.txt`
1009
+ dans les résultats de la passe), et une passe coupée de nouveau monte au superviseur. Ainsi une mesure rend le résultat du code, et
1000
1010
  non celui d'une autre mesure à côté, et aucune passe ne reste figée sans le dire.
1001
1011
 
1002
1012
  **Le cadre passe avant les projets** : une mesure jouée dans le dépôt du cadre lui-même (le
package/docs/INTERFACE.md CHANGED
@@ -366,10 +366,11 @@ l'interruption), la pression de la machine et son verrou, les places de la machi
366
366
  l'environnement de ses enfants, son code de sortie, ou celui de l'attente qui s'arrête, 75 à sa
367
367
  borne, 1 pour un serveur qui ne répond pas ; `avecLaMachineEtUnePlace` : une passe lourde, la place
368
368
  puis le verrou ; aucune place dans la CI ni dans l'enveloppe d'un agent, que couvre la place de sa
369
- séance), les travailleurs d'une séance
370
- (`travailleursDeLaSeance(env)` : le nombre que donne `GRILLHOUSE_TRAVAILLEURS`, max(1, cœurs ÷
371
- places), que le module passe à son outil — `maxWorkers`, `-j`, `-n` — ou `null` pour une passe
372
- lourde, qui garde tous les cœurs ; une valeur fautive est refusée par son nom), le dernier vert, le
369
+ séance), les travailleurs des tests d'une tâche
370
+ (`travailleursDeLaSeance(env)` : le nombre que donne `GRILLHOUSE_TRAVAILLEURS`, que posent une
371
+ séance (max(1, cœurs ÷ places)) et une passe lourde (les cœurs partagés entre ses tâches de tests
372
+ côte à côte), et que le module passe à son outil — `maxWorkers`, `-j`, `-n` — ou `null` sans la
373
+ variable, l'outil gardant son défaut ; une valeur fautive est refusée par son nom), le dernier vert, le
373
374
  registre des résultats (`registre-des-resultats.mjs` : `garderLeRegistre(etat, rapports)`, les
374
375
  tests verts de chaque fichier d'une passe, que la passe complète écrit quand `GRILLHOUSE_RESULTATS`
375
376
  nomme son dossier de résultats ; `lireLeRegistre(racine)`, le registre de la branche quand son
@@ -71,10 +71,16 @@ const etat = atom({ plugin: 'grillhouse', key: 'etat' } as const, {
71
71
  } as Etat)
72
72
 
73
73
  export const k = (n: number) =>
74
- n >= 1e6 ? `${(n / 1e6).toFixed(1).replace('.', ',')} M` : n >= 1e3 ? `${Math.round(n / 1e3)} k` : `${n}`
74
+ n >= 999.95e6
75
+ ? `${(n / 1e9).toFixed(1).replace('.', ',')} G`
76
+ : n >= 999.5e3
77
+ ? `${(n / 1e6).toFixed(1).replace('.', ',')} M`
78
+ : n >= 1e3
79
+ ? `${Math.round(n / 1e3)} k`
80
+ : `${n}`
75
81
  export const duree = (ms: number) => {
76
82
  const min = Math.round(ms / 60_000)
77
- return min < 60 ? `${min} min` : `${Math.floor(min / 60)} h ${String(min % 60).padStart(2, '0')}`
83
+ return min < 60 ? `${min} min` : `${Math.floor(min / 60)}h${String(min % 60).padStart(2, '0')}`
78
84
  }
79
85
  const STATUTS: Record<string, string> = {
80
86
  open: 'ouvert',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@roomi-fields/grillhouse",
3
- "version": "0.42.0",
3
+ "version": "0.43.0",
4
4
  "description": "Roomi's Grillhouse: the frame's scripts, called by one command, grillhouse <sous-commande>",
5
5
  "keywords": [
6
6
  "claude-code",
@@ -26,7 +26,7 @@ import {
26
26
  } from 'node:fs';
27
27
  import path from 'node:path';
28
28
  import { avecLAvancementDuTravail } from './avancement.mjs';
29
- import { A_REPASSER } from './codes-de-sortie.mjs';
29
+ import { A_REPASSER, MEMOIRE_COUPEE } from './codes-de-sortie.mjs';
30
30
  import { ecouteLesBranchesDeTicket } from './ci-des-branches.mjs';
31
31
  import { BASE_DU_LOT, DEPUIS_LE_VERT } from './dernier-vert.mjs';
32
32
  import { empreinteDEtape } from './empreinte-d-etape.mjs';
@@ -1405,7 +1405,7 @@ function npm(ctx, etape, args, env = {}, cwd = ctx.copie) {
1405
1405
  const oublier = nommerLAvancement({ env: envMachine, dossier: avancement });
1406
1406
  try {
1407
1407
  // A targeted pass plays on its share of the cores under nice and ionice; a heavy one
1408
- // keeps every core.
1408
+ // shares the cores between its own tasks of tests.
1409
1409
  const lancement = lancementDeLaPasse({
1410
1410
  lourde,
1411
1411
  cmd: 'npm',
@@ -1440,8 +1440,11 @@ function npm(ctx, etape, args, env = {}, cwd = ctx.copie) {
1440
1440
  }
1441
1441
  );
1442
1442
  const code = r.status ?? 1;
1443
- // The 75 of `npm run verifier` is its wait for the lock or for room under /tmp at its bound.
1444
- return { code, dossier, attente: finale && code === A_REPASSER };
1443
+ // The 75 of `npm run verifier` is its wait for the lock or for room under /tmp at its bound,
1444
+ // which waits again without counting; cut by the watch of its memory (MEMOIRE_COUPEE in its
1445
+ // results), it is a replay that counts.
1446
+ const coupee = existsSync(path.join(dossier, MEMOIRE_COUPEE));
1447
+ return { code, dossier, attente: finale && code === A_REPASSER && !coupee };
1445
1448
  } catch (e) {
1446
1449
  if (!(e instanceof AttenteDeLaMachine)) {
1447
1450
  throw e;
@@ -1949,7 +1952,8 @@ export function controles(ctx, finale, restreinte = null, reportes = null, fichi
1949
1952
  : commandesDuPlan(ctx, liste, fichiers);
1950
1953
  const resultats = commandes.map(({ args, env }) => {
1951
1954
  let r = npm(ctx, 'controles', args, env);
1952
- // The 75 of verifier is final (its wait for the lock reached its bound); a command of the
1955
+ // The 75 of verifier is final (its wait for the lock reached its bound, or the watch of its
1956
+ // memory cut it); a command of the
1953
1957
  // checks plays once more, the gesture `rejeu`.
1954
1958
  if (r.code === A_REPASSER && !finale) {
1955
1959
  geste(ctx, 'rejeu');
@@ -7,3 +7,9 @@
7
7
  // wait of the lock of the machine at its bound (scripts/verrou-de-machine.mjs), a stop of the
8
8
  // circuit that a gesture settles (scripts/etapes.mjs, ARRETS).
9
9
  export const A_REPASSER = 75;
10
+
11
+ /**
12
+ * The file a pass cut by the watch of its memory (scripts/garde-de-la-memoire.mjs) leaves in its
13
+ * results directory, its reason inside: its 75 is no wait of the machine, and counts as a replay.
14
+ */
15
+ export const MEMOIRE_COUPEE = 'memoire-coupee.txt';
@@ -0,0 +1,231 @@
1
+ // The watch of the memory of a pass: a heavy pass runs its command under it, and is cut before the
2
+ // kernel kills, as earlyoom and systemd-oomd end a group before the kernel's own OOM killer does.
3
+ //
4
+ // node garde-de-la-memoire.mjs --temoin <file> -- <command> [<argument>…]
5
+ //
6
+ // - The command runs in the process group of the watch, its streams the caller's: a signal sent
7
+ // to the group of a pass (the stop of an act, of a night, of a session) reaches it as it reaches
8
+ // the watch.
9
+ // - Every PAS ms the watch reads what the machine still gives (`memoireRestante` of
10
+ // scripts/mesure-de-la-machine.mjs: the memory available and the free swap) and the pressure of
11
+ // the memory (`/proc/pressure/memory`, line `full`, field `avg10`: the share of the last ten
12
+ // seconds in which every task waited for memory, in %). The pass is cut (`memoireEpuisee`) under
13
+ // MEMOIRE_MIN for memory and swap together, or at SEUIL_PRESSION_MEMOIRE of pressure, which a
14
+ // swap held in memory (zram) reaches first.
15
+ // - Cut, the watch ends the command and each process born of it (SIGTERM, then SIGKILL after DELAI
16
+ // ms for those still alive), writes why in <file>, and exits at 75, « à repasser », once they are
17
+ // dead: the pass was not judged, and holds no memory when it gives the machine back.
18
+ // - Otherwise it exits with the command's own code; a command a signal ended gives 1, the signal
19
+ // said on the error output.
20
+ // - A machine that says neither its memory nor its pressure is not watched: the command runs as
21
+ // it is.
22
+ import { spawn } from 'node:child_process';
23
+ import { readdirSync, readFileSync, writeFileSync } from 'node:fs';
24
+ import { fileURLToPath, pathToFileURL } from 'node:url';
25
+ import { A_REPASSER } from './codes-de-sortie.mjs';
26
+ import { departDe, memoireRestante, processusVivant } from './mesure-de-la-machine.mjs';
27
+ import { MEMOIRE_MIN } from './regles-des-places.mjs';
28
+
29
+ /** This script. */
30
+ export const SCRIPT = fileURLToPath(import.meta.url);
31
+ /** The variable a trial fixes what the machine gives under: JSON `{ disponible, echange, pression }`. */
32
+ export const VARIABLE_MEMOIRE_D_ESSAI = 'GRILLHOUSE_MEMOIRE_D_ESSAI';
33
+ /** The pressure of the memory a pass is cut at, in %. */
34
+ export const SEUIL_PRESSION_MEMOIRE = 50;
35
+ const FICHIER_PRESSION = '/proc/pressure/memory';
36
+ const PAS = 2000;
37
+ const DELAI = 5000;
38
+
39
+ const go = n => (n / 1024 ** 3).toFixed(1).replace('.', ',');
40
+
41
+ /**
42
+ * The pressure `full avg10` of the memory in <texte> (/proc/pressure/memory), in %; null when it
43
+ * does not say it.
44
+ * @param {string} texte
45
+ * @returns {number | null}
46
+ */
47
+ export function lireLaPressionDeLaMemoire(texte) {
48
+ const m = /^full\b.*\bavg10=(\d+(?:\.\d+)?)/m.exec(texte);
49
+ return m ? Number(m[1]) : null;
50
+ }
51
+
52
+ /**
53
+ * Why a pass is cut at this memory, null while it may go on: the memory available and the free
54
+ * swap together under MEMOIRE_MIN, or the pressure of the memory at SEUIL_PRESSION_MEMOIRE.
55
+ * @param {{ disponible: number | null, echange: number, pression: number | null }} m bytes, %
56
+ * @returns {string | null}
57
+ */
58
+ export function memoireEpuisee({ disponible, echange, pression }) {
59
+ const suite =
60
+ 'la passe est coupée avant que le système ne tue, à repasser quand la machine a de la place.';
61
+ if (disponible !== null && disponible + echange < MEMOIRE_MIN) {
62
+ return `mémoire épuisée : ${go(disponible)} Go disponibles et ${go(echange)} Go d'échange libres, sous les ${go(MEMOIRE_MIN)} Go gardés ; ${suite}`;
63
+ }
64
+ if (pression !== null && pression >= SEUIL_PRESSION_MEMOIRE) {
65
+ return `mémoire épuisée : la machine attend sa mémoire ${String(pression).replace('.', ',')} % du temps (seuil ${SEUIL_PRESSION_MEMOIRE} %) ; ${suite}`;
66
+ }
67
+ return null;
68
+ }
69
+
70
+ /**
71
+ * What the machine gives now under <env>: a trial's, else the kernel's.
72
+ * @param {Record<string, string | undefined>} [env]
73
+ * @returns {{ disponible: number | null, echange: number, pression: number | null }}
74
+ */
75
+ export function mesurerLaMemoire(env = process.env) {
76
+ if (env[VARIABLE_MEMOIRE_D_ESSAI]) {
77
+ return { pression: null, ...JSON.parse(env[VARIABLE_MEMOIRE_D_ESSAI]) };
78
+ }
79
+ let pression = null;
80
+ try {
81
+ pression = lireLaPressionDeLaMemoire(readFileSync(FICHIER_PRESSION, 'utf8'));
82
+ } catch {
83
+ // no pressure stall information on the machine
84
+ }
85
+ return { ...memoireRestante(), pression };
86
+ }
87
+
88
+ // The processes born of <pid>, itself left out, as /proc says them now.
89
+ function descendants(pid) {
90
+ /** @type {Map<number, number[]>} */
91
+ const enfants = new Map();
92
+ for (const n of readdirSync('/proc')) {
93
+ if (!/^\d+$/.test(n)) {
94
+ continue;
95
+ }
96
+ try {
97
+ // The fields after the name, which may hold spaces and parentheses: state, then parent.
98
+ const stat = readFileSync(`/proc/${n}/stat`, 'utf8');
99
+ const parent = Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[1]);
100
+ enfants.set(parent, [...(enfants.get(parent) ?? []), Number(n)]);
101
+ } catch {
102
+ // gone meanwhile
103
+ }
104
+ }
105
+ const nes = [];
106
+ for (const file = [pid]; file.length;) {
107
+ for (const e of enfants.get(file.shift()) ?? []) {
108
+ nes.push(e);
109
+ file.push(e);
110
+ }
111
+ }
112
+ return nes;
113
+ }
114
+
115
+ // <signal> to each process of <relevés> (`{ pid, depart }`) that still is the one relevé.
116
+ const signaler = (releves, signal) => {
117
+ for (const r of releves) {
118
+ if (!processusVivant(r)) {
119
+ continue;
120
+ }
121
+ try {
122
+ process.kill(r.pid, signal);
123
+ } catch {
124
+ // gone
125
+ }
126
+ }
127
+ };
128
+
129
+ // The processes <pids> as relevés now: each with its start, which tells it from another process
130
+ // that takes its number later.
131
+ const relever = pids => pids.map(pid => ({ pid, depart: departDe(pid) })).filter(r => r.depart);
132
+
133
+ /**
134
+ * Runs <cmd> <args> under the watch: its exit code, 75 when the watch cut it, its witness
135
+ * <temoin> then saying why. A cut ends only once the command and every process relevé are dead,
136
+ * SIGKILL sent after <delai> ms to those SIGTERM did not end.
137
+ * @param {{ cmd: string, args: string[], temoin: string, mesurer?: () => { disponible: number | null, echange: number, pression: number | null }, pas?: number, delai?: number, stdio?: import('node:child_process').StdioOptions, env?: NodeJS.ProcessEnv, cwd?: string }} o
138
+ * @returns {Promise<number>}
139
+ */
140
+ export function veiller({
141
+ cmd,
142
+ args,
143
+ temoin,
144
+ mesurer = () => mesurerLaMemoire(),
145
+ pas = PAS,
146
+ delai = DELAI,
147
+ stdio = 'inherit',
148
+ env = process.env,
149
+ cwd,
150
+ }) {
151
+ return new Promise(resolve => {
152
+ const enfant = spawn(cmd, args, { stdio, env, cwd });
153
+ // The processes relevés at the cut, and its end: all dead, or SIGKILL sent at the delay.
154
+ let releves = null;
155
+ let finDeLaCoupe = null;
156
+ const couper = raison => {
157
+ // Relevés twice, the command still their ancestor: one born between the two is caught.
158
+ const nes = new Set([enfant.pid, ...descendants(enfant.pid)]);
159
+ for (const p of descendants(enfant.pid)) {
160
+ nes.add(p);
161
+ }
162
+ releves = relever([...nes]);
163
+ signaler(releves, 'SIGTERM');
164
+ finDeLaCoupe = new Promise(fin => {
165
+ // SIGKILL at the delay to those SIGTERM did not end; the end once none lives, or as long
166
+ // again after SIGKILL at the latest.
167
+ const limite = Date.now() + delai;
168
+ let tues = false;
169
+ const voir = setInterval(() => {
170
+ const vivants = releves.filter(processusVivant);
171
+ if (vivants.length && !tues && Date.now() >= limite) {
172
+ tues = true;
173
+ signaler(vivants, 'SIGKILL');
174
+ }
175
+ if (vivants.length === 0 || Date.now() >= limite + delai) {
176
+ clearInterval(voir);
177
+ fin();
178
+ }
179
+ }, 100);
180
+ });
181
+ try {
182
+ writeFileSync(temoin, `${raison}\n`);
183
+ } catch {
184
+ // the exit code alone says the cut
185
+ }
186
+ };
187
+ const veille = setInterval(() => {
188
+ if (releves) {
189
+ return;
190
+ }
191
+ let raison = null;
192
+ try {
193
+ raison = memoireEpuisee(mesurer());
194
+ } catch {
195
+ // a measure that does not read cuts nothing
196
+ }
197
+ if (raison) {
198
+ couper(raison);
199
+ }
200
+ }, pas);
201
+ enfant.on('error', e => {
202
+ clearInterval(veille);
203
+ process.stderr.write(`⛔ ${cmd} ne se lance pas : ${e.message}\n`);
204
+ resolve(1);
205
+ });
206
+ enfant.on('exit', (code, signal) => {
207
+ clearInterval(veille);
208
+ if (finDeLaCoupe) {
209
+ void finDeLaCoupe.then(() => resolve(A_REPASSER));
210
+ return;
211
+ }
212
+ if (code === null) {
213
+ process.stderr.write(`⛔ ${cmd} est arrêté par le signal ${signal}.\n`);
214
+ }
215
+ resolve(code ?? 1);
216
+ });
217
+ });
218
+ }
219
+
220
+ if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) {
221
+ const args = process.argv.slice(2);
222
+ if (args[0] !== '--temoin' || args[2] !== '--' || args.length < 4) {
223
+ process.stderr.write(
224
+ 'usage: garde-de-la-memoire.mjs --temoin <fichier> -- <commande> [<argument>…]\n'
225
+ );
226
+ process.exitCode = 2;
227
+ } else {
228
+ const [cmd, ...reste] = args.slice(3);
229
+ process.exitCode = await veiller({ cmd, args: reste, temoin: args[1] });
230
+ }
231
+ }
@@ -433,6 +433,12 @@ export function retirerALInterruption(retirer: () => void): () => void;
433
433
  export const SEUIL_PRESSION: number;
434
434
  /** The exit code of a pass « à repasser » (scripts/codes-de-sortie.mjs). */
435
435
  export const A_REPASSER: number;
436
+ /** The file a pass cut by the watch of its memory leaves in its results directory. */
437
+ export const MEMOIRE_COUPEE: string;
438
+ /** The script of the watch of the memory, which a pass runs under (scripts/garde-de-la-memoire.mjs). */
439
+ export const GARDE_DE_LA_MEMOIRE: string;
440
+ /** The variable of the workers of the tests of a task (scripts/places-de-la-machine.mjs). */
441
+ export const VARIABLE_TRAVAILLEURS: string;
436
442
  /** The file of Beads that holds the prefix of the tickets (scripts/prefixe-des-tickets.mjs). */
437
443
  export const CONFIG_BEADS: string;
438
444
  /** The prefix of the tickets, read from the key `issue-prefix`; throws when it is missing. */
@@ -456,8 +462,9 @@ export const PASSE_ROUGE: string;
456
462
  export function garderLeVert(etat: unknown): void;
457
463
  /** The measure of the repository at `racine` against its last green. */
458
464
  export function mesure(racine: string, o?: { tout?: boolean; dans?: string }): unknown;
459
- /** The workers a session of an agent plays its tests on (`GRILLHOUSE_TRAVAILLEURS` of `env`), or
460
- * null in a heavy pass (every core); refuses a value that is not a positive integer, by name. */
465
+ /** The workers a task plays its tests on (`GRILLHOUSE_TRAVAILLEURS` of `env`, which a session
466
+ * and a pass set), or null without the variable (the tool's own default); refuses a value that is
467
+ * not a positive integer, by name. */
461
468
  export function travailleursDeLaSeance(env?: NodeJS.ProcessEnv): number | null;
462
469
  /** The wait for the lock of the machine, ended without it (scripts/verrou-de-machine.mjs). */
463
470
  export class AttenteDeLaMachine extends Error {}
@@ -446,8 +446,8 @@ function jouerLesTests(racine, p, choix, options, temporaire = () => ({}), tranc
446
446
  const junit = path.join(m.workspace_root, 'target', 'nextest', PROFIL, 'junit.xml');
447
447
  const nextest = ['nextest', 'run', '--tool-config-file', `${PROFIL}:${NEXTEST}`];
448
448
  nextest.push('--profile', PROFIL, '--no-fail-fast');
449
- // The workers of a session of an agent (GRILLHOUSE_TRAVAILLEURS): `-j` of cargo and of nextest;
450
- // a heavy pass, without it, keeps every core.
449
+ // The workers of the task (GRILLHOUSE_TRAVAILLEURS, which a session and a pass set): `-j` of
450
+ // cargo and of nextest; without the variable, their own default.
451
451
  const travailleurs = travailleursDeLaSeance(process.env);
452
452
  const j = travailleurs === null ? [] : ['-j', String(travailleurs)];
453
453
  // A bench plays on one thread (`--test-threads 1`, which `-j` of nextest is the alias of): it
@@ -495,7 +495,10 @@ function jouerLesTests(racine, p, choix, options, temporaire = () => ({}), tranc
495
495
  ? [...duC, ...nommes]
496
496
  : []
497
497
  : [...nommes, ...filtreDesModules(nom, autres, modules)];
498
- const args = [...nextest, '-p', nom, ...selection, ...options];
498
+ // The day of a whole crate with no test at all is green (a crate born of its skeleton,
499
+ // its target of tests empty); a target or a module named that plays none stays an error.
500
+ const sansTest = cibles.length === 0 && !tranche ? ['--no-tests=pass'] : [];
501
+ const args = [...nextest, '-p', nom, ...selection, ...options, ...sansTest];
499
502
  prevues.push([
500
503
  p.prevoir(nom, d, 'nextest', true, args),
501
504
  { junit, temporaire: temporaire(nom) },
@@ -259,8 +259,8 @@ function jouerLesTests(p, choix, options) {
259
259
  const cache = path.join(p.racine, CACHE_DE_PYTEST, path.relative(p.racine, c.dossier));
260
260
  const args = [...UV_RUN, '--group', GROUPE, 'pytest', '-o', `cache_dir=${cache}`];
261
261
  args.push(...p.junit(c.nom, c.dossier));
262
- // The workers of a session of an agent (GRILLHOUSE_TRAVAILLEURS): `-n` of pytest-xdist, for a
263
- // package whose test group declares it; a heavy pass, without the variable, plays alone.
262
+ // The workers of the task (GRILLHOUSE_TRAVAILLEURS, which a session and a pass set): `-n` of
263
+ // pytest-xdist, for a package whose test group declares it; without the variable, one process.
264
264
  const travailleurs = travailleursDeLaSeance(process.env);
265
265
  if (travailleurs !== null && declareXdist(c.dossier)) {
266
266
  args.push('-n', String(travailleurs));
@@ -139,7 +139,7 @@
139
139
  // inherits the root's. The generator adds the variable to the `env` of the root's `test:unit`,
140
140
  // the project's entries kept, and the check refuses a `test:unit` of the root without it.
141
141
  //
142
- // Four variables pass to every task without entering any hash: the root's `globalPassThroughEnv`
142
+ // Some variables pass to every task without entering any hash: the root's `globalPassThroughEnv`
143
143
  // names them, Turborepo's strict mode of the variables keeping out of a task every variable its
144
144
  // configuration does not name. The results directory of a run (`GRILLHOUSE_RESULTATS`,
145
145
  // scripts/resultats.mjs), where the guards write their SARIF, Turborepo its summaries and Vitest
@@ -149,7 +149,9 @@
149
149
  // progress directory of a pass (`GRILLHOUSE_AVANCEMENT`, scripts/avancement.mjs), where Vitest
150
150
  // writes the files done and planned of each task, which the board reads; the temporary directory
151
151
  // (`TMPDIR`), the base of a pass (scripts/mesure/base-de-passe.mjs), where every task writes
152
- // its temporary files and which goes at the end of the pass. The generator adds each
152
+ // its temporary files and which goes at the end of the pass; the workers of the tests of a task
153
+ // (`GRILLHOUSE_TRAVAILLEURS`, scripts/places-de-la-machine.mjs), the bound a session or a pass
154
+ // sets, which the tool of each language reads. The generator adds each
153
155
  // one the root lacks, the project's entries kept, and the check refuses a
154
156
  // root without one.
155
157
  //
@@ -169,6 +171,7 @@ import {
169
171
  inscrireLePlan,
170
172
  paquetsSansPackageJson,
171
173
  TRACE,
174
+ VARIABLE_TRAVAILLEURS as TRAVAILLEURS,
172
175
  } from '../../services-du-noyau.mjs';
173
176
  import { matieres } from './consommateurs.mjs';
174
177
  import { parcourir } from './parcours.mjs';
@@ -307,7 +310,7 @@ const attenteDuTypage = racine => (paquets(racine).length ? ['build', '^build']
307
310
  // The temporary directory of a process, which names the base of its pass.
308
311
  const TEMPORAIRE = 'TMPDIR';
309
312
  // The variables the root's `globalPassThroughEnv` names, and why, as the check says it.
310
- const PASSAGES = [RESULTATS, CHANGEMENTS, AVANCEMENT, TEMPORAIRE];
313
+ const PASSAGES = [RESULTATS, CHANGEMENTS, AVANCEMENT, TEMPORAIRE, TRAVAILLEURS];
311
314
  const POURQUOI = {
312
315
  [RESULTATS]: "où les gardes, Turborepo et Vitest écrivent les résultats qu'un circuit lit",
313
316
  [CHANGEMENTS]:
@@ -316,6 +319,8 @@ const POURQUOI = {
316
319
  "le dossier d'avancement d'une passe, où Vitest écrit ses fichiers faits et prévus que lit le tableau",
317
320
  [TEMPORAIRE]:
318
321
  'la base de la passe, où chaque tâche écrit ses fichiers temporaires, effacée à sa fin',
322
+ [TRAVAILLEURS]:
323
+ "les travailleurs des tests d'une tâche, la borne que posent une séance et une passe",
319
324
  };
320
325
  // The variables of the tools of the project at <racine> (`grillhouse.outils` of its package.json,
321
326
  // scripts/outils-cles.mjs), in the order it declares them: the paths of tools outside the
@@ -44,7 +44,13 @@
44
44
  // every task whose prerequisites passed plays, and each red is named. <n>, the tasks side by
45
45
  // side, is half the cores of the machine, one at least (`concurrence`): each task of tests is
46
46
  // itself parallel (Vitest's workers), as make's `-j` and Bazel's `--local_cpu_resources` bound a
47
- // build by the machine; a `--concurrency` among the arguments replaces it.
47
+ // build by the machine; a `--concurrency` among the arguments replaces it. The workers of each
48
+ // task of tests are the cores shared between the tasks of tests side by side
49
+ // (`travailleursDeLaPasse`, GRILLHOUSE_TRAVAILLEURS): the test processes of a pass never
50
+ // outnumber the cores.
51
+ // - The run of Turborepo plays under the watch of the memory (scripts/garde-de-la-memoire.mjs): cut
52
+ // when the memory available and the free swap run out, or when the machine waits for its memory
53
+ // half of the time, the pass says why and ends at 75, « à repasser », no task judged.
48
54
  // - The pass plays no measure of time (grillhouse-bd7): the time budget benches and the time
49
55
  // witnesses (a test file that imports `mesurerAuRepos`) are out of the day, as the night tests
50
56
  // are, and the night plays them (scripts/langages/typescript/vitest-config/cibles.mjs,
@@ -106,6 +112,7 @@ import { availableParallelism, tmpdir } from 'node:os';
106
112
  import path from 'node:path';
107
113
  import { pathToFileURL } from 'node:url';
108
114
  import {
115
+ A_REPASSER,
109
116
  AttenteDeLaMachine,
110
117
  AVANCEMENT,
111
118
  avecLaMachineEtUnePlace,
@@ -115,8 +122,10 @@ import {
115
122
  garderLeRegistre,
116
123
  garderLeTotal,
117
124
  garderLeVert,
125
+ GARDE_DE_LA_MEMOIRE,
118
126
  LA_FORME,
119
127
  langageDe,
128
+ MEMOIRE_COUPEE,
120
129
  lireLaTranche,
121
130
  lireLeRegistre,
122
131
  mesure,
@@ -128,6 +137,7 @@ import {
128
137
  SCRIPT_DES_TESTS,
129
138
  TESTS_CIBLES,
130
139
  testsCibles,
140
+ VARIABLE_TRAVAILLEURS,
131
141
  } from '../../services-du-noyau.mjs';
132
142
  import { paquets, TYPAGE } from '../../paquets.mjs';
133
143
  import { RESULTATS } from '../../resultats.mjs';
@@ -152,9 +162,29 @@ const lister = dossier => (existsSync(dossier) ? readdirSync(dossier) : []);
152
162
  // The tasks a pass plays side by side on a machine of <coeurs> cores: half of them, one at least.
153
163
  const concurrence = (coeurs = availableParallelism()) => Math.max(1, Math.floor(coeurs / 2));
154
164
 
165
+ // The tasks side by side <args> ask for (`--concurrency=<n>`, `--concurrency <n>`), null without
166
+ // a whole number.
167
+ function concurrenceDemandee(args) {
168
+ const i = args.findIndex(a => CONCURRENCE.test(a));
169
+ if (i < 0) {
170
+ return null;
171
+ }
172
+ const v = args[i].includes('=') ? args[i].split('=')[1] : args[i + 1];
173
+ return /^[1-9]\d*$/.test(v ?? '') ? Number(v) : null;
174
+ }
175
+
176
+ /**
177
+ * The workers of each task of tests of a pass: the <coeurs> shared between the tasks of tests
178
+ * played side by side, at most <coteACote> and at most the <paquets> that play tests; one at least.
179
+ * @param {{ coeurs: number, coteACote: number, paquets: number }} o
180
+ * @returns {number}
181
+ */
182
+ export const travailleursDeLaPasse = ({ coeurs, coteACote, paquets: n }) =>
183
+ Math.max(1, Math.floor(coeurs / Math.max(1, Math.min(coteACote, n))));
184
+
155
185
  // The full pass in <racine>, its arguments <args> (`--gardes` among them: the guards alone), under
156
186
  // <env> and the lock of the machine; its verdict, 0 or 1, or 75 when the wait for the lock, or for
157
- // room in the temporary directory, reaches its bound. `dire` writes a line; `coeurs`, the cores of the machine.
187
+ // room in the temporary directory, reaches its bound, or when the watch of the memory cuts the run. `dire` writes a line; `coeurs`, the cores of the machine.
158
188
  export function verifier({
159
189
  racine = process.cwd(),
160
190
  args: demandes = [],
@@ -211,22 +241,24 @@ export function verifier({
211
241
  }
212
242
  }
213
243
 
214
- // Whether a package of <racine>, or its root, plays tests (a script `test:unit`).
215
- function depotAvecTests(racine) {
244
+ // The packages of <racine> that play tests (a script `test:unit`), its root for a repository
245
+ // without packages.
246
+ function paquetsAvecTests(racine) {
216
247
  const liste = paquets(racine);
217
248
  if (liste.length === 0) {
218
249
  try {
219
- return Boolean(
220
- JSON.parse(readFileSync(path.join(racine, 'package.json'), 'utf8')).scripts?.[
221
- SCRIPT_DES_TESTS
222
- ]
223
- );
250
+ return JSON.parse(readFileSync(path.join(racine, 'package.json'), 'utf8')).scripts?.[
251
+ SCRIPT_DES_TESTS
252
+ ]
253
+ ? 1
254
+ : 0;
224
255
  } catch {
225
- return false;
256
+ return 0;
226
257
  }
227
258
  }
228
- return liste.some(p => !p.hors && p.pkg.scripts?.[SCRIPT_DES_TESTS]);
259
+ return liste.filter(p => !p.hors && p.pkg.scripts?.[SCRIPT_DES_TESTS]).length;
229
260
  }
261
+ const depotAvecTests = racine => paquetsAvecTests(racine) > 0;
230
262
 
231
263
  // Whether <args> hold a filter of Turborepo (`--filter=<f>`, `--filter <f>`, `-F <f>`).
232
264
  const filtre = args => args.some(a => a.startsWith('--filter=') || a === '--filter' || a === '-F');
@@ -418,11 +450,22 @@ function jouerLaPasse({ racine, demandes, args, tout, ajouts, env, dire, coeurs,
418
450
  : tout
419
451
  ? testsCibles({ arguments: [], force: true })
420
452
  : undefined;
453
+ const borne = args.some(a => CONCURRENCE.test(a)) ? [] : [`--concurrency=${concurrence(coeurs)}`];
454
+ // The workers of each task of tests: the cores shared between those played side by side.
455
+ const travailleurs = travailleursDeLaPasse({
456
+ coeurs,
457
+ coteACote: concurrenceDemandee(args) ?? concurrence(coeurs),
458
+ paquets: paquetsAvecTests(racine),
459
+ });
421
460
  const e =
422
461
  gardesSeules || sansTests
423
462
  ? propre
424
- : { ...propre, ...ajouts, ...(cibles ? { [TESTS_CIBLES]: JSON.stringify(cibles) } : {}) };
425
- const borne = args.some(a => CONCURRENCE.test(a)) ? [] : [`--concurrency=${concurrence(coeurs)}`];
463
+ : {
464
+ ...propre,
465
+ ...ajouts,
466
+ ...(cibles ? { [TESTS_CIBLES]: JSON.stringify(cibles) } : {}),
467
+ [VARIABLE_TRAVAILLEURS]: String(travailleurs),
468
+ };
426
469
  const a = [
427
470
  ...tachesDeLaPasse(demandes, controlesDuDepot(racine)),
428
471
  '--continue=dependencies-successful',
@@ -437,11 +480,25 @@ function jouerLaPasse({ racine, demandes, args, tout, ajouts, env, dire, coeurs,
437
480
  const runs = path.join(racine, '.turbo', 'runs');
438
481
  const existait = existsSync(runs);
439
482
  const avant = new Set(lister(runs));
440
- const r = spawnSync('turbo', ['run', ...a, '--summarize'], {
441
- cwd: racine,
442
- env: e,
443
- stdio: 'inherit',
444
- });
483
+ // Under the watch of the memory, which writes in its witness why it cut the run.
484
+ const temoin = path.join(e.TMPDIR || tmpdir(), `memoire-coupee-${process.pid}`);
485
+ rmSync(temoin, { force: true });
486
+ const r = spawnSync(
487
+ process.execPath,
488
+ [GARDE_DE_LA_MEMOIRE, '--temoin', temoin, '--', 'turbo', 'run', ...a, '--summarize'],
489
+ { cwd: racine, env: e, stdio: 'inherit' }
490
+ );
491
+ if (existsSync(temoin)) {
492
+ const raison = readFileSync(temoin, 'utf8').trim();
493
+ rmSync(temoin, { force: true });
494
+ garderLesResumes(racine, avant, e);
495
+ // Said to whoever reads the results of the pass: its 75 is a cut, no wait of the machine.
496
+ if (e[RESULTATS]) {
497
+ writeFileSync(path.join(e[RESULTATS], MEMOIRE_COUPEE), `${raison}\n`);
498
+ }
499
+ dire(`⛔ ${raison}`);
500
+ return A_REPASSER;
501
+ }
445
502
  const nouveaux = lister(runs).filter(f => !avant.has(f) && f.endsWith('.json'));
446
503
  let resume = null;
447
504
  if (nouveaux.length === 1) {
@@ -173,10 +173,12 @@ export default {
173
173
  },
174
174
  };
175
175
 
176
- // The workers of a session of an agent: `maxWorkers` of Vitest is GRILLHOUSE_TRAVAILLEURS
177
- // (max(1, cores ÷ places), scripts/places-de-la-machine.mjs); without it (a heavy pass), Vitest's
178
- // own default stands: every core.
176
+ // The workers of a task: `maxWorkers` of Vitest is GRILLHOUSE_TRAVAILLEURS, which a session
177
+ // (max(1, cores ÷ places), scripts/places-de-la-machine.mjs) and a pass (the cores shared between
178
+ // its tasks of tests, ./verifier.mjs) set; without it, Vitest's own default stands: every core.
179
179
  function travailleurs() {
180
180
  const n = travailleursDeLaSeance(process.env);
181
- return n === null ? {} : { maxWorkers: n };
181
+ // Vitest's own least number of workers follows the cores of the machine, and refuses a most
182
+ // under it: the least goes with the most.
183
+ return n === null ? {} : { maxWorkers: n, minWorkers: 1 };
182
184
  }
@@ -5,6 +5,12 @@ import type { MesureDeLaMachine } from './regles-des-places.mjs';
5
5
  /** The memory available now, in bytes. */
6
6
  export function memoireDisponible(): number;
7
7
 
8
+ /** What <texte> (/proc/meminfo) says the machine still gives, in bytes. */
9
+ export function lireLaMemoire(texte: string): { disponible: number | null; echange: number };
10
+
11
+ /** What the machine still gives now: the memory available and the free swap, in bytes. */
12
+ export function memoireRestante(): { disponible: number | null; echange: number };
13
+
8
14
  /** The machine now: its cores, its load over one minute, its free memory in bytes. */
9
15
  export function mesureDeLaMachine(): MesureDeLaMachine;
10
16
 
@@ -12,19 +12,39 @@ import { departDe, leMemeVivant, vivant } from './mesure/base-de-passe.mjs';
12
12
  export { departDe };
13
13
 
14
14
  /**
15
- * The memory available now, in bytes (MemAvailable of the kernel, else the free memory of node).
16
- * @returns {number}
15
+ * What <texte> (/proc/meminfo) says the machine still gives, in bytes: the memory available
16
+ * (MemAvailable, null when it does not say it) and the free swap (SwapFree, 0 without swap).
17
+ * @param {string} texte
18
+ * @returns {{ disponible: number | null, echange: number }}
17
19
  */
18
- export function memoireDisponible() {
20
+ export function lireLaMemoire(texte) {
21
+ const kio = cle => new RegExp(`^${cle}:\\s+(\\d+) kB`, 'm').exec(texte)?.[1];
22
+ const disponible = kio('MemAvailable');
23
+ return {
24
+ disponible: disponible === undefined ? null : Number(disponible) * 1024,
25
+ echange: Number(kio('SwapFree') ?? 0) * 1024,
26
+ };
27
+ }
28
+
29
+ /**
30
+ * What the machine still gives now, as `lireLaMemoire`; nothing known where /proc/meminfo does
31
+ * not read.
32
+ * @returns {{ disponible: number | null, echange: number }}
33
+ */
34
+ export function memoireRestante() {
19
35
  try {
20
- const kio = /^MemAvailable:\s+(\d+) kB/m.exec(readFileSync('/proc/meminfo', 'utf8'))?.[1];
21
- if (kio) {
22
- return Number(kio) * 1024;
23
- }
36
+ return lireLaMemoire(readFileSync('/proc/meminfo', 'utf8'));
24
37
  } catch {
25
- // no /proc/meminfo: the free memory of node
38
+ return { disponible: null, echange: 0 };
26
39
  }
27
- return freemem();
40
+ }
41
+
42
+ /**
43
+ * The memory available now, in bytes (MemAvailable of the kernel, else the free memory of node).
44
+ * @returns {number}
45
+ */
46
+ export function memoireDisponible() {
47
+ return memoireRestante().disponible ?? freemem();
28
48
  }
29
49
 
30
50
  /**
package/scripts/nuit.sh CHANGED
@@ -291,7 +291,7 @@ process.exit(paquets(process.argv[2]).some(p => p.pkg.name === "@roomi-fields/gr
291
291
  GRILLHOUSE_ROUGES="$rouges" GRILLHOUSE_RESULTATS="$resultats" GRILLHOUSE_VERIFICATION_SORTE=Nuit monter npm --prefix "$copie" run verifier -- --force
292
292
  code=$?
293
293
  if [ "$code" -eq 75 ]; then
294
- echo "⏱ la passe complète est à repasser (code 75) : l'attente de la machine a atteint sa borne."
294
+ echo "⏱ la passe complète est à repasser (code 75) : l'attente de la machine a atteint sa borne, ou la veille de la mémoire a coupé la passe."
295
295
  return 75
296
296
  fi
297
297
  if [ "$code" -ne 0 ]; then
@@ -21,7 +21,8 @@ export function passeLourde({ args }) {
21
21
 
22
22
  /**
23
23
  * What a pass or a session out of the envelope launches: a heavy pass runs its command as it is,
24
- * every core kept (no GRILLHOUSE_TRAVAILLEURS, even inherited); any other runs under `nice` and
24
+ * without the workers it inherits (GRILLHOUSE_TRAVAILLEURS): it shares the cores between its own
25
+ * tasks of tests (scripts/langages/typescript/verifier.mjs); any other runs under `nice` and
25
26
  * `ionice`, GRILLHOUSE_TRAVAILLEURS set to max(1, cores ÷ places).
26
27
  * @param {{ lourde: boolean, cmd: string, args: string[], env: Record<string, string | undefined> }} o
27
28
  * @returns {{ cmd: string, args: string[], env: Record<string, string | undefined> }}
@@ -78,9 +78,9 @@ export function travailleursDe({
78
78
  }
79
79
 
80
80
  /**
81
- * The workers a session of an agent plays its tests on, as its environment gives them
82
- * (GRILLHOUSE_TRAVAILLEURS, set by the envelope): what the module of each language passes to its
83
- * tool. Null without the variable (a heavy pass): the tool keeps every core.
81
+ * The workers a task plays its tests on, as its environment gives them (GRILLHOUSE_TRAVAILLEURS,
82
+ * set by the envelope for a session, by the pass for a heavy pass): what the module of each
83
+ * language passes to its tool. Null without the variable: the tool keeps its own default.
84
84
  * @param {Record<string, string | undefined>} [env]
85
85
  * @returns {number | null}
86
86
  * @throws {Error} naming GRILLHOUSE_TRAVAILLEURS when its value is not a positive integer
@@ -7,6 +7,8 @@
7
7
  // repository).
8
8
  // - The core imports ./langages.mjs, never this entry: the command (bin/grillhouse.mjs) loads it
9
9
  // at each call, and a script of the core it loads before running one would not run again.
10
+ import { fileURLToPath } from 'node:url';
11
+
10
12
  export * from './langages.mjs';
11
13
 
12
14
  // The services of the core to a module of language: the plan of an envelope, the progress of a
@@ -57,12 +59,17 @@ export {
57
59
  ouvrirBase,
58
60
  retirerALInterruption,
59
61
  } from './mesure/base-de-passe.mjs';
60
- export { A_REPASSER } from './codes-de-sortie.mjs';
62
+ export { A_REPASSER, MEMOIRE_COUPEE } from './codes-de-sortie.mjs';
63
+ /** The watch of the memory of a pass (./garde-de-la-memoire.mjs), the script a pass runs under. */
64
+ export const GARDE_DE_LA_MEMOIRE = fileURLToPath(
65
+ new URL('./garde-de-la-memoire.mjs', import.meta.url)
66
+ );
61
67
  export { ecrirePression, lirePression, SEUIL_PRESSION } from './mesure/pression.mjs';
62
68
  export {
63
69
  avecLaMachineEtUnePlace,
64
70
  surUnePlace,
65
71
  travailleursDeLaSeance,
72
+ VARIABLE_TRAVAILLEURS,
66
73
  } from './places-de-la-machine.mjs';
67
74
  export { attendreDeLaPlace, AttenteDeLaMachine, nommerLAvancement } from './verrou-de-machine.mjs';
68
75
  export { CONFIG_BEADS, ecrireLePrefixe, prefixe } from './prefixe-des-tickets.mjs';
@@ -674,6 +674,7 @@ export function lireVivant({ racine, home, prefix, maintenant, ps, cache = {} })
674
674
  silence: dernier ? maintenant - dernier.mtime : null,
675
675
  entre: lu?.entre ?? null,
676
676
  jetons: lu?.jetons ?? 0,
677
+ minutes: lu?.minutes,
677
678
  travail: lu?.travail ?? 0,
678
679
  tours: lu?.tours ?? [],
679
680
  });
@@ -690,6 +691,7 @@ export function lireVivant({ racine, home, prefix, maintenant, ps, cache = {} })
690
691
  depuis: lu.premier ?? maintenant,
691
692
  entre: lu.entre,
692
693
  jetons: lu.jetons,
694
+ minutes: lu.minutes,
693
695
  travail: lu.travail,
694
696
  tours: lu.tours,
695
697
  });
@@ -714,6 +716,7 @@ export function lireVivant({ racine, home, prefix, maintenant, ps, cache = {} })
714
716
  depuis: lu.premier ?? maintenant,
715
717
  entre: lu.entre,
716
718
  jetons: lu.jetons,
719
+ minutes: lu.minutes,
717
720
  travail: lu.travail,
718
721
  tours: lu.tours,
719
722
  });
@@ -1068,13 +1071,24 @@ export function assembler({
1068
1071
  travail: l.reduce((s, x) => s + (x.travail ?? 0), 0),
1069
1072
  jetons: l.reduce((s, x) => s + (x.jetons ?? 0), 0),
1070
1073
  });
1071
- // A measure with its turns counts in the day the parts since midnight of their union; a register
1072
- // line written without them counts whole in the day it ended.
1074
+ // A measure with its turns counts in the day the parts since the day's marker of their union,
1075
+ // and, with its tokens by minute, those spent since it: a session opened days ago counts in the
1076
+ // day what it did today, time and tokens alike. A register line written without them counts
1077
+ // whole in the day it ended.
1073
1078
  const partDuJour = tours =>
1074
1079
  reunir(tours).reduce((s, [debut, fin]) => s + Math.max(0, fin - Math.max(debut, jour)), 0);
1080
+ const jetonsDuJour = minutes =>
1081
+ Object.entries(minutes).reduce(
1082
+ (s, [minute, n]) => s + (Number(minute) >= Math.floor(jour / MINUTE) ? n : 0),
1083
+ 0
1084
+ );
1075
1085
  const duJour = mesures
1076
1086
  .filter(m => m.quand >= jour)
1077
- .map(m => (m.tours ? { ...m, travail: partDuJour(m.tours) } : m));
1087
+ .map(m => ({
1088
+ ...m,
1089
+ ...(m.tours ? { travail: partDuJour(m.tours) } : {}),
1090
+ ...(m.minutes ? { jetons: jetonsDuJour(m.minutes) } : {}),
1091
+ }));
1078
1092
  // The discoveries (label `decouverte`, grillhouse-3uv.96): each counts in one case, the first that
1079
1093
  // applies. « rejetés » and « validés » count only since the day's marker <jour>; « new » and
1080
1094
  // « →check », states that await the owner, do not filter by it.
@@ -1107,7 +1121,16 @@ export function assembler({
1107
1121
  decouvertes[c]++;
1108
1122
  }
1109
1123
  }
1110
- const global = { compteurs, jour: somme(duJour), cumul: somme(mesures), decouvertes };
1124
+ // The time of the day and of the cumul is the work of the agents and of the circuits: the
1125
+ // supervisor's own session, a measure with neither ticket nor role, open for weeks and counting
1126
+ // its waits, gives its tokens to both, never its time.
1127
+ const sansLeTempsDuSuperviseur = l => l.map(m => (m.ticket || m.role ? m : { ...m, travail: 0 }));
1128
+ const global = {
1129
+ compteurs,
1130
+ jour: somme(sansLeTempsDuSuperviseur(duJour)),
1131
+ cumul: somme(sansLeTempsDuSuperviseur(mesures)),
1132
+ decouvertes,
1133
+ };
1111
1134
 
1112
1135
  // Chantiers.
1113
1136
  const sous = t => [t, ...(enfants.get(t.id) ?? []).flatMap(sous)];
@@ -1462,15 +1485,19 @@ export function assembler({
1462
1485
  };
1463
1486
  }
1464
1487
 
1488
+ // A count of tokens as a line says it: « 512 », « 40 k », « 3,1 M », « 1,2 G »; a count that would
1489
+ // round to a thousand of its unit takes the next one.
1465
1490
  export const k = n =>
1466
- n >= 1e6
1467
- ? `${(n / 1e6).toFixed(1).replace('.', ',')} M`
1468
- : n >= 1e3
1469
- ? `${Math.round(n / 1e3)} k`
1470
- : `${n}`;
1491
+ n >= 999.95e6
1492
+ ? `${(n / 1e9).toFixed(1).replace('.', ',')} G`
1493
+ : n >= 999.5e3
1494
+ ? `${(n / 1e6).toFixed(1).replace('.', ',')} M`
1495
+ : n >= 1e3
1496
+ ? `${Math.round(n / 1e3)} k`
1497
+ : `${n}`;
1471
1498
  export const duree = ms => {
1472
1499
  const min = Math.round(ms / MINUTE);
1473
- return min < 60 ? `${min} min` : `${Math.floor(min / 60)} h ${String(min % 60).padStart(2, '0')}`;
1500
+ return min < 60 ? `${min} min` : `${Math.floor(min / 60)}h${String(min % 60).padStart(2, '0')}`;
1474
1501
  };
1475
1502
 
1476
1503
  // The local day and month of the instant <t>, « 16/10 ».
@@ -2485,8 +2512,25 @@ export function ligneEtat(t, voisins = []) {
2485
2512
  return `${alerte}${ch.numero} ${ch.faits}/${ch.total} · ${dAgents} · ${k(t.global.jour.jetons)} aujourd'hui`;
2486
2513
  }
2487
2514
 
2488
- // The answer of Beads to <args> in the repository at <racine>, as JSON (`liste`), or the first line
2489
- // of its fault (`faute`), its error output first.
2515
+ /**
2516
+ * The fault of a call of Beads that threw <e>, as an alert says it: the command `bd` missing from
2517
+ * the PATH with its gesture, as the session start names it; else the first line of its error
2518
+ * output, else of its message.
2519
+ * @param {unknown} e
2520
+ * @returns {string}
2521
+ */
2522
+ export function fauteDeBeads(e) {
2523
+ if (/** @type {{ code?: string }} */ (e)?.code === 'ENOENT') {
2524
+ return 'la commande bd est absente du PATH de cette séance : `npm install -g @beads/bd`';
2525
+ }
2526
+ const message =
2527
+ String(/** @type {{ stderr?: unknown }} */ (e)?.stderr ?? '').trim() ||
2528
+ String(/** @type {{ message?: unknown }} */ (e)?.message ?? e);
2529
+ return message.split('\n')[0];
2530
+ }
2531
+
2532
+ // The answer of Beads to <args> in the repository at <racine>, as JSON (`liste`), or its fault
2533
+ // (`faute`, `fauteDeBeads`).
2490
2534
  const bdJson = (racine, ...args) => {
2491
2535
  try {
2492
2536
  return {
@@ -2501,8 +2545,7 @@ const bdJson = (racine, ...args) => {
2501
2545
  faute: null,
2502
2546
  };
2503
2547
  } catch (e) {
2504
- const message = String(e?.stderr ?? '').trim() || String(e?.message ?? e);
2505
- return { liste: [], faute: message.split('\n')[0] };
2548
+ return { liste: [], faute: fauteDeBeads(e) };
2506
2549
  }
2507
2550
  };
2508
2551