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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
let Series Autopilot diagnose the pipeline itself and file a PortOS fix task
[._.]/ Adam Eivy7835db3b8a66
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 7d854da063..d320d28642 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -4,6 +4,8 @@- Series Pipeline **Autonomous mode** gains an **"Unlock everything this series owns first"** option. A locked arc, volume, issue stage, or canon entry makes the corresponding fix path throw or silently skip, so a run would surface an editorial finding and then pause on a problem it was never allowed to resolve — leaving you to hunt down every lock toggle by hand before re-running. With the option on, the run's first step clears the arc freeze, the per-field arc locks, every volume lock and every issue stage lock, then reports exactly what it cleared and what it deliberately left frozen. Two boundaries are hard. **Shared records stay locked:** the universe's canon and world fields are only unlocked when this is the universe's *only* series — a stamp saying this series introduced a character records provenance, not exclusive use, and once a sibling series shares the universe that character may be one the sibling is built on. **Nothing is ever deleted:** the pass clears lock bits only, so characters, objects and volumes can be rewritten in full but stay in the Universe and the Catalog. Because unlocking the volume locks also removes the only thing that used to stop a regenerated arc from *dropping* a volume, all three arc-rewriting paths (arc generation, arc auto-resolve, and the foundation gate's structure fix) now re-insert any volume the rewrite omitted, and existing volumes win the per-series volume cap so a large regeneration can't push them out of the list. Consent is per run and per series: it is never saved as a default, the box clears itself once you launch, and it resets when you switch series — so a scheduled, repeat, or other-series run can't inherit lock-clearing. The dry-run plan names the step, with a count of the locks it would clear, before you commit.+- Series Pipeline **Autonomous mode can now improve the pipeline itself.** A new Options toggle — *Improve the pipeline itself* — lets a run diagnose its own automation rather than only the story. When a run pauses, errors, or finishes carrying unhealthy telemetry (an editorial check that threw, a delegated runner that had to be retried, a step that was skipped), it spends one call asking whether the fault is the manuscript or PortOS: a missing editorial step earlier in the process, a stage prompt breaking its output contract, a runner swallowing a failure, a gate configured so it can't work. A pipeline verdict files a CoS task against PortOS itself — worktree-isolated, PR-opening, and awaiting your approval unless you opt into *Let CoS start the fix without asking me first*. Off by default, and a healthy run never spends anything on it; the diagnosis is billed as one cos action and skipped when the daily budget is spent. Repeat diagnoses of the same area collapse onto one open task instead of piling up per run, and the verdict lands on the run's status banner. Scheduled runs inherit whatever you saved.+- Series Pipeline **Autonomous mode** now says which AI it will spend on. The Options popover names the provider and model the run resolves to, links to where per-stage pins and reasoning effort are configured, and offers a per-run provider/model override (never persisted — a one-off run can't silently re-point the whole series). The live progress line names the provider of an in-flight run too, including one the scheduler started.## Fixeddiff --git a/client/src/components/pipeline/AutopilotPanel.jsx b/client/src/components/pipeline/AutopilotPanel.jsxindex 7905fc226b..484f542bc7 100644--- a/client/src/components/pipeline/AutopilotPanel.jsx+++ b/client/src/components/pipeline/AutopilotPanel.jsx@@ -49,6 +49,12 @@ const DEFAULT_REVISION_PLATEAU_DELTA = 0.3;const DEFAULT_FOUNDATION_GATE = true;const DEFAULT_FOUNDATION_THRESHOLD = 7.5;const DEFAULT_FOUNDATION_ROUNDS = 3;+// Pipeline self-improvement — mirror the server defaults (both off). When on, a+// run that ends badly diagnoses whether PortOS's own automation is at fault and+// files a worktree-isolated CoS task against PortOS to fix it; auto-approve+// decides only whether that task waits for a human before an agent picks it up.+const DEFAULT_SELF_IMPROVE = false;+const DEFAULT_SELF_IMPROVE_AUTO_APPROVE = false;// Threshold input: a [0,10] number (0.5 steps allowed — NOT integer-rounded like// the round clamps), blank/invalid → the default.const clampFoundationThreshold = (n, fallback) => {@@ -195,6 +201,9 @@ function frameLabel(f) {}case 'render:queued': return `Queued draft render: ${f.target}`;case 'gap:filed': return `Filed CoS task (${f.gapKind})`;+ // Pipeline self-improvement post-mortem. Only the START frame is live — the+ // verdict rides the terminal frame (a client tears its stream down there).+ case 'selfimprove:start': return `Diagnosing the pipeline (${f.signals} signal${f.signals === 1 ? '' : 's'})…`;// #1617 — immediate cancel ack; the active step finishes before `canceled`.case 'cancel:acknowledged': return 'Cancelling — finishing the active step…';case 'paused': return `Paused — ${f.reason}`;@@ -214,6 +223,19 @@ const craftGapCaution = (n) => `${n} filed script-craft gap${n === 1 ? '' : 's'}// dimension, so "complete" is qualified rather than "production-ready".const editorialCheckCaution = (n) => `${n} editorial check${n === 1 ? '' : 's'} errored — review before trusting "clean"`;+// One line for a pipeline self-improvement verdict, shared by the run-ended+// toast and the persisted-marker banner so the two can't drift. Null when the+// pass didn't run or found nothing worth filing — there's nothing to say then.+function selfImproveLine(si) {+ if (!si || si.verdict !== 'pipeline') return null;+ const what = si.title ? `: ${si.title}` : '';+ if (si.duplicate) return `Pipeline fix already tracked (${si.area})${what}`;+ if (!si.filed) return `Pipeline defect diagnosed (${si.area})${what} — filing it failed`;+ return si.awaitingApproval+ ? `Filed a PortOS fix task (${si.area})${what} — approve it in CoS to start the work`+ : `Filed a PortOS fix task (${si.area})${what} — CoS will pick it up`;+}+function Findings({ items }) {if (!items?.length) return null;return (@@ -281,6 +303,10 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdateconst [foundationGate, setFoundationGate] = useState(DEFAULT_FOUNDATION_GATE);const [foundationThreshold, setFoundationThreshold] = useState(DEFAULT_FOUNDATION_THRESHOLD);const [foundationRounds, setFoundationRounds] = useState(DEFAULT_FOUNDATION_ROUNDS);+ // Pipeline self-improvement. Persisted like the other options (saved default ++ // per-run override) so an enabled diagnosis is reused on Resume.+ const [selfImprove, setSelfImprove] = useState(DEFAULT_SELF_IMPROVE);+ const [selfImproveAutoApprove, setSelfImproveAutoApprove] = useState(DEFAULT_SELF_IMPROVE_AUTO_APPROVE);// Per-field dirty flags. Until a field is edited its input shows a display// default we must NOT persist (that would clobber a higher saved setting on// the untouched gate). Tracked per-field so editing one gate never discards@@ -298,6 +324,8 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdateconst foundationGateEditedRef = useRef(false);const foundationThresholdEditedRef = useRef(false);const foundationRoundsEditedRef = useRef(false);+ const selfImproveEditedRef = useRef(false);+ const selfImproveApproveEditedRef = useRef(false);const [canon, setCanon] = useState(null);const [canonLoading, setCanonLoading] = useState(false);// Per-run provider/model override. '' = "use the series default", i.e. the@@ -385,6 +413,8 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdateif (!foundationGateEditedRef.current) setFoundationGate(typeof pec.foundationGate === 'boolean' ? pec.foundationGate : DEFAULT_FOUNDATION_GATE);if (!foundationThresholdEditedRef.current) setFoundationThreshold(Number.isFinite(pec.foundationThreshold) ? pec.foundationThreshold : DEFAULT_FOUNDATION_THRESHOLD);if (!foundationRoundsEditedRef.current) setFoundationRounds(Number.isInteger(pec.maxFoundationRounds) ? pec.maxFoundationRounds : DEFAULT_FOUNDATION_ROUNDS);+ if (!selfImproveEditedRef.current) setSelfImprove(typeof pec.selfImprove === 'boolean' ? pec.selfImprove : DEFAULT_SELF_IMPROVE);+ if (!selfImproveApproveEditedRef.current) setSelfImproveAutoApprove(typeof pec.selfImproveAutoApprove === 'boolean' ? pec.selfImproveAutoApprove : DEFAULT_SELF_IMPROVE_AUTO_APPROVE);// Persisted readiness gate — display-only, drives the "saved default" label.setSavedGate(READINESS_GATE_LABELS[pec.readinessGate] ? pec.readinessGate : '');})@@ -436,6 +466,23 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdatesetRevisionEnabled(v);persistRounds({ revisionEnabled: v });}, [persistRounds]);+ // Self-improvement: both are boolean checkboxes, so they persist immediately on+ // toggle (no blur) like notifyOnPause. Turning the diagnosis off also clears+ // auto-approve, so re-enabling it later can't silently resume auto-approving+ // PortOS code changes the user last consented to in a different context.+ const editSelfImprove = useCallback((v) => {+ selfImproveEditedRef.current = true;+ setSelfImprove(v);+ if (v) return void persistRounds({ selfImprove: true });+ selfImproveApproveEditedRef.current = true;+ setSelfImproveAutoApprove(false);+ persistRounds({ selfImprove: false, selfImproveAutoApprove: false });+ }, [persistRounds]);+ const editSelfImproveAutoApprove = useCallback((v) => {+ selfImproveApproveEditedRef.current = true;+ setSelfImproveAutoApprove(v);+ persistRounds({ selfImproveAutoApprove: v });+ }, [persistRounds]);const editRevisionMinCycles = useCallback((v) => { revisionMinEditedRef.current = true; setRevisionMinCycles(v); }, []);const editRevisionMaxCycles = useCallback((v) => { revisionMaxEditedRef.current = true; setRevisionMaxCycles(v); }, []);const editRevisionPlateauDelta = useCallback((v) => { revisionDeltaEditedRef.current = true; setRevisionPlateauDelta(v); }, []);@@ -508,6 +555,10 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdateelse if (latest.type === 'canceled') toast.success('Autopilot canceled');else if (latest.type === 'paused') toast.warning(`Autopilot paused — ${latest.reason || 'needs review'}`);else toast.error(latest.error || 'Autopilot failed');+ // The self-improvement verdict rides the terminal frame; announce a filed+ // PortOS fix separately so it isn't buried in the run's own outcome toast.+ const siLine = selfImproveLine(latest.selfImprove);+ if (siLine) toast(siLine);}, [active, latest, seriesId]);const start = useCallback(async () => {@@ -542,6 +593,9 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdateif (foundationGateEditedRef.current) roundOverrides.foundationGate = foundationGate;if (foundationThresholdEditedRef.current) roundOverrides.foundationThreshold = clampFoundationThreshold(foundationThreshold, DEFAULT_FOUNDATION_THRESHOLD);if (foundationRoundsEditedRef.current) roundOverrides.maxFoundationRounds = clampRound(foundationRounds, DEFAULT_FOUNDATION_ROUNDS);+ // Self-improvement toggles persist + override like the other booleans.+ if (selfImproveEditedRef.current) roundOverrides.selfImprove = selfImprove;+ if (selfImproveApproveEditedRef.current) roundOverrides.selfImproveAutoApprove = selfImproveAutoApprove;if (Object.keys(roundOverrides).length) await persistRounds(roundOverrides);// Per-run readiness-gate override (#1580): send it ONLY when the user picked a// specific gate. Unlike the round inputs we never persist it — '' leaves the@@ -575,7 +629,7 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate// effect can reject a stale terminal frame from the previous run.activeRunIdRef.current = res.runId || null;setActive(true);- }, [seriesId, includeVisual, fileGaps, arcRounds, editorialRounds, beatContinuityRounds, checkPauseThreshold, notifyOnPause, unlockForRun, revisionEnabled, revisionMinCycles, revisionMaxCycles, revisionPlateauDelta, foundationGate, foundationThreshold, foundationRounds, readinessGate, providerOverride, modelOverride, persistRounds]);+ }, [seriesId, includeVisual, fileGaps, arcRounds, editorialRounds, beatContinuityRounds, checkPauseThreshold, notifyOnPause, unlockForRun, revisionEnabled, revisionMinCycles, revisionMaxCycles, revisionPlateauDelta, foundationGate, foundationThreshold, foundationRounds, selfImprove, selfImproveAutoApprove, readinessGate, providerOverride, modelOverride, persistRounds]);const cancel = useCallback(async () => {await cancelPipelineAutopilot(seriesId).catch(() => null);@@ -849,6 +903,21 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate</p></>) : null}+ <label className="flex items-center gap-2 text-xs text-gray-300 pt-1 border-t border-port-border mt-1">+ <input type="checkbox" checked={selfImprove} onChange={(e) => editSelfImprove(e.target.checked)} />+ Improve the pipeline itself (diagnose PortOS when a run goes wrong)+ </label>+ {selfImprove ? (+ <>+ <label className="flex items-center gap-2 text-xs text-gray-300 pl-6">+ <input type="checkbox" checked={selfImproveAutoApprove} onChange={(e) => editSelfImproveAutoApprove(e.target.checked)} />+ Let CoS start the fix without asking me first+ </label>+ <p className="text-[11px] text-gray-500">+ When a run pauses, errors, or finishes with an editorial check that threw or a step that had to be retried, it spends one call asking whether the fault is the <em>story</em> or the <em>pipeline</em> — a missing editorial step earlier in the process, a stage prompt breaking its contract, a runner swallowing a failure. A pipeline verdict files a CoS task against PortOS itself, worktree-isolated and PR-opening{selfImproveAutoApprove ? '' : ', awaiting your approval'}. A healthy run never spends anything here. Saved as the default and reused on Resume.+ </p>+ </>+ ) : null}<p className="text-[11px] text-gray-500">Runs under the CoS auto-run autonomy domain. With it set to <em>dry-run</em>, this only previews the plan.</p>@@ -951,6 +1020,11 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate) : null}</div>{ap.lastError && ap.status !== 'done' ? <p className="text-[11px] text-gray-400 mt-1">{ap.lastError}</p> : null}+ {/* Pipeline self-improvement verdict for that run — the run's trouble+ was the automation, and a PortOS fix task exists for it. */}+ {selfImproveLine(ap.selfImprove) ? (+ <p className="text-[11px] text-port-accent mt-1">🔧 {selfImproveLine(ap.selfImprove)}</p>+ ) : null}<Findings items={ap.residualFindings} /></div>);diff --git a/client/src/components/pipeline/AutopilotPanel.test.jsx b/client/src/components/pipeline/AutopilotPanel.test.jsxindex eedeaa4a64..dd0ab2f01d 100644--- a/client/src/components/pipeline/AutopilotPanel.test.jsx+++ b/client/src/components/pipeline/AutopilotPanel.test.jsx@@ -14,7 +14,11 @@ vi.mock('../../services/api', () => ({getSettings: vi.fn(),patchSettingsSlice: vi.fn(),}));-vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn(), warning: vi.fn() } }));+// The default export is CALLABLE (a neutral toast) as well as carrying the+// typed helpers — the panel uses the bare call for the self-improvement line.+vi.mock('../ui/Toast', () => ({+ default: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn(), warning: vi.fn() }),+}));// Controllable SSE hook so tests don't touch EventSource. `sseLatest` lets a// test simulate a stale terminal frame left over from a previous run.let sseLatest = null;@@ -48,6 +52,8 @@ beforeEach(() => {sseLatest = null;sseFrames = [];getPipelineAutopilotStatus.mockResolvedValue({ autopilot: null, active: false });+ getPipelineSeries.mockResolvedValue(null);+ listPipelineIssues.mockResolvedValue([]);startPipelineAutopilot.mockResolvedValue({ runId: 'r1', mode: 'execute', alreadyRunning: false });getSettings.mockResolvedValue({ pipelineEditorialChecks: {} });patchSettingsSlice.mockResolvedValue({});@@ -470,6 +476,86 @@ describe('AutopilotPanel', () => {expect(screen.getByText(/finishing the active step/i)).toBeInTheDocument();});+ // Pipeline self-improvement — the opt-in that lets a run diagnose PortOS's own+ // automation and file a fix task against it.+ describe('pipeline self-improvement', () => {+ it('is off by default and hides auto-approve until it is enabled', async () => {+ renderPanel({ id: 's1', targetFormat: 'comic' });+ await waitFor(() => expect(getPipelineAutopilotStatus).toHaveBeenCalled());+ fireEvent.click(screen.getByRole('button', { name: /options/i }));+ const toggle = screen.getByLabelText(/improve the pipeline itself/i);+ expect(toggle).not.toBeChecked();+ expect(screen.queryByLabelText(/without asking me first/i)).not.toBeInTheDocument();+ fireEvent.click(toggle);+ expect(await screen.findByLabelText(/without asking me first/i)).toBeInTheDocument();+ await waitFor(() => expect(patchSettingsSlice).toHaveBeenCalledWith(+ 'pipelineEditorialChecks', { selfImprove: true }, { silent: true },+ ));+ });++ it('sends both toggles as per-run overrides once edited', async () => {+ renderPanel({ id: 's1', targetFormat: 'comic' });+ await waitFor(() => expect(getPipelineAutopilotStatus).toHaveBeenCalled());+ fireEvent.click(screen.getByRole('button', { name: /options/i }));+ fireEvent.click(screen.getByLabelText(/improve the pipeline itself/i));+ fireEvent.click(await screen.findByLabelText(/without asking me first/i));+ fireEvent.click(screen.getByRole('button', { name: /run autopilot/i }));+ await waitFor(() => expect(startPipelineAutopilot).toHaveBeenCalledWith(+ 's1',+ { includeVisual: true, fileGaps: false, selfImprove: true, selfImproveAutoApprove: true },+ { silent: true },+ ));+ });++ it('clears auto-approve when the diagnosis is turned back off', async () => {+ // Otherwise a later re-enable would silently resume auto-approving PortOS+ // code changes the user consented to in a different context.+ getSettings.mockResolvedValue({ pipelineEditorialChecks: { selfImprove: true, selfImproveAutoApprove: true } });+ renderPanel({ id: 's1', targetFormat: 'comic' });+ await waitFor(() => expect(getPipelineAutopilotStatus).toHaveBeenCalled());+ fireEvent.click(screen.getByRole('button', { name: /options/i }));+ await waitFor(() => expect(screen.getByLabelText(/without asking me first/i)).toBeChecked());+ fireEvent.click(screen.getByLabelText(/improve the pipeline itself/i));+ await waitFor(() => expect(patchSettingsSlice).toHaveBeenCalledWith(+ 'pipelineEditorialChecks', { selfImprove: false, selfImproveAutoApprove: false }, { silent: true },+ ));+ });++ it('announces a filed PortOS fix from the terminal frame', async () => {+ getPipelineAutopilotStatus.mockResolvedValue({ autopilot: { status: 'running', runId: 'r1' }, active: true });+ sseLatest = {+ type: 'paused', runId: 'r1', reason: 'editorial review ran out of rounds',+ selfImprove: { verdict: 'pipeline', area: 'editorial-check', title: 'Check pleasantries at beat altitude', filed: true, awaitingApproval: true },+ };+ renderPanel({ id: 's1', targetFormat: 'comic' });+ await waitFor(() => expect(toast).toHaveBeenCalledWith(+ expect.stringMatching(/Filed a PortOS fix task \(editorial-check\).*approve it in CoS/i),+ ));+ });++ it('shows the verdict on the persisted status banner', async () => {+ renderPanel({+ id: 's1',+ targetFormat: 'comic',+ autopilot: {+ status: 'paused', runId: 'r1', currentStep: 'editorialReview', lastError: 'ran out of rounds',+ selfImprove: { verdict: 'pipeline', area: 'runner', title: 'Retry budget is never applied', filed: true, awaitingApproval: false },+ },+ });+ expect(await screen.findByText(/Filed a PortOS fix task \(runner\).*CoS will pick it up/i)).toBeInTheDocument();+ });++ it('says nothing when the verdict was that the story, not the code, needs work', async () => {+ renderPanel({+ id: 's1',+ targetFormat: 'comic',+ autopilot: { status: 'paused', runId: 'r1', selfImprove: { verdict: 'content', filed: false } },+ });+ await waitFor(() => expect(getPipelineAutopilotStatus).toHaveBeenCalled());+ expect(screen.queryByText(/PortOS fix task/i)).not.toBeInTheDocument();+ });+ });+it('renders canon readiness gaps with a link to the issue Nouns page', async () => {getPipelineSeriesCanonReadiness.mockResolvedValue({ready: false,diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.jsonindex 9f1a0a20c4..35ec9f0b97 100644--- a/data.reference/prompts/stage-config.json+++ b/data.reference/prompts/stage-config.json@@ -499,6 +499,13 @@"returnsJson": true,"variables": []},+ "pipeline-self-improve": {+ "name": "Pipeline — Self-Improvement Diagnosis",+ "description": "Post-mortem on a Series Autopilot run that ended badly (or limped to done): reads the run's own telemetry — convergence rounds, checks that threw, retried child runners, skipped steps, the terminal reason — and decides whether the fault is the STORY (needs human editorial work) or the PIPELINE (PortOS is missing an earlier editorial step, a stage prompt breaks its output contract, a runner swallows a failure, a gate can't do its job). Returns a { verdict, confidence, area, title, problem, evidence, proposedChange, risks } JSON diagnosis; a `pipeline` verdict above the confidence bar files a worktree-isolated CoS task against PortOS itself. Opt-in per run — never fires on a healthy run.",+ "model": "heavy",+ "returnsJson": true,+ "variables": []+ },"pipeline-manuscript-completeness": {"name": "Pipeline — Manuscript Completeness","description": "Developmental editor pass over the ACTUAL drafted manuscript (comic script / prose / teleplay across all issues), not synopses. Surfaces what's missing to FINISH a near-complete draft: missing-content (beats/pages/scenes), arc-gap (themes/protagonist turns the draft doesn't yet deliver), character-gap (under-developed cast), pacing, and continuity. Returns categorized { severity, category, issueNumber, anchorQuote, location, problem, suggestion } findings — issueNumber + anchorQuote anchor each finding to a manuscript spot so the editor can jump to it; empty list means complete.",diff --git a/data.reference/prompts/stages/pipeline-self-improve.md b/data.reference/prompts/stages/pipeline-self-improve.mdnew file mode 100644index 0000000000..80000874c7--- /dev/null+++ b/data.reference/prompts/stages/pipeline-self-improve.md@@ -0,0 +1,99 @@+# Pipeline — Self-Improvement Diagnosis++You are a **systems engineer** doing a post-mortem on an automated content-production pipeline. A run of PortOS's Series Autopilot just ended. Your job is to decide whether the run's trouble came from the **story** (a manuscript that needs human editorial work — the pipeline behaved correctly) or from the **pipeline itself** (PortOS's own code, prompts, checks, or step ordering are defective or incomplete), and, if it's the pipeline, to say precisely what to change.++You are NOT reviewing the story. Do not comment on plot, prose, characters, or the quality of any manuscript. Do not repeat story content back. Your output is read by a coding agent that will change PortOS's source and open a public pull request, so it must describe **software**, not fiction.++## The pipeline++The autopilot resolves the first unmet step from the series' current state and dispatches it, in this order:++```+{{stepSequence}}+```++Editorial checks enabled for this run: {{enabledChecks}}++Effective gate configuration for this run:++```json+{{gateConfigJson}}+```++## The run++- **Series:** {{seriesName}} (target format: {{targetFormat}})+- **Outcome:** `{{outcome}}`+- **Reason:** {{outcomeReason}}+- **Editorial checks that threw:** {{erroredChecks}}+- **Issues with filed script-craft gaps:** {{craftGapIssues}}+- **Signal frames dropped past the retention cap:** {{droppedSignals}}++Signal-type counts:++```json+{{signalCountsJson}}+```++The run's retained telemetry frames, in order:++```json+{{signalsJson}}+```++## How to read the telemetry++- `verify:round` / `resolve:round` — a convergence loop iterating. Rounds whose `blocking` count doesn't fall (or rises) mean the auto-fix pass isn't fixing what the verify pass finds.+- `check:complete` with `error` — an editorial check **threw**. That dimension was never evaluated, so a "clean" verdict is not actually clean. This is nearly always a code defect.+- `child:retry` / `child:escalate` — a delegated child runner (volume beats, text stages) finished with its target stage still empty and had to be retried or escalated.+- `step:skip` — a step declined to run. The `reason` says whether that was a legitimate no-op or a swallowed failure.+- `gap:filed` — the run already filed a content-level task for something it couldn't resolve.+- `foundation:round` / `foundation:fix` — the pre-draft foundation judge scoring and attempting to improve the weakest dimension.+- `paused` / `error` — the terminal.++## What counts as a PIPELINE problem++Answer `pipeline` only when the evidence points at PortOS, not at the manuscript. The strongest cases:++1. **A missing step, at a nameable place in the order above.** The same class of defect keeps surfacing LATE (at the editorial checks, the health gate, or the script gate) when a cheaper earlier gate could have caught it — e.g. defects visible in beats being found only in full scripts. Say which existing step it belongs before or after.+2. **A step that runs but doesn't work.** A verify→resolve loop that never converges because the resolve pass doesn't address the findings the verify pass returns; an auto-fix that reports applied but changes nothing.+3. **A check or stage that errors.** A thrown check, an unparseable model response, a stage whose output contract the downstream step can't consume.+4. **A swallowed failure.** A step that marks work attempted and advances even though its output is empty or invalid, so the failure surfaces much later (or never).+5. **A gate configured so it cannot do its job.** A round bound of 0 on the gate whose findings are what stalled the run, a threshold that can never be met, a check that consumes an input nothing produces.++## What is NOT a pipeline problem++- The manuscript genuinely needs human editorial judgment and the run correctly paused for it → `content`.+- The run paused on residual findings after honestly trying its bounded rounds, and the findings differ each round because the story is genuinely unfinished → `content`.+- A one-off provider timeout or a transient network failure with no pattern behind it → `none`.+- Anything you would have to guess at because the telemetry doesn't show it → `none`, with low confidence. Do not invent a defect to have something to report.++## Output contract++Return ONLY valid JSON matching this shape — no prose, no markdown fence, no commentary.++```json+{+ "verdict": "pipeline",+ "confidence": 0.0,+ "area": "pipeline-step",+ "title": "string — imperative, one line, names the defect",+ "problem": "string — what is wrong in PortOS and how this run's telemetry shows it",+ "evidence": ["string — a specific frame or counter from the telemetry above"],+ "proposedChange": "string — the smallest change that fixes it, named concretely (which step, which check, which stage prompt, which gate)",+ "risks": "string — what could break, and what must keep working"+}+```++- `verdict` must be one of `pipeline` (PortOS is at fault), `content` (the manuscript needs human work), or `none` (nothing actionable).+- `confidence` is a number from 0 to 1. Be honest: a diagnosis below 0.6 is discarded, which is the correct outcome for a guess.+- `area` must be one of:+ - `editorial-check` — an editorial check is missing, wrong, or throwing+ - `pipeline-step` — a step in the order above is missing, misordered, or ineffective+ - `prompt` — a stage prompt produces output that doesn't meet its contract+ - `runner` — the orchestration/dispatch/retry code mishandles a result+ - `config` — a gate default or bound is set so the gate can't work+- `evidence` is at most 8 entries, each citing something actually present above. No entry may quote manuscript text.+- `proposedChange` must be actionable without access to this run: name the behavior to change, not "investigate the issue".++If the run's trouble was the story, or nothing actionable is visible, return the same shape with `verdict` set to `content` or `none` and empty strings for the change fields. Reporting nothing is a valid, useful answer — a fabricated defect costs an engineer a wasted pull request.diff --git a/scripts/migrations/235-pipeline-self-improve-stage.js b/scripts/migrations/235-pipeline-self-improve-stage.jsnew file mode 100644index 0000000000..a348e3efd2--- /dev/null+++ b/scripts/migrations/235-pipeline-self-improve-stage.js@@ -0,0 +1,18 @@+/**+ * Seed the Series Autopilot self-improvement diagnosis stage into existing installs.+ *+ * Mirrors `230-editorial-interiority-register-stage.js`: copies the `.md`+ * template from `data.reference/prompts/stages/` and merges its stage-config+ * entry into `data/prompts/stage-config.json`. Boot runs migrations+ * (server/index.js) but NOT `setup-data.js`, so an upgrade that pulls ++ * `pm2 restart`s (rather than running `update.sh`) would otherwise leave the+ * stage unseeded — and an autopilot run with self-improvement enabled would+ * throw "Stage not found" the first time it reached its post-mortem.+ *+ * Customization-safe + idempotent per `_seedStageHelpers.js` — the template is+ * copied only when missing and the config entry merged only when absent.+ */++import { makeSeedMigration } from './_seedStageHelpers.js';++export default makeSeedMigration('pipeline-self-improve');diff --git a/scripts/migrations/235-pipeline-self-improve-stage.test.js b/scripts/migrations/235-pipeline-self-improve-stage.test.jsnew file mode 100644index 0000000000..f1a5b5ee3d--- /dev/null+++ b/scripts/migrations/235-pipeline-self-improve-stage.test.js@@ -0,0 +1,17 @@+import { describe } from 'vitest';++import migration from './235-pipeline-self-improve-stage.js';+import { runSeedStageMigrationTests } from './_seedStageTestHelpers.js';++// The autopilot self-improvement post-mortem stage. The drift catch is the+// point: if the reference template or its stage-config entry ever stops+// shipping, a self-improvement-enabled run would throw "Stage not found" at its+// terminal — turning a merely-paused run into an errored one — with nothing+// failing here first.+describe('migration 235 — seed the pipeline self-improvement stage', () => {+ runSeedStageMigrationTests({+ migration,+ stages: ['pipeline-self-improve'],+ prefix: 'migration-235-',+ });+});diff --git a/server/lib/README.md b/server/lib/README.mdindex abc27f6bd3..714a6a9391 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -249,6 +249,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| Module | Purpose ||---|---|+| `appIdentity.js` | The baseline managed-app id (`PORTOS_APP_ID`) — importable without pulling in the `services/apps.js` graph (pm2, scheduler, settings) behind it. Re-exported by `apps.js`. || `appResolver.js` | Fuzzy-match a spoken/typed phrase to a managed app (`{ id, name }`). Tiered exact → prefix → substring, used by voice tools that target a specific app. || `capabilityMap.js` | Pure row builders for the Capability Map (per-integration status tiers + rollup); fed by `routes/capabilities.js`. || `chiptuneRender.js` | Deterministic chiptune score → mono PCM → 16-bit WAV buffer (pure Node, no audio deps); `renderScoreToPcm` / `pcmToWavBuffer` / `renderScoreToWav`. |diff --git a/server/lib/appIdentity.js b/server/lib/appIdentity.jsnew file mode 100644index 0000000000..6f7bfb2e31--- /dev/null+++ b/server/lib/appIdentity.js@@ -0,0 +1,14 @@+/**+ * The managed-apps registry's baseline identity — PortOS itself.+ *+ * Split out of `services/apps.js` so a module that only needs to SAY "this work+ * targets PortOS" (a CoS task's `metadata.app`, a scope check) doesn't have to+ * import the apps service — which drags in pm2, the task scheduler, streaming+ * detection and the settings graph behind it. `apps.js` re-exports the constant,+ * so every existing `import { PORTOS_APP_ID } from './apps.js'` is unchanged.+ *+ * Data only, no dependencies.+ */++/** Stable id of the baseline PortOS app — always present, never deletable. */+export const PORTOS_APP_ID = 'portos-default';diff --git a/server/lib/index.js b/server/lib/index.jsindex 6c6140caca..ed68360a3f 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -227,6 +227,7 @@ export * from './curatedGenomeMarkers.js';export * from './songCraftRef.js';// === Domain utilities ===+export * from './appIdentity.js';export * from './appResolver.js';export * from './capabilityMap.js';export * from './chiptuneRender.js';diff --git a/server/lib/pipelineValidation.js b/server/lib/pipelineValidation.jsindex 1916a425a1..c69566bb58 100644--- a/server/lib/pipelineValidation.js+++ b/server/lib/pipelineValidation.js@@ -261,6 +261,17 @@ export const pipelineEditorialChecksSettingsSchema = z.object({// and `seriesAutopilotScheduler` reads this slice — so a saved default would// arm lock-clearing for every scheduled run of every series. It is a per-run// option only (see seriesAutopilot/config.js#resolveAutopilotUnlockForRun).+ // Pipeline self-improvement. When on, a run that ends badly (or finishes with+ // unhealthy telemetry) spends ONE extra LLM call diagnosing whether the+ // AUTOMATION is at fault — a missing editorial step earlier in the pipeline, a+ // prompt producing unusable output, a runner swallowing a failure — and files+ // a CoS task against PortOS itself to fix it. Defaults OFF (opt-in): it is+ // fresh LLM spend AND it queues work that changes PortOS's own code.+ // `selfImproveAutoApprove` decides only whether that task waits for human+ // approval; the task is worktree-isolated and PR-opening either way. Both+ // optional + additive so older peers fall through to off.+ selfImprove: z.boolean().optional(),+ selfImproveAutoApprove: z.boolean().optional(),}).strict();// Cursor-context payload for the CD-bridge suggest route — identical shape todiff --git a/server/lib/promptStageCallSites.generated.json b/server/lib/promptStageCallSites.generated.jsonindex cf1be8d316..530a6e6d6a 100644--- a/server/lib/promptStageCallSites.generated.json+++ b/server/lib/promptStageCallSites.generated.json@@ -289,6 +289,9 @@"pipeline-season-episodes": ["server/services/pipeline/arcPlanner/episodeSeedPass.js"],+ "pipeline-self-improve": [+ "server/services/pipeline/seriesAutopilot/selfImprove.js"+ ],"pipeline-series-concept-judge": ["server/services/pipeline/seriesGenerate.js"],diff --git a/server/routes/pipeline/autopilot.js b/server/routes/pipeline/autopilot.jsindex 1f3c0c4f7d..80dc9d1437 100644--- a/server/routes/pipeline/autopilot.js+++ b/server/routes/pipeline/autopilot.js@@ -117,6 +117,15 @@ const autopilotStartSchema = z.object({revisionMinCycles: z.number().int().min(1).max(MAX_CONVERGENCE_ROUNDS).optional(),revisionMaxCycles: z.number().int().min(1).max(MAX_CONVERGENCE_ROUNDS).optional(),revisionPlateauDelta: z.number().min(0).max(10).optional(),+ // Pipeline self-improvement. When true, a run whose telemetry says the+ // AUTOMATION limped (a pause, a run-ending error, an editorial check that+ // threw, a retried child, a skipped step) spends one diagnosis call at its+ // terminal and, on a pipeline verdict, files a PortOS fix task.+ // `selfImproveAutoApprove` files that task auto-approved instead of awaiting+ // human approval. Both fall back to the persisted+ // pipelineEditorialChecks.selfImprove* setting, then off.+ selfImprove: z.boolean().optional(),+ selfImproveAutoApprove: z.boolean().optional(),});router.post('/series/:id/autopilot/start', asyncHandler(async (req, res) => {diff --git a/server/services/apps.js b/server/services/apps.jsindex c34a83ab00..d52b900fa7 100644--- a/server/services/apps.js+++ b/server/services/apps.js@@ -2,6 +2,7 @@ import { join } from 'path';import { v4 as uuidv4 } from '../lib/uuid.js';import EventEmitter from 'events';import { atomicWrite, ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';+import { PORTOS_APP_ID } from '../lib/appIdentity.js';import { NON_PM2_TYPES, usesPm2, isDesktopType } from './streamingDetect.js';import { listProcessesStrict } from './pm2.js';import { SELF_IMPROVEMENT_TASK_TYPES } from './taskSchedule.js';@@ -14,8 +15,11 @@ import { certPaths } from '../../lib/certPaths.js';const DATA_DIR = PATHS.data;const APPS_FILE = join(DATA_DIR, 'apps.json');-// Stable ID for the PortOS app — always present, never deletable-export const PORTOS_APP_ID = 'portos-default';+// Stable ID for the PortOS app — always present, never deletable. Defined in+// `lib/appIdentity.js` so a caller that only needs to name PortOS (a CoS task's+// target app, a scope check) can import it without this whole service graph;+// re-exported here so every existing importer is unchanged.+export { PORTOS_APP_ID };/*** Build the baseline PortOS app entry with repoPath resolved to the actual project root.diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.jsindex ee01a41fd9..7875903343 100644--- a/server/services/pipeline/series.js+++ b/server/services/pipeline/series.js@@ -174,6 +174,9 @@ export const sanitizeAutopilot = (raw) => {// health API. Null on any non-health pause. Same transient-marker rationale// as pauseKind / craftGap*: no schema-gate bump.healthBreakdown: sanitizeHealthBreakdown(raw.healthBreakdown),+ // Pipeline self-improvement verdict for the run that just ended (null unless+ // the run opted in and its telemetry warranted a diagnosis).+ selfImprove: sanitizeAutopilotSelfImprove(raw.selfImprove),updatedAt: isStr(raw.updatedAt) ? raw.updatedAt : null,};};@@ -204,6 +207,27 @@ const sanitizeHealthBreakdown = (raw) => {// older marker that predates the field reads as "no gaps", not undefined).const toCount = (v) => (Number.isInteger(v) && v >= 0 ? v : 0);+// Verdict of the opt-in pipeline self-improvement post-mortem, stamped onto the+// terminal marker so the resume/status banner can say a PortOS fix task was+// filed without re-reading the CoS task list. Null on every run that didn't opt+// in (or whose telemetry was clean — the pass makes no LLM call then). Same+// transient-marker rationale as pauseKind / craftGap*: no schema-gate bump.+const SELF_IMPROVE_MARKER_VERDICTS = ['pipeline', 'content', 'none', 'unreadable'];+const sanitizeAutopilotSelfImprove = (raw) => {+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;+ if (!SELF_IMPROVE_MARKER_VERDICTS.includes(raw.verdict)) return null;+ return {+ verdict: raw.verdict,+ confidence: Number.isFinite(raw.confidence) ? Math.min(1, Math.max(0, raw.confidence)) : null,+ area: trimTo(raw.area, 40) || null,+ title: trimTo(raw.title, 160) || null,+ taskId: trimTo(raw.taskId, 64) || null,+ filed: raw.filed === true,+ duplicate: raw.duplicate === true,+ awaitingApproval: raw.awaitingApproval === true,+ };+};+// Per-series editorial-check config overrides (#1591). Shape:// { [checkId]: { [configKey]: number|string|boolean } }// Each entry overrides the GLOBAL per-check config (settings.pipelineEditorialChecks)diff --git a/server/services/pipeline/seriesAutopilot.js b/server/services/pipeline/seriesAutopilot.jsindex 995c78878f..206f67017d 100644--- a/server/services/pipeline/seriesAutopilot.js+++ b/server/services/pipeline/seriesAutopilot.js@@ -77,6 +77,7 @@ export * from './seriesAutopilot/config.js';export * from './seriesAutopilot/convergence.js';export * from './seriesAutopilot/stepResolver.js';export * from './seriesAutopilot/session.js';+export * from './seriesAutopilot/selfImprove.js';export * from './seriesAutopilot/childRuns.js';export * from './seriesAutopilot/editorialSteps.js';export * from './seriesAutopilot/visualSteps.js';diff --git a/server/services/pipeline/seriesAutopilot.test.js b/server/services/pipeline/seriesAutopilot.test.jsindex 31304d26d7..629b2b34e8 100644--- a/server/services/pipeline/seriesAutopilot.test.js+++ b/server/services/pipeline/seriesAutopilot.test.js@@ -795,6 +795,30 @@ describe('resolveNextStep — unlock pre-pass ordering', () => {});});+describe('resolveAutopilotSelfImprove (config gate)', () => {+ const { resolveAutopilotSelfImprove } = autopilot;++ it('defaults both OFF', () => {+ expect(resolveAutopilotSelfImprove({}, null)).toEqual({ selfImprove: false, selfImproveAutoApprove: false });+ });+ it('per-run option wins over the persisted setting', () => {+ expect(resolveAutopilotSelfImprove(+ { selfImprove: true },+ { pipelineEditorialChecks: { selfImprove: false, selfImproveAutoApprove: true } },+ )).toEqual({ selfImprove: true, selfImproveAutoApprove: true });+ });+ it('falls back to the persisted setting when no per-run option', () => {+ expect(resolveAutopilotSelfImprove({}, { pipelineEditorialChecks: { selfImprove: true } }))+ .toEqual({ selfImprove: true, selfImproveAutoApprove: false });+ });+ it('resolves auto-approve independently of the diagnosis toggle', () => {+ // A saved auto-approve must not imply the diagnosis is on — otherwise a+ // stale setting would silently re-arm PortOS code changes.+ expect(resolveAutopilotSelfImprove({}, { pipelineEditorialChecks: { selfImproveAutoApprove: true } }))+ .toEqual({ selfImprove: false, selfImproveAutoApprove: true });+ });+});+// CWQE Phase 7 (#2171) — iterate-to-quality revision loop.describe('resolveAutopilotRevision (config gate, #2171)', () => {const {diff --git a/server/services/pipeline/seriesAutopilot/config.js b/server/services/pipeline/seriesAutopilot/config.jsindex b70c8ae484..a5f1c99e50 100644--- a/server/services/pipeline/seriesAutopilot/config.js+++ b/server/services/pipeline/seriesAutopilot/config.js@@ -204,6 +204,43 @@ export function resolveAutopilotRevision(options = {}, settings = null) {};}+// Pipeline self-improvement — let a run diagnose the AUTOMATION, not just the+// story. When a run ends badly (paused / errored) or finishes carrying unhealthy+// telemetry (an editorial check that threw, a delegated child that had to be+// retried, a convergence loop that never converged), the orchestrator can run+// ONE meta-diagnosis pass over the run's own signal log and, when the verdict is+// that PortOS itself is at fault (a missing editorial step earlier in the+// pipeline, a prompt that keeps producing unusable output, a runner that+// swallows a failure), file a CoS task against PortOS to fix it.+//+// Defaults OFF. It is a fresh burst of LLM spend AND it files work that changes+// PortOS's own code, so it must be an explicit opt-in — a run with clean+// telemetry never spends anything here even when enabled (see+// `shouldDiagnose`). Per-run option wins, then the persisted+// pipelineEditorialChecks setting, then the default.+//+// `selfImproveAutoApprove` decides what the filed task does next: OFF (default)+// files it awaiting approval, so the user reads the proposed change before an+// agent spends anything on it; ON files it auto-approved, so CoS picks it up and+// ships the fix on its own. Either way the task is worktree-isolated and opens a+// PR — an autonomous diagnosis never lands a commit on main unreviewed.+export const DEFAULT_SELF_IMPROVE = false;+export const DEFAULT_SELF_IMPROVE_AUTO_APPROVE = false;+export function resolveAutopilotSelfImprove(options = {}, settings = null) {+ const pec = settings?.pipelineEditorialChecks || {};+ const bool = (o, s, fallback) => {+ if (typeof o === 'boolean') return o;+ if (typeof s === 'boolean') return s;+ return fallback;+ };+ return {+ selfImprove: bool(options?.selfImprove, pec?.selfImprove, DEFAULT_SELF_IMPROVE),+ selfImproveAutoApprove: bool(+ options?.selfImproveAutoApprove, pec?.selfImproveAutoApprove, DEFAULT_SELF_IMPROVE_AUTO_APPROVE,+ ),+ };+}+// Which provider/model do this run's LLM calls use? An explicit per-run// `providerOverride`/`modelOverride` wins (the Options picker, or the scheduler// mapping a schedule's provider/model); otherwise the run inherits the series'diff --git a/server/services/pipeline/seriesAutopilot/orchestrator.js b/server/services/pipeline/seriesAutopilot/orchestrator.jsindex c0229f6f02..2897811986 100644--- a/server/services/pipeline/seriesAutopilot/orchestrator.js+++ b/server/services/pipeline/seriesAutopilot/orchestrator.js@@ -18,8 +18,9 @@ import {resolveAutopilotRounds, resolveAutopilotFoundationGate, resolveAutopilotFoundationThreshold,resolveAutopilotReadinessGate, resolveAutopilotCheckPauseThreshold, resolveAutopilotNotifyOnPause,resolveAutopilotProduceTeaser, resolveAutopilotRevision, resolveAutopilotLlm,- resolveAutopilotUnlockForRun,+ resolveAutopilotUnlockForRun, resolveAutopilotSelfImprove,} from './config.js';+import { runSelfImproveDiagnosis } from './selfImprove.js';import { VISUAL_DRAFT_ENABLED, summarizePlanCost } from './convergence.js';import { broadcast, broadcastStart, persistMarker, clearPauseNotice, notifyPause, fileGap, scheduleCleanup } from './session.js';import { resolveNextStep } from './stepResolver.js';@@ -72,6 +73,11 @@ export async function startSeriesAutopilot(sId, options = {}) {produceTeaser: resolveAutopilotProduceTeaser(options, settings),unlockForRun: resolveAutopilotUnlockForRun(options),...resolveAutopilotRevision(options, settings),+ // Pipeline self-improvement (opt-in): diagnose the AUTOMATION at the run's+ // terminal and file a PortOS fix task when the pipeline — not the story — is+ // what failed. Resolved here with the other gates so the signal tap in+ // `broadcast` sees the flag from the run's very first frame.+ ...resolveAutopilotSelfImprove(options, settings),// Run provider/model: per-run override → the series' own `series.llm` →// unset (stage pin / active provider downstream). Resolved ONCE here so the// manual run, a scheduled run and the UI's "this run calls X / Y" copy all@@ -103,6 +109,12 @@ export async function startSeriesAutopilot(sId, options = {}) {startedAt: new Date().toISOString(),mode,options: runOptions,+ // Diagnosable telemetry retained for the opt-in self-improvement pass —+ // appended by `broadcast` → `noteSignal`, bounded by MAX_SIGNALS (the+ // overflow is counted in `signalsDropped`, not stored). Empty on every run+ // that didn't opt in.+ signals: [],+ signalsDropped: 0,runState: {// Unlock-everything pre-pass (opt-in, see unlockPass.js) has run this// run. Boolean latch like arcVerified so the resolver routes there at@@ -161,6 +173,18 @@ export async function startSeriesAutopilot(sId, options = {}) {...extra,});+ // Post-mortem hook for the opt-in self-improvement pass. Best-effort by+ // contract: a diagnosis that throws must never turn a completed run into a+ // failed one, so every terminal calls it through this catch. Never fires on a+ // cancel (the user stopped it — there's no failure to explain) or a budget+ // pause (an exhausted budget is a spend fact, not an automation defect, and+ // there'd be no budget left to diagnose it with anyway).+ const selfImprove = (outcome, reason = null) => runSelfImproveDiagnosis(sId, record, { outcome, reason })+ .catch((err) => {+ console.log(`⚠️ autopilot: self-improve diagnosis failed for ${sId.slice(0, 12)}: ${err.message}`);+ return null;+ });+// 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 () => {@@ -217,8 +241,15 @@ export async function startSeriesAutopilot(sId, options = {}) {// failing checkIds on the frame so the UI flags it instead of "clean".const editorialCheckErroredIds = [...record.runState.editorialCheckErroredIds];const editorialCheckErrors = editorialCheckErroredIds.length;- await persistMarker(sId, { status: 'done', runId, currentStep: null, craftGapIssues, craftGapFindings, editorialCheckErrors });- broadcast(sId, { type: 'complete', runId, steps: ordinal, craftGapIssues, craftGapFindings, editorialCheckErrors, editorialCheckErroredIds, completedAt: new Date().toISOString() });+ // A "complete" run can still have limped (a check threw, a child was+ // retried, a step was skipped) — diagnose the automation BEFORE the+ // terminal frame so the verdict rides it. No-ops unless the run opted+ // in AND carries such a signal.+ const selfImproveResult = await selfImprove('done', craftGapIssues || editorialCheckErrors+ ? `completed with ${craftGapIssues} filed craft gap(s) and ${editorialCheckErrors} errored check(s)`+ : null);+ await persistMarker(sId, { status: 'done', runId, currentStep: null, craftGapIssues, craftGapFindings, editorialCheckErrors, selfImprove: selfImproveResult });+ broadcast(sId, { type: 'complete', runId, steps: ordinal, craftGapIssues, craftGapFindings, editorialCheckErrors, editorialCheckErroredIds, selfImprove: selfImproveResult, completedAt: new Date().toISOString() });console.log(`✅ autopilot complete — series=${sId.slice(0, 12)} steps=${ordinal}${craftGapIssues ? ` (${craftGapIssues} issue(s) with filed script-craft gaps)` : ''}${editorialCheckErrors ? ` (${editorialCheckErrors} editorial check(s) errored: ${editorialCheckErroredIds.join(', ')})` : ''}`);return;}@@ -275,8 +306,12 @@ export async function startSeriesAutopilot(sId, options = {}) {if (result?.canceled || record.cancelRequested) break;if (result?.pause) {- await persistMarker(sId, { status: 'paused', runId, currentStep: step.kind, residualFindings: result.residual || [], lastError: result.reason, pauseKind: result.pauseKind || null, healthBreakdown: result.healthBreakdown || null });- broadcast(sId, { type: 'paused', runId, scope: step.kind, reason: result.reason, residualFindings: result.residual || [], pauseKind: result.pauseKind || null, healthBreakdown: result.healthBreakdown || null, completedAt: new Date().toISOString() });+ // Diagnose the automation BEFORE the terminal frame so the verdict+ // rides it (a client tears its stream down on `paused`). No-ops unless+ // the run opted into self-improvement.+ const selfImproveResult = await selfImprove('paused', `${step.kind}: ${result.reason}`);+ await persistMarker(sId, { status: 'paused', runId, currentStep: step.kind, residualFindings: result.residual || [], lastError: result.reason, pauseKind: result.pauseKind || null, healthBreakdown: result.healthBreakdown || null, selfImprove: selfImproveResult });+ broadcast(sId, { type: 'paused', runId, scope: step.kind, reason: result.reason, residualFindings: result.residual || [], pauseKind: result.pauseKind || null, healthBreakdown: result.healthBreakdown || null, selfImprove: selfImproveResult, completedAt: new Date().toISOString() });await notifyPause(record, sId, { reason: result.reason, pauseKind: result.pauseKind || null, currentStep: step.kind });// Only file the generic stalled task when the step didn't already file// a more specific gap (canon-undescribed, visual-no-pages, …) — else@@ -303,8 +338,12 @@ export async function startSeriesAutopilot(sId, options = {}) {} catch (err) {const message = (err?.message || String(err)).slice(0, 1000);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() });+ // Same ordering as the other terminals: diagnose first so the verdict can+ // ride the `error` frame + marker rather than arriving after the client+ // has torn its stream down.+ const selfImproveResult = await selfImprove('error', message);+ await persistMarker(sId, { status: 'error', runId, lastError: message, selfImprove: selfImproveResult });+ broadcast(sId, { type: 'error', runId, error: message, selfImprove: selfImproveResult, failedAt: new Date().toISOString() });await fileGap(record, sId, {gapKind: 'run-error',summary: `The autonomous run failed and stopped: ${message}`,diff --git a/server/services/pipeline/seriesAutopilot/selfImprove.js b/server/services/pipeline/seriesAutopilot/selfImprove.jsnew file mode 100644index 0000000000..82550edfca--- /dev/null+++ b/server/services/pipeline/seriesAutopilot/selfImprove.js@@ -0,0 +1,362 @@+/**+ * Series Autopilot — pipeline self-improvement (opt-in meta-diagnosis).+ *+ * Every other gate in this conductor judges the STORY. This one judges the+ * AUTOMATION: when a run ends badly — or finishes carrying unhealthy telemetry —+ * it asks whether the failure is a content problem (the manuscript needs human+ * editorial work) or a PIPELINE problem (PortOS is missing an editorial step+ * earlier in the process, a stage prompt keeps producing unusable output, a+ * runner swallows a failure, a gate is misconfigured). On a pipeline verdict it+ * files a CoS task against PortOS itself so the automation gets fixed instead of+ * the same defect being re-diagnosed by hand on every series.+ *+ * Three properties keep this from becoming a spend/spam hazard:+ *+ * 1. **Opt-in, and signal-gated.** Off by default (`options.selfImprove`), and+ * even when on, a run with clean telemetry never makes an LLM call —+ * `shouldDiagnose` requires an actual bad signal (a pause, an error, a check+ * that threw, a retried child, a filed craft gap, a skipped step).+ * 2. **One call per run, budget-gated.** The diagnosis is a single staged LLM+ * call at the run's terminal, billed as one cos action and skipped when the+ * daily budget is spent.+ * 3. **Deduped + worktree-isolated.** The filed task's first line is stable per+ * `area`, so cosTaskStore's pending/in_progress dedup collapses the same+ * diagnosis across runs and series into one open task. The task always runs+ * in a worktree and opens a PR; `selfImproveAutoApprove` only decides whether+ * a human approves it first, never whether it can land unreviewed.+ *+ * The signal log is captured passively: `noteSignal` taps the same SSE frames+ * the run already broadcasts (`session.js#broadcast`), so a new telemetry frame+ * becomes diagnosable evidence with no extra instrumentation.+ *+ * PRIVACY: the diagnosis prompt asks for a defect report about PortOS's code and+ * prompts, explicitly NOT about the story — and `shapeDiagnosis` bounds every+ * field — because the filed task is read by a coding agent that opens a public+ * PR. Manuscript text must not travel into that task.+ */++import { PORTOS_APP_ID } from '../../../lib/appIdentity.js';+import * as cosTaskStore from '../../cosTaskStore.js';+import { getDomainBudgetStatus, recordDomainUsage } from '../../domainUsage.js';+import { PR_COMPLETIONS } from '../../../lib/prDisposition.js';+import { runStagedLLM } from '../../../lib/stageRunner.js';+import { getSettings } from '../../settings.js';+import { buildEditorialCheckPlan } from '../editorial/checkRunner.js';+import { getSeries } from '../series.js';+import { broadcast, providerOverrideOpts } from './session.js';++export const SELF_IMPROVE_STAGE = 'pipeline-self-improve';++// Frame types worth keeping as diagnosis evidence. Deliberately excludes the+// high-volume happy-path frames (`step:start` / `step:complete` / `start`) — the+// step SEQUENCE is reconstructable from the outcome, while these carry the+// "something went sideways" detail a diagnosis actually reasons over. The+// terminal frames (`paused` / `error` / `complete`) are excluded too: the+// diagnosis runs BEFORE them, and their content arrives as the `outcome` ++// `reason` arguments instead.+export const SIGNAL_FRAME_TYPES = Object.freeze(new Set([+ 'note', 'step:skip', 'verify:round', 'resolve:round', 'check:complete',+ 'foundation:round', 'foundation:fix', 'child:retry', 'child:escalate',+ 'revision:cycle', 'revision:converged', 'gap:filed',+]));++// Ceiling on the retained signal log. A long series run emits a `verify:round`+// per gate round and a `check:complete` per check per pass; past this the log is+// counted, not stored, so a runaway run can't grow the record unbounded (or+// blow the diagnosis prompt's context).+export const MAX_SIGNALS = 200;++// A `check:complete` frame is only evidence when the check misbehaved — a check+// that ran and reported findings is the system working. Without this filter a+// 40-check pass would flood the log with healthy frames and crowd out the+// failures that matter.+const isNoisyHealthyFrame = (payload) => payload?.type === 'check:complete'+ && !payload.error && !payload.skipped;++/**+ * Is this frame worth keeping as diagnosis evidence? Pure.+ */+export function isSignalFrame(payload) {+ if (!payload || typeof payload.type !== 'string') return false;+ if (!SIGNAL_FRAME_TYPES.has(payload.type)) return false;+ return !isNoisyHealthyFrame(payload);+}++/**+ * Record one broadcast frame onto the run's signal log. Called from `broadcast`+ * for EVERY frame, so it must stay cheap and total: it no-ops unless this run+ * opted into self-improvement and is actually executing (a dry-run has no+ * telemetry worth diagnosing). Returns true when the frame was retained.+ */+export function noteSignal(run, payload) {+ if (!run || run.options?.selfImprove !== true || run.mode !== 'execute') return false;+ if (!isSignalFrame(payload)) return false;+ if (!run.signals) run.signals = [];+ if (run.signals.length >= MAX_SIGNALS) {+ run.signalsDropped = (run.signalsDropped || 0) + 1;+ return false;+ }+ run.signals.push(payload);+ return true;+}++/**+ * Roll the retained log into the counts + entries the diagnosis prompt reads.+ * Pure over the run record.+ */+export function summarizeSignals(run) {+ const signals = run?.signals || [];+ const counts = {};+ for (const s of signals) counts[s.type] = (counts[s.type] || 0) + 1;+ return { signals, counts, dropped: run?.signalsDropped || 0 };+}++/**+ * Does this run carry evidence worth spending a diagnosis call on? Pure.+ *+ * `outcome` is the run's terminal disposition: 'done' | 'paused' | 'error'. A+ * cancel is never diagnosed — the user stopped it, so there is no failure to+ * explain. A pause or an error always is. A `done` run only qualifies when its+ * telemetry says the automation limped: a check threw, a child had to be+ * retried/escalated, a step was skipped, or the advisory craft gate filed gaps.+ */+export function shouldDiagnose(record, outcome) {+ if (!record || record.options?.selfImprove !== true || record.mode !== 'execute') return false;+ if (outcome === 'paused' || outcome === 'error') return true;+ if (outcome !== 'done') return false;+ const rs = record.runState || {};+ if (rs.editorialCheckErroredIds?.size > 0) return true;+ if (rs.scriptCraftGapIssues?.size > 0) return true;+ return (record.signals || []).some((s) => (+ s.type === 'child:retry' || s.type === 'child:escalate' || s.type === 'step:skip'+ || (s.type === 'check:complete' && s.error)+ ));+}++// The verdict vocabulary. `pipeline` is the only one that files anything;+// `content` means the manuscript (not the code) needs work, and `none` means the+// run's trouble was expected/benign.+export const SELF_IMPROVE_VERDICTS = Object.freeze(['pipeline', 'content', 'none']);++// Where in PortOS the proposed fix belongs. Doubles as the dedup key: the filed+// task's first line carries the area, so repeat diagnoses of the same area+// collapse onto one open task instead of one per run.+export const SELF_IMPROVE_AREAS = Object.freeze([+ 'editorial-check', 'pipeline-step', 'prompt', 'runner', 'config',+]);++// A diagnosis below this confidence is reported on the frame but never filed —+// a speculative "maybe the pipeline?" is not worth a coding agent's time.+export const SELF_IMPROVE_MIN_CONFIDENCE = 0.6;++const trimTo = (v, max) => (typeof v === 'string' ? v.trim().slice(0, max) : '');++/**+ * Sanitize the LLM's diagnosis into the fixed shape the rest of this module+ * relies on. Returns null when the payload can't be read as a verdict at all.+ * Pure.+ */+export function shapeDiagnosis(raw) {+ if (!raw || typeof raw !== 'object') return null;+ const verdict = SELF_IMPROVE_VERDICTS.includes(raw.verdict) ? raw.verdict : null;+ if (!verdict) return null;+ const confidence = Number.isFinite(raw.confidence)+ ? Math.min(1, Math.max(0, raw.confidence))+ : 0;+ return {+ verdict,+ confidence,+ area: SELF_IMPROVE_AREAS.includes(raw.area) ? raw.area : 'pipeline-step',+ title: trimTo(raw.title, 160),+ problem: trimTo(raw.problem, 2000),+ evidence: Array.isArray(raw.evidence)+ ? raw.evidence.map((e) => trimTo(e, 400)).filter(Boolean).slice(0, 8)+ : [],+ proposedChange: trimTo(raw.proposedChange, 2000),+ risks: trimTo(raw.risks, 800),+ };+}++/**+ * Should this shaped diagnosis produce a CoS task? Pure — a pipeline verdict+ * that clears the confidence bar and actually says what to change.+ */+export function isFilable(diagnosis) {+ return !!diagnosis+ && diagnosis.verdict === 'pipeline'+ && diagnosis.confidence >= SELF_IMPROVE_MIN_CONFIDENCE+ && !!diagnosis.title+ && !!diagnosis.proposedChange;+}++/**+ * Shape the CoS task for a filable diagnosis. Pure, so the dedup key and the+ * agent-facing brief are testable without a task store.+ *+ * The FIRST LINE is stable per area (cosTaskStore dedups on it, lowercased,+ * scoped to the app) — deliberately NOT per series, because the defect lives in+ * shared PortOS code and one open task should cover it however many series hit+ * it. The specifics live below the first line and in `context`.+ */+export function buildSelfImproveTask({ diagnosis, seriesId, seriesName, outcome, outcomeReason, counts, autoApprove }) {+ const lines = [+ `Pipeline self-improvement (${diagnosis.area}) — Series Autopilot diagnosed a PortOS automation defect`,+ '',+ `**${diagnosis.title}**`,+ '',+ diagnosis.problem,+ '',+ `Proposed change: ${diagnosis.proposedChange}`,+ ];+ if (diagnosis.risks) lines.push('', `Risks / things to be careful of: ${diagnosis.risks}`);+ lines.push(+ '',+ `Diagnosed from an autopilot run that ended \`${outcome}\`${outcomeReason ? ` — ${outcomeReason}` : ''}.`,+ 'Confirm the defect in the code before changing anything: this brief is one LLM\'s read of a single run\'s telemetry, not a reproduction.',+ );+ const context = JSON.stringify({+ source: 'series-autopilot-self-improve',+ seriesId,+ seriesName,+ outcome,+ outcomeReason: trimTo(outcomeReason, 500),+ area: diagnosis.area,+ confidence: diagnosis.confidence,+ evidence: diagnosis.evidence,+ signalCounts: counts,+ }).slice(0, 4000);+ return {+ description: lines.join('\n'),+ context,+ app: PORTOS_APP_ID,+ priority: 'MEDIUM',+ // Always isolated, always via a PR — an automated diagnosis never lands a+ // commit on main. `approvalRequired` (honored only for internal tasks) is+ // the one thing auto-approve changes.+ useWorktree: true,+ openPR: true,+ prCompletion: PR_COMPLETIONS.REVIEW_THEN_MERGE,+ simplify: true,+ approvalRequired: !autoApprove,+ };+}++// The conductor's step order, as prose the diagnosis prompt can reason over when+// asked "is a step missing, and where would it go?". Mirrors resolveNextStep's+// STEP comments — a step added there should gain a line here so the model isn't+// told to add something that already exists.+const STEP_SEQUENCE = [+ 'generateArc — draft the whole-series arc + volumes',+ 'generateEpisodes — break each volume into issues',+ 'verifyArc — cross-volume synopsis continuity verify → resolve loop',+ 'foundationGate — weighted judge of world/characters/arc before drafting',+ 'beatSheet — per-volume beat sheets',+ 'beatContinuity — whole-manuscript beat-level continuity loop',+ 'textStages — per-issue prose + scripts',+ 'scriptVerify — structural page/panel parse gate + advisory craft gate',+ 'editorialReview — series-level manuscript completeness review → fix loop',+ 'reverseOutline — refresh scene segmentation for the checks that consume it',+ 'editorialChecks — registry-driven editorial checks (deterministic + LLM)',+ 'editorialHealthGate — readiness gate over open blocking findings',+ 'revisionCycle — opt-in iterate-to-quality adversarial cut + judge loop',+ 'canonVerify — every drawn canon noun has a description',+ 'visualDraft — queue draft renders for covers + interior pages',+ 'produceTeaser — opt-in Creative Director teaser video',+].join('\n');++// The run's effective gate configuration, as the diagnosis context. Only the+// knobs that shape WHICH steps ran and how hard they tried — enough for the+// model to tell "this gate is off" from "this gate ran and failed".+const gateConfigOf = (options) => ({+ maxArcVerifyRounds: options.maxArcVerifyRounds,+ maxBeatContinuityRounds: options.maxBeatContinuityRounds,+ maxEditorialRounds: options.maxEditorialRounds,+ maxFoundationRounds: options.maxFoundationRounds,+ foundationGate: options.foundationGate,+ foundationThreshold: options.foundationThreshold,+ readinessGate: options.readinessGate,+ checkFindingsPauseThreshold: options.checkFindingsPauseThreshold,+ revisionEnabled: options.revisionEnabled,+ includeVisual: options.includeVisual,+ target: options.target,+});++/**+ * Run the meta-diagnosis at a run's terminal and file a PortOS task when the+ * verdict says the automation is at fault.+ *+ * Runs BEFORE the terminal frame is broadcast, and its summary rides that frame+ * (and the persisted marker) rather than arriving after it: a client tears its+ * stream down on the terminal frame and SSE replays only the LAST payload, so a+ * post-terminal frame would be both unseen live and destructive to the replayed+ * terminal. The `selfimprove:start` frame is the live signal that the run is+ * spending one more beat on its post-mortem.+ *+ * Best-effort by contract: callers `.catch()` it, and a skip is silent — the+ * point is that a successful run must never be turned into a failure by its own+ * post-mortem. Returns null when nothing was diagnosed, else a compact summary.+ */+export async function runSelfImproveDiagnosis(sId, record, { outcome, reason = null } = {}) {+ if (!shouldDiagnose(record, outcome)) return null;++ const budget = await getDomainBudgetStatus('cos');+ if (!budget.withinBudget) return null;++ const [series, settings] = await Promise.all([+ getSeries(sId).catch(() => null),+ getSettings().catch(() => null),+ ]);+ const checkPlan = await buildEditorialCheckPlan(sId, { settings }).catch(() => null);+ const { signals, counts, dropped } = summarizeSignals(record);++ broadcast(sId, { type: 'selfimprove:start', runId: record.runId, outcome, signals: signals.length });++ const { content } = await runStagedLLM(SELF_IMPROVE_STAGE, {+ seriesName: series?.name || 'unknown',+ targetFormat: series?.targetFormat || 'unknown',+ outcome,+ outcomeReason: trimTo(reason, 1000) || 'none',+ stepSequence: STEP_SEQUENCE,+ gateConfigJson: JSON.stringify(gateConfigOf(record.options || {}), null, 2),+ enabledChecks: (checkPlan?.checks || []).map((c) => `${c.id} (${c.kind})`).join(', ') || 'none',+ signalsJson: JSON.stringify(signals, null, 2).slice(0, 40_000),+ signalCountsJson: JSON.stringify(counts, null, 2),+ droppedSignals: dropped,+ erroredChecks: [...(record.runState?.editorialCheckErroredIds || [])].join(', ') || 'none',+ craftGapIssues: record.runState?.scriptCraftGapIssues?.size || 0,+ }, { ...providerOverrideOpts(record), returnsJson: true, source: SELF_IMPROVE_STAGE });+ await recordDomainUsage('cos', { actions: 1 });++ const diagnosis = shapeDiagnosis(content);+ if (!isFilable(diagnosis)) {+ return {+ verdict: diagnosis?.verdict || 'unreadable',+ confidence: diagnosis?.confidence ?? null,+ filed: false,+ };+ }++ const task = buildSelfImproveTask({+ diagnosis,+ seriesId: sId,+ seriesName: series?.name || null,+ outcome,+ outcomeReason: reason,+ counts,+ autoApprove: record.options?.selfImproveAutoApprove === true,+ });+ const result = await cosTaskStore.addTask(task, 'internal')+ .catch((err) => { console.log(`⚠️ autopilot: self-improve filing failed: ${err.message}`); return null; });+ const filed = !!result && !result.duplicate;+ console.log(`🔧 autopilot self-improve — series=${sId.slice(0, 12)} area=${diagnosis.area} ${result ? (filed ? `filed ${result.id}` : 'duplicate of an open task') : 'filing failed'}`);+ return {+ verdict: diagnosis.verdict,+ confidence: diagnosis.confidence,+ area: diagnosis.area,+ title: diagnosis.title,+ taskId: result?.id || null,+ filed,+ duplicate: !!result?.duplicate,+ awaitingApproval: task.approvalRequired,+ };+}diff --git a/server/services/pipeline/seriesAutopilot/selfImprove.test.js b/server/services/pipeline/seriesAutopilot/selfImprove.test.jsnew file mode 100644index 0000000000..393b026ede--- /dev/null+++ b/server/services/pipeline/seriesAutopilot/selfImprove.test.js@@ -0,0 +1,281 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { mockNoPeerSync, mockNoPeers } from '../../../lib/mockPathsDataRoot.js';++// selfImprove pulls the pipeline graph in transitively (session → autoRunner →+// …); stub the peer fan-out the way the other autopilot suites do so this stays+// hermetic. Postgres is never touched — nothing here loads a series.+vi.mock('../../instances.js', () => mockNoPeers());+vi.mock('../../sharing/peerSync.js', () => mockNoPeerSync());++const addTask = vi.fn(async (task) => ({ id: 'sys-1', ...task }));+vi.mock('../../cosTaskStore.js', () => ({ addTask: (...a) => addTask(...a) }));++let budgetStatus = { withinBudget: true, exceeded: null };+const recordDomainUsage = vi.fn(async () => {});+vi.mock('../../domainUsage.js', () => ({+ getDomainBudgetStatus: vi.fn(async () => budgetStatus),+ recordDomainUsage: (...a) => recordDomainUsage(...a),+}));++let llmContent = null;+const runStagedLLM = vi.fn(async () => ({ content: llmContent }));+vi.mock('../../../lib/stageRunner.js', () => ({ runStagedLLM: (...a) => runStagedLLM(...a) }));++vi.mock('../../settings.js', async (importOriginal) => ({+ ...(await importOriginal()),+ getSettings: vi.fn(async () => ({})),+}));+// Keep the REAL series module (the pipeline graph re-exports constants from it)+// and override only the reads this module makes.+vi.mock('../series.js', async (importOriginal) => ({+ ...(await importOriginal()),+ getSeries: vi.fn(async (id) => ({ id, name: 'Example Series', targetFormat: 'comic' })),+ updateSeries: vi.fn(async () => null),+}));+vi.mock('../editorial/checkRunner.js', () => ({+ buildEditorialCheckPlan: vi.fn(async () => ({ checks: [{ id: 'info-dumping', kind: 'llm' }] })),+}));++const {+ isSignalFrame, noteSignal, summarizeSignals, shouldDiagnose, shapeDiagnosis, isFilable,+ buildSelfImproveTask, runSelfImproveDiagnosis, MAX_SIGNALS, SELF_IMPROVE_MIN_CONFIDENCE,+} = await import('./selfImprove.js');+const { PORTOS_APP_ID } = await import('../../../lib/appIdentity.js');++// Minimal run record shaped like the orchestrator's, with the knobs each test needs.+const makeRun = (over = {}) => ({+ runId: 'run-1',+ mode: 'execute',+ options: { selfImprove: true, ...(over.options || {}) },+ signals: over.signals || [],+ signalsDropped: 0,+ runState: {+ editorialCheckErroredIds: new Set(),+ scriptCraftGapIssues: new Set(),+ ...(over.runState || {}),+ },+});++const goodDiagnosis = {+ verdict: 'pipeline',+ confidence: 0.9,+ area: 'editorial-check',+ title: 'Add a beat-level pleasantries check before the script stage',+ problem: 'Dialogue pleasantries are only caught after full scripts are generated.',+ evidence: ['verify:round scope=editorial round=2 blocking=7'],+ proposedChange: 'Run the dialogue-pleasantries check at the beat altitude, before textStages.',+ risks: 'Beat sheets are terser than scripts; the check may need a lower finding cap.',+};++beforeEach(() => {+ addTask.mockClear();+ recordDomainUsage.mockClear();+ runStagedLLM.mockClear();+ budgetStatus = { withinBudget: true, exceeded: null };+ llmContent = { ...goodDiagnosis };+});++describe('isSignalFrame', () => {+ it('keeps the frames that describe trouble', () => {+ expect(isSignalFrame({ type: 'child:retry' })).toBe(true);+ expect(isSignalFrame({ type: 'verify:round', blocking: 3 })).toBe(true);+ expect(isSignalFrame({ type: 'check:complete', checkId: 'c', error: 'boom' })).toBe(true);+ });++ it('drops the happy-path noise', () => {+ // A healthy check is the system working — retaining 40 of these per pass+ // would crowd the failures out of the bounded log.+ expect(isSignalFrame({ type: 'check:complete', checkId: 'c', count: 2 })).toBe(false);+ expect(isSignalFrame({ type: 'step:start', kind: 'textStages' })).toBe(false);+ expect(isSignalFrame({ type: 'step:complete', kind: 'textStages' })).toBe(false);+ // The terminals arrive as the outcome/reason arguments, not as signals.+ expect(isSignalFrame({ type: 'paused', reason: 'x' })).toBe(false);+ expect(isSignalFrame({ type: 'error', error: 'x' })).toBe(false);+ expect(isSignalFrame(null)).toBe(false);+ expect(isSignalFrame({})).toBe(false);+ });+});++describe('noteSignal', () => {+ it('no-ops on a run that did not opt in, and on a dry-run', () => {+ const optedOut = makeRun({ options: { selfImprove: false } });+ expect(noteSignal(optedOut, { type: 'child:retry' })).toBe(false);+ expect(optedOut.signals).toEqual([]);++ const dry = makeRun();+ dry.mode = 'dry-run';+ expect(noteSignal(dry, { type: 'child:retry' })).toBe(false);+ expect(dry.signals).toEqual([]);+ });++ it('retains frames up to the cap, then counts the overflow', () => {+ const run = makeRun();+ for (let i = 0; i < MAX_SIGNALS + 5; i += 1) noteSignal(run, { type: 'child:retry', i });+ expect(run.signals).toHaveLength(MAX_SIGNALS);+ expect(run.signalsDropped).toBe(5);+ expect(summarizeSignals(run)).toMatchObject({ counts: { 'child:retry': MAX_SIGNALS }, dropped: 5 });+ });+});++describe('shouldDiagnose', () => {+ it('always diagnoses a pause or an error', () => {+ expect(shouldDiagnose(makeRun(), 'paused')).toBe(true);+ expect(shouldDiagnose(makeRun(), 'error')).toBe(true);+ });++ it('never diagnoses a cancel, a dry-run, or an opted-out run', () => {+ expect(shouldDiagnose(makeRun(), 'canceled')).toBe(false);+ const dry = makeRun();+ dry.mode = 'dry-run';+ expect(shouldDiagnose(dry, 'paused')).toBe(false);+ expect(shouldDiagnose(makeRun({ options: { selfImprove: false } }), 'error')).toBe(false);+ });++ it('spends nothing on a clean `done` run', () => {+ expect(shouldDiagnose(makeRun(), 'done')).toBe(false);+ });++ it('diagnoses a `done` run that limped', () => {+ expect(shouldDiagnose(makeRun({ runState: { editorialCheckErroredIds: new Set(['x']) } }), 'done')).toBe(true);+ expect(shouldDiagnose(makeRun({ runState: { scriptCraftGapIssues: new Set(['i1']) } }), 'done')).toBe(true);+ expect(shouldDiagnose(makeRun({ signals: [{ type: 'child:retry' }] }), 'done')).toBe(true);+ expect(shouldDiagnose(makeRun({ signals: [{ type: 'step:skip', kind: 'scriptVerify' }] }), 'done')).toBe(true);+ // A retained frame that isn't itself a failure doesn't qualify.+ expect(shouldDiagnose(makeRun({ signals: [{ type: 'verify:round', blocking: 0 }] }), 'done')).toBe(false);+ });+});++describe('shapeDiagnosis', () => {+ it('bounds every field and defaults an unknown area', () => {+ const shaped = shapeDiagnosis({+ verdict: 'pipeline',+ confidence: 4,+ area: 'made-up',+ title: 'x'.repeat(500),+ evidence: Array.from({ length: 20 }, (_, i) => `e${i}`),+ proposedChange: 'do the thing',+ });+ expect(shaped.confidence).toBe(1);+ expect(shaped.area).toBe('pipeline-step');+ expect(shaped.title).toHaveLength(160);+ expect(shaped.evidence).toHaveLength(8);+ expect(shaped.problem).toBe('');+ });++ it('returns null when there is no readable verdict', () => {+ expect(shapeDiagnosis(null)).toBeNull();+ expect(shapeDiagnosis({ verdict: 'maybe' })).toBeNull();+ expect(shapeDiagnosis('nope')).toBeNull();+ });+});++describe('isFilable', () => {+ it('files only a confident pipeline verdict that says what to change', () => {+ expect(isFilable(shapeDiagnosis(goodDiagnosis))).toBe(true);+ expect(isFilable(shapeDiagnosis({ ...goodDiagnosis, verdict: 'content' }))).toBe(false);+ expect(isFilable(shapeDiagnosis({ ...goodDiagnosis, confidence: SELF_IMPROVE_MIN_CONFIDENCE - 0.01 }))).toBe(false);+ expect(isFilable(shapeDiagnosis({ ...goodDiagnosis, proposedChange: '' }))).toBe(false);+ expect(isFilable(shapeDiagnosis({ ...goodDiagnosis, title: '' }))).toBe(false);+ });+});++describe('buildSelfImproveTask', () => {+ const build = (over = {}) => buildSelfImproveTask({+ diagnosis: shapeDiagnosis(goodDiagnosis),+ seriesId: 'series-1',+ seriesName: 'Example Series',+ outcome: 'paused',+ outcomeReason: 'editorialReview: ran out of rounds',+ counts: { 'verify:round': 2 },+ autoApprove: false,+ ...over,+ });++ it('targets PortOS itself, worktree-isolated and PR-opening', () => {+ const task = build();+ expect(task.app).toBe(PORTOS_APP_ID);+ expect(task.useWorktree).toBe(true);+ expect(task.openPR).toBe(true);+ expect(task.prCompletion).toBe('review-then-merge');+ });++ it('keeps the dedup line stable per area, not per series', () => {+ const a = build();+ const b = build({ seriesId: 'series-2', seriesName: 'Another Series', outcome: 'error' });+ const firstLine = (t) => t.description.split('\n')[0];+ // The defect lives in shared PortOS code — one open task should cover it+ // however many series hit it, so cosTaskStore's first-line dedup must match.+ expect(firstLine(a)).toBe(firstLine(b));+ expect(firstLine(a)).toContain('editorial-check');+ // A different area is different work and must NOT collapse onto it.+ const other = build({ diagnosis: shapeDiagnosis({ ...goodDiagnosis, area: 'runner' }) });+ expect(firstLine(other)).not.toBe(firstLine(a));+ });++ it('gates on approval unless the user opted into auto-approve', () => {+ expect(build().approvalRequired).toBe(true);+ expect(build({ autoApprove: true }).approvalRequired).toBe(false);+ });++ it('carries the run provenance in context, not the manuscript', () => {+ const ctx = JSON.parse(build().context);+ expect(ctx).toMatchObject({ source: 'series-autopilot-self-improve', seriesId: 'series-1', outcome: 'paused', area: 'editorial-check' });+ expect(ctx.evidence).toEqual(goodDiagnosis.evidence);+ });+});++describe('runSelfImproveDiagnosis', () => {+ it('spends nothing when there is no signal to diagnose', async () => {+ const out = await runSelfImproveDiagnosis('series-1', makeRun(), { outcome: 'done' });+ expect(out).toBeNull();+ expect(runStagedLLM).not.toHaveBeenCalled();+ expect(addTask).not.toHaveBeenCalled();+ });++ it('spends nothing when the daily budget is exhausted', async () => {+ budgetStatus = { withinBudget: false, exceeded: 'actions' };+ const out = await runSelfImproveDiagnosis('series-1', makeRun(), { outcome: 'paused' });+ expect(out).toBeNull();+ expect(runStagedLLM).not.toHaveBeenCalled();+ });++ it('files a PortOS task on a confident pipeline verdict and bills one action', async () => {+ const run = makeRun({ signals: [{ type: 'verify:round', scope: 'editorial', round: 2, blocking: 7 }] });+ const out = await runSelfImproveDiagnosis('series-1', run, { outcome: 'paused', reason: 'editorialReview: ran out of rounds' });+ expect(runStagedLLM).toHaveBeenCalledWith('pipeline-self-improve', expect.any(Object), expect.objectContaining({ returnsJson: true }));+ expect(recordDomainUsage).toHaveBeenCalledWith('cos', { actions: 1 });+ expect(addTask).toHaveBeenCalledWith(expect.objectContaining({ app: PORTOS_APP_ID }), 'internal');+ expect(out).toMatchObject({ verdict: 'pipeline', area: 'editorial-check', filed: true, awaitingApproval: true, taskId: 'sys-1' });+ });++ it('files nothing on a content verdict but still reports it', async () => {+ llmContent = { ...goodDiagnosis, verdict: 'content' };+ const out = await runSelfImproveDiagnosis('series-1', makeRun(), { outcome: 'error', reason: 'boom' });+ expect(addTask).not.toHaveBeenCalled();+ expect(out).toMatchObject({ verdict: 'content', filed: false });+ });++ it('reports an unreadable response instead of throwing', async () => {+ llmContent = 'not json at all';+ const out = await runSelfImproveDiagnosis('series-1', makeRun(), { outcome: 'error', reason: 'boom' });+ expect(addTask).not.toHaveBeenCalled();+ expect(out).toMatchObject({ verdict: 'unreadable', filed: false });+ });++ it('reports a duplicate as tracked, not newly filed', async () => {+ addTask.mockResolvedValueOnce({ id: 'sys-earlier', duplicate: true });+ const out = await runSelfImproveDiagnosis('series-1', makeRun(), { outcome: 'paused', reason: 'x' });+ expect(out).toMatchObject({ filed: false, duplicate: true, taskId: 'sys-earlier' });+ });++ it('sends no manuscript content to the diagnosis stage', async () => {+ await runSelfImproveDiagnosis('series-1', makeRun({ signals: [{ type: 'child:escalate', kind: 'text' }] }), { outcome: 'paused', reason: 'x' });+ const [, vars] = runStagedLLM.mock.calls[0];+ // Only run telemetry + configuration — the prompt is a defect report about+ // PortOS, read by an agent that opens a public PR.+ expect(Object.keys(vars).sort()).toEqual([+ 'craftGapIssues', 'droppedSignals', 'enabledChecks', 'erroredChecks', 'gateConfigJson',+ 'outcome', 'outcomeReason', 'seriesName', 'signalCountsJson', 'signalsJson', 'stepSequence', 'targetFormat',+ ]);+ });+});diff --git a/server/services/pipeline/seriesAutopilot/session.js b/server/services/pipeline/seriesAutopilot/session.jsindex 66cd344bbd..f08ef4d2f0 100644--- a/server/services/pipeline/seriesAutopilot/session.js+++ b/server/services/pipeline/seriesAutopilot/session.js@@ -12,6 +12,7 @@ import { getSeries, updateSeries } from '../series.js';import * as volumeBeatsRunner from '../volumeBeatsRunner.js';import * as autoRunner from '../autoRunner.js';import { runs, autopilotEvents } from './state.js';+import { noteSignal } from './selfImprove.js';// ---------------------------------------------------------------------------// Run registry helpers (mirror editorialAnalysisRunner.js).@@ -60,6 +61,11 @@ export function broadcast(seriesId, payload) {const run = runs.get(seriesId);if (!run) return;broadcastSse(run, payload);+ // Retain the diagnosable frames for the opt-in self-improvement pass. A single+ // tap here (rather than instrumenting each step runner) means any telemetry+ // frame a future step emits is diagnosable evidence for free. No-op unless the+ // run opted in — see selfImprove.js#noteSignal.+ noteSignal(run, payload);// Mirror every frame onto the in-process bus (CDO Phase 3, #2185) so a// server-side consumer (CD plan step) sees the same progress/pause/terminal// frames as an SSE client. Emit is best-effort — a listener throw must never