@danhachuel/jobfinder 0.1.14 → 0.1.16

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,39 @@ 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.16] — 2026-11-22
10
+
11
+ ### Added
12
+
13
+ - **Modo daemon (`node scripts/cli.mjs --daemon`)**: o servidor sobe **detached** do terminal interativo e sobrevive ao fechamento da sessão — a resposta definitiva ao terminal (MobaXterm, wrapper do `npx`, PowerShell) que mata o processo filho. `stdio: ['ignore', <log>, <log>]` (nunca `inherit`), `windowsHide`, `creationFlags: CREATE_NEW_PROCESS_GROUP`, estado do daemon em `jobfinder-daemon.json` via **JsonStore** (atômico, nunca `fs.writeFileSync`). O terminal volta ao prompt em ~300 ms.
14
+ - **Comando `stop`** (`--stop` / `--daemon-stop`): encerra o daemon com SIGTERM, espera o encerramento gracioso, força com SIGKILL se necessário e limpa o pid do registro. Roda limpo quando não há daemon.
15
+ - **`scripts/start-windows.ps1`** (+ wrapper `start-windows.cmd` para duplo clique): detecta porta em uso, sobe o daemon via `Start-Process` (desacoplado dos pipes do terminal — com `&` ou `Start-Process -Wait` o PowerShell fica pendurado esperando handles do processo nativo), confere o `/api/health` e informa PID, log e como parar. Flag `-Local` usa o working copy; `-Version` fixa a versão do npm.
16
+ - **`ecosystem.config.cjs` + scripts PM2** (`pm2:start`, `pm2:stop`, `daemon:logs`): JobFinder como serviço real, com reinício automático em caso de crash. `pm2` entra como **optionalDependency** — a regra do projeto é executar nativamente, sem infraestrutura obrigatória; sem pm2 tudo continua funcionando.
17
+ - **README**: nova seção "Rodando como Serviço (Windows/Linux)" comparando as quatro formas (foreground / `--daemon` / script Windows / PM2).
18
+
19
+ ### Notas
20
+
21
+ - O daemon grava o log em `~/.jobfinder/jobfinder.log` (respeita `JOBFINDER_HOME`/`JOBFINDER_DATA_DIR`).
22
+ - `JOBFINDER_MODE=daemon` é propagado ao processo para identificar o modo no ambiente.
23
+ - Validado: `npm ci` continua instalando pm2 como dependência opcional sem falhar (245 pacotes).
24
+
25
+ ### Tests
26
+
27
+ - Nova suíte `scripts/manual-tests/fase5-daemon.mjs` — **21 verificações, 0 falhas**: launcher volta ao prompt com código 0 em < 8 s, pid registrado, HTTP 200, log em disco com a versão correta (não `0.0.00`), daemon sobrevive à morte do terminal, rodar duas vezes não duplica, `stop` encerra e limpa o registro, `stop` sem daemon não quebra.
28
+ - PM2 validado ponta a ponta: `pm2 start ecosystem.config.cjs` → app `online` (pid + uptime), `/api/health` 200, `pm2 stop` → `stopped`.
29
+ - Script Windows validado ponta a ponta (`-Local`): start → HTTP 200 e `exit 0` sem travar; `-Stop` → porta não responde mais e `exit 0`.
30
+
31
+ ## [0.1.15] — 2026-11-21
32
+
33
+ ### Fixed
34
+
35
+ - **Versão `0.0.00` ao rodar via `npx`**: `readPkgVersion()` em `src/server/index.mjs` lia `package.json` com `path.resolve(process.cwd(), 'package.json')`. Sob `npx` o cwd é o diretório do usuário (home do MobaXterm, um path qualquer do PowerShell), a leitura falhava em silêncio e o servidor imprimia `JobFinder v0.0.00 (npm 0.0.0)`. Agora a versão vem de `JOBFINDER_VERSION` (definida pelo launcher, que lê o `package.json` a partir da própria localização do arquivo) ou, na ausência dela, de `createRequire(import.meta.url)` + `require('../../package.json')` — resolvido a partir **deste módulo**, nunca do cwd. O fallback ruidoso (`console.error`) substitui o silencioso.
36
+ - **Retenção do event loop com rastro forense**: `beforeExit` no launcher **e** no servidor registra os handles ativos antes de qualquer saída natural e re-arma um timer de keep-alive **referenciado** (sem `unref()`) quando o socket do servidor não está entre eles — a saída silenciosa agora é impossível sem deixar `[jobfinder] launcher: event loop esvaziando (beforeExit code=…) — handles: …` no terminal. `exit` registra o código final nos dois processos. Nenhum `server.unref()` e nenhum `process.exit(0)` no caminho de startup.
37
+
38
+ ### Tests
39
+
40
+ - Nova suíte `scripts/manual-tests/fase4-npx-start.mjs` — **12 verificações, 0 falhas**, rodando o binário de um **diretório estranho** (reprodução do ambiente `npx`/MobaXterm): versão correta na linha do `listen`, processo vivo depois do banner, HTTP 200, caminho `node src/server/index.mjs` direto sem `JOBFINDER_VERSION` (valida o `createRequire`) e caminho completo com worker ativo.
41
+
9
42
  ## [0.1.14] — 2026-11-20
10
43
 
11
44
  ### Security
package/README.md CHANGED
@@ -31,15 +31,15 @@ A **background worker** (separate Node process) keeps the queues moving even wit
31
31
  Windows / CMD / MobaXterm:
32
32
 
33
33
  ```bash
34
- npx.cmd --yes --prefer-online @danhachuel/jobfinder@0.1.7 install
35
- npx.cmd --yes --prefer-online @danhachuel/jobfinder@0.1.7
34
+ npx.cmd --yes --prefer-online @danhachuel/jobfinder@0.1.15 install
35
+ npx.cmd --yes --prefer-online @danhachuel/jobfinder@0.1.15
36
36
  ```
37
37
 
38
38
  Normal terminal:
39
39
 
40
40
  ```bash
41
- npx --yes @danhachuel/jobfinder@0.1.7 install
42
- npx --yes @danhachuel/jobfinder@0.1.7
41
+ npx --yes @danhachuel/jobfinder@0.1.15 install
42
+ npx --yes @danhachuel/jobfinder@0.1.15
43
43
  ```
44
44
 
45
45
  `install` creates `~/.jobfinder/` (config, auth, channels, topics, posts, connections, dm-cascades, jobs, applications, resume, logs). It is safe to re-run: existing data is never overwritten.
@@ -54,12 +54,12 @@ The single first-run account is created in `~/.jobfinder/auth.json` on the first
54
54
  # Windows (PowerShell)
55
55
  $env:JOBFINDER_INITIAL_EMAIL = "voce@exemplo.com"
56
56
  $env:JOBFINDER_INITIAL_PASSWORD = "sua-senha-forte"
57
- npx --yes @danhachuel/jobfinder@0.1.14
57
+ npx --yes @danhachuel/jobfinder@0.1.15
58
58
 
59
59
  # Linux / macOS
60
60
  JOBFINDER_INITIAL_EMAIL="voce@exemplo.com" \
61
61
  JOBFINDER_INITIAL_PASSWORD="sua-senha-forte" \
62
- npx --yes @danhachuel/jobfinder@0.1.14
62
+ npx --yes @danhachuel/jobfinder@0.1.15
63
63
  ```
64
64
 
65
65
  Alternative: create the account directly in `~/.jobfinder/auth.json` (see the `user` object) before starting the app.
@@ -85,9 +85,75 @@ Alternative: create the account directly in `~/.jobfinder/auth.json` (see the `u
85
85
  node scripts/cli.mjs start --port 3031 # custom port
86
86
  node scripts/cli.mjs start --data-dir . # custom data directory
87
87
  node scripts/cli.mjs start --dry-run # force dry-run
88
+ node scripts/cli.mjs --daemon # background (terminal fica livre)
89
+ node scripts/cli.mjs stop # encerra o daemon
88
90
  node scripts/cli.mjs --version # version info
89
91
  ```
90
92
 
93
+ ## Rodando como Serviço (Windows/Linux)
94
+
95
+ Alguns terminais — MobaXterm, wrappers do `npx`, sessões de PowerShell — podem encerrar o
96
+ processo filho a qualquer momento. Quando você precisa que o JobFinder **sobreviva ao
97
+ terminal**, use uma das três formas abaixo.
98
+
99
+ ### 1. Foreground (via npx) — ideal para ver os logs
100
+
101
+ ```bash
102
+ npx --yes @danhachuel/jobfinder@0.1.16
103
+ ```
104
+
105
+ O servidor roda neste terminal; `Ctrl+C` encerra. Perfeito para depurar, ruim para deixar
106
+ rodando: se o terminal fechar, o app morre.
107
+
108
+ ### 2. Daemon nativo — `node scripts/cli.mjs --daemon`
109
+
110
+ O servidor sobe **detached** do terminal, com o log em `~/.jobfinder/jobfinder.log`. O
111
+ terminal volta ao prompt na hora.
112
+
113
+ ```bash
114
+ # pacote publicado (qualquer SO)
115
+ npx --yes @danhachuel/jobfinder@0.1.16 --daemon --port 4040
116
+ npx --yes @danhachuel/jobfinder@0.1.16 stop
117
+
118
+ # working copy
119
+ node scripts/cli.mjs --daemon --port 4040
120
+ node scripts/cli.mjs stop
121
+ ```
122
+
123
+ ### 3. Script nativo do Windows — `scripts\start-windows.ps1`
124
+
125
+ Duplo clique ou PowerShell: detecta porta em uso, sobe o daemon, confere o `/api/health` e
126
+ informa o PID e o caminho do log.
127
+
128
+ ```powershell
129
+ .\scripts\start-windows.ps1 # versão latest do npm
130
+ .\scripts\start-windows.ps1 -Version 0.1.16 # versão fixa
131
+ .\scripts\start-windows.ps1 -Local # working copy (desenvolvimento)
132
+ .\scripts\start-windows.ps1 -Stop # encerra
133
+ .\scripts\start-windows.cmd # wrapper para duplo clique
134
+ ```
135
+
136
+ ### 4. PM2 — serviço de verdade (Windows e Linux)
137
+
138
+ Reinicia em caso de crash, gerencia logs e sobrevive ao fechamento da sessão.
139
+
140
+ ```bash
141
+ npm i -g pm2 # ou: npx pm2
142
+ npm run pm2:start # sobe (ecosystem.config.cjs)
143
+ npm run daemon:logs # acompanha os logs
144
+ npm run pm2:stop # para
145
+ ```
146
+
147
+ `pm2` é dependência **opcional**: sem ela o app continua funcionando normalmente pelos
148
+ caminhos 1–3 — a regra do projeto é executar nativamente, sem infraestrutura obrigatória.
149
+
150
+ | Forma | Sobrevive ao terminal? | Logs | Uso |
151
+ |---|---|---|---|
152
+ | Foreground (npx) | não | no terminal | depuração rápida |
153
+ | `--daemon` | sim | `~/.jobfinder/jobfinder.log` | servidor local simples |
154
+ | `start-windows.ps1` | sim | `~/.jobfinder/jobfinder.log` | Windows, duplo clique |
155
+ | PM2 | sim (reinicia) | `pm2 logs` | serviço de longo prazo |
156
+
91
157
  ## Screenshots
92
158
 
93
159
  > Painel, Postagens, Conexões, Cascatas de DM, Vagas, Candidaturas, Integrações e Configurações — see the walkthrough in the app header (**Ver tutorial**) or open the app to explore in dry-run mode. Screenshots are published with each release in the GitHub Releases.
@@ -130,6 +196,7 @@ node scripts/manual-tests/fase1-dryrun-services.mjs # API: flag dry-run aplic
130
196
  node scripts/manual-tests/fase1-ui-e2e.mjs # UI (Playwright): login, badges, configurações, logout
131
197
  node scripts/manual-tests/fase2-worker.mjs # worker: spawn, filas, limite de DMs, órfãos, estresse
132
198
  node scripts/manual-tests/fase3-seed-env.mjs # segurança: seed por env, nenhuma credencial exposta
199
+ node scripts/manual-tests/fase4-npx-start.mjs # npx/cwd estranho: versão correta, processo vivo, HTTP 200
133
200
  node scripts/manual-tests/startup-keepalive.mjs # runtime: boot, unhandledRejection, EPIPE, sinais
134
201
  node --test tests/*.js # contratos/concorrência/UI (stubs por enquanto)
135
202
  ```
@@ -0,0 +1,36 @@
1
+ /**
2
+ * PM2 — JobFinder como serviço de background real (Windows e Linux).
3
+ *
4
+ * npm i -g pm2 # ou: npx pm2
5
+ * npm run start:daemon # sobe
6
+ * npm run daemon:logs # acompanha
7
+ * npm run daemon:stop # para
8
+ *
9
+ * O CLI continua sendo o entrypoint: toda a supervisão do worker, os sinais
10
+ * e o keep-alive do event loop são os mesmos do modo foreground. O PM2 apenas
11
+ * garante que o processo sobreviva ao fechamento do terminal e reinicia em
12
+ * caso de crash.
13
+ */
14
+ module.exports = {
15
+ apps: [
16
+ {
17
+ name: 'jobfinder',
18
+ script: 'scripts/cli.mjs',
19
+ interpreter: 'node',
20
+ // Modo serviço: não trava o terminal e sobrevive ao fechamento da sessão.
21
+ instances: 1,
22
+ exec_mode: 'fork',
23
+ autorestart: true,
24
+ max_restarts: 10,
25
+ restart_delay: 3000,
26
+ // Logs por processo fiquem em ~/.jobfinder (o PM2 gerencia os seus em
27
+ // ~/.pm2/logs; aqui o app escreve o log de aplicação).
28
+ out_file: null,
29
+ error_file: null,
30
+ env: {
31
+ NODE_ENV: 'production',
32
+ JOBFINDER_MODE: 'daemon',
33
+ },
34
+ },
35
+ ],
36
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@danhachuel/jobfinder",
3
- "version": "0.1.14",
3
+ "version": "0.1.16",
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",
@@ -21,6 +21,7 @@
21
21
  "scripts/",
22
22
  "src/server/",
23
23
  "src/ui/dist/",
24
+ "ecosystem.config.cjs",
24
25
  "CHANGELOG.md",
25
26
  "README.md",
26
27
  "LICENSE"
@@ -32,6 +33,11 @@
32
33
  "dev:ui": "npm --prefix src/ui run dev",
33
34
  "build": "npm --prefix src/ui run build",
34
35
  "start": "node scripts/cli.mjs start",
36
+ "start:daemon": "node scripts/cli.mjs --daemon",
37
+ "daemon:stop": "node scripts/cli.mjs stop",
38
+ "daemon:logs": "pm2 logs jobfinder",
39
+ "pm2:start": "pm2 start ecosystem.config.cjs",
40
+ "pm2:stop": "pm2 stop ecosystem.config.cjs",
35
41
  "smoke": "node scripts/cli.mjs install && node scripts/cli.mjs --version"
36
42
  },
37
43
  "engines": {
@@ -43,7 +49,8 @@
43
49
  "pdfjs-dist": "^6.5.438"
44
50
  },
45
51
  "optionalDependencies": {
46
- "playwright": "^1.65.0"
52
+ "playwright": "^1.65.0",
53
+ "pm2": "^6.0.14"
47
54
  },
48
55
  "devDependencies": {
49
56
  "concurrently": "^10.0.7"
package/scripts/cli.mjs CHANGED
@@ -21,8 +21,10 @@ import path from 'node:path';
21
21
  import os from 'node:os';
22
22
  import process from 'node:process';
23
23
  import { fileURLToPath } from 'node:url';
24
+ import { spawn } from 'node:child_process';
24
25
 
25
26
  import { ensureDataDir, resolveDataDir, isDataDirHealthy } from '../src/server/storage/bootstrap.mjs';
27
+ import { JsonStore } from '../src/server/storage/jsonStore.mjs';
26
28
  import { spawnWorker } from '../src/server/workerRuntime.mjs';
27
29
 
28
30
  /**
@@ -83,6 +85,8 @@ Flags:
83
85
  --host <addr> Bind address (default 127.0.0.1)
84
86
  --data-dir <path> Data directory (default ~/.jobfinder, override with JOBFINDER_HOME)
85
87
  --dry-run Run with automations in dry-run mode (no real LinkedIn actions)
88
+ --daemon Run detached from this terminal (background service)
89
+ --stop Stop the daemon started with --daemon
86
90
 
87
91
  Install commands (canonical npm version):
88
92
  npx --yes @danhachuel/jobfinder@${NPM_VERSION} install
@@ -90,7 +94,7 @@ Install commands (canonical npm version):
90
94
  `;
91
95
 
92
96
  function parseArgs(argv) {
93
- const args = { command: null, port: null, host: null, dataDir: null, dryRun: false };
97
+ const args = { command: null, port: null, host: null, dataDir: null, dryRun: false, daemon: false };
94
98
  const rest = [...argv];
95
99
  const first = rest[0];
96
100
  if (first && !first.startsWith('-')) {
@@ -120,6 +124,16 @@ function parseArgs(argv) {
120
124
  case '--dry-run':
121
125
  args.dryRun = true;
122
126
  break;
127
+ // Daemon mode: the server runs detached from this terminal (background
128
+ // service). The terminal returns to the prompt immediately.
129
+ case '--daemon':
130
+ args.daemon = true;
131
+ break;
132
+ // Shorthand to stop a daemon started with --daemon.
133
+ case '--daemon-stop':
134
+ case '--stop':
135
+ args.command = 'stop';
136
+ break;
123
137
  case '--help':
124
138
  case '-h':
125
139
  args.command = 'help';
@@ -200,6 +214,10 @@ async function commandStart({ port, host, dataDir, dryRun }) {
200
214
  process.env.JOBFINDER_DATA_DIR = resolved;
201
215
  process.env.JOBFINDER_PORT = String(listenPort);
202
216
  process.env.JOBFINDER_HOST = listenHost;
217
+ // Version: read from THIS file's package.json (never cwd) and handed to the
218
+ // server via env. Under npx the cwd is the user's directory, so a server
219
+ // that read its own version from cwd would print 0.0.00.
220
+ process.env.JOBFINDER_VERSION = VISUAL_VERSION;
203
221
  if (dryRun) process.env.JOBFINDER_DRY_RUN = '1';
204
222
 
205
223
  // Supervisão do worker. O CLI NUNCA depende do worker para viver: ele
@@ -243,10 +261,25 @@ async function commandStart({ port, host, dataDir, dryRun }) {
243
261
  };
244
262
 
245
263
  // 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);
264
+ // socket do servidor (abaixo) já é a garantia principal. Nunca use unref()
265
+ // aqui: um timer solto é o que permite o loop esvaziar e o processo sumir.
266
+ const keepAliveTimer = setInterval(() => {}, 24 * 60 * 60 * 1000);
248
267
 
249
- // Forensic trail: se o launcher morrer, o motivo fica visível.
268
+ // Forensic trail: se o launcher morrer, o motivo fica visível. `beforeExit`
269
+ // avisa ANTES de o loop esvaziar (com os handles ativos) e permite re-armar
270
+ // o keep-alive; `exit` registra o código final.
271
+ process.on('beforeExit', (code) => {
272
+ const handles = process.getActiveResourcesInfo?.() ?? [];
273
+ console.error(
274
+ `[jobfinder] launcher: event loop esvaziando (beforeExit code=${code}) — ` +
275
+ `handles: ${handles.join(', ') || 'NENHUM'}`
276
+ );
277
+ if (!stopping) {
278
+ console.error('[jobfinder] launcher: re-armando o keep-alive para nao voltar ao prompt.');
279
+ clearInterval(keepAliveTimer);
280
+ setInterval(() => {}, 24 * 60 * 60 * 1000);
281
+ }
282
+ });
250
283
  process.on('exit', (code) => {
251
284
  console.error(`[jobfinder] launcher exiting with code ${code}.`);
252
285
  });
@@ -288,6 +321,131 @@ async function commandStart({ port, host, dataDir, dryRun }) {
288
321
  }
289
322
  }
290
323
 
324
+ /** True when a pid exists (EPERM = alive but owned by another user). */
325
+ function isPidAlive(pid) {
326
+ if (!pid || !Number.isInteger(Number(pid)) || Number(pid) <= 0) return false;
327
+ try {
328
+ process.kill(Number(pid), 0);
329
+ return true;
330
+ } catch (err) {
331
+ return err?.code === 'EPERM';
332
+ }
333
+ }
334
+
335
+ /**
336
+ * Daemon mode (0.1.16): the server runs DETACHED from the interactive
337
+ * terminal, so nothing the terminal does afterwards can kill it.
338
+ *
339
+ * A hostile terminal (MobaXterm wrapper, PowerShell, npx) can TerminateProcess
340
+ * the foreground child at any moment; a detached process with its own stdio
341
+ * pointed at a log file is immune to that. The terminal returns to the prompt
342
+ * immediately — that is the expected behaviour of a daemon.
343
+ */
344
+ async function commandDaemon(args) {
345
+ const resolved = resolveDataDir(args.dataDir);
346
+ ensureDataDir(resolved);
347
+
348
+ const store = new JsonStore(resolved);
349
+ const info = store.read('jobfinder-daemon.json', null) ?? {};
350
+ if (isPidAlive(info.pid)) {
351
+ console.log(`JobFinder ja esta rodando em background (pid ${info.pid}).`);
352
+ console.log(` URL : http://${info.host ?? '127.0.0.1'}:${info.port ?? 4040}`);
353
+ console.log(` Log : ${info.logFile ?? path.join(resolved, 'jobfinder.log')}`);
354
+ console.log(` Parar: npx --yes @danhachuel/jobfinder@${NPM_VERSION} stop`);
355
+ return;
356
+ }
357
+
358
+ const port = args.port || Number(process.env.JOBFINDER_PORT) || 4040;
359
+ const host = args.host || process.env.JOBFINDER_HOST || '127.0.0.1';
360
+ const logFile = path.join(resolved, 'jobfinder.log');
361
+
362
+ printBanner();
363
+ fs.mkdirSync(path.dirname(logFile), { recursive: true });
364
+ const logFd = fs.openSync(logFile, 'a');
365
+
366
+ const child = spawn(process.execPath, [path.join(__dirname, 'cli.mjs'), 'start', '--port', String(port), '--host', host, ...(args.dryRun ? ['--dry-run'] : [])], {
367
+ detached: true,
368
+ // stdio de arquivo: o daemon NUNCA herda os pipes do terminal. Se o canalho
369
+ // do MobaXterm fechar, o daemon não sente — e o log fica em disco.
370
+ stdio: ['ignore', logFd, logFd],
371
+ windowsHide: true,
372
+ creationFlags: process.platform === 'win32' ? 0x00000200 : 0,
373
+ env: {
374
+ ...process.env,
375
+ JOBFINDER_MODE: 'daemon',
376
+ JOBFINDER_DATA_DIR: resolved,
377
+ JOBFINDER_PORT: String(port),
378
+ JOBFINDER_HOST: host,
379
+ JOBFINDER_VERSION: VISUAL_VERSION,
380
+ },
381
+ });
382
+
383
+ child.on('error', (err) => {
384
+ console.error(`[jobfinder] falha ao iniciar o daemon: ${err?.message ?? err}`);
385
+ process.exit(1);
386
+ });
387
+
388
+ // Estado do daemon via JsonStore (atômico) — nunca fs.writeFileSync solto.
389
+ store.write('jobfinder-daemon.json', {
390
+ pid: child.pid,
391
+ port,
392
+ host,
393
+ logFile,
394
+ startedAt: new Date().toISOString(),
395
+ version: VISUAL_VERSION,
396
+ mode: 'daemon',
397
+ });
398
+
399
+ child.unref();
400
+
401
+ const shown = host === '0.0.0.0' ? 'localhost' : host;
402
+ console.log(` Data directory : ${resolved}`);
403
+ console.log(` Mode : daemon (background)`);
404
+ console.log(` URL : http://${shown}:${port}`);
405
+ console.log(` PID : ${child.pid}`);
406
+ console.log(` Log : ${logFile}`);
407
+ console.log(`\nRodando em background — este terminal esta livre.`);
408
+ console.log(` Parar com: npx --yes @danhachuel/jobfinder@${NPM_VERSION} stop`);
409
+ }
410
+
411
+ /** Stop the daemon recorded in jobfinder-daemon.json (SIGTERM, then SIGKILL). */
412
+ async function commandStop() {
413
+ const resolved = resolveDataDir();
414
+ const store = new JsonStore(resolved);
415
+ const info = store.read('jobfinder-daemon.json', null) ?? {};
416
+
417
+ if (!isPidAlive(info.pid)) {
418
+ console.log('Nenhum daemon do JobFinder rodando.');
419
+ store.write('jobfinder-daemon.json', { ...info, pid: null, stoppedAt: new Date().toISOString() });
420
+ return;
421
+ }
422
+
423
+ const pid = Number(info.pid);
424
+ console.log(`Parando o JobFinder (pid ${pid})...`);
425
+ try {
426
+ process.kill(pid, 'SIGTERM');
427
+ } catch (err) {
428
+ console.error(`[jobfinder] falha ao sinalizar o processo: ${err?.message ?? err}`);
429
+ }
430
+
431
+ // Espera o encerramento gracioso; força se necessário.
432
+ for (let i = 0; i < 20; i += 1) {
433
+ if (!isPidAlive(pid)) break;
434
+ await new Promise((resolve) => setTimeout(resolve, 250));
435
+ }
436
+ if (isPidAlive(pid)) {
437
+ console.error('[jobfinder] encerramento gracioso expirou — forcando (SIGKILL).');
438
+ try {
439
+ process.kill(pid, 'SIGKILL');
440
+ } catch {
441
+ /* best effort */
442
+ }
443
+ }
444
+
445
+ store.write('jobfinder-daemon.json', { ...info, pid: null, stoppedAt: new Date().toISOString() });
446
+ console.log('JobFinder parado.');
447
+ }
448
+
291
449
  function commandVersion() {
292
450
  console.log(`JobFinder v${VISUAL_VERSION} (npm: ${NPM_VERSION})`);
293
451
  console.log(`os: ${os.type()} ${os.arch()} • node: ${process.version}`);
@@ -295,6 +453,17 @@ function commandVersion() {
295
453
 
296
454
  async function main() {
297
455
  const args = parseArgs(process.argv.slice(2));
456
+
457
+ // --daemon tem precedência sobre start/null, mas nunca sobre install/help/version.
458
+ if (args.daemon && !['install', 'help', 'version', 'stop'].includes(args.command)) {
459
+ await commandDaemon(args);
460
+ return;
461
+ }
462
+ if (args.command === 'stop') {
463
+ await commandStop();
464
+ return;
465
+ }
466
+
298
467
  switch (args.command) {
299
468
  case 'install':
300
469
  commandInstall(args);
@@ -0,0 +1,181 @@
1
+ /**
2
+ * Reprodução do cenário real: o binário rodando a partir de um diretório
3
+ * ESTRANHO (fora do repo), como o usuário faz no MobaXterm / PowerShell.
4
+ *
5
+ * Uso:
6
+ * node scripts/manual-tests/fase4-npx-start.mjs # build local
7
+ * node scripts/manual-tests/fase4-npx-start.mjs --remote 0.1.15 # pacote publicado via npx
8
+ *
9
+ * Verifica:
10
+ * 1. a versão impressa é a correta (não 0.0.00)
11
+ * 2. o processo continua vivo depois do banner (event loop retido)
12
+ * 3. o servidor responde HTTP 200
13
+ * 4. o terminal não volta ao prompt sozinho
14
+ */
15
+ import { spawn } from 'node:child_process';
16
+ import fs from 'node:fs';
17
+ import os from 'node:os';
18
+ import path from 'node:path';
19
+ import process from 'node:process';
20
+ import { setTimeout as delay } from 'node:timers/promises';
21
+
22
+ const VERSION = process.argv[2] ?? '0.1.14';
23
+ const PORT = 4366;
24
+ const HOME = path.join(os.tmpdir(), `jobfinder-npx-${Date.now()}`);
25
+ // Diretório "estranho": fora do repositório, como a home do MobaXterm.
26
+ const FOREIGN_CWD = path.join(os.tmpdir(), `mobaXterm-home-${Date.now()}`);
27
+ fs.mkdirSync(FOREIGN_CWD, { recursive: true });
28
+
29
+ let passed = 0;
30
+ let failed = 0;
31
+ function check(name, condition, extra = '') {
32
+ if (condition) {
33
+ passed += 1;
34
+ console.log(` OK ${name}${extra ? ` — ${extra}` : ''}`);
35
+ } else {
36
+ failed += 1;
37
+ console.log(` FAIL ${name}${extra ? ` — ${extra}` : ''}`);
38
+ }
39
+ }
40
+
41
+ // Modo remoto: usa o pacote PUBLICADO via npx (validação real da release).
42
+ const remoteIndex = process.argv.indexOf('--remote');
43
+ const REMOTE_VERSION = remoteIndex > -1 ? process.argv[remoteIndex + 1] : null;
44
+ const REPO_ROOT = path.resolve(path.dirname(new URL(import.meta.url).pathname.slice(1)), '..', '..');
45
+
46
+ if (REMOTE_VERSION) {
47
+ console.log(`\n== npx @danhachuel/jobfinder@${REMOTE_VERSION} em ${FOREIGN_CWD} ==`);
48
+ } else {
49
+ console.log(`\n== JobFinder (build local) em ${FOREIGN_CWD} ==`);
50
+ console.log('(equivalente ao `npx @danhachuel/jobfinder@<versao>`: mesmo cwd estranho, mesmo binário)');
51
+ }
52
+
53
+ // `shell: true` é obrigatório no Windows para spawnar um .cmd (npx.cmd).
54
+ const npx = REMOTE_VERSION
55
+ ? spawn(`npx --yes @danhachuel/jobfinder@${REMOTE_VERSION} start --port ${PORT}`, {
56
+ cwd: FOREIGN_CWD,
57
+ shell: true,
58
+ env: { ...process.env, JOBFINDER_HOME: HOME, JOBFINDER_NO_WORKER: '1' },
59
+ stdio: ['ignore', 'pipe', 'pipe'],
60
+ })
61
+ : spawn(process.execPath, [path.join(REPO_ROOT, 'scripts', 'cli.mjs'), 'start', '--port', String(PORT)], {
62
+ cwd: FOREIGN_CWD,
63
+ env: { ...process.env, JOBFINDER_HOME: HOME, JOBFINDER_NO_WORKER: '1' },
64
+ stdio: ['ignore', 'pipe', 'pipe'],
65
+ });
66
+ const cli = npx;
67
+
68
+ let out = '';
69
+ let err = '';
70
+ npx.stdout.on('data', (d) => { out += String(d); });
71
+ npx.stderr.on('data', (d) => { err += String(d); });
72
+
73
+ const alive = async () => new Promise((resolve) => {
74
+ if (npx.exitCode !== null || npx.signalCode !== null) return resolve(false);
75
+ npx.kill(0);
76
+ resolve(true);
77
+ });
78
+
79
+ // 1. espera o servidor subir
80
+ let httpOk = false;
81
+ for (let i = 0; i < 60; i += 1) {
82
+ try {
83
+ if ((await fetch(`http://127.0.0.1:${PORT}/api/health`)).ok) { httpOk = true; break; }
84
+ } catch { /* ainda subindo */ }
85
+ await delay(1000);
86
+ }
87
+ check('servidor respondeu HTTP na porta', httpOk);
88
+
89
+ // 2. versão correta no output (a linha do servidor, não só o banner do CLI)
90
+ const serverLine = out.split('\n').find((l) => l.includes('listening on')) ?? '';
91
+ const expected = REMOTE_VERSION ? REMOTE_VERSION.replace(/^0\./, '0.') : /0\.1\.\d+/.source;
92
+ const expectedRe = REMOTE_VERSION ? new RegExp(REMOTE_VERSION.replace(/\./g, '\\.')) : /0\.1\.\d+/;
93
+ const versionLine = out.split('\n').find((l) => /^JobFinder\s+v?\d/.test(l.trim())) ?? '';
94
+ check('versão correta (não 0.0.00)', expectedRe.test(versionLine) && !versionLine.includes('0.0.00'), versionLine.trim());
95
+ check('linha do listen traz a versão correta', expectedRe.test(serverLine) && !serverLine.includes('0.0.00'), serverLine.trim());
96
+
97
+ // 3. o processo PRECISA continuar vivo (não voltar ao prompt)
98
+ await delay(8000);
99
+ const stillAlive = await alive();
100
+ check('processo npx continua vivo após 8s do listen', stillAlive, `exitCode=${npx.exitCode} signal=${npx.signalCode}`);
101
+
102
+ // 4. HTTP continua respondendo depois (prova que não morreu)
103
+ const httpAfter = await fetch(`http://127.0.0.1:${PORT}/api/health`).then((r) => r.ok).catch(() => false);
104
+ check('HTTP 200 depois da espera', httpAfter);
105
+
106
+ // 5. rastro forense: se morreu, o motivo tem que estar visível
107
+ if (!stillAlive) {
108
+ console.log('--- stdout ---'); console.log(out);
109
+ console.log('--- stderr ---'); console.log(err);
110
+ }
111
+
112
+ check('nenhum "launcher exiting" prematuro no log', !err.includes('launcher exiting') && !out.includes('launcher exiting'), err.split('\n').filter((l) => l.includes('launcher exiting')).slice(0, 1).join(''));
113
+
114
+ try { npx.kill('SIGTERM'); } catch { /* já morreu */ }
115
+ await delay(500);
116
+ try { npx.kill('SIGKILL'); } catch { /* já morreu */ }
117
+
118
+ // ------------------------------------------------------------------ *
119
+ // Caminho 2: `node src/server/index.mjs` DIRETO, de um cwd estranho e SEM
120
+ // JOBFINDER_VERSION — valida o createRequire(import.meta.url) puro.
121
+ // ------------------------------------------------------------------ *
122
+ console.log('\n== node src/server/index.mjs direto (sem JOBFINDER_VERSION) ==');
123
+ const direct = spawn(process.execPath, [path.join(REPO_ROOT, 'src', 'server', 'index.mjs')], {
124
+ cwd: FOREIGN_CWD,
125
+ env: { ...process.env, JOBFINDER_HOME: HOME, JOBFINDER_PORT: String(PORT + 1), JOBFINDER_NO_WORKER: '1' },
126
+ stdio: ['ignore', 'pipe', 'pipe'],
127
+ });
128
+ let directOut = '';
129
+ direct.stdout.on('data', (d) => { directOut += String(d); });
130
+ direct.stderr.on('data', (d) => { directOut += String(d); });
131
+ let directHttp = false;
132
+ for (let i = 0; i < 40; i += 1) {
133
+ try {
134
+ if ((await fetch(`http://127.0.0.1:${PORT + 1}/api/health`)).ok) { directHttp = true; break; }
135
+ } catch { /* subindo */ }
136
+ await delay(500);
137
+ }
138
+ check('servidor direto respondeu HTTP', directHttp);
139
+ const directLine = directOut.split('\n').find((l) => l.includes('listening on')) ?? '';
140
+ check('versão correta sem env override (createRequire)', /0\.1\.\d+/.test(directLine) && !directLine.includes('0.0.00'), directLine.trim());
141
+ await delay(3000);
142
+ check('servidor direto continua vivo', direct.exitCode === null && direct.signalCode === null, `exitCode=${direct.exitCode}`);
143
+ try { direct.kill('SIGTERM'); } catch { /* já morreu */ }
144
+ await delay(500);
145
+ try { direct.kill('SIGKILL'); } catch { /* já morreu */ }
146
+
147
+ // ------------------------------------------------------------------ *
148
+ // Caminho 3: caminho padrão COMPLETO, com o worker ativo (como o usuário
149
+ // really roda) — o worker não pode derrubar o launcher.
150
+ // ------------------------------------------------------------------ *
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)], {
153
+ cwd: FOREIGN_CWD,
154
+ env: { ...process.env, JOBFINDER_HOME: HOME },
155
+ stdio: ['ignore', 'pipe', 'pipe'],
156
+ });
157
+ let fullOut = '';
158
+ full.stdout.on('data', (d) => { fullOut += String(d); });
159
+ full.stderr.on('data', (d) => { fullOut += String(d); });
160
+ let fullHttp = false;
161
+ for (let i = 0; i < 40; i += 1) {
162
+ try {
163
+ if ((await fetch(`http://127.0.0.1:${PORT + 2}/api/health`)).ok) { fullHttp = true; break; }
164
+ } catch { /* subindo */ }
165
+ await delay(500);
166
+ }
167
+ check('app completo (com worker) respondeu HTTP', fullHttp);
168
+ await delay(6000);
169
+ check('app completo continua vivo', full.exitCode === null && full.signalCode === null, `exitCode=${full.exitCode} signal=${full.signalCode}`);
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());
172
+ try { full.kill('SIGTERM'); } catch { /* já morreu */ }
173
+ await delay(3000);
174
+ try { full.kill('SIGKILL'); } catch { /* já morreu */ }
175
+
176
+ console.log('\n--- saída capturada ---');
177
+ console.log(out.split('\n').filter(Boolean).slice(0, 20).join('\n'));
178
+ if (err.trim()) { console.log('--- stderr ---'); console.log(err.split('\n').filter(Boolean).slice(0, 10).join('\n')); }
179
+
180
+ console.log(`\nResultado: ${passed} passaram, ${failed} falharam.`);
181
+ process.exit(failed ? 1 : 0);