@danhachuel/jobfinder 0.1.12 → 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,22 @@ 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
+
9
25
  ## [0.1.12] — 2026-11-18
10
26
 
11
27
  ### Security
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.12",
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,43 +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
- // JOBFINDER_TAKEOVER: the launcher either just booted (any previous
228
- // worker's supervisor is gone by definition) or observed the previous
229
- // worker exit — a stale heartbeat must never block this spawn.
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.
230
227
  worker = spawnWorker({ env: { JOBFINDER_DATA_DIR: resolved, JOBFINDER_TAKEOVER: '1' } });
231
- forwardChildOutput(worker, '[worker]');
232
228
  worker.on('exit', (code, signal) => {
233
229
  const reason = signal ? `signal ${signal}` : `code ${code}`;
234
230
  console.error(`\n[jobfinder] worker encerrou (${reason}). O servidor web continua rodando.`);
235
- const serverAlive = child.exitCode === null && child.signalCode === null;
231
+ const serverAlive = Boolean(serverRef?.listening);
236
232
  if (!stopping && serverAlive && workerRestarts < 5) {
237
233
  workerRestarts += 1;
238
234
  console.error(`[jobfinder] reiniciando o worker (tentativa ${workerRestarts}/5)...`);
239
- // Re-check `stopping`: a shutdown that starts while this timer is
240
- // 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.
241
237
  setTimeout(() => {
242
238
  if (!stopping) startWorker();
243
239
  }, 3000);
@@ -246,52 +242,23 @@ async function commandStart({ port, host, dataDir, dryRun }) {
246
242
  return worker;
247
243
  };
248
244
 
249
- if (process.env.JOBFINDER_NO_WORKER === '1') {
250
- console.log(' Worker : disabled (JOBFINDER_NO_WORKER=1)');
251
- } else {
252
- startWorker();
253
- console.log(` Worker : automação em segundo plano (pid ${worker.pid})`);
254
- }
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);
255
248
 
256
- // The `child` handle keeps this launcher's event loop open for as long as
257
- // the server runs: the CLI stays in the foreground and the terminal only
258
- // returns to the prompt when the server itself exits (or on Ctrl+C).
259
- //
260
- // Independent keep-alive: the launcher must NEVER depend on a child handle
261
- // to stay alive (regression 0.1.7 — an empty event loop makes Node exit
262
- // with code 0, silently, right after the startup banner). This referenced
263
- // timer holds the loop open by itself; explicit process.exit() calls in
264
- // the signal/exit handlers below still terminate immediately.
265
- const keepAlive = setInterval(() => {}, 60_000);
266
- void keepAlive;
267
-
268
- // Forensic trail: if the launcher ever dies, the reason is visible.
249
+ // Forensic trail: se o launcher morrer, o motivo fica visível.
269
250
  process.on('exit', (code) => {
270
251
  console.error(`[jobfinder] launcher exiting with code ${code}.`);
271
252
  });
272
253
 
273
- const stopChildren = () => {
274
- if (worker && worker.exitCode === null && worker.signalCode === null) {
275
- worker.kill('SIGTERM');
276
- // Hard deadline: a worker that ignores SIGTERM must not linger.
277
- setTimeout(() => {
278
- if (worker.exitCode === null && worker.signalCode === null) worker.kill('SIGKILL');
279
- }, 2000).unref();
280
- }
281
- };
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.
282
256
  const forward = (signal) => () => {
283
- // A second Ctrl+C must never be ignored: force the exit if the graceful
284
- // path is stuck.
285
257
  if (stopping) {
286
258
  process.exit(1);
287
259
  }
288
260
  stopping = true;
289
261
  stopChildren();
290
- if (child.exitCode !== null || child.signalCode !== null) {
291
- process.exit(child.exitCode ?? (child.signalCode ? 1 : 0));
292
- return;
293
- }
294
- child.kill(signal);
295
262
  };
296
263
  process.on('SIGINT', forward('SIGINT'));
297
264
  process.on('SIGTERM', forward('SIGTERM'));
@@ -302,14 +269,23 @@ async function commandStart({ port, host, dataDir, dryRun }) {
302
269
  // Opening a browser window on the user's machine without being asked
303
270
  // is not acceptable for a hosted (SaaS) product.
304
271
 
305
- child.on('exit', (code, signal) => {
306
- // Loud, visible reason: the server ending must never look like a silent
307
- // crash back at the prompt.
308
- const reason = signal ? `signal ${signal}` : `code ${code}`;
309
- 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);
310
279
  stopChildren();
311
- process.exit(code ?? (signal ? 1 : 0));
312
- });
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
+ }
313
289
  }
314
290
 
315
291
  function commandVersion() {
@@ -15,6 +15,10 @@
15
15
  * 6. worker direto: rejection injetada -> worker-error.log em disco e o
16
16
  * processo continua vivo; pipes quebrados (EPIPE) não o derrubam;
17
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
18
22
  *
19
23
  * Uso: node scripts/manual-tests/startup-keepalive.mjs
20
24
  */
@@ -347,5 +351,57 @@ async function bootAndObserve(label, { args, port, observeMs, env = {} }) {
347
351
  fs.rmSync(tmp, { recursive: true, force: true });
348
352
  }
349
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
+
350
406
  console.log(`\nResultado: ${passed} passaram, ${failed} falharam.`);
351
407
  process.exit(failed ? 1 : 0);
@@ -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
  });
@@ -78,6 +78,22 @@ function appendErrorLog(line) {
78
78
  }
79
79
  }
80
80
 
81
+ /**
82
+ * Append one line to <dataDir>/worker.log — the worker's lifecycle log
83
+ * (boot, passes, stops). The worker runs with stdio all-'ignore': the FILE
84
+ * is the log, the console (a NUL device or a dying MobaXterm pipe) is not
85
+ * a channel anything may depend on.
86
+ */
87
+ let logFilePath = null;
88
+ function appendLogFile(line) {
89
+ if (!logFilePath) return;
90
+ try {
91
+ fs.appendFileSync(logFilePath, `${new Date().toISOString()} ${line}\n`, 'utf8');
92
+ } catch {
93
+ /* read-only data dir: worker-error.log may still have the failures */
94
+ }
95
+ }
96
+
81
97
  /** Report an unexpected failure: file log + logger + safe console mirror. */
82
98
  function reportUnexpected(scope, reason) {
83
99
  const message = reason instanceof Error ? reason.message : String(reason);
@@ -366,7 +382,7 @@ function stop(reason) {
366
382
  } catch {
367
383
  /* state is best-effort during shutdown */
368
384
  }
369
- appendErrorLog(`stopped (${reason})`);
385
+ appendLogFile(`stopped (${reason})`);
370
386
  safeWrite(process.stderr, `[jobfinder:worker] stopped (${reason}).\n`);
371
387
  process.exit(0);
372
388
  }
@@ -406,12 +422,15 @@ function schedule() {
406
422
 
407
423
  async function main() {
408
424
  const dataDir = resolveDataDir();
425
+ // Log paths first: even the boot checks below must leave a file trace.
426
+ errorLogPath = path.join(dataDir, 'worker-error.log');
427
+ // Lifecycle log (boot/passes/stops): stdio is 'ignore', the file IS the log.
428
+ logFilePath = path.join(dataDir, 'worker.log');
409
429
  if (!fs.existsSync(dataDir)) {
410
- console.error(`[jobfinder:worker] data directory not found: ${dataDir}`);
430
+ appendErrorLog(`data directory not found: ${dataDir}`);
431
+ safeWrite(process.stderr, `[jobfinder:worker] data directory not found: ${dataDir}\n`);
411
432
  process.exit(1);
412
433
  }
413
- // Crash/forensic log: the only artifact that survives a dead pipe.
414
- errorLogPath = path.join(dataDir, 'worker-error.log');
415
434
 
416
435
  // Orphan detection by PIPE (primary). The supervisor keeps our stdin pipe
417
436
  // open for as long as it lives; when it dies (any reason, hard kill
@@ -438,7 +457,8 @@ async function main() {
438
457
  logger = context.logger;
439
458
 
440
459
  if (anotherWorkerOwnsState()) {
441
- console.error('[jobfinder:worker] another worker is already running - exiting.');
460
+ appendLogFile('another worker is already running - exiting.');
461
+ safeWrite(process.stderr, '[jobfinder:worker] another worker is already running - exiting.\n');
442
462
  process.exit(0);
443
463
  }
444
464
 
@@ -457,9 +477,8 @@ async function main() {
457
477
  logs: [],
458
478
  });
459
479
  logger?.info('worker', 'worker started', { pid: process.pid, intervalMs: INTERVAL_MS, dataDir });
460
- console.log(
461
- `[jobfinder:worker] running (pid ${process.pid}, every ${Math.round(INTERVAL_MS / 1000)}s) - data: ${dataDir}`
462
- );
480
+ appendLogFile(`running (pid ${process.pid}, every ${Math.round(INTERVAL_MS / 1000)}s) - data: ${dataDir}`);
481
+ safeWrite(process.stdout, `[jobfinder:worker] running (pid ${process.pid}, every ${Math.round(INTERVAL_MS / 1000)}s)\n`);
463
482
 
464
483
  // Idempotent signals: only the first one triggers the graceful stop.
465
484
  const onSignal = (signal) => () => stop(`received ${signal}`);
@@ -7,9 +7,15 @@
7
7
  * fresh heartbeat from a different pid exits immediately instead of
8
8
  * creating a duplicate.
9
9
  *
10
- * Spawn flags follow windows-runtime-guard: never `stdio: 'inherit'`
11
- * (a broken terminal would kill the child with EPIPE), `windowsHide: true`
12
- * and CREATE_NEW_PROCESS_GROUP (0x00000200) on Windows.
10
+ * Spawn flags follow runtime-guard: `windowsHide: true` and
11
+ * CREATE_NEW_PROCESS_GROUP (0x00000200) on Windows.
12
+ *
13
+ * stdio is ALL 'ignore' on purpose: the worker never writes to the
14
+ * launcher's pipes. A hostile terminal (MobaXterm, npx wrappers, output
15
+ * redirection) that chokes on — or closes — those pipes can no longer
16
+ * disturb either process. The worker records everything in files inside
17
+ * the data dir (worker.log, worker-error.log, logs/*.jsonl); its stdin
18
+ * stays a pipe only to carry the "supervisor died" EOF signal.
13
19
  */
14
20
  import { spawn } from 'node:child_process';
15
21
  import path from 'node:path';
@@ -23,80 +29,25 @@ export const WORKER_ENTRY = path.join(__dirname, 'worker.mjs');
23
29
  export const CREATE_NEW_PROCESS_GROUP = 0x00000200;
24
30
 
25
31
  /**
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
- * stdin is a pipe that the supervisor NEVER writes: when the supervisor
35
- * dies, its end closes and the child sees EOF on stdin — a deterministic
36
- * "parent is gone" signal that does not depend on pid recycling (which
37
- * breaks the classic `process.kill(ppid, 0)` check on Windows). The worker
38
- * uses it to self-terminate; the server ignores it.
39
- *
40
- * @param {string} entry absolute path of the child entrypoint
32
+ * Spawn the worker as a detached-enough child of the caller.
41
33
  * @param {{ env?: object, cwd?: string }} [options]
42
34
  * @returns {import('node:child_process').ChildProcess}
43
35
  */
44
- export function spawnSupervised(entry, options = {}) {
45
- return spawn(process.execPath, [entry], {
36
+ export function spawnWorker(options = {}) {
37
+ return spawn(process.execPath, [WORKER_ENTRY], {
46
38
  cwd: options.cwd ?? path.resolve(__dirname, '..', '..'),
47
39
  env: {
48
40
  ...process.env,
49
- // Tells a supervised worker that fd 0 is a REAL pipe to this supervisor
50
- // (never the NUL device of a manual run): EOF on stdin then means
51
- // "the supervisor died". A manual run must not arm the detector.
41
+ // Tells the worker that fd 0 is a REAL pipe to this supervisor (never
42
+ // the NUL device of a manual run): EOF on stdin then means "the
43
+ // supervisor died". A manual run must not arm the detector.
52
44
  JOBFINDER_SUPERVISED_STDIN: '1',
53
45
  ...(options.env ?? {}),
54
46
  },
55
- stdio: ['pipe', 'pipe', 'pipe'],
47
+ // stdin stays a pipe (the EOF orphan signal); stdout/stderr are ignored
48
+ // so a broken terminal can never choke the worker — it logs to files.
49
+ stdio: ['pipe', 'ignore', 'ignore'],
56
50
  windowsHide: true,
57
51
  creationFlags: process.platform === 'win32' ? CREATE_NEW_PROCESS_GROUP : 0,
58
52
  });
59
- }
60
-
61
- /**
62
- * Spawn the worker as a detached-enough child of the caller.
63
- * @param {{ env?: object, cwd?: string }} [options]
64
- * @returns {import('node:child_process').ChildProcess}
65
- */
66
- export function spawnWorker(options = {}) {
67
- return spawnSupervised(WORKER_ENTRY, options);
68
- }
69
-
70
- /** Pipe a child's output to the console with a prefix (never inherit). */
71
- export function forwardChildOutput(child, prefix, { onLine } = {}) {
72
- const label = prefix ? `${prefix} ` : '';
73
- const emit = (stream) => (chunk) => {
74
- const text = String(chunk);
75
- if (onLine) {
76
- for (const line of text.split('\n')) {
77
- if (line.trim()) onLine(line);
78
- }
79
- } else {
80
- process.stdout.write(`${label}${text}`);
81
- }
82
- void stream;
83
- };
84
- child.stdout?.on('data', emit('stdout'));
85
- child.stderr?.on('data', (chunk) => {
86
- const text = String(chunk);
87
- if (onLine) {
88
- for (const line of text.split('\n')) {
89
- if (line.trim()) onLine(line);
90
- }
91
- } else {
92
- process.stderr.write(`${prefix} ${text}`);
93
- }
94
- });
95
- // A dead pipe must never kill the launcher.
96
- child.stdout?.on?.('error', (err) => {
97
- if (err?.code !== 'EPIPE') console.error(`${prefix} stdout error: ${err?.code ?? ''}`);
98
- });
99
- child.stderr?.on?.('error', (err) => {
100
- if (err?.code !== 'EPIPE') console.error(`${prefix} stderr error: ${err?.code ?? ''}`);
101
- });
102
53
  }