Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor: single opt-in predicate + signal classification for the diagnosis passes
[._.]/ Adam Eivy5af8204ba155
diff --git a/server/services/pipeline/seriesAutopilot/diagnosisCore.js b/server/services/pipeline/seriesAutopilot/diagnosisCore.jsindex 4c73793e82..ef3da49570 100644--- a/server/services/pipeline/seriesAutopilot/diagnosisCore.js+++ b/server/services/pipeline/seriesAutopilot/diagnosisCore.js@@ -36,6 +36,25 @@ export const SELF_IMPROVE_AREAS = Object.freeze(['editorial-check', 'pipeline-step', 'prompt', 'runner', 'config',]);+// The run-option flags that opt a run into diagnosis telemetry. The retention+// gate (`state.js#noteSignal`) derives from this list, so a future diagnosis+// consumer adds its flag HERE and its frames are retained — no third predicate+// to remember in another file.+const DIAGNOSIS_OPT_IN_FLAGS = Object.freeze(['selfImprove', 'observer']);++/**+ * Is this specific diagnosis pass enabled for the run? Pure. The single+ * spelling of "opted in, and in execute mode" — a dry-run has no telemetry+ * worth diagnosing. Consumed by `observerEnabled`, `shouldDiagnose`, and the+ * retention gate, so the three sites can't drift.+ */+export const diagnosisEnabled = (run, flag) => !!run+ && run.mode === 'execute'+ && run.options?.[flag] === true;++/** Did the run opt into ANY diagnosis pass (so its telemetry is worth retaining)? Pure. */+export const diagnosisOptedIn = (run) => DIAGNOSIS_OPT_IN_FLAGS.some((flag) => diagnosisEnabled(run, flag));+/*** Sanitize the LLM's diagnosis into the fixed shape both passes rely on.* Returns null when the payload can't be read as a verdict at all. Pure.@@ -77,6 +96,17 @@ export function isActionableDiagnosis(diagnosis, minConfidence) {&& !!diagnosis.proposedChange;}+// The retained frame types that mean the automation itself misbehaved (vs the+// loop/informational frames — `verify:round`, `note`, `revision:*` — which are+// the system working). The ONE classification both evidence predicates derive+// from: `hasAutomationSignals` (terminal) uses it as-is; the observer's mid-run+// trigger adds `gap:filed` on top (see observer.js#isMidrunTrigger). A+// `check:complete` frame counts only when the check actually THREW — the+// retention filter also keeps `skipped` frames, which are usually benign.+const AUTOMATION_SIGNAL_TYPES = new Set(['child:retry', 'child:escalate', 'step:skip']);+export const isAutomationSignal = (s) => AUTOMATION_SIGNAL_TYPES.has(s.type)+ || (s.type === 'check:complete' && !!s.error);+/*** 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.@@ -85,10 +115,7 @@ 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) => (- s.type === 'child:retry' || s.type === 'child:escalate' || s.type === 'step:skip'- || (s.type === 'check:complete' && s.error)- ));+ return (record?.signals || []).some(isAutomationSignal);}/**diff --git a/server/services/pipeline/seriesAutopilot/observer.js b/server/services/pipeline/seriesAutopilot/observer.jsindex fea2557ed7..9b05795cca 100644--- a/server/services/pipeline/seriesAutopilot/observer.js+++ b/server/services/pipeline/seriesAutopilot/observer.js@@ -51,7 +51,8 @@ import { summarizeSignals } from './state.js';import { broadcast, providerOverrideOpts } from './session.js';import {DIAGNOSIS_MAX_FILED, SELF_IMPROVE_AREAS, buildDiagnosisStageVars, buildDiagnosisTask,- isActionableDiagnosis, shapeDiagnosis, terminalWarrantsDiagnosis,+ diagnosisEnabled, isActionableDiagnosis, isAutomationSignal, shapeDiagnosis,+ terminalWarrantsDiagnosis,} from './diagnosisCore.js';const OBSERVER_STAGE = 'pipeline-observer';@@ -72,24 +73,21 @@ export const OBSERVER_MIN_CONFIDENCE = 0.7;// (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);+// What justifies spending a MID-RUN pass: the shared automation-misbehavior+// classification (`diagnosisCore.js#isAutomationSignal`) plus `gap:filed` — a+// filed gap is worth diagnosing the moment it happens, while the terminal+// ladder already reaches it through the runState gap counters. Deliberately+// narrower than the full retained 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.+const isMidrunTrigger = (s) => isAutomationSignal(s) || s.type === 'gap:filed';/*** Is the observer active for this run? Pure. Exported for the orchestrator's* postMortem supersession gate, so "observer on" means the same thing at both* decision points.*/-export const observerEnabled = (record) => !!record- && record.options?.observer === true- && record.mode === 'execute';+export const observerEnabled = (record) => diagnosisEnabled(record, 'observer');/** The retained frames the run has emitted since the last observer pass. Pure. */export function freshSignals(record) {@@ -100,19 +98,14 @@ export function freshSignals(record) {* Should the observer spend a pass after this step? Pure. Requires the opt-in,* a remaining mid-run pass, budget not already known-exhausted, and at least* one triggering frame past the cursor — a step that went cleanly costs- * nothing. This runs after EVERY step, so the scan is by index (no slice- * allocation on the happy path).+ * nothing.*/export function shouldObserveStep(record) {if (!observerEnabled(record)) return false;const rs = record.runState || {};if (rs.observerBudgetExhausted) return false;if ((rs.observerPassesRun || 0) >= OBSERVER_MAX_MIDRUN_PASSES) return false;- const signals = record.signals || [];- for (let i = rs.observerCursor || 0; i < signals.length; i += 1) {- if (isMidrunTrigger(signals[i])) return true;- }- return false;+ return freshSignals(record).some(isMidrunTrigger);}/**diff --git a/server/services/pipeline/seriesAutopilot/observer.test.js b/server/services/pipeline/seriesAutopilot/observer.test.jsindex 002d5b858f..cde8323c58 100644--- a/server/services/pipeline/seriesAutopilot/observer.test.js+++ b/server/services/pipeline/seriesAutopilot/observer.test.js@@ -38,8 +38,8 @@ const {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 { shapeDiagnosis, SELF_IMPROVE_AREAS, isAutomationSignal } = await import('./diagnosisCore.js');+const { noteSignal, SIGNAL_FRAME_TYPES } = 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.@@ -86,6 +86,17 @@ describe('signal retention for observer-only runs', () => {});});+describe('trigger/retention alignment', () => {+ it('every frame type that can trigger a pass is also retained by noteSignal', () => {+ // A trigger type missing from the retention set would never fire — the+ // frame is dropped before the observer can see it — with no error anywhere.+ const triggerTypes = ['child:retry', 'child:escalate', 'step:skip', 'gap:filed', 'check:complete'];+ for (const type of triggerTypes) expect(SIGNAL_FRAME_TYPES.has(type)).toBe(true);+ expect(isAutomationSignal({ type: 'check:complete', error: 'boom' })).toBe(true);+ expect(isAutomationSignal({ type: 'check:complete' })).toBe(false);+ });+});+describe('shouldObserveStep', () => {it('requires the opt-in and execute mode', () => {expect(shouldObserveStep(makeRun({ options: { observer: false }, signals: [{ type: 'child:retry' }] }))).toBe(false);diff --git a/server/services/pipeline/seriesAutopilot/orchestrator.js b/server/services/pipeline/seriesAutopilot/orchestrator.jsindex b124d8adb6..dc69eabcd5 100644--- a/server/services/pipeline/seriesAutopilot/orchestrator.js+++ b/server/services/pipeline/seriesAutopilot/orchestrator.js@@ -305,8 +305,8 @@ export async function startSeriesAutopilot(sId, options = {}) {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: 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() });+ await persistMarker(sId, { status: 'done', runId, currentStep: null, craftGapIssues, craftGapFindings, editorialCheckErrors, ...pm });+ broadcast(sId, { type: 'complete', runId, steps: ordinal, craftGapIssues, craftGapFindings, editorialCheckErrors, editorialCheckErroredIds, ...pm, 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;}@@ -367,8 +367,8 @@ export async function startSeriesAutopilot(sId, options = {}) {// rides it (a client tears its stream down on `paused`). No-ops unless// the run opted into self-improvement.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 persistMarker(sId, { status: 'paused', runId, currentStep: step.kind, residualFindings: result.residual || [], lastError: result.reason, pauseKind: result.pauseKind || null, healthBreakdown: result.healthBreakdown || null, ...pm });+ broadcast(sId, { type: 'paused', runId, scope: step.kind, reason: result.reason, residualFindings: result.residual || [], pauseKind: result.pauseKind || null, healthBreakdown: result.healthBreakdown || null, ...pm, 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@@ -402,8 +402,8 @@ export async function startSeriesAutopilot(sId, options = {}) {// ride the `error` frame + marker rather than arriving after the client// has torn its stream down.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 persistMarker(sId, { status: 'error', runId, lastError: message, ...pm });+ broadcast(sId, { type: 'error', runId, error: message, ...pm, 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.jsindex ae41a62a05..5a16a14a80 100644--- a/server/services/pipeline/seriesAutopilot/selfImprove.js+++ b/server/services/pipeline/seriesAutopilot/selfImprove.js@@ -58,7 +58,7 @@ import { getSeries } from '../series.js';import { summarizeSignals } from './state.js';import { broadcast, providerOverrideOpts } from './session.js';import {- SELF_IMPROVE_AREAS, buildDiagnosisStageVars, buildDiagnosisTask,+ SELF_IMPROVE_AREAS, buildDiagnosisStageVars, buildDiagnosisTask, diagnosisEnabled,hasAutomationSignals, isActionableDiagnosis, shapeDiagnosis, terminalWarrantsDiagnosis,} from './diagnosisCore.js';@@ -73,8 +73,7 @@ const SELF_IMPROVE_STAGE = 'pipeline-self-improve';* opt-in/execute predicate composed with the shared terminal ladder.*/export function shouldDiagnose(record, outcome) {- if (!record || record.options?.selfImprove !== true || record.mode !== 'execute') return false;- return terminalWarrantsDiagnosis(record, outcome);+ return diagnosisEnabled(record, 'selfImprove') && terminalWarrantsDiagnosis(record, outcome);}// A diagnosis below this confidence is dropped rather than filed — a speculativediff --git a/server/services/pipeline/seriesAutopilot/state.js b/server/services/pipeline/seriesAutopilot/state.jsindex 10926ac22a..0147d96755 100644--- a/server/services/pipeline/seriesAutopilot/state.js+++ b/server/services/pipeline/seriesAutopilot/state.js@@ -5,6 +5,10 @@*/import { EventEmitter } from 'events';+// Safe to import at module evaluation: diagnosisCore is a deliberate LEAF+// (lib/ helpers only), outside the session.js import cycle this file's header+// warns about.+import { diagnosisOptedIn } from './diagnosisCore.js';// runs: Map<seriesId, { runId, clients[], lastPayload, startPayload, cancelRequested,// finished, cleanupTimer, startedAt, mode, options, runState, activeChild }>@@ -76,13 +80,12 @@ 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 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.+ * run that opted into no diagnosis pass (`diagnosisOptedIn` — which also+ * excludes dry-runs, whose telemetry isn't worth diagnosing) does a few+ * property reads and returns. True when retained.*/export function noteSignal(run, payload) {- if (!run || run.mode !== 'execute') return false;- if (run.options?.selfImprove !== true && run.options?.observer !== true) return false;+ if (!diagnosisOptedIn(run)) return false;if (!isSignalFrame(payload)) return false;if (!run.signals) run.signals = [];if (run.signals.length >= MAX_SIGNALS) {