@danhachuel/jobfinder 0.1.11 → 0.1.13

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/CHANGELOG.md CHANGED
@@ -6,6 +6,40 @@ All notable changes to JobFinder are documented in this file.
6
6
 
7
7
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
8
8
 
9
+ ## [0.1.13] — 2026-11-20
10
+
11
+ ### Changed
12
+
13
+ - **Arquitetura: servidor Express embutido no processo do CLI (fim do `spawn`)**: `scripts/cli.mjs` agora importa `start()` de `src/server/index.mjs` diretamente e roda o `app.listen()` **no próprio processo**. Um socket de servidor escutando na porta mantém o event loop do Node aberto **matematicamente** — nenhum comportamento de terminal hostil (MobaXterm, wrapper do npx, redirecionamento, pipes fechados) pode mais esvaziá-lo. Esta é a correção definitiva para o encerramento prematuro que perseguia o Windows desde a 0.1.7.
14
+ - **Worker desacoplado e silencioso**: o worker continua sendo processo filho (tarefas pesadas não travam a UI), mas agora com `stdio: ['ignore','ignore','ignore']` — ele **grava seus logs em arquivo** (`worker.log` para o ciclo de vida e `worker-error.log` para falhas). Um terminal que engasga ao ler os pipes do worker não tem mais como perturbá-lo. A detecção de órfão por `stdin` EOF e o `JOBFINDER_TAKEOVER` permanecem.
15
+ - **Sinais**: o CLI encerra o worker no primeiro Ctrl+C e o shutdown gracioso do servidor (mesmo processo) assume a partir daí; o segundo sinal força a saída.
16
+
17
+ ### Fixed
18
+
19
+ - **Resiliência inquebrável do launcher**: `keep-alive` de 24 h sem `unref()` no `start`, handlers de `unhandledRejection`/`uncaughtException`/EPIPE no topo e o registro `[jobfinder] launcher exiting with code N` — nenhuma morte futura fica sem explicação.
20
+
21
+ ### Tests
22
+
23
+ - **Novo teste de estresse** (`startup-keepalive.mjs`, ambiente hostil): sobe o app pelo CLI, **destrói o `stdout`/`stderr` do launcher** (simulando a queda do MobaXterm) e **mata o worker à força** — o CLI continua vivo, o servidor responde HTTP 200 em todos os pontos e o worker é reiniciado. Suíte completa: 38 keepalive + 39 fase2-worker + 32 auth + 16 serviços + 22 E2E + 5 unit.
24
+
25
+ ## [0.1.12] — 2026-11-18
26
+
27
+ ### Security
28
+
29
+ - **Remoção definitiva da senha no terminal**: a linha `Login: <email> / <senha>` foi **deletada** do startup do servidor — o terminal não exibe mais e-mail nem senha (a dica de "troque a senha padrão" continua apenas na UI, em Configurações → Segurança). Verificado em boot real: stdout/stderr sem `123456`, sem e-mail e sem `Login:`.
30
+
31
+ ### Fixed
32
+
33
+ - **`EPERM` no `rename` atômico (Windows)**: `JsonStore.write` agora usa `renameAtomic` — em `EPERM`/`EACCES`/`EBUSY` (antivírus, editor ou outro processo segurando o destino) o rename é retentado com backoff (5 × 50 ms) e, se ainda falhar, o destino é removido antes da última tentativa (`unlink` + `rename`); falha definitiva limpa o `.tmp` e propaga o erro. Nenhum `.tmp` órfão em nenhum caminho.
34
+ - **Worker não morre por falha de escrita de estado**: `patchState`/`patchStateSync` envolvem a escrita em try/catch — `EPERM` (ou qualquer erro de I/O) VAI para `worker-error.log` + log + console e a escrita é tentada de novo no próximo tick/heartbeat; `process.exit` não é chamado.
35
+ - **Restart do worker determinístico (fim do falso "outro worker dono")**: (1) detecção de órfão por **pipe** — o supervisor mantém o stdin do worker aberto; quando ele morre (inclusive kill externo), o worker vê EOF e se encerra na hora, sem depender de `ppid` (que o Windows recicla); (2) o launcher passa `JOBFINDER_TAKEOVER=1` em seus spawns — no boot e no restart, uma heartbeat velha de pid reciclado nunca mais bloqueia o worker novo.
36
+ - **Loop do worker à prova de fuga síncrona**: callbacks dos timers (tick e heartbeat) em try/catch, com re-agendamento.
37
+
38
+ ### Tests
39
+
40
+ - `tests/test_atomic_write_concurrency.js` (stub → real, node:test): 40 updates concorrentes sem perder registro, mutator que lança preserva o arquivo anterior, `.tmp` restante não quebra o store, **rename travado com EPERM retentado até dar certo** e **EPERM permanente falhando alto sem .tmp órfão**.
41
+ - `startup-keepalive.mjs`: novo cenário **worker direto com rename sabotado (EPERM permanente)** — sobrevive, registra em `worker-error.log`. Suíte: 32 keepalive + 39 fase2-worker + 32 auth + 16 serviços + 22 E2E.
42
+
9
43
  ## [0.1.11] — 2026-11-16
10
44
 
11
45
  ### Fixed
package/README.md CHANGED
@@ -130,7 +130,7 @@ session per repository, surgical scope (no unrequested refactors), atomic JSON w
130
130
  the store, Windows runtime resilience, contract tests that exercise real behavior, and
131
131
  predictable React state.
132
132
 
133
- Layout: `scripts/cli.mjs` (launcher) · `src/server/` (Express API, JSON store, LinkedIn + LLM services, workers) · `src/ui/` (React + Vite + Tailwind v4) · `.agents/skills/` (regression rules) · `tests/` (contract/concurrency/UI stubs).
133
+ Layout: `scripts/cli.mjs` (launcher — embute o Express via import: o `app.listen()` roda no próprio processo) · `src/server/` (Express API, JSON store, LinkedIn + LLM services, worker autônomo) · `src/ui/` (React + Vite + Tailwind v4) · `.agents/skills/` (regression rules) · `tests/` (contract/concurrency/UI stubs).
134
134
 
135
135
  ## Publishing
136
136
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@danhachuel/jobfinder",
3
- "version": "0.1.11",
3
+ "version": "0.1.13",
4
4
  "description": "JobFinder — LinkedIn automation platform (posts, connections/DMs, job matching) with a React + Vite UI. Intelligent workflows, JSON storage.",
5
5
  "keywords": [
6
6
  "linkedin",
package/scripts/cli.mjs CHANGED
@@ -16,7 +16,6 @@
16
16
  * --open / --no-open open/do not open the browser on start
17
17
  * --dry-run start with automation in dry-run mode (nothing is really sent)
18
18
  */
19
- import { spawn } from 'node:child_process';
20
19
  import fs from 'node:fs';
21
20
  import path from 'node:path';
22
21
  import os from 'node:os';
@@ -24,7 +23,7 @@ import process from 'node:process';
24
23
  import { fileURLToPath } from 'node:url';
25
24
 
26
25
  import { ensureDataDir, resolveDataDir, isDataDirHealthy } from '../src/server/storage/bootstrap.mjs';
27
- import { spawnWorker, spawnSupervised, forwardChildOutput } from '../src/server/workerRuntime.mjs';
26
+ import { spawnWorker } from '../src/server/workerRuntime.mjs';
28
27
 
29
28
  /**
30
29
  * Process resilience for the launcher — installed before anything else runs
@@ -32,8 +31,8 @@ import { spawnWorker, spawnSupervised, forwardChildOutput } from '../src/server/
32
31
  * explanation):
33
32
  *
34
33
  * 1. unhandledRejection — since Node 15 any unhandled promise rejection
35
- * terminates the process immediately. Log it and keep supervising the
36
- * server child instead of dying without a trace.
34
+ * terminates the process immediately. Log it instead of dying without
35
+ * a trace.
37
36
  * 2. EPIPE on stdio — when the shell behind stdout disappears (Windows
38
37
  * terminals, MobaXterm, redirection), the next console.log throws an
39
38
  * unhandled 'error' and kills the launcher.
@@ -56,7 +55,6 @@ for (const stream of [process.stdout, process.stderr]) {
56
55
 
57
56
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
58
57
  const ROOT = path.resolve(__dirname, '..');
59
- const SERVER_ENTRY = path.join(ROOT, 'src', 'server', 'index.mjs');
60
58
  const UI_DIST = path.join(ROOT, 'src', 'ui', 'dist');
61
59
 
62
60
  const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8'));
@@ -173,10 +171,6 @@ async function commandStart({ port, host, dataDir, dryRun }) {
173
171
  const resolved = resolveDataDir(dataDir);
174
172
  ensureDataDir(resolved);
175
173
 
176
- if (!fs.existsSync(SERVER_ENTRY)) {
177
- console.error(`[jobfinder] server entry not found at ${SERVER_ENTRY}`);
178
- process.exit(1);
179
- }
180
174
  if (!fs.existsSync(path.join(UI_DIST, 'index.html'))) {
181
175
  console.warn(
182
176
  '[jobfinder] UI build not found (src/ui/dist). The API will run, but the UI will be blank.\n' +
@@ -184,14 +178,6 @@ async function commandStart({ port, host, dataDir, dryRun }) {
184
178
  );
185
179
  }
186
180
 
187
- const env = {
188
- ...process.env,
189
- JOBFINDER_DATA_DIR: resolved,
190
- JOBFINDER_DRY_RUN: dryRun ? '1' : process.env.JOBFINDER_DRY_RUN || '',
191
- };
192
- if (port) env.JOBFINDER_PORT = String(port);
193
- if (host) env.JOBFINDER_HOST = host;
194
-
195
181
  printBanner();
196
182
  const listenPort = port || Number(process.env.JOBFINDER_PORT) || 4040;
197
183
  const listenHost = host || process.env.JOBFINDER_HOST || '127.0.0.1';
@@ -201,40 +187,53 @@ async function commandStart({ port, host, dataDir, dryRun }) {
201
187
  console.log(` URL : ${url}`);
202
188
  console.log(' Press Ctrl+C to stop.\n');
203
189
 
204
- // The server is a supervised child: piped stdio (never 'inherit' — a
205
- // broken terminal must not kill it), windowsHide + a new process group.
206
- // Its output is forwarded below; the CLI relays it to the terminal.
207
- const child = spawnSupervised(SERVER_ENTRY, { env, cwd: ROOT });
208
- forwardChildOutput(child, '');
190
+ // ------------------------------------------------------------------ *
191
+ // ARCHITECTURE (0.1.13): the Express server runs INSIDE this process.
192
+ //
193
+ // `start()` imports src/server/index.mjs in-process and app.listen()
194
+ // opens a real TCP socket on 4040. A listening server socket keeps the
195
+ // Node event loop open MATHEMATICALLY — nothing about the terminal
196
+ // (MobaXterm, the npx wrapper, output redirection, closed pipes) can
197
+ // empty the loop and take the process down anymore. The worker stays a
198
+ // separate child so its heavy tasks never block the server.
199
+ // ------------------------------------------------------------------ *
200
+ process.env.JOBFINDER_DATA_DIR = resolved;
201
+ process.env.JOBFINDER_PORT = String(listenPort);
202
+ process.env.JOBFINDER_HOST = listenHost;
203
+ if (dryRun) process.env.JOBFINDER_DRY_RUN = '1';
209
204
 
210
- // Background worker: a SEPARATE process so the automation queues keep
211
- // running when the browser is closed (or was never opened). Spawn follows
212
- // runtime-guard: windowsHide + new process group + piped stdio (never
213
- // 'inherit'). Disable with JOBFINDER_NO_WORKER=1.
205
+ // Supervisão do worker. O CLI NUNCA depende do worker para viver: ele
206
+ // roda com stdio ['ignore','ignore','ignore'] (logs em arquivo) e, se
207
+ // morrer, o launcher apenas registra e reinicia — o servidor segue.
214
208
  let worker = null;
215
209
  let workerRestarts = 0;
216
210
  let stopping = false;
211
+ let serverRef = null;
212
+
213
+ const stopChildren = () => {
214
+ if (worker && worker.exitCode === null && worker.signalCode === null) {
215
+ worker.kill('SIGTERM');
216
+ // Hard deadline: a worker that ignores SIGTERM must not linger.
217
+ setTimeout(() => {
218
+ if (worker.exitCode === null && worker.signalCode === null) worker.kill('SIGKILL');
219
+ }, 2000).unref();
220
+ }
221
+ };
217
222
 
218
- /**
219
- * Supervise the worker.
220
- *
221
- * THE LAUNCHER NEVER DIES BECAUSE OF THE WORKER. An exit here only logs
222
- * (the server keeps serving) and, while the server is still up, starts a
223
- * fresh worker so the automation queues never stop silently. process.exit
224
- * is NEVER called on this path.
225
- */
226
223
  const startWorker = () => {
227
- worker = spawnWorker({ env: { JOBFINDER_DATA_DIR: resolved } });
228
- forwardChildOutput(worker, '[worker]');
224
+ // JOBFINDER_TAKEOVER: o launcher acabou de subir (o supervisor anterior
225
+ // já se foi) ou observou a saída do worker — heartbeat velha não pode
226
+ // bloquear este spawn.
227
+ worker = spawnWorker({ env: { JOBFINDER_DATA_DIR: resolved, JOBFINDER_TAKEOVER: '1' } });
229
228
  worker.on('exit', (code, signal) => {
230
229
  const reason = signal ? `signal ${signal}` : `code ${code}`;
231
230
  console.error(`\n[jobfinder] worker encerrou (${reason}). O servidor web continua rodando.`);
232
- const serverAlive = child.exitCode === null && child.signalCode === null;
231
+ const serverAlive = Boolean(serverRef?.listening);
233
232
  if (!stopping && serverAlive && workerRestarts < 5) {
234
233
  workerRestarts += 1;
235
234
  console.error(`[jobfinder] reiniciando o worker (tentativa ${workerRestarts}/5)...`);
236
- // Re-check `stopping`: a shutdown that starts while this timer is
237
- // pending must never leave an orphan behind.
235
+ // Re-check `stopping`: um shutdown que começa enquanto este timer
236
+ // está pendente nunca pode deixar um órfão para trás.
238
237
  setTimeout(() => {
239
238
  if (!stopping) startWorker();
240
239
  }, 3000);
@@ -243,52 +242,23 @@ async function commandStart({ port, host, dataDir, dryRun }) {
243
242
  return worker;
244
243
  };
245
244
 
246
- if (process.env.JOBFINDER_NO_WORKER === '1') {
247
- console.log(' Worker : disabled (JOBFINDER_NO_WORKER=1)');
248
- } else {
249
- startWorker();
250
- console.log(` Worker : automação em segundo plano (pid ${worker.pid})`);
251
- }
245
+ // Keep-alive inquebrável: timer de 24h SEM unref. Segurança extra — o
246
+ // socket do servidor (abaixo) já é a garantia principal.
247
+ setInterval(() => {}, 24 * 60 * 60 * 1000);
252
248
 
253
- // The `child` handle keeps this launcher's event loop open for as long as
254
- // the server runs: the CLI stays in the foreground and the terminal only
255
- // returns to the prompt when the server itself exits (or on Ctrl+C).
256
- //
257
- // Independent keep-alive: the launcher must NEVER depend on a child handle
258
- // to stay alive (regression 0.1.7 — an empty event loop makes Node exit
259
- // with code 0, silently, right after the startup banner). This referenced
260
- // timer holds the loop open by itself; explicit process.exit() calls in
261
- // the signal/exit handlers below still terminate immediately.
262
- const keepAlive = setInterval(() => {}, 60_000);
263
- void keepAlive;
264
-
265
- // Forensic trail: if the launcher ever dies, the reason is visible.
249
+ // Forensic trail: se o launcher morrer, o motivo fica visível.
266
250
  process.on('exit', (code) => {
267
251
  console.error(`[jobfinder] launcher exiting with code ${code}.`);
268
252
  });
269
253
 
270
- const stopChildren = () => {
271
- if (worker && worker.exitCode === null && worker.signalCode === null) {
272
- worker.kill('SIGTERM');
273
- // Hard deadline: a worker that ignores SIGTERM must not linger.
274
- setTimeout(() => {
275
- if (worker.exitCode === null && worker.signalCode === null) worker.kill('SIGKILL');
276
- }, 2000).unref();
277
- }
278
- };
254
+ // Sinais: o primeiro encerra o worker e deixa o shutdown gracioso do
255
+ // servidor (registrado dentro de start(), abaixo) rodar; o segundo força.
279
256
  const forward = (signal) => () => {
280
- // A second Ctrl+C must never be ignored: force the exit if the graceful
281
- // path is stuck.
282
257
  if (stopping) {
283
258
  process.exit(1);
284
259
  }
285
260
  stopping = true;
286
261
  stopChildren();
287
- if (child.exitCode !== null || child.signalCode !== null) {
288
- process.exit(child.exitCode ?? (child.signalCode ? 1 : 0));
289
- return;
290
- }
291
- child.kill(signal);
292
262
  };
293
263
  process.on('SIGINT', forward('SIGINT'));
294
264
  process.on('SIGTERM', forward('SIGTERM'));
@@ -299,14 +269,23 @@ async function commandStart({ port, host, dataDir, dryRun }) {
299
269
  // Opening a browser window on the user's machine without being asked
300
270
  // is not acceptable for a hosted (SaaS) product.
301
271
 
302
- child.on('exit', (code, signal) => {
303
- // Loud, visible reason: the server ending must never look like a silent
304
- // crash back at the prompt.
305
- const reason = signal ? `signal ${signal}` : `code ${code}`;
306
- console.error(`\n[jobfinder] server exited (${reason}).`);
272
+ // Sobe o servidor Express NO PRÓPRIO PROCESSO (dinâmico: mantém --help,
273
+ // --version e install leves, sem carregar o Express).
274
+ try {
275
+ const { start } = await import('../src/server/index.mjs');
276
+ ({ server: serverRef } = await start());
277
+ } catch (err) {
278
+ console.error('[jobfinder] falha ao iniciar o servidor:', err?.message ?? err);
307
279
  stopChildren();
308
- process.exit(code ?? (signal ? 1 : 0));
309
- });
280
+ process.exit(1);
281
+ }
282
+
283
+ if (process.env.JOBFINDER_NO_WORKER === '1') {
284
+ console.log(' Worker : disabled (JOBFINDER_NO_WORKER=1)');
285
+ } else {
286
+ startWorker();
287
+ console.log(` Worker : automação em segundo plano (pid ${worker.pid})`);
288
+ }
310
289
  }
311
290
 
312
291
  function commandVersion() {
@@ -13,7 +13,12 @@
13
13
  * 5. worker: sobe com o app, o CLI sobrevive ao crash dele (e o
14
14
  * reinicia), modo JOBFINDER_NO_WORKER=1
15
15
  * 6. worker direto: rejection injetada -> worker-error.log em disco e o
16
- * processo continua vivo; pipes quebrados (EPIPE) não o derrubam
16
+ * processo continua vivo; pipes quebrados (EPIPE) não o derrubam;
17
+ * rename sempre EPERM (arquivo travado no Windows) não o derruba
18
+ * 7. ambiente hostil (arquitetura 0.1.13): servidor Express embutido no
19
+ * processo do CLI, stdout/stderr destruídos (queda do MobaXterm) e
20
+ * worker morto — o socket do app.listen() mantém tudo vivo e o HTTP
21
+ * continua 200, com o worker reiniciado
17
22
  *
18
23
  * Uso: node scripts/manual-tests/startup-keepalive.mjs
19
24
  */
@@ -279,6 +284,51 @@ async function bootAndObserve(label, { args, port, observeMs, env = {} }) {
279
284
  fs.rmSync(tmp, { recursive: true, force: true });
280
285
  }
281
286
 
287
+ // 9) worker direto: rename SEMPRE EPERM (antivirus/arquivo travado no
288
+ // Windows) -> o worker NAO morre; o erro vai para worker-error.log e a
289
+ // escrita é tentada de novo no próximo tick/heartbeat.
290
+ {
291
+ console.log('\n== worker direto: EPERM no rename (arquivo travado) ==');
292
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'jobfinder-keepalive-wperm-'));
293
+ const home = path.join(tmp, 'data');
294
+ ensureDataDir(home);
295
+ const sabotage = path.join(tmp, 'eperm.cjs');
296
+ fs.writeFileSync(
297
+ sabotage,
298
+ `const fs = require('node:fs');\n` +
299
+ `const real = fs.renameSync.bind(fs);\n` +
300
+ `fs.renameSync = (from, to) => {\n` +
301
+ ` if (String(to).endsWith('worker-state.json')) {\n` +
302
+ ` const err = new Error('EPERM: operation not permitted, rename');\n` +
303
+ ` err.code = 'EPERM';\n` +
304
+ ` throw err;\n` +
305
+ ` }\n` +
306
+ ` return real(from, to);\n` +
307
+ `};\n`
308
+ );
309
+ const worker = spawn(process.execPath, [path.join(ROOT, 'src', 'server', 'worker.mjs')], {
310
+ cwd: ROOT,
311
+ env: { ...process.env, JOBFINDER_DATA_DIR: home, JOBFINDER_NO_OPEN: '1', JOBFINDER_WORKER_INTERVAL: '4000', NODE_OPTIONS: `--require ${sabotage}` },
312
+ stdio: ['ignore', 'pipe', 'pipe'],
313
+ });
314
+ let out = '';
315
+ worker.stdout.on('data', (d) => { out += String(d); });
316
+ worker.stderr.on('data', (d) => { out += String(d); });
317
+ await wait(9000);
318
+ check('worker sobrevive ao EPERM no rename', !dead(worker), dead(worker) ? `exitCode=${worker.exitCode} signal=${worker.signalCode}` : 'vivo');
319
+ let errorLog = '';
320
+ try {
321
+ errorLog = fs.readFileSync(path.join(home, 'worker-error.log'), 'utf8');
322
+ } catch {
323
+ /* arquivo pode nao existir */
324
+ }
325
+ check('EPERM registrado em worker-error.log', /EPERM/.test(errorLog), errorLog.split('\n')[0]?.slice(0, 100) ?? 'vazio');
326
+ check('worker-state write failed registrado (não engolido em silêncio)', /worker-state write failed/i.test(errorLog));
327
+ worker.kill();
328
+ await wait(800);
329
+ fs.rmSync(tmp, { recursive: true, force: true });
330
+ }
331
+
282
332
  // 6) JOBFINDER_NO_WORKER=1: modo sem worker, CLI continua vivo
283
333
  {
284
334
  console.log('\n== boot sem worker (JOBFINDER_NO_WORKER=1) ==');
@@ -301,5 +351,57 @@ async function bootAndObserve(label, { args, port, observeMs, env = {} }) {
301
351
  fs.rmSync(tmp, { recursive: true, force: true });
302
352
  }
303
353
 
354
+ // 10) ARQUITETURA 0.1.13: servidor DENTRO do processo do CLI + ambiente
355
+ // hostil. Destrói o stdout/stderr do launcher (simulando a queda do
356
+ // MobaXterm) e mata o worker à força: o socket do app.listen() mantém
357
+ // o processo vivo e respondendo HTTP 200 — e o worker é reiniciado.
358
+ {
359
+ console.log('\n== ambiente hostil: stdout destruído + worker morto (servidor embutido) ==');
360
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'jobfinder-keepalive-hostil-'));
361
+ const home = path.join(tmp, 'data');
362
+ const child = spawn(process.execPath, [path.join(ROOT, 'scripts', 'cli.mjs'), 'start', '--no-open'], {
363
+ cwd: ROOT,
364
+ env: { ...process.env, JOBFINDER_PORT: '4190', JOBFINDER_DATA_DIR: home, JOBFINDER_NO_OPEN: '1' },
365
+ stdio: ['ignore', 'pipe', 'pipe'],
366
+ });
367
+ let out = '';
368
+ child.stdout.on('data', (d) => { out += String(d); });
369
+ child.stderr.on('data', (d) => { out += String(d); });
370
+
371
+ const workerPid = async () => {
372
+ try {
373
+ return JSON.parse(fs.readFileSync(path.join(home, 'worker-state.json'), 'utf8')).pid ?? null;
374
+ } catch {
375
+ return null;
376
+ }
377
+ };
378
+
379
+ await wait(5000);
380
+ const pid0 = await workerPid();
381
+ check('servidor embutido subiu pelo CLI (HTTP 200 antes do caos)', (await getStatus(4190, '/api/health')) === 200, `worker pid=${pid0}`);
382
+
383
+ // Queda do terminal: a ponta de leitura dos pipes do launcher é destruída.
384
+ child.stdout.destroy();
385
+ child.stderr.destroy();
386
+ await wait(1000);
387
+ check('CLI sobrevive à destruição do stdout/stderr', !dead(child), dead(child) ? `exitCode=${child.exitCode} signal=${child.signalCode}` : 'vivo');
388
+ check('servidor continua respondendo após o stdout cair', (await getStatus(4190, '/api/health')) === 200);
389
+
390
+ // Morte forçada do worker (Task Manager / kill externo).
391
+ try {
392
+ process.kill(Number(pid0), 'SIGTERM');
393
+ } catch {
394
+ /* processo pode ja ter saido */
395
+ }
396
+ await wait(6000);
397
+ check('CLI sobrevive à morte do worker', !dead(child), dead(child) ? `exitCode=${child.exitCode} signal=${child.signalCode}` : 'vivo');
398
+ check('servidor continua respondendo após a morte do worker', (await getStatus(4190, '/api/health')) === 200);
399
+ const pid1 = await workerPid();
400
+ check('worker foi reiniciado pelo launcher', pid1 !== null && pid1 !== pid0, `antes=${pid0} depois=${pid1}`);
401
+ child.kill();
402
+ await wait(800);
403
+ fs.rmSync(tmp, { recursive: true, force: true });
404
+ }
405
+
304
406
  console.log(`\nResultado: ${passed} passaram, ${failed} falharam.`);
305
407
  process.exit(failed ? 1 : 0);
@@ -127,7 +127,9 @@ export async function start() {
127
127
  } else {
128
128
  console.log('REAL MODE: live LinkedIn actions are enabled (dry-run is OFF).');
129
129
  }
130
- console.log(`Login: ${auth.getUser().email}${auth.usingDefaultPassword() ? ' / 123456 (troque a senha em Configurações)' : ''}`);
130
+ // Credentials are NEVER printed to the terminal (security): the local
131
+ // account is managed in the UI (Configurações → Segurança). A dangling
132
+ // `Login:` line here leaked the default e-mail/password to every console.
131
133
  });
132
134
 
133
135
  // Pin the server handle: the listening socket keeps the event loop (and
@@ -14,7 +14,7 @@ import { Router } from 'express';
14
14
 
15
15
  import { asyncRoute } from '../middleware/errors.mjs';
16
16
  import { runWorkerPass } from '../services/workers.mjs';
17
- import { spawnWorker, forwardChildOutput } from '../workerRuntime.mjs';
17
+ import { spawnWorker } from '../workerRuntime.mjs';
18
18
  import {
19
19
  readWorkerControl,
20
20
  readWorkerState,
@@ -49,8 +49,9 @@ export function workerRoutes({ store, logger, config, rateLimiter }) {
49
49
  let spawned = false;
50
50
  if (!alive) {
51
51
  try {
52
+ // stdio ignore: o worker escreve logs em arquivo (worker.log,
53
+ // worker-error.log), nunca no pipe do servidor.
52
54
  const child = spawnWorker({ env: { JOBFINDER_DATA_DIR: store.dataDir } });
53
- forwardChildOutput(child, '[jobfinder:worker]');
54
55
  child.on('exit', (code, signal) => {
55
56
  logger.info('worker', 'worker process exited', { reason: signal ? `signal ${signal}` : `code ${code}` });
56
57
  });
@@ -10,6 +10,60 @@ import fs from 'node:fs';
10
10
  import path from 'node:path';
11
11
  import { randomUUID } from 'node:crypto';
12
12
 
13
+ /** Synchronous sleep — the only dependency-free one in Node. */
14
+ function sleepSync(ms) {
15
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
16
+ }
17
+
18
+ /**
19
+ * Atomic replace with Windows patience.
20
+ *
21
+ * On Windows, `rename` over a file that ANY process still holds open —
22
+ * antivirus scanning the data dir, an editor, another node process that
23
+ * opened it without FILE_SHARE_DELETE — fails with EPERM/EACCES/EBUSY.
24
+ * The rename is the LAST step of every atomic write, so the write retries
25
+ * with backoff (5 × 50 ms) and, if the destination is still locked, drops
26
+ * it first: Windows allows deleting a locked file far more often than
27
+ * renaming over it.
28
+ *
29
+ * @param {string} tmp temp file holding the new content
30
+ * @param {string} file destination
31
+ * @throws the OS error when every attempt failed (callers decide how bad
32
+ * that is — a heartbeat failure must never kill a process)
33
+ */
34
+ function renameAtomic(tmp, file) {
35
+ const RETRY_DELAY_MS = 50;
36
+ const MAX_ATTEMPTS = 5;
37
+ let lastErr = null;
38
+ for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt += 1) {
39
+ try {
40
+ fs.renameSync(tmp, file);
41
+ return;
42
+ } catch (err) {
43
+ const code = err?.code;
44
+ if (code !== 'EPERM' && code !== 'EACCES' && code !== 'EBUSY') throw err;
45
+ lastErr = err;
46
+ if (attempt < MAX_ATTEMPTS) sleepSync(RETRY_DELAY_MS);
47
+ }
48
+ }
49
+ // Fallback: remove the locked destination (best-effort) and rename once more.
50
+ try {
51
+ fs.unlinkSync(file);
52
+ } catch {
53
+ /* the rename below may still succeed: only it can report failure */
54
+ }
55
+ try {
56
+ fs.renameSync(tmp, file);
57
+ } catch (err) {
58
+ try {
59
+ fs.unlinkSync(tmp); // never leave the .tmp behind
60
+ } catch {
61
+ /* best effort */
62
+ }
63
+ throw err ?? lastErr;
64
+ }
65
+ }
66
+
13
67
  export function newId(prefix) {
14
68
  return `${prefix}_${randomUUID().replace(/-/g, '').slice(0, 12)}`;
15
69
  }
@@ -71,7 +125,7 @@ export class JsonStore {
71
125
  const tmp = `${file}.tmp.${process.pid}`;
72
126
  fs.mkdirSync(path.dirname(file), { recursive: true });
73
127
  fs.writeFileSync(tmp, `${JSON.stringify(data, null, 2)}\n`, 'utf8');
74
- fs.renameSync(tmp, file);
128
+ renameAtomic(tmp, file);
75
129
  this.cache.set(name, data);
76
130
  return data;
77
131
  }