@danhachuel/jobfinder 0.1.16 → 0.1.17

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.
@@ -60,7 +60,7 @@ async function call(method, endpoint, { body, useCookie = true, raw } = {}) {
60
60
 
61
61
  const server = spawn(process.execPath, ['src/server/index.mjs'], {
62
62
  cwd: process.cwd(),
63
- env: { ...process.env, JOBFINDER_HOME: HOME, JOBFINDER_PORT: String(PORT) },
63
+ env: { ...process.env, JOBFINDER_HOME: HOME, JOBFINDER_PORT: String(PORT), JOBFINDER_NO_WORKER: '1' },
64
64
  stdio: ['ignore', 'pipe', 'pipe'],
65
65
  });
66
66
  server.stdout.on('data', (d) => process.stdout.write(` [server] ${d}`));
@@ -53,7 +53,7 @@ async function call(method, endpoint, body) {
53
53
 
54
54
  const server = spawn(process.execPath, ['src/server/index.mjs'], {
55
55
  cwd: process.cwd(),
56
- env: { ...process.env, JOBFINDER_HOME: HOME, JOBFINDER_PORT: String(PORT) },
56
+ env: { ...process.env, JOBFINDER_HOME: HOME, JOBFINDER_PORT: String(PORT), JOBFINDER_NO_WORKER: '1' },
57
57
  stdio: ['ignore', 'pipe', 'pipe'],
58
58
  });
59
59
  server.stdout.on('data', () => {});
@@ -16,7 +16,7 @@ fs.mkdirSync(OUT, { recursive: true });
16
16
 
17
17
  const server = spawn(process.execPath, ['src/server/index.mjs'], {
18
18
  cwd: process.cwd(),
19
- env: { ...process.env, JOBFINDER_HOME: HOME, JOBFINDER_PORT: String(PORT), JOBFINDER_NO_OPEN: '1' },
19
+ env: { ...process.env, JOBFINDER_HOME: HOME, JOBFINDER_PORT: String(PORT), JOBFINDER_NO_OPEN: '1', JOBFINDER_NO_WORKER: '1' },
20
20
  stdio: ['ignore', 'pipe', 'pipe'],
21
21
  });
22
22
  server.stdout.on('data', () => {});
@@ -41,7 +41,7 @@ function check(name, condition, extra = '') {
41
41
 
42
42
  const server = spawn(process.execPath, ['src/server/index.mjs'], {
43
43
  cwd: process.cwd(),
44
- env: { ...process.env, JOBFINDER_HOME: HOME, JOBFINDER_PORT: String(PORT), JOBFINDER_NO_OPEN: '1' },
44
+ env: { ...process.env, JOBFINDER_HOME: HOME, JOBFINDER_PORT: String(PORT), JOBFINDER_NO_OPEN: '1', JOBFINDER_NO_WORKER: '1' },
45
45
  stdio: ['ignore', 'pipe', 'pipe'],
46
46
  });
47
47
  server.stdout.on('data', () => {});
@@ -156,7 +156,7 @@ if (strayStart.length) {
156
156
  await delay(800);
157
157
  }
158
158
 
159
- const cli = spawn(process.execPath, ['scripts/cli.mjs', 'start', '--port', String(PORT), '--no-open'], {
159
+ const cli = spawn(process.execPath, ['scripts/cli.mjs', '--foreground', '--port', String(PORT), '--no-open'], {
160
160
  cwd: process.cwd(),
161
161
  env: { ...process.env, JOBFINDER_HOME: HOME, JOBFINDER_NO_OPEN: '1', JOBFINDER_WORKER_INTERVAL: '4000' },
162
162
  stdio: ['ignore', 'pipe', 'pipe'],
@@ -171,7 +171,7 @@ try {
171
171
  check('servidor respondeu na porta', up);
172
172
  const spawnedPid = await waitForWorker();
173
173
  check('processo worker.mjs foi spawnado', spawnedPid !== null && isPidAlive(spawnedPid), `pid=${spawnedPid}`);
174
- check('CLI anunciou o worker', /Worker\s+:\s+automa/.test(cliOut));
174
+ check('worker está rodando (spawnado pelo servidor)', spawnedPid !== null && isPidAlive(spawnedPid), `pid=${spawnedPid}`);
175
175
 
176
176
  await api('POST', '/auth/login', { email: 'dan.hachuel@gmail.com', password: '123456' });
177
177
  const statusAlive = await api('GET', '/worker/status');
@@ -63,6 +63,7 @@ const server = spawn(process.execPath, ['src/server/index.mjs'], {
63
63
  JOBFINDER_PORT: String(PORT),
64
64
  JOBFINDER_INITIAL_EMAIL: ENV_EMAIL,
65
65
  JOBFINDER_INITIAL_PASSWORD: ENV_PASSWORD,
66
+ JOBFINDER_NO_WORKER: '1',
66
67
  },
67
68
  stdio: ['ignore', 'pipe', 'pipe'],
68
69
  });
@@ -52,13 +52,13 @@ if (REMOTE_VERSION) {
52
52
 
53
53
  // `shell: true` é obrigatório no Windows para spawnar um .cmd (npx.cmd).
54
54
  const npx = REMOTE_VERSION
55
- ? spawn(`npx --yes @danhachuel/jobfinder@${REMOTE_VERSION} start --port ${PORT}`, {
55
+ ? spawn(`npx --yes @danhachuel/jobfinder@${REMOTE_VERSION} --foreground --port ${PORT}`, {
56
56
  cwd: FOREIGN_CWD,
57
57
  shell: true,
58
58
  env: { ...process.env, JOBFINDER_HOME: HOME, JOBFINDER_NO_WORKER: '1' },
59
59
  stdio: ['ignore', 'pipe', 'pipe'],
60
60
  })
61
- : spawn(process.execPath, [path.join(REPO_ROOT, 'scripts', 'cli.mjs'), 'start', '--port', String(PORT)], {
61
+ : spawn(process.execPath, [path.join(REPO_ROOT, 'scripts', 'cli.mjs'), '--foreground', '--port', String(PORT)], {
62
62
  cwd: FOREIGN_CWD,
63
63
  env: { ...process.env, JOBFINDER_HOME: HOME, JOBFINDER_NO_WORKER: '1' },
64
64
  stdio: ['ignore', 'pipe', 'pipe'],
@@ -149,7 +149,7 @@ try { direct.kill('SIGKILL'); } catch { /* já morreu */ }
149
149
  // really roda) — o worker não pode derrubar o launcher.
150
150
  // ------------------------------------------------------------------ *
151
151
  console.log('\n== caminho padrão com worker ativo ==');
152
- const full = spawn(process.execPath, [path.join(REPO_ROOT, 'scripts', 'cli.mjs'), 'start', '--port', String(PORT + 2)], {
152
+ const full = spawn(process.execPath, [path.join(REPO_ROOT, 'scripts', 'cli.mjs'), '--foreground', '--port', String(PORT + 2)], {
153
153
  cwd: FOREIGN_CWD,
154
154
  env: { ...process.env, JOBFINDER_HOME: HOME },
155
155
  stdio: ['ignore', 'pipe', 'pipe'],
@@ -168,7 +168,16 @@ check('app completo (com worker) respondeu HTTP', fullHttp);
168
168
  await delay(6000);
169
169
  check('app completo continua vivo', full.exitCode === null && full.signalCode === null, `exitCode=${full.exitCode} signal=${full.signalCode}`);
170
170
  const workerPids = fullOut.split('\n').filter((l) => l.includes('Worker')).slice(0, 1).join('');
171
- check('worker foi anunciado', /Worker\s+:/.test(fullOut), workerPids.trim());
171
+ // Desde a 0.1.17 o worker é spawnado pelo SERVIDOR (não pelo launcher): a
172
+ // prova é o processo vivo + o registro em worker-state.json.
173
+ const workerPid = (() => {
174
+ try {
175
+ return JSON.parse(fs.readFileSync(path.join(HOME, 'worker-state.json'), 'utf8')).pid ?? null;
176
+ } catch {
177
+ return null;
178
+ }
179
+ })();
180
+ check('worker está rodando (spawnado pelo servidor)', workerPid !== null && workerPid > 0, `pid=${workerPid}`);
172
181
  try { full.kill('SIGTERM'); } catch { /* já morreu */ }
173
182
  await delay(3000);
174
183
  try { full.kill('SIGKILL'); } catch { /* já morreu */ }
@@ -1,15 +1,15 @@
1
1
  /**
2
- * Modo daemon (0.1.16): o servidor sobrevive ao terminal.
2
+ * Modo daemon (0.1.17): runtime permanente + daemon (arquitetura PandaNews).
3
3
  *
4
- * 1. `--daemon` volta ao prompt IMEDIATO (processo pai sai com código 0)
5
- * 2. o servidor continua vivo em background, detached do terminal
6
- * 3. responde HTTP 200
7
- * 4. o log em ~/.jobfinder/jobfinder.log tem o banner e a versão correta
8
- * 5. `stop` encerra o daemon (HTTP falha depois)
9
- * 6. rodar duas vezes não duplica (detecta o pid ativo)
10
- * 7. matar o terminal não mata o daemon (o teste simula: o PAI morre)
4
+ * 1. `--daemon` (agora o PADRÃO) volta ao prompt imediatamente
5
+ * 2. o servidor continua vivo em background, a partir do runtime permanente
6
+ * 3. responde HTTP 200 e grava o log em ~/.jobfinder/jobfinder.log
7
+ * 4. o lock ~/.jobfinder/jobfinder.pid registra a instância
8
+ * 5. rodar duas vezes não duplica (mata a anterior)
9
+ * 6. `stop` encerra o daemon e limpa o lock
11
10
  *
12
11
  * Uso: node scripts/manual-tests/fase5-daemon.mjs
12
+ * Nota: a cobertura completa do runtime está em fase6-runtime-daemon.mjs.
13
13
  */
14
14
  import { spawn } from 'node:child_process';
15
15
  import fs from 'node:fs';
@@ -47,8 +47,7 @@ function isAlive(pid) {
47
47
 
48
48
  function daemonPid() {
49
49
  try {
50
- const info = JSON.parse(fs.readFileSync(path.join(HOME, 'jobfinder-daemon.json'), 'utf8'));
51
- return info.pid ?? null;
50
+ return JSON.parse(fs.readFileSync(path.join(HOME, 'jobfinder.pid'), 'utf8')).pid ?? null;
52
51
  } catch {
53
52
  return null;
54
53
  }
@@ -79,20 +78,20 @@ launcher.stderr.on('data', (d) => { launcherOut += String(d); });
79
78
 
80
79
  const launcherExit = await new Promise((resolve) => {
81
80
  launcher.on('exit', (code) => resolve(code));
82
- setTimeout(() => resolve(null), 20000);
81
+ setTimeout(() => resolve(null), 120000);
83
82
  });
84
83
  const elapsed = Date.now() - started;
85
84
  check('launcher saiu com código 0', launcherExit === 0, `code=${launcherExit}`);
86
- check('launcher voltou ao prompt rápido (<8s)', elapsed < 8000, `${elapsed}ms`);
87
- check('saída informa PID e log', /PID\s+:\s+\d+/.test(launcherOut) && /jobfinder\.log/.test(launcherOut));
85
+ check('launcher voltou ao prompt rápido (<60s, inclui preparar o runtime)', elapsed < 60000, `${elapsed}ms`);
86
+ check('saída informa PID e URL', /iniciado em background \(PID: \d+\)/.test(launcherOut) && /http:\/\/127\.0\.0\.1:\d+/.test(launcherOut));
88
87
 
89
88
  console.log('\n== 2. Daemon vivo em background ==');
90
89
  const pid = daemonPid();
91
- check('pid do daemon registrado', pid !== null && pid > 0, `pid=${pid}`);
90
+ check('pid do daemon registrado no lock', pid !== null && pid > 0, `pid=${pid}`);
92
91
  check('processo do daemon está rodando', isAlive(pid));
93
92
 
94
93
  let httpData = null;
95
- for (let i = 0; i < 30; i += 1) {
94
+ for (let i = 0; i < 40; i += 1) {
96
95
  httpData = await health();
97
96
  if (httpData) break;
98
97
  await delay(500);
@@ -104,15 +103,11 @@ console.log('\n== 3. Log em disco ==');
104
103
  const logFile = path.join(HOME, 'jobfinder.log');
105
104
  check('arquivo de log existe', fs.existsSync(logFile));
106
105
  const logContent = fs.existsSync(logFile) ? fs.readFileSync(logFile, 'utf8') : '';
107
- check('log tem o banner de startup', /JobFinder v0\.1\.\d+/.test(logContent));
106
+ check('log tem o banner do servidor', new RegExp('JobFinder v0\\.1\\.\\d+').test(logContent));
108
107
  check('log NÃO tem versão 0.0.00', !logContent.includes('0.0.00'));
109
- check('log registra o worker/porta', logContent.length > 50, `${logContent.length} bytes`);
108
+ check('runtime permanente existe', fs.existsSync(path.join(HOME, 'runtime', 'src', 'server', 'index.mjs')));
110
109
 
111
- console.log('\n== 4. Sobrevive à morte do terminal (o launcher já morreu) ==');
112
- check('launcher (terminal) já saiu', launcherExit === 0);
113
- check('daemon continua vivo depois que o terminal morreu', isAlive(pid) && (await health())?.ok === true);
114
-
115
- console.log('\n== 5. Rodar duas vezes não duplica ==');
110
+ console.log('\n== 4. Rodar duas vezes não duplica ==');
116
111
  const second = spawn(process.execPath, [...CLI, '--daemon', '--port', String(PORT)], {
117
112
  cwd: os.tmpdir(),
118
113
  env: { ...process.env, JOBFINDER_HOME: HOME, JOBFINDER_NO_WORKER: '1' },
@@ -122,12 +117,16 @@ let secondOut = '';
122
117
  second.stdout.on('data', (d) => { secondOut += String(d); });
123
118
  const secondExit = await new Promise((resolve) => {
124
119
  second.on('exit', (code) => resolve(code));
125
- setTimeout(() => resolve(null), 15000);
120
+ setTimeout(() => resolve(null), 120000);
126
121
  });
127
- check('segunda execução detecta o daemon ativo', secondExit === 0 && /ja esta rodando/.test(secondOut), secondOut.split('\n')[0] ?? '');
128
- check('pid continua o mesmo (não duplicou)', daemonPid() === pid);
129
-
130
- console.log('\n== 6. stop encerra o daemon ==');
122
+ check('segunda execução volta ao prompt', secondExit === 0, `code=${secondExit}`);
123
+ check('segunda execução detecta/substitui a instância', /iniciado em background/.test(secondOut) || /ja esta rodando/.test(secondOut), secondOut.split('\n')[0] ?? '');
124
+ const pid2 = daemonPid();
125
+ check('lock aponta para uma única instância', isAlive(pid2) && (await health())?.ok === true);
126
+ check('pid anterior não está mais vivo', !isAlive(pid) || pid === pid2, `antigo=${pid} novo=${pid2}`);
127
+ check('servidor responde depois do restart', (await health())?.ok === true);
128
+
129
+ console.log('\n== 5. stop encerra o daemon ==');
131
130
  const stop = spawn(process.execPath, [...CLI, 'stop'], {
132
131
  cwd: os.tmpdir(),
133
132
  env: { ...process.env, JOBFINDER_HOME: HOME },
@@ -137,17 +136,17 @@ let stopOut = '';
137
136
  stop.stdout.on('data', (d) => { stopOut += String(d); });
138
137
  const stopExit = await new Promise((resolve) => {
139
138
  stop.on('exit', (code) => resolve(code));
140
- setTimeout(() => resolve(null), 20000);
139
+ setTimeout(() => resolve(null), 60000);
141
140
  });
141
+ const stopAll = stopOut; // lido após o exit
142
142
  check('stop saiu com código 0', stopExit === 0, `code=${stopExit}`);
143
- check('stop informa que parou', /parado/i.test(stopOut), stopOut.split('\n')[0] ?? '');
143
+ check('stop informa o encerramento', /encerrado|Nenhuma instância/i.test(stopAll), stopAll.split('\n')[0] ?? '');
144
144
  await delay(1500);
145
- check('processo do daemon não existe mais', !isAlive(pid));
146
- const afterStop = await health();
147
- check('HTTP não responde mais', afterStop === null);
148
- check('pid foi limpo no registro', daemonPid() === null, `pid=${daemonPid()}`);
145
+ check('lock foi limpo', daemonPid() === null, `pid=${daemonPid()}`);
146
+ check('porta não responde mais', (await health()) === null);
147
+ check('processo do daemon não existe mais', !isAlive(pid2));
149
148
 
150
- console.log('\n== 7. stop sem daemon não quebra ==');
149
+ console.log('\n== 6. stop sem daemon não quebra ==');
151
150
  const stopAgain = spawn(process.execPath, [...CLI, 'stop'], {
152
151
  cwd: os.tmpdir(),
153
152
  env: { ...process.env, JOBFINDER_HOME: HOME },
@@ -157,12 +156,9 @@ let stopAgainOut = '';
157
156
  stopAgain.stdout.on('data', (d) => { stopAgainOut += String(d); });
158
157
  const stopAgainExit = await new Promise((resolve) => {
159
158
  stopAgain.on('exit', (code) => resolve(code));
160
- setTimeout(() => resolve(null), 15000);
159
+ setTimeout(() => resolve(null), 30000);
161
160
  });
162
161
  check('stop sem daemon roda limpo', stopAgainExit === 0, stopAgainOut.split('\n')[0] ?? '');
163
162
 
164
- // Limpeza de segurança
165
- try { spawn(process.execPath, [...CLI, 'stop'], { cwd: os.tmpdir(), env: { ...process.env, JOBFINDER_HOME: HOME } }); } catch { /* ignore */ }
166
-
167
163
  console.log(`\nResultado: ${passed} passaram, ${failed} falharam.`);
168
164
  process.exit(failed ? 1 : 0);
@@ -0,0 +1,274 @@
1
+ /**
2
+ * Fase 3 (0.1.17): RUNTIME PERMANENTE + DAEMON (arquitetura PandaNews).
3
+ *
4
+ * 1. o runtime ~/.jobfinder/runtime é criado com o código do servidor
5
+ * 2. o servidor NUNCA sobe do cache do npx — sobe do runtime permanente
6
+ * 3. `--daemon` (padrão) volta ao prompt e o servidor continua vivo
7
+ * 4. o lock ~/.jobfinder/jobfinder.pid registra a instância
8
+ * 5. fechar o terminal (morrer o launcher) não mata o servidor
9
+ * 6. rodar duas vezes não empilha instâncias (mata a anterior)
10
+ * 7. `stop` encerra por PID e limpa o lock
11
+ * 8. stale lock (pid morto) não impede novo arranque
12
+ * 9. --foregrade sobe preso ao terminal (depuração)
13
+ *
14
+ * Uso: node scripts/manual-tests/fase6-runtime-daemon.mjs
15
+ */
16
+ import { spawn, execSync } from 'node:child_process';
17
+ import fs from 'node:fs';
18
+ import os from 'node:os';
19
+ import path from 'node:path';
20
+ import process from 'node:process';
21
+ import { setTimeout as delay } from 'node:timers/promises';
22
+
23
+ const PORT = 4577;
24
+ const HOME = path.join(os.tmpdir(), `jobfinder-runtime-${Date.now()}`);
25
+ const APP = `http://127.0.0.1:${PORT}`;
26
+ const REPO = path.resolve(path.dirname(new URL(import.meta.url).pathname.slice(1)), '..', '..');
27
+ const VERSION = JSON.parse(fs.readFileSync(path.join(REPO, 'package.json'), 'utf8')).version;
28
+
29
+ let passed = 0;
30
+ let failed = 0;
31
+ const procsToKill = [];
32
+
33
+ function check(name, condition, extra = '') {
34
+ if (condition) {
35
+ passed += 1;
36
+ console.log(` OK ${name}${extra ? ` — ${extra}` : ''}`);
37
+ } else {
38
+ failed += 1;
39
+ console.log(` FAIL ${name}${extra ? ` — ${extra}` : ''}`);
40
+ }
41
+ }
42
+
43
+ function run(args, { cwd = os.tmpdir(), env = {} } = {}) {
44
+ const child = spawn(process.execPath, [path.join(REPO, 'scripts', 'cli.mjs'), ...args], {
45
+ cwd,
46
+ env: { ...process.env, JOBFINDER_HOME: HOME, JOBFINDER_NO_WORKER: '1', ...env },
47
+ stdio: ['ignore', 'pipe', 'pipe'],
48
+ });
49
+ let out = '';
50
+ let err = '';
51
+ child.stdout.on('data', (d) => { out += String(d); });
52
+ child.stderr.on('data', (d) => { err += String(d); });
53
+ procsToKill.push(child);
54
+ return {
55
+ child,
56
+ out: () => out,
57
+ err: () => err,
58
+ done: () => new Promise((r) => child.on('exit', (c) => r(c))),
59
+ };
60
+ }
61
+
62
+ /** Linha de comando de um PID (para provar de onde o servidor subiu). */
63
+ function cmdlineOf(pid) {
64
+ try {
65
+ const out = execSync(
66
+ `powershell -NoProfile -Command "Get-CimInstance Win32_Process -Filter ProcessId=${pid} | Select-Object -ExpandProperty CommandLine"`,
67
+ { encoding: 'utf8' }
68
+ );
69
+ return out.trim();
70
+ } catch {
71
+ return '';
72
+ }
73
+ }
74
+
75
+ async function healthOk() {
76
+ try {
77
+ return (await fetch(`${APP}/api/health`)).ok;
78
+ } catch {
79
+ return false;
80
+ }
81
+ }
82
+
83
+ async function healthJson() {
84
+ try {
85
+ return await (await fetch(`${APP}/api/health`)).json();
86
+ } catch {
87
+ return null;
88
+ }
89
+ }
90
+
91
+ function daemonPid() {
92
+ try {
93
+ return JSON.parse(fs.readFileSync(path.join(HOME, 'jobfinder.pid'), 'utf8')).pid ?? null;
94
+ } catch {
95
+ return null;
96
+ }
97
+ }
98
+
99
+ function isAlive(pid) {
100
+ if (!pid) return false;
101
+ try {
102
+ process.kill(Number(pid), 0);
103
+ return true;
104
+ } catch (err) {
105
+ return err?.code === 'EPERM';
106
+ }
107
+ }
108
+
109
+ function runtimeDir() {
110
+ return path.join(HOME, 'runtime');
111
+ }
112
+
113
+ /** Texto do log JSONL diário (onde o logger escreve, não o stdout). */
114
+ function dailyLogText() {
115
+ const day = new Date().toISOString().slice(0, 10);
116
+ const file = path.join(HOME, 'logs', `${day}.jsonl`);
117
+ return fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
118
+ }
119
+
120
+ async function waitUp(attempts = 60) {
121
+ for (let i = 0; i < attempts; i += 1) {
122
+ if (await healthOk()) return true;
123
+ await delay(500);
124
+ }
125
+ return false;
126
+ }
127
+
128
+ /* ------------------------------------------------------------------ */
129
+ console.log('\n== 1. Runtime permanente é criado ==');
130
+ const first = run(['--port', String(PORT)]);
131
+ const code = await first.done();
132
+ check('launcher volta ao prompt (exit 0)', code === 0, `code=${code}`);
133
+ const output = first.out();
134
+ console.log(output.split('\n').filter(Boolean).map((l) => ` ${l}`).join('\n'));
135
+ if (code !== 0 && first.err().trim()) {
136
+ console.log(' --- stderr ---');
137
+ console.log(first.err().split('\n').filter(Boolean).slice(0, 8).map((l) => ` ${l}`).join('\n'));
138
+ }
139
+
140
+ check('runtime ~/.jobfinder/runtime foi criado', fs.existsSync(path.join(runtimeDir(), 'src', 'server', 'index.mjs')));
141
+ check('.version do runtime bate com o pacote',
142
+ fs.existsSync(path.join(runtimeDir(), '.version')) &&
143
+ fs.readFileSync(path.join(runtimeDir(), '.version'), 'utf8').trim() === VERSION,
144
+ `runtime=${VERSION}`);
145
+ check('UI buildada foi copiada', fs.existsSync(path.join(runtimeDir(), 'src', 'ui', 'dist', 'index.html')));
146
+ check('node_modules NÃO foi copiado (runtime enxuto)', !fs.existsSync(path.join(runtimeDir(), 'src', 'server', 'node_modules')));
147
+ check('mensagem de background com PID e URL', /iniciado em background \(PID: \d+\)/.test(output) && /http:\/\/127\.0\.0\.1:\d+/.test(output));
148
+
149
+ console.log('\n== 2. Servidor sobe DO RUNTIME, não do cache do npx ==');
150
+ const up = await waitUp();
151
+ check('servidor responde HTTP 200', up);
152
+ const pid = daemonPid();
153
+ check('lock jobfinder.pid escrito com o PID', pid !== null && pid > 0, `pid=${pid}`);
154
+ check('processo do daemon está vivo', isAlive(pid));
155
+ const cmdline = cmdlineOf(pid);
156
+ check('linha de comando aponta para ~/.jobfinder/runtime', cmdline.includes('runtime'), cmdline);
157
+ check('lock registra a porta', JSON.parse(fs.readFileSync(path.join(HOME, 'jobfinder.pid'), 'utf8')).port === PORT);
158
+
159
+ console.log('\n== 3. Log em disco ==');
160
+ const logFile = path.join(HOME, 'jobfinder.log');
161
+ check('~/.jobfinder/jobfinder.log existe', fs.existsSync(logFile));
162
+ const logContent = fs.existsSync(logFile) ? fs.readFileSync(logFile, 'utf8') : '';
163
+ check('log tem o banner do servidor', new RegExp(`JobFinder v${VERSION.replace(/\./g, '\\.')}`).test(logContent));
164
+ check('log NÃO tem versão 0.0.00', !logContent.includes('0.0.00'));
165
+ check('worker desativado por JOBFINDER_NO_WORKER no log', /desativado por JOBFINDER_NO_WORKER/.test(dailyLogText()));
166
+
167
+ console.log('\n== 4. Sobrevive à morte do terminal ==');
168
+ check('launcher já morreu (terminal livre)', code === 0);
169
+ check('servidor continua vivo', isAlive(pid) && (await healthOk()));
170
+
171
+ console.log('\n== 3b. O servidor SUPERVISIONA o worker (sem JOBFINDER_NO_WORKER) ==');
172
+ // Porta dedicada: esta instância não pode derrubar a da seção 1 (que o teste
173
+ // 4 ainda usa para provar a sobrevivência ao terminal).
174
+ const WORKER_PORT = PORT + 1;
175
+ const withWorker = run(['--port', String(WORKER_PORT)], { env: { JOBFINDER_NO_WORKER: '' } });
176
+ await withWorker.done();
177
+ let workerUp = false;
178
+ for (let i = 0; i < 40; i += 1) {
179
+ try {
180
+ if ((await fetch(`http://127.0.0.1:${WORKER_PORT}/api/health`)).ok) { workerUp = true; break; }
181
+ } catch { /* subindo */ }
182
+ await delay(500);
183
+ }
184
+ check('segunda instância subiu na porta dedicada', workerUp);
185
+ await new Promise((resolve) => setTimeout(resolve, 4000));
186
+ check('servidor inicia o worker sozinho', /worker iniciado pelo servidor/.test(dailyLogText()));
187
+ const workerPid = (() => {
188
+ try {
189
+ const state = JSON.parse(fs.readFileSync(path.join(HOME, 'worker-state.json'), 'utf8'));
190
+ return state.pid ?? null;
191
+ } catch {
192
+ return null;
193
+ }
194
+ })();
195
+ check('worker-state.json tem PID do worker', workerPid !== null && workerPid > 0, `pid=${workerPid}`);
196
+ check('processo worker.mjs está rodando', workerPid !== null && isAlive(workerPid));
197
+ // encerra esta instância para o resto do teste
198
+ const stopWorkerRun = run(['stop'], { env: { JOBFINDER_PORT: String(WORKER_PORT) } });
199
+ await stopWorkerRun.done();
200
+ await new Promise((resolve) => setTimeout(resolve, 2500));
201
+ check('stop encerrou o servidor E o worker', !isAlive(workerPid));
202
+ const workerPortDown = await fetch(`http://127.0.0.1:${WORKER_PORT}/api/health`).then(() => true).catch(() => false);
203
+ check('porta do worker deixou de responder', !workerPortDown);
204
+
205
+ console.log('\n== 5. Rodar duas vezes não empilha instâncias ==');
206
+ const second = run(['--port', String(PORT)]);
207
+ const code2 = await second.done();
208
+ const out2 = second.out();
209
+ check('segunda execução volta ao prompt', code2 === 0, `code=${code2}`);
210
+ check('instância anterior foi encerrada antes', /Encerrando instância anterior|runtime/.test(out2), out2.split('\n')[1] ?? '');
211
+ await delay(1000);
212
+ const pid2 = daemonPid();
213
+ check('lock aponta para uma instância só', isAlive(pid2) && (await healthOk()));
214
+ check('pid anterior não está mais vivo', !isAlive(pid) || pid === pid2, `antigo=${pid} novo=${pid2}`);
215
+ check('servidor responde depois do restart', await waitUp());
216
+
217
+ console.log('\n== 6. Lock obsoleto (pid morto) não impede arranque ==');
218
+ const stalePid = daemonPid();
219
+ if (stalePid) {
220
+ try {
221
+ execSync(`powershell -NoProfile -Command "Stop-Process -Id ${stalePid} -Force"`, { stdio: 'ignore' });
222
+ } catch { /* já morto */ }
223
+ }
224
+ await delay(1500);
225
+ fs.writeFileSync(path.join(HOME, 'jobfinder.pid'), JSON.stringify({ pid: stalePid, port: PORT, version: VERSION }, null, 2), 'utf8');
226
+ const third = run(['--port', String(PORT)]);
227
+ const code3 = await third.done();
228
+ check('terceira execução sobe mesmo com lock obsoleto', code3 === 0 && (await waitUp()), `code=${code3}`);
229
+
230
+ console.log('\n== 7. stop encerra e limpa ==');
231
+ const stop = run(['stop']);
232
+ const stopCode = await stop.done();
233
+ const stopAll = stop.out() + stop.err(); // lido DEPOIS do exit (captura completa)
234
+ check('stop volta ao prompt', stopCode === 0, `code=${stopCode}`);
235
+ check('stop informa o encerramento', /encerrado|Nenhuma instância/i.test(stopAll), stopAll.split('\n')[0] ?? '');
236
+ await delay(2000);
237
+ check('lock foi limpo', !fs.existsSync(path.join(HOME, 'jobfinder.pid')) || daemonPid() === null, `pid=${daemonPid()}`);
238
+ check('porta não responde mais', !(await healthOk()));
239
+ const lastPid = daemonPid();
240
+ check('processo do daemon não existe mais', !isAlive(lastPid));
241
+
242
+ console.log('\n== 8. --foreground prende o servidor ao terminal ==');
243
+ const fg = run(['--foreground', '--port', String(PORT)]);
244
+ await new Promise((resolve) => setTimeout(resolve, 6000));
245
+ check('launcher foreground continua vivo (não volta ao prompt)', fg.child.exitCode === null, `exitCode=${fg.child.exitCode}`);
246
+ const fgOut = fg.out();
247
+ check('modo foreground anunciado', /modo foreground/.test(fgOut));
248
+ check('servidor foreground responde HTTP', await waitUp());
249
+ check('saída do servidor é encaminhada', /listening on|JobFinder v/.test(fgOut));
250
+ fg.child.kill('SIGTERM');
251
+ await new Promise((resolve) => setTimeout(resolve, 3000));
252
+ check('Ctrl+C no launcher encerra o servidor', !(await healthOk()));
253
+ const fg2 = run(['--foreground', '--port', String(PORT)]);
254
+ await new Promise((resolve) => setTimeout(resolve, 6000));
255
+ check('foreground sobe novamente', await waitUp());
256
+ fg2.child.kill('SIGTERM');
257
+ await new Promise((resolve) => setTimeout(resolve, 3000));
258
+
259
+ /* ------------------------------------------------------------------ */
260
+ // Limpeza: nenhum processo desta suíte sobrevive.
261
+ for (const proc of procsToKill) {
262
+ try { proc.kill('SIGKILL'); } catch { /* já morreu */ }
263
+ }
264
+ await delay(500);
265
+ const leftover = daemonPid();
266
+ if (isAlive(leftover)) {
267
+ try {
268
+ execSync(`powershell -NoProfile -Command "Stop-Process -Id ${leftover} -Force"`, { stdio: 'ignore' });
269
+ } catch { /* já morto */ }
270
+ }
271
+
272
+ console.log(`\nResultado: ${passed} passaram, ${failed} falharam.`);
273
+ console.log(`Home: ${HOME} · Runtime: ${runtimeDir()}`);
274
+ process.exit(failed ? 1 : 0);