@roomi-fields/grillhouse 0.25.5 → 0.27.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 (83) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/agents/testwriter.md +1 -1
  3. package/bin/grillhouse.mjs +20 -3
  4. package/cadre/templates/cargo/package.json +3 -0
  5. package/cadre/templates/projet/.gitattributes +1 -0
  6. package/cadre/templates/projet/CLAUDE.md +13 -0
  7. package/cadre/templates/projet/docs/ARCHITECTURE.md +15 -0
  8. package/cadre/templates/projet/docs/agents/issue-tracker.md +1 -1
  9. package/cadre/templates/python/package.json +18 -0
  10. package/charte.md +32 -1
  11. package/docs/ARCHITECTURE.md +146 -40
  12. package/docs/CADRE.md +7 -6
  13. package/docs/INTERFACE.md +108 -32
  14. package/hooks/register.tsx +57 -16
  15. package/package.json +9 -3
  16. package/scripts/circuit.mjs +165 -27
  17. package/scripts/commande-du-langage.mjs +2 -2
  18. package/scripts/commandes-composees.mjs +156 -0
  19. package/scripts/composition-des-langages.mjs +306 -0
  20. package/scripts/conformite.mjs +1 -3
  21. package/scripts/copies-finies.mjs +167 -28
  22. package/scripts/crochets.mjs +9 -3
  23. package/scripts/dernier-vert.mjs +15 -2
  24. package/scripts/engendres.mjs +170 -0
  25. package/scripts/enveloppe/enveloppe.mjs +59 -17
  26. package/scripts/enveloppe/lancer.sh +15 -22
  27. package/scripts/enveloppe/travail-de-la-copie.mjs +262 -0
  28. package/scripts/etapes.mjs +1 -1
  29. package/scripts/fusion-du-changelog.mjs +120 -0
  30. package/scripts/gardes-du-cadre.mjs +7 -4
  31. package/scripts/grillhouse-maj.mjs +171 -99
  32. package/scripts/index-interfaces.mjs +78 -0
  33. package/scripts/init.mjs +5 -5
  34. package/scripts/integration/file.mjs +270 -117
  35. package/scripts/integration/integrer.mjs +50 -62
  36. package/scripts/jointure.d.ts +48 -14
  37. package/scripts/langages/cargo/binaires.json +2 -1
  38. package/scripts/langages/cargo/binaires.mjs +29 -6
  39. package/scripts/langages/cargo/clippy.mjs +12 -2
  40. package/scripts/langages/cargo/commandes.mjs +60 -7
  41. package/scripts/langages/cargo/composants.mjs +229 -8
  42. package/scripts/langages/cargo/exemples.mjs +1 -15
  43. package/scripts/langages/cargo/index-interfaces.mjs +20 -3
  44. package/scripts/langages/cargo/index.mjs +25 -17
  45. package/scripts/langages/cargo/mise-a-jour.mjs +2 -1
  46. package/scripts/langages/cargo/sccache.mjs +172 -0
  47. package/scripts/langages/cargo/verdict.mjs +50 -10
  48. package/scripts/langages/python/binaires.json +3 -0
  49. package/scripts/langages/python/binaires.mjs +59 -0
  50. package/scripts/langages/python/commandes.mjs +411 -0
  51. package/scripts/langages/python/composants.mjs +272 -0
  52. package/scripts/langages/python/exemples.mjs +260 -0
  53. package/scripts/langages/python/index-interfaces.mjs +77 -0
  54. package/scripts/langages/python/index.mjs +94 -0
  55. package/scripts/langages/python/lot.mjs +76 -0
  56. package/scripts/langages/python/mise-a-jour.mjs +54 -0
  57. package/scripts/langages/python/tailles-des-tests.mjs +102 -0
  58. package/scripts/langages/python/verdict.mjs +85 -0
  59. package/scripts/langages/typescript/exemples.mjs +1 -20
  60. package/scripts/langages/typescript/index-interfaces.mjs +10 -3
  61. package/scripts/langages/typescript/index.mjs +15 -17
  62. package/scripts/langages/typescript/regle-des-tests.mjs +37 -0
  63. package/scripts/langages-des-paquets.mjs +171 -0
  64. package/scripts/langages.mjs +60 -41
  65. package/scripts/migrations/0.27.0-langages-dans-l-architecture.mjs +182 -0
  66. package/scripts/migrations.mjs +2 -0
  67. package/scripts/nuit.sh +15 -1
  68. package/scripts/outils-cles.mjs +188 -0
  69. package/scripts/resultats.mjs +22 -6
  70. package/scripts/session-start.sh +34 -9
  71. package/scripts/sources.mjs +2 -1
  72. package/scripts/sous-commandes.mjs +21 -3
  73. package/scripts/tableau-des-composants.mjs +138 -0
  74. package/scripts/verrou-de-machine.mjs +14 -13
  75. package/scripts/verrous/verrou.mjs +53 -16
  76. package/skills/developpeur/SKILL.md +4 -0
  77. package/skills/explorateur/SKILL.md +3 -1
  78. package/skills/grill/SKILL.md +9 -1
  79. package/skills/pitmaster/SKILL.md +12 -3
  80. package/skills/pitmaster/references/consigne-agent.md +3 -3
  81. package/skills/redacteur/references/documents-d-un-composant.md +12 -0
  82. package/skills/relecteur/SKILL.md +6 -2
  83. package/skills/testwriter/SKILL.md +29 -6
@@ -0,0 +1,306 @@
1
+ // The composition of the modules of language a project declares (scripts/langages.mjs,
2
+ // `langageDe`), as Bazel and Nx run one list of targets, one tool per language, each target of one
3
+ // language alone: a project has several languages, a package one. The composition answers what the
4
+ // core asks of a language (scripts/jointure.d.ts, `Composition`), by asking each module.
5
+ //
6
+ // - One module declared: the composition is the module itself.
7
+ // - The components are each module's, in the order of the declaration. A folder two modules claim
8
+ // is refused, named with both languages: a package has one language. A file belongs to the
9
+ // module of the component that holds it, the deepest (`moduleDuFichier`); a file out of every
10
+ // component stays the core's, as with one language: the first module, in the order of the
11
+ // declaration, whose answer is not null judges it (`estUnTest`, `manifestes.horsDesTests`).
12
+ // - Whether a component plays tests, the readers of components and the components touched are
13
+ // each module's on its own components, the results joined: a name without supplier is without
14
+ // supplier in every module, a file out of the graph is out of every module's graph.
15
+ // - The elements of a lot are every module's; a changed source that no element reads is the one
16
+ // its own module names (every module, for a file out of every component); the lot is impossible
17
+ // when one module cannot read it, its reason named with its language.
18
+ // - The verdict of a run is every module's, read in the same results directory, where each module
19
+ // writes under names of its own (scripts/resultats.mjs).
20
+ // - Each command a module describes is the composed command by its name
21
+ // (./commandes-composees.mjs), which plays it in each module that describes it and joins their
22
+ // codes.
23
+ // - The guards, the generated files, the migrations, the shared test material: every module's, in
24
+ // the order of the declaration; but the index of the interfaces, which each module generates:
25
+ // one of the core (./index-interfaces.mjs), assembled from each module's entries, its command
26
+ // (`index-interfaces`), its generated file and its guard in place of the modules', at the place
27
+ // of the first. What the role lock, the envelope and the update ask (the lock
28
+ // files, the outputs, the rules of the roles, the tools, the binaries, the directories to
29
+ // ignore): the union, each once.
30
+ import { existsSync, readFileSync } from 'node:fs';
31
+ import path from 'node:path';
32
+ import { fileURLToPath } from 'node:url';
33
+
34
+ // The scripts of the commands above the composition, named by their paths, never imported: the
35
+ // one that plays a composed command (./commandes-composees.mjs), and the index of the interfaces
36
+ // (./index-interfaces.mjs).
37
+ const ICI = path.dirname(fileURLToPath(import.meta.url));
38
+ const COMMANDES_COMPOSEES = path.join(ICI, 'commandes-composees.mjs');
39
+ const INDEX = path.join(ICI, 'index-interfaces.mjs');
40
+ /** The index of the interfaces, from the root. */
41
+ export const INDEX_DES_INTERFACES = 'docs/agents/index-des-interfaces.md';
42
+
43
+ /**
44
+ * The index of the interfaces of the project at <racine>, from the modules <modules>: each one's
45
+ * entries (`entreesDeLIndex`), in the order of their paths, an interface two modules give (the
46
+ * root's) once, the first module's.
47
+ * @param {string} racine
48
+ * @param {import('./jointure.js').Langage[]} modules
49
+ */
50
+ export function indexDesInterfaces(racine, modules) {
51
+ const parRel = new Map();
52
+ for (const m of modules) {
53
+ for (const e of m.entreesDeLIndex(racine)) {
54
+ if (!parRel.has(e.rel)) {
55
+ parRel.set(e.rel, e.lignes);
56
+ }
57
+ }
58
+ }
59
+ const corps = [...parRel]
60
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
61
+ .flatMap(([, lignes]) => lignes);
62
+ return [
63
+ '# Index des interfaces',
64
+ '',
65
+ 'Généré par `npx grillhouse index-interfaces` depuis les `INTERFACE.md` de chaque langage ; ne pas éditer.',
66
+ "Une ligne par composant, puis, selon son langage, une par élément qu'il fournit ; l'interface donne le détail.",
67
+ '',
68
+ ...corps,
69
+ ].join('\n');
70
+ }
71
+
72
+ /**
73
+ * The findings of the check of the index of the project at <racine>: none when it is up to date.
74
+ * @param {string} racine
75
+ * @param {import('./jointure.js').Langage[]} modules
76
+ */
77
+ export function indexEnRetard(racine, modules) {
78
+ const cible = path.join(racine, INDEX_DES_INTERFACES);
79
+ const present = existsSync(cible) ? readFileSync(cible, 'utf8') : '';
80
+ return present === indexDesInterfaces(racine, modules)
81
+ ? []
82
+ : [
83
+ {
84
+ fichier: INDEX_DES_INTERFACES,
85
+ message: `${INDEX_DES_INTERFACES} n'est pas à jour avec les interfaces : npx grillhouse index-interfaces le régénère.`,
86
+ },
87
+ ];
88
+ }
89
+
90
+ const unique = liste => [...new Set(liste)];
91
+ // The index of the interfaces, which each module generates, and its command: one of the core
92
+ // for several languages (./index-interfaces.mjs).
93
+ const INDEX_COMMANDE = 'index-interfaces';
94
+ const deLIndex = e => e.fichiers.includes(INDEX_DES_INTERFACES);
95
+ const sous = (dossier, abs) => abs === dossier || abs.startsWith(`${dossier}${path.sep}`);
96
+
97
+ /**
98
+ * The components of the modules <modules> in the repository at <racine>, each with its module:
99
+ * `[{ composant, module }]`, in the order of the declaration. Throws when two modules claim a
100
+ * folder.
101
+ * @param {import('./jointure.js').Langage[]} modules
102
+ * @param {string} racine
103
+ */
104
+ export function composantsRanges(modules, racine) {
105
+ const ranges = modules.flatMap(module =>
106
+ module.composants(racine).map(composant => ({ composant, module }))
107
+ );
108
+ const parDossier = new Map();
109
+ for (const r of ranges) {
110
+ const deja = parDossier.get(r.composant.dossier);
111
+ if (deja && deja.module !== r.module) {
112
+ const rel = path.relative(racine, r.composant.dossier) || '.';
113
+ throw new Error(
114
+ `⛔ ${rel} : revendiqué par ${deja.module.nom} et ${r.module.nom} ; un paquet n'a qu'un seul langage.`
115
+ );
116
+ }
117
+ parDossier.set(r.composant.dossier, r);
118
+ }
119
+ return ranges;
120
+ }
121
+
122
+ /**
123
+ * The module of the component that holds <fichier> (absolute, or from <racine>), the deepest;
124
+ * null when no component of <modules> holds it.
125
+ * @param {import('./jointure.js').Langage[]} modules
126
+ * @param {string} racine
127
+ * @param {string} fichier
128
+ */
129
+ export function moduleDuFichier(modules, racine, fichier) {
130
+ return rangeDe(composantsRanges(modules, racine), racine, fichier)?.module ?? null;
131
+ }
132
+
133
+ function rangeDe(ranges, racine, fichier) {
134
+ const abs = path.resolve(racine, fichier);
135
+ return (
136
+ ranges
137
+ .filter(r => sous(r.composant.dossier, abs))
138
+ .sort((a, b) => b.composant.dossier.length - a.composant.dossier.length)[0] ?? null
139
+ );
140
+ }
141
+
142
+ // The answer of the module of <fichier>'s component, else the first of <modules> not null.
143
+ function premiereReponse(modules, racine, fichier, demander) {
144
+ const proprietaire = moduleDuFichier(modules, racine, fichier);
145
+ if (proprietaire) {
146
+ return demander(proprietaire);
147
+ }
148
+ for (const m of modules) {
149
+ const r = demander(m);
150
+ if (r !== null) {
151
+ return r;
152
+ }
153
+ }
154
+ return null;
155
+ }
156
+
157
+ /**
158
+ * The composition of <modules>, in the order of the declaration; the module itself for one.
159
+ * @param {import('./jointure.js').Langage[]} modules
160
+ * @returns {import('./jointure.js').Composition}
161
+ */
162
+ export function composer(modules) {
163
+ if (modules.length === 1) {
164
+ return modules[0];
165
+ }
166
+ const ranges = racine => composantsRanges(modules, racine);
167
+ const moduleDe = (racine, fichier) => moduleDuFichier(modules, racine, fichier);
168
+ const moduleDuComposant = (racine, composant) =>
169
+ ranges(racine).find(r => r.composant.dossier === composant.dossier)?.module ?? null;
170
+ const leurs = (racine, liste) =>
171
+ new Map(modules.map(m => [m, liste.filter(c => moduleDuComposant(racine, c) === m)]));
172
+ return {
173
+ nom: modules.map(m => m.nom).join('+'),
174
+ outils: unique(modules.flatMap(m => m.outils)),
175
+ binaires: Object.assign({}, ...modules.map(m => m.binaires)),
176
+ ignorer: unique(modules.flatMap(m => m.ignorer)),
177
+ sorties: {
178
+ ecrites: unique(modules.flatMap(m => m.sorties.ecrites)),
179
+ propres: unique(modules.flatMap(m => m.sorties.propres)),
180
+ lues: unique(modules.flatMap(m => m.sorties.lues)),
181
+ },
182
+ droits: unique(modules.flatMap(m => m.droits)),
183
+ composants: racine => ranges(racine).map(r => r.composant),
184
+ composantDe: (racine, fichier) => rangeDe(ranges(racine), racine, fichier)?.composant ?? null,
185
+ matieres: racine => modules.flatMap(m => m.matieres(racine)),
186
+ joueDesTests: (racine, composant) =>
187
+ moduleDuComposant(racine, composant)?.joueDesTests(racine, composant) ?? false,
188
+ lecteurs(racine, o) {
189
+ const composants = leurs(racine, o.composants);
190
+ const nommes = leurs(racine, o.nommes);
191
+ const parts = modules
192
+ .filter(m => composants.get(m).length)
193
+ .map(m =>
194
+ m.lecteurs(racine, { ...o, composants: composants.get(m), nommes: nommes.get(m) })
195
+ );
196
+ const pasFaits = parts.filter(p => p.types.etat !== 'fait');
197
+ return {
198
+ elements: parts.flatMap(p => p.elements),
199
+ sansFournisseur: parts.length
200
+ ? parts[0].sansFournisseur.filter(n => parts.every(p => p.sansFournisseur.includes(n)))
201
+ : [...o.noms],
202
+ types: {
203
+ etat: pasFaits[0]?.types.etat ?? 'fait',
204
+ raison:
205
+ pasFaits
206
+ .map(p => p.types.raison)
207
+ .filter(Boolean)
208
+ .join(' ; ') || null,
209
+ elements: parts.flatMap(p => p.types.elements),
210
+ },
211
+ lit: new Map(parts.flatMap(p => [...p.lit])),
212
+ parLesTests: new Map(parts.flatMap(p => [...p.parLesTests])),
213
+ };
214
+ },
215
+ touches(racine, o) {
216
+ const parts = modules.map(m => m.touches(racine, o));
217
+ const touches = parts.flatMap(p => p.touches);
218
+ const vus = new Set(touches.map(c => c.dossier));
219
+ return {
220
+ touches,
221
+ dependants: parts.flatMap(p => p.dependants).filter(c => !vus.has(c.dossier)),
222
+ horsGraphe: parts[0].horsGraphe.filter(f => parts.every(p => p.horsGraphe.includes(f))),
223
+ };
224
+ },
225
+ elementsDuLot(racine, o) {
226
+ const parts = modules.map(m => ({ m, l: m.elementsDuLot(racine, o) }));
227
+ const impossibles = parts.filter(p => p.l.etat !== 'fait');
228
+ const horsDuService = unique(parts.flatMap(p => p.l.horsDuService)).filter(f => {
229
+ const proprietaire = moduleDe(racine, f);
230
+ return parts
231
+ .filter(p => (proprietaire ? p.m === proprietaire : true))
232
+ .every(p => p.l.horsDuService.includes(f));
233
+ });
234
+ return {
235
+ etat: impossibles.length ? 'impossible' : 'fait',
236
+ raison: impossibles.length
237
+ ? impossibles.map(p => `${p.m.nom} : ${p.l.raison}`).join(' ; ')
238
+ : null,
239
+ elements: parts.flatMap(p => p.l.elements),
240
+ horsDuService: horsDuService.sort(),
241
+ fichiers: unique(parts.flatMap(p => p.l.fichiers)).sort(),
242
+ };
243
+ },
244
+ commandes: racine =>
245
+ Object.fromEntries(
246
+ unique(modules.flatMap(m => Object.keys(m.commandes(racine)))).map(nom => [
247
+ nom,
248
+ nom === INDEX_COMMANDE
249
+ ? { script: INDEX, args: [] }
250
+ : { script: COMMANDES_COMPOSEES, args: [nom] },
251
+ ])
252
+ ),
253
+ verdict(dossier) {
254
+ const parts = modules.map(m => m.verdict(dossier));
255
+ return {
256
+ rapports: parts.flatMap(p => p.rapports),
257
+ taches: parts.flatMap(p => p.taches),
258
+ };
259
+ },
260
+ estUnTest: (chemin, racine) =>
261
+ premiereReponse(modules, racine, chemin, m => m.estUnTest(chemin, racine)),
262
+ manifestes: {
263
+ verrous: unique(modules.flatMap(m => m.manifestes.verrous)),
264
+ horsDesTests: (chemin, racine, avant, apres) =>
265
+ premiereReponse(modules, racine, chemin, m =>
266
+ m.manifestes.horsDesTests(chemin, racine, avant, apres)
267
+ ),
268
+ },
269
+ fichiersEngendres(racine) {
270
+ const tous = modules.flatMap(m => m.fichiersEngendres(racine));
271
+ const index = tous.filter(deLIndex);
272
+ if (index.length === 0) {
273
+ return tous;
274
+ }
275
+ const reste = tous.filter(e => !deLIndex(e));
276
+ reste.splice(tous.findIndex(deLIndex), 0, {
277
+ nom: index[0].nom,
278
+ commande: `node ${JSON.stringify(INDEX)}`,
279
+ fichiers: [INDEX_DES_INTERFACES],
280
+ lit: unique(index.flatMap(e => e.lit)),
281
+ gardes: unique(index.flatMap(e => e.gardes)),
282
+ entiers: [INDEX_DES_INTERFACES],
283
+ verifier: r => indexEnRetard(r, modules),
284
+ });
285
+ return reste;
286
+ },
287
+ gardes(racine) {
288
+ const tous = modules.flatMap(m => m.gardes(racine));
289
+ const noms = new Set(
290
+ modules
291
+ .flatMap(m => m.fichiersEngendres(racine))
292
+ .filter(deLIndex)
293
+ .flatMap(e => e.gardes)
294
+ );
295
+ if (noms.size === 0) {
296
+ return tous;
297
+ }
298
+ const deLaGarde = g => noms.has(path.basename(g[0]).replace(/\.[cm]?js$/, ''));
299
+ const reste = tous.filter(g => !deLaGarde(g));
300
+ const i = tous.findIndex(deLaGarde);
301
+ reste.splice(i < 0 ? reste.length : i, 0, [INDEX, '--verifier']);
302
+ return reste;
303
+ },
304
+ migrations: modules.flatMap(m => m.migrations),
305
+ };
306
+ }
@@ -30,8 +30,7 @@
30
30
  // - elementsDuLot: each file the lot of the entry changes, each changed source the module reads no
31
31
  // element of, and each element it adds, changes or removes;
32
32
  // - matieres: each component of the shared test material of the repository of the entry;
33
- // - joueDesTests: each component of the repository of the entry that plays tests;
34
- // - trouve: each repository of the entry where the module finds its language.
33
+ // - joueDesTests: each component of the repository of the entry that plays tests.
35
34
  import { existsSync, readdirSync, statSync } from 'node:fs';
36
35
  import { tmpdir } from 'node:os';
37
36
  import path from 'node:path';
@@ -183,7 +182,6 @@ export function cas(langage, exemples, { dans = tmpdir() } = {}) {
183
182
  .composants(racine)
184
183
  .filter(c => langage.joueDesTests(racine, c))
185
184
  .map(c => `${nommer(c)} : joue des tests`),
186
- trouve: depots => depots.filter(d => langage.trouve(d.racine)).map(d => `${d.nom} : trouvé`),
187
185
  };
188
186
  const invalides = {
189
187
  gardes: [...e.gardes.valide, 'garde-inexistante'],
@@ -1,10 +1,14 @@
1
1
  #!/usr/bin/env node
2
2
  // The removal of the working copies whose content is on main, run by the night once its steps
3
- // are played (scripts/nuit.sh), as `git worktree prune` and the workspace cleanup at the end of a
4
- // CI pipeline (Jenkins « Workspace Cleanup »): no copy outlives the entry of its content on main.
3
+ // are played (scripts/nuit.sh) and at the end of each circuit (scripts/circuit.mjs,
4
+ // `retirerLesCopiesDuDepot`), as `git worktree prune` and the workspace cleanup at the end of a
5
+ // CI pipeline (Jenkins « Workspace Cleanup »): no copy outlives the entry of its content on main,
6
+ // and no target directory its ticket (grillhouse-cyr: 34 GB of target/ under synthhub's copies).
5
7
  //
6
8
  // node scripts/copies-finies.mjs [<copie à garder>…] from the main tree of the repository
7
9
  //
10
+ // - The night's copy (`.claude/worktrees/nuit`) is always left out: the night prepares and
11
+ // removes its own.
8
12
  // - First `git worktree prune`: a copy whose folder is gone leaves the list. Then each copy
9
13
  // `git worktree list` names, the main tree and the copies named on the command line (the
10
14
  // night's) left out, passes through scripts/retirer-copie.sh, without `--jetable`: a copy whose
@@ -17,25 +21,46 @@
17
21
  // scripts/circuit.mjs), or, for the integration copy and the queue copy
18
22
  // (`.claude/worktrees/integration`, `.claude/worktrees/file`), their lock in git's common
19
23
  // directory (`integration.lock`, `file-integration.lock`, scripts/integration/). Tickets in
20
- // progress that do not read, or not within a minute, hold every copy: none is removed.
24
+ // progress that do not read, or not within a minute, hold every copy: none is removed. They are
25
+ // read only when a copy is left to judge: a repository with no copy but the night's calls no bd.
26
+ // A locked copy (`git worktree lock`, as Claude Code locks the copy of a live agent) stays too.
21
27
  // - A copy whose commits are not on main stays, its line naming the first path that has not
22
28
  // entered: retirer-copie.sh judges the local work alone, so the copy's HEAD is judged first, as
23
29
  // the removal judges local work: each path HEAD changed since its base with main holds the
24
30
  // content and the mode a commit of main after that base gave it (a cherry-pick or a rebase
25
31
  // counts, not the commit's identity). A detached HEAD's commits thus never become unreachable.
32
+ // A file the CHANGELOG's merge driver merges (`.gitattributes`, `merge=grillhouse-changelog`,
33
+ // scripts/fusion-du-changelog.mjs) enters main merged with the entries of the lots beside it:
34
+ // it counts as entered once each line not blank its commits added is a line of it on main.
35
+ // - The link `node_modules` of a copy to the main tree's install is no work: when it is all the
36
+ // local work of the copy, it goes before scripts/retirer-copie.sh judges the copy, which goes;
37
+ // beside other work, the copy keeps it, refused with its work.
38
+ // - A copy kept that no circuit holds, its ticket closed (read by `bd list --status closed`, once,
39
+ // the copy's folder bearing its id), loses what the tools of its languages wrote there,
40
+ // untracked by git (`git ls-files --others --directory`): each directory the module of the
41
+ // project's language names (`ignorer`: cargo's `target`, typescript's `.turbo`), and each
42
+ // `node_modules`, a link or a directory; its tracked work stays. A copy whose ticket is in
43
+ // progress, or open, keeps everything.
44
+ // - The line of each copy kept names the place it holds, as `du -sk` counts it (« 2,7 Go »).
26
45
  // - The branch of a copy removed goes (`git branch -D`), its content being HEAD's, on main; main
27
46
  // and a branch another copy holds stay.
28
47
  // - One line per copy removed or kept, on the output, which the night adds to its log. The exit is
29
48
  // 0 whatever is removed or kept: the removal never changes the night's verdict.
30
49
  import { spawnSync } from 'node:child_process';
31
- import { existsSync, realpathSync } from 'node:fs';
50
+ import { existsSync, lstatSync, realpathSync, rmSync } from 'node:fs';
32
51
  import path from 'node:path';
33
52
  import { pathToFileURL } from 'node:url';
53
+ import { PILOTE } from './fusion-du-changelog.mjs';
54
+ import { langageDe } from './langages.mjs';
34
55
 
35
56
  const RETIRER = path.join(import.meta.dirname, 'retirer-copie.sh');
36
57
  const PRINCIPALE = 'main';
37
58
  // The copies of the integration and of the queue, each held while its lock stands.
38
59
  const VERROUS = { integration: 'integration.lock', file: 'file-integration.lock' };
60
+ // The install of a copy: a link to the main tree's, or its own directory.
61
+ const INSTALLATION = 'node_modules';
62
+ // The copy of the night, its own to prepare and to remove (scripts/nuit.sh).
63
+ const NUIT = path.join('.claude', 'worktrees', 'nuit');
39
64
 
40
65
  const lancer = (dossier, cmd, args) =>
41
66
  spawnSync(cmd, args, { cwd: dossier, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
@@ -48,7 +73,8 @@ const reel = p => {
48
73
  }
49
74
  };
50
75
 
51
- // The copies `git worktree list` names: `{ chemin, tete, branche }`, the main tree first.
76
+ // The copies `git worktree list` names: `{ chemin, tete, branche, verrou }`, the main tree first;
77
+ // `verrou` the reason of a locked copy (`git worktree lock`), null for one unlocked.
52
78
  function lesCopies(racine) {
53
79
  return git(racine, 'worktree', 'list', '--porcelain')
54
80
  .stdout.split('\n\n')
@@ -58,11 +84,13 @@ function lesCopies(racine) {
58
84
  chemin: l[0].slice('worktree '.length),
59
85
  tete: l.find(x => x.startsWith('HEAD '))?.slice('HEAD '.length),
60
86
  branche: l.find(x => x.startsWith('branch refs/heads/'))?.slice('branch refs/heads/'.length),
87
+ verrou:
88
+ l.find(x => x === 'locked' || x.startsWith('locked '))?.slice('locked '.length) ?? null,
61
89
  }));
62
90
  }
63
91
 
64
- // What holds <chemin> for a running circuit, or null.
65
- function tenue(chemin, enCours, commun) {
92
+ // What holds the copy <chemin> for a running circuit or a live process (its lock), or null.
93
+ function tenue({ chemin, verrou: raison }, enCours, commun) {
66
94
  const nom = path.basename(chemin);
67
95
  if (existsSync(`${chemin}.travail`)) {
68
96
  return `son circuit a son dossier ${nom}.travail`;
@@ -70,6 +98,9 @@ function tenue(chemin, enCours, commun) {
70
98
  if (enCours.has(nom)) {
71
99
  return `le ticket ${nom} est en cours`;
72
100
  }
101
+ if (raison !== null) {
102
+ return `elle est verrouillée${raison ? ` (${raison})` : ''}`;
103
+ }
73
104
  const verrou = VERROUS[nom];
74
105
  if (verrou && path.dirname(chemin).endsWith(path.join('.claude', 'worktrees'))) {
75
106
  if (existsSync(path.join(commun, verrou))) {
@@ -79,14 +110,35 @@ function tenue(chemin, enCours, commun) {
79
110
  return null;
80
111
  }
81
112
 
113
+ // Whether <p> is merged by the frame's driver of the CHANGELOG (`.gitattributes`, `merge=<PILOTE>`).
114
+ const fusionneParLePilote = (racine, p) =>
115
+ git(racine, 'check-attr', 'merge', '--', p).stdout.trim().endsWith(`: merge: ${PILOTE}`);
116
+
117
+ // Whether each entry (a line not blank) the commits of <b> added to <p> since <base> is a line of
118
+ // <p> on main: a file the driver merges enters main merged with the entries of the lots beside it,
119
+ // never as the copy holds it.
120
+ function entreesSurMain(racine, base, b, p) {
121
+ const ajoutees = git(racine, 'diff', '-U0', '--no-renames', base, b, '--', p)
122
+ .stdout.split('\n')
123
+ .filter(l => l.startsWith('+') && !l.startsWith('+++') && l.slice(1).trim());
124
+ const surMain = git(racine, 'show', `${PRINCIPALE}:${p}`);
125
+ if (surMain.status !== 0) {
126
+ return false;
127
+ }
128
+ const lignes = new Set(surMain.stdout.split('\n'));
129
+ return ajoutees.every(l => lignes.has(l.slice(1)));
130
+ }
131
+
82
132
  // The first path the commit or branch <b> changed since its base with main whose content no commit of main
83
- // after that base gave, or null when all its content is on main.
133
+ // after that base gave, or null when all its content is on main. A file the CHANGELOG's driver
134
+ // merges counts as entered once each of its entries is on main (`entreesSurMain`).
84
135
  function pasEntre(racine, b) {
85
136
  const base = git(racine, 'merge-base', b, PRINCIPALE);
86
137
  if (base.status !== 0) {
87
138
  return `ses commits n'ont pas de base commune avec ${PRINCIPALE}`;
88
139
  }
89
- const chemins = git(racine, 'diff', '--name-only', '-z', '--no-renames', base.stdout.trim(), b)
140
+ const depuis = base.stdout.trim();
141
+ const chemins = git(racine, 'diff', '--name-only', '-z', '--no-renames', depuis, b)
90
142
  .stdout.split('\0')
91
143
  .filter(Boolean);
92
144
  for (const p of chemins) {
@@ -107,19 +159,68 @@ function pasEntre(racine, b) {
107
159
  const [, m, , i] = l.split(/\s+/);
108
160
  return m === mode && (i === id || (id === '0' && /^0+$/.test(i ?? '')));
109
161
  });
110
- if (!entre) {
162
+ if (!entre && !(fusionneParLePilote(racine, p) && entreesSurMain(racine, depuis, b, p))) {
111
163
  return `${p} n'est pas sur ${PRINCIPALE}`;
112
164
  }
113
165
  }
114
166
  return null;
115
167
  }
116
168
 
169
+ // The place <chemin> holds on the disk, as `du` counts it (a link not followed): « 2,7 Go ».
170
+ function place(chemin) {
171
+ const ko = Number.parseInt(lancer(chemin, 'du', ['-sk', chemin]).stdout, 10);
172
+ if (!Number.isFinite(ko)) {
173
+ return '? Go';
174
+ }
175
+ const [valeur, unite] =
176
+ ko >= 1024 * 1024 ? [ko / 1024 / 1024, 'Go'] : ko >= 1024 ? [ko / 1024, 'Mo'] : [ko, 'Ko'];
177
+ const texte = unite === 'Ko' ? String(valeur) : valeur.toFixed(1).replace('.', ',');
178
+ return `${texte} ${unite}`;
179
+ }
180
+
181
+ // What the tools of the languages wrote in the copy <chemin>, untracked by git: each directory of
182
+ // <ignorer> and each install (`node_modules`, a link or a directory), wherever git lists it as
183
+ // untracked; their paths from the copy.
184
+ function sortiesDesOutils(chemin, ignorer) {
185
+ const noms = new Set([...ignorer, INSTALLATION]);
186
+ return git(chemin, 'ls-files', '-z', '--others', '--directory')
187
+ .stdout.split('\0')
188
+ .map(p => p.replace(/\/$/, ''))
189
+ .filter(p => p && noms.has(path.basename(p)));
190
+ }
191
+
192
+ // Whether the link `node_modules` is the only local work of the copy <chemin>, as
193
+ // scripts/retirer-copie.sh reads it (`git status`, submodules included).
194
+ function seulLeLien(chemin) {
195
+ const r = git(chemin, 'status', '--porcelain', '-z', '--ignore-submodules=none');
196
+ return r.status === 0 && r.stdout === `?? ${INSTALLATION}\0`;
197
+ }
198
+
199
+ // Removes from the copy <chemin> what the tools of the languages wrote there; their paths.
200
+ function retirerLesSorties(chemin, ignorer) {
201
+ const retirees = sortiesDesOutils(chemin, ignorer);
202
+ for (const p of retirees) {
203
+ rmSync(path.join(chemin, p), { recursive: true, force: true });
204
+ }
205
+ return retirees;
206
+ }
207
+
117
208
  /**
118
209
  * Removes the copies of the repository at <racine> whose content is on main; returns one line per
119
- * copy removed or kept. <garder> names the copies left out (the night's); <enCours> the ids of the
120
- * tickets in progress, null when they do not read.
210
+ * copy removed or kept, a kept copy's with the place it holds. <garder> names the copies left out
211
+ * (the night's); <lireEnCours> reads the ids of the tickets in progress, null when they do not
212
+ * read: called once, and only when a copy is left to judge, as a cleanup with nothing to clean
213
+ * asks nothing; <lireFermes> reads the ids of the tickets closed, called once, when a copy is kept
214
+ * that no circuit holds. A copy kept whose ticket is closed loses what the tools of its languages
215
+ * wrote there (<ignorer>, the directories the module of the language names, and `node_modules`).
121
216
  */
122
- export function retirerLesCopiesFinies(racine, { garder = [], enCours }) {
217
+ export function retirerLesCopiesFinies(racine, { garder = [], lireEnCours, lireFermes, ignorer }) {
218
+ const [principale, ...listees] = lesCopies(racine);
219
+ const ecartees = new Set([principale?.chemin, ...garder].filter(Boolean).map(reel));
220
+ if (listees.every(c => ecartees.has(reel(c.chemin)))) {
221
+ return [];
222
+ }
223
+ const enCours = lireEnCours();
123
224
  if (enCours === null) {
124
225
  return ['✗ les tickets en cours ne se lisent pas (bd list) : aucune copie n’est retirée.'];
125
226
  }
@@ -130,31 +231,46 @@ export function retirerLesCopiesFinies(racine, { garder = [], enCours }) {
130
231
  '--path-format=absolute',
131
232
  '--git-common-dir'
132
233
  ).stdout.trim();
133
- const [principale, ...copies] = lesCopies(racine);
134
- const ecartees = new Set([principale?.chemin, ...garder].filter(Boolean).map(reel));
234
+ const copies = lesCopies(racine).slice(1);
135
235
  const ici = reel(racine);
136
236
  const vu = c => (path.relative(ici, reel(c)).startsWith('..') ? c : path.relative(ici, reel(c)));
137
237
  const lignes = [];
138
- for (const { chemin, tete, branche } of copies) {
238
+ let fermes;
239
+ // The line of the copy <chemin> kept for <raison>: what it lost when its ticket is closed, then
240
+ // the place it holds.
241
+ const gardee = (chemin, raison) => {
242
+ fermes ??= lireFermes() ?? new Set();
243
+ const perdues = fermes.has(path.basename(chemin)) ? retirerLesSorties(chemin, ignorer) : [];
244
+ const perte = perdues.length ? ` ; son ticket est fermé : ${perdues.join(', ')} retirés` : '';
245
+ return `· copie gardée : ${vu(chemin)} (${place(chemin)}) : ${raison}${perte}`;
246
+ };
247
+ for (const copie of copies) {
248
+ const { chemin, tete, branche } = copie;
139
249
  if (ecartees.has(reel(chemin))) {
140
250
  continue;
141
251
  }
142
- const raison = tenue(chemin, enCours, commun);
252
+ const raison = tenue(copie, enCours, commun);
143
253
  if (raison) {
144
- lignes.push(`· copie gardée : ${vu(chemin)} : ${raison}.`);
254
+ lignes.push(`· copie gardée : ${vu(chemin)} (${place(chemin)}) : ${raison}.`);
145
255
  continue;
146
256
  }
147
257
  const commits = tete ? pasEntre(racine, tete) : null;
148
258
  if (commits) {
149
- lignes.push(`· copie gardée : ${vu(chemin)} : ses commits ne sont pas entrés, ${commits}.`);
259
+ lignes.push(`${gardee(chemin, `ses commits ne sont pas entrés, ${commits}`)}.`);
150
260
  continue;
151
261
  }
262
+ // The copy's link to the main tree's install is no work: when it is all the copy carries, it
263
+ // goes, and the copy with it; beside other work, the copy is judged with it, and keeps it.
264
+ const lien = path.join(chemin, INSTALLATION);
265
+ if (lstatSync(lien, { throwIfNoEntry: false })?.isSymbolicLink() && seulLeLien(chemin)) {
266
+ rmSync(lien);
267
+ }
152
268
  const r = lancer(racine, 'bash', [RETIRER, chemin]);
153
269
  if (r.status !== 0) {
154
270
  const refus = String(r.stderr || r.stdout)
155
271
  .trim()
156
272
  .split('\n');
157
- lignes.push(`· copie gardée : ${vu(chemin)} : ${refus.join('\n ')}`);
273
+ lignes.push(gardee(chemin, refus.join('\n ')));
158
274
  continue;
159
275
  }
160
276
  let ligne = `✓ copie retirée : ${vu(chemin)}`;
@@ -175,10 +291,10 @@ export function retirerLesCopiesFinies(racine, { garder = [], enCours }) {
175
291
  return lignes;
176
292
  }
177
293
 
178
- // The ids of the tickets in progress, null when they do not read within LECTURE_MS.
294
+ // The ids of the tickets of status <statut>, null when they do not read within LECTURE_MS.
179
295
  const LECTURE_MS = 60_000;
180
- function ticketsEnCours(racine) {
181
- const r = spawnSync('bd', ['list', '--status', 'in_progress', '--limit', '0', '--json'], {
296
+ function tickets(racine, statut) {
297
+ const r = spawnSync('bd', ['list', '--status', statut, '--limit', '0', '--json'], {
182
298
  cwd: racine,
183
299
  encoding: 'utf8',
184
300
  maxBuffer: 256 * 1024 * 1024,
@@ -194,12 +310,35 @@ function ticketsEnCours(racine) {
194
310
  }
195
311
  }
196
312
 
197
- if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
198
- const racine = process.cwd();
199
- const lignes = retirerLesCopiesFinies(racine, {
200
- garder: process.argv.slice(2),
201
- enCours: ticketsEnCours(racine),
313
+ // The directories the tools of the project's language write (`ignorer` of its module), none for a
314
+ // project that declares no language.
315
+ function ignoresDuLangage(racine) {
316
+ try {
317
+ return langageDe(racine).ignorer;
318
+ } catch {
319
+ return [];
320
+ }
321
+ }
322
+
323
+ /**
324
+ * The removal of the copies of the repository at <racine> (`retirerLesCopiesFinies`), the copy of
325
+ * the night and the copies <garder> left out, the tickets read by bd: what the night and the end
326
+ * of each circuit (scripts/circuit.mjs) run. Its lines.
327
+ * @param {string} racine the main tree
328
+ * @param {string[]} [garder]
329
+ * @returns {string[]}
330
+ */
331
+ export function retirerLesCopiesDuDepot(racine, garder = []) {
332
+ return retirerLesCopiesFinies(racine, {
333
+ garder: [path.join(racine, NUIT), ...garder],
334
+ lireEnCours: () => tickets(racine, 'in_progress'),
335
+ lireFermes: () => tickets(racine, 'closed'),
336
+ ignorer: ignoresDuLangage(racine),
202
337
  });
338
+ }
339
+
340
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
341
+ const lignes = retirerLesCopiesDuDepot(process.cwd(), process.argv.slice(2));
203
342
  if (lignes.length) {
204
343
  process.stdout.write(`${lignes.join('\n')}\n`);
205
344
  }