@roomi-fields/grillhouse 0.31.0 → 0.32.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 (54) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +18 -0
  3. package/dist/temporal/installation.d.ts +3 -2
  4. package/dist/temporal/installation.js +7 -4
  5. package/dist/temporal/installation.js.map +1 -1
  6. package/dist/temporal/tickets/activites.d.ts +1 -0
  7. package/dist/temporal/tickets/activites.js +5 -0
  8. package/dist/temporal/tickets/activites.js.map +1 -1
  9. package/dist/temporal/tickets/contrat.d.ts +10 -0
  10. package/dist/temporal/tickets/deroule.js +8 -1
  11. package/dist/temporal/tickets/deroule.js.map +1 -1
  12. package/docs/ARCHITECTURE.md +71 -9
  13. package/docs/CADRE.md +10 -0
  14. package/docs/INTERFACE.md +9 -1
  15. package/hooks/hooks.json +4 -0
  16. package/package.json +1 -1
  17. package/scripts/activites.mjs +5 -7
  18. package/scripts/aiguillage.mjs +2 -0
  19. package/scripts/attente-au-tour.mjs +99 -0
  20. package/scripts/base-des-workflows.mjs +57 -0
  21. package/scripts/circuit.mjs +20 -1
  22. package/scripts/copies-finies.mjs +8 -1
  23. package/scripts/dernier-vert.mjs +30 -4
  24. package/scripts/effets.mjs +9 -0
  25. package/scripts/etapes.mjs +1 -1
  26. package/scripts/jointure.d.ts +4 -0
  27. package/scripts/journal-des-etats.d.mts +41 -0
  28. package/scripts/journal-des-etats.mjs +273 -0
  29. package/scripts/journal.mjs +119 -0
  30. package/scripts/langages/cargo/index.mjs +3 -0
  31. package/scripts/langages/python/index.mjs +2 -0
  32. package/scripts/langages/typescript/frontieres.mjs +46 -0
  33. package/scripts/langages/typescript/index.mjs +2 -0
  34. package/scripts/langages/typescript/verifier.mjs +33 -4
  35. package/scripts/langages/typescript/vitest-config/base.mjs +3 -0
  36. package/scripts/langages.d.mts +20 -0
  37. package/scripts/matiere-de-test.d.ts +11 -0
  38. package/scripts/nuit.sh +9 -0
  39. package/scripts/places-de-la-machine.mjs +6 -0
  40. package/scripts/sous-commandes.mjs +2 -0
  41. package/scripts/superviseur.mjs +127 -75
  42. package/scripts/tableau.mjs +99 -1
  43. package/scripts/ticket-du-circuit.mjs +37 -7
  44. package/scripts/transitions.mjs +18 -5
  45. package/skills/developpeur/SKILL.md +1 -1
  46. package/skills/explorateur/SKILL.md +1 -1
  47. package/skills/grill/SKILL.md +2 -56
  48. package/skills/grill/references/paquets.md +60 -0
  49. package/skills/pitmaster/SKILL.md +16 -27
  50. package/skills/questionneur/SKILL.md +1 -1
  51. package/skills/relecteur/SKILL.md +1 -1
  52. package/skills/testwriter/SKILL.md +7 -1
  53. package/skills/release/SKILL.md +0 -134
  54. package/skills/release/scripts/update-version.cjs +0 -92
@@ -0,0 +1,99 @@
1
+ #!/usr/bin/env node
2
+ // The signal of the supervisor's turn: the hook UserPromptSubmit of the mod runs it at each turn
3
+ // of a session of supervision (`npx grillhouse attente-au-tour`), and what it writes reaches the
4
+ // session. A question of a circuit must never stay mute because the wait in the background died
5
+ // unseen, as a review requested on GitHub is named again until it is answered.
6
+ //
7
+ // - It names each circuit that waits for the supervisor (`questionsEnAttente`, the one source of
8
+ // the opening and of the wait), a circuit ended without its issue included: its ticket, its
9
+ // question, the command that answers it, then the wait to launch again.
10
+ // - A question already gone up to the wait is named again: the file of the stops gone up is not
11
+ // read.
12
+ // - A wait that lives says it all: its lock (`attente-des-questions.lock`) names a live process,
13
+ // and nothing is said. A lock whose process is dead counts as no wait.
14
+ // - Out of a git repository, in an agent's copy (a worktree) and in the session of a role that
15
+ // the circuit launches (BEADS_ACTOR set), nothing is said.
16
+ // Exit 0, whatever it finds.
17
+ import { spawnSync } from 'node:child_process';
18
+ import { readFileSync } from 'node:fs';
19
+ import path from 'node:path';
20
+ import { pathToFileURL } from 'node:url';
21
+ import { circuitsDuServeur } from './circuits-du-serveur.mjs';
22
+ import { vivant } from './mesure/base-de-passe.mjs';
23
+ import { questionsEnAttente, ticketsFermes, verrouDeLAttente } from './superviseur.mjs';
24
+
25
+ // The process that the lock of the wait of the repository at <racine> names; null without a lock.
26
+ function tenant(racine) {
27
+ try {
28
+ return Number(/^(\d+)/.exec(readFileSync(verrouDeLAttente(racine), 'utf8'))?.[1]) || null;
29
+ } catch {
30
+ return null;
31
+ }
32
+ }
33
+
34
+ /**
35
+ * What the session of supervision in <dossier> reads at its turn: the circuits that wait for the
36
+ * supervisor, each with its ticket, its question and the command that answers it, then the wait to
37
+ * launch again; empty when a wait lives, when no circuit waits, or out of a session of supervision.
38
+ * @param {string} dossier the directory the session works in
39
+ * @param {{ env?: Record<string, string | undefined>,
40
+ * fermes?: (racine: string, ids: string[]) => Set<string>,
41
+ * circuitsDe?: (racine: string) => Promise<import('./circuits-du-serveur.mjs').CircuitDuServeur[]> }} options
42
+ * @returns {Promise<string>}
43
+ */
44
+ export async function attenteAuTour(
45
+ dossier,
46
+ { env = process.env, fermes = ticketsFermes, circuitsDe = circuitsDuServeur } = {}
47
+ ) {
48
+ if (env.BEADS_ACTOR) {
49
+ return '';
50
+ }
51
+ const r = spawnSync(
52
+ 'git',
53
+ ['-C', dossier, 'rev-parse', '--path-format=absolute', '--git-dir', '--git-common-dir'],
54
+ { encoding: 'utf8' }
55
+ );
56
+ if (r.status !== 0) {
57
+ return '';
58
+ }
59
+ const [dossierGit, commun] = r.stdout.trim().split('\n');
60
+ if (path.resolve(dossierGit) !== path.resolve(commun)) {
61
+ return '';
62
+ }
63
+ const racine = path.dirname(commun);
64
+ const vit = tenant(racine);
65
+ if (vit && vivant(vit)) {
66
+ return '';
67
+ }
68
+ let circuits;
69
+ try {
70
+ circuits = await circuitsDe(racine);
71
+ } catch {
72
+ return '';
73
+ }
74
+ const questions = questionsEnAttente(racine, circuits, { fermes });
75
+ if (!questions.length) {
76
+ return '';
77
+ }
78
+ return [
79
+ questions.length > 1
80
+ ? '## Circuits en attente du superviseur'
81
+ : "## Circuit en attente du superviseur",
82
+ ...questions.map(q =>
83
+ q.interrompu
84
+ ? `- ${q.ticket} a fini sans son issue, à ${q.etape} : \`${q.commande}\`.`
85
+ : [
86
+ `- ${q.ticket}, à ${q.etape} : ${q.question.replace(/\n/g, '\n ')}`,
87
+ ` La réponse : \`${q.commande}\`.`,
88
+ ].join('\n')
89
+ ),
90
+ "Aucune attente de fond ne vit : lance-la en arrière-plan (`run_in_background`) et surveille son flux (l'outil `Monitor`) : `npx grillhouse superviseur --attendre`.",
91
+ ].join('\n');
92
+ }
93
+
94
+ if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) {
95
+ const texte = await attenteAuTour(process.cwd());
96
+ if (texte) {
97
+ process.stdout.write(`${texte}\n`);
98
+ }
99
+ }
@@ -0,0 +1,57 @@
1
+ // The base of a pass in the workflows: a workflow that plays `verifier` gives it a base
2
+ // (`--base <commit>`, scripts/dernier-vert.mjs) for a push alone. A pull request, the call of the
3
+ // workflow by the release (workflow_call), the nightly schedule and any run without a push event play
4
+ // the complete pass, as `turbo --affected` takes its base (`TURBO_SCM_BASE`) from a push event.
5
+ //
6
+ // The control reads the text of each workflow of `.github/workflows`: a step that plays `verifier`
7
+ // with a base names, in its condition or in its own line, the event `push`, and, when it reads
8
+ // `github.event.before`, that this commit is not empty (the zeros of a first push are no base).
9
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
10
+ import path from 'node:path';
11
+ import { parse } from 'yaml';
12
+
13
+ const PUSH = /github\.event_name\s*==\s*'push'/;
14
+ const AVANT_NON_VIDE = /github\.event\.before\s*!=\s*''/;
15
+
16
+ // The faults of the base in the workflow of text <texte>, one line each; none when no step gives
17
+ // a base, or when each step that does is conditioned on a push.
18
+ export function erreursDeBase(texte) {
19
+ let flux;
20
+ try {
21
+ flux = parse(texte);
22
+ } catch (e) {
23
+ return [`le workflow ne se lit pas : ${e.message}`];
24
+ }
25
+ const erreurs = [];
26
+ for (const [nomDuJob, job] of Object.entries(flux?.jobs ?? {})) {
27
+ for (const etape of job?.steps ?? []) {
28
+ const run = String(etape.run ?? '');
29
+ if (!/\bverifier\b/.test(run) || !/--base\b/.test(run)) {
30
+ continue;
31
+ }
32
+ const t = `${job.if ?? ''}\n${etape.if ?? ''}\n${run}`;
33
+ const nom = `${nomDuJob} : ${etape.name ?? run.trim()}`;
34
+ if (!PUSH.test(t)) {
35
+ erreurs.push(`${nom} : la base se donne pour un push seulement (github.event_name == 'push')`);
36
+ } else if (/github\.event\.before/.test(t) && !AVANT_NON_VIDE.test(t)) {
37
+ erreurs.push(`${nom} : la base github.event.before se donne non vide (!= '')`);
38
+ }
39
+ }
40
+ }
41
+ return erreurs;
42
+ }
43
+
44
+ // The faults of the base in each workflow of `.github/workflows` of the repository at <racine>,
45
+ // each line led by the file.
46
+ export function erreursDesWorkflows(racine) {
47
+ const dossier = path.join(racine, '.github', 'workflows');
48
+ if (!existsSync(dossier)) {
49
+ return [];
50
+ }
51
+ return readdirSync(dossier)
52
+ .filter(f => /\.ya?ml$/.test(f))
53
+ .sort()
54
+ .flatMap(f =>
55
+ erreursDeBase(readFileSync(path.join(dossier, f), 'utf8')).map(e => `${f} : ${e}`)
56
+ );
57
+ }
@@ -260,7 +260,10 @@
260
260
  // of its paths and the content of each file it lists, taken before and after the session; the
261
261
  // sheet and the handover do not count) has nothing to deliver, the gesture `rien-a-livrer`, as a
262
262
  // CI skips a job without object: the checks judge the lot; green, the run goes on; red, the
263
- // circuit stops at « sans-livraison », its report sending to the developpeur's handover. A
263
+ // circuit stops at « sans-livraison », its report sending to the developpeur's handover; but the
264
+ // red of a reference the lot lowers, the debt of the guards (its notes `a-elaguer`), is
265
+ // regenerated (4.2) instead of stopping, and the checks of the plan play again on the
266
+ // regenerated tree. A
264
267
  // developpeur that `--depuis developpeur` launches on the lot the integration refused (`refus`,
265
268
  // the fingerprint of its plan), as a merge queue lets a lot it sends back pass again only with a
266
269
  // change, a session that changes nothing does not go to the checks of the copy, which do not see
@@ -691,6 +694,7 @@ import {
691
694
  sansCouleurs,
692
695
  } from './ticket-du-circuit.mjs';
693
696
  import { emettre } from './effets.mjs';
697
+ import { heureLocale } from './journal-des-etats.mjs';
694
698
  import { consigne, auLancement, idDeSeance, jusquALaFiche, seance } from './seances.mjs';
695
699
  import { releve } from './composants-affectes.mjs';
696
700
  import { ligneDEtape, transcriptionsDeLaCopie } from './registre.mjs';
@@ -876,6 +880,21 @@ export function ecrireEtat(ctx, etat) {
876
880
  rang: ctx.rang ?? null,
877
881
  };
878
882
  emettre(ctx, { genre: 'etat', etat: { ...ctx.courant, journal: ctx.journal } });
883
+ // The same transition, dated, in the journal of states (scripts/journal-des-etats.mjs): its
884
+ // loop the first counted, its reason the stop's name or the cause of the return, empty for a
885
+ // normal transition.
886
+ emettre(ctx, {
887
+ genre: 'trace',
888
+ ligne: {
889
+ ts: heureLocale(),
890
+ genre: 'circuit',
891
+ ticket: ctx.ticket,
892
+ etape: etat.etape,
893
+ boucle: Object.values(etat.boucles ?? {})[0] ?? null,
894
+ place: null,
895
+ raison: etat.raison ?? '',
896
+ },
897
+ });
879
898
  }
880
899
 
881
900
  // The register's line of the step <etape> the circuit led itself from <debut> (an ISO date) to
@@ -82,6 +82,7 @@ import path from 'node:path';
82
82
  import { PILOTE } from './fusion-du-changelog.mjs';
83
83
  import { langageDe } from './langages.mjs';
84
84
  import { balayerLesTickets } from './mesure/base-de-passe.mjs';
85
+ import { nettoyerLeJournal } from './journal-des-etats.mjs';
85
86
 
86
87
  const RETIRER = path.join(import.meta.dirname, 'retirer-copie.sh');
87
88
  const PRINCIPALE = 'main';
@@ -498,5 +499,11 @@ export function retirerLesCopiesDuDepot(racine, finies = [], vivants = null) {
498
499
  ignorer: ignoresDuLangage(racine),
499
500
  });
500
501
  const retires = balayerLesTickets(() => tickets(racine, 'closed'));
501
- return [...lignes, ...retires.map(t => `✓ dossier temporaire du ticket ${t} retiré.`)];
502
+ // The journal of states, bounded as the other working files (scripts/journal-des-etats.mjs).
503
+ const segments = nettoyerLeJournal(racine).retires;
504
+ return [
505
+ ...lignes,
506
+ ...retires.map(t => `✓ dossier temporaire du ticket ${t} retiré.`),
507
+ ...segments.map(s => `✓ segment ${s} du journal des états retiré.`),
508
+ ];
502
509
  }
@@ -173,6 +173,25 @@ function lireLeVertDe(etat, branche) {
173
173
  return { commit: v.commit, arbre: v.arbre, branche };
174
174
  }
175
175
 
176
+ // The base <base> given to a pass (`verifier --base <commit>`), when it counts for a pass in the
177
+ // state <etat>: `{ commit, arbre, branche: null }`, the tree of the commit; `{ raison }` when it
178
+ // has no value, is not a commit id, is not in the repository (the zeros of a first push, a
179
+ // rewritten history) or is not an ancestor of HEAD.
180
+ function lireLaBase(etat, base) {
181
+ if (!SHA.test(base)) {
182
+ return { raison: base ? 'la base n’est pas un commit' : 'la base est sans valeur' };
183
+ }
184
+ const arbre = sortie(etat.racine, ['rev-parse', '--verify', '-q', `${base}^{tree}`]);
185
+ const commit = sortie(etat.racine, ['rev-parse', '--verify', '-q', `${base}^{commit}`]);
186
+ if (!arbre || !commit) {
187
+ return { raison: 'la base n’est pas dans le dépôt' };
188
+ }
189
+ if (git(etat.racine, ['merge-base', '--is-ancestor', commit, etat.commit]).status !== 0) {
190
+ return { raison: 'la base n’est pas un ancêtre de HEAD' };
191
+ }
192
+ return { commit, arbre, branche: null };
193
+ }
194
+
176
195
  // Keeps <etat> (etatDuDepot) as the last green of its branch, of main when HEAD is detached.
177
196
  export function garderLeVert(etat) {
178
197
  const branche = etat.branche ?? etat.main;
@@ -228,7 +247,7 @@ function supprimesDuCommit(racine, commit, arbre) {
228
247
  // function that removes the file of the changes. <tout> asks for the complete pass; the file lies
229
248
  // in <dans>, the base of the pass (scripts/mesure/base-de-passe.mjs), which a killed pass
230
249
  // leaves to the next one to sweep.
231
- export function mesure(racine, { tout = false, dans = os.tmpdir() } = {}) {
250
+ export function mesure(racine, { tout = false, base, dans = os.tmpdir() } = {}) {
232
251
  const etat = etatDuDepot(racine);
233
252
  const complete = raison => ({
234
253
  etat: etat.raison ? null : etat,
@@ -242,7 +261,12 @@ export function mesure(racine, { tout = false, dans = os.tmpdir() } = {}) {
242
261
  if (tout) {
243
262
  return complete('demandée');
244
263
  }
245
- const vert = lireLeVert(etat);
264
+ // A base given takes precedence over the last green: the pass keeps no green of its own.
265
+ const donnee = base === undefined ? null : lireLaBase(etat, base);
266
+ if (donnee?.raison) {
267
+ return complete(donnee.raison);
268
+ }
269
+ const vert = donnee ?? lireLeVert(etat);
246
270
  if (vert.raison) {
247
271
  return complete(vert.raison);
248
272
  }
@@ -268,9 +292,11 @@ export function mesure(racine, { tout = false, dans = os.tmpdir() } = {}) {
268
292
  );
269
293
  const n = ch.fichiers.length + ch.supprimes.length;
270
294
  return {
271
- etat,
295
+ etat: donnee ? null : etat,
272
296
  env: { [CHANGEMENTS]: fichier },
273
- ligne: `↳ depuis le dernier vert de ${vert.branche} (${vert.commit.slice(0, 12)}, arbre ${vert.arbre.slice(0, 12)}) : ${n} fichier(s) changé(s) ; chaque paquet rejoué joue les tests que ses changements atteignent.`,
297
+ ligne: donnee
298
+ ? `↳ depuis la base ${vert.commit.slice(0, 7)} : ${n} fichier(s) changé(s) ; chaque paquet rejoué joue les tests que ses changements atteignent.`
299
+ : `↳ depuis le dernier vert de ${vert.branche} (${vert.commit.slice(0, 12)}, arbre ${vert.arbre.slice(0, 12)}) : ${n} fichier(s) changé(s) ; chaque paquet rejoué joue les tests que ses changements atteignent.`,
274
300
  retirer: () => rmSync(dir, { recursive: true, force: true }),
275
301
  };
276
302
  }
@@ -16,6 +16,8 @@
16
16
  // - `decouverte` `{ role, sujet, corps, composants }`: a discovery filed closed under the ticket
17
17
  // (scripts/ticket.sh, label `decouverte`), then its line among the sheets (`{ id, sujet }`);
18
18
  // - `registre` `{ ligne }`: a line of the register of the steps (scripts/registre.mjs);
19
+ // - `trace` `{ ligne }`: a line of the journal of states (scripts/journal-des-etats.mjs), whose
20
+ // failure is said once and never stops the circuit;
19
21
  // - `etat` `{ etat }`: the circuit's state, which the workflow of a ticket holds and no player writes
20
22
  // (src/temporal/circuit/deroule.ts);
21
23
  // - `plan` `{ titre, description }`: the plan written at the ticket (its title, its description);
@@ -39,6 +41,7 @@ import { appendFileSync, existsSync, readFileSync } from 'node:fs';
39
41
  import path from 'node:path';
40
42
  import { stripVTControlCharacters } from 'node:util';
41
43
  import { ecrireLeBilan } from './bilan.mjs';
44
+ import { ecrireLaTrace } from './journal-des-etats.mjs';
42
45
  import { ecrire as ecrireAuRegistre } from './registre.mjs';
43
46
 
44
47
  /** The line of HTML comment that carries the key <cle> in a text at a ticket. */
@@ -215,6 +218,12 @@ const JOUEURS = {
215
218
  return echec(e.message);
216
219
  }
217
220
  },
221
+ // A line of the journal of states: never an arrest, never a wait (ecrireLaTrace says a failure
222
+ // once and goes on).
223
+ trace(ctx, { ligne }) {
224
+ ecrireLaTrace(ctx.racine, ligne);
225
+ return ok;
226
+ },
218
227
  plan(ctx, { titre, description }) {
219
228
  const options = [
220
229
  ...(titre === null ? [] : ['--title', titre]),
@@ -218,7 +218,7 @@ export const GESTES = [
218
218
  genre: 'rien-a-livrer',
219
219
  geste: 'aux contrôles, qui jugent le lot',
220
220
  regle:
221
- 'un développeur qui ne change aucun fichier du plan n’a rien à livrer quand les contrôles sont verts ; rouges, l’arrêt monte (sans-livraison) ; sur le lot que l’intégration refuse, pour un développeur que --depuis developpeur lance, le geste ne joue pas : il est relancé une fois avec le refus',
221
+ 'un développeur qui ne change aucun fichier du plan n’a rien à livrer quand les contrôles sont verts ; rouges, l’arrêt monte (sans-livraison), sauf le rouge d’une référence que le lot fait baisser, la dette des gardes, qui se régénère au lieu d’arrêter ; sur le lot que l’intégration refuse, pour un développeur que --depuis developpeur lance, le geste ne joue pas : il est relancé une fois avec le refus',
222
222
  cas: 'BP 320.9 : 995-tools n’a rien à livrer, 4 montées et 49 min (B5)',
223
223
  },
224
224
  {
@@ -281,6 +281,10 @@ export interface Composition {
281
281
 
282
282
  /** A module of language, the default export of `scripts/langages/<nom>/index.mjs`. */
283
283
  export interface Langage extends Composition {
284
+ /** The programs of this language's toolchain (`cargo`, `python3`) that the installer of Temporal
285
+ * requires in its PATH, each refused by its name when absent; none for TypeScript, Node being a
286
+ * tool of the account. */
287
+ executables: string[];
284
288
  /** The manifest of a package of this language, in its folder (`package.json`, `Cargo.toml`):
285
289
  * the guard of the languages asks it of a package the architecture declares of this language. */
286
290
  manifeste: string;
@@ -0,0 +1,41 @@
1
+ // The types of the journal of states (./journal-des-etats.mjs).
2
+
3
+ /** A line of the journal of states. */
4
+ export interface LigneDuJournal {
5
+ ts: string;
6
+ genre: 'circuit' | 'file' | 'places';
7
+ ticket: string | null;
8
+ etape: string | null;
9
+ boucle: number | null;
10
+ place: string | null;
11
+ raison: string;
12
+ }
13
+
14
+ /** A trace to write: a line, `ts` set when it already has its date. */
15
+ export type Trace = Partial<LigneDuJournal> & { genre: LigneDuJournal['genre'] };
16
+
17
+ export const AGE_MAX_JOURS: number;
18
+ export const TAILLE_MAX: number;
19
+ export function heureLocale(date?: Date): string;
20
+ export function dossierDuJournal(racine: string): string;
21
+ export function ecrireLaTrace(
22
+ racine: string,
23
+ trace: Trace,
24
+ options?: { maintenant?: Date; dire?: (message: string) => void }
25
+ ): { ecrit: boolean };
26
+ export function traceDeLaFile(e: { ticket: string; evenement: 'lance' | 'termine' }): Trace;
27
+ export function traceDesPlaces(e: {
28
+ evenement: 'prise' | 'rendue' | 'attente';
29
+ ticket?: string | null;
30
+ place?: string | null;
31
+ raison?: string;
32
+ }): Trace;
33
+ export function lireLeJournal(
34
+ racine: string,
35
+ plage?: { depuis?: string; jusquA?: string; ticket?: string }
36
+ ): { lignes: LigneDuJournal[] };
37
+ export function nettoyerLeJournal(
38
+ racine: string,
39
+ options?: { maintenant?: Date; ageMaxJours?: number; tailleMax?: number }
40
+ ): { retires: string[] };
41
+ export function ensemblesEnTravail(lignes: LigneDuJournal[]): { ts: string; enTravail: string[] }[];
@@ -0,0 +1,273 @@
1
+ // The journal of states of a project (grillhouse-4nr.20, docs/ARCHITECTURE.md « Le journal des
2
+ // états »): one dated JSONL line per change of state of the circuits, the queue and the places, a
3
+ // segment per local date under the common git directory (`<git-common-dir>/grillhouse-journal/
4
+ // <YYYY-MM-DD>.jsonl`, never versioned), read back as a chronology. As the log of a scheduler: a
5
+ // whole line in one append, no lock, no wait, so that it never delays what it traces.
6
+ //
7
+ // A line: `{ ts, genre, ticket, etape, boucle, place, raison }`, `genre` one of `circuit`, `file`,
8
+ // `places`; `ts` ISO 8601 with the local offset; `raison` empty for a normal transition, the name
9
+ // of the stop for a stop, the cause of the return for a loop, the message of the wait for a wait
10
+ // for a place.
11
+ import { execFileSync } from 'node:child_process';
12
+ import {
13
+ appendFileSync,
14
+ existsSync,
15
+ mkdirSync,
16
+ readdirSync,
17
+ readFileSync,
18
+ statSync,
19
+ unlinkSync,
20
+ } from 'node:fs';
21
+ import path from 'node:path';
22
+
23
+ /** The age, in days, beyond which the cleaning removes a segment. */
24
+ export const AGE_MAX_JOURS = 14;
25
+ /** The total size, in bytes, beyond which the cleaning removes the oldest segments (50 Mo). */
26
+ export const TAILLE_MAX = 50 * 1024 * 1024;
27
+ // A line, its newline included, fits in this many bytes: an append of that size stays whole
28
+ // (POSIX `PIPE_BUF` order, the size git and journald hold their lines to).
29
+ const LIGNE_MAX = 4096;
30
+ const SEGMENT = /^(\d{4}-\d{2}-\d{2})\.jsonl$/;
31
+
32
+ const deux = n => String(n).padStart(2, '0');
33
+
34
+ /**
35
+ * <date> in ISO 8601 with the local offset (`2026-11-09T10:00:00.250+01:00`).
36
+ * @param {Date} [date]
37
+ * @returns {string}
38
+ */
39
+ export function heureLocale(date = new Date()) {
40
+ const d = date;
41
+ const decalage = -d.getTimezoneOffset();
42
+ const signe = decalage < 0 ? '-' : '+';
43
+ const h = Math.floor(Math.abs(decalage) / 60);
44
+ const m = Math.abs(decalage) % 60;
45
+ return (
46
+ `${d.getFullYear()}-${deux(d.getMonth() + 1)}-${deux(d.getDate())}` +
47
+ `T${deux(d.getHours())}:${deux(d.getMinutes())}:${deux(d.getSeconds())}` +
48
+ `.${String(d.getMilliseconds()).padStart(3, '0')}${signe}${deux(h)}:${deux(m)}`
49
+ );
50
+ }
51
+
52
+ const communs = new Map();
53
+
54
+ /**
55
+ * The directory of the journal of the project at <racine>: under its common git directory.
56
+ * @param {string} racine
57
+ * @returns {string}
58
+ * @throws {Error} when <racine> is no git project
59
+ */
60
+ export function dossierDuJournal(racine) {
61
+ let commun = communs.get(racine);
62
+ if (!commun) {
63
+ commun = execFileSync(
64
+ 'git',
65
+ ['-C', racine, 'rev-parse', '--path-format=absolute', '--git-common-dir'],
66
+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }
67
+ ).trim();
68
+ communs.set(racine, commun);
69
+ }
70
+ return path.join(commun, 'grillhouse-journal');
71
+ }
72
+
73
+ // The line of <trace> with every field, the raison cut so that the whole line, newline included,
74
+ // fits under LIGNE_MAX bytes (by characters, never through one).
75
+ function ligneEntiere(trace, ts) {
76
+ const champ = v => (v === undefined ? null : v);
77
+ const ligne = {
78
+ ts,
79
+ genre: trace.genre,
80
+ ticket: champ(trace.ticket),
81
+ etape: champ(trace.etape),
82
+ boucle: champ(trace.boucle),
83
+ place: champ(trace.place),
84
+ raison: trace.raison ?? '',
85
+ };
86
+ let raison = Array.from(String(ligne.raison));
87
+ let texte = JSON.stringify(ligne);
88
+ while (Buffer.byteLength(texte) + 1 > LIGNE_MAX && raison.length > 0) {
89
+ const exces = Buffer.byteLength(texte) + 1 - LIGNE_MAX;
90
+ raison = raison.slice(0, Math.max(0, raison.length - Math.max(1, Math.ceil(exces / 4))));
91
+ texte = JSON.stringify({ ...ligne, raison: raison.join('') });
92
+ }
93
+ return `${texte}\n`;
94
+ }
95
+
96
+ let echecDit = false;
97
+
98
+ /**
99
+ * The trace <trace> (`{ genre, ticket, etape, boucle, place, raison }`, `ts` when it already has
100
+ * one) appended to the segment of its local date, in one write. A trace that cannot be written
101
+ * (no project, a full disk) never throws: `{ ecrit: false }`, said once through <dire>.
102
+ * @param {string} racine the project
103
+ * @param {object} trace
104
+ * @param {{ maintenant?: Date, dire?: (m: string) => void }} [options]
105
+ * @returns {{ ecrit: boolean }}
106
+ */
107
+ export function ecrireLaTrace(racine, trace, { maintenant, dire } = {}) {
108
+ try {
109
+ const ts = trace.ts ?? heureLocale(maintenant ?? new Date());
110
+ const dossier = dossierDuJournal(racine);
111
+ mkdirSync(dossier, { recursive: true });
112
+ appendFileSync(path.join(dossier, `${ts.slice(0, 10)}.jsonl`), ligneEntiere(trace, ts), {
113
+ flag: 'a',
114
+ });
115
+ return { ecrit: true };
116
+ } catch (e) {
117
+ return dit(e, dire);
118
+ }
119
+ }
120
+
121
+ function dit(erreur, dire) {
122
+ if (!echecDit) {
123
+ echecDit = true;
124
+ const m = `⚠️ journal des états non écrit : ${erreur?.message ?? erreur}`;
125
+ (dire ?? (t => process.stderr.write(`${t}\n`)))(m);
126
+ }
127
+ return { ecrit: false };
128
+ }
129
+
130
+ /** The trace of a circuit of the queue launched (`lance`) or ended (`termine`). */
131
+ export function traceDeLaFile({ ticket, evenement }) {
132
+ return { genre: 'file', ticket, etape: evenement, boucle: null, place: null, raison: '' };
133
+ }
134
+
135
+ /** The trace of a place taken (`prise`), given back (`rendue`) or waited for (`attente`). */
136
+ export function traceDesPlaces({ evenement, ticket = null, place = null, raison = '' }) {
137
+ return { genre: 'places', ticket, etape: evenement, boucle: null, place, raison };
138
+ }
139
+
140
+ const instant = ts => Date.parse(ts);
141
+
142
+ /**
143
+ * The lines of the journal of <racine> within the range, from every segment, in the order of their
144
+ * timestamps (instants, the order of the lines for a tie); a line unreadable is left out.
145
+ * @param {string} racine
146
+ * @param {{ depuis?: string, jusquA?: string, ticket?: string }} [plage] ISO 8601, bounds included
147
+ * @returns {{ lignes: object[] }}
148
+ */
149
+ export function lireLeJournal(racine, { depuis, jusquA, ticket } = {}) {
150
+ let dossier;
151
+ try {
152
+ dossier = dossierDuJournal(racine);
153
+ } catch {
154
+ return { lignes: [] };
155
+ }
156
+ if (!existsSync(dossier)) {
157
+ return { lignes: [] };
158
+ }
159
+ const du = depuis === undefined ? -Infinity : instant(depuis);
160
+ const au = jusquA === undefined ? Infinity : instant(jusquA);
161
+ const lignes = [];
162
+ for (const nom of readdirSync(dossier)
163
+ .filter(n => SEGMENT.test(n))
164
+ .sort()) {
165
+ let brut;
166
+ try {
167
+ brut = readFileSync(path.join(dossier, nom), 'utf8');
168
+ } catch {
169
+ continue;
170
+ }
171
+ for (const l of brut.split('\n')) {
172
+ let v;
173
+ try {
174
+ v = l ? JSON.parse(l) : null;
175
+ } catch {
176
+ continue;
177
+ }
178
+ if (!v || typeof v !== 'object' || Array.isArray(v) || Number.isNaN(instant(v.ts))) {
179
+ continue;
180
+ }
181
+ const t = instant(v.ts);
182
+ if (t >= du && t <= au && (ticket === undefined || v.ticket === ticket)) {
183
+ lignes.push({ v, t });
184
+ }
185
+ }
186
+ }
187
+ return { lignes: lignes.sort((a, b) => a.t - b.t).map(x => x.v) };
188
+ }
189
+
190
+ const jourDe = nom =>
191
+ Date.UTC(
192
+ ...nom
193
+ .slice(0, 10)
194
+ .split('-')
195
+ .map((n, i) => Number(n) - (i === 1 ? 1 : 0))
196
+ );
197
+
198
+ /**
199
+ * The cleaning: removes whole segments older than <ageMaxJours> days, then, past <tailleMax> bytes
200
+ * in all, the oldest first, never the latest. It rewrites no segment, so a line written meanwhile
201
+ * is not lost; it touches only the journal of <racine>.
202
+ * @param {string} racine
203
+ * @param {{ maintenant?: Date, ageMaxJours?: number, tailleMax?: number }} [options]
204
+ * @returns {{ retires: string[] }}
205
+ */
206
+ export function nettoyerLeJournal(
207
+ racine,
208
+ { maintenant = new Date(), ageMaxJours = AGE_MAX_JOURS, tailleMax = TAILLE_MAX } = {}
209
+ ) {
210
+ let dossier;
211
+ try {
212
+ dossier = dossierDuJournal(racine);
213
+ } catch {
214
+ return { retires: [] };
215
+ }
216
+ if (!existsSync(dossier)) {
217
+ return { retires: [] };
218
+ }
219
+ const aujourdhui = jourDe(heureLocale(maintenant));
220
+ const retires = [];
221
+ const retirer = nom => {
222
+ try {
223
+ unlinkSync(path.join(dossier, nom));
224
+ } catch {
225
+ // already gone
226
+ }
227
+ retires.push(nom);
228
+ };
229
+ let restants = readdirSync(dossier)
230
+ .filter(n => SEGMENT.test(n))
231
+ .sort();
232
+ for (const nom of restants.filter(n => (aujourdhui - jourDe(n)) / 86_400_000 > ageMaxJours)) {
233
+ retirer(nom);
234
+ }
235
+ restants = restants.filter(n => !retires.includes(n));
236
+ const tailles = new Map(restants.map(n => [n, statSync(path.join(dossier, n)).size]));
237
+ let total = [...tailles.values()].reduce((a, b) => a + b, 0);
238
+ for (const nom of restants.slice(0, -1)) {
239
+ if (total <= tailleMax) {
240
+ break;
241
+ }
242
+ retirer(nom);
243
+ total -= tailles.get(nom);
244
+ }
245
+ return { retires };
246
+ }
247
+
248
+ /**
249
+ * The set of tickets at work after each launch or end of a circuit of the queue (the lines `file`
250
+ * `lance` and `termine`), in the order of the instants: `[{ ts, enTravail }]`, one entry per change.
251
+ * @param {object[]} lignes
252
+ * @returns {{ ts: string, enTravail: string[] }[]}
253
+ */
254
+ export function ensemblesEnTravail(lignes) {
255
+ const file = lignes
256
+ .filter(l => l.genre === 'file' && (l.etape === 'lance' || l.etape === 'termine'))
257
+ .map((l, i) => ({ l, i, t: instant(l.ts) }))
258
+ .sort((a, b) => a.t - b.t || a.i - b.i);
259
+ const en = new Set();
260
+ const rendu = [];
261
+ for (const { l } of file) {
262
+ if (l.etape === 'lance') {
263
+ if (en.has(l.ticket)) {
264
+ continue;
265
+ }
266
+ en.add(l.ticket);
267
+ } else if (!en.delete(l.ticket)) {
268
+ continue;
269
+ }
270
+ rendu.push({ ts: l.ts, enTravail: [...en] });
271
+ }
272
+ return rendu;
273
+ }