@roomi-fields/grillhouse 0.29.0 → 0.31.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 (263) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +769 -0
  3. package/agents/developpeur.md +0 -1
  4. package/agents/explorateur.md +0 -1
  5. package/agents/questionneur.md +0 -1
  6. package/agents/testwriter.md +0 -1
  7. package/bin/grillhouse.mjs +79 -18
  8. package/cadre/templates/projet/.github/workflows/ci.yml +2 -13
  9. package/cadre/templates/projet/CLAUDE.md +5 -1
  10. package/cadre/templates/projet/docs/agents/issue-tracker.md +1 -1
  11. package/cadre/templates/projet/package.json +2 -2
  12. package/charte.md +24 -0
  13. package/dist/temporal/acte.d.ts +24 -0
  14. package/dist/temporal/acte.js +139 -0
  15. package/dist/temporal/acte.js.map +1 -0
  16. package/dist/temporal/attributs.d.ts +6 -0
  17. package/dist/temporal/attributs.js +15 -0
  18. package/dist/temporal/attributs.js.map +1 -0
  19. package/dist/temporal/circuit/activites.d.ts +13 -0
  20. package/dist/temporal/circuit/activites.js +33 -0
  21. package/dist/temporal/circuit/activites.js.map +1 -0
  22. package/dist/temporal/circuit/client.d.ts +72 -0
  23. package/dist/temporal/circuit/client.js +247 -0
  24. package/dist/temporal/circuit/client.js.map +1 -0
  25. package/dist/temporal/circuit/commande.d.ts +2 -0
  26. package/dist/temporal/circuit/commande.js +238 -0
  27. package/dist/temporal/circuit/commande.js.map +1 -0
  28. package/dist/temporal/circuit/contrat.d.ts +305 -0
  29. package/dist/temporal/circuit/contrat.js +30 -0
  30. package/dist/temporal/circuit/contrat.js.map +1 -0
  31. package/dist/temporal/circuit/deroule.d.ts +3 -0
  32. package/dist/temporal/circuit/deroule.js +540 -0
  33. package/dist/temporal/circuit/deroule.js.map +1 -0
  34. package/dist/temporal/client.d.ts +47 -0
  35. package/dist/temporal/client.js +69 -0
  36. package/dist/temporal/client.js.map +1 -0
  37. package/dist/temporal/commande.d.ts +2 -0
  38. package/dist/temporal/commande.js +94 -0
  39. package/dist/temporal/commande.js.map +1 -0
  40. package/dist/temporal/deroules.d.ts +5 -0
  41. package/dist/temporal/deroules.js +10 -0
  42. package/dist/temporal/deroules.js.map +1 -0
  43. package/dist/temporal/etat.d.ts +33 -0
  44. package/dist/temporal/etat.js +59 -0
  45. package/dist/temporal/etat.js.map +1 -0
  46. package/dist/temporal/file/activites.d.ts +10 -0
  47. package/dist/temporal/file/activites.js +25 -0
  48. package/dist/temporal/file/activites.js.map +1 -0
  49. package/dist/temporal/file/client.d.ts +4 -0
  50. package/dist/temporal/file/client.js +6 -0
  51. package/dist/temporal/file/client.js.map +1 -0
  52. package/dist/temporal/file/contrat.d.ts +158 -0
  53. package/dist/temporal/file/contrat.js +14 -0
  54. package/dist/temporal/file/contrat.js.map +1 -0
  55. package/dist/temporal/file/deroule.d.ts +15 -0
  56. package/dist/temporal/file/deroule.js +235 -0
  57. package/dist/temporal/file/deroule.js.map +1 -0
  58. package/dist/temporal/installation.d.ts +120 -0
  59. package/dist/temporal/installation.js +386 -0
  60. package/dist/temporal/installation.js.map +1 -0
  61. package/dist/temporal/places/activites.d.ts +8 -0
  62. package/dist/temporal/places/activites.js +13 -0
  63. package/dist/temporal/places/activites.js.map +1 -0
  64. package/dist/temporal/places/client.d.ts +28 -0
  65. package/dist/temporal/places/client.js +64 -0
  66. package/dist/temporal/places/client.js.map +1 -0
  67. package/dist/temporal/places/contrat.d.ts +106 -0
  68. package/dist/temporal/places/contrat.js +21 -0
  69. package/dist/temporal/places/contrat.js.map +1 -0
  70. package/dist/temporal/places/deroule.d.ts +3 -0
  71. package/dist/temporal/places/deroule.js +198 -0
  72. package/dist/temporal/places/deroule.js.map +1 -0
  73. package/dist/temporal/sonde/activites.d.ts +6 -0
  74. package/dist/temporal/sonde/activites.js +52 -0
  75. package/dist/temporal/sonde/activites.js.map +1 -0
  76. package/dist/temporal/sonde/contrat.d.ts +35 -0
  77. package/dist/temporal/sonde/contrat.js +10 -0
  78. package/dist/temporal/sonde/contrat.js.map +1 -0
  79. package/dist/temporal/sonde/deroule.d.ts +3 -0
  80. package/dist/temporal/sonde/deroule.js +39 -0
  81. package/dist/temporal/sonde/deroule.js.map +1 -0
  82. package/dist/temporal/tickets/activites.d.ts +7 -0
  83. package/dist/temporal/tickets/activites.js +81 -0
  84. package/dist/temporal/tickets/activites.js.map +1 -0
  85. package/dist/temporal/tickets/client.d.ts +10 -0
  86. package/dist/temporal/tickets/client.js +31 -0
  87. package/dist/temporal/tickets/client.js.map +1 -0
  88. package/dist/temporal/tickets/contrat.d.ts +56 -0
  89. package/dist/temporal/tickets/contrat.js +13 -0
  90. package/dist/temporal/tickets/contrat.js.map +1 -0
  91. package/dist/temporal/tickets/deroule.d.ts +3 -0
  92. package/dist/temporal/tickets/deroule.js +94 -0
  93. package/dist/temporal/tickets/deroule.js.map +1 -0
  94. package/dist/temporal/travailleur.d.ts +2 -0
  95. package/dist/temporal/travailleur.js +69 -0
  96. package/dist/temporal/travailleur.js.map +1 -0
  97. package/docs/ARCHITECTURE.md +646 -87
  98. package/docs/CADRE.md +27 -0
  99. package/docs/INTERFACE.md +139 -42
  100. package/hooks/crochet.mjs +19 -2
  101. package/hooks/hooks.json +11 -0
  102. package/package.json +16 -4
  103. package/scripts/activites.mjs +2255 -0
  104. package/scripts/aiguillage.d.mts +37 -0
  105. package/scripts/aiguillage.mjs +40 -14
  106. package/scripts/avancement.mjs +155 -26
  107. package/scripts/bilan.mjs +137 -43
  108. package/scripts/cadre.mjs +16 -4
  109. package/scripts/circuit.mjs +993 -4075
  110. package/scripts/circuits-cles.d.mts +4 -0
  111. package/scripts/circuits-cles.mjs +21 -0
  112. package/scripts/circuits-du-serveur.mjs +105 -0
  113. package/scripts/codes-de-sortie.mjs +9 -0
  114. package/scripts/commandes-composees.mjs +45 -41
  115. package/scripts/commandes-du-path.d.mts +7 -0
  116. package/scripts/commandes-du-path.mjs +25 -0
  117. package/scripts/composants-affectes.mjs +64 -21
  118. package/scripts/composition-des-langages.mjs +18 -12
  119. package/scripts/conformite.mjs +56 -28
  120. package/scripts/copies-finies.mjs +52 -47
  121. package/scripts/depart-du-ticket.d.mts +53 -0
  122. package/scripts/depart-du-ticket.mjs +124 -0
  123. package/scripts/dependances-internes.mjs +121 -0
  124. package/scripts/dernier-vert.mjs +61 -34
  125. package/scripts/dette.mjs +32 -11
  126. package/scripts/donnees-cles.mjs +244 -0
  127. package/scripts/droits.mjs +51 -16
  128. package/scripts/effets.mjs +352 -0
  129. package/scripts/empreinte-d-etape.mjs +17 -0
  130. package/scripts/engendres.mjs +15 -5
  131. package/scripts/enveloppe/enveloppe.mjs +259 -55
  132. package/scripts/enveloppe/lancer.sh +14 -18
  133. package/scripts/enveloppe/paquets-du-plan.mjs +2 -2
  134. package/scripts/enveloppe/travail-de-la-copie.mjs +41 -13
  135. package/scripts/etapes.mjs +5 -2
  136. package/scripts/faits-du-circuit.mjs +493 -0
  137. package/scripts/file-des-tickets.d.mts +21 -0
  138. package/scripts/file-des-tickets.mjs +58 -0
  139. package/scripts/flux-des-paquets.mjs +201 -0
  140. package/scripts/gardes-du-cadre.mjs +21 -5
  141. package/scripts/init.mjs +11 -4
  142. package/scripts/integration/file.mjs +544 -434
  143. package/scripts/integration/integrer.mjs +87 -43
  144. package/scripts/integration/rejeu.mjs +45 -13
  145. package/scripts/jointure.d.ts +151 -28
  146. package/scripts/langages/cargo/commandes.mjs +383 -124
  147. package/scripts/langages/cargo/composants.mjs +154 -42
  148. package/scripts/langages/cargo/exemples.mjs +12 -21
  149. package/scripts/langages/cargo/index.mjs +22 -8
  150. package/scripts/langages/cargo/sccache.mjs +8 -14
  151. package/scripts/langages/cargo/tests-de-head.mjs +25 -9
  152. package/scripts/langages/python/commandes.mjs +218 -100
  153. package/scripts/langages/python/composants.mjs +53 -21
  154. package/scripts/langages/python/exemples.mjs +6 -16
  155. package/scripts/langages/python/index.mjs +28 -8
  156. package/scripts/langages/python/lot.mjs +1 -36
  157. package/scripts/langages/typescript/chemins-des-tests.mjs +6 -2
  158. package/scripts/langages/typescript/composants.mjs +9 -3
  159. package/scripts/langages/typescript/consommateurs-arbitres.mjs +40 -14
  160. package/scripts/langages/typescript/consommateurs.mjs +39 -14
  161. package/scripts/langages/typescript/construire.mjs +6 -163
  162. package/scripts/langages/typescript/elements-du-lot.mjs +36 -12
  163. package/scripts/langages/typescript/exemples.mjs +3 -11
  164. package/scripts/langages/typescript/frontieres.mjs +66 -22
  165. package/scripts/langages/typescript/index-interfaces.mjs +36 -13
  166. package/scripts/langages/typescript/index.mjs +50 -61
  167. package/scripts/langages/typescript/interfaces-contre-code.mjs +113 -45
  168. package/scripts/langages/typescript/lecteurs.mjs +36 -11
  169. package/scripts/langages/typescript/migrations/0.23.0-config-vitest.mjs +15 -5
  170. package/scripts/langages/typescript/migrations/0.25.0-chemins-des-tests.mjs +6 -2
  171. package/scripts/langages/typescript/migrations/0.25.0-tailles-des-tests.mjs +6 -2
  172. package/scripts/langages/typescript/migrations/0.30.0-prefixe-des-tickets.mjs +63 -0
  173. package/scripts/langages/typescript/migrations/0.30.0-tailles-des-outils-lourds.mjs +33 -0
  174. package/scripts/langages/typescript/migrations/0.30.0-titres-nommant-un-ticket.mjs +40 -0
  175. package/scripts/langages/typescript/mise-a-jour.mjs +1 -2
  176. package/scripts/langages/typescript/parcours.mjs +12 -4
  177. package/scripts/langages/typescript/regle-des-tests.mjs +9 -3
  178. package/scripts/langages/typescript/resumes.mjs +9 -3
  179. package/scripts/langages/typescript/tailles-des-tests.mjs +93 -20
  180. package/scripts/langages/typescript/tests-de-nuit.mjs +15 -10
  181. package/scripts/langages/typescript/tests.mjs +40 -15
  182. package/scripts/langages/typescript/titres-de-tests.mjs +320 -0
  183. package/scripts/langages/typescript/turbo-des-paquets.mjs +327 -81
  184. package/scripts/langages/typescript/verdict.mjs +4 -2
  185. package/scripts/langages/typescript/verifier.mjs +58 -20
  186. package/scripts/langages/typescript/vitest-config/avancement.reporter.mjs +15 -5
  187. package/scripts/langages/typescript/vitest-config/base.mjs +29 -3
  188. package/scripts/langages/typescript/vitest-config/bornes.mjs +13 -0
  189. package/scripts/langages/typescript/vitest-config/changements.mjs +21 -8
  190. package/scripts/langages/typescript/vitest-config/cibles.mjs +36 -14
  191. package/scripts/langages/typescript/vitest-config/delais.mjs +60 -0
  192. package/scripts/langages/typescript/vitest-config/delais.setup.mjs +11 -0
  193. package/scripts/langages/typescript/vitest-config/duree.classement.mjs +108 -0
  194. package/scripts/langages/typescript/vitest-config/duree.reporter.mjs +56 -59
  195. package/scripts/langages/typescript/vitest-config/lances.mjs +83 -27
  196. package/scripts/langages/typescript/vitest-config/machine.setup.mjs +10 -0
  197. package/scripts/langages/typescript/vitest-config/resultats.mjs +3 -1
  198. package/scripts/langages/typescript/vitest.nuit.config.mjs +4 -0
  199. package/scripts/lint-des-scripts.mjs +58 -0
  200. package/scripts/mesure/base-de-passe.mjs +117 -25
  201. package/scripts/mesure/pression.mjs +12 -6
  202. package/scripts/mesure-de-la-machine.d.mts +21 -0
  203. package/scripts/mesure-de-la-machine.mjs +76 -0
  204. package/scripts/migrations/0.23.0-charte-importee.mjs +6 -2
  205. package/scripts/migrations/0.23.0-crochets-de-seance.mjs +25 -8
  206. package/scripts/migrations/0.23.0-marche-du-projet.mjs +18 -6
  207. package/scripts/migrations/0.23.2-copies-du-cadre.mjs +56 -18
  208. package/scripts/migrations/0.24.12-tri-des-decouvertes.mjs +6 -2
  209. package/scripts/migrations/0.25.0-script-des-tests.mjs +15 -5
  210. package/scripts/migrations/0.30.0-ci-appelle-la-verification.mjs +124 -0
  211. package/scripts/migrations/0.31.0-paquets-dans-le-graphe.mjs +81 -0
  212. package/scripts/migrations.mjs +5 -0
  213. package/scripts/nuit.sh +25 -3
  214. package/scripts/outil.mjs +3 -1
  215. package/scripts/outils-cles.d.mts +24 -0
  216. package/scripts/outils-cles.mjs +18 -8
  217. package/scripts/paquet-npm.mjs +157 -0
  218. package/scripts/paquet.mjs +73 -4
  219. package/scripts/paquets.mjs +46 -10
  220. package/scripts/passe-de-la-machine.mjs +71 -0
  221. package/scripts/places-de-la-machine.mjs +414 -0
  222. package/scripts/places-du-serveur.mjs +170 -0
  223. package/scripts/prefixe-des-tickets.mjs +68 -0
  224. package/scripts/preparation.mjs +25 -8
  225. package/scripts/registre.mjs +9 -4
  226. package/scripts/regles-des-places.d.mts +36 -0
  227. package/scripts/regles-des-places.mjs +70 -0
  228. package/scripts/reponses-du-circuit.d.mts +6 -0
  229. package/scripts/reponses-du-circuit.mjs +28 -0
  230. package/scripts/reprise.mjs +66 -0
  231. package/scripts/resultats.mjs +112 -46
  232. package/scripts/retirer-les-copies-finies.mjs +25 -0
  233. package/scripts/sans-reponse.d.mts +4 -0
  234. package/scripts/sans-reponse.mjs +13 -0
  235. package/scripts/seances.mjs +936 -0
  236. package/scripts/services-du-noyau.mjs +27 -8
  237. package/scripts/session-start.sh +2 -2
  238. package/scripts/sortie.mjs +3 -3
  239. package/scripts/sous-commandes.mjs +41 -10
  240. package/scripts/style-a-l-ecriture.mjs +260 -0
  241. package/scripts/superviseur.mjs +122 -111
  242. package/scripts/tableau.mjs +180 -117
  243. package/scripts/taches-du-graphe.mjs +348 -0
  244. package/scripts/ticket-du-circuit.mjs +216 -0
  245. package/scripts/transitions.d.mts +148 -0
  246. package/scripts/transitions.mjs +1018 -0
  247. package/scripts/verrou-de-fichier.mjs +8 -4
  248. package/scripts/verrou-de-machine.mjs +150 -51
  249. package/scripts/verrous/commande.mjs +50 -17
  250. package/scripts/verrous/ticket-du-sous-agent.mjs +9 -3
  251. package/scripts/verrous/verrou.mjs +42 -14
  252. package/skills/explorateur/SKILL.md +9 -2
  253. package/skills/grill/SKILL.md +1 -1
  254. package/skills/mesure/SKILL.md +3 -0
  255. package/skills/pitmaster/SKILL.md +17 -18
  256. package/skills/pitmaster/references/consigne-agent.md +5 -1
  257. package/skills/release/SKILL.md +3 -3
  258. package/skills/relecteur/SKILL.md +5 -3
  259. package/skills/testwriter/SKILL.md +49 -31
  260. package/scripts/demon.mjs +0 -251
  261. package/scripts/integration/file-attente.mjs +0 -61
  262. package/scripts/langages/cargo/touches.mjs +0 -93
  263. package/scripts/langages/typescript/script-des-tests.mjs +0 -6
@@ -0,0 +1,2255 @@
1
+ // The activities of the circuit of a ticket (scripts/circuit.mjs) beside its sessions
2
+ // (scripts/seances.mjs), as Temporal runs the activities of a workflow: the proof of the red
3
+ // (`preuve`), the checks and the final pass (`controles`), the regeneration of the references
4
+ // (`regenerer`), the integration (`integrer`), the review (`relire`), the tri of the discoveries
5
+ // (`trier`) and the readings of the copy (its tree, its lot kept, its fingerprint, what it
6
+ // delivers). Each receives its inputs (the run's context <ctx>, its paths and its ports, and what
7
+ // it reads of the circuit's memory) and returns its outcome; none reads nor writes the circuit's
8
+ // memory: the circuit keeps what it returns (grillhouse-4nr.4). The regeneration starts by
9
+ // restoring the copy it kept before it; the integration of a lot already committed, its branch in
10
+ // the queue, makes no second commit. The port of <ctx> (`ctx.ports.signeDeVie`, the sign of life
11
+ // of a session) is the caller's.
12
+ import { spawnSync } from 'node:child_process';
13
+ import { createHash, randomUUID } from 'node:crypto';
14
+ import {
15
+ appendFileSync,
16
+ closeSync,
17
+ cpSync,
18
+ existsSync,
19
+ mkdirSync,
20
+ mkdtempSync,
21
+ openSync,
22
+ readdirSync,
23
+ readFileSync,
24
+ rmSync,
25
+ statSync,
26
+ symlinkSync,
27
+ writeFileSync,
28
+ } from 'node:fs';
29
+ import path from 'node:path';
30
+ import { avecLAvancementDuTravail } from './avancement.mjs';
31
+ import { A_REPASSER } from './codes-de-sortie.mjs';
32
+ import { DEPUIS_LE_VERT } from './dernier-vert.mjs';
33
+ import { empreinteDEtape } from './empreinte-d-etape.mjs';
34
+ import { FICHIER as DETTE } from './dette.mjs';
35
+ import { commandesPermises, optionsDuRole } from './droits.mjs';
36
+ import { couvertPar } from './engendres.mjs';
37
+ import { ecrireLaListe, VARIABLE as VARIABLE_ENVELOPPE } from './enveloppe/paquets-du-plan.mjs';
38
+ import { etapeDuCircuit, EXPLORATEUR, SUITE } from './etapes.mjs';
39
+ import { nomsDesGardes } from './gardes-du-cadre.mjs';
40
+ import { INTEGRE } from './integration/file.mjs';
41
+ import { AUTEUR_DU_VERDICT } from './integration/verdict.mjs';
42
+ import { langageDe } from './langages.mjs';
43
+ import { avecUneLecture } from './lecture-unique.mjs';
44
+ import { AVANCEMENT } from './mesure/avancement.mjs';
45
+ import { avecLesOutils } from './outils-cles.mjs';
46
+ import { avecLesDonnees } from './donnees-cles.mjs';
47
+ import { consigneDesFlux } from './flux-des-paquets.mjs';
48
+ import { avecLaPasse, lancementDeLaPasse, passeLourde } from './passe-de-la-machine.mjs';
49
+ import {
50
+ A_ELAGUER,
51
+ bloquantsDeLaFiche,
52
+ conformiteDuLot,
53
+ conformiteDuTri,
54
+ lireSarif,
55
+ regleDeLaLigne,
56
+ RESULTATS,
57
+ suiviDesConstats,
58
+ VERDICTS_DU_TRI,
59
+ VERDICTS_ROUVERTS,
60
+ } from './resultats.mjs';
61
+ import { consigne, idDeSeance, jusquALaFiche } from './seances.mjs';
62
+ import {
63
+ Arret,
64
+ AUTEUR_DU_CIRCUIT,
65
+ codeDejaPresent,
66
+ commenter,
67
+ composantsDe,
68
+ entete,
69
+ fichesDe,
70
+ fin,
71
+ geste,
72
+ inscrire,
73
+ lesFiches,
74
+ leTicket,
75
+ lire,
76
+ lireJson,
77
+ PREFIXE,
78
+ premiereLigne,
79
+ sansCouleurs,
80
+ } from './ticket-du-circuit.mjs';
81
+ import { emettre } from './effets.mjs';
82
+ import { PREUVE, TRI } from './transitions.mjs';
83
+ import { AttenteDeLaMachine, nommerLAvancement } from './verrou-de-machine.mjs';
84
+ import { avecLaMachineEtUnePlace } from './places-de-la-machine.mjs';
85
+
86
+ const ici = import.meta.dirname;
87
+ // The sessions out of the envelope (the reviewer, the explorateur and the questionneur, all on
88
+ // Sonnet), each in the
89
+ // ticket's copy, the main tree once the integration removed it, under the rights and the context
90
+ // of its role (scripts/droits.mjs: the commands its skill names, the refusal of a change of its
91
+ // author at the ticket), without a prompt: any call its rights do not permit is refused.
92
+ export const horsDeLEnveloppe = (ctx, role, modele) => [
93
+ '--model',
94
+ modele,
95
+ '--permission-mode',
96
+ 'dontAsk',
97
+ ...optionsDuRole(role, {
98
+ racine: ctx.racine,
99
+ copie: existsSync(ctx.copie) ? ctx.copie : ctx.racine,
100
+ ticket: ctx.ticket,
101
+ }),
102
+ ];
103
+ const INTEGRER = path.join(ici, 'integration', 'integrer.mjs');
104
+ // A generator of the frame, beside this script, as the command of a reference.
105
+ const generateur = (script, ...args) =>
106
+ [`node ${JSON.stringify(path.join(ici, script))}`, ...args].join(' ');
107
+ // The references of the circuit that no project declares (4.2), as Bazel's genrules: the files the
108
+ // module of the project's language generates (`fichiersEngendres`, scripts/jointure.d.ts), each
109
+ // judged by a guard of the frame and written again by its generator, whose
110
+ // code the circuit does not read (a real failure aside): what it writes, then the pass that
111
+ // follows, judge it; and the known debt of the guards, lowered from the notes of the final pass (`dette.mjs --abaisser`,
112
+ // `abaisser`: its command names the file of those notes). Each `{ nom, commande, fichiers, lit,
113
+ // gardes }`, `lit` the files of the copy it reads that another reference writes (as the
114
+ // prerequisites of a rule of make: the index reads the interfaces, whose generated part the API
115
+ // reports write), `gardes` the names the findings its regeneration lifts carry (their guard or
116
+ // their rule), `entiers` the files of `fichiers` its command writes in full, which the integration
117
+ // does not apply from the lot but regenerates on main of the moment
118
+ // (scripts/integration/integrer.mjs), as the module says of each of its own; not the debt, which
119
+ // reads the notes of a pass.
120
+ const referencesDuCadre = racine => [
121
+ ...langageDe(racine)
122
+ .fichiersEngendres(racine)
123
+ .map(({ verifier: _verifier, ...reference }) => reference),
124
+ {
125
+ nom: 'la dette des gardes',
126
+ commande: generateur('dette.mjs', '--abaisser', '<notes>'),
127
+ fichiers: [DETTE],
128
+ lit: [],
129
+ gardes: [],
130
+ entiers: [],
131
+ abaisser: true,
132
+ },
133
+ ];
134
+
135
+ // The line CONTEXTE of a reviewer's session: the text of `--contexte` of the run; « aucun »
136
+ // without it.
137
+ const contexteDe = ctx => ctx.contexte || 'aucun';
138
+
139
+ // The discoveries the sheets of the ticket filed, `{ id, sujet }`, in their order.
140
+ const decouvertesDuTicket = ctx =>
141
+ lesFiches(ctx)
142
+ .filter(e => e.role === AUTEUR_DU_CIRCUIT && e.decouverte)
143
+ .map(e => e.decouverte);
144
+
145
+ // The circuit's reports since the reviewer's last sheet: those of its proofs and checks (the final
146
+ // pass among them), as it wrote them at the ticket.
147
+ function rapportsDuCircuit(ctx) {
148
+ const tous = lesFiches(ctx);
149
+ const depuis = tous.findLastIndex(e => e.role === 'relecteur') + 1;
150
+ return tous
151
+ .slice(depuis)
152
+ .filter(e => e.role === AUTEUR_DU_CIRCUIT && e.rapport)
153
+ .map(e => e.rapport);
154
+ }
155
+
156
+ // The files of the lot, as the copy holds them against its HEAD: `{ tests, code }`, the
157
+ // testwriter's files (`estUnTest`: test files and the shared test material) and the others.
158
+ function fichiersDuLot(ctx) {
159
+ const tests = [];
160
+ const code = [];
161
+ for (const { fichier } of changements(ctx)) {
162
+ (duTestwriter(ctx, fichier) ? tests : code).push(fichier);
163
+ }
164
+ return { tests: tests.sort(), code: code.sort() };
165
+ }
166
+
167
+ // The blocking findings of a reviewer's sheet <fiche>, the ones that send the lot back: its
168
+ // blocking findings and each element it judges not conforming (scripts/resultats.mjs).
169
+ const bloquants = bloquantsDeLaFiche;
170
+
171
+ // The blocking findings <constats>, each under its heading, the criterion or rule it holds, its
172
+ // recipient (or the criterion in question), its body and its piece (an element judged not
173
+ // conforming carries it in its body), then the developpeur's answer to it, when he gave one: lines.
174
+ const lignesDesConstats = constats =>
175
+ constats.flatMap((c, i) => [
176
+ `### Constat ${i + 1} — ${c.titre}`,
177
+ `Bloquant : ${c.regle}`,
178
+ c.critere_en_cause ? `Critère en cause : ${c.critere_en_cause}` : `Agent : ${c.role ?? '?'}`,
179
+ c.corps,
180
+ ...(c.piece ? [`Pièce : ${c.piece}`] : []),
181
+ ...(c.reponse
182
+ ? [
183
+ `Réponse du développeur : ${c.reponse.etat}${c.reponse.raison ? ` — ${c.reponse.raison}` : ''}`,
184
+ `Pièce de la réponse : ${c.reponse.piece}`,
185
+ ]
186
+ : []),
187
+ '',
188
+ ]);
189
+
190
+ // The verdict the reviewer's sheet <fiche> carries, as the circuit writes it at the ticket for the
191
+ // human, its first word ACCEPTÉ or RENDU: after a bounded review, each finding before it lifted or
192
+ // not, with its proof; each blocking finding under its heading, what it holds, its recipient (or
193
+ // the criterion in question) and its body (an element judged not conforming among them); then the
194
+ // conformity of each element of the lot, its rule and its piece, the remarks (its findings of
195
+ // `genre` remarque), the question for the owner and the deviations to name at the commit.
196
+ export function texteDuVerdict(fiche) {
197
+ const section = (titre, l) => (l?.length ? [`## ${titre}`, '', ...l.map(x => `- ${x}`), ''] : []);
198
+ const suivi = (fiche.suivi ?? []).map(
199
+ x => `${x.titre} : ${x.etat}${x.preuve ? ` — ${x.preuve}` : ''}`
200
+ );
201
+ return [
202
+ fiche.verdict,
203
+ '',
204
+ ...section("Constats d'avant", suivi),
205
+ ...lignesDesConstats(bloquants(fiche)),
206
+ ...section(
207
+ 'Conformité',
208
+ (fiche.conformite ?? []).map(
209
+ l => `${l.element} : ${l.conforme} — ${regleDeLaLigne(l)} — ${l.piece}`
210
+ )
211
+ ),
212
+ ...section(
213
+ 'Remarques',
214
+ (fiche.constats ?? [])
215
+ .filter(c => c.genre === 'remarque')
216
+ .map(c => `${c.titre} — ${c.corps} (${c.piece})`)
217
+ ),
218
+ ...section(
219
+ 'Question au responsable',
220
+ fiche.question ? [`${fiche.question} (${fiche.piece})`] : []
221
+ ),
222
+ ...section(
223
+ 'Écarts à nommer au commit',
224
+ fiche.ecarts?.map(e => `${e.sujet} : ${e.texte}`)
225
+ ),
226
+ ]
227
+ .join('\n')
228
+ .trim();
229
+ }
230
+
231
+ // The review of the lot, the reviewer's session out of the envelope, from the second template:
232
+ // `{ verdict, fiche, texte, arbre }`, its sheet, the verdict the circuit writes at the ticket from
233
+ // it, under the reviewer's author, and the tree of the lot it read. The lot it reads is kept as a
234
+ // patch set (`leLotGarde`), on the lot the review before read set on the copy's HEAD, joined to
235
+ // its sheet's entry (`lot: { commit, arbre, base, fichiers }`); after a review sent back, the
236
+ // review reads the difference between the two and the findings before it (the bounded review), as
237
+ // Gerrit has the next review read the difference between two patch sets, each against its own
238
+ // base: the files of the lot that changed since, the command of the difference, the findings
239
+ // still open with their recipients.
240
+ export async function relire(ctx, { constats = [] } = {}) {
241
+ const { tests, code } = fichiersDuLot(ctx);
242
+ const rapports = rapportsDuCircuit(ctx);
243
+ const precedents = fichesDe(ctx, 'relecteur').length;
244
+ const { avant, depuis, lot } = leLotGarde(ctx);
245
+ let lus = { tests, code };
246
+ // The findings still open go to every review, bounded or whole.
247
+ const ouvertsALaRelecture = constats.map(c => c.titre);
248
+ let precedente = relectureEntiere(constats);
249
+ if (avant && depuis && lot) {
250
+ const dansLeLot = new Set([...tests, ...code, ...(avant.lot.fichiers ?? [])]);
251
+ const changes = differenceDesLots(ctx, depuis, lot.commit).filter(f => dansLeLot.has(f));
252
+ lus = {
253
+ tests: changes.filter(f => duTestwriter(ctx, f)),
254
+ code: changes.filter(f => !duTestwriter(ctx, f)),
255
+ };
256
+ precedente = [
257
+ `la relecture ${precedents}, ${avant.fiche.verdict} : tu relis la différence du lot depuis elle et ses constats, selon ta compétence (« La relecture bornée »).`,
258
+ '',
259
+ `- La différence : \`git diff ${depuis} ${lot.commit}\`, dans la copie du ticket ; ses fichiers : ${changes.join(', ') || 'aucun'}.`,
260
+ '- Les constats bloquants qui restent ouverts, chacun avec son destinataire :',
261
+ '',
262
+ ...lignesDesConstats(constats),
263
+ ]
264
+ .join('\n')
265
+ .trim();
266
+ }
267
+ const affirmations = path.join(ctx.tmp, 'affirmations.md');
268
+ writeFileSync(affirmations, leTicket(ctx).description);
269
+ const liste = lot
270
+ ? langageDe(ctx.copie).elementsDuLot(ctx.copie, { avant: 'HEAD', apres: lot.commit })
271
+ : { etat: 'impossible', raison: 'le lot n’a pas pu être gardé', elements: [] };
272
+ // A bounded review: the lines of the review before, and the elements the difference touches
273
+ // (every one when it cannot be computed), as a review unticks « viewed » on the files changed
274
+ // since.
275
+ const touches =
276
+ avant &&
277
+ depuis &&
278
+ lot &&
279
+ langageDe(ctx.copie).elementsDuLot(ctx.copie, { avant: depuis, apres: lot.commit });
280
+ const bornee = touches
281
+ ? {
282
+ touches: touches.etat === 'fait' ? new Set(touches.elements.map(e => e.id)) : null,
283
+ lignes: new Map((avant.fiche.conformite ?? []).map(l => [l.element, l])),
284
+ }
285
+ : null;
286
+ const valeurs = {
287
+ depot: ctx.racine,
288
+ ticket: ctx.ticket,
289
+ sujet: ctx.sujet,
290
+ paquets: ctx.paquets.join(', '),
291
+ reprise: precedents
292
+ ? `oui : ${precedents} relecture(s) d'avant ont rendu le lot, et le lot a repassé le circuit depuis`
293
+ : 'non',
294
+ lots: [
295
+ ...(avant && depuis && lot ? ["ce que le lot change depuis la relecture d'avant"] : []),
296
+ `le lot de tests : ${lus.tests.join(', ') || 'aucun fichier'}`,
297
+ `le lot de code : ${lus.code.join(', ') || 'aucun fichier'}`,
298
+ ].join(' ; '),
299
+ precedente,
300
+ affirmations,
301
+ elements: texteDesElements(liste, bornee),
302
+ flux: consigneDesFlux(ctx.racine, [...tests, ...code]),
303
+ rapports: rapports.join('\n\n') || 'aucun',
304
+ // The supervisor's context of a resumption, his answer to a question of the reviewer among them.
305
+ contexte: contexteDe(ctx),
306
+ };
307
+ const fiche = await jusquALaFiche(ctx, 'relecteur', consigne(valeurs, 1), {
308
+ signeDeVie: ctx.ports?.signeDeVie,
309
+ id: idDeSeance(ctx, 'relecture'),
310
+ evenement: 'relecture',
311
+ horsEnveloppe: true,
312
+ droits: horsDeLEnveloppe(ctx, 'relecteur', 'sonnet'),
313
+ avec: lot ? { lot: { ...lot, fichiers: [...tests, ...code] } } : {},
314
+ // Every review judges the findings still open, bounded or whole (`suiviDesConstats`).
315
+ valider: f =>
316
+ [conformiteDuLot(f, liste), suiviDesConstats(f, ouvertsALaRelecture)]
317
+ .filter(Boolean)
318
+ .join(' ; ') || null,
319
+ });
320
+ const texte = texteDuVerdict(fiche);
321
+ emettre(ctx, {
322
+ genre: 'commentaire',
323
+ ticket: ctx.ticket,
324
+ texte,
325
+ auteur: AUTEUR_DU_VERDICT,
326
+ });
327
+ return { verdict: fiche.verdict, fiche, texte, arbre: lot?.arbre ?? null };
328
+ }
329
+
330
+ // The line « LA RELECTURE D'AVANT » of a whole review (no review before, the replay of the lot in
331
+ // conflict, or a review before without its base): with the findings <constats> still open, each
332
+ // with its recipient and the developpeur's answer under it, which it judges lifted or not in
333
+ // `suivi`, as Gerrit carries the unresolved comments to each new patch set whatever the form of
334
+ // the review.
335
+ export function relectureEntiere(constats) {
336
+ if (!constats.length) {
337
+ return 'aucune : tu relis le lot entier';
338
+ }
339
+ return [
340
+ 'aucune différence à lire : tu relis le lot entier, et tu juges chaque constat bloquant qui reste ouvert, levé ou non levé, dans `suivi`, selon ta compétence (« La relecture entière ») ; chacun, avec son destinataire :',
341
+ '',
342
+ ...lignesDesConstats(constats),
343
+ ]
344
+ .join('\n')
345
+ .trim();
346
+ }
347
+
348
+ // The elements of the lot <liste> (`elementsDuLot` of the module of language) as the reviewer's instruction
349
+ // lists them: one line each, its id, its kind, its status, its export, its package and its place;
350
+ // in a bounded review (<bornee>: `{ touches, lignes }`, the ids the difference touches, null for
351
+ // every one, and the lines of the review before by element), each marked to judge again, or to
352
+ // take up with its line before; then the changed sources the language service does not read,
353
+ // whose elements he surveys himself, one line of conformity each as `<fichier>#<nom>`, and why.
354
+ function texteDesElements(liste, bornee = null) {
355
+ if (liste.etat !== 'fait') {
356
+ return `aucun : la liste n'a pas pu être calculée (${liste.raison}) ; tu relèves toi-même chaque élément du lot.`;
357
+ }
358
+ const marque = e => {
359
+ if (!bornee) {
360
+ return '';
361
+ }
362
+ const ligne = bornee.lignes.get(e.id);
363
+ if (bornee.touches && !bornee.touches.has(e.id) && ligne) {
364
+ return ` — reprise, la différence ne le touche pas : ${ligne.conforme} — ${regleDeLaLigne(ligne)} — ${ligne.piece}`;
365
+ }
366
+ return ligne ? ' — à rejuger : la différence le touche' : " — à rejuger : aucune ligne d'avant";
367
+ };
368
+ const lignes = liste.elements.map(
369
+ e =>
370
+ `- \`${e.id}\` : ${e.genre}, ${e.statut}, ${e.exporte ? 'exporté' : 'non exporté'}, paquet ${e.paquet}, ${e.fichier}:${e.ligne}${marque(e)}`
371
+ );
372
+ if (liste.horsDuService.length) {
373
+ const pourquoi = liste.service
374
+ ? `le service de langage n'a pas pu tourner : ${liste.service}`
375
+ : 'aucun tsconfig.json ne les lit';
376
+ lignes.push(
377
+ `- Hors du service de langage (${pourquoi}), tu relèves toi-même leurs éléments, une ligne de conformité chacun, son élément \`<fichier>#<nom>\` : ${liste.horsDuService.join(', ')}.`
378
+ );
379
+ }
380
+ return lignes.join('\n') || 'aucun : le lot ne change aucun élément du code.';
381
+ }
382
+
383
+ // The last review of the ticket and the lot it read: its sheet's entry (`{ fiche, lot: { commit,
384
+ // arbre, base, fichiers } }`), or null before any, without a copy, or when the lot or its base is
385
+ // not kept (the repository no longer holds one of them).
386
+ function relectureDAvant(ctx) {
387
+ const e = lesFiches(ctx).findLast(x => x.role === 'relecteur');
388
+ if (!e?.lot?.commit || !e.lot.base || !existsSync(ctx.copie)) {
389
+ return null;
390
+ }
391
+ const tient = c =>
392
+ spawnSync('git', ['-C', ctx.copie, 'cat-file', '-e', `${c}^{commit}`]).status === 0;
393
+ return tient(e.lot.commit) && tient(e.lot.base) ? e : null;
394
+ }
395
+
396
+ // The tree of the copy as it stands, the copy's HEAD and index untouched: a fresh index of the
397
+ // circuit's, read from HEAD (no stat cache, so git hashes every file's content and a file changed
398
+ // within the second of the index, the racy case, is never missed), every file of the copy added to
399
+ // it (`git add -A`, the ignored files left out), written as a tree. Its id, or null when git fails.
400
+ export function arbreDeLaCopie(ctx) {
401
+ const index = path.join(ctx.tmp, `index-${randomUUID().replaceAll('-', '')}`);
402
+ const env = { ...process.env, GIT_INDEX_FILE: index };
403
+ const git = (...a) => spawnSync('git', ['-C', ctx.copie, ...a], { encoding: 'utf8', env });
404
+ try {
405
+ if (git('read-tree', 'HEAD').status !== 0) {
406
+ return null;
407
+ }
408
+ if (git('add', '-A').status !== 0) {
409
+ return null;
410
+ }
411
+ const r = git('write-tree');
412
+ return r.status === 0 ? r.stdout.trim() : null;
413
+ } finally {
414
+ rmSync(index, { force: true });
415
+ }
416
+ }
417
+
418
+ // The copy's HEAD, the base of the lot as it stands (the tip of main of its time), or null.
419
+ function laBase(ctx) {
420
+ const r = spawnSync('git', ['-C', ctx.copie, 'rev-parse', 'HEAD'], { encoding: 'utf8' });
421
+ return r.status === 0 ? r.stdout.trim() : null;
422
+ }
423
+
424
+ // The tree <arbre> kept as a commit on <parent> in the copy, under the circuit's author, with the
425
+ // message <message>: its id, or null when git fails.
426
+ function unCommit(ctx, arbre, parent, message) {
427
+ const qui = { name: AUTEUR_DU_CIRCUIT, email: 'circuit@grillhouse.invalid' };
428
+ const r = spawnSync('git', ['-C', ctx.copie, 'commit-tree', arbre, '-p', parent, '-m', message], {
429
+ encoding: 'utf8',
430
+ env: {
431
+ ...process.env,
432
+ GIT_AUTHOR_NAME: qui.name,
433
+ GIT_AUTHOR_EMAIL: qui.email,
434
+ GIT_COMMITTER_NAME: qui.name,
435
+ GIT_COMMITTER_EMAIL: qui.email,
436
+ },
437
+ });
438
+ return r.status === 0 ? r.stdout.trim() : null;
439
+ }
440
+
441
+ // The lot of the copy kept as a commit on <parent> (a lot kept before, or HEAD), as Gerrit keeps
442
+ // each patch set of a change: `{ commit, arbre, base }`, its base the copy's HEAD, or null when git
443
+ // fails. Turborepo compares two of them (`--filter=...[<avant>...<après>]`, the merge base of the
444
+ // range being the first), and the reviewer reads their difference.
445
+ function garderLeLot(ctx, parent) {
446
+ const arbre = arbreDeLaCopie(ctx);
447
+ const base = laBase(ctx);
448
+ if (!arbre || !base) {
449
+ return null;
450
+ }
451
+ const commit = unCommit(ctx, arbre, parent ?? base, `lot de ${ctx.ticket}`);
452
+ return commit ? { commit, arbre, base } : null;
453
+ }
454
+
455
+ // The lot <lot> kept before (`{ commit, base }`) as it reads on the copy's HEAD, as Gerrit compares
456
+ // two patch sets each against its own base: the lot itself while HEAD is its base; after an
457
+ // advance of the copy, what it changed since its base replayed on HEAD (`git merge-tree
458
+ // --write-tree --merge-base=<base> HEAD <lot>`), kept as a commit on HEAD, so that its difference
459
+ // with the next lot holds what the lot changed, never the commits of main. Null when the replay
460
+ // conflicts with what main changed, or git fails: nothing bounds the next review.
461
+ function leLotSurLaBase(ctx, lot) {
462
+ const base = laBase(ctx);
463
+ if (!base) {
464
+ return null;
465
+ }
466
+ if (lot.base === base) {
467
+ return lot.commit;
468
+ }
469
+ const r = spawnSync(
470
+ 'git',
471
+ ['-C', ctx.copie, 'merge-tree', '--write-tree', `--merge-base=${lot.base}`, base, lot.commit],
472
+ { encoding: 'utf8' }
473
+ );
474
+ if (r.status !== 0) {
475
+ return null;
476
+ }
477
+ const arbre = r.stdout.split('\n')[0].trim();
478
+ return unCommit(ctx, arbre, base, `lot relu de ${ctx.ticket} sur ${base}`);
479
+ }
480
+
481
+ // The lot of the copy kept against the review before: `{ avant, depuis, lot }`, that review
482
+ // (`relectureDAvant`, null before any), the lot it read set on the copy's HEAD (`leLotSurLaBase`,
483
+ // null when nothing bounds), and the copy kept as a lot on it (on HEAD without it). The bounded
484
+ // review and its elements to judge again read the difference from `depuis` to `lot`; the final
485
+ // pass does not read it, it plays the band of the lot (`laPasseFinale`).
486
+ export function leLotGarde(ctx) {
487
+ const avant = relectureDAvant(ctx);
488
+ const depuis = avant ? leLotSurLaBase(ctx, avant.lot) : null;
489
+ return { avant, depuis, lot: garderLeLot(ctx, depuis) };
490
+ }
491
+
492
+ // The tree of the commit <commit> in the copy, or null.
493
+ function arbreDuCommit(ctx, commit) {
494
+ const r = spawnSync('git', ['-C', ctx.copie, 'rev-parse', `${commit}^{tree}`], {
495
+ encoding: 'utf8',
496
+ });
497
+ return r.status === 0 ? r.stdout.trim() : null;
498
+ }
499
+
500
+ // Whether the last review accepted the lot whose tree is <arbre>: its lot, set on the copy's HEAD
501
+ // (`leLotSurLaBase`), is that tree, as Gerrit keeps the votes of a patch set across a trivial
502
+ // rebase; an advance of the copy that leaves the lot as it was sends it to no other review.
503
+ export function leLotAccepte(ctx, arbre) {
504
+ const r = relectureDAvant(ctx);
505
+ if (r?.fiche.verdict !== 'ACCEPTÉ' || !arbre) {
506
+ return false;
507
+ }
508
+ if (r.lot.arbre === arbre) {
509
+ return true;
510
+ }
511
+ const surLaBase = leLotSurLaBase(ctx, r.lot);
512
+ return Boolean(surLaBase) && arbreDuCommit(ctx, surLaBase) === arbre;
513
+ }
514
+
515
+ // The files that differ between the lots kept <avant> and <apres>, relative to the copy, sorted.
516
+ function differenceDesLots(ctx, avant, apres) {
517
+ const r = spawnSync('git', ['-C', ctx.copie, 'diff', '--name-only', '-z', avant, apres], {
518
+ encoding: 'utf8',
519
+ maxBuffer: 64 * 1024 * 1024,
520
+ });
521
+ return r.status === 0 ? r.stdout.split('\0').filter(Boolean).sort() : [];
522
+ }
523
+
524
+ // The final pass the lot calls for: `{ arbre, restreinte }`, the tree of the copy and the band
525
+ // Turborepo plays (`{ avant, apres }`: the copy's HEAD, the base of the lot, and the copy kept as a
526
+ // commit on it), as Bazel and Nx `affected` play the reverse-dependency closure of a change: always
527
+ // the band of the lot, before any review, after one, on an accepted lot, main advanced or not,
528
+ // never the whole repository, which the night and the integration play. It throws, naming git,
529
+ // when git cannot keep the lot: a null band would be the whole repository.
530
+ export function laPasseFinale(ctx) {
531
+ const arbre = arbreDeLaCopie(ctx);
532
+ const lot = arbre ? garderLeLot(ctx, null) : null;
533
+ if (!arbre || !lot) {
534
+ throw new Error(`la passe finale ne peut borner le lot de ${ctx.ticket} : git ne le garde pas`);
535
+ }
536
+ return { arbre, restreinte: { avant: lot.base, apres: lot.commit } };
537
+ }
538
+
539
+ // The references of the circuit: those the project declares in the package.json of the copy
540
+ // (`grillhouse.references`), each `{ nom, commande, fichiers, tests, lit, gardes }` with a name, a
541
+ // command and files, `tests`, `lit` and `gardes` arrays when given, empty when not, `entiers` empty;
542
+ // then its generated files (`grillhouse.engendres`, read at the launch, `ctx.engendres`), each
543
+ // written in full (`entiers`), which the integration regenerates itself; then the frame's
544
+ // (`referencesDuCadre`, `cadre`), each but one whose first file a reference of the project covers,
545
+ // which replaces it.
546
+ export function lesReferences(ctx) {
547
+ const l = lireJson(path.join(existsSync(ctx.copie) ? ctx.copie : ctx.racine, 'package.json'))
548
+ ?.grillhouse?.references;
549
+ const duProjet = (Array.isArray(l) ? l : [])
550
+ .filter(
551
+ r =>
552
+ typeof r?.nom === 'string' &&
553
+ typeof r.commande === 'string' &&
554
+ Array.isArray(r.fichiers) &&
555
+ r.fichiers.length > 0 &&
556
+ (r.tests === undefined || Array.isArray(r.tests)) &&
557
+ (r.lit === undefined || Array.isArray(r.lit)) &&
558
+ (r.gardes === undefined || Array.isArray(r.gardes))
559
+ )
560
+ .map(r => ({
561
+ ...r,
562
+ tests: r.tests ?? [],
563
+ lit: r.lit ?? [],
564
+ gardes: r.gardes ?? [],
565
+ entiers: [],
566
+ cadre: false,
567
+ }))
568
+ .concat((ctx.engendres ?? []).map(e => ({ ...e, tests: [], cadre: false })));
569
+ const duCadre = referencesDuCadre(existsSync(ctx.copie) ? ctx.copie : ctx.racine)
570
+ .filter(c => !duProjet.some(r => couvertPar(r.fichiers, c.fichiers[0])))
571
+ .map(c => ({ ...c, tests: [], cadre: true }));
572
+ return [...duProjet, ...duCadre];
573
+ }
574
+
575
+ // The references a red of <lieux> is one of (each `{ fichier, gardes, dansLePlan }`, its file, the
576
+ // names its finding carries, and whether a path of the plan holds it), however many other reds
577
+ // stand beside it, as `--update-snapshots` updates the snapshots that fail and leaves the other
578
+ // failures: a finding of one of their `gardes`, a file of their `tests`, or a file their
579
+ // `fichiers` cover, the frame's by their `gardes` alone; with <aElaguer> (a guard wrote a key of
580
+ // the debt inscribed above what it finds), the reference that covers the debt's file too. A
581
+ // finding of a guard of a reference of the project on a file of the plan its `fichiers` do not
582
+ // cover is no output it generates, but the code of the lot: the developpeur's (BPScript 320.10,
583
+ // a word of library in the code of 030-binder).
584
+ export function referencesDesRouges(ctx, lieux, aElaguer = false) {
585
+ const sien = (r, { fichier: f, gardes, dansLePlan: plan = false }) =>
586
+ (gardes.some(g => r.gardes.includes(g)) &&
587
+ (r.cadre || !f || !plan || couvertPar(r.fichiers, f))) ||
588
+ (!r.cadre && Boolean(f) && (r.tests.includes(f) || couvertPar(r.fichiers, f)));
589
+ return lesReferences(ctx).filter(
590
+ r => lieux.some(l => sien(r, l)) || (aElaguer && couvertPar(r.fichiers, DETTE))
591
+ );
592
+ }
593
+
594
+ // The regeneration of the references named <noms> (4.2), as make remakes a target and then the
595
+ // targets that depend on its outputs: the copy kept as a lot on the one the last review read (or
596
+ // HEAD), each command run on the whole copy, in their order; a reference that reads (`lit`) a file
597
+ // another one has just written runs after it, once for each reference whose writing calls for it;
598
+ // then the copy kept again on that lot. `{ texte, regenerees, fichiers, restreinte }`: the report,
599
+ // the names of the references changed, the files changed, and the range of the final pass that
600
+ // follows (null when nothing changed: no pass plays again, and the reds stand); <suite>, the
601
+ // regeneration the checks of the plan call for: `controles`, beside other reds, the checks of the
602
+ // plan follow, on the regenerated tree; `passe`, without, the final pass that is due follows,
603
+ // on the band of the lot; null after a final pass. A file a reference writes follows from the lot, as
604
+ // the output of a genrule, without a word of the plan, and the reviewer reads its difference; a
605
+ // file changed that none of the references run declares, or a command that fails (a reference of
606
+ // the project at another code than 0, one of the frame on a real failure alone) restores the copy
607
+ // as it was and stops at « references », each deviation in its question. With <refusAuLot>, the
608
+ // pass that called for it (the checks of the plan or the final pass) carries reds of the plan: a command of the project that refuses
609
+ // (another code than 0, no real failure), its only deviation, judges the lot, as a ceiling that
610
+ // never rises refuses a lot beyond it; the copy restored, `{ refus }` gives the report of each
611
+ // refusal with the end of its output, for the developpeur (BPScript 320.10).
612
+ export function regenerer(
613
+ ctx,
614
+ { noms, notes = [], suite = null, refusAuLot = false, avant: gardee = null }
615
+ ) {
616
+ // The notes of the debt, in a file of the run, which the command that lowers it reads.
617
+ const fichierDesNotes = path.join(ctx.base.dossier, 'dette-a-abaisser.json');
618
+ const toutes = lesReferences(ctx).map(r =>
619
+ r.abaisser
620
+ ? { ...r, commande: generateur('dette.mjs', '--abaisser', JSON.stringify(fichierDesNotes)) }
621
+ : r
622
+ );
623
+ const aJouer = toutes.filter(r => noms.includes(r.nom));
624
+ if (aJouer.some(r => r.abaisser)) {
625
+ writeFileSync(fichierDesNotes, `${JSON.stringify(notes)}\n`);
626
+ }
627
+ // The copy kept before the regeneration (<gardee>, taken by its caller, or now): the regeneration
628
+ // starts by restoring the copy to it, so that an attempt played again after one cut short
629
+ // starts from the same copy.
630
+ const avant = gardee ?? leLotGarde(ctx).lot;
631
+ if (avant) {
632
+ restaurerLaCopie(ctx, avant.commit);
633
+ }
634
+ if (!avant) {
635
+ throw new Arret(
636
+ 'references',
637
+ 'Le circuit ne garde pas la copie avant la régénération des références (git échoue).'
638
+ );
639
+ }
640
+ // The command of a reference of the frame is judged by what it writes, then by the pass that
641
+ // follows, never by its code, which also judges the reds it leaves (`npm run api` refuses beside
642
+ // them): a real failure alone counts; a reference of the project, by its code.
643
+ const refs = [];
644
+ const echecs = [];
645
+ // The refusals of the commands of the project, each its line and the end of its output.
646
+ const refus = [];
647
+ const appelees = new Set();
648
+ let arbre = avant.arbre;
649
+ while (aJouer.length) {
650
+ const r = aJouer.shift();
651
+ const x = commandeDeReference(ctx, r.commande);
652
+ if (!refs.includes(r)) {
653
+ refs.push(r);
654
+ }
655
+ if (x.panne || (!r.cadre && x.code !== 0)) {
656
+ const ligne = `- ${r.nom} : \`${r.commande}\` rend le code ${x.code}${x.panne ? ' (une panne)' : ''}.`;
657
+ echecs.push(ligne);
658
+ if (!x.panne) {
659
+ refus.push([ligne, '', fin(x.sortie.trimEnd(), 30)].join('\n'));
660
+ }
661
+ }
662
+ // The references that read a file this command wrote run after it.
663
+ const suivant = arbreDeLaCopie(ctx);
664
+ const ecrits = suivant ? differenceDesLots(ctx, arbre, suivant) : [];
665
+ arbre = suivant ?? arbre;
666
+ for (const s of toutes) {
667
+ const appel = `${r.nom}\0${s.nom}`;
668
+ if (s === r || appelees.has(appel) || !ecrits.some(f => couvertPar(s.lit, f))) {
669
+ continue;
670
+ }
671
+ appelees.add(appel);
672
+ if (!aJouer.includes(s)) {
673
+ aJouer.push(s);
674
+ }
675
+ }
676
+ }
677
+ const apres = garderLeLot(ctx, avant.commit);
678
+ const fichiers = apres ? differenceDesLots(ctx, avant.commit, apres.commit) : [];
679
+ const siens = r => fichiers.filter(f => couvertPar(r.fichiers, f));
680
+ const regenerees = refs.filter(r => siens(r).length);
681
+ const horsDeclaration = fichiers.filter(f => !refs.some(r => couvertPar(r.fichiers, f)));
682
+ const ecarts = [
683
+ ...echecs,
684
+ ...(!apres ? ['- Le circuit ne garde pas la copie après la régénération (git échoue).'] : []),
685
+ ...horsDeclaration.map(f => `- ${f} change, et aucune référence régénérée ne l'écrit.`),
686
+ ];
687
+ if (ecarts.length) {
688
+ restaurer(ctx, avant.commit, fichiers);
689
+ if (refusAuLot && refus.length === ecarts.length) {
690
+ return { refus };
691
+ }
692
+ const difference =
693
+ apres && fichiers.length
694
+ ? [
695
+ `La différence, avant d'être rendue : \`git diff ${avant.commit} ${apres.commit}\`, dans la copie du ticket.`,
696
+ ]
697
+ : [];
698
+ throw new Arret(
699
+ 'references',
700
+ [
701
+ `La régénération des références, sur la copie entière, s'arrête ; la copie est rendue telle qu'avant elle. Le superviseur fait corriger la référence ou le lot qui cause l'écart (\`--depuis developpeur --contexte <texte>\`), ou \`--reprendre\` une fois la cause levée.`,
702
+ '',
703
+ ...ecarts,
704
+ '',
705
+ ...difference,
706
+ `Le journal du ticket : ${ctx.journal}`,
707
+ ].join('\n'),
708
+ {
709
+ piece: [...ecarts, ...difference].join('\n'),
710
+ question: `Les écarts de la régénération :\n${ecarts.join('\n')}`,
711
+ }
712
+ );
713
+ }
714
+ if (!fichiers.length) {
715
+ return {
716
+ texte: `La régénération (${refs.map(r => `${r.nom}, \`${r.commande}\``).join(' ; ')}) ne change aucun fichier : ${
717
+ suite === 'passe'
718
+ ? 'la passe finale juge le lot tel quel'
719
+ : suite === 'controles'
720
+ ? 'les contrôles ne rejouent pas, et leurs rouges restent, chacun à son propriétaire'
721
+ : 'aucune passe ne rejoue, et les rouges de la passe finale restent, chacun à son propriétaire'
722
+ }.`,
723
+ regenerees: [],
724
+ fichiers,
725
+ restreinte: null,
726
+ };
727
+ }
728
+ return {
729
+ texte: [
730
+ `Les références régénérées sur la copie entière : ${regenerees.map(r => r.nom).join(', ')} ; le lot porte leurs fichiers, puis ${
731
+ suite === 'controles'
732
+ ? "les contrôles du plan, sur l'arbre régénéré"
733
+ : suite === 'passe'
734
+ ? 'la passe finale'
735
+ : "la passe finale restreinte à ce qu'elles changent"
736
+ }.`,
737
+ '',
738
+ ...regenerees.map(r => `- ${r.nom} (\`${r.commande}\`) : ${siens(r).join(', ')}`),
739
+ '',
740
+ `La différence : \`git diff ${avant.commit} ${apres.commit}\`, dans la copie du ticket.`,
741
+ ].join('\n'),
742
+ regenerees: regenerees.map(r => r.nom),
743
+ fichiers,
744
+ restreinte: { avant: avant.commit, apres: apres.commit },
745
+ };
746
+ }
747
+
748
+ // The copy of <ctx> restored to the commit <commit> of a lot kept: each file that differs between
749
+ // that commit and the copy as it stands (`arbreDeLaCopie`, its files git does not track included)
750
+ // takes its version there, or goes when the commit does not hold it. A copy that is that lot changes
751
+ // nothing.
752
+ export function restaurerLaCopie(ctx, commit) {
753
+ const arbre = arbreDeLaCopie(ctx);
754
+ if (arbre) {
755
+ restaurer(ctx, commit, differenceDesLots(ctx, commit, arbre));
756
+ }
757
+ }
758
+
759
+ // The environment of a pass of the circuit (the proof, the checks, the final pass, a command of a
760
+ // reference): <base>, the launcher's under the lock of the machine, with the tools of the project
761
+ // (`ctx.outils`, `grillhouse.outils`) and its data (`ctx.donnees`, `grillhouse.donnees`), read at
762
+ // the launch, whatever <base> holds, then <env>.
763
+ export const environnementDeLaPasse = (ctx, base, env = {}) => ({
764
+ ...avecLesDonnees(ctx.donnees ?? {}, avecLesOutils(ctx.outils ?? {}, base)),
765
+ ...env,
766
+ });
767
+
768
+ // One command of a reference, run by the shell at the root of the copy, out of the envelope,
769
+ // under the lock of the machine, its output added to the log: `{ code, panne, sortie }`, its exit
770
+ // code, whether it failed for real, whatever it judges (the command not found or not executable,
771
+ // 126, 127, as the shell says it; killed by a signal, the shell's 128 + its number; or the lock of
772
+ // the machine not taken), and what it wrote to the log. It runs in the environment of a pass
773
+ // (`environnementDeLaPasse`).
774
+ function commandeDeReference(ctx, commande) {
775
+ entete(ctx, 'references');
776
+ appendFileSync(ctx.journal, `$ ${commande}\n`);
777
+ const debut = statSync(ctx.journal).size;
778
+ const sortie = () => readFileSync(ctx.journal).subarray(debut).toString('utf8');
779
+ const fd = openSync(ctx.journal, 'a');
780
+ try {
781
+ const r = avecLaMachineEtUnePlace(
782
+ env =>
783
+ spawnSync('sh', ['-c', commande], {
784
+ cwd: ctx.copie,
785
+ stdio: ['ignore', fd, fd],
786
+ env: environnementDeLaPasse(ctx, env),
787
+ }),
788
+ {
789
+ racine: ctx.copie,
790
+ dire: l => appendFileSync(ctx.journal, `${l}\n`),
791
+ ticket: ctx.ticket,
792
+ sorte: etapeDuCircuit({ etape: 'references' }).titre,
793
+ }
794
+ );
795
+ const code = r.status ?? 1;
796
+ return {
797
+ code,
798
+ panne:
799
+ r.signal !== null || r.error !== undefined || code === 126 || code === 127 || code > 128,
800
+ sortie: sortie(),
801
+ };
802
+ } catch (e) {
803
+ if (!(e instanceof AttenteDeLaMachine)) {
804
+ throw e;
805
+ }
806
+ appendFileSync(ctx.journal, `${e.message}\n`);
807
+ return { code: e.code, panne: true, sortie: sortie() };
808
+ } finally {
809
+ closeSync(fd);
810
+ }
811
+ }
812
+
813
+ // The files <fichiers> of the copy as the lot kept <commit> holds them, a file it does not hold
814
+ // removed; the copy's index untouched.
815
+ function restaurer(ctx, commit, fichiers) {
816
+ for (const f of fichiers) {
817
+ const tient = spawnSync('git', ['-C', ctx.copie, 'cat-file', '-e', `${commit}:${f}`]);
818
+ if (tient.status === 0) {
819
+ spawnSync('git', ['-C', ctx.copie, 'restore', `--source=${commit}`, '--worktree', '--', f]);
820
+ } else {
821
+ rmSync(path.join(ctx.copie, f), { force: true });
822
+ }
823
+ }
824
+ }
825
+
826
+ // Whether a proof of the counts <compte> passes: no file of the lot that does not load, no green
827
+ // the sheet names in `portent_le_travail` (`nommes`), and at least one red (of the lot, existing
828
+ // or of a build); the greens the sheet does not name and the ones HEAD holds are accepted but prove
829
+ // nothing. Under a plan « comportement inchangé » (<inchange>), nothing has to turn red and every
830
+ // green passes: a proof passes with no file of the lot that does not load, its reds going to the
831
+ // developpeur.
832
+ // The files of the lot that only the night plays (<misDeCote>, `separerLesFichiersDuJour`) are no
833
+ // part of the proof: the red proves the behaviour the ticket develops, and a bench or a night test
834
+ // is neither required red nor a cause of refusal. A lot whose only test files are those passes.
835
+ // With the code of the behaviour already in the copy (<codePresent>, `codeDejaPresent`), no test
836
+ // can turn red: the proof abstains the same way, a lot that holds a red keeps its verdict.
837
+ export function preuveReussie(
838
+ { fichiers, rouges, casses, nommes, misDeCote = 0 },
839
+ { inchange, codePresent = false }
840
+ ) {
841
+ if (casses > 0) {
842
+ return false;
843
+ }
844
+ if (inchange || codePresent) {
845
+ return true;
846
+ }
847
+ if (nommes > 0) {
848
+ return false;
849
+ }
850
+ if (fichiers === 0 && rouges === 0 && misDeCote > 0) {
851
+ return true;
852
+ }
853
+ return rouges > 0;
854
+ }
855
+
856
+ // The files <fichiers> of the lot, in the copy, split into the ones the day plays (`jour`) and the
857
+ // ones only the night plays (`misDeCote`: a night test, a bench, a time witness), by each module's
858
+ // own definition (`horsDuJour` of the join); the order of the lot kept.
859
+ export function separerLesFichiersDuJour(ctx, fichiers) {
860
+ const langage = langageDe(ctx.copie);
861
+ const jour = [];
862
+ const misDeCote = [];
863
+ for (const f of fichiers) {
864
+ (langage.horsDuJour(f, ctx.copie) ? misDeCote : jour).push(f);
865
+ }
866
+ return { jour, misDeCote };
867
+ }
868
+
869
+ // The lines of the section of the report of the proof that names the files <fichiers> put aside;
870
+ // none for none.
871
+ export const sectionMisDeCote = fichiers =>
872
+ fichiers.length
873
+ ? [
874
+ `Mis de côté (joués par la nuit seule) (${fichiers.length}) :`,
875
+ ...fichiers.map(f => `- ${f}`),
876
+ '',
877
+ ]
878
+ : [];
879
+
880
+ // The integration of the lot: its two patches, its message and the references that write files in
881
+ // full (`--references`, from `lesReferences`, the one list), written from the copy, then
882
+ // scripts/integration/integrer.mjs from the main tree, its output added to the log. A run « à
883
+ // repasser » (75) plays once more, the gesture `rejeu`. `{ code, sortie, args }`.
884
+ export function integrer(ctx) {
885
+ // A lot already committed: its ticket is labelled `en-file` (scripts/integration/integrer.mjs)
886
+ // until the queue takes it off, as a job of a CI keyed by its commit is not run twice. The
887
+ // integration plays again without a second commit.
888
+ const branche = `agent/${ctx.ticket}`;
889
+ const show = ctx.bd('show', ctx.ticket, '--json');
890
+ const etiquettes = show.status === 0 ? (JSON.parse(show.stdout)[0]?.labels ?? []) : [];
891
+ if (etiquettes.includes('en-file')) {
892
+ const sortie = `la branche ${branche} est déjà en file : le lot est déjà commité, aucun second commit.\n`;
893
+ appendFileSync(ctx.journal, sortie);
894
+ return { code: 0, sortie, args: [], commande: `node ${INTEGRER}`, deja: true };
895
+ }
896
+ const { tests, code } = fichiersDuLot(ctx);
897
+ const dansCopie = (...a) =>
898
+ spawnSync('git', ['-C', ctx.copie, ...a], { encoding: 'utf8', maxBuffer: 256 * 1024 * 1024 });
899
+ // Each file against HEAD, a new one against nothing: the index of the copy is not written.
900
+ const patch = fichiers =>
901
+ fichiers
902
+ .map(f =>
903
+ dansCopie('cat-file', '-e', `HEAD:${f}`).status === 0
904
+ ? dansCopie('diff', '--binary', 'HEAD', '--', f).stdout
905
+ : dansCopie('diff', '--no-index', '--binary', '/dev/null', f).stdout
906
+ )
907
+ .join('');
908
+ const args = ['--ticket', ctx.ticket];
909
+ for (const [option, fichiers] of [
910
+ ['--tests', tests],
911
+ ['--code', code],
912
+ ]) {
913
+ if (!fichiers.length) {
914
+ continue;
915
+ }
916
+ const f = path.join(ctx.tmp, `${option.slice(2)}.patch`);
917
+ writeFileSync(f, patch(fichiers));
918
+ args.push(option, f);
919
+ }
920
+ const message = path.join(ctx.tmp, 'message');
921
+ writeFileSync(message, messageDeCommit(ctx));
922
+ args.push('--message', message);
923
+ // The project's generated files, the integration reads from the main tree itself.
924
+ const entieres = lesReferences(ctx)
925
+ .filter(r => r.cadre && r.entiers.length)
926
+ .map(({ nom, commande, fichiers, lit, entiers, cadre }) => ({
927
+ nom,
928
+ commande,
929
+ fichiers,
930
+ lit,
931
+ entiers,
932
+ cadre,
933
+ }));
934
+ if (entieres.length) {
935
+ const f = path.join(ctx.tmp, 'references.json');
936
+ writeFileSync(f, `${JSON.stringify(entieres)}\n`);
937
+ args.push('--references', f);
938
+ }
939
+ let r;
940
+ for (let essai = 1; essai <= 2; essai++) {
941
+ entete(ctx, 'integration');
942
+ appendFileSync(ctx.journal, `$ node ${INTEGRER} ${args.join(' ')}\n`);
943
+ const x = avecLAvancementDuTravail(
944
+ ctx.tmp,
945
+ { racine: ctx.copie, genre: 'integration' },
946
+ avancement =>
947
+ spawnSync(process.execPath, [INTEGRER, ...args], {
948
+ cwd: ctx.racine,
949
+ encoding: 'utf8',
950
+ maxBuffer: 256 * 1024 * 1024,
951
+ env: { ...process.env, [AVANCEMENT]: avancement },
952
+ })
953
+ );
954
+ r = {
955
+ code: x.status ?? 1,
956
+ sortie: `${x.stdout ?? ''}${x.stderr ?? ''}`,
957
+ args,
958
+ commande: `node ${INTEGRER} ${args.join(' ')}`,
959
+ };
960
+ appendFileSync(ctx.journal, r.sortie);
961
+ if (r.code !== A_REPASSER) {
962
+ break;
963
+ }
964
+ if (essai === 1) {
965
+ geste(ctx, 'rejeu');
966
+ }
967
+ }
968
+ return r;
969
+ }
970
+
971
+ // The tri of the discoveries of the ticket (step 5.3 of scripts/etapes.mjs), once the queue has
972
+ // brought its lot onto main, as Chromium and Mozilla give each new report a verdict before it is
973
+ // filed. Without a discovery, no session. Else one session of the explorateur out of the
974
+ // envelope, on Sonnet, in the main tree, under the rights of its role (reading, the build of a
975
+ // package, no pass), its instruction from the eighth template (the ticket, its commit on main, the
976
+ // one the queue names in the reason it closes the ticket with, `commitIntegre`, its discoveries,
977
+ // one per line, the commands its rights permit, `commandesPermises`), its sheet the tri's (`tri` of scripts/resultats.mjs): one line per discovery
978
+ // (`conformiteDuTri`), asked again once of the same session. Each verdict is written at the ticket
979
+ // of its discovery (`Circuit · tri : <verdict> — <texte> (<piece>)`), its label set there; an
980
+ // a-porter or a non-confirmee reopens under `a-valider`, the pane's list « à valider »; the others
981
+ // stay closed. The line of the tri at the ticket names each writing that failed (the verdict, the
982
+ // label, the reopening), with its error, and counts as reopened only what reopened. A tri that ends
983
+ // without a sheet that conforms leaves the discoveries as
984
+ // they are and says so at the ticket. Either way, its end is kept with the circuit's results
985
+ // (`tri`: the discoveries read, whether its sheet conformed, its verdicts by kind), which the bilan
986
+ // reads, and the working directory the queue removed at the closure, recreated for the session, is
987
+ // removed again.
988
+ export async function trier(ctx) {
989
+ const decouvertes = decouvertesDuTicket(ctx);
990
+ if (!decouvertes.length) {
991
+ return;
992
+ }
993
+ const ids = decouvertes.map(d => d.id);
994
+ const n = `${decouvertes.length} découverte${decouvertes.length > 1 ? 's' : ''}`;
995
+ // The commit the queue brought onto main for this ticket, not main's last, another ticket's
996
+ // once several circuits run.
997
+ const show = ctx.bd('show', ctx.ticket, '--json');
998
+ const fermeture = show.status === 0 ? (JSON.parse(show.stdout)[0]?.close_reason ?? null) : null;
999
+ const integre = commitIntegre(fermeture);
1000
+ const commit = integre
1001
+ ? spawnSync('git', ['-C', ctx.racine, 'log', '-1', '--format=%h %s', integre], {
1002
+ encoding: 'utf8',
1003
+ }).stdout.trim()
1004
+ : '';
1005
+ mkdirSync(ctx.tmp, { recursive: true });
1006
+ let fiche = null;
1007
+ let faute = null;
1008
+ try {
1009
+ fiche = await jusquALaFiche(
1010
+ ctx,
1011
+ EXPLORATEUR,
1012
+ consigne(
1013
+ {
1014
+ depot: ctx.racine,
1015
+ ticket: ctx.ticket,
1016
+ sujet: ctx.sujet,
1017
+ commit: commit || 'inconnu',
1018
+ decouvertes: decouvertes.map(d => `- ${d.id} — ${d.sujet}`).join('\n'),
1019
+ commandes: commandesPermises(EXPLORATEUR),
1020
+ },
1021
+ 7
1022
+ ),
1023
+ {
1024
+ signeDeVie: ctx.ports?.signeDeVie,
1025
+ horsEnveloppe: true,
1026
+ droits: horsDeLEnveloppe(ctx, EXPLORATEUR, 'sonnet'),
1027
+ id: idDeSeance(ctx, 'tri'),
1028
+ evenement: 'tri',
1029
+ fiche: 'tri',
1030
+ objet: 'tri',
1031
+ valider: f => conformiteDuTri(f, ids),
1032
+ }
1033
+ );
1034
+ } catch (x) {
1035
+ if (!(x instanceof Arret)) {
1036
+ throw x;
1037
+ }
1038
+ faute = premiereLigne(x.rapport);
1039
+ } finally {
1040
+ rmSync(ctx.tmp, { recursive: true, force: true });
1041
+ }
1042
+ if (!fiche) {
1043
+ inscrire(ctx, {
1044
+ role: AUTEUR_DU_CIRCUIT,
1045
+ etape: TRI,
1046
+ tri: { decouvertes: ids.length, conforme: false, verdicts: {} },
1047
+ });
1048
+ commenter(
1049
+ ctx,
1050
+ TRI,
1051
+ `le tri ne rend pas de fiche conforme (${faute}) : les ${n} restent telles quelles ; l'intégration tient.`
1052
+ );
1053
+ return;
1054
+ }
1055
+ // Each writing at a discovery's ticket: its verdict, its labels, its reopening. The line of the
1056
+ // tri, written after them, reads each one at the discovery when it is written
1057
+ // (`resume-du-tri`) and names one absent.
1058
+ const ecritures = [];
1059
+ for (const l of fiche.verdicts) {
1060
+ const rouvre = VERDICTS_ROUVERTS.includes(l.verdict);
1061
+ const verdict = `${PREFIXE}${TRI} : ${l.verdict} — ${l.texte.trim()}${l.piece ? ` (${l.piece.trim()})` : ''}${rouvre ? ' ; rouverte sous a-valider, pour le responsable.' : ''}`;
1062
+ const etiquettes = [l.verdict, ...(rouvre ? ['a-valider'] : [])];
1063
+ emettre(ctx, {
1064
+ genre: 'commentaire',
1065
+ ticket: l.decouverte,
1066
+ texte: verdict,
1067
+ auteur: AUTEUR_DU_CIRCUIT,
1068
+ });
1069
+ emettre(ctx, { genre: 'etiquettes', ticket: l.decouverte, etiquettes });
1070
+ if (rouvre) {
1071
+ emettre(ctx, { genre: 'reouverture', ticket: l.decouverte });
1072
+ }
1073
+ ecritures.push({ decouverte: l.decouverte, verdict, etiquettes, rouvre });
1074
+ }
1075
+ const verdicts = Object.fromEntries(
1076
+ VERDICTS_DU_TRI.map(v => [v, fiche.verdicts.filter(l => l.verdict === v).length]).filter(
1077
+ ([, k]) => k
1078
+ )
1079
+ );
1080
+ inscrire(ctx, {
1081
+ role: AUTEUR_DU_CIRCUIT,
1082
+ etape: TRI,
1083
+ tri: { decouvertes: ids.length, conforme: true, verdicts },
1084
+ });
1085
+ emettre(ctx, {
1086
+ genre: 'resume-du-tri',
1087
+ ticket: ctx.ticket,
1088
+ debut: `${PREFIXE}${TRI} : ${n} triée${decouvertes.length > 1 ? 's' : ''} — ${Object.entries(
1089
+ verdicts
1090
+ )
1091
+ .map(([v, k]) => `${k} ${v}`)
1092
+ .join(', ')}`,
1093
+ ecritures,
1094
+ });
1095
+ }
1096
+
1097
+ // The commit the queue names in the reason of a ticket it closes (`intégré : <commit>`,
1098
+ // scripts/integration/file.mjs), or null for another reason.
1099
+ export function commitIntegre(raison) {
1100
+ const r = String(raison ?? '');
1101
+ return r.startsWith(INTEGRE) ? r.slice(INTEGRE.length).trim().split(' ')[0] || null : null;
1102
+ }
1103
+
1104
+ // The type of a conventional commit for the ticket's type in Beads; `feat` for any other.
1105
+ const TYPES_DE_COMMIT = { bug: 'fix', chore: 'chore', docs: 'docs' };
1106
+
1107
+ // The commit message of the lot: `<type>(<paquets>): <sujet> (<ticket>)`, the packages of the
1108
+ // plan by their name; then the message the sheets of the developpeur and of the reviewer give, in
1109
+ // their order, written once from the final state (`messageDuLot`).
1110
+ function messageDeCommit(ctx) {
1111
+ const liste = composantsDe(existsSync(ctx.copie) ? ctx.copie : ctx.racine);
1112
+ const noms = ctx.paquets.flatMap(c => {
1113
+ const nom = liste.find(p => p.dossier === c)?.pkg.name;
1114
+ return nom ? [nom] : c === '.' ? [] : [path.basename(c)];
1115
+ });
1116
+ const type = TYPES_DE_COMMIT[ctx.type] ?? 'feat';
1117
+ const portee = noms.length ? `(${noms.join(',')})` : '';
1118
+ return messageDuLot({
1119
+ entete: `${type}${portee}: ${ctx.sujet} (${ctx.ticket})`,
1120
+ description: leTicket(ctx).description,
1121
+ fiches: lesFiches(ctx)
1122
+ .filter(e => e.role === 'developpeur' || e.role === 'relecteur')
1123
+ .map(e => e.fiche),
1124
+ });
1125
+ }
1126
+
1127
+ // The commit message of a lot, written once from its final state, as a change merged on Gerrit
1128
+ // carries the one description of its last patch set: <entete>, the title of the ticket; the
1129
+ // section of the criteria of the plan <description> (its heading begins with « Critères »), what
1130
+ // the lot changes; a paragraph per deviation the sheets <fiches> carry (`ecarts`), each subject
1131
+ // once, in the order it first appears, with the value of the last sheet that carries it (a
1132
+ // subject known again whatever its case and spacing); then the trailer.
1133
+ export function messageDuLot({ entete, description, fiches }) {
1134
+ const criteres = [];
1135
+ let dedans = false;
1136
+ for (const ligne of String(description ?? '').split('\n')) {
1137
+ const m = /^##\s+(.*)$/.exec(ligne);
1138
+ if (m) {
1139
+ dedans = /^Critères\b/.test(m[1].trim());
1140
+ } else if (dedans) {
1141
+ criteres.push(ligne);
1142
+ }
1143
+ }
1144
+ const cle = sujet => sujet.toLocaleLowerCase('fr').replace(/\s+/g, ' ').trim();
1145
+ const ecarts = new Map();
1146
+ for (const e of fiches.flatMap(f => f.ecarts ?? [])) {
1147
+ const sujet = ecarts.get(cle(e.sujet))?.sujet ?? e.sujet.trim();
1148
+ ecarts.set(cle(e.sujet), { sujet, texte: e.texte.trim() });
1149
+ }
1150
+ return [
1151
+ entete,
1152
+ criteres.join('\n').trim(),
1153
+ ...[...ecarts.values()].map(e => `${e.sujet} : ${e.texte}`),
1154
+ 'Co-Authored-By: Claude <noreply@anthropic.com>',
1155
+ ]
1156
+ .filter(Boolean)
1157
+ .join('\n\n')
1158
+ .concat('\n');
1159
+ }
1160
+
1161
+ // The files the copy changes against its HEAD: [{ fichier, supprime }], relative to the copy.
1162
+ function changements(ctx) {
1163
+ const r = spawnSync(
1164
+ 'git',
1165
+ ['-C', ctx.copie, 'status', '--porcelain', '-z', '--untracked-files=all'],
1166
+ { encoding: 'utf8' }
1167
+ );
1168
+ if (r.status !== 0) {
1169
+ return [];
1170
+ }
1171
+ const entrees = r.stdout.split('\0');
1172
+ const out = [];
1173
+ for (let i = 0; i < entrees.length; i++) {
1174
+ const e = entrees[i];
1175
+ if (e.length < 4) {
1176
+ continue;
1177
+ }
1178
+ const xy = e.slice(0, 2);
1179
+ out.push({ fichier: e.slice(3), supprime: xy.includes('D') });
1180
+ // A rename or a copy names its source next.
1181
+ if (xy.includes('R') || xy.includes('C')) {
1182
+ i++;
1183
+ }
1184
+ }
1185
+ return out;
1186
+ }
1187
+
1188
+ // Whether the testwriter writes <fichier> of the copy: the rule of a test file of the module of its
1189
+ // language (`estUnTest`, scripts/jointure.d.ts).
1190
+ const duTestwriter = (ctx, fichier) => langageDe(ctx.copie).estUnTest(fichier, ctx.copie) !== null;
1191
+
1192
+ // The test files of the lot that the testwriter writes, present in the copy: in the packages of
1193
+ // the plan and in the shared test material.
1194
+ export function testsDuLot(ctx) {
1195
+ return changements(ctx)
1196
+ .filter(c => !c.supprime)
1197
+ .map(c => c.fichier)
1198
+ .filter(f => langageDe(ctx.copie).estUnTest(f, ctx.copie)?.joue)
1199
+ .sort();
1200
+ }
1201
+
1202
+ // The package directory of the copy that holds <fichier>, or « . ».
1203
+ function paquetDe(liste, fichier) {
1204
+ const p = liste.find(({ dossier }) => `${fichier}`.startsWith(`${dossier}${path.sep}`));
1205
+ return p ? p.dossier : '.';
1206
+ }
1207
+
1208
+ // One npm command in the copy, under <env> added to the circuit's environment, its results written
1209
+ // to a directory of its own (RESULTATS, scripts/resultats.mjs: the summaries of Turborepo, the
1210
+ // JSON reports of Vitest, the SARIF of the guards), its output added to the log for the human:
1211
+ // `{ code, dossier }`. The circuit reads its results, never its output. A heavy pass (the final
1212
+ // pass, `npm run verifier`) holds the lock of the machine (scripts/verrou-de-machine.mjs) and
1213
+ // passes it to the `npm run verifier` it runs, on a place of the machine taken first
1214
+ // (`avecLaMachineEtUnePlace` of scripts/places-de-la-machine.mjs); a targeted one (the proof of the
1215
+ // red, the checks on the tests of the ticket) takes a place like a session of an agent
1216
+ // (scripts/passe-de-la-machine.mjs); its wait is written to the log. A wait that stops (its bound,
1217
+ // 75; a lock held by an ancestor or a server of the places that does not answer, 1) is the
1218
+ // command's code, its message in the log. Once it holds the lock, the pass plays under a
1219
+ // progress directory of its own (`avancement`), of the kind `genreDeLaPasse` names. It plays in
1220
+ // the environment of a pass (`environnementDeLaPasse`).
1221
+ function npm(ctx, etape, args, env = {}, cwd = ctx.copie) {
1222
+ entete(ctx, etape);
1223
+ const dossier = mkdtempSync(path.join(ctx.base.dossier, 'resultats-'));
1224
+ const prefixe = Object.entries(env).map(([k, v]) => `${k}=${v} `);
1225
+ appendFileSync(ctx.journal, `$ ${prefixe.join('')}npm ${args.join(' ')}\n`);
1226
+ const fd = openSync(ctx.journal, 'a');
1227
+ try {
1228
+ const finale = etape === 'controles' && args[1] === 'verifier';
1229
+ const lourde = passeLourde({ etape, args });
1230
+ const r = avecLaPasse(
1231
+ envMachine =>
1232
+ avecLAvancementDuTravail(
1233
+ ctx.tmp,
1234
+ { racine: ctx.copie, genre: genreDeLaPasse(ctx, etape, args) },
1235
+ avancement => {
1236
+ const oublier = nommerLAvancement({ env: envMachine, dossier: avancement });
1237
+ try {
1238
+ // A targeted pass plays on its share of the cores under nice and ionice; a heavy one
1239
+ // keeps every core.
1240
+ const lancement = lancementDeLaPasse({
1241
+ lourde,
1242
+ cmd: 'npm',
1243
+ args,
1244
+ env: environnementDeLaPasse(ctx, envMachine, {
1245
+ ...env,
1246
+ [RESULTATS]: dossier,
1247
+ [AVANCEMENT]: avancement,
1248
+ ...(args[0] === 'test' ? { [DEPUIS_LE_VERT]: '1' } : {}),
1249
+ }),
1250
+ });
1251
+ return spawnSync(lancement.cmd, lancement.args, {
1252
+ cwd,
1253
+ stdio: ['ignore', fd, fd],
1254
+ env: lancement.env,
1255
+ });
1256
+ } finally {
1257
+ oublier();
1258
+ }
1259
+ }
1260
+ ),
1261
+ {
1262
+ lourde,
1263
+ env: process.env,
1264
+ racine: ctx.copie,
1265
+ dire: l => appendFileSync(ctx.journal, `${l}\n`),
1266
+ ticket: ctx.ticket,
1267
+ rang: ctx.rang ?? undefined,
1268
+ sorte: etapeDuCircuit({ etape, finale })?.titre ?? etape,
1269
+ }
1270
+ );
1271
+ return { code: r.status ?? 1, dossier };
1272
+ } catch (e) {
1273
+ if (!(e instanceof AttenteDeLaMachine)) {
1274
+ throw e;
1275
+ }
1276
+ appendFileSync(ctx.journal, `${e.message}\n`);
1277
+ return { code: e.code, dossier };
1278
+ } finally {
1279
+ closeSync(fd);
1280
+ }
1281
+ }
1282
+
1283
+ // The kind of an automatic pass, by which its total is kept from one pass to the next
1284
+ // (scripts/avancement.mjs): its step (the checks once final, the final pass) and its command
1285
+ // without the test files and the filters, which move from one lot to the next.
1286
+ function genreDeLaPasse(ctx, etape, args) {
1287
+ const commande = args.filter(
1288
+ a => !langageDe(ctx.copie).estUnTest(a, ctx.copie)?.joue && !a.startsWith('--filter=')
1289
+ );
1290
+ return etape === 'controles' && args[1] === 'verifier'
1291
+ ? ['passe finale', ...commande].join(' ')
1292
+ : [etape, ...commande].join(' ');
1293
+ }
1294
+
1295
+ // Removes from the copy each sibling of HEAD's version a killed process left there, between its
1296
+ // writing and its removal (`avecLesVersionsDAvant`): a file git does not track, the sibling, by
1297
+ // the name the module of its language gives (`soeurDAvant` of the join, a file beside its own:
1298
+ // TypeScript's alone, Rust and Python play HEAD's version in a tree), of a file of its folder that
1299
+ // git tracks and that exists, each named in the ticket's log. A file git tracks, or whose file is
1300
+ // absent, is left. What the module reads at a cost is read once for the sweep (`avecUneLecture`,
1301
+ // ./lecture-unique.mjs), whatever the number of files. Returns the siblings removed, from the
1302
+ // copy, sorted.
1303
+ export function balayerLesSoeurs(ctx) {
1304
+ return avecUneLecture(() => balayer(ctx));
1305
+ }
1306
+
1307
+ // The sibling of HEAD's version of <f> by the module of its language, null for a module that
1308
+ // names none (Rust, Python).
1309
+ function soeurDe(langage, f, racine) {
1310
+ return typeof langage.soeurDAvant === 'function' ? langage.soeurDAvant(f, racine) : null;
1311
+ }
1312
+
1313
+ // Whether HEAD's version of <f> plays in a tree of its own, by the module of its language.
1314
+ function arbreDe(langage, f, racine) {
1315
+ return typeof langage.arbreDAvant === 'function' && langage.arbreDAvant(f, racine) === true;
1316
+ }
1317
+
1318
+ // The sweep of `balayerLesSoeurs`, in its scope of readings done once.
1319
+ function balayer(ctx) {
1320
+ const git = (...a) =>
1321
+ spawnSync('git', ['-C', ctx.copie, ...a], { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
1322
+ const r = git('ls-files', '-z', '--others', '--exclude-standard');
1323
+ if (r.status !== 0) {
1324
+ return [];
1325
+ }
1326
+ const parDossier = new Map();
1327
+ for (const f of r.stdout.split('\0').filter(Boolean)) {
1328
+ const d = path.posix.dirname(f);
1329
+ parDossier.set(d, [...(parDossier.get(d) ?? []), f]);
1330
+ }
1331
+ const langage = langageDe(ctx.copie);
1332
+ const retirees = [];
1333
+ for (const [dossier, nonSuivis] of parDossier) {
1334
+ const suivis = git('ls-files', '-z', ...(dossier === '.' ? [] : ['--', `${dossier}/`]));
1335
+ const soeurs = new Set(
1336
+ suivis.stdout
1337
+ .split('\0')
1338
+ .filter(f => f && path.posix.dirname(f) === dossier)
1339
+ .filter(f => existsSync(path.join(ctx.copie, f)))
1340
+ .map(f => soeurDe(langage, f, ctx.copie))
1341
+ .filter(n => n !== null)
1342
+ );
1343
+ for (const f of nonSuivis.filter(n => soeurs.has(n))) {
1344
+ rmSync(path.join(ctx.copie, f), { force: true });
1345
+ retirees.push(f);
1346
+ if (ctx.journal) {
1347
+ appendFileSync(ctx.journal, `sœur de la version de HEAD laissée, retirée : ${f}\n`);
1348
+ }
1349
+ }
1350
+ }
1351
+ return retirees.sort();
1352
+ }
1353
+
1354
+ // What a tree of HEAD's version leaves out of the copy: the history, the builds, the installed
1355
+ // dependencies, none of which a test reads as its own file.
1356
+ const HORS_DE_L_ARBRE = new Set(['.git', 'target', 'node_modules', '.venv']);
1357
+
1358
+ // Removes from the temporary directory of the ticket each tree of HEAD's version (`avant-<pid>-*`)
1359
+ // whose owner, the process that built it, no longer lives: a circuit killed between the building
1360
+ // and the removal (`avecLesVersionsDAvant`) leaves one, no `finally` having played. A tree of a
1361
+ // live process is left.
1362
+ function balayerLesArbres(ctx) {
1363
+ if (!existsSync(ctx.tmp)) {
1364
+ return;
1365
+ }
1366
+ for (const nom of readdirSync(ctx.tmp)) {
1367
+ // The name is written by `batirLArbre`: `avant-`, the pid, `-`, the suffix of mkdtemp.
1368
+ const [prefixe, pid] = nom.split('-');
1369
+ if (prefixe !== 'avant' || !Number.isInteger(Number(pid)) || Number(pid) <= 0) {
1370
+ continue;
1371
+ }
1372
+ try {
1373
+ process.kill(Number(pid), 0);
1374
+ continue;
1375
+ } catch (e) {
1376
+ if (e.code === 'EPERM') {
1377
+ continue;
1378
+ }
1379
+ }
1380
+ rmSync(path.join(ctx.tmp, nom), { recursive: true, force: true });
1381
+ }
1382
+ }
1383
+
1384
+ // Builds under the temporary directory of the ticket the tree of HEAD's version of <f>: the copy
1385
+ // (the code of the lot included), without `.git`, `target`, `node_modules` and `.venv`, where <f>
1386
+ // alone holds <texte>, HEAD's text, under its own name. Returns its root.
1387
+ function batirLArbre(ctx, f, texte) {
1388
+ const racine = mkdtempSync(path.join(ctx.tmp, `avant-${process.pid}-`));
1389
+ try {
1390
+ cpSync(ctx.copie, racine, {
1391
+ recursive: true,
1392
+ filter: src =>
1393
+ src === ctx.copie ||
1394
+ (!HORS_DE_L_ARBRE.has(path.basename(src)) && path.resolve(src) !== path.resolve(ctx.tmp)),
1395
+ });
1396
+ writeFileSync(path.join(racine, f), texte);
1397
+ } catch (e) {
1398
+ rmSync(racine, { recursive: true, force: true });
1399
+ throw e;
1400
+ }
1401
+ return racine;
1402
+ }
1403
+
1404
+ // Runs <jouer> with HEAD's version of each file of <fichiers> that HEAD holds, where the module
1405
+ // of its language puts it: a sibling written beside the file in the copy (`soeurDAvant` of the
1406
+ // join: TypeScript, whose tool plays it in the same run), swept first (`balayerLesSoeurs`) and
1407
+ // removed after the run, a red included; or a tree of its own (`arbreDAvant` of the join: Rust,
1408
+ // Python), the copy's with that file alone replaced by its version of HEAD, under its own name, in
1409
+ // the temporary directory of the ticket (`batirLArbre`), removed after the run, a red included,
1410
+ // the copy getting no file. <jouer> gets the Map file → sibling (from the copy), the Map file →
1411
+ // names of the tests of HEAD's version, read without playing them, of each file its tool cannot
1412
+ // play twice (`testsDeHead` of the join), and the Map file → `{ racine, env }`, the root of its
1413
+ // tree and the environment it plays under (`envDArbre` of the join). With <sansArbres>, no tree
1414
+ // is built: the names of HEAD's tests of each file that would have one are read too. Returns
1415
+ // what <jouer> returns.
1416
+ export function avecLesVersionsDAvant(ctx, fichiers, jouer, { sansArbres = false } = {}) {
1417
+ balayerLesSoeurs(ctx);
1418
+ balayerLesArbres(ctx);
1419
+ return avecUneLecture(() => {
1420
+ const avant = new Map();
1421
+ const lus = new Map();
1422
+ const arbres = new Map();
1423
+ const deHead = f => {
1424
+ const r = spawnSync('git', ['-C', ctx.copie, 'show', `HEAD:${f}`], {
1425
+ encoding: 'utf8',
1426
+ maxBuffer: 64 * 1024 * 1024,
1427
+ });
1428
+ return r.status === 0 ? r.stdout : null;
1429
+ };
1430
+ try {
1431
+ const langage = langageDe(ctx.copie);
1432
+ for (const f of fichiers) {
1433
+ const soeur = soeurDe(langage, f, ctx.copie);
1434
+ if (soeur !== null) {
1435
+ const texte = deHead(f);
1436
+ if (texte === null) {
1437
+ continue;
1438
+ }
1439
+ writeFileSync(path.join(ctx.copie, soeur), texte);
1440
+ avant.set(f, soeur);
1441
+ continue;
1442
+ }
1443
+ if (arbreDe(langage, f, ctx.copie) && !sansArbres) {
1444
+ const texte = deHead(f);
1445
+ if (texte === null) {
1446
+ continue;
1447
+ }
1448
+ const env =
1449
+ typeof langage.envDArbre === 'function' ? langage.envDArbre(f, ctx.copie) : {};
1450
+ arbres.set(f, { racine: batirLArbre(ctx, f, texte), env });
1451
+ continue;
1452
+ }
1453
+ const noms = langage.testsDeHead(f, ctx.copie, deHead);
1454
+ if (noms !== null) {
1455
+ lus.set(f, noms);
1456
+ }
1457
+ }
1458
+ return jouer(avant, lus, arbres);
1459
+ } finally {
1460
+ for (const soeur of avant.values()) {
1461
+ rmSync(path.join(ctx.copie, soeur), { force: true });
1462
+ }
1463
+ for (const { racine } of arbres.values()) {
1464
+ rmSync(racine, { recursive: true, force: true });
1465
+ }
1466
+ }
1467
+ });
1468
+ }
1469
+
1470
+ // The run of the files <groupe> of one package of the proof, HEAD's version of each beside it or
1471
+ // in a tree (`avecLesVersionsDAvant`): `{ avant, lus, arbres, code, resultats, constructions }`,
1472
+ // <jouer> given the files to play in the copy and the trees to play, and returning `{ code,
1473
+ // resultats, constructions }`. A tree that does not compile is not a red of the lot (the owner's
1474
+ // decision on grillhouse-3e2.2): when the build fails with trees, the package plays again without
1475
+ // them, and when the lot alone builds, that run is kept, the names of HEAD's tests of those files
1476
+ // read without playing them; a build the lot alone breaks stays a red, the first run kept.
1477
+ export function jouerAvecLesVersionsDAvant(ctx, groupe, jouer) {
1478
+ const avecArbres = avecLesVersionsDAvant(ctx, groupe, (avant, lus, arbres) => ({
1479
+ avant,
1480
+ lus,
1481
+ arbres,
1482
+ ...jouer([...groupe, ...avant.values()], arbres),
1483
+ }));
1484
+ if (avecArbres.arbres.size === 0 || avecArbres.constructions.length === 0) {
1485
+ return avecArbres;
1486
+ }
1487
+ const sansArbres = avecLesVersionsDAvant(
1488
+ ctx,
1489
+ groupe,
1490
+ (avant, lus, arbres) => ({
1491
+ avant,
1492
+ lus,
1493
+ arbres,
1494
+ ...jouer([...groupe, ...avant.values()], arbres),
1495
+ }),
1496
+ { sansArbres: true }
1497
+ );
1498
+ return sansArbres.constructions.length === 0 ? sansArbres : avecArbres;
1499
+ }
1500
+
1501
+ // The log of the task <t> of a summary of Turborepo, its file from the root of the copy: its path,
1502
+ // and its first lines, the task's own output.
1503
+ function journalDeTache(ctx, t) {
1504
+ if (!t.journal) {
1505
+ return { chemin: null, debut: '' };
1506
+ }
1507
+ const chemin = path.join(ctx.copie, t.journal);
1508
+ return { chemin, debut: sansCouleurs(lire(chemin)).trim().split('\n').slice(0, 80).join('\n') };
1509
+ }
1510
+
1511
+ // Runs <jouer> with the installed dependencies of the copy (`node_modules` of its root) linked in
1512
+ // the tree <racine>, which carries none, so that its tool (npm) starts there; the link goes after
1513
+ // the run, a red included.
1514
+ function avecLesDependancesDeLaCopie(ctx, racine, jouer) {
1515
+ const source = path.join(ctx.copie, 'node_modules');
1516
+ const lien = path.join(racine, 'node_modules');
1517
+ if (!existsSync(source) || existsSync(lien)) {
1518
+ return jouer();
1519
+ }
1520
+ symlinkSync(source, lien);
1521
+ try {
1522
+ return jouer();
1523
+ } finally {
1524
+ rmSync(lien, { force: true });
1525
+ }
1526
+ }
1527
+
1528
+ // The measure of the proof of the red: one run per package, `npm test -- --force <files>` of the
1529
+ // lot that lie in it, HEAD's version of each beside it or in a tree of its own, played again
1530
+ // without the trees when they alone break the build (`jouerAvecLesVersionsDAvant`), or, with no
1531
+ // file of the lot, `npm test -- <package>` for each package of the plan, played whole. Each run
1532
+ // `{ groupe, entier, avant, lus, arbres, code, resultats, constructions }`. A measure on the same tree (the copy's fingerprint, `empreinte`) is
1533
+ // not played again, as Turborepo replays a task whose inputs did not move: the last one, <derniere>,
1534
+ // its caller keeps. `{ cle, runs }`, each map of a run (`avant`, `lus`, `arbres`) an object.
1535
+ function mesureDeLaPreuve(ctx, liste, fichiers, derniere = null) {
1536
+ const cle = empreinte(ctx, ['.']);
1537
+ if (derniere?.cle === cle) {
1538
+ return derniere;
1539
+ }
1540
+ const entiers = fichiers.length ? [] : paquetsDuPlan(ctx, liste);
1541
+ const groupes = new Map(entiers.map(d => [d, []]));
1542
+ for (const f of fichiers) {
1543
+ const p = paquetDe(liste, f);
1544
+ groupes.set(p, [...(groupes.get(p) ?? []), f]);
1545
+ }
1546
+ const runs = [];
1547
+ for (const [dossier, groupe] of groupes) {
1548
+ const entier = entiers.includes(dossier);
1549
+ // The files of the lot play for real (`--force`): a run replayed from Turborepo's cache, the
1550
+ // checks' same command on the same inputs, writes no report of Vitest.
1551
+ const run = jouerAvecLesVersionsDAvant(ctx, groupe, (aJouer, arbres) => {
1552
+ // The copy plays the files of the lot; each tree plays its one file, HEAD's version, in its
1553
+ // own root, under its own environment, as the copy's tool plays it.
1554
+ const passes = [
1555
+ npm(ctx, 'preuve', ['test', '--', ...(entier ? [dossier] : ['--force']), ...aJouer]),
1556
+ ...[...arbres].map(([f, arbre]) =>
1557
+ avecLesDependancesDeLaCopie(ctx, arbre.racine, () =>
1558
+ npm(ctx, 'preuve', ['test', '--', '--force', f], arbre.env, arbre.racine)
1559
+ )
1560
+ ),
1561
+ ];
1562
+ return {
1563
+ code: passes.find(r => r.code !== 0)?.code ?? 0,
1564
+ resultats: passes.flatMap(r => langageDe(ctx.copie).verdict(r.dossier).rapports),
1565
+ // The builds of the plan's packages that failed: each one a red, not compiling is failing.
1566
+ constructions: passes.flatMap(r => constructionsEchouees(ctx, liste, r.dossier)),
1567
+ };
1568
+ });
1569
+ // Its maps as objects, so that the measure is a plain object, which its caller keeps.
1570
+ runs.push({
1571
+ groupe,
1572
+ entier,
1573
+ ...run,
1574
+ avant: Object.fromEntries(run.avant),
1575
+ lus: Object.fromEntries(run.lus),
1576
+ arbres: Object.fromEntries(run.arbres),
1577
+ });
1578
+ }
1579
+ return { cle, runs };
1580
+ }
1581
+
1582
+ // The green tests of HEAD's version of the file <f> of the lot, by their full name: those of the
1583
+ // report of its sibling (`avant`, file → sibling, from the copy <copie>) or of its tree (`arbres`,
1584
+ // file → `{ racine }`, the file there at the same path: the copy's by the change of root alone)
1585
+ // in the results <resultats> of the run (`verdict` of the join), or, for a file played in neither,
1586
+ // the names of its tests read in HEAD's version (`lus`, file → names), each held green, as main
1587
+ // stays green; empty for a file HEAD does not hold.
1588
+ export function vertsDeHead(resultats, copie, f, avant, lus = new Map(), arbres = new Map()) {
1589
+ if (lus.has(f)) {
1590
+ return new Set(lus.get(f));
1591
+ }
1592
+ const soeur = avant.has(f)
1593
+ ? path.join(copie, avant.get(f))
1594
+ : arbres.has(f)
1595
+ ? path.join(arbres.get(f).racine, f)
1596
+ : null;
1597
+ return new Set(
1598
+ (resultats.find(t => soeur !== null && t.fichier === soeur)?.tests ?? [])
1599
+ .filter(a => a.etat === 'passed')
1600
+ .map(a => a.nom)
1601
+ );
1602
+ }
1603
+
1604
+ // The full name of a test <nom> with each separator between a group and what it holds, « > » or
1605
+ // « › » between blanks, read as the blank that Vitest's full name puts there.
1606
+ const sansSeparateur = nom =>
1607
+ String(nom ?? '')
1608
+ .replace(/\s+[>›]\s+/g, ' ')
1609
+ .trim();
1610
+
1611
+ // The tests that carry the ticket's work, from the testwriter's sheets in their order: the list is
1612
+ // replaced, not added. A sheet without the field keeps the list of the sheet before, a given list
1613
+ // replaces it, and `[]` empties it (a rerun testwriter withdraws a name that way).
1614
+ export const portentLeTravail = fiches =>
1615
+ fiches.filter(f => Array.isArray(f.portent_le_travail)).at(-1)?.portent_le_travail ?? [];
1616
+
1617
+ // The proof of the red, on every test of the lot: `{ ok, rouges, texte, resume }`, `texte` the
1618
+ // report, written whole to its file beside the copy. A
1619
+ // green test is a defect when the testwriter's sheets name it (`portent_le_travail`), read at
1620
+ // each proof, and accepted when they do not; a test's full name is read whatever the
1621
+ // separator between its group and its title, a blank, or « > » as Vitest prints it, or « › » as
1622
+ // Jest and the report of the proof print it (`sansSeparateur`); the measure plays again only when
1623
+ // the copy changed (`mesureDeLaPreuve`).
1624
+ export function preuve(ctx, { mesure: derniere = null, fichiers: seuls = null } = {}) {
1625
+ // Only the files of the day are proved; the ones only the night plays are put aside, named.
1626
+ // Resumed at a red (<seuls>, the files it names), the proof plays these files alone and passes
1627
+ // when they load: a test fixed is green, not red.
1628
+ const { jour: fichiers, misDeCote } = separerLesFichiersDuJour(ctx, seuls ?? testsDuLot(ctx));
1629
+ const portent = portentLeTravail(fichesDe(ctx, 'testwriter'));
1630
+ // Whether the sheet names the test <a> of the file <f>, by its full name or by its whole file.
1631
+ const nomme = (f, a) =>
1632
+ portent.some(
1633
+ v =>
1634
+ v.fichier === f &&
1635
+ (!v.test || [a.nom, a.titre].some(n => sansSeparateur(v.test) === sansSeparateur(n)))
1636
+ );
1637
+ const rouges = [];
1638
+ // The reds of the files of the lot, apart from the existing ones and the builds.
1639
+ let rougesDuLot = 0;
1640
+ const nonNommes = [];
1641
+ const nommes = [];
1642
+ const casses = [];
1643
+ const liste = composantsDe(ctx.copie).filter(p => !p.hors);
1644
+ let anciens = 0;
1645
+ const reportes = [];
1646
+ // A lot of files put aside alone plays nothing, not the packages whole.
1647
+ const mesuree =
1648
+ fichiers.length || !misDeCote.length ? mesureDeLaPreuve(ctx, liste, fichiers, derniere) : null;
1649
+ const mesure = (mesuree?.runs ?? []).map(r => ({
1650
+ ...r,
1651
+ avant: new Map(Object.entries(r.avant)),
1652
+ lus: new Map(Object.entries(r.lus)),
1653
+ arbres: new Map(Object.entries(r.arbres)),
1654
+ }));
1655
+ // A plan « comportement inchangé »: every green of the lot is expected.
1656
+ const inchange = Boolean(ctx.sorte?.inchange);
1657
+ // The developpeur already ran after the last testwriter: the code is there, no test can turn red.
1658
+ const codePresent = codeDejaPresent(ctx);
1659
+ for (const { groupe, entier, avant, lus, arbres, code, resultats, constructions } of mesure) {
1660
+ for (const { nom, erreur } of constructions) {
1661
+ if (reportes.includes(nom)) {
1662
+ continue;
1663
+ }
1664
+ rouges.push(`construction de ${nom} — ${erreur}`);
1665
+ reportes.push(nom);
1666
+ }
1667
+ // The files of a package played whole, out of the lot, which HEAD holds green: a red of theirs
1668
+ // is a regression of the lot.
1669
+ if (entier) {
1670
+ for (const res of resultats) {
1671
+ const f = path.relative(ctx.copie, res.fichier);
1672
+ if (res.tests.length === 0 && res.etat === 'failed' && !constructions.length) {
1673
+ rouges.push(
1674
+ `rouge existant : ${f} — ne se charge pas : ${premiereLigne(res.message || res.etat)}`
1675
+ );
1676
+ }
1677
+ for (const a of res.tests.filter(x => x.etat === 'failed')) {
1678
+ rouges.push(`rouge existant : ${f} › ${a.nom} — ${premiereLigne(a.message)}`);
1679
+ }
1680
+ }
1681
+ }
1682
+ for (const f of groupe) {
1683
+ const res = resultats.find(t => t.fichier === path.join(ctx.copie, f));
1684
+ const tests = res?.tests ?? [];
1685
+ const deHead = vertsDeHead(resultats, ctx.copie, f, avant, lus, arbres);
1686
+ if (constructions.length && (!res || tests.length === 0)) {
1687
+ // It cannot load before the build: it plays at the checks.
1688
+ } else if (!res) {
1689
+ casses.push(
1690
+ `${f} — ne se charge pas : non joué (code ${code}) ; le journal du ticket : ${ctx.journal}`
1691
+ );
1692
+ } else if (tests.length === 0) {
1693
+ casses.push(`${f} — ne se charge pas : ${premiereLigne(res.message || res.etat)}`);
1694
+ }
1695
+ for (const a of tests) {
1696
+ if (a.etat === 'failed') {
1697
+ rouges.push(`${f} › ${a.nom} — ${premiereLigne(a.message)}`);
1698
+ rougesDuLot++;
1699
+ } else if (a.etat === 'passed' && deHead.has(a.nom)) {
1700
+ anciens++;
1701
+ } else if (a.etat === 'passed') {
1702
+ (nomme(f, a) ? nommes : nonNommes).push(`${f} › ${a.nom}`);
1703
+ }
1704
+ }
1705
+ }
1706
+ }
1707
+ const section = (titre, l) =>
1708
+ l.length ? [`${titre} (${l.length}) :`, ...l.map(x => `- ${x}`), ''] : [];
1709
+ const ok = seuls
1710
+ ? casses.length === 0
1711
+ : preuveReussie(
1712
+ {
1713
+ fichiers: fichiers.length,
1714
+ rouges: rouges.length,
1715
+ casses: casses.length,
1716
+ nommes: nommes.length,
1717
+ nonNommes: nonNommes.length,
1718
+ anciens,
1719
+ misDeCote: misDeCote.length,
1720
+ },
1721
+ { inchange, codePresent }
1722
+ );
1723
+ const resume = `${rouges.length} rouge(s), ${nommes.length} vert(s) nommé(s) qui portent le travail, ${nonNommes.length} vert(s) non nommé(s), ${casses.length} fichier(s) qui ne se charge(nt) pas, ${anciens} test(s) vert(s) que HEAD tient déjà, laissé(s) de côté`;
1724
+ const ecrit = (...sections) =>
1725
+ [
1726
+ `${SUITE.find(e => e.etat === PREUVE).titre} : ${resume}.`,
1727
+ ...[...new Set(reportes)].map(
1728
+ nom => `Les tests de ${nom} se jouent aux contrôles, après le développeur.`
1729
+ ),
1730
+ '',
1731
+ ...(codePresent && !inchange && ok && rouges.length === 0
1732
+ ? ['Le code du développeur est déjà dans la copie : le rouge n’a rien à prouver.', '']
1733
+ : fichiers.length || rouges.length || misDeCote.length
1734
+ ? []
1735
+ : inchange
1736
+ ? [
1737
+ 'Aucun fichier de test du lot : le plan dit « comportement inchangé », rien à prouver.',
1738
+ '',
1739
+ ]
1740
+ : ['Aucun fichier de test du lot dans le plan : rien ne prouve le rouge.', '']),
1741
+ ...section('Rouges', rouges),
1742
+ ...sections,
1743
+ ...(nommes.length
1744
+ ? [
1745
+ `Tests qui portent le travail, verts avant le code (${nommes.length}) :`,
1746
+ 'Ta fiche les nomme dans `portent_le_travail` : un test qui porte le travail du ticket rougit d’abord ; nomme seulement ceux-là, ou écris-les pour qu’ils échouent sur le code présent.',
1747
+ ...nommes.map(x => `- ${x}`),
1748
+ '',
1749
+ ]
1750
+ : []),
1751
+ ...section('Fichiers qui ne prouvent rien', casses),
1752
+ ...sectionMisDeCote(misDeCote),
1753
+ ]
1754
+ .join('\n')
1755
+ .trim();
1756
+ let n = 1;
1757
+ while (existsSync(`${ctx.copie}.preuve-${n}.md`)) {
1758
+ n++;
1759
+ }
1760
+ const complet = `${ctx.copie}.preuve-${n}.md`;
1761
+ const texte = ecrit(
1762
+ `Le rapport entier : ${complet}`,
1763
+ '',
1764
+ ...section('Verts non nommés (acceptés sans justification)', nonNommes)
1765
+ );
1766
+ writeFileSync(complet, `${texte}\n`);
1767
+ return {
1768
+ ok,
1769
+ rouges: rouges.length,
1770
+ texte,
1771
+ resume,
1772
+ // A lot put aside alone measures nothing: the measure kept stays.
1773
+ mesure: mesuree ?? derniere,
1774
+ resultat: {
1775
+ ok,
1776
+ rouges: rouges.length,
1777
+ justifies: nonNommes.length,
1778
+ sans: nommes.length,
1779
+ casses: casses.length,
1780
+ anciens,
1781
+ vide: rougesDuLot + nonNommes.length + nommes.length + casses.length === 0,
1782
+ },
1783
+ };
1784
+ }
1785
+
1786
+ // The builds that failed in the run whose results are under <dossier> (the summary of Turborepo,
1787
+ // task `<package>#build`) of a package of the plan: `{ nom, erreur }`, `erreur` its log file and
1788
+ // the beginning of its own output.
1789
+ function constructionsEchouees(ctx, liste, dossier) {
1790
+ return langageDe(ctx.copie)
1791
+ .verdict(dossier)
1792
+ .taches.filter(t => t.script === 'build' && t.code !== null && t.code !== 0)
1793
+ .flatMap(t => {
1794
+ const p = liste.find(x => x.pkg.name === t.paquet);
1795
+ if (!p || !dansLePlan(ctx, p.dossier)) {
1796
+ return [];
1797
+ }
1798
+ const j = journalDeTache(ctx, t);
1799
+ return [{ nom: t.paquet, erreur: `son journal : ${j.chemin}\n\n${j.debut}\n` }];
1800
+ });
1801
+ }
1802
+
1803
+ // The tasks of style, played per package (`<package>#lint`, `<package>#format:check`).
1804
+ const STYLE = new Set(['lint', 'format:check']);
1805
+
1806
+ // Where <chemin> (from the root of the copy) lies: `{ dansLePlan, paquet, horsTitre }`, whether
1807
+ // a path of the plan holds it, the name of the package of <liste> that holds it, and that name
1808
+ // again when the plan does not hold it. A red with no path (null) is in the plan when the plan
1809
+ // names « . », which holds the whole copy.
1810
+ function situer(ctx, liste, chemin) {
1811
+ const dedans = chemin ? dansLePlan(ctx, chemin) : nommeLaRacine(ctx);
1812
+ const p = chemin ? liste.find(x => chemin.startsWith(`${x.dossier}/`)) : null;
1813
+ const paquet = p ? p.pkg.name : null;
1814
+ return { dansLePlan: dedans, paquet, horsTitre: dedans ? null : paquet };
1815
+ }
1816
+
1817
+ // The reds of the check <c> (`{ args, env, code, dossier }`), read in its results: each failed
1818
+ // test of the reports of Vitest, each finding of the guards' SARIF, each failed build, and each
1819
+ // failed task none of those situates; a red check with none of them is one red of the command.
1820
+ // Each red `{ texte, fichier, gardes, detail, dansLePlan, paquet, horsTitre, arbitrer, joue }`: the
1821
+ // line that names it (test or finding, file, message), its file (null for a red of a task), the
1822
+ // names its finding carries (its guard and its rule), the beginning of its task's log for a build,
1823
+ // whether a path of the plan holds it (none for a red without a file), the package that holds it
1824
+ // and that package again when it is out of the plan, whether it is a finding to settle
1825
+ // (`a-arbitrer`), and the package whose task gave it, as Turborepo names it (« // » for the
1826
+ // root's guards; null for a red of the command).
1827
+ // As SARIF 2.1.0 and GitHub code scanning, a finding of level error fails, a warning or a note
1828
+ // shows without failing: `{ rouges, avertissements }`, `avertissements` the lines of the findings
1829
+ // of another level, which the report lists apart. A guards' task red without a finding of level
1830
+ // error keeps its line of a red task, with its log.
1831
+ function rougesDe(ctx, liste, c) {
1832
+ const lus = lireSarif(c.dossier).constats.filter(k => k.genre !== A_ELAGUER);
1833
+ const vert = c.code === 0 || c.code === A_REPASSER;
1834
+ const gardesDuCadre = nomsDesGardes(ctx.copie);
1835
+ const duCadre = k => gardesDuCadre.includes(k.garde);
1836
+ const rouge = k => k.niveau === 'error';
1837
+ const ligneDe = k => {
1838
+ const ou = k.fichier ? ` ${k.fichier}${k.ligne ? `:${k.ligne}` : ''}` : '';
1839
+ return `${k.garde}${ou} — ${k.message}${k.genre === 'a-arbitrer' ? ' (à arbitrer)' : ''}`;
1840
+ };
1841
+ const avertissements = lus.filter(k => !rouge(k)).map(k => `${k.niveau} ${ligneDe(k)}`);
1842
+ if (vert) {
1843
+ return { rouges: [], avertissements };
1844
+ }
1845
+ const out = [];
1846
+ const testes = new Set();
1847
+ for (const res of langageDe(ctx.copie).verdict(c.dossier).rapports) {
1848
+ const f = path.relative(ctx.copie, res.fichier);
1849
+ const lieu = situer(ctx, liste, f);
1850
+ if (res.tests.length === 0 && res.etat === 'failed') {
1851
+ out.push({
1852
+ texte: `test ${f} — ne se charge pas : ${premiereLigne(res.message)}`,
1853
+ fichier: f,
1854
+ ...lieu,
1855
+ joue: lieu.paquet,
1856
+ });
1857
+ testes.add(paquetDe(liste, f));
1858
+ }
1859
+ for (const a of res.tests.filter(x => x.etat === 'failed')) {
1860
+ out.push({
1861
+ texte: `test ${f} › ${a.nom} — ${premiereLigne(a.message)}`,
1862
+ fichier: f,
1863
+ ...lieu,
1864
+ joue: lieu.paquet,
1865
+ });
1866
+ testes.add(paquetDe(liste, f));
1867
+ }
1868
+ }
1869
+ // A key of the debt to lower (`a-elaguer`, scripts/dette.mjs) is a note, not a red.
1870
+ const constats = lus.filter(rouge);
1871
+ for (const k of constats) {
1872
+ out.push({
1873
+ texte: `constat ${ligneDe(k)}`,
1874
+ fichier: k.fichier ?? null,
1875
+ gardes: [k.garde, k.regle].filter(Boolean),
1876
+ ...situer(ctx, liste, k.fichier),
1877
+ arbitrer: k.genre === 'a-arbitrer',
1878
+ joue: '//',
1879
+ });
1880
+ }
1881
+ // The guards of the project wrote findings when one comes from a guard out of the frame's.
1882
+ const duProjet = constats.some(k => !duCadre(k));
1883
+ for (const t of langageDe(ctx.copie).verdict(c.dossier).taches) {
1884
+ if (t.code === null || t.code === 0 || t.code === A_REPASSER) {
1885
+ continue;
1886
+ }
1887
+ if (t.tests && testes.has(t.dossier)) {
1888
+ continue;
1889
+ }
1890
+ if (t.script === 'grillhouse:gardes' && constats.length) {
1891
+ continue;
1892
+ }
1893
+ if (t.script === 'gardes' && duProjet) {
1894
+ continue;
1895
+ }
1896
+ const p = liste.find(x => x.pkg.name === t.paquet);
1897
+ const lieu = p ? situer(ctx, liste, `${p.dossier}/`) : situer(ctx, liste, null);
1898
+ const j = journalDeTache(ctx, t);
1899
+ out.push({
1900
+ texte:
1901
+ t.script === 'build'
1902
+ ? `construction de ${t.paquet} — son journal : ${j.chemin}`
1903
+ : `tâche ${t.tache} rouge (code ${t.code}) — son journal : ${j.chemin}`,
1904
+ detail: t.script === 'build' ? j.debut : '',
1905
+ ...lieu,
1906
+ // A red task of style (`<package>#lint`, `<package>#format:check`) is named by its task, as
1907
+ // the plan's package that holds it: the one out of the plan reads `<package>#lint`.
1908
+ horsTitre: lieu.horsTitre && STYLE.has(t.script) ? t.tache : lieu.horsTitre,
1909
+ joue: t.paquet,
1910
+ });
1911
+ }
1912
+ if (out.length === 0) {
1913
+ out.push({
1914
+ texte: `${ligneDeCommande(c)} rouge (code ${c.code}), sans résultat qui situe son rouge — le journal du ticket : ${ctx.journal}`,
1915
+ ...situer(ctx, liste, null),
1916
+ });
1917
+ }
1918
+ return { rouges: out, avertissements };
1919
+ }
1920
+
1921
+ const ligneDeCommande = c =>
1922
+ `${Object.entries(c.env ?? {})
1923
+ .map(([k, v]) => `${k}=${v} `)
1924
+ .join('')}npm ${c.args.join(' ')}`;
1925
+
1926
+ // The checks after the developpeur: those of the plan (3.1), or, when <finale>, `npm run
1927
+ // verifier`, what the integration plays (4.1), restricted by <restreinte> (`{ avant, apres }`, two
1928
+ // lots kept) to the packages that changed from one to the other and their dependents, with the
1929
+ // root's tasks, the guards (`--filter=...[<avant>...<apres>] --filter=//`). After a regeneration,
1930
+ // <reportes> (`{ rouges, rejouee }`) carries the reds of the pass before it, the final pass or the
1931
+ // checks of the plan: each one in a package the pass after the regeneration does not play again
1932
+ // stands, as a CI keeps the verdict of a job it does not run again; when the regeneration changes
1933
+ // nothing (`rejouee` false), no command plays, and they all stand. `{ rouge, aRepasser, arbitrer, auDeveloppeur,
1934
+ // texte, complet, resume, horsTitre, lieux, tous, notes, avertissements }`: `texte` the report for
1935
+ // the developpeur, his reds first; `complet` every red, for a stop, and the warnings;
1936
+ // `avertissements` the section of the warnings and notes of the guards, which are no reds, for the
1937
+ // report of the checks (empty without one); `auDeveloppeur` whether a red lies
1938
+ // in a package of the plan; `horsTitre` the packages out of the plan that hold a red; `arbitrer`
1939
+ // when every red of the plan is a finding to settle; `lieux` the place of each red, `{ fichier,
1940
+ // gardes, dansLePlan }`, its file (null for a red without one), the names its finding carries
1941
+ // (none for a test or a task), and whether a path of the plan holds it; `references`, out of the final pass, the references whose reds the checks saw,
1942
+ // which their regeneration lifts before the checks judge the lot again, or before the final pass; `tous` every red as it was read; `notes`,
1943
+ // at the final pass, each key of the debt a guard wrote inscribed above what it finds, `{ garde,
1944
+ // fichier, regle, trouve }`.
1945
+ export function controles(ctx, finale, restreinte = null, reportes = null, fichiers = null) {
1946
+ const liste = composantsDe(ctx.copie).filter(p => !p.hors);
1947
+ // Resumed at a red in the test files <fichiers>: the final pass plays their packages alone (the
1948
+ // graph of packages of Turborepo, the root's tasks beside), the checks of the plan their tests
1949
+ // alone (Vitest plays what the files import) and the guards.
1950
+ const duReprise = fichiers
1951
+ ? [...new Set(fichiers.map(f => liste.find(p => f.startsWith(`${p.dossier}/`))?.pkg.name))]
1952
+ .filter(Boolean)
1953
+ .sort()
1954
+ : null;
1955
+ const filtres = duReprise
1956
+ ? ['--', ...duReprise.map(n => `--filter=${n}`), '--filter=//']
1957
+ : restreinte
1958
+ ? ['--', `--filter=...[${restreinte.avant}...${restreinte.apres}]`, '--filter=//']
1959
+ : [];
1960
+ const commandes =
1961
+ reportes && !reportes.rejouee
1962
+ ? []
1963
+ : finale
1964
+ ? [{ args: ['run', 'verifier', ...filtres] }]
1965
+ : commandesDuPlan(ctx, liste, fichiers);
1966
+ const resultats = commandes.map(({ args, env }) => {
1967
+ let r = npm(ctx, 'controles', args, env);
1968
+ // The 75 of verifier is final (its wait for the lock reached its bound); a command of the
1969
+ // checks plays once more, the gesture `rejeu`.
1970
+ if (r.code === A_REPASSER && !finale) {
1971
+ geste(ctx, 'rejeu');
1972
+ r = npm(ctx, 'controles', args, env);
1973
+ }
1974
+ const c = { args, env, ...r };
1975
+ return { ...c, ...rougesDe(ctx, liste, c) };
1976
+ });
1977
+ // The packages the commands played (the root's tasks under « // »), whose reds are read again.
1978
+ const joues = new Set(
1979
+ resultats.flatMap(r =>
1980
+ langageDe(ctx.copie)
1981
+ .verdict(r.dossier)
1982
+ .taches.map(t => t.paquet)
1983
+ )
1984
+ );
1985
+ const tous = [
1986
+ ...resultats.flatMap(r => r.rouges),
1987
+ ...(reportes?.rouges ?? []).filter(
1988
+ r => !reportes.rejouee || (Boolean(r.joue) && !joues.has(r.joue))
1989
+ ),
1990
+ ];
1991
+ // Out of the final pass, the reds of the plan are the developpeur's; a red of a reference goes to
1992
+ // its regeneration (4.2), before any red goes to him; the others (the root, a red no file situates, a
1993
+ // package out of the plan) wait for the final pass.
1994
+ const lieu = r => ({
1995
+ fichier: r.fichier ?? null,
1996
+ gardes: r.gardes ?? [],
1997
+ dansLePlan: Boolean(r.dansLePlan),
1998
+ });
1999
+ const deReference = r => referencesDesRouges(ctx, [lieu(r)]).length > 0;
2000
+ const siens = r => finale || (r.dansLePlan && !deReference(r));
2001
+ const rouges = tous.filter(siens);
2002
+ const references = finale
2003
+ ? []
2004
+ : referencesDesRouges(ctx, tous.filter(r => !siens(r) && deReference(r)).map(lieu));
2005
+ const laisses = tous.filter(r => !siens(r) && (finale || !deReference(r)));
2006
+ const aRepasser = resultats.filter(r => r.code === A_REPASSER);
2007
+ const nommer = r => `${ligneDeCommande(r)} (code ${r.code})`;
2008
+ const enEchec = resultats.filter(r => r.code !== 0 && r.code !== A_REPASSER);
2009
+ const a = rouges.filter(r => r.dansLePlan);
2010
+ const autres = rouges.filter(r => !r.dansLePlan);
2011
+ const resume = rouges.length
2012
+ ? `rouge : ${rouges.length} rouge(s) — ${
2013
+ commandes.length
2014
+ ? enEchec.map(nommer).join(' ; ')
2015
+ : `ceux ${finale ? "de la passe finale d'avant" : "des contrôles d'avant"}, que la régénération ne change pas`
2016
+ }`
2017
+ : aRepasser.length
2018
+ ? `à repasser : ${aRepasser.map(nommer).join(' ; ')}`
2019
+ : `verts : ${commandes.length ? resultats.map(ligneDeCommande).join(' ; ') : finale ? "la passe finale d'avant" : "les contrôles d'avant"}${
2020
+ laisses.length
2021
+ ? ` ; laissés à la passe finale, ${laisses.length} rouge(s) hors du plan`
2022
+ : ''
2023
+ }`;
2024
+ // Where the checks played: the final pass out of the envelope, on the band of the lot (its base
2025
+ // and its dependents); the checks of the plan, its tests and packages, its guards in its
2026
+ // envelope.
2027
+ const ou = !finale
2028
+ ? 'Contrôles du plan, ses tests et ses paquets, ses gardes dans son enveloppe'
2029
+ : 'Contrôles de la passe finale, hors enveloppe, sur la bande du lot (sa base et ses dépendants)';
2030
+ const ligne = r => [`- ${r.texte}`, ...(r.detail ? ['', r.detail, ''] : [])];
2031
+ const nomDuPaquet = r => r.paquet ?? 'hors des paquets';
2032
+ const journal = `Le journal du ticket, pour le détail des commandes : ${ctx.journal}`;
2033
+ // The warnings and notes of the guards, apart from the reds: shown, given to no one to correct.
2034
+ const signales = resultats.flatMap(r => r.avertissements);
2035
+ const avertissements = signales.length
2036
+ ? [
2037
+ `Les avertissements (${signales.length}), qui ne sont pas des rouges :`,
2038
+ ...signales.map(l => `- ${l}`),
2039
+ '',
2040
+ ]
2041
+ : [];
2042
+ const texte = [
2043
+ `${ou} : ${resume}.`,
2044
+ '',
2045
+ ...(a.length ? [`Tes rouges (${a.length}) :`, ...a.flatMap(ligne), ''] : []),
2046
+ ...(aRepasser.length && !rouges.length
2047
+ ? [`À repasser (${aRepasser.length}) : ${aRepasser.map(nommer).join(' ; ')}`, '']
2048
+ : []),
2049
+ ...(autres.length
2050
+ ? [`Les autres rouges (${autres.length}), hors du plan, montent au superviseur.`, '']
2051
+ : []),
2052
+ ...(laisses.length && !finale
2053
+ ? [`Laissés à la passe finale (${laisses.length}) :`, ...laisses.map(r => `- ${r.texte}`), '']
2054
+ : []),
2055
+ journal,
2056
+ ].join('\n');
2057
+ const sansListe = [`${ou} : ${resume}.`, '', journal].join('\n');
2058
+ const complet = [
2059
+ `${ou} : ${resume}.`,
2060
+ '',
2061
+ ...(rouges.length
2062
+ ? [
2063
+ `Les rouges (${rouges.length}) :`,
2064
+ ...rouges.flatMap(r => ligne({ ...r, texte: `${nomDuPaquet(r)} : ${r.texte}` })),
2065
+ '',
2066
+ ]
2067
+ : []),
2068
+ ...avertissements,
2069
+ journal,
2070
+ ].join('\n');
2071
+ return {
2072
+ rouge: rouges.length > 0,
2073
+ aRepasser: aRepasser.length > 0,
2074
+ arbitrer: a.length > 0 && a.every(r => r.arbitrer),
2075
+ auDeveloppeur: a.length > 0,
2076
+ texte,
2077
+ complet,
2078
+ sansListe,
2079
+ avertissements: avertissements.length ? `\n\n${avertissements.join('\n').trimEnd()}` : '',
2080
+ // The reds of the stop, each with where it lies: the plan's, or at the final pass all of them;
2081
+ // never those left to the final pass.
2082
+ rouges: rouges.map(r => ({ paquet: nomDuPaquet(r), texte: r.texte, detail: r.detail })),
2083
+ resume,
2084
+ horsTitre: [...new Set(rouges.map(r => r.horsTitre).filter(Boolean))].sort(),
2085
+ lieux: rouges.map(lieu),
2086
+ references,
2087
+ tous,
2088
+ notes: finale
2089
+ ? resultats.flatMap(r =>
2090
+ lireSarif(r.dossier)
2091
+ .constats.filter(k => k.genre === A_ELAGUER)
2092
+ .map(({ garde, fichier, regle, trouve }) => ({ garde, fichier, regle, trouve }))
2093
+ )
2094
+ : [],
2095
+ };
2096
+ }
2097
+
2098
+ // The checks of the plan, out of the final pass: `npm test -- <package>` for each package of the
2099
+ // plan and each the lot touches in it, `npm test -- <test files of the lot>` that none of them
2100
+ // holds (the shared test material's out of the plan), each test played once, then the guards in
2101
+ // the envelope of the plan, whose findings on its files alone count.
2102
+ function commandesDuPlan(ctx, liste, seuls = null) {
2103
+ const lot = changements(ctx);
2104
+ const touches = liste.length
2105
+ ? [...new Set(lot.map(c => paquetDe(liste, c.fichier)).filter(d => d !== '.'))].sort()
2106
+ : ['.'];
2107
+ // Resumed at a red (<seuls>, the test files it names): these tests alone, no package whole.
2108
+ const entiers = seuls
2109
+ ? []
2110
+ : [
2111
+ ...new Set([...touches.filter(d => dansLePlan(ctx, d)), ...paquetsDuPlan(ctx, liste)]),
2112
+ ].sort();
2113
+ const tests = (seuls ?? testsDuLot(ctx)).filter(
2114
+ f => !entiers.some(d => d === '.' || f.startsWith(`${d}/`))
2115
+ );
2116
+ const scripts = lireJson(path.join(ctx.copie, 'package.json'))?.scripts ?? {};
2117
+ const enveloppe = { [VARIABLE_ENVELOPPE]: ecrireLaListe(ctx.paquets) };
2118
+ return [
2119
+ ...(tests.length ? [{ args: ['test', '--', ...tests] }] : []),
2120
+ ...entiers.map(d => ({ args: d === '.' ? ['test'] : ['test', '--', d] })),
2121
+ ...['grillhouse:gardes', 'gardes']
2122
+ .filter(s => s in scripts)
2123
+ .map(s => ({ args: ['run', s], env: enveloppe })),
2124
+ ];
2125
+ }
2126
+
2127
+ // Whether the package <p> of the repository at <racine> (an entry of `paquets`) plays tests, as the
2128
+ // module of its language answers.
2129
+ const joueDesTests = (racine, p) =>
2130
+ langageDe(racine).joueDesTests(racine, {
2131
+ dossier: path.join(racine, p.dossier),
2132
+ nom: path.basename(p.dossier),
2133
+ paquet: p.pkg.name ?? null,
2134
+ });
2135
+
2136
+ // The directories of the packages of <liste> that play tests (`joueDesTests`) and that the plan
2137
+ // holds; sorted.
2138
+ function paquetsDuPlan(ctx, liste) {
2139
+ return liste
2140
+ .filter(p => dansLePlan(ctx, p.dossier) && joueDesTests(ctx.copie, p))
2141
+ .map(p => p.dossier)
2142
+ .sort();
2143
+ }
2144
+
2145
+ // Whether the plan carries no test: in a repository of packages, no package of the frame that
2146
+ // plays tests (`joueDesTests`) lies in a path of the plan or holds it, as `npm test -- <chemin>`
2147
+ // refuses a path out of every package or in a package without tests. A repository without
2148
+ // packages plays its tests at its root: each plan has them.
2149
+ export function sansTests(ctx) {
2150
+ const racine = existsSync(ctx.copie) ? ctx.copie : ctx.racine;
2151
+ const liste = composantsDe(racine).filter(p => !p.hors);
2152
+ if (liste.length === 0) {
2153
+ return false;
2154
+ }
2155
+ const touche = (c, d) => c === '.' || d === c || d.startsWith(`${c}/`) || c.startsWith(`${d}/`);
2156
+ return !liste.some(p => ctx.paquets.some(c => touche(c, p.dossier)) && joueDesTests(racine, p));
2157
+ }
2158
+
2159
+ // Whether the copy holds a change of the plan against its HEAD.
2160
+ export function livre(ctx) {
2161
+ const r = spawnSync(
2162
+ 'git',
2163
+ ['-C', ctx.copie, 'status', '--porcelain', '--untracked-files=all', '--', ...ctx.paquets],
2164
+ { encoding: 'utf8' }
2165
+ );
2166
+ return String(r.stdout ?? '').trim() !== '';
2167
+ }
2168
+
2169
+ // The fingerprint of the files of <chemins> in the copy (the plan by default): `git status
2170
+ // --porcelain` of them and the content of each file it lists.
2171
+ export function empreinte(ctx, chemins = ctx.paquets) {
2172
+ const r = spawnSync(
2173
+ 'git',
2174
+ ['-C', ctx.copie, 'status', '--porcelain', '-z', '--untracked-files=all', '--', ...chemins],
2175
+ { encoding: 'utf8' }
2176
+ );
2177
+ const statut = String(r.stdout ?? '');
2178
+ const h = createHash('sha256').update(statut);
2179
+ for (const e of statut.split('\0')) {
2180
+ if (e.length < 4) {
2181
+ continue;
2182
+ }
2183
+ const f = path.join(ctx.copie, e.slice(3));
2184
+ try {
2185
+ if (statSync(f).isFile()) {
2186
+ h.update(e).update(readFileSync(f));
2187
+ }
2188
+ } catch {
2189
+ // A file removed: its line in the status is its trace.
2190
+ }
2191
+ }
2192
+ return h.digest('hex');
2193
+ }
2194
+
2195
+ // The fingerprint of the step <etape> (`preuve`, `controles`, `passe-finale`) on the copy
2196
+ // (scripts/reprise.mjs `empreinteDEtape`): its command and the hashes of what it reads, each
2197
+ // package of the plan and its dependents by the hash of its test task in the plan of Turborepo
2198
+ // (`turbo run test:unit --filter=...<package> --dry=json`: the hash of the inputs of a task), the
2199
+ // files of the plan in the copy (`empreinte`), and the configuration at the root of the copy by
2200
+ // its content. Null when Turborepo does not give its plan: nothing is then read back.
2201
+ export function empreinteDeLEtape(ctx, etape) {
2202
+ const liste = composantsDe(ctx.copie).filter(p => !p.hors);
2203
+ const commande =
2204
+ etape === 'preuve'
2205
+ ? `preuve ${testsDuLot(ctx).join(' ')}`
2206
+ : etape === 'controles'
2207
+ ? JSON.stringify(commandesDuPlan(ctx, liste))
2208
+ : 'npm run verifier';
2209
+ const noms = liste
2210
+ .filter(p => dansLePlan(ctx, p.dossier))
2211
+ .map(p => p.pkg.name)
2212
+ .filter(Boolean)
2213
+ .sort();
2214
+ const empreintes = langageDe(ctx.copie).empreintes(ctx.copie, noms);
2215
+ if (!empreintes) {
2216
+ return null;
2217
+ }
2218
+ const hashes = { plan: empreinte(ctx), ...empreintes };
2219
+ const racine = createHash('sha256');
2220
+ for (const f of readdirSync(ctx.copie).sort()) {
2221
+ const chemin = path.join(ctx.copie, f);
2222
+ if (statSync(chemin, { throwIfNoEntry: false })?.isFile()) {
2223
+ racine.update(f).update(readFileSync(chemin));
2224
+ }
2225
+ }
2226
+ hashes['//'] = racine.digest('hex');
2227
+ return empreinteDEtape({ commande, hashes });
2228
+ }
2229
+
2230
+ // The test files and the files of code a red lies in (<lieux>, the places of the red as the
2231
+ // checks name them) that the testwriter and the developpeur carry (scripts/reprise.mjs
2232
+ // `attribuerLeRouge`): `{ tests, code }`. The testwriter carries the test files of the lot; the
2233
+ // developpeur, every other file of a path of the plan.
2234
+ export function portesDuRouge(ctx, lieux) {
2235
+ const dulot = new Set(
2236
+ changements(ctx)
2237
+ .filter(c => !c.supprime && duTestwriter(ctx, c.fichier))
2238
+ .map(c => c.fichier)
2239
+ );
2240
+ const nommes = [...new Set((lieux ?? []).map(l => l.fichier).filter(Boolean))];
2241
+ return {
2242
+ tests: nommes.filter(f => dulot.has(f)),
2243
+ code: nommes.filter(f => !dulot.has(f) && dansLePlan(ctx, f)),
2244
+ };
2245
+ }
2246
+
2247
+ // Whether the plan names `.`, which holds the whole copy.
2248
+ function nommeLaRacine(ctx) {
2249
+ return ctx.paquets.includes('.');
2250
+ }
2251
+
2252
+ // Whether a path of the plan holds <chemin> (relative to the copy), `.` holding every path.
2253
+ function dansLePlan(ctx, chemin) {
2254
+ return ctx.paquets.some(c => c === '.' || chemin === c || chemin.startsWith(`${c}/`));
2255
+ }