@mostajs/delegation 0.0.0-stage → 0.9.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.
package/src/train.js ADDED
@@ -0,0 +1,370 @@
1
+ // @mostajs/delegation — le type de tâche « train » (plan 04) : le conducteur de train, comme une tâche déléguée.
2
+ //
3
+ // paquet → envoi → suite → resultats → tournage → rapatriement → [index → fusion → d4q → push]
4
+ //
5
+ // Rien d'une application ici : tout vient de la configuration de l'agent (train.json) — dépôt source, clone de travail,
6
+ // machine d'essai, gabarits des exécutions distantes, rouges connus, films, auteur, D4Q, push. Les quatre dernières
7
+ // phases n'existent que si la machine l'autorise (`integration.autorisee`), et seulement dans son clone de travail.
8
+ // JAMAIS D4PF, D4PFQ ni aucun déploiement (plan 01, §3.3) : une configuration qui en contient est refusée (E_INTERDIT).
9
+ // Chaque phase est une étape de l'exécutant (journal, progression, reprise) : `delegation-train <phase> …`.
10
+ // 0.8.0 (décision du 21/11/2026, D-E5) :
11
+ // T1 rouges connus { essai, motif, echeance, depuis?, renvoi? } : une échéance dépassée fait échouer le train ; les
12
+ // rouges connus devenus verts sont signalés (à retirer) ;
13
+ // T2 attestation Ed25519 de l'index des films (`films.signature.clePrivee`, fichier local en 600), commitée avec lui ;
14
+ // T3 la cible a bougé depuis le paquet (et la branche ne la contient pas) : arrêt clair avant la fusion ;
15
+ // T4 `suite.reessai` : UN nouvel essai des rouges nouveaux ; ceux qui passent sont « instables », le train continue.
16
+ // @author Dr Hamid MADANI <drmdh@msn.com>
17
+ import { readFileSync, writeFileSync, mkdirSync, existsSync, copyFileSync, renameSync } from 'node:fs';
18
+ import { createHash } from 'node:crypto';
19
+ import { join, dirname, isAbsolute } from 'node:path';
20
+ import { spawnSync, execFileSync } from 'node:child_process';
21
+ import { lireClePrivee, signerAttestation, FORMAT_ATTESTATION } from './signature.js';
22
+
23
+ export const PHASES_VERIFICATION = Object.freeze(['paquet', 'envoi', 'suite', 'resultats', 'tournage', 'rapatriement']);
24
+ export const PHASES_INTEGRATION = Object.freeze(['index', 'fusion', 'd4q', 'push']);
25
+ const INTERDIT = /d4pf|deploy/i;
26
+ const APPLICATION = /^[a-z][a-z0-9-]{1,40}$/;
27
+ const ESSAI = /^[A-Za-z0-9._-]{1,80}$/;
28
+ const MOTIFS = { branche: '^lot/[A-Za-z0-9._-]{1,80}$', version: '^\\d+\\.\\d+\\.\\d+$' };
29
+ const BIN = new URL('../bin/delegation-train.mjs', import.meta.url).pathname;
30
+ const D4PF = 'D4PF/D4PFQ : hors délégation (plan 01 §3.3) — au poste, sur feu vert de la version.';
31
+ const erreur = (code, message) => Object.assign(new Error(message), { code });
32
+ const q = (s) => `'${String(s).replace(/'/g, "'\\''")}'`;
33
+
34
+ /** Les commandes d'une application (pour la garde D4PF / déploiement). */
35
+ const commandes = (a) => [a.executant?.lanceur, a.integration?.d4q?.commande, ...[a.suite, a.suite?.reessai, a.tournage].flatMap((x) => (x?.etapes || []).map((e) => e.commande))].filter(Boolean);
36
+
37
+ /** Valide une configuration de train ; rend la liste de ses défauts (vide : bonne). Lève E_INTERDIT pour D4PF/déploiement. */
38
+ export function validerConfigTrain(conf) {
39
+ const f = [];
40
+ if (!conf || typeof conf !== 'object') return ['un objet est attendu'];
41
+ if (typeof conf.travail !== 'string' || !isAbsolute(conf.travail)) f.push('travail : un chemin absolu');
42
+ const apps = Object.entries(conf.applications || {});
43
+ if (!apps.length) f.push('applications : au moins une');
44
+ for (const [nom, a] of apps) {
45
+ const p = `applications.${nom}`;
46
+ if (!APPLICATION.test(nom)) f.push(`${p} : nom invalide`);
47
+ for (const c of commandes(a)) if (INTERDIT.test(c)) throw erreur('E_INTERDIT', `${p} : « ${c.slice(0, 80)} » — D4PF, D4PFQ et tout déploiement restent hors de la délégation (plan 01, §3.3)`);
48
+ for (const k of ['source', 'depot']) if (typeof a[k] !== 'string' || !a[k]) f.push(`${p}.${k} : requis`);
49
+ if (!a.executant?.racine || !a.executant?.lanceur || !a.executant?.hote) f.push(`${p}.executant : { hote, racine, lanceur } requis`);
50
+ if (!Array.isArray(a.suite?.etapes) || !a.suite.etapes.length || !a.suite.rapport) f.push(`${p}.suite : { etapes, rapport } requis`);
51
+ if (a.tournage && (!Array.isArray(a.tournage.etapes) || !a.films?.distant || !a.films?.local || !a.films?.index)) f.push(`${p}.tournage : etapes, et films { distant, local, index } requis`);
52
+ if (a.rougesConnus != null && !Array.isArray(a.rougesConnus)) f.push(`${p}.rougesConnus : une liste`);
53
+ for (const [i, r] of (Array.isArray(a.rougesConnus) ? a.rougesConnus : []).entries()) {
54
+ const k = `${p}.rougesConnus[${i}]`;
55
+ if (!r || typeof r !== 'object') { f.push(`${k} : { essai, motif, echeance } attendu (une échéance oblige à revoir la liste)`); continue; }
56
+ if (typeof r.essai !== 'string' || !ESSAI.test(r.essai)) f.push(`${k}.essai : un identifiant d'essai`);
57
+ if (typeof r.motif !== 'string' || r.motif.trim().length < 3) f.push(`${k}.motif : pourquoi il est accepté rouge`);
58
+ if (!Number.isFinite(Date.parse(r.echeance))) f.push(`${k}.echeance : une date`);
59
+ if (r.depuis != null && !Number.isFinite(Date.parse(r.depuis))) f.push(`${k}.depuis : une date`);
60
+ }
61
+ if (a.suite?.reessai && (!Array.isArray(a.suite.reessai.etapes) || !a.suite.reessai.etapes.length || !a.suite.reessai.rapport)) f.push(`${p}.suite.reessai : { etapes, rapport } requis`);
62
+ if (a.films?.signature && typeof a.films.signature.clePrivee !== 'string') f.push(`${p}.films.signature.clePrivee : un chemin`);
63
+ if (a.integration?.autorisee && (!a.integration.auteur?.nom || !a.integration.auteur?.email || !a.films?.indexDepot)) f.push(`${p}.integration : auteur { nom, email } et films.indexDepot requis`);
64
+ }
65
+ return f;
66
+ }
67
+
68
+ export function lireConfigTrain(fichier) {
69
+ const conf = JSON.parse(readFileSync(fichier, 'utf8'));
70
+ const f = validerConfigTrain(conf);
71
+ if (f.length) throw erreur('E_CONFIG', `configuration du train refusée : ${f.join(' ; ')}`);
72
+ return conf;
73
+ }
74
+
75
+ /** Les phases d'une application, dans l'ordre. */
76
+ export function phasesDe(a) {
77
+ const v = PHASES_VERIFICATION.filter((p) => a.tournage || !['tournage', 'rapatriement'].includes(p));
78
+ return a.integration?.autorisee ? [...v, ...PHASES_INTEGRATION] : v;
79
+ }
80
+
81
+ /**
82
+ * Le type « train » pour le registre d'un agent. Les commandes sont fabriquées ICI, sur la machine, à partir d'entrées
83
+ * revalidées : elles n'appellent que `delegation-train <phase>` avec la configuration de la machine.
84
+ * @param {{ fichier: string, type?: string, capacites?: string[], dureeMinutes?: number }} o
85
+ */
86
+ export function creerTypeTrain({ fichier, type = 'train', capacites = ['node@20', 'git', 'ssh', 'conducteur'], dureeMinutes = 360, siInterrompue = 'arreter' }) {
87
+ const conf = lireConfigTrain(fichier);
88
+ const noms = Object.keys(conf.applications);
89
+ return {
90
+ type, version: '1', capacites, dureeMinutes, siInterrompue,
91
+ entrees: { application: { requis: true, motif: `^(${noms.join('|')})$` }, branche: { requis: true, motif: MOTIFS.branche }, version: { requis: true, motif: MOTIFS.version } },
92
+ livrables: ['rapport.json'],
93
+ etapes: ({ application, branche, version }) => {
94
+ const a = lireConfigTrain(fichier).applications[application];
95
+ return phasesDe(a).map((p) => ({ code: p, titre: `Train ${application} ${version} — ${p}`, cwd: conf.travail,
96
+ commande: `${q(process.execPath)} ${q(BIN)} ${p} --config ${q(fichier)} --application ${q(application)} --branche ${q(branche)} --version ${q(version)}` }));
97
+ },
98
+ };
99
+ }
100
+
101
+ // ── Les outils des phases ───────────────────────────────────────────────────────────────────────────────────────────
102
+ const remplir = (s, v) => String(s ?? '').replace(/\{([a-z]+)\}/g, (m, k) => (v[k] != null ? String(v[k]) : m));
103
+ const sha256 = (f) => createHash('sha256').update(readFileSync(f)).digest('hex');
104
+ const pause = (s) => new Promise((ok) => setTimeout(ok, s * 1000));
105
+ const gitDe = (cwd) => (...args) => execFileSync('git', ['-C', cwd, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
106
+
107
+ /** La machine d'essai : ssh (BatchMode) ou, si `hote: "local"`, la machine même. */
108
+ function transport(ex) {
109
+ const local = ex.hote === 'local';
110
+ const sh = (cmd) => {
111
+ const r = local ? spawnSync('bash', ['-c', cmd], { encoding: 'utf8' }) : spawnSync('ssh', ['-o', 'BatchMode=yes', ex.hote, cmd], { encoding: 'utf8' });
112
+ return { code: r.status ?? 1, out: r.stdout || '', err: r.stderr || '' };
113
+ };
114
+ return {
115
+ sh,
116
+ lire: (chemin) => { const r = sh(`cat ${q(chemin)}`); return r.code === 0 ? r.out : null; },
117
+ envoyer(source, cible) {
118
+ sh(`mkdir -p ${q(dirname(cible))}`);
119
+ const r = local ? spawnSync('cp', [source, cible]) : spawnSync('scp', ['-q', '-o', 'BatchMode=yes', source, `${ex.hote}:${cible}`]);
120
+ if (r.status !== 0) throw erreur('E_TRANSPORT', `copie vers ${cible} : ${String(r.stderr || '').trim()}`);
121
+ },
122
+ rapatrier(source, cible) {
123
+ mkdirSync(cible, { recursive: true });
124
+ const r = local ? spawnSync('cp', ['-a', `${source}/.`, `${cible}/`]) : spawnSync('rsync', ['-a', '-e', 'ssh -o BatchMode=yes', `${ex.hote}:${source}/`, `${cible}/`]);
125
+ if (r.status !== 0) throw erreur('E_TRANSPORT', `rapatriement de ${source} : ${String(r.stderr || '').trim()}`);
126
+ },
127
+ };
128
+ }
129
+
130
+ /**
131
+ * Exécute UNE phase du train ; rend le code de sortie (0 : la suite peut continuer). Imprime ce qu'elle fait ; sur arrêt,
132
+ * écrit le rapport court (rapport.json du dossier du train) et l'imprime en dernières lignes.
133
+ * @param {string} phase
134
+ * @param {{ fichier: string, application: string, branche: string, version: string, dire?: (t: string) => void }} o
135
+ */
136
+ export async function phaseTrain(phase, { fichier, application, branche, version, dire = (t) => console.log(t) }) {
137
+ const conf = lireConfigTrain(fichier);
138
+ const a = conf.applications[application];
139
+ if (!a) throw erreur('E_ENTREES', `application « ${application} » inconnue de cette machine`);
140
+ if (!new RegExp(MOTIFS.branche).test(branche) || !new RegExp(MOTIFS.version).test(version)) throw erreur('E_ENTREES', 'branche ou version hors motif');
141
+ if (!phasesDe(a).includes(phase)) throw erreur('E_PHASE', `phase « ${phase} » inconnue ou non autorisée ici`);
142
+
143
+ const dossier = join(conf.travail, 'trains', `${application}-${version}`);
144
+ mkdirSync(dossier, { recursive: true });
145
+ const fEtat = join(dossier, 'etat-train.json');
146
+ const lireEtat = () => { try { return JSON.parse(readFileSync(fEtat, 'utf8')); } catch { return {}; } };
147
+ const ecrireEtat = (x) => { writeFileSync(`${fEtat}.tmp`, JSON.stringify(x, null, 1)); renameSync(`${fEtat}.tmp`, fEtat); };
148
+ let st = lireEtat();
149
+ const ex = a.executant; const t = transport(ex); const git = gitDe(a.depot);
150
+ const cible = a.cible || 'main'; const distant = a.integration?.push?.distant || 'origin';
151
+ const paquetDistant = `${ex.racine}/paquets/${application}-${version}.bundle`;
152
+ const vars = () => ({ racine: ex.racine, paquet: paquetDistant, branche, version, application, suite: st.suite?.id });
153
+ const arret = (rapport) => {
154
+ const r = { verdict: 'rouge', application, version, branche, phase, quand: new Date().toISOString(), ...rapport };
155
+ writeFileSync(join(dossier, 'rapport.json'), JSON.stringify(r, null, 1));
156
+ dire(`✗ train ${application} ${version} arrêté à « ${phase} » — rapport court :`);
157
+ dire(JSON.stringify(r, null, 1));
158
+ return 1;
159
+ };
160
+
161
+ /** Lance une exécution distante (si elle ne l'est pas déjà) et attend sa fin. */
162
+ const executerDistant = async (cle, gabarit, plus = {}) => {
163
+ if (!st[cle]?.id) {
164
+ const id = `${application}-${version}-${cle}-${new Date().toISOString().replace(/[-:]/g, '').slice(0, 15)}`;
165
+ const v = { ...vars(), ...plus, id };
166
+ const def = { id, titre: `${cle} — ${application} ${version}`, etapes: gabarit.map((e) => ({ ...e, cwd: remplir(e.cwd || '{racine}', v), commande: remplir(e.commande, v) })) };
167
+ const local = join(dossier, `${id}.json`); writeFileSync(local, JSON.stringify(def, null, 1));
168
+ const json = `${ex.racine}/trains/${id}.json`;
169
+ t.envoyer(local, json);
170
+ // Le lanceur (avec ses variables d'environnement éventuelles) tourne détaché : la phase peut s'interrompre sans lui.
171
+ const r = t.sh(`cd ${q(ex.racine)} && nohup bash -c ${q(`${ex.lanceur} ${q(json)}`)} > ${q(`${json}.log`)} 2>&1 < /dev/null &`);
172
+ if (r.code !== 0) throw erreur('E_TRANSPORT', `lancement de ${id} : ${r.err.trim()}`);
173
+ st[cle] = { id, lance: new Date().toISOString() }; ecrireEtat(st);
174
+ dire(`→ ${cle} lancée sur ${ex.hote} : ${id}`);
175
+ } else dire(`↻ ${cle} déjà lancée (${st[cle].id}) : on reprend l'attente`);
176
+ const id = st[cle].id; const debut = Date.now(); let vu = '';
177
+ for (;;) {
178
+ const brut = t.lire(`${ex.racine}/executions/${id}/etat.json`);
179
+ const e = brut ? JSON.parse(brut) : null;
180
+ if (e) {
181
+ const resume = e.etapes.map((x) => `${x.code}:${x.etat}${x.progression ? `(${x.progression.passes ?? 0}✓ ${x.progression.echoues ?? 0}✗)` : ''}`).join(' ');
182
+ if (resume !== vu) { vu = resume; dire(` ${cle} : ${resume}`); }
183
+ if (e.etat !== 'en_cours') return e;
184
+ if (e.pid && t.sh(`kill -0 ${Number(e.pid)}`).code !== 0 && !(t.lire(`${ex.racine}/executions/${id}/etat.json`) || '').includes('"fin": "2')) return { ...e, etat: 'interrompue' };
185
+ }
186
+ if (!e && Date.now() - debut > (a.demarrageMaxS ?? 120) * 1000) {
187
+ return { etapes: [], etat: 'non-demarree', journal: (t.sh(`tail -c 2000 ${q(`${ex.racine}/trains/${id}.json.log`)}`).out || '').trim() };
188
+ }
189
+ if (Date.now() - debut > (a.delaiMaxMin || 600) * 60_000) return { ...(e || { etapes: [] }), etat: 'delai' };
190
+ await pause(a.attenteS ?? 30);
191
+ }
192
+ };
193
+ const finJournal = (id, code) => (t.sh(`tail -c 3000 ${q(`${ex.racine}/executions/${id}/${code}.log`)}`).out || '').replace(/\x1b\[[0-9;]*m/g, '');
194
+
195
+ switch (phase) {
196
+ case 'paquet': {
197
+ if (!existsSync(join(a.depot, '.git'))) return arret({ message: `clone de travail absent : ${a.depot}` });
198
+ const distants = git('remote').split('\n');
199
+ if (distants.includes(distant)) { git('fetch', '-q', distant); git('checkout', '-q', '-B', cible, `${distant}/${cible}`); } else git('checkout', '-q', cible);
200
+ try { git('fetch', '-q', a.source, `+refs/heads/${branche}:refs/heads/${branche}`); } catch (e) { return arret({ message: `branche ${branche} introuvable dans la source : ${String(e.stderr || e.message).trim().slice(0, 300)}` }); }
201
+ const tete = git('rev-parse', branche);
202
+ if (st.tete !== tete) st = { tete, branche };
203
+ st.cible = git('rev-parse', cible); ecrireEtat(st); // T3 : la cible telle qu'au paquet
204
+ git('bundle', 'create', '-q', join(dossier, `${application}-${version}.bundle`), branche);
205
+ dire(`✓ paquet de ${branche} (${tete.slice(0, 7)}) depuis la source, dans le clone de travail`);
206
+ return 0;
207
+ }
208
+ case 'envoi':
209
+ t.envoyer(join(dossier, `${application}-${version}.bundle`), paquetDistant);
210
+ dire(`✓ paquet envoyé sur ${ex.hote} : ${paquetDistant}`);
211
+ return 0;
212
+ case 'suite': {
213
+ const e = await executerDistant('suite', a.suite.etapes);
214
+ const gabarit = Object.fromEntries(a.suite.etapes.map((x) => [x.code, x]));
215
+ const casse = e.etapes.find((x) => x.etat === 'echec' && gabarit[x.code]?.analyse !== 'suite');
216
+ if (['delai', 'interrompue', 'non-demarree'].includes(e.etat)) return arret({ message: `exécution distante ${{ delai: 'trop longue', interrompue: 'interrompue', 'non-demarree': 'jamais démarrée' }[e.etat]} (${st.suite.id})`, ...(e.journal ? { finJournal: e.journal } : {}) });
217
+ if (casse) return arret({ etape: casse.code, message: `l'étape « ${casse.code} » a échoué (code ${casse.sortie})`, finJournal: finJournal(st.suite.id, casse.code) });
218
+ dire(`✓ suite terminée (${e.etat}) ; verdict à la phase suivante`);
219
+ return 0;
220
+ }
221
+ case 'resultats': {
222
+ if (!st.suite?.id) return arret({ message: 'aucune suite lancée' });
223
+ const brut = t.lire(remplir(a.suite.rapport, { ...vars(), id: st.suite.id }));
224
+ if (!brut) return arret({ message: 'rapport de la suite introuvable' });
225
+ const r = JSON.parse(brut);
226
+ const resultats = (r.suites || []).flatMap((s) => s.results || []);
227
+ const rouges = resultats.filter((x) => x.status === 'fail').map((x) => ({ essai: String(x.name).split(' ')[0], message: String(x.error?.message || x.message || x.failure || '').slice(0, 300) }));
228
+ // T1 : des rouges connus datés et motivés ; une échéance dépassée redevient bloquante.
229
+ const connus = (a.rougesConnus || []).map((y) => ({ essai: y.essai, motif: y.motif, echeance: y.echeance, ...(y.depuis ? { depuis: y.depuis } : {}), ...(y.renvoi ? { renvoi: y.renvoi } : {}) }));
230
+ const parEssai = new Map(connus.map((y) => [y.essai, y]));
231
+ const ids = new Set(rouges.map((y) => y.essai));
232
+ const maintenant = Date.now();
233
+ const echus = connus.filter((y) => Date.parse(y.echeance) < maintenant).map((y) => ({ ...y, encoreRouge: ids.has(y.essai) }));
234
+ let nouveaux = rouges.filter((y) => !parEssai.has(y.essai));
235
+ // T4 : UN nouvel essai des rouges nouveaux ; ceux qui passent sont instables.
236
+ let instables = [];
237
+ if (nouveaux.length && a.suite.reessai && nouveaux.every((y) => ESSAI.test(y.essai))) {
238
+ dire(`↻ nouvel essai (un seul) : ${nouveaux.map((y) => y.essai).join(', ')}`);
239
+ const e = await executerDistant('reessai', a.suite.reessai.etapes, { essais: nouveaux.map((y) => q(y.essai)).join(' ') });
240
+ const b2 = t.lire(remplir(a.suite.reessai.rapport, { ...vars(), id: st.reessai?.id }));
241
+ const res2 = b2 ? (JSON.parse(b2).suites || []).flatMap((s) => s.results || []) : [];
242
+ const passes = new Set(res2.filter((y) => y.status === 'pass').map((y) => String(y.name).split(' ')[0]));
243
+ instables = nouveaux.filter((y) => passes.has(y.essai)).map((y) => y.essai);
244
+ nouveaux = nouveaux.filter((y) => !passes.has(y.essai));
245
+ st.reessai = { ...st.reessai, etat: e.etat, instables }; ecrireEtat(st);
246
+ }
247
+ const x = r.execution || {};
248
+ const incomplete = x.executes != null && x.declares != null && x.executes !== x.declares;
249
+ const messages = [
250
+ ...(incomplete ? [`suite incomplète : ${x.executes} exécutés sur ${x.declares} déclarés`] : []),
251
+ ...(echus.length ? [`rouge(s) connu(s) à échéance dépassée : ${echus.map((y) => `${y.essai} (${y.echeance.slice(0, 10)}, ${y.encoreRouge ? 'encore rouge : corrigez-le ou renouvelez l’échéance avec un motif' : 'redevenu vert : retirez-le de la liste'})`).join(' ; ')}`] : []),
252
+ ];
253
+ if (nouveaux.length || incomplete || echus.length) {
254
+ return arret({ nouveaux, rougesConnus: rouges.filter((y) => parEssai.has(y.essai)).map((y) => y.essai), ...(echus.length ? { echus } : {}),
255
+ ...(st.reessai ? { reessai: true, instables } : {}), ...(messages.length ? { message: messages.join(' — ') } : {}) });
256
+ }
257
+ const devenusVerts = connus.filter((y) => !ids.has(y.essai)).map((y) => y.essai);
258
+ st.resultats = { essais: resultats.length, rougesConnus: connus.filter((y) => ids.has(y.essai)), devenusVerts, instables }; ecrireEtat(st);
259
+ dire(`✓ verdict vert : ${resultats.length} essais, rouges connus seulement (${[...ids].map((k) => `${k} : ${parEssai.get(k)?.motif}`).join(' ; ') || 'aucun'})`);
260
+ if (devenusVerts.length) dire(`ℹ rouges connus devenus verts, à retirer de la liste : ${devenusVerts.join(', ')}`);
261
+ if (instables.length) dire(`⚠ essai(s) instable(s), rouges puis verts au nouvel essai : ${instables.join(', ')}`);
262
+ return 0;
263
+ }
264
+ case 'tournage': {
265
+ const e = await executerDistant('tournage', a.tournage.etapes);
266
+ if (['delai', 'interrompue', 'non-demarree'].includes(e.etat)) return arret({ message: `tournage ${{ delai: 'trop long', interrompue: 'interrompu', 'non-demarree': 'jamais démarré' }[e.etat]} (${st.tournage.id})`, ...(e.journal ? { finJournal: e.journal } : {}) });
267
+ const dossierCaptures = a.tournage.captures ? remplir(a.tournage.captures, vars()) : null;
268
+ const captures = dossierCaptures ? t.sh(`ls -1 ${q(dossierCaptures)} 2>/dev/null`).out.split('\n').filter(Boolean) : [];
269
+ const films = e.etapes.flatMap((x) => x.progression?.echecs || []).map((y) => {
270
+ const c = captures.find((f) => f.startsWith(`${y.essai}.`) || f.startsWith(`${y.essai}-`));
271
+ return { film: y.essai, message: y.titre || y.message || '', ...(c ? { capture: `${dossierCaptures}/${c}` } : {}) };
272
+ });
273
+ const casse = e.etapes.find((x) => x.etat === 'echec');
274
+ if (films.length || casse) return arret({ films, ...(casse && !films.length ? { etape: casse.code, finJournal: finJournal(st.tournage.id, casse.code) } : {}) });
275
+ dire(`✓ tournage vert : ${e.etapes.reduce((n, x) => n + (x.progression?.passes || 0), 0)} film(s)`);
276
+ return 0;
277
+ }
278
+ case 'rapatriement': {
279
+ const source = remplir(a.films.distant, vars());
280
+ t.rapatrier(source, a.films.local);
281
+ const fIndex = join(a.films.local, a.films.index);
282
+ if (!existsSync(fIndex)) return arret({ message: `index des films absent : ${a.films.index}` });
283
+ const index = JSON.parse(readFileSync(fIndex, 'utf8'));
284
+ if (index.format !== 'geste-film-index/1') return arret({ message: `format d'index inattendu : ${index.format}` });
285
+ const fautes = [];
286
+ for (const [film, x] of Object.entries(index.films || {})) {
287
+ for (const [k, f] of Object.entries(x.fichiers || {})) {
288
+ const p = join(a.films.local, f); const attendu = x.sha256?.[k];
289
+ if (!attendu) continue;
290
+ if (!existsSync(p)) { fautes.push({ film, fichier: f, faute: 'absent' }); continue; }
291
+ const trouve = sha256(p);
292
+ if (trouve !== attendu) fautes.push({ film, fichier: f, faute: 'empreinte SHA-256 différente', attendu, trouve });
293
+ }
294
+ }
295
+ if (fautes.length) return arret({ message: `${fautes.length} fichier(s) refusé(s) au contrôle SHA-256`, fichiers: fautes });
296
+ st.rapatriement = { films: Object.keys(index.films || {}).length };
297
+ // T2 : l'attestation de provenance, signée par la clé du conducteur (fichier local en 600).
298
+ if (a.films.signature) {
299
+ let pem;
300
+ try { pem = lireClePrivee(a.films.signature.clePrivee); } catch (e) { return arret({ message: `clé de signature de l'index refusée : ${e.message}` }); }
301
+ const films = Object.fromEntries(Object.entries(index.films || {}).map(([film, y]) => [film, { ...(y.sha256 || {}) }]));
302
+ const att = signerAttestation({ format: FORMAT_ATTESTATION, application, version, branche, tete: st.tete, index: { fichier: a.films.index, sha256: sha256(fIndex) }, films, quand: new Date().toISOString() }, pem);
303
+ writeFileSync(`${fIndex}.attestation.json`, `${JSON.stringify(att, null, 1)}\n`);
304
+ st.rapatriement.attestation = { cle: att.cle };
305
+ dire(`✓ index des films attesté (Ed25519, clé ${att.cle})`);
306
+ } else dire('· index des films non attesté (films.signature absent de la configuration)');
307
+ ecrireEtat(st);
308
+ dire(`✓ ${st.rapatriement.films} film(s) rapatrié(s), empreintes SHA-256 vérifiées`);
309
+ if (!a.integration?.autorisee) {
310
+ writeFileSync(join(dossier, 'rapport.json'), JSON.stringify({ verdict: 'vert', application, version, branche, integration: false, quand: new Date().toISOString() }, null, 1));
311
+ dire('■ intégration non autorisée par la configuration de cette machine : le train s’arrête ici (index, fusion, D4Q et push au poste).');
312
+ dire(`■ ${D4PF}`);
313
+ }
314
+ return 0;
315
+ }
316
+ case 'index': {
317
+ git('checkout', '-q', branche);
318
+ const source = join(a.films.local, a.films.index); const dest = join(a.depot, a.films.indexDepot);
319
+ if (!existsSync(source)) { dire('· pas d’index de films : rien à commiter'); return 0; }
320
+ mkdirSync(dirname(dest), { recursive: true }); copyFileSync(source, dest);
321
+ git('add', a.films.indexDepot);
322
+ const att = existsSync(`${source}.attestation.json`) ? JSON.parse(readFileSync(`${source}.attestation.json`, 'utf8')) : null;
323
+ if (att) { copyFileSync(`${source}.attestation.json`, `${dest}.attestation.json`); git('add', `${a.films.indexDepot}.attestation.json`); }
324
+ if (spawnSync('git', ['-C', a.depot, 'diff', '--cached', '--quiet']).status === 0) { dire('· index inchangé : rien à commiter'); return 0; }
325
+ const { nom, email } = a.integration.auteur;
326
+ const n = st.rapatriement?.films ?? Object.keys(JSON.parse(readFileSync(source, 'utf8')).films || {}).length;
327
+ const attLigne = att ? `\nAttestation signée (Ed25519, clé ${att.cle}) : index sha256 ${att.index.sha256.slice(0, 16)}, tête ${String(att.tete).slice(0, 7)}.\n` : '';
328
+ const msg = `formation : index des films de la ${version} (${n} films)\n\nFilms rapatriés de ${ex.hote}, fichiers hors git, empreintes SHA-256 vérifiées.\n${attLigne}\nAuthor: ${nom} <${email}>\n`;
329
+ const fMsg = join(dossier, 'message-index.txt'); writeFileSync(fMsg, msg);
330
+ execFileSync('git', ['-C', a.depot, '-c', `user.name=${nom}`, '-c', `user.email=${email}`, 'commit', '-q', '-F', fMsg], { stdio: ['ignore', 'pipe', 'pipe'] });
331
+ dire(`✓ index commité sur ${branche} (${git('rev-parse', '--short', 'HEAD')})`);
332
+ return 0;
333
+ }
334
+ case 'fusion': {
335
+ // T3 : la cible a-t-elle bougé depuis le paquet ? (l'avance rapide échouerait, ou le push serait refusé)
336
+ if (git('remote').split('\n').includes(distant)) { try { git('fetch', '-q', distant); } catch { /* distant injoignable : la fusion locale tranchera */ } }
337
+ let maintenantCible = null;
338
+ try { maintenantCible = git('rev-parse', `${distant}/${cible}`); } catch { try { maintenantCible = git('rev-parse', cible); } catch { /* aucune */ } }
339
+ if (st.cible && maintenantCible && maintenantCible !== st.cible && spawnSync('git', ['-C', a.depot, 'merge-base', '--is-ancestor', maintenantCible, branche]).status !== 0) {
340
+ return arret({ message: `${cible} a bougé depuis le paquet (${st.cible.slice(0, 7)} → ${maintenantCible.slice(0, 7)}) : l'arbre éprouvé ne serait plus celui fusionné. Rebasez ${branche} sur ${cible} (git rebase ${cible}), puis relancez le train.`,
341
+ cibleAvant: st.cible, cibleMaintenant: maintenantCible });
342
+ }
343
+ git('checkout', '-q', cible);
344
+ try { git('merge', '-q', '--ff-only', branche); } catch (e) { return arret({ message: `fusion en avance rapide impossible : ${String(e.stderr || e.message).trim().slice(0, 300)}` }); }
345
+ if (git('rev-parse', cible) !== git('rev-parse', branche)) return arret({ message: `${cible} n’est pas sur la tête de ${branche}` });
346
+ dire(`✓ ${cible} avancé sur ${git('rev-parse', '--short', cible)} (--ff-only)`);
347
+ return 0;
348
+ }
349
+ case 'd4q': {
350
+ const d = a.integration.d4q;
351
+ if (!d?.commande) { dire('· pas de D4Q configuré pour cette application'); return 0; }
352
+ const r = spawnSync('bash', ['-lc', d.commande], { cwd: d.cwd || a.depot, stdio: 'inherit' });
353
+ if (r.status !== 0) return arret({ message: `D4Q en échec (code ${r.status})` });
354
+ dire('✓ D4Q terminé (ne déploie rien)');
355
+ return 0;
356
+ }
357
+ case 'push': {
358
+ if (!a.integration.push) dire('· pas de push configuré'); else {
359
+ try { git('push', '-q', distant, cible); } catch (e) { return arret({ message: `push refusé : ${String(e.stderr || e.message).trim().slice(0, 300)}` }); }
360
+ dire(`✓ ${cible} poussé vers ${distant}`);
361
+ }
362
+ writeFileSync(join(dossier, 'rapport.json'), JSON.stringify({ verdict: 'vert', application, version, branche, integration: true, tete: git('rev-parse', cible), quand: new Date().toISOString() }, null, 1));
363
+ dire(`■ train ${application} ${version} intégré. ${D4PF}`);
364
+ return 0;
365
+ }
366
+ default: throw erreur('E_PHASE', phase);
367
+ }
368
+ }
369
+
370
+
package/src/types.js ADDED
@@ -0,0 +1,98 @@
1
+ // @mostajs/delegation — le registre des types de tâches, sur le patron des dialectes.
2
+ // Ajouter un type, c'est ajouter une définition : ni l'agent ni l'application ne changent.
3
+ // @author Dr Hamid MADANI <drmdh@msn.com>
4
+
5
+ const NOM = /^[a-z][a-z0-9-]{1,40}$/;
6
+ /**
7
+ * Ce que Delegate fait d'une tâche INTERROMPUE (machine redémarrée, hors ligne trop longtemps, bail dépassé) :
8
+ * `remettre` en file (défaut), l'`arreter` (échec motivé), ou laisser la même machine la `reprendre` sans rejouer les
9
+ * étapes faites. Jamais deux exécutions : remise en file, la tâche n'appartient plus à l'ancienne machine.
10
+ */
11
+ export const SI_INTERROMPUE = Object.freeze(['remettre', 'arreter', 'reprendre']);
12
+ /** La capacité du conducteur de train : déclarée par l'agent d'un PC, jamais par la centrale. */
13
+ export const CAPACITE_CONDUCTEUR = 'conducteur';
14
+ /** Vrai si le type ne doit jamais aller à la centrale (le train, ou tout type qui exige « conducteur »). */
15
+ export const exigeConducteur = (def) => Boolean(def) && (def.type === 'train' || (def.capacites || []).includes(CAPACITE_CONDUCTEUR));
16
+ const erreur = (code, message) => Object.assign(new Error(message), { code });
17
+ /**
18
+ * Les délais d'un type (R4) : `demarrageMaxS` (affectée sans être démarrée), `dureeMaxMin` (en cours trop longtemps),
19
+ * `silenceMaxS` (en cours sans battement). Au-delà, la centrale déclare la tâche interrompue.
20
+ */
21
+ export const DELAIS = Object.freeze(['demarrageMaxS', 'dureeMaxMin', 'silenceMaxS']);
22
+
23
+ /**
24
+ * Les défauts d'une définition de type, nommés.
25
+ * `declarations` : registre d'une CENTRALE (plan 02, §8.2-1) — un type n'y est qu'une déclaration (nom, version,
26
+ * capacités, schéma des entrées) ; il n'a pas d'étapes, donc pas de commandes. Les commandes vivent chez l'agent.
27
+ */
28
+ function defauts(def, declarations) {
29
+ const f = [];
30
+ if (!def || typeof def !== 'object') return ['une définition (objet) est attendue'];
31
+ if (typeof def.type !== 'string' || !NOM.test(def.type)) f.push('type : un nom (minuscules, chiffres, -)');
32
+ if (typeof def.version !== 'string' || !def.version) f.push('version : une chaîne');
33
+ if (!Array.isArray(def.capacites) || def.capacites.some((c) => typeof c !== 'string' || !c)) f.push('capacites : une liste de chaînes');
34
+ if (declarations && def.etapes != null) f.push('etapes : une centrale ne porte ni étapes ni commandes (elles vivent chez l’agent)');
35
+ if (!declarations && typeof def.etapes !== 'function') f.push('etapes : une fonction (entrées) → étapes');
36
+ if (def.entrees != null && (typeof def.entrees !== 'object' || Array.isArray(def.entrees))) f.push('entrees : un objet { champ: { requis?, motif? } }');
37
+ for (const [k, c] of Object.entries(def.entrees || {})) {
38
+ if (c.motif != null) { try { new RegExp(c.motif); } catch { f.push(`entrees.${k}.motif : expression invalide`); } }
39
+ }
40
+ if (def.dureeMinutes != null && !(Number(def.dureeMinutes) > 0)) f.push('dureeMinutes : un nombre positif');
41
+ if (def.livrables != null && !Array.isArray(def.livrables)) f.push('livrables : une liste');
42
+ if (def.siInterrompue != null && !SI_INTERROMPUE.includes(def.siInterrompue)) f.push(`siInterrompue : ${SI_INTERROMPUE.join(' | ')}`);
43
+ // R4 (0.7.0) : les délais de la tâche, surveillés par la centrale (secondes ou minutes, positifs).
44
+ for (const k of DELAIS) if (def[k] != null && !(Number(def[k]) > 0)) f.push(`${k} : un nombre positif`);
45
+ return f;
46
+ }
47
+
48
+ /**
49
+ * Crée un registre vide.
50
+ * @param {{ declarations?: boolean }} [o] declarations : registre de centrale, sans étapes (§8.2-1 du plan 02).
51
+ */
52
+ export function creerRegistre({ declarations = false } = {}) {
53
+ const types = new Map();
54
+ return {
55
+ declarations,
56
+ /** Déclare un type ; une définition incomplète est refusée (E_TYPE), un doublon aussi (E_TYPE_DOUBLE). */
57
+ enregistrer(def) {
58
+ const f = defauts(def, declarations);
59
+ if (f.length) throw erreur('E_TYPE', `type de tâche refusé : ${f.join(' ; ')}`);
60
+ if (types.has(def.type)) throw erreur('E_TYPE_DOUBLE', `le type « ${def.type} » est déjà déclaré`);
61
+ types.set(def.type, Object.freeze({ entrees: {}, livrables: [], dureeMinutes: null, ...def, capacites: [...def.capacites] }));
62
+ return this;
63
+ },
64
+ types: () => [...types.keys()],
65
+ type: (nom) => types.get(nom) || null,
66
+ /** Ce qu'on peut dire d'un type hors de la machine : tout, sauf ses étapes. */
67
+ declaration(nom) {
68
+ const d = types.get(nom);
69
+ if (!d) return null;
70
+ return { type: d.type, version: d.version, capacites: [...d.capacites], entrees: structuredClone(d.entrees), dureeMinutes: d.dureeMinutes, livrables: [...d.livrables],
71
+ ...(d.siInterrompue ? { siInterrompue: d.siInterrompue } : {}), ...Object.fromEntries(DELAIS.filter((k) => d[k] != null).map((k) => [k, d[k]])) };
72
+ },
73
+ /**
74
+ * Les défauts des entrées d'une tâche : clé hors schéma, champ requis absent, motif non respecté.
75
+ * Une tâche ne porte JAMAIS de commande — seulement des entrées que le type sait lire.
76
+ */
77
+ valider(nom, entrees = {}) {
78
+ const def = types.get(nom);
79
+ if (!def) return [`type inconnu « ${nom} »`];
80
+ if (!entrees || typeof entrees !== 'object' || Array.isArray(entrees)) return ['entrées : un objet'];
81
+ const f = [];
82
+ for (const k of Object.keys(entrees)) if (!Object.hasOwn(def.entrees, k)) f.push(`${k} : champ inconnu du type « ${nom} »`);
83
+ for (const [k, c] of Object.entries(def.entrees)) {
84
+ const v = entrees[k];
85
+ if (v == null || v === '') { if (c.requis) f.push(`${k} : requis`); continue; }
86
+ if (typeof v !== 'string' && typeof v !== 'number' && typeof v !== 'boolean') { f.push(`${k} : une valeur simple`); continue; }
87
+ if (c.motif != null && !new RegExp(c.motif).test(String(v))) f.push(`${k} : « ${String(v).slice(0, 60)} » ne suit pas ${c.motif}`);
88
+ }
89
+ return f;
90
+ },
91
+ };
92
+ }
93
+
94
+ /** Les capacités requises par un type qu'une machine n'a pas (liste vide : elle sait faire). */
95
+ export function manquesPour(machine, def) {
96
+ const a = new Set(machine?.capacites || []);
97
+ return (def?.capacites || []).filter((c) => !a.has(c));
98
+ }
@@ -0,0 +1,80 @@
1
+ // @mostajs/delegation — le VEILLEUR (R9, 0.9.0) : sous Windows, la tâche planifiée lance ce veilleur, qui lance l'agent
2
+ // et le RELANCE après une panne, comme systemd (Restart=always, RestartSec=5, RestartPreventExitStatus=2) :
3
+ // - sortie ≠ 0 et ≠ 2 : relance après `delaiS`, attente croissante bornée (`delaiMaxS`) si les pannes s'enchaînent ;
4
+ // - sortie 2 (configuration refusée : pas de clé, pas de jeton…) : il s'arrête avec le code 2, sans s'emballer ;
5
+ // - sortie 0 : arrêt voulu, il s'arrête avec 0 ;
6
+ // - un signal d'arrêt (SIGTERM, SIGINT, SIGBREAK) : il arrête l'agent puis sort avec 0.
7
+ // L'agent est lancé avec un canal IPC : si le veilleur meurt (tué net), l'agent reçoit « disconnect » et s'arrête —
8
+ // jamais deux agents. Sortie de l'agent dans un journal, renommé en .1 au démarrage au-delà de `tailleMaxMo`.
9
+ // Aucune dépendance au système : il tourne aussi sous Linux et macOS (essais).
10
+ // @author Dr Hamid MADANI <drmdh@msn.com>
11
+ import { spawn as spawnParDefaut } from 'node:child_process';
12
+ import { createWriteStream, mkdirSync, statSync, renameSync, rmSync } from 'node:fs';
13
+ import { dirname } from 'node:path';
14
+ import { signauxArret } from './plateforme.js';
15
+
16
+ const iso = () => new Date().toISOString();
17
+
18
+ /** Renomme le journal en .1 s'il dépasse la taille permise (un seul ancien gardé). */
19
+ export function tournerJournal(journal, tailleMaxMo = 5) {
20
+ try {
21
+ if (statSync(journal).size > tailleMaxMo * 1024 * 1024) {
22
+ rmSync(`${journal}.1`, { force: true }); renameSync(journal, `${journal}.1`); return true;
23
+ }
24
+ } catch { /* pas encore de journal */ }
25
+ return false;
26
+ }
27
+
28
+ /**
29
+ * Lance `programme arguments` et le relance après une panne. Rend { fini: Promise<code>, arreter() }.
30
+ * @param {{ programme: string, arguments?: string[], journal?: string, delaiS?: number, delaiMaxS?: number,
31
+ * codeArret?: number, tailleMaxMo?: number, plateforme?: string, spawn?: typeof spawnParDefaut, ecouterSignaux?: boolean }} o
32
+ */
33
+ export function veiller({ programme, arguments: args = [], journal = null, delaiS = 5, delaiMaxS = 60, codeArret = 2, tailleMaxMo = 5,
34
+ plateforme = process.platform, spawn = spawnParDefaut, ecouterSignaux = true }) {
35
+ if (!programme) throw Object.assign(new Error('veiller : programme requis'), { code: 'E_OPTION' });
36
+ let flux = null;
37
+ if (journal) { mkdirSync(dirname(journal), { recursive: true }); tournerJournal(journal, tailleMaxMo); flux = createWriteStream(journal, { flags: 'a' }); }
38
+ const dire = (t) => { const l = `${iso()} [veilleur] ${t}\n`; if (flux) flux.write(l); else process.stderr.write(l); };
39
+ let enfant = null; let arrete = false; let pannes = 0; let minuteur = null; let finir;
40
+ const fini = new Promise((ok) => { finir = ok; });
41
+ const terminer = (code) => {
42
+ clearTimeout(minuteur);
43
+ for (const s of signaux) process.removeListener(s, surSignal);
44
+ const fin = () => finir(code);
45
+ if (flux) flux.end(fin); else fin();
46
+ };
47
+ const lancer = () => {
48
+ if (arrete) return;
49
+ const debut = Date.now();
50
+ dire(`lance : ${programme} ${args.join(' ')}`);
51
+ enfant = spawn(programme, args, { stdio: ['ignore', 'pipe', 'pipe', 'ipc'], windowsHide: true });
52
+ const ecrire = (b) => { if (flux) flux.write(b); else process.stdout.write(b); };
53
+ enfant.stdout?.on('data', ecrire); enfant.stderr?.on('data', ecrire);
54
+ enfant.on('error', (e) => dire(`✗ lancement impossible : ${e.message}`));
55
+ enfant.on('close', (code, signal) => {
56
+ enfant = null;
57
+ if (arrete) { dire('arrêté'); terminer(0); return; }
58
+ if (code === 0) { dire('l’agent s’est arrêté (code 0) : fin'); terminer(0); return; }
59
+ if (code === codeArret) { dire(`l’agent refuse de démarrer (code ${codeArret}) : pas de relance — corrigez la configuration`); terminer(codeArret); return; }
60
+ pannes = Date.now() - debut > 60_000 ? 1 : pannes + 1; // une panne après une minute de marche remet le compteur
61
+ const attente = Math.min(delaiMaxS, delaiS * 2 ** Math.min(pannes - 1, 10));
62
+ dire(`panne (code ${code ?? '-'}${signal ? `, signal ${signal}` : ''}) : relance dans ${attente} s`);
63
+ minuteur = setTimeout(lancer, attente * 1000);
64
+ });
65
+ };
66
+ const arreter = () => {
67
+ if (arrete) return; arrete = true; clearTimeout(minuteur);
68
+ if (!enfant) { dire('arrêté'); terminer(0); return; }
69
+ // D'abord la demande polie par le canal IPC (sous Windows, un « signal » tue sans prévenir), puis le signal.
70
+ try { if (enfant.connected) enfant.send({ arreter: true }); } catch { /* canal fermé */ }
71
+ const tuer = (s) => { try { enfant?.kill(s); } catch { /* déjà fini */ } };
72
+ if (plateforme === 'win32') setTimeout(() => tuer('SIGTERM'), 3000).unref(); else tuer('SIGTERM');
73
+ setTimeout(() => tuer('SIGKILL'), 8000).unref();
74
+ };
75
+ const surSignal = () => arreter();
76
+ const signaux = ecouterSignaux ? signauxArret(plateforme) : [];
77
+ for (const s of signaux) process.on(s, surSignal);
78
+ lancer();
79
+ return { fini, arreter };
80
+ }