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

simplify: reuse shared helpers, drop the auto-approve knob, key dedup on the defect

[._.]/ Adam Eivy9d4f9ecf955d
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index d320d28642..dffda3d187 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -4,7 +4,7 @@
- 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 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.
- 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.
diff --git a/client/src/components/pipeline/AutopilotPanel.jsx b/client/src/components/pipeline/AutopilotPanel.jsx
index 484f542bc7..5f56822c8b 100644
--- a/client/src/components/pipeline/AutopilotPanel.jsx
+++ b/client/src/components/pipeline/AutopilotPanel.jsx
@@ -49,12 +49,10 @@ 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.
+// Pipeline self-improvement — mirror the server default (off). When on, a run
+// 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;
-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) => {
@@ -231,9 +229,7 @@ function selfImproveLine(si) {
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`;
+ return `Filed a PortOS fix task (${si.area})${what} — approve it in CoS to start the work`;
}
function Findings({ items }) {
@@ -306,7 +302,6 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
// 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
@@ -325,7 +320,6 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
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
@@ -414,7 +408,6 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
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 : '');
})
@@ -466,22 +459,11 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
setRevisionEnabled(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.
+ // Boolean checkbox — persists immediately on toggle (no blur) like notifyOnPause.
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({ selfImprove: v });
}, [persistRounds]);
const editRevisionMinCycles = useCallback((v) => { revisionMinEditedRef.current = true; setRevisionMinCycles(v); }, []);
const editRevisionMaxCycles = useCallback((v) => { revisionMaxEditedRef.current = true; setRevisionMaxCycles(v); }, []);
@@ -593,9 +575,8 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
if (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.
+ // Self-improvement persists + overrides 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
@@ -629,7 +610,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, selfImprove, selfImproveAutoApprove, readinessGate, providerOverride, modelOverride, persistRounds]);
+ }, [seriesId, includeVisual, fileGaps, arcRounds, editorialRounds, beatContinuityRounds, checkPauseThreshold, notifyOnPause, unlockForRun, revisionEnabled, revisionMinCycles, revisionMaxCycles, revisionPlateauDelta, foundationGate, foundationThreshold, foundationRounds, selfImprove, readinessGate, providerOverride, modelOverride, persistRounds]);
const cancel = useCallback(async () => {
await cancelPipelineAutopilot(seriesId).catch(() => null);
@@ -908,15 +889,9 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
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>
- </>
+ <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, 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}
<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.
@@ -989,6 +964,7 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
// craft-gap message takes precedence when both are present).
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);
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">
@@ -1022,9 +998,7 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
{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}
+ {siLine ? <p className="text-[11px] text-port-accent mt-1">🔧 {siLine}</p> : 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 dd0ab2f01d..4bef76cb62 100644
--- a/client/src/components/pipeline/AutopilotPanel.test.jsx
+++ b/client/src/components/pipeline/AutopilotPanel.test.jsx
@@ -479,53 +479,38 @@ describe('AutopilotPanel', () => {
// 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 () => {
+ 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(/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 },
));
+ // The filed task is always approval-gated — there is no auto-start knob.
+ expect(await screen.findByText(/waiting in your CoS approval queue/i)).toBeInTheDocument();
});
- it('sends both toggles as per-run overrides once edited', async () => {
+ 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(/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 },
+ { includeVisual: true, fileGaps: false, selfImprove: 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 },
+ selfImprove: { verdict: 'pipeline', area: 'editorial-check', title: 'Check pleasantries at beat altitude', filed: true },
};
renderPanel({ id: 's1', targetFormat: 'comic' });
await waitFor(() => expect(toast).toHaveBeenCalledWith(
@@ -539,10 +524,10 @@ describe('AutopilotPanel', () => {
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 },
+ selfImprove: { verdict: 'pipeline', area: 'runner', title: 'Retry budget is never applied', filed: true },
},
});
- expect(await screen.findByText(/Filed a PortOS fix task \(runner\).*CoS will pick it up/i)).toBeInTheDocument();
+ expect(await screen.findByText(/Filed a PortOS fix task \(runner\).*approve it in CoS/i)).toBeInTheDocument();
});
it('says nothing when the verdict was that the story, not the code, needs work', async () => {
diff --git a/server/lib/pipelineValidation.js b/server/lib/pipelineValidation.js
index c69566bb58..1a375087ee 100644
--- a/server/lib/pipelineValidation.js
+++ b/server/lib/pipelineValidation.js
@@ -267,11 +267,11 @@ export const pipelineEditorialChecksSettingsSchema = z.object({
// 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.
+ // The filed task always awaits human approval, runs in a worktree and opens a
+ // PR — that is not configurable, matching every other autonomously generated
+ // code-editing task in PortOS. 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 to
diff --git a/server/routes/pipeline/autopilot.js b/server/routes/pipeline/autopilot.js
index 80dc9d1437..5ceb1d5e9a 100644
--- a/server/routes/pipeline/autopilot.js
+++ b/server/routes/pipeline/autopilot.js
@@ -121,11 +121,9 @@ const autopilotStartSchema = z.object({
// 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.
+ // That task always awaits human approval. Falls 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/pipeline/series.js b/server/services/pipeline/series.js
index 7875903343..fbc0365fb2 100644
--- a/server/services/pipeline/series.js
+++ b/server/services/pipeline/series.js
@@ -210,21 +210,20 @@ 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'];
+// in, whose telemetry was clean (the pass makes no LLM call then), or that
+// diagnosed nothing filable — the producer only reports a `pipeline` verdict, so
+// that's the only shape this accepts. Same transient-marker rationale as
+// pauseKind / craftGap*: no schema-gate bump.
const sanitizeAutopilotSelfImprove = (raw) => {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
- if (!SELF_IMPROVE_MARKER_VERDICTS.includes(raw.verdict)) return null;
+ if (raw.verdict !== 'pipeline') return null;
return {
- verdict: raw.verdict,
- confidence: Number.isFinite(raw.confidence) ? Math.min(1, Math.max(0, raw.confidence)) : null,
+ verdict: 'pipeline',
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,
};
};
diff --git a/server/services/pipeline/seriesAutopilot.test.js b/server/services/pipeline/seriesAutopilot.test.js
index 629b2b34e8..2a431b7b4d 100644
--- a/server/services/pipeline/seriesAutopilot.test.js
+++ b/server/services/pipeline/seriesAutopilot.test.js
@@ -798,24 +798,15 @@ 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('defaults OFF', () => {
+ expect(resolveAutopilotSelfImprove({}, null)).toBe(false);
});
it('per-run option wins over the persisted setting', () => {
- expect(resolveAutopilotSelfImprove(
- { selfImprove: true },
- { pipelineEditorialChecks: { selfImprove: false, selfImproveAutoApprove: true } },
- )).toEqual({ selfImprove: true, selfImproveAutoApprove: true });
+ expect(resolveAutopilotSelfImprove({ selfImprove: true }, { pipelineEditorialChecks: { selfImprove: false } })).toBe(true);
+ expect(resolveAutopilotSelfImprove({ selfImprove: false }, { pipelineEditorialChecks: { selfImprove: true } })).toBe(false);
});
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 });
+ expect(resolveAutopilotSelfImprove({}, { pipelineEditorialChecks: { selfImprove: true } })).toBe(true);
});
});
diff --git a/server/services/pipeline/seriesAutopilot/config.js b/server/services/pipeline/seriesAutopilot/config.js
index a5f1c99e50..160947a549 100644
--- a/server/services/pipeline/seriesAutopilot/config.js
+++ b/server/services/pipeline/seriesAutopilot/config.js
@@ -42,6 +42,17 @@ export const DEFAULT_FOUNDATION_GATE_ENABLED = true;
// `maxChildRetries` option overrides it (plumbed through runOptions).
export const MAX_CHILD_RETRIES = 1;
+// The one precedence rule every gate below follows for a BOOLEAN knob: an
+// explicit per-run option wins, then the persisted pipelineEditorialChecks
+// setting, then the module default. Hoisted so the file states it once — it was
+// open-coded in three resolvers and closed over twice more, which is how the
+// next gate ends up copying whichever variant it happened to land next to.
+const pickBool = (o, s, fallback) => {
+ if (typeof o === 'boolean') return o;
+ if (typeof s === 'boolean') return s;
+ return fallback;
+};
+
// Resolve the effective round bounds for a run: an explicit per-run option wins,
// then the persisted pipelineEditorialChecks setting, then the module default.
// Returns integers only — a non-integer at any layer falls through to the next.
@@ -69,10 +80,8 @@ export function resolveAutopilotRounds(options = {}, settings = null) {
// onto run options once at start so the loop, the dry-run plan, and a resume all
// read the same effective values.
export function resolveAutopilotFoundationGate(options = {}, settings = null) {
- if (typeof options?.foundationGate === 'boolean') return options.foundationGate;
const pec = settings?.pipelineEditorialChecks || {};
- if (typeof pec?.foundationGate === 'boolean') return pec.foundationGate;
- return DEFAULT_FOUNDATION_GATE_ENABLED;
+ return pickBool(options?.foundationGate, pec?.foundationGate, DEFAULT_FOUNDATION_GATE_ENABLED);
}
export function resolveAutopilotFoundationThreshold(options = {}, settings = null) {
if (Number.isFinite(options?.foundationThreshold)) return options.foundationThreshold;
@@ -116,10 +125,8 @@ export function resolveAutopilotCheckPauseThreshold(options = {}, settings = nul
// at every layer: per-run option wins, then the persisted setting, then true.
export const DEFAULT_NOTIFY_ON_PAUSE = true;
export function resolveAutopilotNotifyOnPause(options = {}, settings = null) {
- if (typeof options?.notifyOnPause === 'boolean') return options.notifyOnPause;
const pec = settings?.pipelineEditorialChecks || {};
- if (typeof pec?.notifyOnPause === 'boolean') return pec.notifyOnPause;
- return DEFAULT_NOTIFY_ON_PAUSE;
+ return pickBool(options?.notifyOnPause, pec?.notifyOnPause, DEFAULT_NOTIFY_ON_PAUSE);
}
// Autopilot → CD teaser deliverable (CDO Phase 3, #2185). Once a comic issue is
@@ -132,10 +139,8 @@ export function resolveAutopilotNotifyOnPause(options = {}, settings = null) {
// all read the same effective flag.
export const DEFAULT_PRODUCE_TEASER = false;
export function resolveAutopilotProduceTeaser(options = {}, settings = null) {
- if (typeof options?.produceTeaser === 'boolean') return options.produceTeaser;
const pec = settings?.pipelineEditorialChecks || {};
- if (typeof pec?.produceTeaser === 'boolean') return pec.produceTeaser;
- return DEFAULT_PRODUCE_TEASER;
+ return pickBool(options?.produceTeaser, pec?.produceTeaser, DEFAULT_PRODUCE_TEASER);
}
// Does THIS run want to produce a teaser deliverable? Gated on the resolved
@@ -178,11 +183,6 @@ export const DEFAULT_REVISION_MAX_CYCLES = 2;
export const DEFAULT_REVISION_PLATEAU_DELTA = 0.3;
export function resolveAutopilotRevision(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;
- };
const int = (o, s, fallback) => {
if (Number.isInteger(o)) return o;
if (Number.isInteger(s)) return s;
@@ -196,7 +196,7 @@ export function resolveAutopilotRevision(options = {}, settings = null) {
const minCycles = int(options?.revisionMinCycles, pec?.revisionMinCycles, DEFAULT_REVISION_MIN_CYCLES);
const maxCycles = int(options?.revisionMaxCycles, pec?.revisionMaxCycles, DEFAULT_REVISION_MAX_CYCLES);
return {
- revisionEnabled: bool(options?.revisionEnabled, pec?.revisionEnabled, DEFAULT_REVISION_ENABLED),
+ revisionEnabled: pickBool(options?.revisionEnabled, pec?.revisionEnabled, DEFAULT_REVISION_ENABLED),
revisionMinCycles: Math.max(1, minCycles),
// maxCycles never below minCycles — a misconfig can't strand the loop unable to run.
revisionMaxCycles: Math.max(Math.max(1, minCycles), maxCycles),
@@ -219,26 +219,12 @@ export function resolveAutopilotRevision(options = {}, settings = null) {
// `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.
+// The filed task always awaits human approval and always opens a PR — see
+// selfImprove.js's header for why that isn't a knob.
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,
- ),
- };
+ return pickBool(options?.selfImprove, pec?.selfImprove, DEFAULT_SELF_IMPROVE);
}
// Which provider/model do this run's LLM calls use? An explicit per-run
diff --git a/server/services/pipeline/seriesAutopilot/orchestrator.js b/server/services/pipeline/seriesAutopilot/orchestrator.js
index 2897811986..daf7fc1ed0 100644
--- a/server/services/pipeline/seriesAutopilot/orchestrator.js
+++ b/server/services/pipeline/seriesAutopilot/orchestrator.js
@@ -77,7 +77,7 @@ export async function startSeriesAutopilot(sId, options = {}) {
// 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),
+ selfImprove: 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
diff --git a/server/services/pipeline/seriesAutopilot/selfImprove.js b/server/services/pipeline/seriesAutopilot/selfImprove.js
index 82550edfca..5accf4ff0f 100644
--- a/server/services/pipeline/seriesAutopilot/selfImprove.js
+++ b/server/services/pipeline/seriesAutopilot/selfImprove.js
@@ -19,11 +19,16 @@
* 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.
+ * 3. **Deduped, approval-gated and worktree-isolated.** The filed task's first
+ * line is stable per (area, defect), so cosTaskStore's dedup collapses the
+ * same diagnosis across runs and series onto one open task. The task always
+ * awaits human approval, runs in a worktree, and opens a PR — an LLM's
+ * unverified read of one run's telemetry never dispatches a coding agent at
+ * PortOS's own source unattended. That matches every other autonomously
+ * generated code-editing task in PortOS (layeredIntelligence's
+ * `buildHandoffTask`, `autoFixer`, `agentErrorAnalysis` all hard-code
+ * `approvalRequired: true`); the autonomy dial for this class of work is the
+ * CoS approval queue, not a per-series checkbox.
*
* The signal log is captured passively: `noteSignal` taps the same SSE frames
* the run already broadcasts (`session.js#broadcast`), so a new telemetry frame
@@ -40,76 +45,15 @@ 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';
-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 };
-}
+const SELF_IMPROVE_STAGE = 'pipeline-self-improve';
/**
* Does this run carry evidence worth spending a diagnosis call on? Pure.
@@ -133,24 +77,23 @@ export function shouldDiagnose(record, outcome) {
));
}
-// 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']);
+// The verdict vocabulary. `pipeline` is the only one that files anything (and the
+// only one this pass reports at all — see runSelfImproveDiagnosis); `content`
+// means the manuscript, not the code, needs work, and `none` means the run's
+// trouble was expected/benign.
+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([
+// 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([
'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.
+// A diagnosis below this confidence is dropped rather than 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.
@@ -167,13 +110,13 @@ export function shapeDiagnosis(raw) {
verdict,
confidence,
area: SELF_IMPROVE_AREAS.includes(raw.area) ? raw.area : 'pipeline-step',
- title: trimTo(raw.title, 160),
- problem: trimTo(raw.problem, 2000),
+ title: trimToClause(raw.title, 160),
+ problem: trimToClause(raw.problem, 2000),
evidence: Array.isArray(raw.evidence)
- ? raw.evidence.map((e) => trimTo(e, 400)).filter(Boolean).slice(0, 8)
+ ? raw.evidence.map((e) => trimToClause(e, 400)).filter(Boolean).slice(0, 8)
: [],
- proposedChange: trimTo(raw.proposedChange, 2000),
- risks: trimTo(raw.risks, 800),
+ proposedChange: trimToClause(raw.proposedChange, 2000),
+ risks: trimToClause(raw.risks, 800),
};
}
@@ -193,14 +136,19 @@ export function isFilable(diagnosis) {
* 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`.
+ * The FIRST LINE is the dedup key (cosTaskStore matches on it, lowercased,
+ * scoped to the app), so it carries the area AND a slug of the diagnosis itself.
+ * Area alone would be wrong in both directions: it is deliberately NOT
+ * per-series (the defect lives in shared PortOS code, so one open task should
+ * cover it however many series hit it), but keying on the bucket would cap
+ * PortOS at one open task per area forever and silently discard the next,
+ * different `editorial-check` defect — and a task that ends up `blocked` counts
+ * as a duplicate too, which would mute that area permanently.
*/
-export function buildSelfImproveTask({ diagnosis, seriesId, seriesName, outcome, outcomeReason, counts, autoApprove }) {
+export function buildSelfImproveTask({ diagnosis, seriesId, seriesName, outcome, outcomeReason, counts }) {
+ const slug = slugify(diagnosis.title);
const lines = [
- `Pipeline self-improvement (${diagnosis.area}) — Series Autopilot diagnosed a PortOS automation defect`,
+ `Pipeline self-improvement (${diagnosis.area}/${slug}) — Series Autopilot diagnosed a PortOS automation defect`,
'',
`**${diagnosis.title}**`,
'',
@@ -219,7 +167,7 @@ export function buildSelfImproveTask({ diagnosis, seriesId, seriesName, outcome,
seriesId,
seriesName,
outcome,
- outcomeReason: trimTo(outcomeReason, 500),
+ outcomeReason: trimToClause(outcomeReason, 500),
area: diagnosis.area,
confidence: diagnosis.confidence,
evidence: diagnosis.evidence,
@@ -230,14 +178,14 @@ export function buildSelfImproveTask({ diagnosis, seriesId, seriesName, outcome,
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.
+ // Always isolated, always via a PR, always approval-gated — see the module
+ // header. `approvalRequired` is honored only for internal tasks, which is
+ // why this files as one.
useWorktree: true,
openPR: true,
prCompletion: PR_COMPLETIONS.REVIEW_THEN_MERGE,
simplify: true,
- approvalRequired: !autoApprove,
+ approvalRequired: true,
};
}
@@ -315,11 +263,15 @@ export async function runSelfImproveDiagnosis(sId, record, { outcome, reason = n
seriesName: series?.name || 'unknown',
targetFormat: series?.targetFormat || 'unknown',
outcome,
- outcomeReason: trimTo(reason, 1000) || 'none',
+ 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',
- signalsJson: JSON.stringify(signals, null, 2).slice(0, 40_000),
+ // One COMPACT frame per line, not a pretty-printed array: the frames are flat
+ // and scalar-only, so indenting them puts every key on its own line and
+ // roughly doubles the token count of the single expensive call this feature
+ // makes. One object per line reads the same to the model at half the cost.
+ signalsJson: signals.map((s) => JSON.stringify(s)).join('\n').slice(0, 40_000),
signalCountsJson: JSON.stringify(counts, null, 2),
droppedSignals: dropped,
erroredChecks: [...(record.runState?.editorialCheckErroredIds || [])].join(', ') || 'none',
@@ -328,12 +280,14 @@ export async function runSelfImproveDiagnosis(sId, record, { outcome, reason = n
await recordDomainUsage('cos', { actions: 1 });
const diagnosis = shapeDiagnosis(content);
+ // Nothing filable → nothing to report. A `content` / `none` verdict means the
+ // pipeline behaved, and a low-confidence guess is not worth a line of UI, so
+ // the terminal frame and the marker stay clean rather than carrying a
+ // "diagnosed nothing" payload no reader consumes. The log line is where an
+ // operator can still see the pass ran.
if (!isFilable(diagnosis)) {
- return {
- verdict: diagnosis?.verdict || 'unreadable',
- confidence: diagnosis?.confidence ?? null,
- filed: false,
- };
+ console.log(`🔧 autopilot self-improve — series=${sId.slice(0, 12)} nothing filed (verdict=${diagnosis?.verdict || 'unreadable'} confidence=${diagnosis?.confidence ?? '—'})`);
+ return null;
}
const task = buildSelfImproveTask({
@@ -343,7 +297,6 @@ export async function runSelfImproveDiagnosis(sId, record, { outcome, reason = n
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; });
@@ -351,12 +304,12 @@ export async function runSelfImproveDiagnosis(sId, record, { outcome, reason = n
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,
+ // The durable pointer from "this run" to "that task" — the console line above
+ // is not something a user can go read later.
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.js
index 393b026ede..ca2da89948 100644
--- a/server/services/pipeline/seriesAutopilot/selfImprove.test.js
+++ b/server/services/pipeline/seriesAutopilot/selfImprove.test.js
@@ -37,9 +37,10 @@ vi.mock('../editorial/checkRunner.js', () => ({
}));
const {
- isSignalFrame, noteSignal, summarizeSignals, shouldDiagnose, shapeDiagnosis, isFilable,
- buildSelfImproveTask, runSelfImproveDiagnosis, MAX_SIGNALS, SELF_IMPROVE_MIN_CONFIDENCE,
+ shouldDiagnose, shapeDiagnosis, isFilable, buildSelfImproveTask, runSelfImproveDiagnosis,
+ SELF_IMPROVE_MIN_CONFIDENCE,
} = await import('./selfImprove.js');
+const { isSignalFrame, noteSignal, summarizeSignals, MAX_SIGNALS } = await import('./state.js');
const { PORTOS_APP_ID } = await import('../../../lib/appIdentity.js');
// Minimal run record shaped like the orchestrator's, with the knobs each test needs.
@@ -187,7 +188,6 @@ describe('buildSelfImproveTask', () => {
outcome: 'paused',
outcomeReason: 'editorialReview: ran out of rounds',
counts: { 'verify:round': 2 },
- autoApprove: false,
...over,
});
@@ -199,22 +199,26 @@ describe('buildSelfImproveTask', () => {
expect(task.prCompletion).toBe('review-then-merge');
});
- it('keeps the dedup line stable per area, not per series', () => {
+ it('keeps the dedup line stable per defect, not per series', () => {
+ const firstLine = (t) => t.description.split('\n')[0];
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));
+ // A different area is different work and must NOT collapse onto it...
+ const otherArea = build({ diagnosis: shapeDiagnosis({ ...goodDiagnosis, area: 'runner' }) });
+ expect(firstLine(otherArea)).not.toBe(firstLine(a));
+ // ...and neither must a DIFFERENT defect in the same area. Keying on the
+ // bucket alone would cap PortOS at one open task per area forever and
+ // silently discard every later diagnosis in it.
+ const otherDefect = build({ diagnosis: shapeDiagnosis({ ...goodDiagnosis, title: 'Reverse outline is never refreshed before the checks' }) });
+ expect(firstLine(otherDefect)).not.toBe(firstLine(a));
});
- it('gates on approval unless the user opted into auto-approve', () => {
+ it('always awaits approval — an LLM diagnosis never dispatches a coding agent on its own', () => {
expect(build().approvalRequired).toBe(true);
- expect(build({ autoApprove: true }).approvalRequired).toBe(false);
});
it('carries the run provenance in context, not the manuscript', () => {
@@ -245,21 +249,29 @@ describe('runSelfImproveDiagnosis', () => {
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' });
+ expect(out).toMatchObject({ verdict: 'pipeline', area: 'editorial-check', filed: true, taskId: 'sys-1' });
+ expect(addTask.mock.calls[0][0].approvalRequired).toBe(true);
});
- it('files nothing on a content verdict but still reports it', async () => {
+ it('reports nothing on a content verdict — the pipeline behaved', 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 });
+ expect(out).toBeNull();
});
- it('reports an unreadable response instead of throwing', async () => {
+ it('swallows 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 });
+ expect(out).toBeNull();
+ });
+
+ it('files nothing on a low-confidence pipeline verdict', async () => {
+ llmContent = { ...goodDiagnosis, confidence: 0.4 };
+ const out = await runSelfImproveDiagnosis('series-1', makeRun(), { outcome: 'paused', reason: 'x' });
+ expect(addTask).not.toHaveBeenCalled();
+ expect(out).toBeNull();
});
it('reports a duplicate as tracked, not newly filed', async () => {
diff --git a/server/services/pipeline/seriesAutopilot/session.js b/server/services/pipeline/seriesAutopilot/session.js
index f08ef4d2f0..e4acc836f2 100644
--- a/server/services/pipeline/seriesAutopilot/session.js
+++ b/server/services/pipeline/seriesAutopilot/session.js
@@ -11,8 +11,7 @@ import { addNotification, removeByMetadata, NOTIFICATION_TYPES, PRIORITY_LEVELS
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';
+import { runs, autopilotEvents, noteSignal } from './state.js';
// ---------------------------------------------------------------------------
// Run registry helpers (mirror editorialAnalysisRunner.js).
diff --git a/server/services/pipeline/seriesAutopilot/state.js b/server/services/pipeline/seriesAutopilot/state.js
index 909a8e35ec..e07d86c05b 100644
--- a/server/services/pipeline/seriesAutopilot/state.js
+++ b/server/services/pipeline/seriesAutopilot/state.js
@@ -30,3 +30,74 @@ autopilotEvents.setMaxListeners(0);
// (user stop), and `error` (run-ending throw) are exhaustive of the run's exit
// frames (see the fire-and-forget coordinator in startSeriesAutopilot).
export const AUTOPILOT_TERMINAL_TYPES = new Set(['complete', 'paused', 'canceled', 'error']);
+
+// ---------------------------------------------------------------------------
+// Diagnosable-signal retention (feeds the opt-in self-improvement post-mortem,
+// `selfImprove.js`). It lives here rather than there because it is run-RECORD
+// state — `session.js#broadcast` writes it on the record this module owns, and
+// keeping it here is what lets the diagnosis import the registry instead of the
+// registry importing the diagnosis (an import cycle through session.js, which
+// this package has been bitten by before — see the barrel's TDZ note).
+// ---------------------------------------------------------------------------
+
+// Frame types worth keeping as diagnosis evidence. Deliberately excludes the
+// high-volume happy-path frames (`start` / `step:start` / `step:complete`) — the
+// step SEQUENCE is reconstructable from the outcome, while these carry the
+// "something went sideways" detail a diagnosis actually reasons over. The
+// terminal frames (`complete` / `paused` / `error`) are excluded too: the
+// diagnosis runs BEFORE them, and their content reaches it 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 log. A long run emits a `verify:round` per gate round
+// and a `check:complete` per check per pass; past this the overflow 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 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.
+ */
+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 entries + per-type counts 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 };
+}