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

feat: observing orchestrator mode for series autopilot — auto-dispatch pipeline fixes mid-run

[._.]/ Adam Eivy7b701a254be3
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 72294b1ef2..ba0d72521c 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 gains an observing orchestrator** — the continuous, self-dispatching sibling of *Improve the pipeline itself*. With the new *Observing orchestrator* toggle on, the run watches its own telemetry step by step: when a step's fresh signals say the automation misbehaved (a retried or escalated child runner, a skipped step, an editorial check that threw, a filed gap), it spends one bounded diagnosis call asking what in PortOS should change — a missing or misordered step, an ineffective verify→resolve loop, a broken check or stage prompt, a misconfigured gate, even a missing autopilot option — and **dispatches the fix immediately** as an auto-approved CoS task that works in a worktree, opens a PR, and merges through the review loop with no human gate, so a defect noticed at step 4 is being fixed while steps 5–16 still run. Enabling the toggle is the explicit consent for those unattended changes; the guards are structural: execute-mode only, every pass billed against and gated on the daily cos budget, at most three mid-run passes plus one terminal pass per run, a higher confidence bar than the approval-gated post-mortem (which it supersedes at the run's end), and repeat diagnoses collapsing onto one open task. Live progress frames show each observation and dispatch, and the run's status banner lists everything that was filed. Off by default; scheduled runs inherit whatever you saved.
+
- 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 waiting in your CoS approval queue, so an LLM's read of one run's telemetry never starts a coding agent on PortOS's own source by itself. 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 defect 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.
- Video Gen now offers Apple-local Wan 2.2 TI2V-5B plus validated 4-step A14B Lightning text- and image-to-video profiles through a pinned MLX-Gen runtime. Runtime tools/packages, immutable base snapshots, and exact Lightning adapters install only after an explicit UI action; existing installs receive an in-app repair/upgrade path, saved Hugging Face credentials are applied automatically, gated-source errors link back to the settings/access UI, and render/queue actions stay blocked until every required file is cached. The catalog identifies the A14B profiles as roughly 40 GiB downloads intended for 64+ GB Apple Silicon rather than understating their footprint. Wan-specific 4n+1 frame choices, FPS options, mode compatibility, process-tree cancellation, and locked Lightning sampler settings keep the UI aligned with the actual model contract.
diff --git a/client/src/components/pipeline/AutopilotPanel.jsx b/client/src/components/pipeline/AutopilotPanel.jsx
index 56f3c58508..dd17cd0a3c 100644
--- a/client/src/components/pipeline/AutopilotPanel.jsx
+++ b/client/src/components/pipeline/AutopilotPanel.jsx
@@ -54,6 +54,11 @@ const DEFAULT_FOUNDATION_ROUNDS = 3;
// that ends badly diagnoses whether PortOS's own automation is at fault and
// files a worktree-isolated, approval-gated CoS task against PortOS to fix it.
const DEFAULT_SELF_IMPROVE = false;
+// Observing orchestrator — mirror the server default (off). When on, the run
+// watches its own telemetry step by step and dispatches AUTO-APPROVED PortOS
+// fix tasks (worktree + PR + review loop + merge, no human gate) as pipeline
+// defects surface. Supersedes the selfImprove terminal diagnosis when both on.
+const DEFAULT_OBSERVER = 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) => {
@@ -177,6 +182,14 @@ const OPTION_SPECS = {
read: readBoolean,
persistOnEdit: true,
},
+ // Observing orchestrator — boolean, off by default. Persisted like selfImprove:
+ // a scheduled unattended run is exactly where the user wants the pipeline
+ // hardening itself.
+ observer: {
+ defaultValue: DEFAULT_OBSERVER,
+ read: readBoolean,
+ persistOnEdit: true,
+ },
};
// A single numeric field for the Options popover (round bounds + the pause
@@ -287,6 +300,11 @@ function frameLabel(f) {
// 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'})…`;
+ // Observing orchestrator — its passes ARE live (mid-run), so both frames show.
+ case 'observer:start': return `Orchestrator observing the pipeline (${f.signals} signal${f.signals === 1 ? '' : 's'})…`;
+ case 'observer:filed': return f.duplicate
+ ? `Orchestrator: pipeline fix already tracked (${f.area})`
+ : `Orchestrator dispatched a pipeline fix (${f.area})${f.title ? `: ${f.title}` : ''}`;
// #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}`;
@@ -317,6 +335,17 @@ function selfImproveLine(si) {
return `Filed a PortOS fix task (${si.area})${what} — approve it in CoS to start the work`;
}
+// One line for the observing orchestrator's run summary, shared by the run-ended
+// toast and the persisted-marker banner so the two can't drift. Null when the
+// observer dispatched nothing — there's nothing to say then.
+function observerLine(ob) {
+ const n = ob?.filed?.length || 0;
+ if (n === 0) return null;
+ const fresh = ob.filed.filter((f) => f.filed).length;
+ if (fresh === 0) return `Orchestrator: ${n} pipeline fix${n === 1 ? '' : 'es'} already tracked in CoS`;
+ return `Orchestrator dispatched ${fresh} pipeline fix${fresh === 1 ? '' : 'es'} — PRs will review and merge on their own`;
+}
+
function Findings({ items }) {
if (!items?.length) return null;
return (
@@ -549,6 +578,9 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
// PortOS fix separately so it isn't buried in the run's own outcome toast.
const siLine = selfImproveLine(latest.selfImprove);
if (siLine) toast(siLine);
+ // Same for the observing orchestrator's run summary.
+ const obLine = observerLine(latest.observer);
+ if (obLine) toast(obLine);
}, [active, latest, seriesId]);
const start = useCallback(async () => {
@@ -849,6 +881,15 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
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, PR-opening, and waiting in your CoS approval queue — it never starts on its own. A healthy run never spends anything here. Saved as the default and reused on Resume.
</p>
) : null}
+ <label className="flex items-center gap-2 text-xs text-gray-300 pt-1">
+ <input type="checkbox" checked={opt.observer} onChange={(e) => options.edit('observer', e.target.checked)} />
+ Observing orchestrator (auto-fix the pipeline as the run progresses)
+ </label>
+ {opt.observer ? (
+ <p className="text-[11px] text-gray-500">
+ An orchestrator watches the run step by step. When a step&apos;s telemetry says the automation misbehaved — a retried child, a skipped step, a check that threw, a filed gap — it diagnoses what in PortOS should change (step ordering, missing steps, editorial checks, prompts, gates, even missing options) and <strong>dispatches the fix immediately</strong>: an auto-approved CoS task that works in a worktree, opens a PR, and merges after the review loop with no approval step. Enabling this is your standing consent for those unattended changes. Bounded passes per run, budget-gated, higher confidence bar than the diagnosis above (which this supersedes at the run&apos;s end). Saved as the default and reused on Resume — including scheduled runs.
+ </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>
@@ -922,6 +963,7 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
const doneWithCheckErrors = ap.status === 'done' && !doneWithGaps && ap.editorialCheckErrors > 0;
const tone = ap.status === 'paused' || doneWithGaps || doneWithCheckErrors ? 'warning' : ap.status === 'error' ? 'error' : 'success';
const siLine = selfImproveLine(ap.selfImprove);
+ const obLine = observerLine(ap.observer);
return (
<div className={`px-3 pb-3 border-t pt-2 ${tone === 'warning' ? 'border-port-warning/30' : tone === 'error' ? 'border-port-error/30' : 'border-port-success/30'}`}>
<div className="flex items-center gap-2 text-xs">
@@ -956,6 +998,16 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
{/* Pipeline self-improvement verdict for that run — the run's trouble
was the automation, and a PortOS fix task exists for it. */}
{siLine ? <p className="text-[11px] text-port-accent mt-1">🔧 {siLine}</p> : null}
+ {/* Observing-orchestrator summary — fixes are already dispatched and
+ merging on their own; list what was filed. */}
+ {obLine ? (
+ <div className="mt-1">
+ <p className="text-[11px] text-port-accent">👁️ {obLine}</p>
+ {ap.observer.filed.map((f, i) => (
+ <p key={i} className="text-[11px] text-gray-500 ml-4">{f.area}{f.title ? ` — ${f.title}` : ''}</p>
+ ))}
+ </div>
+ ) : null}
<Findings items={ap.residualFindings} />
</div>
);
diff --git a/client/src/components/pipeline/AutopilotPanel.test.jsx b/client/src/components/pipeline/AutopilotPanel.test.jsx
index 9e54c27f12..da36791043 100644
--- a/client/src/components/pipeline/AutopilotPanel.test.jsx
+++ b/client/src/components/pipeline/AutopilotPanel.test.jsx
@@ -573,6 +573,70 @@ describe('AutopilotPanel', () => {
});
});
+ // Observing orchestrator — the opt-in that lets a run dispatch auto-approved
+ // pipeline fixes (PR + review loop + merge, no human gate) as it progresses.
+ describe('observing orchestrator', () => {
+ it('is off by default and persists the toggle on change', async () => {
+ renderPanel({ id: 's1', targetFormat: 'comic' });
+ await waitFor(() => expect(getPipelineAutopilotStatus).toHaveBeenCalled());
+ fireEvent.click(screen.getByRole('button', { name: /options/i }));
+ const toggle = screen.getByLabelText(/observing orchestrator/i);
+ expect(toggle).not.toBeChecked();
+ fireEvent.click(toggle);
+ await waitFor(() => expect(patchSettingsSlice).toHaveBeenCalledWith(
+ 'pipelineEditorialChecks', { observer: true }, { silent: true },
+ ));
+ // The explainer must say the quiet part out loud: fixes dispatch and
+ // merge without an approval step, and enabling this is the consent.
+ expect(await screen.findByText(/merges after the review loop with no approval step/i)).toBeInTheDocument();
+ });
+
+ it('sends the toggle as a per-run override 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(/observing orchestrator/i));
+ fireEvent.click(screen.getByRole('button', { name: /run autopilot/i }));
+ await waitFor(() => expect(startPipelineAutopilot).toHaveBeenCalledWith(
+ 's1',
+ { includeVisual: true, fileGaps: false, observer: true },
+ { silent: true },
+ ));
+ });
+
+ it('renders a live observer:filed frame with the dispatched fix', async () => {
+ getPipelineAutopilotStatus.mockResolvedValue({ autopilot: { status: 'running' }, active: true });
+ sseLatest = { type: 'observer:filed', runId: 'r1', area: 'editorial-check', title: 'Check pleasantries at beat altitude', filed: true };
+ renderPanel({ id: 's1', targetFormat: 'comic' });
+ expect(await screen.findByText(/Orchestrator dispatched a pipeline fix \(editorial-check\): Check pleasantries at beat altitude/i)).toBeInTheDocument();
+ });
+
+ it('announces the dispatched fixes 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',
+ observer: { passes: 2, filed: [{ area: 'runner', title: 'Retry budget is never applied', taskId: 't1', filed: true }] },
+ };
+ renderPanel({ id: 's1', targetFormat: 'comic' });
+ await waitFor(() => expect(toast).toHaveBeenCalledWith(
+ expect.stringMatching(/Orchestrator dispatched 1 pipeline fix.*review and merge on their own/i),
+ ));
+ });
+
+ it('lists the dispatched fixes on the persisted status banner', async () => {
+ renderPanel({
+ id: 's1',
+ targetFormat: 'comic',
+ autopilot: {
+ status: 'done', runId: 'r1',
+ observer: { passes: 1, filed: [{ area: 'pipeline-step', title: 'Verify beats before drafting text', taskId: 't1', filed: true }] },
+ },
+ });
+ expect(await screen.findByText(/Orchestrator dispatched 1 pipeline fix/i)).toBeInTheDocument();
+ expect(screen.getByText(/pipeline-step — Verify beats before drafting text/i)).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.json
index 35ec9f0b97..66ec82867b 100644
--- a/data.reference/prompts/stage-config.json
+++ b/data.reference/prompts/stage-config.json
@@ -506,6 +506,13 @@
"returnsJson": true,
"variables": []
},
+ "pipeline-observer": {
+ "name": "Pipeline — Observing Orchestrator",
+ "description": "In-flight observer for a Series Autopilot run (the continuous, self-dispatching sibling of the self-improve post-mortem): after a step whose fresh telemetry says the automation misbehaved — a retried/escalated child, a skipped step, an editorial check that threw, a filed gap — it reads the run's signal window and decides whether the fault is the STORY or the PIPELINE (a missing/misordered step, an ineffective loop, a broken check or prompt, a misconfigured gate, a missing option). Returns the same { verdict, confidence, area, title, problem, evidence, proposedChange, risks } JSON diagnosis at a HIGHER confidence bar: a `pipeline` verdict dispatches an AUTO-APPROVED, worktree-isolated CoS task that PRs and merges through the review loop without a human gate. Opt-in per run; bounded passes; never fires on a clean step.",
+ "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-observer.md b/data.reference/prompts/stages/pipeline-observer.md
new file mode 100644
index 0000000000..463d35ca45
--- /dev/null
+++ b/data.reference/prompts/stages/pipeline-observer.md
@@ -0,0 +1,111 @@
+# Pipeline — Observing Orchestrator
+
+You are a **systems engineer** riding along with an automated content-production pipeline while it runs. PortOS's Series Autopilot is mid-flight (or just ended), and its recent telemetry says something may have gone sideways. Your job is to decide whether that 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, gates, step ordering, or missing capabilities), and, if it's the pipeline, to say precisely what to change.
+
+**Your diagnosis dispatches a coding agent immediately.** Unlike a post-mortem read by a human, a `pipeline` verdict here files an auto-approved task: an agent will confirm the defect in the source, change PortOS, open a public pull request, and merge it after the review loop — with no human in between. Be exactly as confident as the evidence allows. A fabricated or speculative defect wastes an autonomous engineering run and can land a wrong change; `none` with low confidence is the correct answer for a guess.
+
+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 describes **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 observation window
+
+- **Series:** {{seriesName}} (target format: {{targetFormat}})
+- **Where you are:** {{phase}}
+- **Run outcome so far:** `{{outcome}}`
+- **Reason:** {{outcomeReason}}
+- **Editorial checks that threw:** {{erroredChecks}}
+- **Issues with filed script-craft gaps:** {{craftGapIssues}}
+- **Signal frames dropped past the retention cap:** {{droppedSignals}}
+
+Fixes this run has ALREADY dispatched (do not re-file these — propose the next most valuable change, or report `none` if nothing new is evidenced):
+
+```
+{{priorFilings}}
+```
+
+Signal-type counts for the whole run so far:
+
+```json
+{{signalCountsJson}}
+```
+
+The telemetry frames in this observation window, 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.
+
+## What counts as a PIPELINE problem
+
+Answer `pipeline` only when the evidence points at PortOS, not at the manuscript. Anything about the automation is in scope — the goal is that an unattended run produces a complete, high-quality series without wasting spend on late-stage rework, so favor changes that build the missing foundation EARLIER in the order:
+
+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 misordered step.** Work is generated before the foundation it depends on is verified, so downstream steps redo or discard it.
+3. **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.
+4. **A check or stage that errors, or a check that's missing.** A thrown check, an unparseable model response, a stage whose output contract the downstream step can't consume — or a recurring editorial weakness no enabled check looks for at all.
+5. **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).
+6. **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.
+7. **A missing control.** The run needed a knob that doesn't exist — a per-run option, a threshold, a UI affordance on the autopilot panel — and its absence is what forced a pause or wasted spend (`area: "ui"` or `"config"`).
+
+## 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`.
+- A defect this run has already dispatched a fix for (see the list above) → `none`, unless you are proposing a genuinely different change.
+- 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, which option)",
+ "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.7 is discarded, which is the correct outcome for a guess — the bar is higher here than in a human-reviewed post-mortem because no one reads this before an agent acts on it.
+- `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
+ - `ui` — a missing autopilot option/affordance is what forced the pause or waste
+- `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 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 here costs an unattended engineering run and risks a wrong merge.
diff --git a/scripts/migrations/237-pipeline-observer-stage.js b/scripts/migrations/237-pipeline-observer-stage.js
new file mode 100644
index 0000000000..7307c3bb03
--- /dev/null
+++ b/scripts/migrations/237-pipeline-observer-stage.js
@@ -0,0 +1,19 @@
+/**
+ * Seed the Series Autopilot observing-orchestrator diagnosis stage into
+ * existing installs.
+ *
+ * Mirrors `235-pipeline-self-improve-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 would
+ * otherwise leave the stage unseeded — and an autopilot run with the observer
+ * enabled would throw "Stage not found" the first time a step's telemetry
+ * triggered a pass.
+ *
+ * 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-observer');
diff --git a/scripts/migrations/237-pipeline-observer-stage.test.js b/scripts/migrations/237-pipeline-observer-stage.test.js
new file mode 100644
index 0000000000..f4478c2149
--- /dev/null
+++ b/scripts/migrations/237-pipeline-observer-stage.test.js
@@ -0,0 +1,16 @@
+import { describe } from 'vitest';
+
+import migration from './237-pipeline-observer-stage.js';
+import { runSeedStageMigrationTests } from './_seedStageTestHelpers.js';
+
+// The autopilot observing-orchestrator stage. The drift catch is the point: if
+// the reference template or its stage-config entry ever stops shipping, an
+// observer-enabled run would throw "Stage not found" the first time a step's
+// telemetry triggered a pass — with nothing failing here first.
+describe('migration 237 — seed the pipeline observing-orchestrator stage', () => {
+ runSeedStageMigrationTests({
+ migration,
+ stages: ['pipeline-observer'],
+ prefix: 'migration-237-',
+ });
+});
diff --git a/server/lib/pipelineValidation.js b/server/lib/pipelineValidation.js
index c90aa2e88e..abfc48f0a8 100644
--- a/server/lib/pipelineValidation.js
+++ b/server/lib/pipelineValidation.js
@@ -273,6 +273,19 @@ export const pipelineEditorialChecksSettingsSchema = z.object({
// code-editing task in PortOS. Optional + additive so older peers fall
// through to off.
selfImprove: z.boolean().optional(),
+ // Observing orchestrator — the continuous, self-dispatching sibling of
+ // selfImprove. When on, an autopilot run watches its own telemetry step by
+ // step and dispatches AUTO-APPROVED PortOS fix tasks (worktree + PR + review
+ // loop + merge, no human gate) as pipeline defects surface, so unattended
+ // runs continuously harden the pipeline itself. Defaults OFF (opt-in): it is
+ // fresh LLM spend AND standing consent for unattended changes to PortOS's own
+ // code — enabling it is that consent (see seriesAutopilot/observer.js for the
+ // structural guards: execute-mode only, budget-gated, pass-capped, raised
+ // confidence bar, full PR review loop). Persistable deliberately, unlike
+ // unlockForRun: a scheduled unattended run is exactly where the user wants
+ // the pipeline improving itself. Optional + additive so older peers fall
+ // through to off.
+ observer: z.boolean().optional(),
}).strict();
// Cursor-context payload for the CD-bridge suggest route — identical shape to
diff --git a/server/lib/promptStageCallSites.generated.json b/server/lib/promptStageCallSites.generated.json
index 530a6e6d6a..2ce1f6fcb7 100644
--- a/server/lib/promptStageCallSites.generated.json
+++ b/server/lib/promptStageCallSites.generated.json
@@ -258,6 +258,9 @@
"pipeline-manuscript-fix": [
"server/services/pipeline/manuscriptFix.js"
],
+ "pipeline-observer": [
+ "server/services/pipeline/seriesAutopilot/observer.js"
+ ],
"pipeline-panel-editor": [
"server/services/pipeline/readerPanel.js"
],
diff --git a/server/routes/pipeline/autopilot.js b/server/routes/pipeline/autopilot.js
index 056d9b1dba..83dc6d8b4f 100644
--- a/server/routes/pipeline/autopilot.js
+++ b/server/routes/pipeline/autopilot.js
@@ -131,6 +131,14 @@ const autopilotStartSchema = z.object({
// That task always awaits human approval. Falls back to the persisted
// pipelineEditorialChecks.selfImprove setting, then off.
selfImprove: z.boolean().optional(),
+ // Observing orchestrator. When true, the run watches its own telemetry step
+ // by step and, when a step's fresh signals say the automation misbehaved,
+ // spends a bounded diagnosis call and dispatches an AUTO-APPROVED PortOS fix
+ // task — worktree-isolated, PR-opening, review-loop-then-merge, no human
+ // gate (the explicit opt-in IS the consent; see seriesAutopilot/observer.js).
+ // Supersedes the selfImprove terminal diagnosis when both are on. Falls back
+ // to the persisted pipelineEditorialChecks.observer setting, then off.
+ observer: z.boolean().optional(),
});
router.post('/series/:id/autopilot/start', asyncHandler(async (req, res) => {
diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.js
index fbc0365fb2..8d36f688fe 100644
--- a/server/services/pipeline/series.js
+++ b/server/services/pipeline/series.js
@@ -177,6 +177,9 @@ export const sanitizeAutopilot = (raw) => {
// 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),
+ // Observing-orchestrator activity for the run that just ended (null unless
+ // the run opted in and the observer dispatched at least one fix task).
+ observer: sanitizeAutopilotObserver(raw.observer),
updatedAt: isStr(raw.updatedAt) ? raw.updatedAt : null,
};
};
@@ -227,6 +230,31 @@ const sanitizeAutopilotSelfImprove = (raw) => {
};
};
+// Observing-orchestrator summary for the run that just ended: how many passes
+// it spent and which fix tasks it dispatched, so the status banner can report
+// "the pipeline is being fixed" without re-reading the CoS task list. The
+// producer (observer.js#summarizeObserver) only reports when at least one task
+// was filed, so an empty list reads as null. Same transient-marker rationale as
+// pauseKind / craftGap* / selfImprove: no schema-gate bump.
+const AUTOPILOT_OBSERVER_MAX_FILED = 5;
+const sanitizeAutopilotObserver = (raw) => {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
+ const filed = (Array.isArray(raw.filed) ? raw.filed : [])
+ .map((f) => (f && typeof f === 'object'
+ ? {
+ area: trimTo(f.area, 40) || null,
+ title: trimTo(f.title, 160) || null,
+ taskId: trimTo(f.taskId, 64) || null,
+ filed: f.filed === true,
+ duplicate: f.duplicate === true,
+ }
+ : null))
+ .filter(Boolean)
+ .slice(0, AUTOPILOT_OBSERVER_MAX_FILED);
+ if (filed.length === 0) return null;
+ return { passes: toCount(raw.passes), filed };
+};
+
// 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.js
index 206f67017d..9c01af2600 100644
--- a/server/services/pipeline/seriesAutopilot.js
+++ b/server/services/pipeline/seriesAutopilot.js
@@ -78,6 +78,7 @@ export * from './seriesAutopilot/convergence.js';
export * from './seriesAutopilot/stepResolver.js';
export * from './seriesAutopilot/session.js';
export * from './seriesAutopilot/selfImprove.js';
+export * from './seriesAutopilot/observer.js';
export * from './seriesAutopilot/childRuns.js';
export * from './seriesAutopilot/editorialSteps.js';
export * from './seriesAutopilot/visualSteps.js';
diff --git a/server/services/pipeline/seriesAutopilot/config.js b/server/services/pipeline/seriesAutopilot/config.js
index 7bd3749307..7b91cc030d 100644
--- a/server/services/pipeline/seriesAutopilot/config.js
+++ b/server/services/pipeline/seriesAutopilot/config.js
@@ -227,6 +227,24 @@ export function resolveAutopilotSelfImprove(options = {}, settings = null) {
return pickBool(options?.selfImprove, pec?.selfImprove, DEFAULT_SELF_IMPROVE);
}
+// Observing orchestrator — the continuous, self-dispatching sibling of the
+// self-improve post-mortem (see observer.js's header for the full contract).
+// When on, the run watches its own telemetry as it progresses; a step whose
+// fresh signals say the automation misbehaved spends a diagnosis call, and a
+// confident pipeline verdict files an AUTO-APPROVED CoS task that PRs and
+// merges without a human gate. Defaults OFF and must stay an explicit opt-in:
+// it is both fresh LLM spend and standing consent for unattended changes to
+// PortOS's own code. Per-run option wins, then the persisted
+// pipelineEditorialChecks setting, then the default — persistable like
+// selfImprove (a scheduled unattended run is exactly where the user wants the
+// pipeline hardening itself), unlike unlockForRun (which rewrites user-set
+// protection state and stays per-run only).
+export const DEFAULT_OBSERVER = false;
+export function resolveAutopilotObserver(options = {}, settings = null) {
+ const pec = settings?.pipelineEditorialChecks || {};
+ return pickBool(options?.observer, pec?.observer, DEFAULT_OBSERVER);
+}
+
// 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/observer.js b/server/services/pipeline/seriesAutopilot/observer.js
new file mode 100644
index 0000000000..cbf899850f
--- /dev/null
+++ b/server/services/pipeline/seriesAutopilot/observer.js
@@ -0,0 +1,272 @@
+/**
+ * Series Autopilot — observing orchestrator (opt-in, continuous pipeline
+ * improvement).
+ *
+ * The sibling of `selfImprove.js` with a stronger contract. Self-improve is a
+ * ONE-shot post-mortem whose filed task waits in the human approval queue; the
+ * observer WATCHES the run as it progresses — after each step whose fresh
+ * telemetry says the automation misbehaved (a retried child, a skipped step, an
+ * editorial check that threw, a filed gap) it spends one diagnosis call asking
+ * what in PortOS should change, and files that change as an AUTO-APPROVED CoS
+ * task: worktree-isolated, PR-opening, review-loop-then-merge, no human gate.
+ * The goal is that an unattended autopilot run continuously hardens its own
+ * pipeline — a defect noticed at step 4 is being fixed while steps 5–16 run —
+ * instead of every run re-hitting the same weakness until someone reads the
+ * post-mortems. Its mandate is deliberately broad: step ordering, missing
+ * steps, editorial checks, stage prompts, gates/config, even missing UI
+ * options are all in scope (see the `pipeline-observer` stage prompt).
+ *
+ * Why auto-approval is acceptable HERE when every other autonomously generated
+ * code-editing task in PortOS hard-codes `approvalRequired: true`: this option
+ * is the user explicitly opting into unattended pipeline self-repair — the
+ * checkbox copy says the filed work PRs and merges on its own. The remaining
+ * guards are structural, not procedural: the cos autonomy domain must be
+ * `execute`, every pass is billed against and gated on the daily cos budget,
+ * the run caps its passes (OBSERVER_MAX_MIDRUN_PASSES + one terminal), the
+ * confidence bar is HIGHER than self-improve's (no human reads the brief before
+ * an agent acts on it), the agent works in a worktree and lands through the
+ * full PR review loop, and cosTaskStore's first-line dedup collapses repeat
+ * diagnoses across steps, runs and series onto one open task.
+ *
+ * When both options are enabled the observer SUPERSEDES the self-improve
+ * terminal diagnosis (see orchestrator.js#postMortem) — same evidence, stronger
+ * action policy; running both would double-bill one run's telemetry and file
+ * near-duplicate tasks under different dedup keys.
+ *
+ * PRIVACY: identical contract to selfImprove.js — the prompt asks for a defect
+ * report about PortOS's code, never the story, and every shaped field is
+ * bounded, 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 { trimToClause } from '../../../lib/storyBible.js';
+import { slugify } from '../../../lib/planIds.js';
+import { getSettings } from '../../settings.js';
+import { buildEditorialCheckPlan } from '../editorial/checkRunner.js';
+import { getSeries } from '../series.js';
+import { summarizeSignals } from './state.js';
+import { broadcast, providerOverrideOpts } from './session.js';
+import { STEP_SEQUENCE, gateConfigOf, hasAutomationSignals, shapeDiagnosis } from './selfImprove.js';
+
+const OBSERVER_STAGE = 'pipeline-observer';
+
+// SELF_IMPROVE_AREAS plus `ui` — the observer's fix can also be "the autopilot
+// panel is missing a knob the user needed", the one area the post-mortem never
+// files because a human triages its briefs and can make that call themselves.
+// A literal rather than a spread of the imported constant: this package's
+// import cycle through session.js (see the barrel's TDZ note) means selfImprove
+// may still be mid-evaluation when this module loads, so its consts are only
+// safe to touch at CALL time. observer.test.js pins the superset relation.
+export const OBSERVER_AREAS = Object.freeze([
+ 'editorial-check', 'pipeline-step', 'prompt', 'runner', 'config', 'ui',
+]);
+
+// Higher than SELF_IMPROVE_MIN_CONFIDENCE: nobody reads this brief before a
+// coding agent acts on it and merges the result, so a speculative diagnosis
+// must die here rather than in a human's approval queue.
+export const OBSERVER_MIN_CONFIDENCE = 0.7;
+
+// Spend ceiling for the in-flight passes; the terminal pass is a separate
+// (single) beat on top, so a run makes at most MIDRUN + 1 observer calls.
+export const OBSERVER_MAX_MIDRUN_PASSES = 3;
+
+// The retained frame types that justify spending a MID-RUN pass. Narrower than
+// the full signal set: `verify:round`/`foundation:round` are loops working as
+// designed (a loop that never converges shows up as a pause, which the terminal
+// pass reads), and `note`/`revision:*` are informational. A retained
+// `check:complete` counts only when the check actually THREW — the retention
+// filter also keeps `skipped` frames, which are usually benign.
+const MIDRUN_TRIGGER_TYPES = new Set(['child:retry', 'child:escalate', 'step:skip', 'gap:filed']);
+const isMidrunTrigger = (s) => MIDRUN_TRIGGER_TYPES.has(s.type)
+ || (s.type === 'check:complete' && !!s.error);
+
+// Ceiling on the per-run filing log carried to the terminal frame + marker.
+export const OBSERVER_MAX_FINDINGS = 5;
+
+const observerEnabled = (record) => !!record
+ && record.options?.observer === true
+ && record.mode === 'execute';
+
+/** The retained frames the run has emitted since the last observer pass. Pure. */
+export function freshSignals(record) {
+ return (record.signals || []).slice(record.runState?.observerCursor || 0);
+}
+
+/**
+ * Should the observer spend a pass after this step? Pure. Requires the opt-in,
+ * a remaining mid-run pass, and at least one triggering frame among the fresh
+ * signals — a step that went cleanly costs nothing.
+ */
+export function shouldObserveStep(record) {
+ if (!observerEnabled(record)) return false;
+ if ((record.runState?.observerPassesRun || 0) >= OBSERVER_MAX_MIDRUN_PASSES) return false;
+ return freshSignals(record).some(isMidrunTrigger);
+}
+
+/**
+ * Should the observer spend its terminal pass? Pure. Mirrors selfImprove's
+ * shouldDiagnose: a pause or error always warrants it, a cancel never does, and
+ * a `done` run qualifies only when its telemetry says the automation limped.
+ */
+export function shouldObserveTerminal(record, outcome) {
+ if (!observerEnabled(record)) return false;
+ if (outcome === 'paused' || outcome === 'error') return true;
+ if (outcome !== 'done') return false;
+ return hasAutomationSignals(record);
+}
+
+/** Should this shaped diagnosis dispatch an agent? Pure — observer bar. */
+export function isDispatchable(diagnosis) {
+ return !!diagnosis
+ && diagnosis.verdict === 'pipeline'
+ && diagnosis.confidence >= OBSERVER_MIN_CONFIDENCE
+ && !!diagnosis.title
+ && !!diagnosis.proposedChange;
+}
+
+/**
+ * Shape the auto-approved CoS task for a dispatchable diagnosis. Pure. Same
+ * one-line-description/dedup-key contract as buildSelfImproveTask (the brief
+ * rides `context`; the first line is the dedup key, stable per (area, defect)
+ * and deliberately not per-series). Differs in exactly one policy bit:
+ * `approvalRequired: false` — the whole point of the observer is that the fix
+ * lands without a human gate, which the user opted into by enabling it. The PR
+ * still goes through the review loop before merging (REVIEW_THEN_MERGE).
+ */
+export function buildObserverTask({ diagnosis, seriesId, seriesName, phase, outcome, outcomeReason, counts }) {
+ const slug = slugify(diagnosis.title);
+ const brief = [
+ `The autopilot's observing orchestrator diagnosed a PortOS pipeline defect mid-flight: ${diagnosis.title}`,
+ '',
+ diagnosis.problem,
+ '',
+ `Proposed change: ${diagnosis.proposedChange}`,
+ ];
+ if (diagnosis.risks) brief.push('', `Risks / things to be careful of: ${diagnosis.risks}`);
+ if (diagnosis.evidence.length) {
+ brief.push('', 'Evidence from the run telemetry:', ...diagnosis.evidence.map((e) => `- ${e}`));
+ }
+ brief.push(
+ '',
+ `Observed ${phase} during an autopilot run on series ${seriesId}${seriesName ? ` ("${seriesName}")` : ''}${outcome ? ` that ended \`${outcome}\`` : ''}${outcomeReason ? ` — ${trimToClause(outcomeReason, 500)}` : ''}.`,
+ `Signal counts: ${JSON.stringify(counts)}.`,
+ 'This task is auto-approved and its PR will merge after the review loop — confirm the defect in the code before changing anything, keep the change minimal, and abandon it (close the task without a PR) if the defect does not reproduce in the source.',
+ );
+ return {
+ description: `Pipeline orchestrator improvement (${diagnosis.area}/${slug})`,
+ context: brief.join('\n').slice(0, 4000),
+ app: PORTOS_APP_ID,
+ priority: 'MEDIUM',
+ useWorktree: true,
+ openPR: true,
+ prCompletion: PR_COMPLETIONS.REVIEW_THEN_MERGE,
+ simplify: true,
+ approvalRequired: false,
+ };
+}
+
+/**
+ * Run one observer pass — mid-run (`phase: 'step'`, after `stepKind`) or
+ * terminal (`phase: 'terminal'`, with the run's outcome) — and dispatch an
+ * auto-approved PortOS task when the verdict clears the bar.
+ *
+ * Best-effort by contract, like the self-improve pass: callers `.catch()` it
+ * and a skip is silent — observing a run must never break the run. Returns null
+ * when nothing was filed, else `{ area, title, taskId, filed, duplicate }`.
+ */
+export async function runObserverPass(sId, record, { phase, stepKind = null, outcome = null, reason = null } = {}) {
+ const gate = phase === 'terminal' ? shouldObserveTerminal(record, outcome) : shouldObserveStep(record);
+ if (!gate) return null;
+
+ const budget = await getDomainBudgetStatus('cos');
+ if (!budget.withinBudget) return null;
+
+ const rs = record.runState || {};
+ // A mid-run pass reads the window since the last pass (and consumes it — the
+ // same frames are never billed twice); the terminal pass reads the whole
+ // retained log, the way the post-mortem does.
+ const windowed = phase === 'terminal' ? (record.signals || []) : freshSignals(record);
+ if (phase !== 'terminal') {
+ rs.observerCursor = (record.signals || []).length;
+ rs.observerPassesRun = (rs.observerPassesRun || 0) + 1;
+ }
+
+ const [series, settings] = await Promise.all([
+ getSeries(sId).catch(() => null),
+ getSettings().catch(() => null),
+ ]);
+ const checkPlan = await buildEditorialCheckPlan(sId, { settings }).catch(() => null);
+ const { counts, dropped } = summarizeSignals(record);
+
+ broadcast(sId, { type: 'observer:start', runId: record.runId, phase, stepKind, signals: windowed.length });
+
+ const { content } = await runStagedLLM(OBSERVER_STAGE, {
+ seriesName: series?.name || 'unknown',
+ targetFormat: series?.targetFormat || 'unknown',
+ phase: phase === 'terminal' ? `terminal (run ended \`${outcome}\`)` : `mid-run, after the \`${stepKind}\` step`,
+ outcome: outcome || 'in-progress',
+ outcomeReason: trimToClause(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',
+ // Compact one-frame-per-line encoding, for the same token-cost reason as
+ // the self-improve pass.
+ signalsJson: windowed.map((s) => JSON.stringify(s)).join('\n').slice(0, 40_000),
+ signalCountsJson: JSON.stringify(counts, null, 2),
+ droppedSignals: dropped,
+ erroredChecks: [...(rs.editorialCheckErroredIds || [])].join(', ') || 'none',
+ craftGapIssues: rs.scriptCraftGapIssues?.size || 0,
+ // What this run already filed, so a later pass proposes the NEXT fix
+ // instead of re-describing the one already dispatched.
+ priorFilings: (rs.observerFindings || []).map((f) => `${f.area}: ${f.title}`).join('\n') || 'none',
+ }, { ...providerOverrideOpts(record), returnsJson: true, source: OBSERVER_STAGE });
+ await recordDomainUsage('cos', { actions: 1 });
+
+ const diagnosis = shapeDiagnosis(content, OBSERVER_AREAS);
+ if (!isDispatchable(diagnosis)) {
+ console.log(`👁️ autopilot observer — series=${sId.slice(0, 12)} ${phase} pass filed nothing (verdict=${diagnosis?.verdict || 'unreadable'} confidence=${diagnosis?.confidence ?? '—'})`);
+ return null;
+ }
+
+ const task = buildObserverTask({
+ diagnosis,
+ seriesId: sId,
+ seriesName: series?.name || null,
+ phase: phase === 'terminal' ? 'at the terminal' : `after the ${stepKind} step`,
+ outcome,
+ outcomeReason: reason,
+ counts,
+ });
+ const result = await cosTaskStore.addTask(task, 'internal')
+ .catch((err) => { console.log(`⚠️ autopilot: observer filing failed: ${err.message}`); return null; });
+ const filed = !!result && !result.duplicate;
+ const summary = {
+ area: diagnosis.area,
+ title: diagnosis.title,
+ taskId: result?.id || null,
+ filed,
+ duplicate: !!result?.duplicate,
+ };
+ if (result) {
+ if (!rs.observerFindings) rs.observerFindings = [];
+ if (rs.observerFindings.length < OBSERVER_MAX_FINDINGS) rs.observerFindings.push(summary);
+ broadcast(sId, { type: 'observer:filed', runId: record.runId, ...summary });
+ }
+ console.log(`👁️ autopilot observer — series=${sId.slice(0, 12)} area=${diagnosis.area} ${result ? (filed ? `dispatched ${result.id}` : 'duplicate of an open task') : 'filing failed'}`);
+ return summary;
+}
+
+/**
+ * Roll the run's observer activity into the terminal frame + persisted marker
+ * shape. Null when the observer never filed anything (nothing to report). Pure.
+ */
+export function summarizeObserver(record) {
+ const filed = record?.runState?.observerFindings || [];
+ if (filed.length === 0) return null;
+ return { passes: record.runState?.observerPassesRun || 0, filed };
+}
diff --git a/server/services/pipeline/seriesAutopilot/observer.test.js b/server/services/pipeline/seriesAutopilot/observer.test.js
new file mode 100644
index 0000000000..489d589db4
--- /dev/null
+++ b/server/services/pipeline/seriesAutopilot/observer.test.js
@@ -0,0 +1,318 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { mockNoPeerSync, mockNoPeers } from '../../../lib/mockPathsDataRoot.js';
+
+// Same hermetic setup as selfImprove.test.js — the observer pulls the pipeline
+// graph in transitively; stub the peer fan-out and the spend/LLM edges.
+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 () => ({})),
+}));
+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 {
+ freshSignals, shouldObserveStep, shouldObserveTerminal, isDispatchable,
+ buildObserverTask, runObserverPass, summarizeObserver,
+ OBSERVER_MIN_CONFIDENCE, OBSERVER_MAX_MIDRUN_PASSES, OBSERVER_AREAS,
+} = await import('./observer.js');
+const { shapeDiagnosis, SELF_IMPROVE_AREAS } = await import('./selfImprove.js');
+const { noteSignal } = await import('./state.js');
+const { PORTOS_APP_ID } = await import('../../../lib/appIdentity.js');
+
+// Minimal run record shaped like the orchestrator's, with the observer knobs.
+const makeRun = (over = {}) => ({
+ runId: 'run-1',
+ mode: 'execute',
+ options: { observer: true, ...(over.options || {}) },
+ signals: over.signals || [],
+ signalsDropped: 0,
+ runState: {
+ editorialCheckErroredIds: new Set(),
+ scriptCraftGapIssues: new Set(),
+ observerCursor: 0,
+ observerPassesRun: 0,
+ observerFindings: [],
+ ...(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: ['child:retry kind=text'],
+ 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('signal retention for observer-only runs', () => {
+ it('retains signals when only the observer opted in', () => {
+ const run = makeRun();
+ expect(noteSignal(run, { type: 'child:retry' })).toBe(true);
+ expect(run.signals).toHaveLength(1);
+ });
+});
+
+describe('shouldObserveStep', () => {
+ it('requires the opt-in and execute mode', () => {
+ expect(shouldObserveStep(makeRun({ options: { observer: false }, signals: [{ type: 'child:retry' }] }))).toBe(false);
+ const dry = makeRun({ signals: [{ type: 'child:retry' }] });
+ dry.mode = 'dry-run';
+ expect(shouldObserveStep(dry)).toBe(false);
+ });
+
+ it('spends nothing after a clean step', () => {
+ expect(shouldObserveStep(makeRun())).toBe(false);
+ // Loop-progress frames are the system working, not a mid-run trigger.
+ expect(shouldObserveStep(makeRun({ signals: [{ type: 'verify:round', blocking: 3 }] }))).toBe(false);
+ // A skipped (not errored) check is usually benign.
+ expect(shouldObserveStep(makeRun({ signals: [{ type: 'check:complete', checkId: 'c', skipped: true }] }))).toBe(false);
+ });
+
+ it('fires on the frames that say the automation misbehaved', () => {
+ for (const s of [
+ { type: 'child:retry' }, { type: 'child:escalate' }, { type: 'step:skip' },
+ { type: 'gap:filed' }, { type: 'check:complete', checkId: 'c', error: 'boom' },
+ ]) {
+ expect(shouldObserveStep(makeRun({ signals: [s] }))).toBe(true);
+ }
+ });
+
+ it('only reads signals past the cursor, and stops at the pass cap', () => {
+ const consumed = makeRun({
+ signals: [{ type: 'child:retry' }],
+ runState: { observerCursor: 1 },
+ });
+ expect(freshSignals(consumed)).toEqual([]);
+ expect(shouldObserveStep(consumed)).toBe(false);
+
+ const capped = makeRun({
+ signals: [{ type: 'child:retry' }],
+ runState: { observerPassesRun: OBSERVER_MAX_MIDRUN_PASSES },
+ });
+ expect(shouldObserveStep(capped)).toBe(false);
+ });
+});
+
+describe('shouldObserveTerminal', () => {
+ it('mirrors the post-mortem gate: pause/error always, cancel never, clean done never', () => {
+ expect(shouldObserveTerminal(makeRun(), 'paused')).toBe(true);
+ expect(shouldObserveTerminal(makeRun(), 'error')).toBe(true);
+ expect(shouldObserveTerminal(makeRun(), 'canceled')).toBe(false);
+ expect(shouldObserveTerminal(makeRun(), 'done')).toBe(false);
+ expect(shouldObserveTerminal(makeRun({ signals: [{ type: 'child:retry' }] }), 'done')).toBe(true);
+ expect(shouldObserveTerminal(makeRun({ options: { observer: false } }), 'error')).toBe(false);
+ });
+});
+
+describe('isDispatchable', () => {
+ it('holds a HIGHER confidence bar than the human-reviewed post-mortem', () => {
+ expect(isDispatchable(shapeDiagnosis(goodDiagnosis, OBSERVER_AREAS))).toBe(true);
+ expect(isDispatchable(shapeDiagnosis({ ...goodDiagnosis, confidence: OBSERVER_MIN_CONFIDENCE - 0.01 }, OBSERVER_AREAS))).toBe(false);
+ expect(isDispatchable(shapeDiagnosis({ ...goodDiagnosis, verdict: 'content' }, OBSERVER_AREAS))).toBe(false);
+ expect(isDispatchable(shapeDiagnosis({ ...goodDiagnosis, proposedChange: '' }, OBSERVER_AREAS))).toBe(false);
+ });
+
+ it('accepts the observer-only ui area', () => {
+ const shaped = shapeDiagnosis({ ...goodDiagnosis, area: 'ui' }, OBSERVER_AREAS);
+ expect(shaped.area).toBe('ui');
+ expect(isDispatchable(shaped)).toBe(true);
+ // OBSERVER_AREAS is a literal (not a spread of SELF_IMPROVE_AREAS — the
+ // session.js import cycle makes that a TDZ throw); pin the superset here.
+ for (const area of SELF_IMPROVE_AREAS) expect(OBSERVER_AREAS).toContain(area);
+ });
+});
+
+describe('buildObserverTask', () => {
+ const build = (over = {}) => buildObserverTask({
+ diagnosis: shapeDiagnosis(goodDiagnosis, OBSERVER_AREAS),
+ seriesId: 'series-1',
+ seriesName: 'Example Series',
+ phase: 'after the textStages step',
+ outcome: null,
+ outcomeReason: null,
+ counts: { 'child:retry': 2 },
+ ...over,
+ });
+
+ it('targets PortOS, worktree-isolated, PR-opening, review-loop-then-merge', () => {
+ 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');
+ expect(task.simplify).toBe(true);
+ });
+
+ it('is auto-approved — the one deliberate divergence from the post-mortem task', () => {
+ expect(build().approvalRequired).toBe(false);
+ });
+
+ it('keeps the one-line description dedup key stable per defect, not per series', () => {
+ const a = build();
+ expect(a.description).not.toContain('\n');
+ const b = build({ seriesId: 'series-2', seriesName: 'Another Series' });
+ expect(b.description).toBe(a.description);
+ const otherDefect = build({ diagnosis: shapeDiagnosis({ ...goodDiagnosis, title: 'Reverse outline is never refreshed' }, OBSERVER_AREAS) });
+ expect(otherDefect.description).not.toBe(a.description);
+ // Distinct from the self-improve dedup key so an observer task and a
+ // post-mortem task about different diagnoses can't collide.
+ expect(a.description).toMatch(/^Pipeline orchestrator improvement /);
+ });
+
+ it('warns the agent that its PR merges unattended', () => {
+ expect(build().context).toContain('auto-approved');
+ expect(build().context).toContain(goodDiagnosis.proposedChange);
+ });
+});
+
+describe('runObserverPass (mid-run)', () => {
+ it('spends nothing on a clean step and leaves the cursor alone', async () => {
+ const run = makeRun();
+ const out = await runObserverPass('series-1', run, { phase: 'step', stepKind: 'textStages' });
+ expect(out).toBeNull();
+ expect(runStagedLLM).not.toHaveBeenCalled();
+ expect(run.runState.observerPassesRun).toBe(0);
+ });
+
+ it('spends nothing when the daily budget is exhausted', async () => {
+ budgetStatus = { withinBudget: false, exceeded: 'actions' };
+ const run = makeRun({ signals: [{ type: 'child:retry' }] });
+ const out = await runObserverPass('series-1', run, { phase: 'step', stepKind: 'textStages' });
+ expect(out).toBeNull();
+ expect(runStagedLLM).not.toHaveBeenCalled();
+ });
+
+ it('dispatches an auto-approved task, bills one action and consumes the window', async () => {
+ const run = makeRun({ signals: [{ type: 'child:retry', kind: 'text' }] });
+ const out = await runObserverPass('series-1', run, { phase: 'step', stepKind: 'textStages' });
+ expect(runStagedLLM).toHaveBeenCalledWith('pipeline-observer', expect.any(Object), expect.objectContaining({ returnsJson: true }));
+ expect(recordDomainUsage).toHaveBeenCalledWith('cos', { actions: 1 });
+ expect(addTask).toHaveBeenCalledWith(expect.objectContaining({ app: PORTOS_APP_ID, approvalRequired: false }), 'internal');
+ expect(out).toMatchObject({ area: 'editorial-check', filed: true, taskId: 'sys-1' });
+ // The window is consumed — the same frames are never billed twice.
+ expect(run.runState.observerCursor).toBe(1);
+ expect(run.runState.observerPassesRun).toBe(1);
+ expect(run.runState.observerFindings).toHaveLength(1);
+ });
+
+ it('consumes the window even when the verdict files nothing', async () => {
+ llmContent = { ...goodDiagnosis, verdict: 'none' };
+ const run = makeRun({ signals: [{ type: 'child:retry' }] });
+ const out = await runObserverPass('series-1', run, { phase: 'step', stepKind: 'textStages' });
+ expect(out).toBeNull();
+ expect(addTask).not.toHaveBeenCalled();
+ expect(run.runState.observerCursor).toBe(1);
+ expect(run.runState.observerPassesRun).toBe(1);
+ });
+
+ it('drops a verdict below the raised confidence bar', async () => {
+ // Filable for the post-mortem (>= 0.6) but NOT dispatchable unattended.
+ llmContent = { ...goodDiagnosis, confidence: 0.65 };
+ const run = makeRun({ signals: [{ type: 'child:retry' }] });
+ const out = await runObserverPass('series-1', run, { phase: 'step', stepKind: 'textStages' });
+ expect(out).toBeNull();
+ expect(addTask).not.toHaveBeenCalled();
+ });
+
+ it('reports a duplicate as tracked, not newly dispatched', async () => {
+ addTask.mockResolvedValueOnce({ id: 'sys-earlier', duplicate: true });
+ const run = makeRun({ signals: [{ type: 'child:retry' }] });
+ const out = await runObserverPass('series-1', run, { phase: 'step', stepKind: 'textStages' });
+ expect(out).toMatchObject({ filed: false, duplicate: true, taskId: 'sys-earlier' });
+ });
+
+ it('sends no manuscript content to the diagnosis stage', async () => {
+ const run = makeRun({ signals: [{ type: 'child:escalate', kind: 'text' }] });
+ await runObserverPass('series-1', run, { phase: 'step', stepKind: 'textStages' });
+ const [, vars] = runStagedLLM.mock.calls[0];
+ // Only run telemetry + configuration — the brief is read by an agent that
+ // opens (and merges) a public PR.
+ expect(Object.keys(vars).sort()).toEqual([
+ 'craftGapIssues', 'droppedSignals', 'enabledChecks', 'erroredChecks', 'gateConfigJson',
+ 'outcome', 'outcomeReason', 'phase', 'priorFilings', 'seriesName', 'signalCountsJson',
+ 'signalsJson', 'stepSequence', 'targetFormat',
+ ]);
+ });
+
+ it('names prior filings so a later pass proposes the NEXT fix', async () => {
+ const run = makeRun({
+ signals: [{ type: 'child:retry' }],
+ runState: { observerFindings: [{ area: 'runner', title: 'Retry budget is never applied' }] },
+ });
+ await runObserverPass('series-1', run, { phase: 'step', stepKind: 'textStages' });
+ const [, vars] = runStagedLLM.mock.calls[0];
+ expect(vars.priorFilings).toContain('Retry budget is never applied');
+ });
+});
+
+describe('runObserverPass (terminal)', () => {
+ it('reads the whole retained log without consuming a mid-run pass', async () => {
+ const run = makeRun({
+ signals: [{ type: 'child:retry' }, { type: 'step:skip' }],
+ runState: { observerCursor: 2, observerPassesRun: OBSERVER_MAX_MIDRUN_PASSES },
+ });
+ const out = await runObserverPass('series-1', run, { phase: 'terminal', outcome: 'paused', reason: 'editorialReview: ran out of rounds' });
+ expect(out).toMatchObject({ filed: true });
+ const [, vars] = runStagedLLM.mock.calls[0];
+ // Both frames, not the (empty) fresh window.
+ expect(vars.signalsJson).toContain('child:retry');
+ expect(vars.signalsJson).toContain('step:skip');
+ expect(run.runState.observerPassesRun).toBe(OBSERVER_MAX_MIDRUN_PASSES);
+ });
+
+ it('never fires on a cancel', async () => {
+ const out = await runObserverPass('series-1', makeRun({ signals: [{ type: 'child:retry' }] }), { phase: 'terminal', outcome: 'canceled' });
+ expect(out).toBeNull();
+ expect(runStagedLLM).not.toHaveBeenCalled();
+ });
+});
+
+describe('summarizeObserver', () => {
+ it('is null until something was dispatched, then reports passes + filings', () => {
+ expect(summarizeObserver(makeRun())).toBeNull();
+ const run = makeRun({
+ runState: {
+ observerPassesRun: 2,
+ observerFindings: [{ area: 'runner', title: 'x', taskId: 'sys-1', filed: true, duplicate: false }],
+ },
+ });
+ expect(summarizeObserver(run)).toEqual({
+ passes: 2,
+ filed: [{ area: 'runner', title: 'x', taskId: 'sys-1', filed: true, duplicate: false }],
+ });
+ });
+});
diff --git a/server/services/pipeline/seriesAutopilot/orchestrator.js b/server/services/pipeline/seriesAutopilot/orchestrator.js
index 6aa698a38b..2614a3313d 100644
--- a/server/services/pipeline/seriesAutopilot/orchestrator.js
+++ b/server/services/pipeline/seriesAutopilot/orchestrator.js
@@ -18,9 +18,10 @@ import {
resolveAutopilotRounds, resolveAutopilotFoundationGate, resolveAutopilotFoundationThreshold,
resolveAutopilotReadinessGate, resolveAutopilotCheckPauseThreshold, resolveAutopilotNotifyOnPause,
resolveAutopilotProduceTeaser, resolveAutopilotRevision, resolveAutopilotLlm,
- resolveAutopilotUnlockForRun, resolveAutopilotSelfImprove,
+ resolveAutopilotUnlockForRun, resolveAutopilotSelfImprove, resolveAutopilotObserver,
} from './config.js';
import { runSelfImproveDiagnosis } from './selfImprove.js';
+import { runObserverPass, summarizeObserver } from './observer.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';
@@ -78,6 +79,11 @@ export async function startSeriesAutopilot(sId, options = {}) {
// what failed. Resolved here with the other gates so the signal tap in
// `broadcast` sees the flag from the run's very first frame.
selfImprove: resolveAutopilotSelfImprove(options, settings),
+ // Observing orchestrator (opt-in): watch the run's telemetry step by step
+ // and dispatch AUTO-APPROVED PortOS fix tasks (PR + review loop + merge, no
+ // human gate) as pipeline defects surface. Same early resolution so the
+ // signal tap retains frames from the first one.
+ observer: resolveAutopilotObserver(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
@@ -158,6 +164,15 @@ export async function startSeriesAutopilot(sId, options = {}) {
revisionCyclesRun: 0,
revisionScoreHistory: [],
revisionConverged: false,
+ // Observing orchestrator state (opt-in, see observer.js). `observerCursor`
+ // is the index into `signals` the next mid-run pass reads from (each pass
+ // consumes its window so the same frames are never billed twice);
+ // `observerPassesRun` counts the bounded mid-run passes;
+ // `observerFindings` is the bounded log of dispatched tasks, carried to
+ // the terminal frame + marker.
+ observerCursor: 0,
+ observerPassesRun: 0,
+ observerFindings: [],
},
activeChild: null,
};
@@ -174,15 +189,39 @@ 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 })
+ // Post-mortem hook for the opt-in diagnosis passes. Best-effort by contract:
+ // a diagnosis that throws must never turn a completed run into a failed one,
+ // so every terminal calls it through these catches. 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). When the observing orchestrator
+ // is on it SUPERSEDES the one-shot self-improve post-mortem — same evidence,
+ // stronger action policy; running both would bill one run's telemetry twice
+ // and file near-duplicate tasks under different dedup keys. Returns
+ // `{ selfImprove, observer }` so each terminal spreads both marker fields.
+ const postMortem = async (outcome, reason = null) => {
+ if (record.options.observer === true) {
+ await runObserverPass(sId, record, { phase: 'terminal', outcome, reason })
+ .catch((err) => {
+ console.log(`⚠️ autopilot: observer terminal pass failed for ${sId.slice(0, 12)}: ${err.message}`);
+ });
+ return { selfImprove: null, observer: summarizeObserver(record) };
+ }
+ const selfImprove = await runSelfImproveDiagnosis(sId, record, { outcome, reason })
+ .catch((err) => {
+ console.log(`⚠️ autopilot: self-improve diagnosis failed for ${sId.slice(0, 12)}: ${err.message}`);
+ return null;
+ });
+ return { selfImprove, observer: null };
+ };
+
+ // Mid-run observer beat: after each completed step, spend one bounded
+ // diagnosis pass when the step's fresh telemetry warrants it (see
+ // observer.js#shouldObserveStep — a clean step costs nothing). Best-effort
+ // like the post-mortem: observing must never break the run.
+ const observeStep = (step) => runObserverPass(sId, record, { phase: 'step', stepKind: step.kind })
.catch((err) => {
- console.log(`⚠️ autopilot: self-improve diagnosis failed for ${sId.slice(0, 12)}: ${err.message}`);
+ console.log(`⚠️ autopilot: observer pass failed for ${sId.slice(0, 12)}: ${err.message}`);
return null;
});
@@ -246,11 +285,11 @@ export async function startSeriesAutopilot(sId, options = {}) {
// 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
+ const pm = await postMortem('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() });
+ await persistMarker(sId, { status: 'done', runId, currentStep: null, craftGapIssues, craftGapFindings, editorialCheckErrors, selfImprove: pm.selfImprove, observer: pm.observer });
+ broadcast(sId, { type: 'complete', runId, steps: ordinal, craftGapIssues, craftGapFindings, editorialCheckErrors, editorialCheckErroredIds, selfImprove: pm.selfImprove, observer: pm.observer, 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;
}
@@ -310,9 +349,9 @@ export async function startSeriesAutopilot(sId, options = {}) {
// 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() });
+ const pm = await postMortem('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: pm.selfImprove, observer: pm.observer });
+ broadcast(sId, { type: 'paused', runId, scope: step.kind, reason: result.reason, residualFindings: result.residual || [], pauseKind: result.pauseKind || null, healthBreakdown: result.healthBreakdown || null, selfImprove: pm.selfImprove, observer: pm.observer, 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
@@ -330,6 +369,7 @@ export async function startSeriesAutopilot(sId, options = {}) {
return;
}
broadcast(sId, { type: 'step:complete', kind: step.kind, seasonId: step.seasonId, issueId: step.issueId, ordinal });
+ await observeStep(step);
}
// Cancelled.
@@ -342,9 +382,9 @@ export async function startSeriesAutopilot(sId, options = {}) {
// 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() });
+ const pm = await postMortem('error', message);
+ await persistMarker(sId, { status: 'error', runId, lastError: message, selfImprove: pm.selfImprove, observer: pm.observer });
+ broadcast(sId, { type: 'error', runId, error: message, selfImprove: pm.selfImprove, observer: pm.observer, 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.js
index ae72fff222..5ae6ff9167 100644
--- a/server/services/pipeline/seriesAutopilot/selfImprove.js
+++ b/server/services/pipeline/seriesAutopilot/selfImprove.js
@@ -71,10 +71,20 @@ 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 || {};
+ return hasAutomationSignals(record);
+}
+
+/**
+ * Did the run's telemetry say the AUTOMATION limped — a check that threw, a
+ * filed craft gap, a retried/escalated child, a skipped step? Pure. Shared with
+ * the observing orchestrator (observer.js), whose terminal pass gates on the
+ * same evidence.
+ */
+export function hasAutomationSignals(record) {
+ const rs = record?.runState || {};
if (rs.editorialCheckErroredIds?.size > 0) return true;
if (rs.scriptCraftGapIssues?.size > 0) return true;
- return (record.signals || []).some((s) => (
+ return (record?.signals || []).some((s) => (
s.type === 'child:retry' || s.type === 'child:escalate' || s.type === 'step:skip'
|| (s.type === 'check:complete' && s.error)
));
@@ -88,8 +98,9 @@ const SELF_IMPROVE_VERDICTS = Object.freeze(['pipeline', 'content', 'none']);
// Where in PortOS the proposed fix belongs. Prefixes the filed task's dedup key
// (see buildSelfImproveTask) and tells a reader which part of the system the
-// brief is about before they open it.
-const SELF_IMPROVE_AREAS = Object.freeze([
+// brief is about before they open it. Exported as the base vocabulary the
+// observing orchestrator (observer.js) extends.
+export const SELF_IMPROVE_AREAS = Object.freeze([
'editorial-check', 'pipeline-step', 'prompt', 'runner', 'config',
]);
@@ -100,9 +111,10 @@ export const SELF_IMPROVE_MIN_CONFIDENCE = 0.6;
/**
* 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.
+ * Pure. `areas` is the accepted area vocabulary — the observer passes its
+ * extended set; the default keeps the post-mortem's behavior unchanged.
*/
-export function shapeDiagnosis(raw) {
+export function shapeDiagnosis(raw, areas = SELF_IMPROVE_AREAS) {
if (!raw || typeof raw !== 'object') return null;
const verdict = SELF_IMPROVE_VERDICTS.includes(raw.verdict) ? raw.verdict : null;
if (!verdict) return null;
@@ -112,7 +124,7 @@ export function shapeDiagnosis(raw) {
return {
verdict,
confidence,
- area: SELF_IMPROVE_AREAS.includes(raw.area) ? raw.area : 'pipeline-step',
+ area: areas.includes(raw.area) ? raw.area : 'pipeline-step',
title: trimToClause(raw.title, 160),
problem: trimToClause(raw.problem, 2000),
evidence: Array.isArray(raw.evidence)
@@ -196,8 +208,9 @@ export function buildSelfImproveTask({ diagnosis, seriesId, seriesName, outcome,
// 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 = [
+// told to add something that already exists. Exported for the observer's prompt,
+// which reasons over the same order.
+export const STEP_SEQUENCE = [
'generateArc — draft the whole-series arc + volumes',
'generateEpisodes — break each volume into issues',
'verifyArc — cross-volume synopsis continuity verify → resolve loop',
@@ -218,8 +231,9 @@ const STEP_SEQUENCE = [
// 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) => ({
+// model to tell "this gate is off" from "this gate ran and failed". Exported
+// for the observer, whose prompt carries the same context.
+export const gateConfigOf = (options) => ({
maxArcVerifyRounds: options.maxArcVerifyRounds,
maxBeatContinuityRounds: options.maxBeatContinuityRounds,
maxEditorialRounds: options.maxEditorialRounds,
diff --git a/server/services/pipeline/seriesAutopilot/state.js b/server/services/pipeline/seriesAutopilot/state.js
index e07d86c05b..10926ac22a 100644
--- a/server/services/pipeline/seriesAutopilot/state.js
+++ b/server/services/pipeline/seriesAutopilot/state.js
@@ -76,11 +76,13 @@ export function isSignalFrame(payload) {
/**
* Record one broadcast frame onto the run's signal log. Called from `broadcast`
* for EVERY frame of EVERY run, so the opt-out must come first and stay cheap: a
- * run that didn't ask for a post-mortem (or a dry-run, which has no telemetry
- * worth diagnosing) does two property reads and returns. True when retained.
+ * run that asked for neither the post-mortem (`selfImprove`) nor the observing
+ * orchestrator (`observer`) — or a dry-run, which has no telemetry worth
+ * diagnosing — does a few property reads and returns. True when retained.
*/
export function noteSignal(run, payload) {
- if (!run || run.options?.selfImprove !== true || run.mode !== 'execute') return false;
+ if (!run || run.mode !== 'execute') return false;
+ if (run.options?.selfImprove !== true && run.options?.observer !== true) return false;
if (!isSignalFrame(payload)) return false;
if (!run.signals) run.signals = [];
if (run.signals.length >= MAX_SIGNALS) {