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

add Series Autopilot Phase 3: file CoS tasks for capability gaps

[._.]/ Adam Eivy42c782a33f9c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index dd42a05fc0..8d86583be6 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,7 +2,7 @@
## Added
-- **Series Autopilot — drive a whole series end-to-end autonomously.** A new `POST /api/pipeline/series/:id/autopilot/start` runs a *conductor* that inspects the series' current state and walks every missing step in order — generate arc → generate episodes per volume → verify arc → per-issue beat sheets → per-issue text stages (prose + scripts) → structural comic-script gate → series-level editorial review → **draft cover + back cover + all interior comic pages** — by composing the existing pipeline service functions (it never re-implements generation). The "what's next" decision is a **pure resolver over the canonical records**, so it is non-destructive and resumable: anything already `ready`/`edited`/rendered is skipped (every pass runs `force:false`), and on restart you just start again and it picks up at the first still-missing step (a partially-built series is never clobbered). Progress streams over SSE (`/autopilot/progress`); `/autopilot/cancel` stops it (propagating to the active child runner); `/autopilot/status` exposes a thin persisted `series.autopilot` marker for resume/paused UI. Gated on the **cos** autonomy domain: `off` rejects the start (409), `dry-run` emits a no-side-effect `plan` of what it would do, `execute` runs and meters the daily cos action budget (pausing when exhausted — every draft render is one budget-gated action, since a comic is many GPU jobs). The arc-verify and editorial loops are **bounded** and **pause for human review** when they can't converge (arc verification can surface fresh findings every pass) — the residual findings are persisted on the marker. Draft renders are fire-and-forget proof-quality jobs whose in-flight job ids are persisted onto each cover/page slot (so a resumed run never re-renders an already-queued slot). Boot recovery demotes a marker stuck at `running` to `paused`. Remaining follow-ups: a craft-level LLM comic-script verify (today's script gate is a structural parse only) and auto-filing CoS tasks for capability gaps. (`server/services/pipeline/seriesAutopilot.js`, `server/routes/pipeline/autopilot.js`, `server/routes/pipeline/index.js`, `server/services/pipeline/series.js`, `server/index.js`)
+- **Series Autopilot — drive a whole series end-to-end autonomously.** A new `POST /api/pipeline/series/:id/autopilot/start` runs a *conductor* that inspects the series' current state and walks every missing step in order — generate arc → generate episodes per volume → verify arc → per-issue beat sheets → per-issue text stages (prose + scripts) → structural comic-script gate → series-level editorial review → **draft cover + back cover + all interior comic pages** — by composing the existing pipeline service functions (it never re-implements generation). The "what's next" decision is a **pure resolver over the canonical records**, so it is non-destructive and resumable: anything already `ready`/`edited`/rendered is skipped (every pass runs `force:false`), and on restart you just start again and it picks up at the first still-missing step (a partially-built series is never clobbered). Progress streams over SSE (`/autopilot/progress`); `/autopilot/cancel` stops it (propagating to the active child runner); `/autopilot/status` exposes a thin persisted `series.autopilot` marker for resume/paused UI. Gated on the **cos** autonomy domain: `off` rejects the start (409), `dry-run` emits a no-side-effect `plan` of what it would do, `execute` runs and meters the daily cos action budget (pausing when exhausted — every draft render is one budget-gated action, since a comic is many GPU jobs). The arc-verify and editorial loops are **bounded** and **pause for human review** when they can't converge (arc verification can surface fresh findings every pass) — the residual findings are persisted on the marker. Draft renders are fire-and-forget proof-quality jobs whose in-flight job ids are persisted onto each cover/page slot (so a resumed run never re-renders an already-queued slot). Boot recovery demotes a marker stuck at `running` to `paused`. With opt-in `fileGaps`, capability/quality gaps the run can't resolve on its own — an unparseable script, a failing render, a stalled verify/editorial gate, a run-ending error — are filed as **deduped CoS tasks** (scoped to the pipeline app) so they're tracked rather than silently swallowed. Remaining follow-up: a dedicated craft-level LLM comic-script verify (today's per-issue script gate is a structural parse only; deeper craft is already caught by the series-level editorial pass) — see PLAN.md. (`server/services/pipeline/seriesAutopilot.js`, `server/routes/pipeline/autopilot.js`, `server/routes/pipeline/index.js`, `server/services/pipeline/series.js`, `server/index.js`)
- **"Describe from prose" button on the Nouns stage backfills missing descriptions — and flags the nouns the manuscript can't describe.** Extracted nouns (characters/places/objects) often land with a name but no description, so a generated reference image has nothing to work from but the name. The new button writes a description for every undescribed noun that appears in the issue, using **only** what the prose actually establishes — and, crucially, it does **not** invent. This is the inverse of "Extract from prose" (which commits opinionated, renderable choices when the prose is silent so it never leaves a blank): a noun the manuscript names but never describes comes back graded `none` and stays blank, surfacing in a persistent red-flag banner ("The manuscript is thin on description for N nouns…") rather than being papered over with a fabricated look. Nouns the prose describes only in passing are graded `thin` (the grounded fragment is filled, with a note on what's missing). Strictly prose-grounded descriptions double as a manuscript-quality check: if the story can't describe its own people and places, that's a signal the prose needs enriching, not the bible. Fills only empty, unlocked entries (never clobbers an existing description or a locked one), re-reads freshest state at write time, and persists the gap report on the prose stage so the banner survives reload. Driven by a new strictly-grounded `pipeline-canon-describe-from-prose` stage prompt. (`data.reference/prompts/stages/pipeline-canon-describe-from-prose.md`, `scripts/migrations/089-canon-describe-from-prose-stage.js`, `server/services/universeCanon.js`, `server/routes/pipeline/issues.js`, `server/services/pipeline/issues.js`, `client/src/services/apiPipeline.js`, `client/src/components/pipeline/stages/NounsStage.jsx`)
diff --git a/PLAN.md b/PLAN.md
index cd8dbc85d2..ee89f5fc1c 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -20,6 +20,8 @@ independently.
<!-- reference-watch proposals: slug-tagged, picked up by /claim later -->
+- [ ] [autopilot-llm-script-verify] **Add a dedicated craft-level LLM comic-script verify pass to Series Autopilot's `scriptVerify` step.** Surfaced 2026-06-16 building Series Autopilot (`server/services/pipeline/seriesAutopilot.js` `runScriptVerify`). Today the per-issue script gate is a *structural* parse only (`scriptStructurallyReady` → does the comic script parse into ≥1 page/≥1 panel via `parseComicScript`); deeper craft issues are caught indirectly by the series-level editorial completeness pass. A dedicated pass would verify the script reads as a working comic *script* (panel-to-panel flow, page turns/beats, dialogue/art balance, clarity of action) in isolation, per issue, before pages are extracted. Needs: a new `data.reference/prompts/stages/pipeline-script-verify.md` stage prompt + `stage-config.json` entry + a `scripts/migrations/NNN-*.js` that seeds it (mind the prompt-migration drift cross-sync discipline — resync NEW/ACCEPTED_OLD hashes in earlier migrations that track the file), a `verifyComicScript(issueId, opts)` service returning `{issues:[{severity,location,problem,suggestion}]}`, and wiring into `runScriptVerify` (high-severity → seed into manuscriptReview + pause for human review, consistent with the arc/editorial gates). Deferred from the autopilot PR because the editorial completeness pass already covers comic-script craft and a new stage prompt carries real cross-install migration maintenance for marginal added value. Estimated scope: medium.
+
- [ ] [brain-memory-delete-hard-prune-vector] **Hard-delete the mapped pgvector row when a brain memory is deleted by the user (vs a peer-sync tombstone), instead of soft-archiving it forever.** Surfaced 2026-06-14 while wiring ChatGPT-import embeddings. Deleting a brain memory emits `{type}:deleted` → the bridge's `archiveMappedMemory` does `UPDATE memories SET status='archived'` (`brainMemoryBridge.js:373`). That correctly hides it from search (search filters `status='active'`), but the row + its 768-dim embedding **stay in Postgres forever** — nothing ever hard-prunes bridge-archived rows (`memoryDB.deleteMemory(id, hard=true)` exists but the bridge never calls it). For a 1482-record ChatGPT import that's later cleared, that's ~1482 dead vectors lingering. Fix: distinguish a **real local delete** (user action via `remove()` → genuine tombstone) from a **sync-driven archive** (peer delete, recoverable — must stay soft so resurrection works, see the reactivation path at `brainMemoryBridge.js:~193`). On a real local delete, hard-`DELETE` the mapped memory row + drop its bridge-map entry; keep soft-archive for the sync path. The signal is available: `handleEntityDeleted`/`resyncBrainRecord` know whether they're handling a local `:deleted` event vs a `sync:applied` resync. Add a test asserting a local delete removes the row (not just archives) while a synced delete still soft-archives. Note: the `*.db.test.js` real-Postgres guard applies. Estimated scope: small-medium.
- [ ] [media-jobs-survive-pm2-server-restart] **Isolate long media-job subprocesses (LoRA training, video gen) from pm2's restart SIGINT via spawn-side double-fork.** Surfaced 2026-06-14: a 9B LoRA training run died repeatedly with `SIGINT`/`KeyboardInterrupt` at the exact second of a `pm2 restart portos-server`. Root cause: pm2's `TreeKill.js` does `ps -e -o pid=,ppid=` and walks the **parent→child tree**, SIGINT-ing every descendant on restart/stop — and portos-server restarts routinely (was a hardcoded `max_memory_restart: 2G`, now raised + `PORTOS_SERVER_MAX_MEMORY`-configurable, default 4G). `detached: true` does NOT help (TreeKill keys on ppid, not process group); `treekill: false` on the app does NOT work either (pm2 then fails to reap the old node process → it lingers on :5555 → new instance EADDRINUSE crash-loops — tried and reverted). The correct fix is spawn-side: **double-fork the trainer/video-gen child so it reparents to launchd/init (ppid=1) and leaves pm2's tree**, while still streaming stdout for progress (e.g. an intermediate `setsid` launcher that pipes through a fifo/file the parent tails, or a tiny detached supervisor). Apply to BOTH `server/services/loraTraining/index.js:~501` AND `server/services/videoGen/local.js:~918` (same vulnerability). Validate: note the child pid, `pm2 restart portos-server`, confirm the SAME pid keeps running and the job completes. Until then, the raised memory ceiling minimizes restarts and checkpoint-resume recovers any that slip through. Estimated scope: medium.
diff --git a/server/services/pipeline/seriesAutopilot.js b/server/services/pipeline/seriesAutopilot.js
index 71fe0e6b34..cc84253cce 100644
--- a/server/services/pipeline/seriesAutopilot.js
+++ b/server/services/pipeline/seriesAutopilot.js
@@ -32,10 +32,18 @@
* run to `paused` with the residual findings for human review rather than
* looping forever.
*
+* CoS gap-filing (opt-in via `options.fileGaps`): when the autopilot hits a
+ * capability/quality gap it can't resolve — a script that won't parse, a render
+ * that keeps failing, a verify/editorial gate that stalls, or a run-ending
+ * error — it files a deduped CoS task (`fileGap`) so the gap is tracked instead
+ * of silently swallowed.
+ *
* KNOWN GAP — "script verification": there is no dedicated comic-script verify
* endpoint. The scriptVerify step is a STRUCTURAL gate only (does the comic
- * script parse into pages+panels). A real craft-level LLM script-verify prompt
- * is a deliberate Phase-3 follow-up, not silently assumed solved.
+ * script parse into pages+panels); deeper craft issues are caught by the
+ * series-level editorial completeness pass, which already analyzes comic
+ * scripts. A dedicated craft-level LLM script-verify prompt is a deferred
+ * follow-up (see PLAN.md), not silently assumed solved.
*
* DRAFT VISUALS (Phase 2, VISUAL_DRAFT_ENABLED): once a story is text-ready,
* extract comic pages from the script (if not already), then enqueue PROOF
@@ -55,6 +63,7 @@ import { getDomainMode } from '../../lib/domainAutonomy.js';
import { parseComicScript } from '../../lib/comicScriptParser.js';
import { loadState } from '../cosState.js';
import { getDomainBudgetStatus, recordDomainUsage } from '../domainUsage.js';
+import * as cosTaskStore from '../cosTaskStore.js';
import { getSeries, updateSeries } from './series.js';
import { listIssues, getIssue, isStageReady, updateStageWithLatest } from './issues.js';
import { compareIssuesByPosition } from './arcPlanner.js';
@@ -292,6 +301,24 @@ async function persistMarker(seriesId, patch) {
// Two override shapes because the delegated services disagree on field names:
// the arc/episode/verify passes take { providerOverride, modelOverride }; the
// child runners (volumeBeatsRunner, autoRunner) take { providerId, model }.
+// File a CoS task for a capability/quality gap the autopilot can't resolve on
+// its own (a script that won't parse, a render that keeps failing, a stalled
+// verify, a run-ending error). Opt-in via `options.fileGaps`; never fires in
+// dry-run. The first description line is kept STABLE per (series, gapKind,
+// issue) so cosTaskStore.addTask's pending/in_progress dedup collapses repeats
+// instead of spamming a task per page / per run. Best-effort — a task-store
+// failure must never abort the autopilot.
+async function fileGap(record, sId, { gapKind, issueId = null, summary, context = '' }) {
+ if (!record.options.fileGaps || record.mode !== 'execute') return;
+ const idTag = `series ${sId}${issueId ? ` issue ${issueId}` : ''}`;
+ const description = `Autopilot ${gapKind} gap — ${idTag}\n\n${summary}`;
+ const result = await cosTaskStore.addTask({ description, context, app: 'pipeline' }, 'user')
+ .catch((err) => { console.log(`⚠️ autopilot: fileGap (${gapKind}) failed: ${err.message}`); return null; });
+ if (result && !result.duplicate) {
+ broadcast(sId, { type: 'gap:filed', gapKind, issueId, taskId: result.id });
+ }
+}
+
const providerOverrideOpts = (record) => ({
providerOverride: record.options.providerOverride,
modelOverride: record.options.modelOverride,
@@ -377,14 +404,19 @@ async function runScriptVerify(sId, issueId, record) {
record.runState.scriptChecked.add(issueId);
const issue = await getIssue(issueId);
if (!scriptStructurallyReady(issue)) {
- // Structural gap — surface it but don't block the run (Phase 3 will file a
- // CoS task / run a craft-level LLM verify). Not billable.
+ // Structural gap — surface it but don't block the run. Not billable.
broadcast(sId, {
type: 'step:skip',
kind: 'scriptVerify',
issueId,
reason: 'comic script did not parse into pages/panels — flagged for review',
});
+ await fileGap(record, sId, {
+ gapKind: 'script-unparseable',
+ issueId,
+ summary: 'The comic script for this issue does not parse into pages/panels, so comic pages can\'t be extracted. It likely needs a manual fix or regeneration of the comicScript stage.',
+ context: `issueId=${issueId}`,
+ });
}
return {};
}
@@ -512,7 +544,16 @@ async function runVisualDraft(sId, issueId, record) {
await recordDomainUsage('cos', { actions: 1 });
broadcast(sId, { type: 'render:queued', issueId, target });
} catch (err) {
- broadcast(sId, { type: 'step:skip', kind: 'visualDraft', issueId, target, reason: (err?.message || String(err)).slice(0, 200) });
+ const reason = (err?.message || String(err)).slice(0, 200);
+ broadcast(sId, { type: 'step:skip', kind: 'visualDraft', issueId, target, reason });
+ // Dedups to one task per issue (idTag has no target), so a broken page
+ // doesn't file a task per page.
+ await fileGap(record, sId, {
+ gapKind: 'render-failed',
+ issueId,
+ summary: `A draft render failed for this issue (first failure: ${target} — ${reason}). The comic page/panel structure may be incomplete.`,
+ context: `issueId=${issueId} target=${target}`,
+ });
}
return {};
};
@@ -712,6 +753,12 @@ export async function startSeriesAutopilot(sId, options = {}) {
if (result?.pause) {
await persistMarker(sId, { status: 'paused', runId, currentStep: step.kind, residualFindings: result.residual || [], lastError: result.reason });
broadcast(sId, { type: 'paused', runId, scope: step.kind, reason: result.reason, residualFindings: result.residual || [], completedAt: new Date().toISOString() });
+ await fileGap(record, sId, {
+ gapKind: `${step.kind}-stalled`,
+ issueId: step.issueId || null,
+ summary: `Autopilot paused: ${result.reason}. Needs human review of the residual findings before it can continue.`,
+ context: JSON.stringify(result.residual || []).slice(0, 1000),
+ });
console.log(`⏸️ autopilot paused (${step.kind}) — series=${sId.slice(0, 12)}: ${result.reason}`);
return;
}
@@ -727,6 +774,11 @@ export async function startSeriesAutopilot(sId, options = {}) {
console.error(`❌ autopilot failed — series=${sId.slice(0, 12)} ${message}`);
await persistMarker(sId, { status: 'error', runId, lastError: message });
broadcast(sId, { type: 'error', runId, error: message, failedAt: new Date().toISOString() });
+ await fileGap(record, sId, {
+ gapKind: 'run-error',
+ summary: `The autonomous run failed and stopped: ${message}`,
+ context: message,
+ }).catch(() => {});
} finally {
record.finished = true;
scheduleCleanup(sId, record);
diff --git a/server/services/pipeline/seriesAutopilot.test.js b/server/services/pipeline/seriesAutopilot.test.js
index 4361f33bb3..2424aa711c 100644
--- a/server/services/pipeline/seriesAutopilot.test.js
+++ b/server/services/pipeline/seriesAutopilot.test.js
@@ -82,6 +82,10 @@ const visualSpies = {
};
vi.mock('./visualStages.js', () => visualSpies);
+let nextTaskId = 0;
+const addTask = vi.fn(async () => ({ id: `task-gap-${++nextTaskId}` }));
+vi.mock('../cosTaskStore.js', () => ({ addTask }));
+
// Real services + the unit under test (imported AFTER the mocks above).
const seriesSvc = await import('./series.js');
const seasonsSvc = await import('./seasons.js');
@@ -112,6 +116,7 @@ beforeEach(() => {
budgetStatus = { withinBudget: true, exceeded: null };
verifyFindings = [];
editorialFindings = [];
+ nextTaskId = 0;
autopilot.__testing.runs.clear();
vi.clearAllMocks();
});
@@ -266,14 +271,14 @@ describe('visualReady', () => {
// ---------------------------------------------------------------------------
// Conductor lifecycle + gating (uses real series/issues against file store).
// ---------------------------------------------------------------------------
-async function seedComplete() {
+async function seedComplete({ script = VALID_SCRIPT } = {}) {
const series = await seriesSvc.createSeries({ name: 'S', logline: 'L', premise: 'P', targetFormat: 'comic' });
await seriesSvc.updateSeries(series.id, { arc: { logline: 'A', summary: 'S' } });
const season = await seasonsSvc.createSeason(series.id, { number: 1, title: 'V1' });
const seasonId = season.id;
const issue = await issuesSvc.createIssue({ seriesId: series.id, seasonId, title: 'I1', number: 1 });
await issuesSvc.updateStage(issue.id, 'idea', ready('beats'));
- await issuesSvc.updateStage(issue.id, 'comicScript', ready(VALID_SCRIPT));
+ await issuesSvc.updateStage(issue.id, 'comicScript', ready(script));
return { seriesId: series.id, seasonId, issueId: issue.id };
}
@@ -374,6 +379,35 @@ describe('autopilot conductor', () => {
expect(visualSpies.enqueueVisualComicPage).not.toHaveBeenCalled();
});
+ it('files a CoS gap task for an unparseable script when fileGaps is set', async () => {
+ const { seriesId } = await seedComplete({ script: 'just prose, no comic pages here' });
+ await autopilot.startSeriesAutopilot(seriesId, { fileGaps: true, includeVisual: false });
+ await waitFor(runFinished(seriesId));
+ expect(addTask).toHaveBeenCalled();
+ const [taskData, taskType] = addTask.mock.calls[0];
+ expect(taskType).toBe('user');
+ expect(taskData.app).toBe('pipeline');
+ expect(taskData.description).toMatch(/script-unparseable/);
+ const last = autopilot.__testing.runs.get(seriesId)?.lastPayload;
+ expect(last?.type).toBe('complete'); // gap filed, run still finishes
+ });
+
+ it('does not file gap tasks when fileGaps is off', async () => {
+ const { seriesId } = await seedComplete({ script: 'just prose, no comic pages here' });
+ await autopilot.startSeriesAutopilot(seriesId, { includeVisual: false });
+ await waitFor(runFinished(seriesId));
+ expect(addTask).not.toHaveBeenCalled();
+ });
+
+ it('files a CoS gap task when a verify gate stalls (fileGaps)', async () => {
+ verifyFindings = [{ severity: 'high', problem: 'unresolved plot hole' }];
+ const { seriesId } = await seedComplete();
+ await autopilot.startSeriesAutopilot(seriesId, { fileGaps: true, maxArcVerifyRounds: 1 });
+ await waitFor(runFinished(seriesId));
+ expect(addTask).toHaveBeenCalled();
+ expect(addTask.mock.calls[0][0].description).toMatch(/verifyArc-stalled/);
+ });
+
it('recoverStuckAutopilots demotes a running marker to paused', async () => {
const series = await seriesSvc.createSeries({ name: 'S', logline: 'L', premise: 'P' });
await seriesSvc.updateSeries(series.id, { autopilot: { status: 'running', runId: 'dead' } });