@roomi-fields/grillhouse 0.47.1 → 0.49.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 (186) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +116 -0
  3. package/agents/direct.md +9 -0
  4. package/cadre/templates/projet/.github/workflows/ci.yml +24 -38
  5. package/cadre/templates/projet/.github/workflows/machine-vierge.yml +5 -0
  6. package/cadre/templates/projet/.github/workflows/nuit.yml +14 -2
  7. package/cadre/templates/projet/CLAUDE.md +31 -10
  8. package/cadre/templates/projet/docs/agents/issue-tracker.md +1 -1
  9. package/cadre/templates/turbo/paquets.json +3 -1
  10. package/cadre/templates/turbo/sans-paquets.json +3 -1
  11. package/charte.md +46 -13
  12. package/dist/temporal/circuit/appel.d.ts +4 -1
  13. package/dist/temporal/circuit/appel.js +15 -1
  14. package/dist/temporal/circuit/appel.js.map +1 -1
  15. package/dist/temporal/circuit/client.d.ts +7 -1
  16. package/dist/temporal/circuit/client.js +54 -1
  17. package/dist/temporal/circuit/client.js.map +1 -1
  18. package/dist/temporal/circuit/commande.js +35 -60
  19. package/dist/temporal/circuit/commande.js.map +1 -1
  20. package/dist/temporal/circuit/contrat.d.ts +2 -1
  21. package/dist/temporal/circuit/contrat.js +2 -1
  22. package/dist/temporal/circuit/contrat.js.map +1 -1
  23. package/dist/temporal/circuit/deroule.js +9 -2
  24. package/dist/temporal/circuit/deroule.js.map +1 -1
  25. package/dist/temporal/commande.js +2 -13
  26. package/dist/temporal/commande.js.map +1 -1
  27. package/dist/temporal/deroules.d.ts +1 -1
  28. package/dist/temporal/deroules.js +2 -2
  29. package/dist/temporal/deroules.js.map +1 -1
  30. package/dist/temporal/file/activites.d.ts +1 -4
  31. package/dist/temporal/file/activites.js +13 -14
  32. package/dist/temporal/file/activites.js.map +1 -1
  33. package/dist/temporal/file/contrat.d.ts +34 -91
  34. package/dist/temporal/file/contrat.js +33 -5
  35. package/dist/temporal/file/contrat.js.map +1 -1
  36. package/dist/temporal/file/deroule.d.ts +1 -9
  37. package/dist/temporal/file/deroule.js +57 -166
  38. package/dist/temporal/file/deroule.js.map +1 -1
  39. package/dist/temporal/installation.d.ts +26 -1
  40. package/dist/temporal/installation.js +111 -2
  41. package/dist/temporal/installation.js.map +1 -1
  42. package/dist/temporal/nuits/activites.d.ts +5 -10
  43. package/dist/temporal/nuits/activites.js +9 -57
  44. package/dist/temporal/nuits/activites.js.map +1 -1
  45. package/dist/temporal/nuits/choix.d.ts +15 -0
  46. package/dist/temporal/nuits/choix.js +20 -0
  47. package/dist/temporal/nuits/choix.js.map +1 -1
  48. package/dist/temporal/nuits/contrat.d.ts +11 -16
  49. package/dist/temporal/nuits/deroule.js +38 -67
  50. package/dist/temporal/nuits/deroule.js.map +1 -1
  51. package/dist/temporal/places/client.d.ts +9 -11
  52. package/dist/temporal/places/client.js +11 -19
  53. package/dist/temporal/places/client.js.map +1 -1
  54. package/dist/temporal/places/contrat.d.ts +25 -24
  55. package/dist/temporal/places/contrat.js +5 -7
  56. package/dist/temporal/places/contrat.js.map +1 -1
  57. package/dist/temporal/places/deroule.js +26 -36
  58. package/dist/temporal/places/deroule.js.map +1 -1
  59. package/dist/temporal/tickets/activites.js +4 -2
  60. package/dist/temporal/tickets/activites.js.map +1 -1
  61. package/dist/temporal/tickets/contrat.d.ts +2 -1
  62. package/docs/ARCHITECTURE.md +453 -133
  63. package/docs/CADRE.md +16 -13
  64. package/docs/INTERFACE.md +100 -25
  65. package/hooks/hooks.json +9 -0
  66. package/hooks/register.tsx +59 -5
  67. package/package.json +1 -1
  68. package/scripts/activites.mjs +319 -52
  69. package/scripts/aiguillage.mjs +5 -1
  70. package/scripts/attente-a-l-arret.mjs +2 -5
  71. package/scripts/attente-au-tour.mjs +2 -5
  72. package/scripts/bilan.mjs +125 -2
  73. package/scripts/branche-de-nuit.mjs +32 -44
  74. package/scripts/ci-de-main.mjs +215 -16
  75. package/scripts/circuit.mjs +275 -189
  76. package/scripts/circuits-cles.d.mts +3 -3
  77. package/scripts/circuits-cles.mjs +6 -5
  78. package/scripts/coeurs-dedies.mjs +4 -4
  79. package/scripts/commandes-composees.mjs +12 -5
  80. package/scripts/composition-des-langages.mjs +2 -0
  81. package/scripts/crochets.mjs +2 -2
  82. package/scripts/dette.d.ts +2 -1
  83. package/scripts/dette.mjs +49 -6
  84. package/scripts/direct.mjs +343 -0
  85. package/scripts/droits.mjs +19 -0
  86. package/scripts/effets.mjs +6 -5
  87. package/scripts/engendres.mjs +2 -1
  88. package/scripts/enveloppe/enveloppe.mjs +127 -18
  89. package/scripts/enveloppe/lancer.sh +14 -3
  90. package/scripts/enveloppe/paquets-du-plan.mjs +9 -0
  91. package/scripts/enveloppe/travail-de-la-copie.mjs +121 -21
  92. package/scripts/etapes.mjs +14 -4
  93. package/scripts/etat-du-depot.mjs +23 -0
  94. package/scripts/faits-du-circuit.mjs +24 -34
  95. package/scripts/fermeture-de-la-machine.d.mts +27 -0
  96. package/scripts/fermeture-de-la-machine.mjs +98 -0
  97. package/scripts/fichiers-nommes.mjs +27 -1
  98. package/scripts/file-des-tickets.d.mts +18 -1
  99. package/scripts/file-des-tickets.mjs +63 -15
  100. package/scripts/greffons.mjs +1 -1
  101. package/scripts/grillhouse-maj.mjs +13 -25
  102. package/scripts/groupe-cles.d.mts +6 -0
  103. package/scripts/groupe-cles.mjs +29 -1
  104. package/scripts/integration/file.mjs +162 -48
  105. package/scripts/integration/integrer.mjs +2 -0
  106. package/scripts/jointure.d.ts +22 -3
  107. package/scripts/journal-des-etats.d.mts +16 -0
  108. package/scripts/journal-des-etats.mjs +44 -2
  109. package/scripts/journal.mjs +3 -0
  110. package/scripts/langages/c/commandes.mjs +5 -5
  111. package/scripts/langages/c/composants.mjs +13 -5
  112. package/scripts/langages/c/index.mjs +2 -0
  113. package/scripts/langages/c/squelette.mjs +1 -1
  114. package/scripts/langages/cargo/commandes.mjs +5 -6
  115. package/scripts/langages/cargo/index.mjs +2 -0
  116. package/scripts/langages/python/commandes.mjs +5 -5
  117. package/scripts/langages/python/composants.mjs +10 -2
  118. package/scripts/langages/python/index.mjs +2 -0
  119. package/scripts/langages/typescript/composants.mjs +10 -3
  120. package/scripts/langages/typescript/construire.mjs +2 -0
  121. package/scripts/langages/typescript/exemples.mjs +33 -1
  122. package/scripts/langages/typescript/index.mjs +22 -0
  123. package/scripts/langages/typescript/migrations/0.49.0-tests-equipes.mjs +32 -0
  124. package/scripts/langages/typescript/module-absent.mjs +24 -0
  125. package/scripts/langages/typescript/tests-de-nuit.mjs +152 -32
  126. package/scripts/langages/typescript/tests-du-poste.mjs +65 -23
  127. package/scripts/langages/typescript/titres-de-tests.mjs +11 -7
  128. package/scripts/langages/typescript/turbo-des-paquets.mjs +40 -5
  129. package/scripts/langages/typescript/verifier.mjs +3 -5
  130. package/scripts/langages/typescript/verrou-des-dependances.mjs +161 -0
  131. package/scripts/langages/typescript/vitest-config/cibles.mjs +57 -6
  132. package/scripts/langages/typescript/vitest-config/lances.mjs +3 -1
  133. package/scripts/langages/typescript/vitest-config/machine.setup.mjs +11 -5
  134. package/scripts/langages/typescript/vitest.nuit.config.mjs +53 -5
  135. package/scripts/langages.mjs +25 -3
  136. package/scripts/machine.mjs +103 -0
  137. package/scripts/matieres-cles.mjs +17 -0
  138. package/scripts/matieres-lues.mjs +104 -0
  139. package/scripts/mesure/base-de-passe.mjs +2 -1
  140. package/scripts/migrations/0.48.0-ci-declenchee-par-la-file.mjs +32 -0
  141. package/scripts/migrations/0.48.0-poussee-retiree.mjs +31 -0
  142. package/scripts/migrations/0.49.0-reservation-de-trois-coeurs.mjs +30 -0
  143. package/scripts/migrations.mjs +6 -0
  144. package/scripts/nuit.sh +113 -46
  145. package/scripts/paquet.mjs +16 -5
  146. package/scripts/paquets.d.ts +4 -0
  147. package/scripts/paquets.mjs +57 -0
  148. package/scripts/passe-de-la-machine.mjs +13 -14
  149. package/scripts/places-de-la-machine.mjs +120 -44
  150. package/scripts/places-du-serveur.mjs +29 -8
  151. package/scripts/plafond-de-la-machine.d.mts +7 -13
  152. package/scripts/plafond-de-la-machine.mjs +19 -35
  153. package/scripts/poussee-retiree.mjs +18 -0
  154. package/scripts/prefixe-des-tickets.mjs +1 -1
  155. package/scripts/references-changees.mjs +159 -0
  156. package/scripts/registre.d.mts +2 -2
  157. package/scripts/regles-des-places.d.mts +20 -12
  158. package/scripts/regles-des-places.mjs +27 -30
  159. package/scripts/repli-de-la-nuit.mjs +112 -0
  160. package/scripts/reponses-du-circuit.d.mts +4 -2
  161. package/scripts/reponses-du-circuit.mjs +44 -9
  162. package/scripts/reprise.mjs +27 -8
  163. package/scripts/resultats.mjs +61 -9
  164. package/scripts/seances.mjs +258 -40
  165. package/scripts/services-du-noyau.mjs +3 -0
  166. package/scripts/sous-commandes.mjs +37 -7
  167. package/scripts/superviseur.mjs +241 -88
  168. package/scripts/tableau.mjs +327 -131
  169. package/scripts/taches-du-graphe.mjs +84 -4
  170. package/scripts/ticket.mjs +345 -0
  171. package/scripts/transitions.d.mts +52 -0
  172. package/scripts/transitions.mjs +194 -16
  173. package/scripts/un-commit-par-ticket.mjs +4 -3
  174. package/scripts/verdict-de-la-nuit.mjs +47 -20
  175. package/scripts/verrou-de-fichier.mjs +2 -2
  176. package/scripts/verrous/ecriture-hors-enveloppe.mjs +86 -0
  177. package/scripts/verrous/verrou.mjs +17 -1
  178. package/skills/developpeur/SKILL.md +1 -1
  179. package/skills/direct/SKILL.md +57 -0
  180. package/skills/explorateur/SKILL.md +10 -6
  181. package/skills/pitmaster/SKILL.md +37 -14
  182. package/skills/pitmaster/references/consigne-agent.md +7 -1
  183. package/skills/relecteur/SKILL.md +11 -1
  184. package/skills/testwriter/SKILL.md +10 -0
  185. package/scripts/poussee-cles.mjs +0 -46
  186. package/scripts/ticket.sh +0 -25
@@ -34,13 +34,44 @@
34
34
  // build failed and what was built, then its output, which the launcher puts in the session's
35
35
  // instruction. The exit code: 0 when the launch goes on, a build failure included; 1 for a step
36
36
  // that stops it; 2 for a malformed call.
37
+ // - `construirePourLesGardes` is the command `construire --gardes` of every module, which the checks
38
+ // of a plan play before its guards (scripts/activites.mjs, `commandesDuPlan`): a guard reads what
39
+ // the builds write, and its task of the graph waits for them (`dependsOn`, as the deps of a Bazel
40
+ // target), while the checks play the guard's script alone, in the envelope of the plan. It reads
41
+ // the runner's plan of the guard tasks the root holds a script for (`run grillhouse:gardes gardes
42
+ // --dry=json`), then plays every task of it but the guards (`lancerLesTaches`): the builds they
43
+ // wait for, replayed from the cache when nothing moved, side by side within the cores of the part
44
+ // the checks play on (`tachesCoteACote`, `--concurrency`). No guard script, or no task waited for:
45
+ // nothing plays, 0. Its exit code is the runner's, 1 for a plan the runner refuses.
37
46
  import { spawnSync } from 'node:child_process';
38
47
  import { closeSync, openSync, readFileSync, writeFileSync } from 'node:fs';
48
+ import { availableParallelism } from 'node:os';
39
49
  import path from 'node:path';
40
50
  import { lireLaListe } from './enveloppe/paquets-du-plan.mjs';
41
51
  import { paquets } from './paquets.mjs';
42
52
  import { langage } from './langages.mjs';
53
+ import { travailleursDeLaSeance } from './places-de-la-machine.mjs';
43
54
 
55
+ /** The guard scripts of the root, and their tasks of the graph: the frame's controls, then the
56
+ * project's own guards. */
57
+ export const SCRIPTS_DE_GARDES = ['grillhouse:gardes', 'gardes'];
58
+ /**
59
+ * The tasks a run of the graph plays side by side on <coeurs> cores: half of them, one at least,
60
+ * each task being itself parallel, as make's `-j` and Bazel's `--local_cpu_resources` bound a build
61
+ * by the machine. The pass of the verification and the build the guards wait for share it.
62
+ * @param {number} [coeurs]
63
+ */
64
+ export const tachesCoteACote = (coeurs = availableParallelism()) =>
65
+ Math.max(1, Math.floor(coeurs / 2));
66
+ /** The option of the command `construire` that builds what the guard tasks wait for. */
67
+ export const POUR_LES_GARDES = '--gardes';
68
+ /**
69
+ * Whether the arguments <args> of a command `construire` ask for a build of the graph, the core's
70
+ * one for every language (`construireDepuisLesArguments`), and not for the build of one package.
71
+ * @param {string[]} args
72
+ */
73
+ export const constructionDuGraphe = args =>
74
+ args.includes('--echec') || args.includes(POUR_LES_GARDES);
44
75
  /** The name of the script and of the task of the tests of a package, the same for every language. */
45
76
  export const SCRIPT_DES_TESTS = 'test:unit';
46
77
  // The variable that carries the paths and the options of a targeted run to the task of the tests.
@@ -105,9 +136,10 @@ export function nomDuPaquet(racine, dossier) {
105
136
  * <tests>, when given, is the content of the variable `TESTS_CIBLES` of the run (`{ arguments,
106
137
  * rejouer? }`); the variable of <env> never passes on. A red run names, through <dire>, each task
107
138
  * whose code is not 0, « ⛔ <tâche> (code N) », as the pass of the module typescript does.
139
+ * <coteACote>, when given, bounds the tasks played side by side (`--concurrency=<n>`).
108
140
  * @param {{ outil: string, racine: string, taches: string[], noms?: Iterable<string>,
109
141
  * tests?: { arguments: string[], rejouer?: string }, env?: NodeJS.ProcessEnv,
110
- * dire?: (ligne: string) => void }} o
142
+ * dire?: (ligne: string) => void, coteACote?: number }} o
111
143
  * @returns {number}
112
144
  */
113
145
  export function lancerLesTaches({
@@ -118,6 +150,7 @@ export function lancerLesTaches({
118
150
  tests,
119
151
  env = process.env,
120
152
  dire = l => process.stderr.write(`${l}\n`),
153
+ coteACote,
121
154
  }) {
122
155
  const e = { ...env };
123
156
  delete e[TESTS_CIBLES];
@@ -128,11 +161,12 @@ export function lancerLesTaches({
128
161
  // The runner's summary gives each task's verdict; kept in a named results directory, never left
129
162
  // in the project.
130
163
  const resume = ['--summarize'];
164
+ const borne = coteACote ? [`--concurrency=${coteACote}`] : [];
131
165
  const lanceur = langage('typescript');
132
166
  const avant = lanceur.resumesDuLancement(racine);
133
167
  const r = spawnSync(
134
168
  outil,
135
- ['run', ...taches, ...filtres, '--continue=dependencies-successful', ...resume],
169
+ ['run', ...taches, ...filtres, '--continue=dependencies-successful', ...borne, ...resume],
136
170
  { cwd: racine, stdio: 'inherit', env: e }
137
171
  );
138
172
  const verdicts = lanceur.garderLesResumes(racine, avant, e);
@@ -382,21 +416,67 @@ function construire(outil, racine, liste, echec) {
382
416
  }
383
417
  }
384
418
 
419
+ /**
420
+ * Builds what the guard tasks of the root at <racine> wait for in the graph, with <outil>: its exit
421
+ * code (see the header).
422
+ * @param {string} outil the task runner
423
+ * @param {string} racine the root of the copy
424
+ * @param {NodeJS.ProcessEnv} [env]
425
+ * @returns {number}
426
+ */
427
+ function construirePourLesGardes(outil, racine, env = process.env) {
428
+ let scripts = {};
429
+ try {
430
+ scripts = JSON.parse(readFileSync(path.join(racine, 'package.json'), 'utf8')).scripts ?? {};
431
+ } catch {
432
+ scripts = {};
433
+ }
434
+ const gardes = SCRIPTS_DE_GARDES.filter(s => typeof scripts[s] === 'string');
435
+ if (gardes.length === 0) {
436
+ return 0;
437
+ }
438
+ let graphe;
439
+ try {
440
+ graphe = plan(outil, racine, ['run', ...gardes]);
441
+ } catch (e) {
442
+ if (!(e instanceof Arret)) {
443
+ throw e;
444
+ }
445
+ process.stderr.write(`⛔ ${e.message} échoue.\n`);
446
+ return 1;
447
+ }
448
+ const attendues = (graphe.tasks ?? [])
449
+ .filter(t => !gardes.includes(t.task))
450
+ .map(t => t.taskId)
451
+ .sort();
452
+ if (attendues.length === 0) {
453
+ return 0;
454
+ }
455
+ // The builds side by side are bounded by the cores of the part the checks play on, as the pass of
456
+ // the verification bounds its tasks.
457
+ const coteACote = tachesCoteACote(travailleursDeLaSeance(env) ?? availableParallelism());
458
+ return lancerLesTaches({ outil, racine, taches: attendues, env, coteACote });
459
+ }
460
+
385
461
  /**
386
462
  * The command `construire --echec <fichier> <plan>` of a module, run from the root of the copy:
387
463
  * its exit code. <args> are the arguments after the command's name; a call without the file of a
388
- * failure and a plan is refused (2).
464
+ * failure and a plan is refused (2). `construire --gardes` builds what the guard tasks wait for
465
+ * (`construirePourLesGardes`).
389
466
  * @param {string} outil the task runner
390
467
  * @param {string[]} args
391
468
  * @param {string} [racine]
392
469
  * @returns {number}
393
470
  */
394
471
  export function construireDepuisLesArguments(outil, args, racine = process.cwd()) {
472
+ if (args.length === 1 && args[0] === POUR_LES_GARDES) {
473
+ return construirePourLesGardes(outil, racine);
474
+ }
395
475
  const i = args.indexOf('--echec');
396
476
  const echec = i >= 0 ? args[i + 1] : undefined;
397
477
  const reste = i >= 0 ? [...args.slice(0, i), ...args.slice(i + 2)] : args;
398
478
  if (!echec || reste.length !== 1) {
399
- process.stderr.write('usage: construire --echec <fichier> <plan>\n');
479
+ process.stderr.write('usage: construire --echec <fichier> <plan> | construire --gardes\n');
400
480
  return 2;
401
481
  }
402
482
  return construire(outil, racine, reste[0], echec);
@@ -0,0 +1,345 @@
1
+ #!/usr/bin/env node
2
+ // Creates a ticket under its mother, titled « <number> — <subject> — <components> », and prints its
3
+ // id: `grillhouse ticket <mother> <subject> <components> <body> [label]` (USAGE).
4
+ //
5
+ // The creation is played again without a second ticket (« create if not exists », the
6
+ // Idempotency-Key of a payment API): its key is the mother and the title. Before it creates, the
7
+ // command reads the children of the mother; a child that bears the title is the ticket: the
8
+ // command creates nothing, says so on the error stream and prints that id.
9
+ // - A closed child counts for a discovery alone, which is created closed: under any other label a
10
+ // closed ticket is no obstacle, and a defect that comes back gets a new ticket.
11
+ // - A child that bears the bare subject and the body of the request is a creation stopped before
12
+ // its title: the command finishes it (its title, the closure of a discovery). A bare subject
13
+ // with another body is someone else's ticket, left alone.
14
+ // - A reading that fails, or answers nothing, creates nothing.
15
+ //
16
+ // The reading and the creation are one step under a lock of the project, in the main tree, whose
17
+ // store of Beads the copies share (`.beads/grillhouse-ticket.lock`, scripts/verrou-de-fichier.mjs;
18
+ // Beads' own .gitignore leaves `*.lock` out of git): a creation launched while another still runs,
19
+ // its caller's delay passed, waits for it, then finds its ticket. The lock is judged by its age
20
+ // (5 min, a process number meaning nothing across envelopes) and written again after each call of
21
+ // Beads; one left by a command that was killed is taken over past that age. A command its caller
22
+ // cuts (SIGTERM, SIGINT) releases the lock before it ends, so that the next creation does not wait.
23
+ //
24
+ // Beads serves one process at a time (its embedded store is taken under an exclusive lock), and
25
+ // the command calls it two to four times: on a store other processes read, each call waits its
26
+ // turn. Past a threshold, the command says which call of Beads it waits for, and for how long.
27
+ import { spawn } from 'node:child_process';
28
+ import { readFileSync, utimesSync } from 'node:fs';
29
+ import path from 'node:path';
30
+ import { pathToFileURL } from 'node:url';
31
+ import { arbrePrincipal } from './outils-cles.mjs';
32
+ import { prefixe } from './prefixe-des-tickets.mjs';
33
+ import { lacherVerrou, prendreVerrou } from './verrou-de-fichier.mjs';
34
+
35
+ export const USAGE = [
36
+ 'Crée un ticket sous sa mère, titré « <numéro> — <sujet> — <composants> », et affiche son id.',
37
+ ' grillhouse ticket <mère> <sujet> <composants> <corps> [étiquette]',
38
+ 'Les composants tiennent en un argument, séparés par des virgules, le fournisseur d’abord :',
39
+ '« 020-loader, 050-emitter ».',
40
+ 'Un corps @<fichier> se lit dans ce fichier. L’étiquette vaut a-valider par défaut ;',
41
+ 'decouverte crée le ticket fermé (« découverte consignée »).',
42
+ 'Le numéro est l’id sans le préfixe entier du projet (la clé issue-prefix de .beads/config.yaml).',
43
+ 'Rejouée pour la même mère et le même titre, la commande ne crée rien : elle rend le ticket',
44
+ 'existant et le dit (un ticket fermé ne compte que pour une découverte).',
45
+ '',
46
+ ].join('\n');
47
+
48
+ // The label of a ticket that waits for the owner, the one of a discovery, and the reason a
49
+ // discovery is closed with.
50
+ const A_VALIDER = 'a-valider';
51
+ const DECOUVERTE = 'decouverte';
52
+ const CLOTURE = 'découverte consignée';
53
+
54
+ // The wait of one call of Beads after which the command says it, and the step between two lines.
55
+ const SEUIL_MS = 5_000;
56
+ const PAS_MS = 10_000;
57
+
58
+ /** The lock of the creations of tickets of a project, from the root of its main tree. */
59
+ export const VERROU = '.beads/grillhouse-ticket.lock';
60
+ /** The age past which that lock is abandoned. */
61
+ export const PERIME_MS = 5 * 60_000;
62
+ // The pause between two tries of the lock.
63
+ const ESSAI_MS = 200;
64
+ // The signals by which a caller cuts the command.
65
+ const COUPURES = ['SIGTERM', 'SIGINT'];
66
+
67
+ /**
68
+ * @typedef {{ status: number | null, stdout?: string, stderr?: string }} Reponse
69
+ * @typedef {(args: string[]) => Promise<Reponse>} Bd
70
+ * @typedef {{ mere: string, sujet: string, composants: string, corps: string, etiquette?: string }} Demande
71
+ */
72
+
73
+ /**
74
+ * The title of the ticket <id> of a project whose tickets bear <prefixeDuProjet>: its number (the
75
+ * id without the whole prefix), its subject and its components.
76
+ * @param {string} prefixeDuProjet
77
+ * @param {string} id
78
+ * @param {string} sujet
79
+ * @param {string} composants
80
+ */
81
+ export function titreDe(prefixeDuProjet, id, sujet, composants) {
82
+ const debut = `${prefixeDuProjet}-`;
83
+ return `${id.startsWith(debut) ? id.slice(debut.length) : id} — ${sujet} — ${composants}`;
84
+ }
85
+
86
+ /**
87
+ * Beads run with <args> in <cwd>: what it answers, its failure to start included (status 127).
88
+ * @param {string[]} args
89
+ * @param {string} cwd
90
+ * @returns {Promise<Reponse>}
91
+ */
92
+ export function lancerBd(args, cwd) {
93
+ return new Promise(resolve => {
94
+ const enfant = spawn('bd', args, { cwd, stdio: ['ignore', 'pipe', 'pipe'] });
95
+ let stdout = '';
96
+ let stderr = '';
97
+ enfant.stdout.on('data', d => (stdout += d));
98
+ enfant.stderr.on('data', d => (stderr += d));
99
+ enfant.on('error', e => resolve({ status: 127, stdout, stderr: e.message }));
100
+ enfant.on('close', status => resolve({ status: status ?? 1, stdout, stderr }));
101
+ });
102
+ }
103
+
104
+ // What <promesse> answers; while it lasts past <seuilMs>, then every <pasMs>, <dire> receives the
105
+ // call of Beads <quoi> the command waits for and for how long.
106
+ async function enDisantLAttente(promesse, quoi, { dire, seuilMs, pasMs }) {
107
+ const debut = Date.now();
108
+ let veille;
109
+ const dit = () => {
110
+ const secondes = Math.round((Date.now() - debut) / 1000);
111
+ dire(
112
+ `… grillhouse ticket attend la réponse de bd (${quoi}) depuis ${secondes} s : Beads sert un processus à la fois, et d’autres lisent ou écrivent les tickets du projet.\n`
113
+ );
114
+ veille = setTimeout(dit, pasMs);
115
+ };
116
+ veille = setTimeout(dit, seuilMs);
117
+ try {
118
+ return await promesse;
119
+ } finally {
120
+ clearTimeout(veille);
121
+ }
122
+ }
123
+
124
+ // What <f> returns, played under the lock <verrou>; while another creation holds it past
125
+ // <seuilMs>, then every <pasMs>, <dire> receives what the command waits for and for how long. A
126
+ // signal of COUPURES that <signaux> emits while the lock is held releases it, stops listening,
127
+ // then sends the signal again by <renvoyer>: the process ends by it, as one that never listened.
128
+ async function sousLeVerrou(verrou, { dire, seuilMs, pasMs, signaux, renvoyer }, f) {
129
+ const debut = Date.now();
130
+ let aDire = seuilMs;
131
+ while (!prendreVerrou(verrou, { attendre: false, perime: PERIME_MS })) {
132
+ const attendu = Date.now() - debut;
133
+ if (attendu >= aDire) {
134
+ dire(
135
+ `… grillhouse ticket attend la fin d’une autre création de ticket du projet depuis ${Math.round(attendu / 1000)} s (${verrou}).\n`
136
+ );
137
+ aDire = attendu + pasMs;
138
+ }
139
+ await new Promise(resolve => setTimeout(resolve, ESSAI_MS));
140
+ }
141
+ const sourd = () => {
142
+ for (const [signal, coupe] of coupes) {
143
+ signaux.off(signal, coupe);
144
+ }
145
+ };
146
+ const coupes = COUPURES.map(signal => [
147
+ signal,
148
+ () => {
149
+ lacherVerrou(verrou);
150
+ sourd();
151
+ renvoyer(signal);
152
+ },
153
+ ]);
154
+ for (const [signal, coupe] of coupes) {
155
+ signaux.on(signal, coupe);
156
+ }
157
+ try {
158
+ return await f();
159
+ } finally {
160
+ sourd();
161
+ lacherVerrou(verrou);
162
+ }
163
+ }
164
+
165
+ const premiereLigne = t =>
166
+ String(t ?? '')
167
+ .trim()
168
+ .split('\n')[0];
169
+
170
+ /**
171
+ * The ticket of <demande> under its mother, created unless a child of the mother already bears its
172
+ * title: `{ id, cree }`, `cree` false when the ticket existed; one creation of the project at a
173
+ * time, the others waiting for it. Throws, nothing created, when the prefix of the project at
174
+ * <racine> or the children of the mother cannot be read; throws with the call of Beads that failed
175
+ * otherwise.
176
+ * @param {Demande} demande
177
+ * @param {{ racine: string, bd: Bd, dire: (ligne: string) => void, seuilMs?: number, pasMs?: number, signaux?: Pick<NodeJS.EventEmitter, 'on' | 'off'>, renvoyer?: (signal: string) => void }} options
178
+ * `signaux` emits the signals that cut the command (the process by default), `renvoyer` sends
179
+ * one to the process again
180
+ * @returns {Promise<{ id: string, cree: boolean }>}
181
+ */
182
+ export async function creerLeTicket(
183
+ demande,
184
+ {
185
+ racine,
186
+ bd,
187
+ dire,
188
+ seuilMs = SEUIL_MS,
189
+ pasMs = PAS_MS,
190
+ signaux = process,
191
+ renvoyer = signal => void process.kill(process.pid, signal),
192
+ }
193
+ ) {
194
+ const duProjet = prefixe(racine);
195
+ const attente = { dire, seuilMs, pasMs, signaux, renvoyer };
196
+ const verrou = path.join(arbrePrincipal(racine), VERROU);
197
+ // The lock written again: a creation Beads makes wait is not taken for an abandoned one.
198
+ const tenu = async args => {
199
+ try {
200
+ return await bd(args);
201
+ } finally {
202
+ try {
203
+ const maintenant = new Date();
204
+ utimesSync(verrou, maintenant, maintenant);
205
+ } catch {
206
+ // the lock is gone: taken over past its age, the creation ends without it
207
+ }
208
+ }
209
+ };
210
+ return sousLeVerrou(verrou, attente, () =>
211
+ creerSousLeVerrou(demande, racine, duProjet, tenu, attente)
212
+ );
213
+ }
214
+
215
+ // The body of a request: the text of the file a body « @file » names, read from <racine>, else
216
+ // the body itself; null when that file does not read.
217
+ function texteDuCorps(corps, racine) {
218
+ if (!corps.startsWith('@')) {
219
+ return corps;
220
+ }
221
+ try {
222
+ return readFileSync(path.resolve(racine, corps.slice(1)), 'utf8');
223
+ } catch {
224
+ return null;
225
+ }
226
+ }
227
+
228
+ // The ticket of <demande> in the project at <racine>, whose tickets bear <duProjet>, found or
229
+ // created, the lock of the creations held.
230
+ async function creerSousLeVerrou(
231
+ { mere, sujet, composants, corps, etiquette: demandee },
232
+ racine,
233
+ duProjet,
234
+ bd,
235
+ { dire, seuilMs, pasMs }
236
+ ) {
237
+ const etiquette = demandee || A_VALIDER;
238
+ const titre = id => titreDe(duProjet, id, sujet, composants);
239
+ const appeler = async (...args) => {
240
+ const r = await enDisantLAttente(bd(args), args[0], { dire, seuilMs, pasMs });
241
+ if (r.status !== 0) {
242
+ throw new Error(`bd ${args[0]} : ${premiereLigne(r.stderr) || `code ${r.status}`}`);
243
+ }
244
+ return r.stdout ?? '';
245
+ };
246
+ const titrer = id => appeler('update', id, '--title', titre(id));
247
+ const clore = id => appeler('close', id, '-r', CLOTURE);
248
+
249
+ const lus = await appeler('list', '--parent', mere, '--all', '--limit', '0', '--json');
250
+ let enfants;
251
+ try {
252
+ enfants = JSON.parse(lus);
253
+ } catch (e) {
254
+ throw new Error(`bd list : les tickets sous ${mere} sont illisibles (${e.message})`);
255
+ }
256
+ if (!Array.isArray(enfants)) {
257
+ throw new Error(`bd list : les tickets sous ${mere} sont illisibles (aucune liste rendue)`);
258
+ }
259
+ const texte = texteDuCorps(corps, racine)?.trim();
260
+ const interrompu = t =>
261
+ t.title === sujet && texte !== undefined && String(t.description ?? '').trim() === texte;
262
+ const existant = enfants.find(
263
+ t =>
264
+ (t.status !== 'closed' || etiquette === DECOUVERTE) &&
265
+ (t.title === titre(t.id) || interrompu(t))
266
+ );
267
+ if (existant) {
268
+ const { id } = existant;
269
+ if (existant.title !== titre(id)) {
270
+ await titrer(id);
271
+ }
272
+ if (
273
+ etiquette === DECOUVERTE &&
274
+ existant.status !== 'closed' &&
275
+ (existant.labels ?? []).includes(DECOUVERTE)
276
+ ) {
277
+ await clore(id);
278
+ }
279
+ dire(`grillhouse ticket : ${id} existe déjà sous ${mere} avec ce titre, aucun ticket créé.\n`);
280
+ return { id, cree: false };
281
+ }
282
+
283
+ const source = corps.startsWith('@') ? ['--body-file', corps.slice(1)] : ['-d', corps];
284
+ const cree = await appeler(
285
+ 'create',
286
+ sujet,
287
+ '--parent',
288
+ mere,
289
+ '--no-inherit-labels',
290
+ '-t',
291
+ 'task',
292
+ '-l',
293
+ etiquette,
294
+ ...source,
295
+ '--silent'
296
+ );
297
+ const id = cree.trim().split('\n').at(-1) ?? '';
298
+ if (!id) {
299
+ throw new Error('bd create : aucun id rendu');
300
+ }
301
+ await titrer(id);
302
+ if (etiquette === DECOUVERTE) {
303
+ await clore(id);
304
+ }
305
+ return { id, cree: true };
306
+ }
307
+
308
+ /**
309
+ * The command played with <argv> in the project at <racine>: its exit code, 0 with the id of the
310
+ * ticket on <sortie>, 2 with its usage on <dire> under four arguments, 1 with the reason on <dire>
311
+ * otherwise.
312
+ * @param {string[]} argv
313
+ * @param {{ racine?: string, bd?: Bd, sortie?: (texte: string) => void, dire?: (texte: string) => void }} [options]
314
+ * @returns {Promise<number>}
315
+ */
316
+ export async function principal(
317
+ argv,
318
+ {
319
+ racine = process.cwd(),
320
+ bd = args => lancerBd(args, racine),
321
+ sortie = t => void process.stdout.write(t),
322
+ dire = t => void process.stderr.write(t),
323
+ } = {}
324
+ ) {
325
+ if (argv.length < 4) {
326
+ dire(USAGE);
327
+ return 2;
328
+ }
329
+ const [mere, sujet, composants, corps, etiquette] = argv;
330
+ try {
331
+ const { id } = await creerLeTicket(
332
+ { mere, sujet, composants, corps, etiquette },
333
+ { racine, bd, dire }
334
+ );
335
+ sortie(`${id}\n`);
336
+ return 0;
337
+ } catch (e) {
338
+ dire(`${e.message}\n`);
339
+ return 1;
340
+ }
341
+ }
342
+
343
+ if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) {
344
+ process.exitCode = await principal(process.argv.slice(2));
345
+ }
@@ -17,6 +17,11 @@ export interface EntreeDeLaTransition {
17
17
  ticket: { id: string; paquets: string[]; sorte: unknown; copie: string };
18
18
  reprend?: boolean;
19
19
  faits?: Record<string, unknown>;
20
+ /**
21
+ * The markers of the workflow of a ticket (`patched`), each true when the run carries it; a run
22
+ * recorded before a marker decides as before it.
23
+ */
24
+ marqueurs?: { attributionAvantSansLivraison?: boolean };
20
25
  }
21
26
 
22
27
  /** The next fact to read, with what the step decided before it; or the decision of the step. */
@@ -36,6 +41,45 @@ export const MEMOIRE: string[];
36
41
  /** The decision of the step of <entree>, or the next fact it needs. */
37
42
  export function transition(entree: EntreeDeLaTransition): Transition;
38
43
 
44
+ /** Where the run starts: the state and the memory it changes, or a refusal (`usage`). */
45
+ export function depart(entree: {
46
+ depuis?: string | null;
47
+ reprendre?: boolean;
48
+ marque?: boolean;
49
+ etat?: (Partial<EtatDeLaTransition> & { etape: string; raison?: string }) | null;
50
+ refus?: { rapport: string; [cle: string]: unknown } | null;
51
+ ticket?: string;
52
+ }): { suivant?: EtatDeLaTransition; memoire?: Record<string, unknown>; usage?: string };
53
+
54
+ /** What the testwriter receives of a developpeur's sheet that sends the red back; null without a sending. */
55
+ export function renvoiDe(entree: {
56
+ fiche: { renvoi?: { role: string } | null; raison?: string };
57
+ passation: string | null;
58
+ controlesRouges: string | null;
59
+ fichiersRouges?: string[];
60
+ }): string | null;
61
+
62
+ /** The test files the red output of checks names, each once. */
63
+ export function fichiersDeTestRouges(controlesRouges: string | null): string[];
64
+
65
+ /** The context `--etendre` gives the sessions of the run it resumes. */
66
+ export function contexteDeLExtension(entree: {
67
+ question?: unknown;
68
+ etendus: string[];
69
+ plan: string;
70
+ contexte: string | null;
71
+ }): string | null;
72
+
73
+ /** Where the circuit resumes when the supervisor extends the plan: `suivant` null without a state. */
74
+ export function etendre(entree: {
75
+ etat:
76
+ (Partial<EtatDeLaTransition> & { etape: string; raison?: string; question?: unknown }) | null;
77
+ etendus: string[];
78
+ plan: string;
79
+ contexte: string | null;
80
+ renvoi: { role: string } | null;
81
+ }): { suivant: EtatDeLaTransition | null; contexte?: string | null; reprend?: boolean };
82
+
39
83
  /** The state of the plan of a ticket: the explorateur's sheet, the questionneur's, the questions put, the answer. */
40
84
  export interface EtatDuPlan {
41
85
  plan: { questions: unknown[] } | null;
@@ -166,8 +210,16 @@ export function refusDeLaFile(issue?: { raison?: string | null; conflit?: boolea
166
210
  export function etapeApresLePlan(e: {
167
211
  sorte?: { genre?: string; comportement?: string } | null;
168
212
  sansTests?: boolean;
213
+ demande?: boolean;
169
214
  }): string;
170
215
 
216
+ /** The mark « the supervisor asked the testwriter » after a start: set by `--depuis testwriter`, kept by a `--reprendre` without `--depuis`, dropped otherwise. */
217
+ export function testwriterDemande(e: {
218
+ depuis?: string | null;
219
+ reprendre?: boolean;
220
+ marque?: boolean;
221
+ }): boolean;
222
+
171
223
  /** The step after a proof that passes: the developpeur, or the checks. */
172
224
  export function apresLaPreuve(e: {
173
225
  rouges: number;