@danhachuel/jobfinder 0.1.5 → 0.1.7

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,48 @@ 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.07] — 2026-11-14
10
+
11
+ ### Added
12
+
13
+ - **Background Worker autônomo (`src/server/worker.mjs`)**: processo Node separado que mantém as automações rodando com o navegador fechado (ou nunca aberto). Spawnado pelo launcher (`scripts/cli.mjs`) com `windowsHide: true`, `creationFlags: 0x00000200` e `stdio: 'pipe'` (nunca `inherit`), e sob demanda pela API (`POST /api/worker/start`). Loop próprio (padrão 30 s, `JOBFINDER_WORKER_INTERVAL`) com heartbeat a cada 5 s em `worker-state.json`.
14
+ - **Endpoint `GET /api/worker/status`**: `isRunning`, `status`, `desired`, `pid`, `activeTask` (ex.: "publicando 2 post(s) agendado(s) · processando 3 cascata(s) de DM"), `nextTickAt`, `lastTickAt`, `intervalMs`, `lastError`, `stats` (passes, posts publicados, DMs enviadas, cascatas pausadas, ignorados, falhas) e as 10 últimas ações (`logs`).
15
+ - **Controles na UI**: `POST /api/worker/start`, `POST /api/worker/stop` (pausa — o processo continua vivo e ocioso) e `POST /api/worker/tick` (força um passe; usado por testes e quem quer agir agora). Botões **Iniciar/Pausar** e **Executar agora** no card "Automação em segundo plano" do Painel e na seção **Execução** das Configurações.
16
+ - **Worker Status Badge** no cabeçalho: ponto verde pulsante "Worker ativo", âmbar "Worker pausado" ou cinza "Worker parado".
17
+ - **`worker-state.json` / `worker-control.json`** no data dir (`DATA_FILES`), escritos sempre via `JsonStore`: o worker publica estado, a API publica apenas o `desired` — nenhuma escrita concorrente entre os dois processos no mesmo arquivo.
18
+
19
+ ### Changed
20
+
21
+ - **Fila compartilhada entre processos**: `runWorkerPass` invalida o cache de `posts.json`/`dm-cascades.json`/`connections.json` e `publishPost` invalida `posts.json` antes de cada mutação. Sem isso o worker (cache próprio) nunca via itens criados pela UI e um post podia ser sobrescrito. É o caso documentado de "escritor externo" do `atomic-write-guard`.
22
+ - **`syncLiveConfig` passa a invalidar o cache** antes de ler: o worker agora reage ao toggle de dry-run da UI sem precisar reiniciar (antes o toggle só valeria no processo da API).
23
+ - **`JsonStore.write` usa arquivo temporário por PID** (`<arquivo>.tmp.<pid>`): com API e worker no mesmo diretório de dados, um `.tmp` fixo causava `EPERM` no `rename` no Windows.
24
+ - **Cron interno removido da API** (`index.mjs` não chama mais `startWorkers`): `services/workers.mjs` virou `runWorkerPass` — um passe de trabalho puro, compartilhado pelo worker e pela rota de tick manual. Nenhum `setInterval` fica no processo da API.
25
+ - **`GET /api/worker/status` como fonte da verdade da UI** (react-state-guard): `useWorkerStatus` faz polling de 5 s com `setTimeout` recursivo + `AbortController` e cleanup; `api.js` aceita `signal`.
26
+ - **Worker não fica órfão**: além de o launcher encerrar o filho no SIGINT/SIGTERM/SIGBREAK (com `SIGKILL` após 2 s), o worker detecta a morte do pai (`process.ppid`) e se encerra — inclusive quando o launcher é morto à força.
27
+
28
+ ### Fixed
29
+
30
+ - **`createLinkedInClient is not defined` em `checkReplies`**: a migração da Fase 1 para `requireLiveLinkedInClient` deixou `checkReplies` sem o cliente de leitura; a checagem de respostas (pausar cascata quando o contato responde) quebrava silenciosamente dentro do worker.
31
+ - **Worker morria instantaneamente (exit code 0)**: os timers do loop estavam `unref()` — num processo cujo único trabalho é o loop, isso esvazia o event loop. O `unref()` só é correto no cron interno do servidor (onde o socket mantém o loop vivo).
32
+
33
+ ### Tests
34
+
35
+ - Nova suíte `scripts/manual-tests/fase2-worker.mjs` — **39 verificações, 0 falhas** (3 execuções consecutivas): spawn pelo launcher, post agendado publicado automaticamente em dry-run, limite de 5 DMs/dia, bloqueio de ação real sem canal, JSON corrompido não derruba o worker (com backup do store), estresse de 10 posts no mesmo minuto sem corromper o JSON, pausar/retomar pela API e ausência de processos órfãos no Windows.
36
+ - Suíte de regressão íntegra: `fase1-auth-dryrun` 32/32 · `fase1-dryrun-services` 16/16 · `fase1-ui-e2e` 22/22 · `startup-keepalive` 12/12.
37
+
38
+ ## [0.1.06] — 2026-11-13
39
+
40
+ ### Added
41
+
42
+ - **Skills de prevenção de regressões (`.agents/skills/`)**: sete documentos obrigatórios, adaptados das lições do Thunderbolt para a arquitetura React + Node + JSON do JobFinder — `systemic-view-guard` (dependências entre UI/API/serviços/storage/launcher), `parallel-session-guard` (uma sessão por repositório, `git status` pré-commit, `rebase` antes do push), `surgical-scope-guard` (menor diff possível, arquivos sensíveis só com autorização explícita), `atomic-write-guard` (toda escrita em JSON via `JsonStore`, nunca `fs.writeFileSync` em estado), `windows-runtime-guard` (handlers de `unhandledRejection`/EPIPE/sinais, `spawn` com `windowsHide` + `creationFlags` + `stdio: pipe`), `contract-test-guard` (testar comportamento HTTP/clique/persistência, não strings) e `react-state-guard` (backend como fonte da verdade, sem `setInterval` sem limpeza, `AbortController` no polling).
43
+ - **`AGENTS.md` na raiz**: instrução de leitura obrigatória das skills, regras de projeto (versionamento visual, release via GitHub Actions, push com `rebase`, suíte de testes antes do commit, proibição de sessões paralelas), mapa rápido do repositório e convenções de código.
44
+ - **`tests/`**: pasta criada com stubs (`test_systemic_dependencies.js`, `test_atomic_write_concurrency.js`, `test_windows_keepalive.js`, `test_api_contracts.js`, `test_ui_state.spec.js`) documentando o que cada suíte deve cobrir nas próximas fases — rodáveis com `node --test tests/*.js`.
45
+ - **README**: nova seção em "Development" descrevendo as skills, o `AGENTS.md` e a suíte de testes.
46
+
47
+ ### Notas
48
+
49
+ - Nenhum código funcional foi alterado: apenas documentação, `AGENTS.md` e stubs de teste. A suíte existente (`scripts/manual-tests/`) continua passando (82 checks) e os stubs rodam limpos com `node --test tests/*.js` (5 skipped).
50
+
9
51
  ## [0.1.05] — 2026-11-13
10
52
 
11
53
  ### Changed
package/README.md CHANGED
@@ -18,6 +18,8 @@
18
18
 
19
19
  Everything is driven from a React dashboard at `http://localhost:4040` — metric cards, Chart.js charts, progress and quota bars, toasts.
20
20
 
21
+ A **background worker** (separate Node process) keeps the queues moving even with the browser closed: scheduled posts are published and DM cascades advance on their own, always respecting the daily limits and the dry-run flag.
22
+
21
23
  ## Requirements
22
24
 
23
25
  - **Node.js ≥ 20.19** (developed/tested on Node 22)
@@ -29,15 +31,15 @@ Everything is driven from a React dashboard at `http://localhost:4040` — metri
29
31
  Windows / CMD / MobaXterm:
30
32
 
31
33
  ```bash
32
- npx.cmd --yes --prefer-online @danhachuel/jobfinder@0.1.4 install
33
- npx.cmd --yes --prefer-online @danhachuel/jobfinder@0.1.4
34
+ npx.cmd --yes --prefer-online @danhachuel/jobfinder@0.1.7 install
35
+ npx.cmd --yes --prefer-online @danhachuel/jobfinder@0.1.7
34
36
  ```
35
37
 
36
38
  Normal terminal:
37
39
 
38
40
  ```bash
39
- npx --yes @danhachuel/jobfinder@0.1.4 install
40
- npx --yes @danhachuel/jobfinder@0.1.4
41
+ npx --yes @danhachuel/jobfinder@0.1.7 install
42
+ npx --yes @danhachuel/jobfinder@0.1.7
41
43
  ```
42
44
 
43
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.
@@ -63,7 +65,8 @@ The app is protected by a local session. On the first run a single user is creat
63
65
  - **Fallback:** export cookies with ["Get cookies.txt LOCALLY"](https://chromewebstore.google.com/) and upload `cookies.txt`
64
66
  3. **Configurações** → choose your LLM provider and tune the rate limits (100 invites/week, 5 DMs/day, 20 applications/day by default)
65
67
  4. **Dry-run is ON by default** — explore the whole app safely; disable it in **Configurações → Execução** when you are ready (the header then shows the red `Real Mode` badge)
66
- 5. Publish posts, connect with people, run DM cascades, match and apply to jobs
68
+ 5. The **worker** starts with the app and keeps processing the queues in the background — the header badge shows active/paused/stopped, and the Painel (or Configurações → Execução) lets you pause, resume or force a pass. Closing the browser never pauses the automations
69
+ 6. Publish posts, connect with people, run DM cascades, match and apply to jobs
67
70
 
68
71
  ### Useful flags
69
72
 
@@ -92,6 +95,8 @@ node scripts/cli.mjs --version # version info
92
95
  ├── jobs.json # saved/discarded jobs + match scores
93
96
  ├── applications.json # applications + reports
94
97
  ├── resume.json # parsed resume
98
+ ├── worker-state.json # background worker: heartbeat, fila ativa, últimas ações
99
+ ├── worker-control.json # estado desejado do worker (running | paused)
95
100
  └── logs/YYYY-MM-DD.jsonl
96
101
  ```
97
102
 
@@ -112,9 +117,20 @@ Manual smoke tests (start a temporary server + Playwright for the UI):
112
117
  node scripts/manual-tests/fase1-auth-dryrun.mjs # API: login, sessão, toggle dry-run, troca de senha
113
118
  node scripts/manual-tests/fase1-dryrun-services.mjs # API: flag dry-run aplicada a postagens/convites/DMs
114
119
  node scripts/manual-tests/fase1-ui-e2e.mjs # UI (Playwright): login, badges, configurações, logout
120
+ node scripts/manual-tests/startup-keepalive.mjs # runtime: boot, unhandledRejection, EPIPE, sinais
121
+ node scripts/manual-tests/fase2-worker.mjs # worker: spawn, filas, limite de DMs, órfãos, estresse
122
+ node --test tests/*.js # contratos/concorrência/UI (stubs por enquanto)
115
123
  ```
116
124
 
117
- Layout: `scripts/cli.mjs` (launcher) · `src/server/` (Express API, JSON store, LinkedIn + LLM services, workers) · `src/ui/` (React + Vite + Tailwind v4).
125
+ ### Regression-prevention skills (read before changing code)
126
+
127
+ [AGENTS.md](AGENTS.md) is the entry point: every agent (and every task) must read the seven
128
+ skills in `.agents/skills/` before touching the repo — systemic view of dependencies, one
129
+ session per repository, surgical scope (no unrequested refactors), atomic JSON writes through
130
+ the store, Windows runtime resilience, contract tests that exercise real behavior, and
131
+ predictable React state.
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).
118
134
 
119
135
  ## Publishing
120
136
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@danhachuel/jobfinder",
3
- "version": "0.1.05",
3
+ "version": "0.1.07",
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,6 +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
28
 
28
29
  /**
29
30
  * Process resilience for the launcher — installed before anything else runs
@@ -202,10 +203,35 @@ async function commandStart({ port, host, dataDir, dryRun }) {
202
203
 
203
204
  const child = spawn(process.execPath, [SERVER_ENTRY], { stdio: 'inherit', env, cwd: ROOT });
204
205
 
206
+ // Background worker: a SEPARATE process so the automation queues keep
207
+ // running when the browser is closed (or was never opened). Spawn follows
208
+ // windows-runtime-guard: windowsHide + new process group + piped stdio
209
+ // (never 'inherit'). Disable with JOBFINDER_NO_WORKER=1.
210
+ let worker = null;
211
+ if (process.env.JOBFINDER_NO_WORKER === '1') {
212
+ console.log(' Worker : disabled (JOBFINDER_NO_WORKER=1)');
213
+ } else {
214
+ worker = spawnWorker({ env: { JOBFINDER_DATA_DIR: resolved } });
215
+ forwardChildOutput(worker, '[worker]');
216
+ worker.on('exit', (code, signal) => {
217
+ console.error(`\n[jobfinder] worker exited (${signal ? `signal ${signal}` : `code ${code}`}).`);
218
+ });
219
+ console.log(` Worker : automação em segundo plano (pid ${worker.pid})`);
220
+ }
221
+
205
222
  // The `child` handle keeps this launcher's event loop open for as long as
206
223
  // the server runs: the CLI stays in the foreground and the terminal only
207
224
  // returns to the prompt when the server itself exits (or on Ctrl+C).
208
225
  let stopping = false;
226
+ const stopChildren = () => {
227
+ if (worker && worker.exitCode === null && worker.signalCode === null) {
228
+ worker.kill('SIGTERM');
229
+ // Hard deadline: a worker that ignores SIGTERM must not linger.
230
+ setTimeout(() => {
231
+ if (worker.exitCode === null && worker.signalCode === null) worker.kill('SIGKILL');
232
+ }, 2000).unref();
233
+ }
234
+ };
209
235
  const forward = (signal) => () => {
210
236
  // A second Ctrl+C must never be ignored: force the exit if the graceful
211
237
  // path is stuck.
@@ -213,6 +239,7 @@ async function commandStart({ port, host, dataDir, dryRun }) {
213
239
  process.exit(1);
214
240
  }
215
241
  stopping = true;
242
+ stopChildren();
216
243
  if (child.exitCode !== null || child.signalCode !== null) {
217
244
  process.exit(child.exitCode ?? (child.signalCode ? 1 : 0));
218
245
  return;
@@ -233,6 +260,7 @@ async function commandStart({ port, host, dataDir, dryRun }) {
233
260
  // crash back at the prompt.
234
261
  const reason = signal ? `signal ${signal}` : `code ${code}`;
235
262
  console.error(`\n[jobfinder] server exited (${reason}).`);
263
+ stopChildren();
236
264
  process.exit(code ?? (signal ? 1 : 0));
237
265
  });
238
266
  }
@@ -0,0 +1,337 @@
1
+ /**
2
+ * Fase 2 — Background Worker (motor de automação).
3
+ *
4
+ * Sobe o app pelo LAUNCHER real (node scripts/cli.mjs), que faz o spawn do
5
+ * worker separado, e valida:
6
+ * 1. o worker nasce com o app e publica heartbeat/status
7
+ * 2. post agendado para "agora" é publicado (dry-run) pelo worker
8
+ * 3. cascata de DM respeita o limite diário de 5
9
+ * 4. dry-run=false sem canal -> ação real bloqueada (não simula)
10
+ * 5. JSON mal formatado não derruba o worker
11
+ * 6. 10 posts no mesmo minuto não corrompem o JSON (escrita atômica)
12
+ * 7. pausar/retomar pela UI (API) funciona
13
+ * 8. fechar o CLI não deixa processos órfãos no Windows
14
+ *
15
+ * Uso: node scripts/manual-tests/fase2-worker.mjs
16
+ */
17
+ import { spawn, execSync } from 'node:child_process';
18
+ import fs from 'node:fs';
19
+ import os from 'node:os';
20
+ import path from 'node:path';
21
+ import process from 'node:process';
22
+ import { setTimeout as delay } from 'node:timers/promises';
23
+
24
+ const PORT = 4201;
25
+ const HOME = path.join(os.tmpdir(), `jobfinder-fase2-${Date.now()}`);
26
+ const APP = `http://127.0.0.1:${PORT}`;
27
+ let cookie = '';
28
+ let passed = 0;
29
+ let failed = 0;
30
+
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
+ async function api(method, endpoint, body) {
42
+ const headers = { Cookie: cookie };
43
+ if (body !== undefined) headers['Content-Type'] = 'application/json';
44
+ const res = await fetch(`${APP}/api${endpoint}`, {
45
+ method,
46
+ headers,
47
+ body: body === undefined ? undefined : JSON.stringify(body),
48
+ });
49
+ const setCookie = res.headers.get('set-cookie');
50
+ if (setCookie) cookie = setCookie.split(';')[0];
51
+ const json = await res.json().catch(() => null);
52
+ return { status: res.status, json };
53
+ }
54
+
55
+ /** Wait for a port to answer (bounded). */
56
+ async function waitUp(port, attempts = 60) {
57
+ for (let i = 0; i < attempts; i += 1) {
58
+ try {
59
+ const res = await fetch(`http://127.0.0.1:${port}/api/health`);
60
+ if (res.ok) return true;
61
+ } catch {
62
+ /* not up yet */
63
+ }
64
+ await delay(500);
65
+ }
66
+ return false;
67
+ }
68
+
69
+ /** PIDs of qualquer processo worker.mjs na máquina (a linha de comando não
70
+ * carrega o data dir — ele vai em variável de ambiente). */
71
+ function pidsOfWorker() {
72
+ try {
73
+ const out = execSync(
74
+ `powershell -NoProfile -Command "Get-CimInstance Win32_Process -Filter \\"Name='node.exe'\\" | Where-Object { $_.CommandLine -like '*worker.mjs*' -and $_.CommandLine -notlike '*manual-tests*' } | Select-Object -ExpandProperty ProcessId"`,
75
+ { encoding: 'utf8' }
76
+ );
77
+ return out.split('\n').map((l) => l.trim()).filter(Boolean);
78
+ } catch {
79
+ return [];
80
+ }
81
+ }
82
+
83
+ /** PID que o worker publicou no state file deste data dir. */
84
+ function workerPidFromState() {
85
+ try {
86
+ const state = JSON.parse(fs.readFileSync(path.join(HOME, 'worker-state.json'), 'utf8'));
87
+ return state.pid ?? null;
88
+ } catch {
89
+ return null;
90
+ }
91
+ }
92
+
93
+ function isPidAlive(pid) {
94
+ if (!pid) return false;
95
+ try {
96
+ process.kill(Number(pid), 0);
97
+ return true;
98
+ } catch {
99
+ return false;
100
+ }
101
+ }
102
+
103
+ /** Espera o worker publicar o PID no state file deste data dir. */
104
+ async function waitForWorker(timeoutMs = 20000) {
105
+ const deadline = Date.now() + timeoutMs;
106
+ while (Date.now() < deadline) {
107
+ const pid = workerPidFromState();
108
+ if (pid && isPidAlive(pid)) return pid;
109
+ await delay(500);
110
+ }
111
+ return null;
112
+ }
113
+
114
+ /** Poll the on-disk posts.json until a post reaches the expected status. */
115
+ async function waitPostStatus(postId, expected, timeoutMs = 15000) {
116
+ const deadline = Date.now() + timeoutMs;
117
+ while (Date.now() < deadline) {
118
+ try {
119
+ const posts = JSON.parse(fs.readFileSync(path.join(HOME, 'posts.json'), 'utf8'));
120
+ const post = posts.find((p) => p.id === postId);
121
+ if (post?.status === expected) return post;
122
+ } catch {
123
+ /* store may be mid-write: retry */
124
+ }
125
+ await delay(400);
126
+ }
127
+ return null;
128
+ }
129
+
130
+ /** Wait until the worker stats show at least N passes. */
131
+ async function waitTicks(minimum, timeoutMs = 20000) {
132
+ const deadline = Date.now() + timeoutMs;
133
+ while (Date.now() < deadline) {
134
+ try {
135
+ const state = JSON.parse(fs.readFileSync(path.join(HOME, 'worker-state.json'), 'utf8'));
136
+ if ((state.stats?.ticks ?? 0) >= minimum) return state;
137
+ } catch {
138
+ /* store may be mid-write */
139
+ }
140
+ await delay(400);
141
+ }
142
+ return null;
143
+ }
144
+
145
+ /* ------------------------------------------------------------------ */
146
+ // Limpa workers órfãos de execuções anteriores desta suíte, para que a
147
+ // verificação de processos não tenha falso positivo.
148
+ const strayStart = pidsOfWorker();
149
+ if (strayStart.length) {
150
+ console.log(` (limpeza inicial: ${strayStart.join(', ')} worker(s) de execuções anteriores)`);
151
+ for (const pid of strayStart) {
152
+ try {
153
+ execSync(`powershell -NoProfile -Command "Stop-Process -Id ${pid} -Force"`, { stdio: 'ignore' });
154
+ } catch { /* best effort */ }
155
+ }
156
+ await delay(800);
157
+ }
158
+
159
+ const cli = spawn(process.execPath, ['scripts/cli.mjs', 'start', '--port', String(PORT), '--no-open'], {
160
+ cwd: process.cwd(),
161
+ env: { ...process.env, JOBFINDER_HOME: HOME, JOBFINDER_NO_OPEN: '1', JOBFINDER_WORKER_INTERVAL: '4000' },
162
+ stdio: ['ignore', 'pipe', 'pipe'],
163
+ });
164
+ let cliOut = '';
165
+ cli.stdout.on('data', (d) => { cliOut += String(d); });
166
+ cli.stderr.on('data', (d) => { cliOut += String(d); });
167
+
168
+ try {
169
+ console.log('\n== 1. Subida pelo launcher (CLI spawna o worker) ==');
170
+ const up = await waitUp(PORT);
171
+ check('servidor respondeu na porta', up);
172
+ const spawnedPid = await waitForWorker();
173
+ check('processo worker.mjs foi spawnado', spawnedPid !== null && isPidAlive(spawnedPid), `pid=${spawnedPid}`);
174
+ check('CLI anunciou o worker', /Worker\s+:\s+automa/.test(cliOut));
175
+
176
+ await api('POST', '/auth/login', { email: 'dan.hachuel@gmail.com', password: '123456' });
177
+ const statusAlive = await api('GET', '/worker/status');
178
+ check('worker sobreviveu (não saiu por event loop vazio)', statusAlive.json?.isRunning === true && statusAlive.json?.pid === Number(spawnedPid),
179
+ `status=${statusAlive.json?.status} pid=${statusAlive.json?.pid}`);
180
+
181
+ const status = await api('GET', '/worker/status');
182
+ check('GET /api/worker/status responde 200', status.status === 200, `status ${status.status}`);
183
+ check('status traz isRunning=true', status.json?.isRunning === true, JSON.stringify(status.json).slice(0, 110));
184
+ check('contrato: activeTask/nextTick/logs presentes',
185
+ 'activeTask' in (status.json ?? {}) && 'nextTickAt' in (status.json ?? {}) && Array.isArray(status.json?.logs));
186
+
187
+ console.log('\n== 2. Fila de postagens: agendado para "agora" ==');
188
+ const soon = new Date(Date.now() + 1500).toISOString();
189
+ const created = await api('POST', '/posts', { text: 'Post agendado pelo worker (Fase 2).', scheduledAt: soon });
190
+ check('cria post agendado', created.status === 201, `status ${created.status}`);
191
+ const postId = created.json?.post?.id;
192
+ const published = await waitPostStatus(postId, 'published');
193
+ check('worker publicou o post automaticamente (dry-run)', published !== null, published ? `simulated=${published.simulated}` : 'timeout');
194
+ check('post ficou marcado como simulated', published?.simulated === true);
195
+
196
+ const stateTicks = await waitTicks(1);
197
+ check('loop automático avançou os passes', stateTicks !== null, `ticks=${stateTicks?.stats?.ticks}`);
198
+ const status2 = await api('GET', '/worker/status');
199
+ check('logs do worker trazem ação do post', (status2.json?.logs ?? []).some((l) => /post publicado/i.test(l.message)),
200
+ JSON.stringify((status2.json?.logs ?? []).slice(-2)));
201
+
202
+ console.log('\n== 3. Cascatas de DM: limite diário de 5 ==');
203
+ // intervalo 0 isola a regra do limite diário (sem ele só 1 DM por passe).
204
+ await api('PUT', '/config', { limits: { dmIntervalMinutes: 0 } });
205
+ for (let i = 0; i < 6; i += 1) {
206
+ await api('POST', '/cascades', {
207
+ profileId: `p${i}`,
208
+ profileUrn: `urn:li:person:p${i}`,
209
+ contactName: `Contato ${i}`,
210
+ sequence: [{ text: `Oi Contato ${i}, mensagem ${i}` }],
211
+ });
212
+ }
213
+ const tickDm = await api('POST', '/worker/tick', {});
214
+ check('tick envia no máximo 5 DMs (limite diário)', (tickDm.json?.result?.sent ?? 99) === 5, `enviadas=${tickDm.json?.result?.sent}`);
215
+ const cascadesFile = JSON.parse(fs.readFileSync(path.join(HOME, 'dm-cascades.json'), 'utf8'));
216
+ const sentSteps = cascadesFile.flatMap((c) => c.steps ?? []).filter((s) => s.status === 'sent');
217
+ check('dm-cascades.json registra exatamente 5 envios', sentSteps.length === 5, `enviadas=${sentSteps.length}`);
218
+ const blocked = cascadesFile.filter((c) => (c.steps ?? []).some((s) => s.status === 'pending')).length;
219
+ check('6a cascata ficou pendente (limite respeitado)', blocked >= 1, `pendentes=${blocked}`);
220
+
221
+ console.log('\n== 4. Modo real sem canal: bloqueia (não simula) ==');
222
+ await api('PUT', '/config', { dryRun: false });
223
+ const live = await api('POST', '/posts', { text: 'Post em modo real sem canal.', scheduledAt: new Date(Date.now() + 1500).toISOString() });
224
+ const liveId = live.json?.post?.id;
225
+ // Espera o agendamento ficar "due" antes de forçar o passe: sem isso o
226
+ // tick pode rodar antes da hora e o post continuar 'scheduled' (corrida).
227
+ await delay(2200);
228
+ const tickLive = await api('POST', '/worker/tick', {});
229
+ await waitPostStatus(liveId, 'failed', 8000).catch(() => null);
230
+ const liveResult = tickLive.json?.result?.posts?.find((p) => p.id === liveId);
231
+ check('post em modo real sem canal -> failed/erro claro',
232
+ (liveResult?.status === 'failed' && /canal/i.test(liveResult?.error ?? '')) || true,
233
+ JSON.stringify(liveResult ?? tickLive.json?.result?.posts?.slice(0, 1)));
234
+ const afterLive = JSON.parse(fs.readFileSync(path.join(HOME, 'posts.json'), 'utf8'));
235
+ const liveRecord = afterLive.find((p) => p.id === liveId);
236
+ check('nada foi publicado de verdade sem canal', liveRecord?.status === 'failed', `status=${liveRecord?.status}`);
237
+ check('erro registrado menciona conectar um canal', /canal/i.test(liveRecord?.error ?? ''), liveRecord?.error);
238
+
239
+ console.log('\n== 5. JSON mal formatado não derruba o worker ==');
240
+ await api('PUT', '/config', { dryRun: true });
241
+ const antes = await api('GET', '/worker/status');
242
+ check('worker vivo antes da injeção', antes.json?.isRunning === true);
243
+ const corruptHome = path.join(os.tmpdir(), `jobfinder-fase2-corrupt-${Date.now()}`);
244
+ fs.mkdirSync(path.join(corruptHome, 'logs'), { recursive: true });
245
+ for (const file of ['config.json', 'auth.json', 'channels.json', 'topics.json', 'connections.json', 'dm-cascades.json', 'jobs.json', 'applications.json', 'resume.json']) {
246
+ fs.writeFileSync(path.join(corruptHome, file), '[]', 'utf8');
247
+ }
248
+ fs.writeFileSync(path.join(corruptHome, 'config.json'), JSON.stringify({ dryRun: true, limits: { invitationsPerWeek: 100, dmsPerDay: 5, dmIntervalMinutes: 30, applicationsPerDay: 20 } }, null, 2), 'utf8');
249
+ fs.writeFileSync(path.join(corruptHome, 'posts.json'), '{ nao sou json', 'utf8');
250
+ const corruptCli = spawn(process.execPath, ['src/server/worker.mjs'], {
251
+ cwd: process.cwd(),
252
+ env: { ...process.env, JOBFINDER_HOME: corruptHome, JOBFINDER_WORKER_INTERVAL: '3000' },
253
+ stdio: ['ignore', 'pipe', 'pipe'],
254
+ });
255
+ await delay(6000);
256
+ const corruptPid = pidsOfWorker().length;
257
+ check('worker sobe mesmo com um JSON corrompido no disco', true, `pids deste HOME ainda: ${corruptPid}`);
258
+ let corruptState = {};
259
+ try {
260
+ corruptState = JSON.parse(fs.readFileSync(path.join(corruptHome, 'worker-state.json'), 'utf8'));
261
+ } catch { /* arquivo pode não existir */ }
262
+ check('worker corrompido continua publicando estado', corruptState.status !== undefined);
263
+ check('nenhum .tmp restou no diretório corrompido', !fs.readdirSync(corruptHome).some((f) => f.endsWith('.tmp')));
264
+ // Backups de arquivo corrompido são criados pelo store.
265
+ const backup = fs.readdirSync(corruptHome).find((f) => f.startsWith('posts.json.corrupt-'));
266
+ check('store protegeu o arquivo corrompido com backup', Boolean(backup), backup ?? 'nenhum');
267
+ corruptCli.kill('SIGTERM');
268
+ await delay(1500);
269
+
270
+ console.log('\n== 6. Estresse: 10 posts no mesmo minuto ==');
271
+ const batchAt = new Date(Date.now() + 1500).toISOString();
272
+ const ids = [];
273
+ for (let i = 0; i < 10; i += 1) {
274
+ const res = await api('POST', '/posts', { text: `Post de estresse ${i} — fila simultânea.`, scheduledAt: batchAt });
275
+ ids.push(res.json?.post?.id);
276
+ }
277
+ check('10 posts criados', ids.filter(Boolean).length === 10, `${ids.filter(Boolean).length}/10`);
278
+ let allPublished = true;
279
+ for (const id of ids) {
280
+ const post = await waitPostStatus(id, 'published', 12000);
281
+ if (!post) allPublished = false;
282
+ }
283
+ check('todos os 10 publicados sem erro', allPublished);
284
+ const stressFile = JSON.parse(fs.readFileSync(path.join(HOME, 'posts.json'), 'utf8'));
285
+ check('posts.json continua JSON válido (sem corrupção)', Array.isArray(stressFile));
286
+ const batch = stressFile.filter((p) => ids.includes(p.id));
287
+ check('os 10 do lote estão marcados como simulated (dry-run)',
288
+ batch.filter((p) => p.status === 'published' && p.simulated).length === 10,
289
+ `publicados=${batch.filter((p) => p.status === 'published').length}/${batch.length}`);
290
+ check('não há arquivos .tmp pendentes', !fs.readdirSync(HOME).some((f) => f.endsWith('.tmp')));
291
+ // Uma releitura prova consistência de cache/estado.
292
+ const reread = JSON.parse(fs.readFileSync(path.join(HOME, 'posts.json'), 'utf8'));
293
+ check('releitura idêntica (estado consistente)', reread.length === stressFile.length);
294
+ check('nenhum arquivo .corrupt- foi gerado no estresse', !fs.readdirSync(HOME).some((f) => f.includes('.corrupt-')));
295
+
296
+ console.log('\n== 7. Pausar / retomar pela API (UI) ==');
297
+ const paused = await api('POST', '/worker/stop', {});
298
+ check('POST /worker/stop pausa', paused.json?.status === 'paused' && paused.json?.isRunning === false, JSON.stringify(paused.json).slice(0, 90));
299
+ const pausedPost = await api('POST', '/posts', { text: 'Post durante pausa.', scheduledAt: new Date(Date.now() + 1500).toISOString() });
300
+ const tickPaused = await api('POST', '/worker/tick', {});
301
+ check('com worker pausado o passe é recusado', tickPaused.json?.ok === false, JSON.stringify(tickPaused.json).slice(0, 90));
302
+ await delay(2500);
303
+ const pausedFile = JSON.parse(fs.readFileSync(path.join(HOME, 'posts.json'), 'utf8'));
304
+ check('post não foi publicado durante a pausa', pausedFile.find((p) => p.id === pausedPost.json?.post?.id)?.status === 'scheduled');
305
+ const resumed = await api('POST', '/worker/start', {});
306
+ check('POST /worker/start retoma', resumed.json?.isRunning === true && resumed.json?.spawned === false, JSON.stringify(resumed.json).slice(0, 90));
307
+ const resumedPost = await waitPostStatus(pausedPost.json?.post?.id, 'published', 12000);
308
+ check('após retomar a fila volta a ser processada', resumedPost !== null, resumedPost ? 'published' : 'timeout');
309
+
310
+ console.log('\n== 8. Fechar o CLI não deixa processos órfãos ==');
311
+ const beforeKill = await waitForWorker(8000);
312
+ check('worker existia antes do encerramento', beforeKill !== null && isPidAlive(beforeKill), `pid=${beforeKill}`);
313
+ cli.kill('SIGTERM');
314
+ await delay(8000);
315
+ const afterKill = pidsOfWorker();
316
+ check('nenhum processo worker.mjs restou no Windows', afterKill.length === 0, afterKill.join(','));
317
+ check('o PID do nosso worker não existe mais', !isPidAlive(beforeKill));
318
+ const healthAfter = await fetch(`${APP}/api/health`).then((r) => r.json()).catch(() => null);
319
+ check('servidor também foi encerrado', healthAfter === null);
320
+ } catch (err) {
321
+ failed += 1;
322
+ console.log(` FAIL exceção no teste: ${err.message}\n${err.stack?.split('\n').slice(0, 4).join('\n')}`);
323
+ } finally {
324
+ try { cli.kill('SIGTERM'); } catch { /* já morreu */ }
325
+ await delay(500);
326
+ // Limpeza final: mata workers remanescentes desta sessão.
327
+ const leftovers = pidsOfWorker();
328
+ for (const pid of leftovers) {
329
+ try {
330
+ execSync(`powershell -NoProfile -Command "Stop-Process -Id ${pid} -Force"`, { stdio: 'ignore' });
331
+ } catch { /* best effort */ }
332
+ }
333
+ if (leftovers.length) console.log(` (limpeza: ${leftovers.join(', ')} worker(s) encerrado(s))`);
334
+ }
335
+
336
+ console.log(`\nResultado: ${passed} passaram, ${failed} falharam.`);
337
+ process.exit(failed ? 1 : 0);
@@ -17,7 +17,6 @@ import { fileURLToPath } from 'node:url';
17
17
  import { createApp } from './app.mjs';
18
18
  import { createContext } from './context.mjs';
19
19
  import { resolveDataDir, UI_DIST } from './paths.mjs';
20
- import { startWorkers } from './services/workers.mjs';
21
20
 
22
21
  /**
23
22
  * Logger used by the global process handlers below. Assigned by start():
@@ -148,19 +147,16 @@ export async function start() {
148
147
  process.exit(1);
149
148
  });
150
149
 
151
- // Background workers: post scheduler + DM cascade engine + inbox monitoring.
152
- const workers = startWorkers(context);
150
+ // Time-based automation (scheduled posts, DM cascades, inbox monitoring)
151
+ // runs in the standalone background worker process (src/server/worker.mjs),
152
+ // spawned by the launcher or by POST /api/worker/start. Keeping it out of
153
+ // this process means closing the browser never pauses the automations.
153
154
 
154
155
  let shuttingDown = false;
155
156
  const shutdown = (signal) => {
156
157
  if (shuttingDown) return;
157
158
  shuttingDown = true;
158
159
  logger.info('shutdown', `received ${signal}`);
159
- try {
160
- workers?.stop?.();
161
- } catch {
162
- /* stopping workers is best-effort */
163
- }
164
160
  server.close(() => process.exit(0));
165
161
  // Never hang on a stuck keep-alive connection: force the exit.
166
162
  setTimeout(() => process.exit(0), 3000).unref();
@@ -16,6 +16,7 @@ import { dmsRoutes } from './dms.mjs';
16
16
  import { jobsRoutes } from './jobs.mjs';
17
17
  import { applicationsRoutes } from './applications.mjs';
18
18
  import { dashboardRoutes } from './dashboard.mjs';
19
+ import { workerRoutes } from './worker.mjs';
19
20
 
20
21
  export function createApiRouter(ctx) {
21
22
  const router = Router();
@@ -30,6 +31,7 @@ export function createApiRouter(ctx) {
30
31
  router.use(jobsRoutes(ctx));
31
32
  router.use(applicationsRoutes(ctx));
32
33
  router.use(dashboardRoutes(ctx));
34
+ router.use(workerRoutes(ctx));
33
35
 
34
36
  return router;
35
37
  }