@danhachuel/jobfinder 0.1.10 → 0.1.11

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,24 @@ 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.11] — 2026-11-16
10
+
11
+ ### Fixed
12
+
13
+ - **Crash do Worker (exit `4294967295` / `0xFFFFFFFF`) não encerra mais o processo principal** (Windows/MobaXterm): o launcher passou a **supervisionar** o worker — a saída dele só é registrada (`[jobfinder] worker encerrou (code/signal). O servidor web continua rodando.`) e, com o servidor no ar, um worker novo é iniciado automaticamente (até 5 tentativas, 3 s de intervalo; nunca durante o shutdown — sem órfãos). `process.exit` não é chamado nesse caminho.
14
+ - **Worker não morre mais por falha de I/O no console**: escritas em `stdout`/`stderr` passaram por um helper à prova de throw (`safeWrite`); `unhandledRejection` é registrado e o processo **continua rodando** (antes um EPIPE/escrita quebrada no MobaXterm podia derrubar o worker); `uncaughtException` registra e sai(1) — com o launcher reiniciando o worker.
15
+ - **`worker-error.log`**: falhas inesperadas do worker (rejection, exceção, erro de stdio) agora são gravadas em `<dataDir>/worker-error.log` — o único artefato que sobrevive a um pipe morto, permitindo diagnosticar o crash no terminal hostil.
16
+ - **Heartbeat fresca de pid morto não bloqueia mais um worker novo**: `anotherWorkerOwnsState()` confirma que o pid dono do estado está vivo (`process.kill(pid, 0)`). Sem isso, um worker morto por kill externo (que no Windows pula o handler de exit) deixava a heartbeat "fresca" e o restart seria recusado como duplicado.
17
+ - **Loop do worker à prova de fuga**: os callbacks dos timers (tick e heartbeat) estão envoltos em try/catch — uma falha síncrona é reportada e o loop é re-agendado, nunca abandonado.
18
+
19
+ ### Changed
20
+
21
+ - Mensagem de encerramento do worker no launcher agora é em português e explícita sobre a continuidade do servidor.
22
+
23
+ ### Tests
24
+
25
+ - `startup-keepalive.mjs` cobre o worker de ponta a ponta: crash do worker com o CLI vivo + **restart automático** (pid novo assumindo a fila), `worker-error.log` com rejection injetada, worker sobrevivendo a EPIPE com heartbeat no disco. Suíte: 29 keepalive + 39 fase2-worker + 32 auth + 16 serviços + 22 E2E.
26
+
9
27
  ## [0.1.10] — 2026-11-15
10
28
 
11
29
  ### Documentation
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@danhachuel/jobfinder",
3
- "version": "0.1.10",
3
+ "version": "0.1.11",
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
@@ -209,17 +209,44 @@ async function commandStart({ port, host, dataDir, dryRun }) {
209
209
 
210
210
  // Background worker: a SEPARATE process so the automation queues keep
211
211
  // running when the browser is closed (or was never opened). Spawn follows
212
- // windows-runtime-guard: windowsHide + new process group + piped stdio
213
- // (never 'inherit'). Disable with JOBFINDER_NO_WORKER=1.
212
+ // runtime-guard: windowsHide + new process group + piped stdio (never
213
+ // 'inherit'). Disable with JOBFINDER_NO_WORKER=1.
214
214
  let worker = null;
215
- if (process.env.JOBFINDER_NO_WORKER === '1') {
216
- console.log(' Worker : disabled (JOBFINDER_NO_WORKER=1)');
217
- } else {
215
+ let workerRestarts = 0;
216
+ let stopping = false;
217
+
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
+ const startWorker = () => {
218
227
  worker = spawnWorker({ env: { JOBFINDER_DATA_DIR: resolved } });
219
228
  forwardChildOutput(worker, '[worker]');
220
229
  worker.on('exit', (code, signal) => {
221
- console.error(`\n[jobfinder] worker exited (${signal ? `signal ${signal}` : `code ${code}`}).`);
230
+ const reason = signal ? `signal ${signal}` : `code ${code}`;
231
+ console.error(`\n[jobfinder] worker encerrou (${reason}). O servidor web continua rodando.`);
232
+ const serverAlive = child.exitCode === null && child.signalCode === null;
233
+ if (!stopping && serverAlive && workerRestarts < 5) {
234
+ workerRestarts += 1;
235
+ 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.
238
+ setTimeout(() => {
239
+ if (!stopping) startWorker();
240
+ }, 3000);
241
+ }
222
242
  });
243
+ return worker;
244
+ };
245
+
246
+ if (process.env.JOBFINDER_NO_WORKER === '1') {
247
+ console.log(' Worker : disabled (JOBFINDER_NO_WORKER=1)');
248
+ } else {
249
+ startWorker();
223
250
  console.log(` Worker : automação em segundo plano (pid ${worker.pid})`);
224
251
  }
225
252
 
@@ -240,7 +267,6 @@ async function commandStart({ port, host, dataDir, dryRun }) {
240
267
  console.error(`[jobfinder] launcher exiting with code ${code}.`);
241
268
  });
242
269
 
243
- let stopping = false;
244
270
  const stopChildren = () => {
245
271
  if (worker && worker.exitCode === null && worker.signalCode === null) {
246
272
  worker.kill('SIGTERM');
@@ -10,6 +10,10 @@
10
10
  * 4. SIGTERM encerra de forma limpa — verificado emitindo o sinal dentro
11
11
  * do próprio processo (no Windows, child.kill() sempre vira
12
12
  * TerminateProcess e os handlers graceful nunca rodam)
13
+ * 5. worker: sobe com o app, o CLI sobrevive ao crash dele (e o
14
+ * reinicia), modo JOBFINDER_NO_WORKER=1
15
+ * 6. worker direto: rejection injetada -> worker-error.log em disco e o
16
+ * processo continua vivo; pipes quebrados (EPIPE) não o derrubam
13
17
  *
14
18
  * Uso: node scripts/manual-tests/startup-keepalive.mjs
15
19
  */
@@ -20,6 +24,8 @@ import os from 'node:os';
20
24
  import path from 'node:path';
21
25
  import process from 'node:process';
22
26
 
27
+ import { ensureDataDir } from '../../src/server/storage/bootstrap.mjs';
28
+
23
29
  const ROOT = process.cwd();
24
30
  let passed = 0;
25
31
  let failed = 0;
@@ -190,7 +196,7 @@ async function bootAndObserve(label, { args, port, observeMs, env = {} }) {
190
196
  const pid1 = await workerPid();
191
197
  check('worker continua vivo apos os heartbeats (sem falso positivo do guardiao)', pid1 === pid0 && (await getStatus(4185, '/api/health')) === 200, `pid=${pid1}`);
192
198
 
193
- // CRASH do worker: o CLI NAO pode morrer — so logar.
199
+ // CRASH do worker: o CLI NAO pode morrer — so logar (e reiniciar o worker).
194
200
  try {
195
201
  process.kill(Number(pid1), 'SIGTERM');
196
202
  } catch {
@@ -198,13 +204,81 @@ async function bootAndObserve(label, { args, port, observeMs, env = {} }) {
198
204
  }
199
205
  await wait(2500);
200
206
  check('CLI sobrevive ao crash do worker', !dead(child), dead(child) ? `exitCode=${child.exitCode} signal=${child.signalCode}` : 'vivo');
201
- check('SAIBA do worker foi registrada no log', /worker exited/i.test(out), out.split('\n').filter((l) => /worker exited/i.test(l))[0] ?? '');
207
+ check('saida do worker foi registrada no log', /worker encerrou/i.test(out), out.split('\n').filter((l) => /worker encerrou/i.test(l))[0] ?? '');
202
208
  check('servidor continua respondendo apos o crash do worker', (await getStatus(4185, '/api/health')) === 200);
209
+
210
+ // O launcher supervisiona: um worker novo assume a fila.
211
+ await wait(5000);
212
+ const pid2 = await workerPid();
213
+ check('launcher reiniciou o worker automaticamente', pid2 !== null && pid2 !== pid1, `antes=${pid1} depois=${pid2}`);
214
+ check('restart anunciado no log', /reiniciando o worker/i.test(out), out.split('\n').filter((l) => /reiniciando o worker/i.test(l))[0] ?? '');
215
+ check('CLI continua vivo depois do restart', !dead(child) && (await getStatus(4185, '/api/health')) === 200);
203
216
  child.kill();
204
217
  await wait(800);
205
218
  fs.rmSync(tmp, { recursive: true, force: true });
206
219
  }
207
220
 
221
+ // 7) worker direto: rejection injetada -> worker-error.log + processo vivo
222
+ {
223
+ console.log('\n== worker direto: rejection injetada e log em arquivo ==');
224
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'jobfinder-keepalive-wrej-'));
225
+ const home = path.join(tmp, 'data');
226
+ ensureDataDir(home); // o worker exige o skeleton (como o launcher faz)
227
+ const fault = path.join(tmp, 'fault.cjs');
228
+ fs.writeFileSync(fault, "setTimeout(() => { Promise.reject(new Error('fault-injection: worker rejection')); }, 1200);\n");
229
+ const worker = spawn(process.execPath, [path.join(ROOT, 'src', 'server', 'worker.mjs')], {
230
+ cwd: ROOT,
231
+ env: { ...process.env, JOBFINDER_DATA_DIR: home, JOBFINDER_NO_OPEN: '1', JOBFINDER_WORKER_INTERVAL: '4000', NODE_OPTIONS: `--require ${fault}` },
232
+ stdio: ['ignore', 'pipe', 'pipe'],
233
+ });
234
+ let out = '';
235
+ worker.stdout.on('data', (d) => { out += String(d); });
236
+ worker.stderr.on('data', (d) => { out += String(d); });
237
+ await wait(8000);
238
+ check('worker sobrevive a rejection (nao morre silencioso)', !dead(worker), dead(worker) ? `exitCode=${worker.exitCode} signal=${worker.signalCode}` : 'vivo');
239
+ let errorLog = '';
240
+ try {
241
+ errorLog = fs.readFileSync(path.join(home, 'worker-error.log'), 'utf8');
242
+ } catch {
243
+ /* arquivo pode nao existir */
244
+ }
245
+ check('worker-error.log registrou a falha', /fault-injection: worker rejection/.test(errorLog), errorLog.split('\n')[0]?.slice(0, 100) ?? 'vazio');
246
+ check('falha tambem apareceu no console', /unhandled promise rejection ignored/i.test(out));
247
+ worker.kill();
248
+ await wait(800);
249
+ fs.rmSync(tmp, { recursive: true, force: true });
250
+ }
251
+
252
+ // 8) worker direto: stdout/stderr quebrados (EPIPE) -> worker segue vivo
253
+ {
254
+ console.log('\n== worker direto: EPIPE nos pipes ==');
255
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'jobfinder-keepalive-wepipe-'));
256
+ const home = path.join(tmp, 'data');
257
+ ensureDataDir(home); // o worker exige o skeleton (como o launcher faz)
258
+ const worker = spawn(process.execPath, [path.join(ROOT, 'src', 'server', 'worker.mjs')], {
259
+ cwd: ROOT,
260
+ env: { ...process.env, JOBFINDER_DATA_DIR: home, JOBFINDER_NO_OPEN: '1', JOBFINDER_WORKER_INTERVAL: '4000' },
261
+ stdio: ['ignore', 'pipe', 'pipe'],
262
+ });
263
+ worker.stdout.on('data', () => {});
264
+ worker.stderr.on('data', () => {});
265
+ await wait(3000);
266
+ worker.stdout.destroy();
267
+ worker.stderr.destroy();
268
+ await wait(6000);
269
+ check('worker sobrevive ao EPIPE', !dead(worker), dead(worker) ? `exitCode=${worker.exitCode} signal=${worker.signalCode}` : 'vivo');
270
+ let state = null;
271
+ try {
272
+ state = JSON.parse(fs.readFileSync(path.join(home, 'worker-state.json'), 'utf8'));
273
+ } catch {
274
+ /* arquivo pode nao existir */
275
+ }
276
+ check('heartbeat continua sendo publicado sem o console', Boolean(state?.pid) && state.pid === worker.pid, `pid=${state?.pid}`);
277
+ worker.kill();
278
+ await wait(800);
279
+ fs.rmSync(tmp, { recursive: true, force: true });
280
+ }
281
+
208
282
  // 6) JOBFINDER_NO_WORKER=1: modo sem worker, CLI continua vivo
209
283
  {
210
284
  console.log('\n== boot sem worker (JOBFINDER_NO_WORKER=1) ==');
@@ -22,9 +22,10 @@
22
22
  * Rules honoured here (see .agents/skills/): only atomic JSON writes through
23
23
  * the store, dry-run re-checked on every pass against the live config, spawn
24
24
  * flags and stdio handled by the launcher, and no unhandled error can kill
25
- * this process silently (windows-runtime-guard).
25
+ * this process silently (runtime-guard).
26
26
  */
27
27
  import fs from 'node:fs';
28
+ import path from 'node:path';
28
29
  import process from 'node:process';
29
30
 
30
31
  import { createContext } from './context.mjs';
@@ -44,26 +45,66 @@ const INTERVAL_MS = Math.max(2_000, Number(process.env.JOBFINDER_WORKER_INTERVAL
44
45
  const HEARTBEAT_MS = Math.min(5_000, INTERVAL_MS);
45
46
 
46
47
  /* ------------------------------------------------------------------ *
47
- * Process resilience (windows-runtime-guard): never die silently *
48
+ * Process resilience (runtime-guard): never die silently *
48
49
  * ------------------------------------------------------------------ */
49
50
  let logger = null;
51
+ let errorLogPath = null;
50
52
 
51
- process.on('unhandledRejection', (reason) => {
53
+ /**
54
+ * Write that cannot kill the process: a broken stdout/stderr (EPIPE on
55
+ * Windows terminals, MobaXterm, redirection) must never take the worker
56
+ * down — the automation queues would stop for a console line.
57
+ */
58
+ function safeWrite(stream, text) {
59
+ try {
60
+ stream?.write?.(text);
61
+ } catch {
62
+ /* the pipe is gone: the file log keeps the evidence */
63
+ }
64
+ }
65
+
66
+ /**
67
+ * Append one line to <dataDir>/worker-error.log (best-effort, sync).
68
+ * This file is the ONLY artifact that survives a dead pipe: when the
69
+ * process dies on a hostile terminal, the console output is gone but the
70
+ * crash reason stays on disk for diagnosis.
71
+ */
72
+ function appendErrorLog(line) {
73
+ if (!errorLogPath) return;
74
+ try {
75
+ fs.appendFileSync(errorLogPath, `${new Date().toISOString()} ${line}\n`, 'utf8');
76
+ } catch {
77
+ /* the data dir may be read-only: the console mirror still has the line */
78
+ }
79
+ }
80
+
81
+ /** Report an unexpected failure: file log + logger + safe console mirror. */
82
+ function reportUnexpected(scope, reason) {
52
83
  const message = reason instanceof Error ? reason.message : String(reason);
53
- logger?.error('worker', 'unhandled promise rejection ignored', { message });
54
- console.error(`[jobfinder:worker] unhandled promise rejection ignored: ${message}`);
84
+ const stack = reason instanceof Error ? reason.stack : undefined;
85
+ appendErrorLog(`${scope}: ${message}${stack ? `\n${stack}` : ''}`);
86
+ logger?.error('worker', scope, { message, stack });
87
+ safeWrite(process.stderr, `[jobfinder:worker] ${scope}: ${message}\n`);
88
+ }
89
+
90
+ process.on('unhandledRejection', (reason) => {
91
+ // Keep running: the worker owns the automation queues and must survive a
92
+ // stray async failure instead of exiting silently.
93
+ reportUnexpected('unhandled promise rejection ignored', reason);
55
94
  });
56
95
 
57
96
  process.on('uncaughtException', (err) => {
58
- logger?.error('worker', 'uncaught exception - shutting down', { message: err?.message });
59
- console.error('[jobfinder:worker] uncaught exception:', err);
97
+ // An uncaught exception leaves the state undefined: record it, then exit(1)
98
+ // — the launcher supervises the worker and starts a fresh one.
99
+ reportUnexpected('uncaught exception - exiting', err);
60
100
  process.exit(1);
61
101
  });
62
102
 
63
103
  for (const stream of [process.stdout, process.stderr]) {
64
104
  stream?.on?.('error', (err) => {
65
105
  if (err?.code === 'EPIPE') return; // terminal/pipe closed: keep working
66
- console.error(`[jobfinder:worker] stdio error: ${err?.code ?? ''} ${err?.message ?? err}`);
106
+ appendErrorLog(`stdio error: ${err?.code ?? ''} ${err?.message ?? err}`);
107
+ safeWrite(process.stderr, `[jobfinder:worker] stdio error: ${err?.code ?? ''} ${err?.message ?? err}\n`);
67
108
  });
68
109
  }
69
110
 
@@ -108,12 +149,25 @@ async function writeLog(level, message, data) {
108
149
  await patchState({ logs: appendLog(readWorkerState(store).logs, entry) });
109
150
  }
110
151
 
111
- /** Is another live worker already holding the state file? */
152
+ /**
153
+ * Is another live worker already holding the state file?
154
+ *
155
+ * A fresh heartbeat from a DEAD pid is not ownership: on Windows a hard
156
+ * kill (TerminateProcess, exit 0xFFFFFFFF) skips the worker's exit handler,
157
+ * so the heartbeat stays fresh for a few seconds after the process is gone.
158
+ * Without the pid check, a crash-restart would be rejected as a duplicate.
159
+ */
112
160
  function anotherWorkerOwnsState() {
113
161
  const state = readWorkerState(store);
114
162
  if (!state.pid || state.pid === process.pid || !state.heartbeatAt) return false;
115
163
  const age = Date.now() - new Date(state.heartbeatAt).getTime();
116
- return age >= 0 && age < 12_000;
164
+ if (!(age >= 0 && age < 12_000)) return false;
165
+ try {
166
+ process.kill(state.pid, 0);
167
+ return true; // heartbeat fresh AND the pid is alive: someone owns it
168
+ } catch (err) {
169
+ return err?.code !== 'ESRCH'; // dead pid -> not an owner
170
+ }
117
171
  }
118
172
 
119
173
  function beatHeartbeat() {
@@ -292,7 +346,8 @@ function stop(reason) {
292
346
  } catch {
293
347
  /* state is best-effort during shutdown */
294
348
  }
295
- console.error(`[jobfinder:worker] stopped (${reason}).`);
349
+ appendErrorLog(`stopped (${reason})`);
350
+ safeWrite(process.stderr, `[jobfinder:worker] stopped (${reason}).\n`);
296
351
  process.exit(0);
297
352
  }
298
353
 
@@ -305,18 +360,27 @@ function schedule() {
305
360
  if (stopping) return;
306
361
  beatHeartbeat();
307
362
  timer = setTimeout(async () => {
308
- if (parentIsGone()) {
309
- stop('parent launcher exited');
310
- return;
363
+ // A synchronous failure in this callback must never escape as an
364
+ // uncaughtException: report it and reschedule instead of dying.
365
+ try {
366
+ if (parentIsGone()) {
367
+ stop('parent launcher exited');
368
+ return;
369
+ }
370
+ await tick().catch((err) => reportUnexpected('tick failed', err));
371
+ schedule();
372
+ } catch (err) {
373
+ reportUnexpected('loop failed', err);
374
+ if (!stopping) schedule();
311
375
  }
312
- await tick().catch((err) => {
313
- logger?.error('worker', 'tick failed', { message: err?.message });
314
- });
315
- schedule();
316
376
  }, INTERVAL_MS);
317
377
  heartbeatTimer = setInterval(() => {
318
- beatHeartbeat();
319
- if (parentIsGone()) stop('parent launcher exited');
378
+ try {
379
+ beatHeartbeat();
380
+ if (parentIsGone()) stop('parent launcher exited');
381
+ } catch (err) {
382
+ reportUnexpected('heartbeat failed', err);
383
+ }
320
384
  }, HEARTBEAT_MS);
321
385
  }
322
386
 
@@ -326,6 +390,8 @@ async function main() {
326
390
  console.error(`[jobfinder:worker] data directory not found: ${dataDir}`);
327
391
  process.exit(1);
328
392
  }
393
+ // Crash/forensic log: the only artifact that survives a dead pipe.
394
+ errorLogPath = path.join(dataDir, 'worker-error.log');
329
395
 
330
396
  context = createContext(dataDir);
331
397
  store = context.store;