Skip to content

Commit 9df9f4d

Browse files
committed
test: reproduce the Windows app's unerasable task folder and silent refusals
Red on purpose, before the fix: - desktop/scripts/effacement-electron.mjs, run by app-bureau.yml under the Electron the app ships: a task prepared twice without cleanup (a hive restarted mid-task). Under Electron's libc++ Node, fs.rmSync cannot delete git's read-only objects on Windows (nodejs/node#64374): this is Hive 0.5.0's "clone impossible : EPERM, Permission denied" loop. - tests/dossier-tache-tenu.test.ts: a previous task folder that really is held (a process's cwd on Windows, a non-writable dir elsewhere) must be refused with a reason that names the held file, then fail after the bounded refusals with a cockpit alert that does not blame an agent. - tests/requisition-mid-task.test.ts: an infra refusal must carry what the agent said, not a bare "agent indisponible (auth/quota)". - tests/cockpit.test.ts: an alert records whether the refusals happened before the agent. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent fe9fafd commit 9df9f4d

5 files changed

Lines changed: 307 additions & 0 deletions

File tree

‎.github/workflows/app-bureau.yml‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,13 @@ jobs:
105105
- name: Installer les dépendances de l'app
106106
run: npm ci --prefix desktop
107107

108+
# Le nœud tourne dans l'Electron de l'app, pas dans le Node de la CI — et
109+
# sous Windows, les deux n'effacent pas pareil un clone git (objets en
110+
# lecture seule) : Hive 0.5.0 refusait chaque tentative d'une tâche dont
111+
# la précédente avait été tuée. Voir desktop/scripts/effacement-electron.mjs.
112+
- name: Le dossier d'une tâche s'efface sous l'Electron de l'app
113+
run: node desktop/scripts/effacement-electron.mjs
114+
108115
- name: Construire les paquets
109116
run: npm --prefix desktop run ${{ matrix.dist }}
110117
env:
Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
// LE DOSSIER D'UNE TÂCHE, EFFACÉ PAR L'ELECTRON DE L'APP —
2+
// `node desktop/scripts/effacement-electron.mjs`, après `npm run build` et
3+
// `npm ci --prefix desktop`.
4+
//
5+
// ─── POURQUOI CE BANC TOURNE ICI, ET PAS DANS VITEST ─────────────────────────
6+
//
7+
// Dans l'app, la Reine et les ouvrières tournent dans le binaire d'Electron en
8+
// mode Node (`ELECTRON_RUN_AS_NODE`, `desktop/app/piece.cjs`) — pas dans le
9+
// Node de la CI. Et les deux n'effacent pas pareil : `fs.rmSync` est du C++
10+
// posé sur `std::filesystem`, et sous Windows la libc++ d'Electron refuse un
11+
// fichier en lecture seule là où la STL du Node officiel l'efface
12+
// (nodejs/node#64374). Git pose ses objets en lecture seule : dans Hive 0.5.0,
13+
// le dossier d'une tentative tuée ne s'effaçait plus (« EPERM, Permission
14+
// denied »), et chaque tentative suivante était refusée. La suite vitest, sous
15+
// le Node officiel, était verte ; seul ce binaire-ci montre la panne.
16+
//
17+
// Le banc prépare donc DEUX fois la même tâche avec le vrai `prepareWorkspace`
18+
// compilé (`dist/`), sans effacer entre les deux — une ruche redémarrée en
19+
// pleine tâche —, sous l'Electron que l'app embarque. Il dit aussi ce que fait
20+
// `rmSync` de ce runtime sur un fichier en lecture seule : un vert là où
21+
// `rmSync` efface ne prouverait rien.
22+
23+
import { execFileSync, spawnSync } from 'node:child_process';
24+
import {
25+
chmodSync,
26+
mkdirSync,
27+
mkdtempSync,
28+
readdirSync,
29+
rmSync,
30+
statSync,
31+
writeFileSync,
32+
} from 'node:fs';
33+
import { rm } from 'node:fs/promises';
34+
import { createRequire } from 'node:module';
35+
import { tmpdir } from 'node:os';
36+
import path from 'node:path';
37+
import { fileURLToPath, pathToFileURL } from 'node:url';
38+
39+
const ICI = fileURLToPath(import.meta.url);
40+
const RACINE = path.resolve(path.dirname(ICI), '..', '..');
41+
42+
// ─── Sous Node : relancer ce fichier dans l'Electron de l'app ───────────────
43+
if (process.versions.electron === undefined) {
44+
const electron = createRequire(ICI)('electron');
45+
const r = spawnSync(electron, [ICI], {
46+
stdio: 'inherit',
47+
env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },
48+
});
49+
process.exit(r.status ?? 1);
50+
}
51+
52+
function git(cwd, ...args) {
53+
execFileSync('git', ['-c', '[email protected]', '-c', 'user.name=Banc Hive', ...args], {
54+
cwd,
55+
stdio: 'ignore',
56+
});
57+
}
58+
59+
/** Les fichiers en lecture seule sous `dossier` — ce que git y a posé. */
60+
function lectureSeule(dossier) {
61+
let n = 0;
62+
for (const e of readdirSync(dossier, { withFileTypes: true, recursive: true })) {
63+
if (e.isFile() && (statSync(path.join(e.parentPath, e.name)).mode & 0o200) === 0) n += 1;
64+
}
65+
return n;
66+
}
67+
68+
const { prepareWorkspace } = await import(
69+
pathToFileURL(path.join(RACINE, 'dist', 'node-client', 'workspace.js')).href
70+
);
71+
const banc = mkdtempSync(path.join(tmpdir(), 'hive-effacement-'));
72+
let code = 0;
73+
try {
74+
const temoin = path.join(banc, 'lecture-seule');
75+
writeFileSync(temoin, 'x');
76+
chmodSync(temoin, 0o444);
77+
let refus = null;
78+
try {
79+
rmSync(temoin, { force: true });
80+
} catch (e) {
81+
refus = e.code ?? String(e);
82+
}
83+
console.log(
84+
`runtime : Electron ${process.versions.electron}, Node ${process.versions.node} · ` +
85+
`rmSync d'un fichier en lecture seule : ${refus === null ? 'effacé' : `REFUSÉ (${refus})`}`,
86+
);
87+
88+
const amont = path.join(banc, 'amont');
89+
mkdirSync(amont);
90+
git(amont, 'init', '-q', '-b', 'main');
91+
writeFileSync(path.join(amont, 'a.txt'), 'base\n');
92+
git(amont, 'add', '-A');
93+
git(amont, 'commit', '-q', '-m', 'base');
94+
95+
const travail = path.join(banc, 'travail');
96+
const tache = { id: 'banc-effacement', branch: null };
97+
const premiere = await prepareWorkspace(travail, tache, amont);
98+
console.log(`1re tentative : ${lectureSeule(premiere.cwd)} fichier(s) en lecture seule laissés`);
99+
// Pas de `cleanup` : la ruche a redémarré pendant la tâche.
100+
const seconde = await prepareWorkspace(travail, tache, amont);
101+
console.log(`✔ 2e tentative préparée dans ${seconde.cwd}`);
102+
await seconde.cleanup();
103+
} catch (e) {
104+
console.error(`✘ ${e instanceof Error ? e.message : String(e)}`);
105+
code = 1;
106+
} finally {
107+
await rm(banc, { recursive: true, force: true, maxRetries: 5 });
108+
}
109+
process.exit(code);

‎tests/cockpit.test.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,7 @@ describe('ce qui arrête la ruche', () => {
159159
raison: 'claude : non authentifié',
160160
depuis: echec.ts,
161161
definitif: true,
162+
avantAgent: false,
162163
},
163164
]);
164165
// Relancée (de nouveau prête) : l'alerte se lève.
@@ -183,6 +184,27 @@ describe('ce qui arrête la ruche', () => {
183184
).toBe(0);
184185
});
185186

187+
it('un échec dont les refus ont eu lieu AVANT l’agent ne met pas l’agent en cause', () => {
188+
// Le dossier de la tentative précédente, tenu (Hive 0.5.0 sous Windows) :
189+
// aucun agent n'a tourné. L'alerte le porte, pour que l'écran ne dise pas
190+
// « réparez l'agent » (tests/dossier-tache-tenu.test.ts, de bout en bout).
191+
const refus = ev('task_rejected', {
192+
taskId: 't',
193+
nodeId: 'n',
194+
reason: 'dossier de la tâche impossible à vider — un processus le tient-il encore ? (EBUSY)',
195+
infra: true,
196+
avantAgent: true,
197+
});
198+
const echec = ev('task_failed', { taskId: 't', reason: 'no_working_agent', infraRejects: 3 });
199+
expect(
200+
alertesCockpit(entree({ evenements: [refus, echec], tacheDe: taches({ t: 'failed' }) }))
201+
.alertes,
202+
).toMatchObject([{ genre: 'refus', definitif: true, avantAgent: true }]);
203+
expect(
204+
alertesCockpit(entree({ evenements: [refus], tacheDe: taches({ t: 'ready' }) })).alertes,
205+
).toMatchObject([{ genre: 'refus', definitif: false, avantAgent: true }]);
206+
});
207+
186208
it('une relecture qui attend une famille absente alerte tant qu’elle est prête', () => {
187209
const attente = ev('contre_expertise_review_waiting', {
188210
taskId: 'prod',

‎tests/dossier-tache-tenu.test.ts‎

Lines changed: 163 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
1+
// Le dossier d'une tâche que la tentative précédente a laissé, et qu'on ne peut
2+
// plus effacer : la tâche doit finir en échec VISIBLE, avec la vraie cause.
3+
//
4+
// ─── LA PANNE QUE CE BANC TIENT FERMÉE ───────────────────────────────────────
5+
//
6+
// Hive 0.5.0, application de bureau sous Windows : la ruche redémarre pendant
7+
// qu'une ouvrière travaille, et le dossier de la tâche reste, clone compris.
8+
// À la tentative suivante, `prepareWorkspace` ne pouvait plus l'effacer
9+
// (`effacerDossier`, workspace.ts, dit pourquoi) et le refus partait sous
10+
// « clone impossible : EPERM … » — une panne de dépôt ou d'identifiants qui
11+
// n'existait pas. Le compte des refus concluait bien, mais en « aucun agent
12+
// qui fonctionne — réparez l'agent » : deux fausses pistes pour l'opérateur.
13+
//
14+
// Ici le dossier est TENU pour de vrai, par le moyen que chaque système offre :
15+
// un processus vivant dont c'est le répertoire courant sous Windows (un tel
16+
// dossier ne s'efface pas), un sous-dossier sans droit d'écriture ailleurs
17+
// (hors root, qui passe outre). Puis le vrai chemin : une Reine réelle, un
18+
// `HiveNodeClient`, et la mesure de ce que l'écran reçoit — le refus, puis
19+
// l'échec borné et l'alerte de l'accueil (`/api/cockpit`).
20+
21+
import { type ChildProcess, execFileSync, spawn } from 'node:child_process';
22+
import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
23+
import os from 'node:os';
24+
import path from 'node:path';
25+
import { afterEach, describe, expect, it } from 'vitest';
26+
import type { AgentAdapter } from '../src/adapters/index.js';
27+
import { HiveNodeClient } from '../src/node-client/client.js';
28+
import { createServer } from '../src/orchestrator/server.js';
29+
30+
const TOKEN = 'jeton-dossier-tache-tenu-long';
31+
const WINDOWS = process.platform === 'win32';
32+
const RACINE = typeof process.getuid === 'function' && process.getuid() === 0;
33+
34+
const aNettoyer: (() => void)[] = [];
35+
afterEach(() => {
36+
for (const f of aNettoyer.splice(0).reverse()) f();
37+
});
38+
39+
function git(cwd: string, ...args: string[]): void {
40+
execFileSync('git', ['-c', '[email protected]', '-c', 'user.name=Banc Hive', ...args], {
41+
cwd,
42+
stdio: 'ignore',
43+
});
44+
}
45+
46+
/** Tient `dossier` jusqu'au nettoyage du banc. */
47+
function tenir(dossier: string): void {
48+
const objets = path.join(dossier, '.git', 'objects', 'pack');
49+
mkdirSync(objets, { recursive: true });
50+
writeFileSync(path.join(objets, 'pack-banc.pack'), 'objet\n');
51+
if (WINDOWS) {
52+
const garde: ChildProcess = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], {
53+
cwd: objets,
54+
stdio: 'ignore',
55+
});
56+
aNettoyer.push(() => garde.kill());
57+
return;
58+
}
59+
chmodSync(objets, 0o555);
60+
aNettoyer.push(() => chmodSync(objets, 0o755));
61+
}
62+
63+
describe.skipIf(RACINE)('un dossier de tâche qui ne s’efface plus', () => {
64+
it(
65+
'refus qui nomme le dossier tenu, puis échec borné que l’accueil DIT — sans parler de clone',
66+
{ timeout: 90_000 },
67+
async () => {
68+
const racine = mkdtempSync(path.join(os.tmpdir(), 'hive-dossier-tenu-'));
69+
aNettoyer.push(() => rmSync(racine, { recursive: true, force: true, maxRetries: 5 }));
70+
const amont = path.join(racine, 'amont');
71+
mkdirSync(amont);
72+
git(amont, 'init', '-q', '-b', 'main');
73+
writeFileSync(path.join(amont, 'a.txt'), 'base\n');
74+
git(amont, 'add', '-A');
75+
git(amont, 'commit', '-q', '-m', 'base');
76+
77+
let lance = false;
78+
const adapter: AgentAdapter = {
79+
name: 'jamais-lance',
80+
async run() {
81+
lance = true;
82+
return { success: true, diff: '', logs: '', subAgents: [] };
83+
},
84+
};
85+
const server = await createServer({
86+
port: 0,
87+
host: '127.0.0.1',
88+
token: TOKEN,
89+
corsOrigins: ['http://localhost:5173'],
90+
dbPath: path.join(racine, 'hive.db'),
91+
simulation: false,
92+
tickMs: 20,
93+
});
94+
const work = path.join(racine, 'work');
95+
const client = new HiveNodeClient({
96+
url: `ws://127.0.0.1:${server.port}/ws`,
97+
token: TOKEN,
98+
name: 'noeud-tenu',
99+
ownerName: 'banc',
100+
agentType: 'custom',
101+
nodeId: 'noeud-tenu',
102+
maxConcurrency: 1,
103+
workRoot: work,
104+
adapter,
105+
quiet: true,
106+
});
107+
client.start();
108+
const attendre = async (condition: () => boolean, message: string): Promise<void> => {
109+
const limite = Date.now() + 75_000;
110+
while (Date.now() < limite) {
111+
if (condition()) return;
112+
await new Promise((resolve) => setTimeout(resolve, 25));
113+
}
114+
throw new Error(message);
115+
};
116+
try {
117+
await attendre(
118+
() => server.store.listNodes().some((n) => n.status === 'online'),
119+
'le nœud ne rejoint pas la ruche',
120+
);
121+
const nodeId = server.store.listNodes()[0]!.id;
122+
const projet = server.store.createProject({ name: 'Dossier tenu', repoUrl: amont });
123+
const t = server.store.createTask({
124+
projectId: projet.id,
125+
title: 'Ligne',
126+
prompt: 'ligne',
127+
});
128+
// Le reste de la tentative tuée : `<work>/tasks/<tâche>-<nœud court>`.
129+
tenir(path.join(work, 'tasks', `${t.id}-${nodeId.slice(0, 8)}`));
130+
server.store.patchTask(t.id, { status: 'ready' });
131+
132+
const refus = () =>
133+
server.store
134+
.listEvents(0, 1000)
135+
.filter((e) => e.type === 'task_rejected' && e.payload.taskId === t.id);
136+
await attendre(() => refus().length > 0, 'la tâche n’est jamais refusée');
137+
const premier = refus()[0]!.payload;
138+
expect(premier).toMatchObject({ infra: true, avantAgent: true });
139+
expect(String(premier.reason)).toMatch(
140+
/^dossier de la tâche impossible à vider — un processus le tient-il encore \? \((EBUSY|EPERM|EACCES|ENOTEMPTY) : \.git/,
141+
);
142+
143+
// Un seul nœud : le compte des refus conclut (`rejectTask`), et l'échec
144+
// se lit à l'accueil avec la vraie cause — une préparation, pas un agent.
145+
await attendre(() => server.store.getTask(t.id)?.status === 'failed', 'jamais échouée');
146+
const reponse = await fetch(`http://127.0.0.1:${server.port}/api/cockpit`, {
147+
headers: { 'x-hive-token': TOKEN },
148+
});
149+
const { alertes } = (await reponse.json()) as { alertes: Record<string, unknown>[] };
150+
expect(alertes.find((a) => a.taskId === t.id)).toMatchObject({
151+
genre: 'refus',
152+
definitif: true,
153+
avantAgent: true,
154+
raison: expect.stringMatching(/^dossier de la tâche impossible à vider/),
155+
});
156+
expect(lance).toBe(false);
157+
} finally {
158+
client.stop();
159+
await server.stop();
160+
}
161+
},
162+
);
163+
});

‎tests/requisition-mid-task.test.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -348,6 +348,12 @@ describe('réquisition mid-task — boucle B/C/D', () => {
348348
if (rejet === undefined) await new Promise((r) => setTimeout(r, 60));
349349
}
350350
expect(rejet, 'la tâche doit être réaffectée').toMatchObject({ infra: true });
351+
// Et le refus DIT ce que l'agent a dit : il part sans les logs, et
352+
// « agent indisponible (auth/quota) » seul ne laissait rien à lire à
353+
// l'opérateur (Hive 0.5.0 : l'ouvrière Codex réaffectée sans un mot).
354+
expect(rejet).toMatchObject({
355+
reason: 'agent indisponible : API Error: 429 rate_limit_error',
356+
});
351357
expect(
352358
server.store.listerRequisitions({ statut: 'ouverte' }).filter((r) => r.taskId === taskId),
353359
).toEqual([]);

0 commit comments

Comments
 (0)