@roomi-fields/grillhouse 0.41.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.
Files changed (36) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +34 -0
  3. package/cadre/templates/projet/.github/workflows/ci.yml +13 -0
  4. package/cadre/templates/projet/.github/workflows/nuit.yml +9 -0
  5. package/cadre/templates/projet/CLAUDE.md +1 -1
  6. package/cadre/templates/turbo/paquets.json +2 -1
  7. package/cadre/templates/turbo/sans-paquets.json +2 -1
  8. package/docs/ARCHITECTURE.md +17 -5
  9. package/docs/INTERFACE.md +7 -6
  10. package/hooks/register.tsx +8 -2
  11. package/package.json +1 -1
  12. package/scripts/activites.mjs +20 -8
  13. package/scripts/circuit.mjs +96 -9
  14. package/scripts/codes-de-sortie.mjs +6 -0
  15. package/scripts/effets.mjs +9 -3
  16. package/scripts/faits-du-circuit.mjs +13 -5
  17. package/scripts/garde-de-la-memoire.mjs +231 -0
  18. package/scripts/jointure.d.ts +9 -2
  19. package/scripts/langages/cargo/commandes.mjs +6 -3
  20. package/scripts/langages/python/commandes.mjs +2 -2
  21. package/scripts/langages/python/index.mjs +4 -2
  22. package/scripts/langages/typescript/turbo-des-paquets.mjs +23 -5
  23. package/scripts/langages/typescript/verifier.mjs +75 -18
  24. package/scripts/langages/typescript/vitest-config/base.mjs +6 -4
  25. package/scripts/mesure-de-la-machine.d.mts +6 -0
  26. package/scripts/mesure-de-la-machine.mjs +29 -9
  27. package/scripts/nuit.sh +1 -1
  28. package/scripts/passe-de-la-machine.mjs +2 -1
  29. package/scripts/places-de-la-machine.mjs +3 -3
  30. package/scripts/resultats.mjs +10 -5
  31. package/scripts/seances.mjs +18 -5
  32. package/scripts/services-du-noyau.mjs +8 -1
  33. package/scripts/superviseur.mjs +14 -9
  34. package/scripts/tableau.mjs +57 -14
  35. package/scripts/ticket-du-circuit.mjs +12 -1
  36. package/skills/pitmaster/references/consigne-agent.md +1 -1
@@ -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));
@@ -14,7 +14,9 @@
14
14
  // (./commandes.mjs), and uv's cache, `~/.cache/grillhouse/uv` (UV_CACHE_DIR, ./commandes.mjs: the
15
15
  // frame's caches of compilation, never in the temporary directory); proper to the session, the
16
16
  // tree of the bytecode at the root, `__pycache__` (PYTHONPYCACHEPREFIX, ./commandes.mjs); read,
17
- // the Pythons uv installs, `~/.local/share/uv/python`. The version of Python is uv's choice, from
17
+ // uv itself where its installer lays it, `~/.local/bin/uv` (./binaires.mjs: without it a session
18
+ // of the envelope, whose home shows only what is declared, cannot play `npm test` on a package of
19
+ // Python), and the Pythons uv installs, `~/.local/share/uv/python`. The version of Python is uv's choice, from
18
20
  // `requires-python` and `.python-version`. The rules that refuse a role that writes pytest run
19
21
  // directly (`droits`).
20
22
  // - The packages, a file's, the test files, what the testwriter writes, of the manifests too, the
@@ -79,7 +81,7 @@ export default {
79
81
  sorties: {
80
82
  ecrites: ['.venv/', '.pytest_cache/', '~/.cache/grillhouse/uv/'],
81
83
  propres: [PYCACHE],
82
- lues: ['~/.local/share/uv/python/'],
84
+ lues: ['~/.local/bin/uv', '~/.local/share/uv/python/'],
83
85
  },
84
86
  // pytest run directly, by itself, by Python or by uv: `npm test` and `npm run verifier` play it.
85
87
  droits: [
@@ -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';
@@ -251,8 +254,15 @@ function cheminsDuScript(script) {
251
254
  return chemins.map(m => m.replace(/^\.\//, ''));
252
255
  }
253
256
 
254
- // The refusals of the root's format and lint scripts at <racine> that name a file a package holds:
255
- // the root keeps its own files (grillhouse-44b.9), a package plays its own.
257
+ // Whether a root script launches the packages' own scripts again: npm's workspaces (`--workspaces`,
258
+ // `-ws`, `--workspace`, `-w`) or a run of Turborepo, which already plays each package's task.
259
+ const relanceLesPaquets = script =>
260
+ /(^|\s)(--workspaces?|-ws|-w)(=|\s|$)/.test(String(script)) ||
261
+ /(^|[\s;&|])(npx\s+)?turbo\s+run(\s|$)/.test(String(script));
262
+
263
+ // The refusals of the root's format and lint scripts at <racine> that name a file a package holds,
264
+ // or launch the packages' scripts again: the root keeps its own files (grillhouse-44b.9), a package
265
+ // plays its own.
256
266
  function controlesDeRacineRefuses(racine) {
257
267
  const dossiers = paquets(racine)
258
268
  .filter(p => !p.hors)
@@ -269,6 +279,12 @@ function controlesDeRacineRefuses(racine) {
269
279
  return refus;
270
280
  }
271
281
  for (const c of CONTROLES) {
282
+ if (relanceLesPaquets(scripts?.[c] ?? '')) {
283
+ refus.push(
284
+ `⛔ package.json : le script \`${c}\` de la racine (tâche \`//#${c}\`) relance les paquets (\`${scripts[c]}\`) ; Turborepo joue déjà le script \`${c}\` de chaque paquet du cadre : retire ce script, ou réduis-le aux fichiers de la racine.`
285
+ );
286
+ continue;
287
+ }
272
288
  for (const chemin of cheminsDuScript(scripts?.[c] ?? '')) {
273
289
  const { fixe, glob } = partieFixe(chemin);
274
290
  // A glob at the root's top (`*.mjs`) names the root's files; `**` reaches the packages.
@@ -294,7 +310,7 @@ const attenteDuTypage = racine => (paquets(racine).length ? ['build', '^build']
294
310
  // The temporary directory of a process, which names the base of its pass.
295
311
  const TEMPORAIRE = 'TMPDIR';
296
312
  // The variables the root's `globalPassThroughEnv` names, and why, as the check says it.
297
- const PASSAGES = [RESULTATS, CHANGEMENTS, AVANCEMENT, TEMPORAIRE];
313
+ const PASSAGES = [RESULTATS, CHANGEMENTS, AVANCEMENT, TEMPORAIRE, TRAVAILLEURS];
298
314
  const POURQUOI = {
299
315
  [RESULTATS]: "où les gardes, Turborepo et Vitest écrivent les résultats qu'un circuit lit",
300
316
  [CHANGEMENTS]:
@@ -303,6 +319,8 @@ const POURQUOI = {
303
319
  "le dossier d'avancement d'une passe, où Vitest écrit ses fichiers faits et prévus que lit le tableau",
304
320
  [TEMPORAIRE]:
305
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",
306
324
  };
307
325
  // The variables of the tools of the project at <racine> (`grillhouse.outils` of its package.json,
308
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> }}