Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refactor([issue-1338]): extract shared createSseRunner for the three pipeline batch runners

[._.]/ Adam Eivye44d85053c78
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 170f9d43f4..4d056ce05a 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -38,6 +38,8 @@
- **Retire the repo-local `/claim`, `/gitup`, and `/work` slash commands in favor of slashdo.** The custom 46 KB `.claude/commands/claim.md` procedure (and its `.agents/skills/claim/SKILL.md` adapter) is replaced by slashdo's `/do:next`, which runs the same claim-an-item-in-a-worktree-and-ship-a-PR flow; `/gitup` and `/work` are dropped in favor of `/do:push` and slashdo's worktree workflow. The slashdo submodule is bumped v3.5.0 → v3.9.0 so `/do:next` ships from the module itself (symlinked into `.claude/commands/do/next.md` like the other `/do:*` commands) instead of relying on a separate global install. The CoS `plan-task` / `claim-issue` scheduled agents are unaffected — they carry their own self-contained prompts and never loaded the deleted command file.
+- **Unify the three pipeline editorial batch runners onto one shared SSE lifecycle.** The manuscript-completeness, editorial-analysis, and editorial-checks runners each carried a near-identical copy of the in-memory run-tracking machinery (active-run map, late-client terminal-frame replay, cancel, and the fire-and-forget coordinator); they now share a single `createSseRunner` factory, so a future fix to the streaming/replay/cancel behavior applies to all three at once. No user-visible behavior change. (`server/lib/sseUtils.js`, the three `server/services/pipeline/*Runner.js` modules, #1338)
+
## Fixed
- **The "Claim Issue" scheduled CoS task no longer reports an empty queue when there are claimable issues.** The task's prompt skipped any issue carrying the `plan` label, calling them "tracking/umbrella" issues. But `do-replan --issues` labels *every* migrated backlog item `plan` — atomic bug-fixes included — so that rule discarded the entire actionable backlog and the task always exited with "no eligible issue" even with dozens of ready-to-work issues open. The prompt now treats `plan` as the claimable-queue label (matching the `/do:next --issues` flow) and skips only true epics (an `epic` label or a "(epic)" title, which need per-slice shipping). Non-customized installs auto-upgrade to the corrected prompt on the next schedule load. (`server/services/taskPromptDefaults/`)
diff --git a/server/lib/README.md b/server/lib/README.md
index e2e508b3ed..b620d9588e 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -221,7 +221,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `objects.js` | Object utilities — `deepMerge` (recursive merge w/ array replacement), `isPlainObject` (non-null, non-array `object` guard for JSON / LLM payloads), `POLLUTING_KEYS` (shared `__proto__`/`constructor`/`prototype` denylist for sanitizers), `canonicalStringify` (recursive sorted-key JSON serialization for cross-machine content hashing), `isEmptyScalar` (true for null/undefined/whitespace-string/empty-array — merge gap-fill gate). |
| `openapiSpec.js` | `buildOpenApiSpec(settings, { baseUrl, version })` — builds an OpenAPI 3.1 document for the currently-exposed public APIs from `apiRegistry`, reusing route Zod schemas via `z.toJSONSchema`. Exposed+`requireAuth` operations get a `security` requirement; passwordless ones don't. Served by `routes/apiDocs.js`. |
| `singleFlight.js` | `createSingleFlight()` → `run(key, fn)` — keyed in-flight coalescer: concurrent calls for the same key share one `fn()` execution and result; the slot auto-clears on settle. Minimal by design (no TTL/result cache layered on top, doesn't reject concurrent callers). Used by `promptRunner.js`'s fallback mark-and-pick. |
-| `sseUtils.js` | Per-job SSE stream helpers (imageGen + others). |
+| `sseUtils.js` | Per-job SSE stream helpers (imageGen + others) plus `createSseRunner` — the shared batch-runner lifecycle (runs map, terminal-frame replay, cancel, fire-and-forget coordinator) used by the pipeline completeness/analysis/checks runners. |
| `streamBackpressure.js` | `awaitWritableDrain(res)` — park a streaming-response producer on the socket's next `drain` (or `close`) when `res.write()` returned false, so SSE/NDJSON writes stay bounded for a slow reader. Shared by `routes/ask.js` (SSE) and `routes/localLlm.js` (NDJSON). |
| `uuid.js` | `v4()` thin wrapper over `crypto.randomUUID()`. |
| `workspaceRoots.js` | Shared allow-list for routes that take a caller-supplied filesystem path. `ALLOWED_WORKSPACE_ROOTS` (defaults + `PORTOS_WORKSPACE_ROOTS`, symlink-resolved), `isWithinRoot(resolvedPath, root)` (separator-safe containment), `isWithinAllowedRoots(realPath)`, and `WORKSPACE_ROOTS_CONFIGURED` (true when the operator set the env var — lets a permissive-by-default route like `routes/detect.js` opt into confinement). Used by `routes/commands.js` (always scoped) and `routes/detect.js` (scoped only when configured). |
diff --git a/server/lib/sseUtils.js b/server/lib/sseUtils.js
index a04ae436e7..77dfd3e677 100644
--- a/server/lib/sseUtils.js
+++ b/server/lib/sseUtils.js
@@ -2,6 +2,13 @@
// videoGen/local.js. Both providers attach a list of `res` clients to a
// per-jobId record and broadcast diffuser progress as SSE frames; this module
// keeps the wire format and the response headers in one place.
+//
+// `createSseRunner` (bottom of file) layers a run-lifecycle on top of these
+// primitives for the pipeline batch runners (manuscript completeness, editorial
+// analysis, editorial checks) that all share an identical in-memory `runs` map +
+// fire-and-forget coordinator shape.
+
+import { randomUUID } from 'crypto';
// Filters Python child noise (HF/torch/bitsandbytes/xformers warnings, deprecation
// notices, etc.) that would otherwise drown the user's view of real progress.
@@ -72,3 +79,112 @@ export const closeJobAfterDelay = (jobs, jobId, delay = SSE_CLEANUP_DELAY_MS, ex
jobs.delete(jobId);
}, delay);
};
+
+// ---------------------------------------------------------------------------
+// createSseRunner — shared batch-runner lifecycle for the pipeline runners.
+// ---------------------------------------------------------------------------
+//
+// The manuscript-completeness, editorial-analysis, and editorial-checks runners
+// each kept a near-identical ~100-LOC block: a `runs` Map keyed by seriesId, a
+// `scheduleCleanup` that lingers a finished run for terminal-frame replay (with
+// an identity guard so a restart isn't clobbered by the old run's timer), an
+// `attachClient`/`cancel`/`isActive` trio, and a `start` that guards against a
+// duplicate in-flight run, mints a runId + AbortController, and drives the work
+// inside a fire-and-forget IIFE whose catch/finally emit `error` and schedule
+// cleanup. This factory owns all of that so a fix to the replay/cancel/cleanup
+// semantics can't drift between the three callers.
+//
+// The caller supplies only the per-run `work({ runId, signal, record, broadcast })`
+// async function — it owns its own `start`/`complete`/`canceled` frames and any
+// seeding; the factory owns the `error` frame, `finished` flag, and cleanup.
+//
+// `logLabel` is interpolated into the failure log (`❌ <logLabel> failed — …`).
+//
+// Returns `{ runs, isActive, attachClient, cancel, start }`. `runs` is exposed
+// so a module can re-export it as `__testing.runs`.
+export function createSseRunner({ logLabel = 'sse run' } = {}) {
+ // runs: Map<key, { runId, clients[], lastPayload, cancelRequested, finished, cleanupTimer, startedAt, abort }>
+ // A finished run lingers in the map for SSE_CLEANUP_DELAY_MS so late-attaching
+ // clients can replay its terminal frame — but `finished` lets `isActive` and
+ // the restart guard treat it as done, so an immediate re-run isn't swallowed.
+ const runs = new Map();
+
+ // Hold a finished run open briefly for terminal-frame replay, then evict it —
+ // but only if THIS record is still the one mapped, so a restart that replaced
+ // it within the window isn't clobbered by the prior run's timer.
+ const scheduleCleanup = (key, record) => {
+ record.cleanupTimer = setTimeout(() => {
+ if (runs.get(key) !== record) return;
+ for (const c of record.clients) c.end();
+ runs.delete(key);
+ }, SSE_CLEANUP_DELAY_MS);
+ };
+
+ const isActive = (key) => {
+ const run = runs.get(key);
+ return !!run && !run.finished;
+ };
+
+ const attachClient = (key, res) => attachSseClient(runs, key, res);
+
+ const cancel = (key) => {
+ const run = runs.get(key);
+ if (!run) return false;
+ run.cancelRequested = true;
+ run.abort?.abort();
+ return true;
+ };
+
+ // Kick off a run for `key`. Re-calling while a run is in flight resolves to the
+ // existing runId (no second coordinator). `work` runs inside the IIFE below.
+ const start = (key, work) => {
+ const existing = runs.get(key);
+ if (existing && !existing.finished) {
+ return { runId: existing.runId, alreadyRunning: true };
+ }
+ if (existing) {
+ // A finished run still in its replay window — cancel its pending eviction
+ // and drop its replay clients so this fresh run fully replaces it.
+ if (existing.cleanupTimer) clearTimeout(existing.cleanupTimer);
+ for (const c of existing.clients) c.end();
+ }
+ const runId = randomUUID();
+ const abort = new AbortController();
+ const record = {
+ runId,
+ clients: [],
+ lastPayload: null,
+ cancelRequested: false,
+ finished: false,
+ cleanupTimer: null,
+ startedAt: new Date().toISOString(),
+ abort,
+ };
+ runs.set(key, record);
+
+ const broadcast = (payload) => {
+ const run = runs.get(key);
+ if (!run) return;
+ broadcastSse(run, payload);
+ };
+
+ // Fire-and-forget coordinator. The try/catch is the permitted boundary use:
+ // an unhandled rejection here would crash the process on Node ≥15.
+ (async () => {
+ try {
+ await work({ runId, signal: abort.signal, record, broadcast });
+ } catch (err) {
+ const message = (err?.message || String(err)).slice(0, 1000);
+ console.error(`❌ ${logLabel} failed — series=${String(key).slice(0, 12)} ${message}`);
+ broadcast({ type: 'error', runId, error: message, failedAt: new Date().toISOString() });
+ } finally {
+ record.finished = true;
+ scheduleCleanup(key, record);
+ }
+ })();
+
+ return { runId, alreadyRunning: false };
+ };
+
+ return { runs, isActive, attachClient, cancel, start };
+}
diff --git a/server/lib/sseUtils.test.js b/server/lib/sseUtils.test.js
index 27f7970e4c..be9b51b2d5 100644
--- a/server/lib/sseUtils.test.js
+++ b/server/lib/sseUtils.test.js
@@ -4,7 +4,8 @@ import {
SSE_CLEANUP_DELAY_MS,
broadcastSse,
attachSseClient,
- closeJobAfterDelay
+ closeJobAfterDelay,
+ createSseRunner
} from './sseUtils.js';
const makeRes = () => {
@@ -183,3 +184,123 @@ describe('closeJobAfterDelay', () => {
expect(jobs.has('j1')).toBe(false);
});
});
+
+describe('createSseRunner', () => {
+ // Flush the microtask queue enough times for the fire-and-forget IIFE
+ // (try → await work → finally) to settle. Real promises are not faked even
+ // when timers are.
+ const flush = async () => {
+ for (let i = 0; i < 5; i += 1) await Promise.resolve();
+ };
+ // A never-settling promise keeps a run "in flight" for the duration of a test
+ // without leaking a pending timer.
+ const pending = () => new Promise(() => {});
+
+ it('start returns a runId, registers the run, and reports it active', () => {
+ const runner = createSseRunner({ logLabel: 'test' });
+ const { runId, alreadyRunning } = runner.start('k1', () => pending());
+
+ expect(typeof runId).toBe('string');
+ expect(runId.length).toBeGreaterThan(0);
+ expect(alreadyRunning).toBe(false);
+ expect(runner.runs.has('k1')).toBe(true);
+ expect(runner.isActive('k1')).toBe(true);
+ });
+
+ it('a second start while one is in flight resolves to the existing runId without re-running work', () => {
+ const runner = createSseRunner({ logLabel: 'test' });
+ const first = runner.start('k1', () => pending());
+ const work2 = vi.fn(() => pending());
+ const second = runner.start('k1', work2);
+
+ expect(second.runId).toBe(first.runId);
+ expect(second.alreadyRunning).toBe(true);
+ expect(work2).not.toHaveBeenCalled();
+ });
+
+ it('broadcasts frames to attached clients and caches the last frame for replay', async () => {
+ const runner = createSseRunner({ logLabel: 'test' });
+ let release;
+ const gate = new Promise((r) => { release = r; });
+ runner.start('k1', async ({ broadcast }) => {
+ broadcast({ type: 'start' });
+ await gate;
+ broadcast({ type: 'complete' });
+ });
+
+ // A client that attaches after `start` fired still replays the cached frame.
+ const res = makeRes();
+ runner.attachClient('k1', res);
+ expect(res.write).toHaveBeenCalledWith(`data: ${JSON.stringify({ type: 'start' })}\n\n`);
+
+ release();
+ await flush();
+ expect(res.write).toHaveBeenCalledWith(`data: ${JSON.stringify({ type: 'complete' })}\n\n`);
+ });
+
+ it('cancel flags the record, aborts the signal, and returns false for an unknown key', () => {
+ const runner = createSseRunner({ logLabel: 'test' });
+ let captured;
+ runner.start('k1', ({ signal, record }) => {
+ captured = { signal, record };
+ return pending();
+ });
+
+ expect(runner.cancel('k1')).toBe(true);
+ expect(captured.record.cancelRequested).toBe(true);
+ expect(captured.signal.aborted).toBe(true);
+ expect(runner.cancel('missing')).toBe(false);
+ });
+
+ it('a thrown error emits an error frame and logs, then the run is no longer active', async () => {
+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const runner = createSseRunner({ logLabel: 'widget run' });
+ const res = makeRes();
+ runner.start('k1', async ({ broadcast }) => {
+ // Attach happens inside work so the client receives the error frame live.
+ runner.attachClient('k1', res);
+ throw new Error('boom');
+ });
+
+ await flush();
+ const errorWrite = res.write.mock.calls.find(([m]) => m.includes('"type":"error"'));
+ expect(errorWrite).toBeTruthy();
+ expect(errorWrite[0]).toContain('boom');
+ expect(errSpy).toHaveBeenCalledWith(expect.stringContaining('widget run failed'));
+ expect(runner.isActive('k1')).toBe(false);
+ errSpy.mockRestore();
+ });
+
+ it('a finished run lingers for replay then is evicted after SSE_CLEANUP_DELAY_MS', async () => {
+ vi.useFakeTimers();
+ const runner = createSseRunner({ logLabel: 'test' });
+ runner.start('k1', async ({ broadcast }) => { broadcast({ type: 'complete' }); });
+
+ await flush();
+ expect(runner.isActive('k1')).toBe(false); // finished
+ expect(runner.runs.has('k1')).toBe(true); // but still mapped for replay
+
+ vi.advanceTimersByTime(SSE_CLEANUP_DELAY_MS);
+ expect(runner.runs.has('k1')).toBe(false);
+ vi.useRealTimers();
+ });
+
+ it('restarting within the replay window cancels the old eviction and replaces the run', async () => {
+ vi.useFakeTimers();
+ const runner = createSseRunner({ logLabel: 'test' });
+ const first = runner.start('k1', async ({ broadcast }) => { broadcast({ type: 'complete' }); });
+ await flush();
+ expect(runner.runs.has('k1')).toBe(true);
+
+ // Re-run before the eviction timer fires — should fully replace the record.
+ const second = runner.start('k1', () => pending());
+ expect(second.runId).not.toBe(first.runId);
+ expect(second.alreadyRunning).toBe(false);
+ expect(runner.isActive('k1')).toBe(true);
+
+ // The first run's eviction timer must NOT evict the live replacement.
+ vi.advanceTimersByTime(SSE_CLEANUP_DELAY_MS);
+ expect(runner.runs.get('k1')?.runId).toBe(second.runId);
+ vi.useRealTimers();
+ });
+});
diff --git a/server/services/pipeline/editorial/checkRunner.js b/server/services/pipeline/editorial/checkRunner.js
index ff44538104..0e599cc052 100644
--- a/server/services/pipeline/editorial/checkRunner.js
+++ b/server/services/pipeline/editorial/checkRunner.js
@@ -16,7 +16,7 @@
*/
import { randomUUID } from 'crypto';
-import { broadcastSse, attachSseClient, SSE_CLEANUP_DELAY_MS } from '../../../lib/sseUtils.js';
+import { createSseRunner } from '../../../lib/sseUtils.js';
import { runStagedLLM } from '../../../lib/stageRunner.js';
import { getEnabledChecks, getEnabledCheckRows } from '../../../lib/editorial/index.js';
import { getSettings } from '../../settings.js';
@@ -133,41 +133,22 @@ export async function buildEditorialCheckPlan(seriesId, { checkIds = null, setti
}
// ---------------------------------------------------------------------------
-// SSE run-tracking (mirrors manuscriptCompletenessRunner.js).
+// SSE run-tracking — shared lifecycle via createSseRunner (server/lib/sseUtils.js),
+// the same factory backing manuscriptCompletenessRunner + editorialAnalysisRunner.
// ---------------------------------------------------------------------------
-// runs: Map<seriesId, { runId, clients[], lastPayload, cancelRequested, finished, cleanupTimer, startedAt, abort }>
-const runs = new Map();
+const runner = createSseRunner({ logLabel: 'editorial checks' });
export function isEditorialChecksActive(seriesId) {
- const run = runs.get(seriesId);
- return !!run && !run.finished;
-}
-
-function scheduleCleanup(seriesId, record) {
- record.cleanupTimer = setTimeout(() => {
- if (runs.get(seriesId) !== record) return;
- for (const c of record.clients) c.end();
- runs.delete(seriesId);
- }, SSE_CLEANUP_DELAY_MS);
+ return runner.isActive(seriesId);
}
export function attachClient(seriesId, res) {
- return attachSseClient(runs, seriesId, res);
+ return runner.attachClient(seriesId, res);
}
export function cancelEditorialChecks(seriesId) {
- const run = runs.get(seriesId);
- if (!run) return false;
- run.cancelRequested = true;
- run.abort?.abort();
- return true;
-}
-
-function broadcast(seriesId, payload) {
- const run = runs.get(seriesId);
- if (!run) return;
- broadcastSse(run, payload);
+ return runner.cancel(seriesId);
}
/**
@@ -176,65 +157,30 @@ function broadcast(seriesId, payload) {
* existing runId.
*/
export function startEditorialChecksRun(seriesId, options = {}) {
- const existing = runs.get(seriesId);
- if (existing && !existing.finished) {
- return { runId: existing.runId, alreadyRunning: true };
- }
- if (existing) {
- if (existing.cleanupTimer) clearTimeout(existing.cleanupTimer);
- for (const c of existing.clients) c.end();
- }
- const runId = randomUUID();
- const abort = new AbortController();
- const record = {
- runId,
- clients: [],
- lastPayload: null,
- cancelRequested: false,
- finished: false,
- cleanupTimer: null,
- startedAt: new Date().toISOString(),
- abort,
- };
- runs.set(seriesId, record);
-
- // Fire-and-forget coordinator. The try/catch is the permitted boundary use:
- // an unhandled LLM rejection here would crash the process on Node ≥15.
- (async () => {
- try {
- broadcast(seriesId, { type: 'start', runId });
- const result = await runEditorialChecks(seriesId, {
- checkIds: options.checkIds,
- providerOverride: options.providerOverride,
- modelOverride: options.modelOverride,
- signal: abort.signal,
- onProgress: (event) => broadcast(seriesId, { ...event, runId }),
- });
- if (record.cancelRequested || result.canceled) {
- broadcast(seriesId, { type: 'canceled', runId, canceledAt: new Date().toISOString() });
- console.log(`📝 editorial checks canceled — series=${String(seriesId).slice(0, 12)}`);
- return;
- }
- broadcast(seriesId, {
- type: 'complete',
- runId,
- findingCount: result.findings.length,
- perCheck: result.perCheck,
- completedAt: new Date().toISOString(),
- });
- console.log(`📝 editorial checks complete — series=${String(seriesId).slice(0, 12)} findings=${result.findings.length}`);
- } catch (err) {
- const message = (err?.message || String(err)).slice(0, 1000);
- console.error(`❌ editorial checks failed — series=${String(seriesId).slice(0, 12)} ${message}`);
- broadcast(seriesId, { type: 'error', runId, error: message, failedAt: new Date().toISOString() });
- } finally {
- record.finished = true;
- scheduleCleanup(seriesId, record);
+ return runner.start(seriesId, async ({ runId, signal, record, broadcast }) => {
+ broadcast({ type: 'start', runId });
+ const result = await runEditorialChecks(seriesId, {
+ checkIds: options.checkIds,
+ providerOverride: options.providerOverride,
+ modelOverride: options.modelOverride,
+ signal,
+ onProgress: (event) => broadcast({ ...event, runId }),
+ });
+ if (record.cancelRequested || result.canceled) {
+ broadcast({ type: 'canceled', runId, canceledAt: new Date().toISOString() });
+ console.log(`📝 editorial checks canceled — series=${String(seriesId).slice(0, 12)}`);
+ return;
}
- })();
-
- return { runId, alreadyRunning: false };
+ broadcast({
+ type: 'complete',
+ runId,
+ findingCount: result.findings.length,
+ perCheck: result.perCheck,
+ completedAt: new Date().toISOString(),
+ });
+ console.log(`📝 editorial checks complete — series=${String(seriesId).slice(0, 12)} findings=${result.findings.length}`);
+ });
}
// Export internals for tests.
-export const __testing = { runs };
+export const __testing = { runs: runner.runs };
diff --git a/server/services/pipeline/editorialAnalysisRunner.js b/server/services/pipeline/editorialAnalysisRunner.js
index ca4fe78af2..d9820c2335 100644
--- a/server/services/pipeline/editorialAnalysisRunner.js
+++ b/server/services/pipeline/editorialAnalysisRunner.js
@@ -11,48 +11,22 @@
* (or all of them when `force: true`).
*/
-import { randomUUID } from 'crypto';
-import { broadcastSse, attachSseClient, SSE_CLEANUP_DELAY_MS } from '../../lib/sseUtils.js';
+import { createSseRunner } from '../../lib/sseUtils.js';
import { listIssues } from './issues.js';
import { analyzeIssue, pickAnalyzableContent } from './editorialAnalysis.js';
-// runs: Map<seriesId, { runId, clients[], lastPayload, cancelRequested, finished, cleanupTimer, startedAt }>
-// A finished run lingers in the map for SSE_CLEANUP_DELAY_MS so late-attaching
-// clients can replay its terminal frame — but `finished` lets `isActive` and
-// the restart guard treat it as done, so an immediate re-run isn't swallowed.
-const runs = new Map();
+const runner = createSseRunner({ logLabel: 'editorial batch' });
export function isSeriesAnalysisActive(seriesId) {
- const run = runs.get(seriesId);
- return !!run && !run.finished;
-}
-
-// Hold a finished run open briefly for terminal-frame replay, then evict it —
-// but only if THIS record is still the one mapped, so a restart that replaced
-// it within the window isn't clobbered by the prior run's timer.
-function scheduleCleanup(seriesId, record) {
- record.cleanupTimer = setTimeout(() => {
- if (runs.get(seriesId) !== record) return;
- for (const c of record.clients) c.end();
- runs.delete(seriesId);
- }, SSE_CLEANUP_DELAY_MS);
+ return runner.isActive(seriesId);
}
export function attachClient(seriesId, res) {
- return attachSseClient(runs, seriesId, res);
+ return runner.attachClient(seriesId, res);
}
export function cancelSeriesAnalysis(seriesId) {
- const run = runs.get(seriesId);
- if (!run) return false;
- run.cancelRequested = true;
- return true;
-}
-
-function broadcast(seriesId, payload) {
- const run = runs.get(seriesId);
- if (!run) return;
- broadcastSse(run, payload);
+ return runner.cancel(seriesId);
}
/**
@@ -60,88 +34,53 @@ function broadcast(seriesId, payload) {
* progress lands via SSE. Re-calling while a run is in flight resolves to the
* existing runId.
*/
-export async function startSeriesAnalysis(seriesId, options = {}) {
- const existing = runs.get(seriesId);
- if (existing && !existing.finished) {
- return { runId: existing.runId, alreadyRunning: true };
- }
- if (existing) {
- // A finished run still in its replay window — cancel its pending eviction
- // and drop its replay clients so this fresh run fully replaces it.
- if (existing.cleanupTimer) clearTimeout(existing.cleanupTimer);
- for (const c of existing.clients) c.end();
- }
- const runId = randomUUID();
- const record = {
- runId,
- clients: [],
- lastPayload: null,
- cancelRequested: false,
- finished: false,
- cleanupTimer: null,
- startedAt: new Date().toISOString(),
- };
- runs.set(seriesId, record);
+export function startSeriesAnalysis(seriesId, options = {}) {
+ return runner.start(seriesId, async ({ runId, record, broadcast }) => {
+ const issues = await listIssues({ seriesId });
+ const analyzable = issues.filter((i) => pickAnalyzableContent(i));
+ const ordered = analyzable.sort(
+ (a, b) => (a.arcPosition ?? 9999) - (b.arcPosition ?? 9999) || (a.number || 0) - (b.number || 0)
+ );
+ broadcast({ type: 'start', runId, total: ordered.length });
- // Fire-and-forget coordinator. The try/catch is the permitted boundary use:
- // an unhandled LLM rejection here would crash the process on Node ≥15.
- (async () => {
- try {
- const issues = await listIssues({ seriesId });
- const analyzable = issues.filter((i) => pickAnalyzableContent(i));
- const ordered = analyzable.sort(
- (a, b) => (a.arcPosition ?? 9999) - (b.arcPosition ?? 9999) || (a.number || 0) - (b.number || 0)
- );
- broadcast(seriesId, { type: 'start', runId, total: ordered.length });
-
- let done = 0;
- for (const issue of ordered) {
- if (record.cancelRequested) break;
- broadcast(seriesId, {
- type: 'issue:start',
- issueId: issue.id,
- number: issue.number,
- title: issue.title,
- done,
- total: ordered.length,
- });
- const result = await analyzeIssue(issue.id, {
- providerId: options.providerId,
- model: options.model,
- force: !!options.force,
- }).catch((err) => ({ status: 'error', error: (err?.message || String(err)).slice(0, 500) }));
- done += 1;
- broadcast(seriesId, {
- type: result?.status === 'error' ? 'issue:error' : 'issue:complete',
- issueId: issue.id,
- number: issue.number,
- done,
- total: ordered.length,
- cached: !!result?.cached,
- sections: result?.sections?.length || 0,
- error: result?.status === 'error' ? result.error : undefined,
- });
- }
-
- broadcast(seriesId, {
- type: record.cancelRequested ? 'canceled' : 'complete',
- runId,
- analyzed: done,
- completedAt: new Date().toISOString(),
+ let done = 0;
+ for (const issue of ordered) {
+ if (record.cancelRequested) break;
+ broadcast({
+ type: 'issue:start',
+ issueId: issue.id,
+ number: issue.number,
+ title: issue.title,
+ done,
+ total: ordered.length,
+ });
+ const result = await analyzeIssue(issue.id, {
+ providerId: options.providerId,
+ model: options.model,
+ force: !!options.force,
+ }).catch((err) => ({ status: 'error', error: (err?.message || String(err)).slice(0, 500) }));
+ done += 1;
+ broadcast({
+ type: result?.status === 'error' ? 'issue:error' : 'issue:complete',
+ issueId: issue.id,
+ number: issue.number,
+ done,
+ total: ordered.length,
+ cached: !!result?.cached,
+ sections: result?.sections?.length || 0,
+ error: result?.status === 'error' ? result.error : undefined,
});
- console.log(`📊 editorial batch ${record.cancelRequested ? 'canceled' : 'complete'} — series=${seriesId.slice(0, 12)} analyzed=${done}/${ordered.length}`);
- } catch (err) {
- const message = (err?.message || String(err)).slice(0, 1000);
- console.error(`❌ editorial batch failed — series=${seriesId.slice(0, 12)} ${message}`);
- broadcast(seriesId, { type: 'error', runId, error: message, failedAt: new Date().toISOString() });
- } finally {
- record.finished = true;
- scheduleCleanup(seriesId, record);
}
- })();
- return { runId, alreadyRunning: false };
+ broadcast({
+ type: record.cancelRequested ? 'canceled' : 'complete',
+ runId,
+ analyzed: done,
+ completedAt: new Date().toISOString(),
+ });
+ console.log(`📊 editorial batch ${record.cancelRequested ? 'canceled' : 'complete'} — series=${seriesId.slice(0, 12)} analyzed=${done}/${ordered.length}`);
+ });
}
// Export internals for tests.
-export const __testing = { runs };
+export const __testing = { runs: runner.runs };
diff --git a/server/services/pipeline/manuscriptCompletenessRunner.js b/server/services/pipeline/manuscriptCompletenessRunner.js
index 22f976f1d5..570c74612a 100644
--- a/server/services/pipeline/manuscriptCompletenessRunner.js
+++ b/server/services/pipeline/manuscriptCompletenessRunner.js
@@ -17,49 +17,22 @@
* sync route does.
*/
-import { randomUUID } from 'crypto';
-import { broadcastSse, attachSseClient, SSE_CLEANUP_DELAY_MS } from '../../lib/sseUtils.js';
+import { createSseRunner } from '../../lib/sseUtils.js';
import { analyzeManuscriptCompleteness } from './arcPlanner.js';
import { seedReviewFromFindings } from './manuscriptReview.js';
-// runs: Map<seriesId, { runId, clients[], lastPayload, cancelRequested, finished, cleanupTimer, startedAt, abort }>
-// A finished run lingers in the map for SSE_CLEANUP_DELAY_MS so late-attaching
-// clients can replay its terminal frame — but `finished` lets `isActive` and
-// the restart guard treat it as done, so an immediate re-run isn't swallowed.
-const runs = new Map();
+const runner = createSseRunner({ logLabel: 'completeness review' });
export function isCompletenessReviewActive(seriesId) {
- const run = runs.get(seriesId);
- return !!run && !run.finished;
-}
-
-// Hold a finished run open briefly for terminal-frame replay, then evict it —
-// but only if THIS record is still the one mapped, so a restart that replaced
-// it within the window isn't clobbered by the prior run's timer.
-function scheduleCleanup(seriesId, record) {
- record.cleanupTimer = setTimeout(() => {
- if (runs.get(seriesId) !== record) return;
- for (const c of record.clients) c.end();
- runs.delete(seriesId);
- }, SSE_CLEANUP_DELAY_MS);
+ return runner.isActive(seriesId);
}
export function attachClient(seriesId, res) {
- return attachSseClient(runs, seriesId, res);
+ return runner.attachClient(seriesId, res);
}
export function cancelCompletenessReview(seriesId) {
- const run = runs.get(seriesId);
- if (!run) return false;
- run.cancelRequested = true;
- run.abort?.abort();
- return true;
-}
-
-function broadcast(seriesId, payload) {
- const run = runs.get(seriesId);
- if (!run) return;
- broadcastSse(run, payload);
+ return runner.cancel(seriesId);
}
/**
@@ -68,85 +41,48 @@ function broadcast(seriesId, payload) {
* is in flight resolves to the existing runId.
* `options`: { providerOverride, modelOverride, mode }.
*/
-export async function startCompletenessReview(seriesId, options = {}) {
- const existing = runs.get(seriesId);
- if (existing && !existing.finished) {
- return { runId: existing.runId, alreadyRunning: true };
- }
- if (existing) {
- // A finished run still in its replay window — cancel its pending eviction
- // and drop its replay clients so this fresh run fully replaces it.
- if (existing.cleanupTimer) clearTimeout(existing.cleanupTimer);
- for (const c of existing.clients) c.end();
- }
- const runId = randomUUID();
- const abort = new AbortController();
- const record = {
- runId,
- clients: [],
- lastPayload: null,
- cancelRequested: false,
- finished: false,
- cleanupTimer: null,
- startedAt: new Date().toISOString(),
- abort,
- };
- runs.set(seriesId, record);
-
- // Fire-and-forget coordinator. The try/catch is the permitted boundary use:
- // an unhandled LLM rejection here would crash the process on Node ≥15.
- (async () => {
- try {
- broadcast(seriesId, { type: 'start', runId });
- const result = await analyzeManuscriptCompleteness(seriesId, {
- providerOverride: options.providerOverride,
- modelOverride: options.modelOverride,
- withEdits: true, // the streamed runner exists to pre-build per-finding edits
- signal: abort.signal,
- onProgress: (event) => {
- // Forward the analyzer's progress events to SSE, stamping the runId and
- // flattening `plan`'s mode into a `chunked` flag the client reads.
- if (event.type === 'plan') broadcast(seriesId, { type: 'plan', runId, total: event.total, chunked: event.mode === 'chunked' });
- else if (event.type === 'chunk:start' || event.type === 'chunk:complete') {
- broadcast(seriesId, { type: event.type, runId, done: event.done, total: event.total });
- }
- },
- });
-
- if (record.cancelRequested || result.canceled) {
- broadcast(seriesId, { type: 'canceled', runId, canceledAt: new Date().toISOString() });
- console.log(`📚 completeness review canceled — series=${String(seriesId).slice(0, 12)}`);
- return;
- }
+export function startCompletenessReview(seriesId, options = {}) {
+ return runner.start(seriesId, async ({ runId, signal, record, broadcast }) => {
+ broadcast({ type: 'start', runId });
+ const result = await analyzeManuscriptCompleteness(seriesId, {
+ providerOverride: options.providerOverride,
+ modelOverride: options.modelOverride,
+ withEdits: true, // the streamed runner exists to pre-build per-finding edits
+ signal,
+ onProgress: (event) => {
+ // Forward the analyzer's progress events to SSE, stamping the runId and
+ // flattening `plan`'s mode into a `chunked` flag the client reads.
+ if (event.type === 'plan') broadcast({ type: 'plan', runId, total: event.total, chunked: event.mode === 'chunked' });
+ else if (event.type === 'chunk:start' || event.type === 'chunk:complete') {
+ broadcast({ type: event.type, runId, done: event.done, total: event.total });
+ }
+ },
+ });
- // Seed the persisted review exactly as the sync route does, so each comment
- // lands with its pre-built `fix` (when the finding carried a replace).
- const review = await seedReviewFromFindings(seriesId, result.issues, {
- runId: result.runId,
- mode: options.mode,
- });
- const openCount = review.comments.filter((c) => c.status === 'open').length;
- broadcast(seriesId, {
- type: 'complete',
- runId,
- openCount,
- chunked: !!result.chunked,
- chunkCount: result.chunkCount || 1,
- completedAt: new Date().toISOString(),
- });
- console.log(`📚 completeness review complete — series=${String(seriesId).slice(0, 12)} open=${openCount} chunks=${result.chunkCount || 1}`);
- } catch (err) {
- const message = (err?.message || String(err)).slice(0, 1000);
- console.error(`❌ completeness review failed — series=${String(seriesId).slice(0, 12)} ${message}`);
- broadcast(seriesId, { type: 'error', runId, error: message, failedAt: new Date().toISOString() });
- } finally {
- record.finished = true;
- scheduleCleanup(seriesId, record);
+ if (record.cancelRequested || result.canceled) {
+ broadcast({ type: 'canceled', runId, canceledAt: new Date().toISOString() });
+ console.log(`📚 completeness review canceled — series=${String(seriesId).slice(0, 12)}`);
+ return;
}
- })();
- return { runId, alreadyRunning: false };
+ // Seed the persisted review exactly as the sync route does, so each comment
+ // lands with its pre-built `fix` (when the finding carried a replace).
+ const review = await seedReviewFromFindings(seriesId, result.issues, {
+ runId: result.runId,
+ mode: options.mode,
+ });
+ const openCount = review.comments.filter((c) => c.status === 'open').length;
+ broadcast({
+ type: 'complete',
+ runId,
+ openCount,
+ chunked: !!result.chunked,
+ chunkCount: result.chunkCount || 1,
+ completedAt: new Date().toISOString(),
+ });
+ console.log(`📚 completeness review complete — series=${String(seriesId).slice(0, 12)} open=${openCount} chunks=${result.chunkCount || 1}`);
+ });
}
// Export internals for tests.
-export const __testing = { runs };
+export const __testing = { runs: runner.runs };