@danhachuel/jobfinder 0.1.7 → 0.1.10

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,23 @@ 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.10] — 2026-11-15
10
+
11
+ ### Documentation
12
+
13
+ - **Regra permanente de infraestrutura**: nova seção "Regras de Infraestrutura" no `AGENTS.md` — **Multiplataforma e Sem Docker Obrigatório**. O JobFinder deve rodar nativamente no Windows e no Linux; é proibido adicionar dependências obrigatórias de Docker/containers para desenvolvimento, testes ou execução; nada pode quebrar a execução direta via Node.js em nenhum dos dois sistemas; compatibilidade cruzada via bibliotecas nativas do Node (`path`, `os`, `node:fs`, `node:child_process`).
14
+ - **Skill `windows-runtime-guard` → `runtime-guard`** (renomeada para refletir o escopo multiplataforma): além do Blindagem de runtime (EPIPE, sinais, spawn), passou a documentar explicitamente a regra de execução nativa em Windows e Linux sem imposição de Docker, com item dedicado no checklist. Referências atualizadas no `AGENTS.md` e na stub `tests/test_windows_keepalive.js`.
15
+
16
+ ## [0.1.08] — 2026-11-15
17
+
18
+ ### Fixed
19
+
20
+ - **Encerramento prematuro do CLI após a introdução do Background Worker** (regressão da 0.1.7): o launcher delegava 100% da sua sobrevivência aos handles dos processos filhos — com o event loop vazio, o Node saía com código 0 **em silêncio**, logo após o banner de startup, e o terminal voltava ao prompt. Causas combinadas: (1) nenhum keep-alive próprio no `cli.mjs`; (2) o servidor era spawnado com `stdio: 'inherit'` (proibido pela `windows-runtime-guard` — um terminal quebrado, ex. MobaXterm, o matava com EPIPE); (3) o guardião de órfãos do worker tratava **qualquer** erro ≠ EPERM do `process.kill(ppid, 0)` como "pai morreu", podendo se suicidar por falso-positivo no Windows. Agora: o `cli.mjs` tem um keep-alive referenciado (timer de 60 s, independente de qualquer filho); o servidor é spawnado via `spawnSupervised` com `stdio: ['ignore','pipe','pipe']` + `windowsHide` + `CREATE_NEW_PROCESS_GROUP`, com a saída encaminhada pelo launcher (o servidor não escreve mais direto no terminal); o guardião só considera o pai morto em **ESRCH** (pid inexistente); e o launcher passou a registrar `[jobfinder] launcher exiting with code N` para que nenhuma morte futura fique sem explicação.
21
+
22
+ ### Added
23
+
24
+ - Regressão `startup-keepalive.mjs` cobre o worker: sobe o app pelo launcher, confirma pid/heartbeat em `worker-state.json`, **mata o worker e o CLI continua vivo servindo HTTP 200** (só loga `worker exited`), e valida o modo `JOBFINDER_NO_WORKER=1`. Suíte: 21 keepalive + 39 fase2-worker + 32 auth + 16 serviços + 22 E2E.
25
+
9
26
  ## [0.1.07] — 2026-11-14
10
27
 
11
28
  ### Added
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@danhachuel/jobfinder",
3
- "version": "0.1.07",
3
+ "version": "0.1.10",
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
@@ -24,7 +24,7 @@ import process from 'node:process';
24
24
  import { fileURLToPath } from 'node:url';
25
25
 
26
26
  import { ensureDataDir, resolveDataDir, isDataDirHealthy } from '../src/server/storage/bootstrap.mjs';
27
- import { spawnWorker, forwardChildOutput } from '../src/server/workerRuntime.mjs';
27
+ import { spawnWorker, spawnSupervised, forwardChildOutput } from '../src/server/workerRuntime.mjs';
28
28
 
29
29
  /**
30
30
  * Process resilience for the launcher — installed before anything else runs
@@ -201,7 +201,11 @@ async function commandStart({ port, host, dataDir, dryRun }) {
201
201
  console.log(` URL : ${url}`);
202
202
  console.log(' Press Ctrl+C to stop.\n');
203
203
 
204
- const child = spawn(process.execPath, [SERVER_ENTRY], { stdio: 'inherit', env, cwd: ROOT });
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, '');
205
209
 
206
210
  // Background worker: a SEPARATE process so the automation queues keep
207
211
  // running when the browser is closed (or was never opened). Spawn follows
@@ -222,6 +226,20 @@ async function commandStart({ port, host, dataDir, dryRun }) {
222
226
  // The `child` handle keeps this launcher's event loop open for as long as
223
227
  // the server runs: the CLI stays in the foreground and the terminal only
224
228
  // returns to the prompt when the server itself exits (or on Ctrl+C).
229
+ //
230
+ // Independent keep-alive: the launcher must NEVER depend on a child handle
231
+ // to stay alive (regression 0.1.7 — an empty event loop makes Node exit
232
+ // with code 0, silently, right after the startup banner). This referenced
233
+ // timer holds the loop open by itself; explicit process.exit() calls in
234
+ // the signal/exit handlers below still terminate immediately.
235
+ const keepAlive = setInterval(() => {}, 60_000);
236
+ void keepAlive;
237
+
238
+ // Forensic trail: if the launcher ever dies, the reason is visible.
239
+ process.on('exit', (code) => {
240
+ console.error(`[jobfinder] launcher exiting with code ${code}.`);
241
+ });
242
+
225
243
  let stopping = false;
226
244
  const stopChildren = () => {
227
245
  if (worker && worker.exitCode === null && worker.signalCode === null) {
@@ -158,5 +158,74 @@ async function bootAndObserve(label, { args, port, observeMs, env = {} }) {
158
158
  fs.rmSync(tmp, { recursive: true, force: true });
159
159
  }
160
160
 
161
+ // 5) o worker sobe junto, bate heartbeat e o CLI continua vivo depois
162
+ // dele (regressao 0.1.7: event loop vazio matava o launcher).
163
+ {
164
+ console.log('\n== boot com worker: heartbeat + CLI independente do worker ==');
165
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'jobfinder-keepalive-worker-'));
166
+ const home = path.join(tmp, 'data');
167
+ const child = spawn(process.execPath, [path.join(ROOT, 'scripts', 'cli.mjs'), 'start', '--no-open'], {
168
+ cwd: ROOT,
169
+ env: { ...process.env, JOBFINDER_PORT: '4185', JOBFINDER_DATA_DIR: home, JOBFINDER_NO_OPEN: '1' },
170
+ stdio: ['ignore', 'pipe', 'pipe'],
171
+ });
172
+ let out = '';
173
+ child.stdout.on('data', (d) => { out += String(d); });
174
+ child.stderr.on('data', (d) => { out += String(d); });
175
+
176
+ const workerPid = async () => {
177
+ try {
178
+ return JSON.parse(fs.readFileSync(path.join(home, 'worker-state.json'), 'utf8')).pid ?? null;
179
+ } catch {
180
+ return null;
181
+ }
182
+ };
183
+
184
+ await wait(3000);
185
+ const pid0 = await workerPid();
186
+ check('worker spawnado publicou o pid no estado', Boolean(pid0), `pid=${pid0}`);
187
+ check('output do launcher anuncia o worker', /Worker\s+:\s+automa/.test(out));
188
+
189
+ await wait(4000); // passa de 1 heartbeat (5s): o guardiao de orfaos rodou
190
+ const pid1 = await workerPid();
191
+ check('worker continua vivo apos os heartbeats (sem falso positivo do guardiao)', pid1 === pid0 && (await getStatus(4185, '/api/health')) === 200, `pid=${pid1}`);
192
+
193
+ // CRASH do worker: o CLI NAO pode morrer — so logar.
194
+ try {
195
+ process.kill(Number(pid1), 'SIGTERM');
196
+ } catch {
197
+ /* processo pode ja ter saido */
198
+ }
199
+ await wait(2500);
200
+ 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] ?? '');
202
+ check('servidor continua respondendo apos o crash do worker', (await getStatus(4185, '/api/health')) === 200);
203
+ child.kill();
204
+ await wait(800);
205
+ fs.rmSync(tmp, { recursive: true, force: true });
206
+ }
207
+
208
+ // 6) JOBFINDER_NO_WORKER=1: modo sem worker, CLI continua vivo
209
+ {
210
+ console.log('\n== boot sem worker (JOBFINDER_NO_WORKER=1) ==');
211
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'jobfinder-keepalive-noworker-'));
212
+ const home = path.join(tmp, 'data');
213
+ const child = spawn(process.execPath, [path.join(ROOT, 'scripts', 'cli.mjs'), 'start', '--no-open'], {
214
+ cwd: ROOT,
215
+ env: { ...process.env, JOBFINDER_PORT: '4187', JOBFINDER_DATA_DIR: home, JOBFINDER_NO_OPEN: '1', JOBFINDER_NO_WORKER: '1' },
216
+ stdio: ['ignore', 'pipe', 'pipe'],
217
+ });
218
+ let out = '';
219
+ child.stdout.on('data', (d) => { out += String(d); });
220
+ child.stderr.on('data', (d) => { out += String(d); });
221
+ await wait(6000);
222
+ check('CLI continua rodando sem worker', !dead(child), dead(child) ? `exitCode=${child.exitCode} signal=${child.signalCode}` : 'vivo');
223
+ check('nenhum worker foi spawnado', /Worker\s+:\s+disabled/.test(out));
224
+ check('API responde em localhost', (await getStatus(4187, '/api/health')) === 200);
225
+ child.kill();
226
+ await wait(800);
227
+ fs.rmSync(tmp, { recursive: true, force: true });
228
+ }
229
+
161
230
  console.log(`\nResultado: ${passed} passaram, ${failed} falharam.`);
162
231
  process.exit(failed ? 1 : 0);
@@ -124,7 +124,16 @@ function beatHeartbeat() {
124
124
  }
125
125
  }
126
126
 
127
- /** True when the parent launcher disappeared (orphan guard on Windows). */
127
+ /**
128
+ * True when the parent launcher disappeared (orphan guard on Windows).
129
+ *
130
+ * Only ESRCH (the pid does not exist) means the parent is gone. ANY other
131
+ * error — EPERM, EINVAL, anything the host decides to return — means
132
+ * "unknown", and an unknown parent must be treated as ALIVE: on Windows the
133
+ * liveness probe is not a POSIX kill (MobaXterm/npx wrap the real parent),
134
+ * and the previous "any error = gone" rule made the worker suicide for no
135
+ * reason whenever the host answered with an unexpected code.
136
+ */
128
137
  function parentIsGone() {
129
138
  const ppid = process.ppid;
130
139
  if (!ppid || ppid <= 1) return false;
@@ -132,7 +141,7 @@ function parentIsGone() {
132
141
  process.kill(ppid, 0);
133
142
  return false;
134
143
  } catch (err) {
135
- return err?.code === 'EPERM' ? false : true;
144
+ return err?.code === 'ESRCH';
136
145
  }
137
146
  }
138
147
 
@@ -23,23 +23,40 @@ export const WORKER_ENTRY = path.join(__dirname, 'worker.mjs');
23
23
  export const CREATE_NEW_PROCESS_GROUP = 0x00000200;
24
24
 
25
25
  /**
26
- * Spawn the worker as a detached-enough child of the caller.
26
+ * Spawn a long-lived child that the caller supervises (server or worker).
27
+ *
28
+ * windows-runtime-guard: NEVER `stdio: 'inherit'` — a child that writes
29
+ * straight to the terminal dies with EPIPE when the terminal/pipe breaks
30
+ * (MobaXterm, redirection, closed SSH session). Piped stdio keeps the child
31
+ * independent from the terminal: the supervisor forwards the output and its
32
+ * own EPIPE handlers absorb a dead pipe.
33
+ *
34
+ * @param {string} entry absolute path of the child entrypoint
27
35
  * @param {{ env?: object, cwd?: string }} [options]
28
36
  * @returns {import('node:child_process').ChildProcess}
29
37
  */
30
- export function spawnWorker(options = {}) {
31
- const child = spawn(process.execPath, [WORKER_ENTRY], {
38
+ export function spawnSupervised(entry, options = {}) {
39
+ return spawn(process.execPath, [entry], {
32
40
  cwd: options.cwd ?? path.resolve(__dirname, '..', '..'),
33
41
  env: { ...process.env, ...(options.env ?? {}) },
34
42
  stdio: ['ignore', 'pipe', 'pipe'],
35
43
  windowsHide: true,
36
44
  creationFlags: process.platform === 'win32' ? CREATE_NEW_PROCESS_GROUP : 0,
37
45
  });
38
- return child;
46
+ }
47
+
48
+ /**
49
+ * Spawn the worker as a detached-enough child of the caller.
50
+ * @param {{ env?: object, cwd?: string }} [options]
51
+ * @returns {import('node:child_process').ChildProcess}
52
+ */
53
+ export function spawnWorker(options = {}) {
54
+ return spawnSupervised(WORKER_ENTRY, options);
39
55
  }
40
56
 
41
57
  /** Pipe a child's output to the console with a prefix (never inherit). */
42
58
  export function forwardChildOutput(child, prefix, { onLine } = {}) {
59
+ const label = prefix ? `${prefix} ` : '';
43
60
  const emit = (stream) => (chunk) => {
44
61
  const text = String(chunk);
45
62
  if (onLine) {
@@ -47,7 +64,7 @@ export function forwardChildOutput(child, prefix, { onLine } = {}) {
47
64
  if (line.trim()) onLine(line);
48
65
  }
49
66
  } else {
50
- process.stdout.write(`${prefix} ${text}`);
67
+ process.stdout.write(`${label}${text}`);
51
68
  }
52
69
  void stream;
53
70
  };