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

refactor: extract shared diagnosis core; unblock the step loop from observer passes

[._.]/ Adam Eivye1850fe29a00
diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.js
index 8d36f688fe..48e9b91184 100644
--- a/server/services/pipeline/series.js
+++ b/server/services/pipeline/series.js
@@ -22,6 +22,7 @@ import { sanitizeSeverityWeights, sanitizeBlockingSeverities } from '../../lib/e
import { sanitizeOrigin } from '../../lib/sharingOrigin.js';
import { sanitizeSoftDeleteFields } from '../../lib/syncWire.js';
import { persistedRenderPinFields } from '../../lib/renderTargets.js';
+import { DIAGNOSIS_MAX_FILED } from './seriesAutopilot/diagnosisCore.js';
import {
maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes,
deleteSyncBaseHash,
@@ -217,40 +218,36 @@ const toCount = (v) => (Number.isInteger(v) && v >= 0 ? v : 0);
// 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.
+// One bounded task-reference shape, shared by both diagnosis markers below —
+// they feed the same status banner, so the field caps must not drift.
+const sanitizeDiagnosisRef = (raw) => ({
+ 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,
+});
+
const sanitizeAutopilotSelfImprove = (raw) => {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
if (raw.verdict !== 'pipeline') return null;
- return {
- 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,
- };
+ return { verdict: 'pipeline', ...sanitizeDiagnosisRef(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;
+// was filed, so an empty list reads as null. The cap is the producer's own
+// (DIAGNOSIS_MAX_FILED — diagnosisCore is a leaf, so this import can't cycle).
+// Same transient-marker rationale as pauseKind / craftGap* / selfImprove: no
+// schema-gate bump.
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))
+ .map((f) => (f && typeof f === 'object' ? sanitizeDiagnosisRef(f) : null))
.filter(Boolean)
- .slice(0, AUTOPILOT_OBSERVER_MAX_FILED);
+ .slice(0, DIAGNOSIS_MAX_FILED);
if (filed.length === 0) return null;
return { passes: toCount(raw.passes), filed };
};
diff --git a/server/services/pipeline/seriesAutopilot.js b/server/services/pipeline/seriesAutopilot.js
index 9c01af2600..9d2f2b882f 100644
--- a/server/services/pipeline/seriesAutopilot.js
+++ b/server/services/pipeline/seriesAutopilot.js
@@ -77,6 +77,7 @@ export * from './seriesAutopilot/config.js';
export * from './seriesAutopilot/convergence.js';
export * from './seriesAutopilot/stepResolver.js';
export * from './seriesAutopilot/session.js';
+export * from './seriesAutopilot/diagnosisCore.js';
export * from './seriesAutopilot/selfImprove.js';
export * from './seriesAutopilot/observer.js';
export * from './seriesAutopilot/childRuns.js';
diff --git a/server/services/pipeline/seriesAutopilot/diagnosisCore.js b/server/services/pipeline/seriesAutopilot/diagnosisCore.js
new file mode 100644
index 0000000000..4c73793e82
--- /dev/null
+++ b/server/services/pipeline/seriesAutopilot/diagnosisCore.js
@@ -0,0 +1,226 @@
+/**
+ * Series Autopilot — shared diagnosis core for the two pipeline-improvement
+ * passes: the self-improve post-mortem (`selfImprove.js`, human-approved) and
+ * the observing orchestrator (`observer.js`, auto-dispatched).
+ *
+ * DELIBERATELY A LEAF: this module imports only `lib/` helpers — never
+ * `./session.js`, `../series.js`, or anything else inside this package's known
+ * import cycle (session → autoRunner → … → the barrel; see the barrel's TDZ
+ * note). That is what lets both siblings dereference these exports at
+ * module-evaluation time (`OBSERVER_AREAS` derives from `SELF_IMPROVE_AREAS`
+ * with a spread) instead of each keeping a hand-mirrored copy. Keep it pure:
+ * an import added here from inside the cycle re-introduces the TDZ crash this
+ * module exists to avoid.
+ *
+ * What lives here is the shared CONTRACT — the verdict/area vocabulary, the
+ * diagnosis shape, the evidence predicates, the prompt context both stage
+ * templates consume, and the filed-task frame (dedup key + brief layout). The
+ * POLICY deltas (confidence bars, approval, pass gating/windowing) stay in the
+ * feature modules where they read as explicit decisions.
+ */
+
+import { PORTOS_APP_ID } from '../../../lib/appIdentity.js';
+import { PR_COMPLETIONS } from '../../../lib/prDisposition.js';
+import { trimToClause } from '../../../lib/storyBible.js';
+import { slugify } from '../../../lib/planIds.js';
+
+// 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.
+const DIAGNOSIS_VERDICTS = Object.freeze(['pipeline', 'content', 'none']);
+
+// Where in PortOS the proposed fix belongs. Prefixes the filed task's dedup key
+// (see buildDiagnosisTask) and tells a reader which part of the system the
+// brief is about before they open it. The observer extends this with `ui`.
+export const SELF_IMPROVE_AREAS = Object.freeze([
+ 'editorial-check', 'pipeline-step', 'prompt', 'runner', 'config',
+]);
+
+/**
+ * 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.
+ * `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, areas = SELF_IMPROVE_AREAS) {
+ if (!raw || typeof raw !== 'object') return null;
+ const verdict = DIAGNOSIS_VERDICTS.includes(raw.verdict) ? raw.verdict : null;
+ if (!verdict) return null;
+ const confidence = Number.isFinite(raw.confidence)
+ ? Math.min(1, Math.max(0, raw.confidence))
+ : 0;
+ return {
+ verdict,
+ confidence,
+ area: areas.includes(raw.area) ? raw.area : 'pipeline-step',
+ title: trimToClause(raw.title, 160),
+ problem: trimToClause(raw.problem, 2000),
+ evidence: Array.isArray(raw.evidence)
+ ? raw.evidence.map((e) => trimToClause(e, 400)).filter(Boolean).slice(0, 8)
+ : [],
+ proposedChange: trimToClause(raw.proposedChange, 2000),
+ risks: trimToClause(raw.risks, 800),
+ };
+}
+
+/**
+ * Should this shaped diagnosis produce work? Pure — a pipeline verdict that
+ * clears the caller's confidence bar and actually says what to change. The bar
+ * is a parameter because it is POLICY: the human-approved post-mortem accepts
+ * more speculation than the auto-merging observer.
+ */
+export function isActionableDiagnosis(diagnosis, minConfidence) {
+ return !!diagnosis
+ && diagnosis.verdict === 'pipeline'
+ && diagnosis.confidence >= minConfidence
+ && !!diagnosis.title
+ && !!diagnosis.proposedChange;
+}
+
+/**
+ * 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.
+ */
+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)
+ ));
+}
+
+/**
+ * Does a run terminal carry evidence worth spending a diagnosis call on? Pure.
+ * A pause or an error always does; a cancel never (the user stopped it — there
+ * is no failure to explain); a `done` run only when its telemetry says the
+ * automation limped. Each pass composes this with its own enable predicate.
+ */
+export function terminalWarrantsDiagnosis(record, outcome) {
+ if (outcome === 'paused' || outcome === 'error') return true;
+ if (outcome !== 'done') return false;
+ return hasAutomationSignals(record);
+}
+
+// The conductor's step order, as prose the diagnosis prompts 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.
+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',
+ 'foundationGate — weighted judge of world/characters/arc before drafting',
+ 'beatSheet — per-volume beat sheets',
+ 'beatContinuity — whole-manuscript beat-level continuity loop',
+ 'textStages — per-issue prose + scripts',
+ 'scriptVerify — structural page/panel parse gate + advisory craft gate',
+ 'editorialReview — series-level manuscript completeness review → fix loop',
+ 'reverseOutline — refresh scene segmentation for the checks that consume it',
+ 'editorialChecks — registry-driven editorial checks (deterministic + LLM)',
+ 'editorialHealthGate — readiness gate over open blocking findings',
+ 'revisionCycle — opt-in iterate-to-quality adversarial cut + judge loop',
+ 'canonVerify — every drawn canon noun has a description',
+ 'visualDraft — queue draft renders for covers + interior pages',
+ 'produceTeaser — opt-in Creative Director teaser video',
+].join('\n');
+
+// The run's effective gate configuration, as 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".
+export const gateConfigOf = (options) => ({
+ maxArcVerifyRounds: options.maxArcVerifyRounds,
+ maxBeatContinuityRounds: options.maxBeatContinuityRounds,
+ maxEditorialRounds: options.maxEditorialRounds,
+ maxFoundationRounds: options.maxFoundationRounds,
+ foundationGate: options.foundationGate,
+ foundationThreshold: options.foundationThreshold,
+ readinessGate: options.readinessGate,
+ checkFindingsPauseThreshold: options.checkFindingsPauseThreshold,
+ revisionEnabled: options.revisionEnabled,
+ includeVisual: options.includeVisual,
+ target: options.target,
+});
+
+/**
+ * The prompt variables both diagnosis stage templates share. Pure over the run
+ * record + pre-fetched context; each caller spreads its phase-specific vars
+ * (`outcome`/`outcomeReason`, and the observer's `phase`/`priorFilings`) on
+ * top. One builder so the encoding below can't drift between the two prompts.
+ */
+export function buildDiagnosisStageVars(record, { series, checkPlan, signals, counts, dropped }) {
+ const rs = record.runState || {};
+ return {
+ seriesName: series?.name || 'unknown',
+ targetFormat: series?.targetFormat || 'unknown',
+ stepSequence: STEP_SEQUENCE,
+ gateConfigJson: JSON.stringify(gateConfigOf(record.options || {}), null, 2),
+ enabledChecks: (checkPlan?.checks || []).map((c) => `${c.id} (${c.kind})`).join(', ') || 'none',
+ // 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 call. 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: [...(rs.editorialCheckErroredIds || [])].join(', ') || 'none',
+ craftGapIssues: rs.scriptCraftGapIssues?.size || 0,
+ };
+}
+
+// Ceiling on the observer's per-run filing log — shared with the marker
+// sanitizer in ../series.js so the wire cap and the producer cap can't drift.
+export const DIAGNOSIS_MAX_FILED = 5;
+
+/**
+ * Shape the CoS task for an actionable diagnosis. Pure, so the dedup key and
+ * the agent-facing brief are testable without a task store. The callers supply
+ * the wording deltas (`descriptionPrefix`, `leadLine`, `tailLines`) and the ONE
+ * policy bit that separates the passes (`approvalRequired`).
+ *
+ * `description` is ONE LINE, and that is a hard requirement, not a style
+ * choice: `generateTasksMarkdown` writes the description verbatim into a single
+ * `- [ ] #id | PRIORITY | <description>` row (only *metadata* values go through
+ * `escapeNewlines`). A multi-line description therefore spills its tail into
+ * TASKS.md as stray un-parsed lines AND is truncated to its first line on the
+ * next read — silently dropping the entire brief, so the agent would receive a
+ * defect report with no defect in it. The brief lives in `context`, which is
+ * newline-escaped and round-trips intact.
+ *
+ * That one line is also 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 defect in it — and a task that ends up `blocked` counts as a
+ * duplicate too, which would mute that area permanently. The slug is the
+ * kebab-cased title, so the row stays readable in TASKS.md.
+ */
+export function buildDiagnosisTask({ diagnosis, descriptionPrefix, leadLine, tailLines, approvalRequired }) {
+ const slug = slugify(diagnosis.title);
+ const brief = [
+ leadLine,
+ '',
+ 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('', ...tailLines);
+ return {
+ description: `${descriptionPrefix} (${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,
+ };
+}
diff --git a/server/services/pipeline/seriesAutopilot/observer.js b/server/services/pipeline/seriesAutopilot/observer.js
index cbf899850f..fea2557ed7 100644
--- a/server/services/pipeline/seriesAutopilot/observer.js
+++ b/server/services/pipeline/seriesAutopilot/observer.js
@@ -31,7 +31,8 @@
* 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.
+ * near-duplicate tasks under different dedup keys. The vocabulary, shape, and
+ * task/prompt frames shared with the post-mortem live in `diagnosisCore.js`.
*
* 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
@@ -39,32 +40,28 @@
* 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';
+import {
+ DIAGNOSIS_MAX_FILED, SELF_IMPROVE_AREAS, buildDiagnosisStageVars, buildDiagnosisTask,
+ isActionableDiagnosis, shapeDiagnosis, terminalWarrantsDiagnosis,
+} from './diagnosisCore.js';
const OBSERVER_STAGE = 'pipeline-observer';
-// SELF_IMPROVE_AREAS plus `ui` — the observer's fix can also be "the autopilot
+// The base vocabulary 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',
-]);
+// (Safe to derive with a spread: diagnosisCore is a leaf, outside this
+// package's session.js import cycle.)
+export const OBSERVER_AREAS = Object.freeze([...SELF_IMPROVE_AREAS, '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
@@ -85,10 +82,12 @@ const MIDRUN_TRIGGER_TYPES = new Set(['child:retry', 'child:escalate', 'step:ski
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
+/**
+ * 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';
@@ -99,75 +98,58 @@ export function freshSignals(record) {
/**
* 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.
+ * 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).
*/
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);
+ 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;
}
/**
- * 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.
+ * Should the observer spend its terminal pass? Pure — the enable predicate
+ * composed with the shared terminal ladder (pause/error always, cancel never,
+ * `done` only when 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);
+ return observerEnabled(record) && terminalWarrantsDiagnosis(record, outcome);
}
/** 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;
+ return isActionableDiagnosis(diagnosis, OBSERVER_MIN_CONFIDENCE);
}
/**
- * 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).
+ * Shape the auto-approved CoS task for a dispatchable diagnosis. Pure. The
+ * dedup key/one-line-description contract and the brief layout live in
+ * `diagnosisCore.js#buildDiagnosisTask`; this supplies the observer's wording
+ * and its one deliberate policy divergence, `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.
*/
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,
+ return buildDiagnosisTask({
+ diagnosis,
+ descriptionPrefix: 'Pipeline orchestrator improvement',
+ leadLine: `The autopilot's observing orchestrator diagnosed a PortOS pipeline defect mid-flight: ${diagnosis.title}`,
+ tailLines: [
+ `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.',
+ ],
approvalRequired: false,
- };
+ });
}
/**
@@ -180,18 +162,27 @@ export function buildObserverTask({ diagnosis, seriesId, seriesName, phase, outc
* 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);
+ const terminal = phase === 'terminal';
+ const gate = terminal ? shouldObserveTerminal(record, outcome) : shouldObserveStep(record);
if (!gate) return null;
+ const rs = record.runState || {};
const budget = await getDomainBudgetStatus('cos');
- if (!budget.withinBudget) return null;
+ if (!budget.withinBudget) {
+ // Latch mid-run passes off for the rest of the run: without this, the
+ // untaken trigger frame keeps passing the gate and every remaining step
+ // re-reads the usage file just to learn "still no budget". The terminal
+ // pass deliberately ignores the latch — the day (and the budget) may have
+ // rolled over by then, and it re-checks exactly once.
+ if (!terminal) rs.observerBudgetExhausted = true;
+ 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') {
+ const windowed = terminal ? (record.signals || []) : freshSignals(record);
+ if (!terminal) {
rs.observerCursor = (record.signals || []).length;
rs.observerPassesRun = (rs.observerPassesRun || 0) + 1;
}
@@ -206,21 +197,10 @@ export async function runObserverPass(sId, record, { phase, stepKind = null, out
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`,
+ ...buildDiagnosisStageVars(record, { series, checkPlan, signals: windowed, counts, dropped }),
+ 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',
@@ -237,7 +217,7 @@ export async function runObserverPass(sId, record, { phase, stepKind = null, out
diagnosis,
seriesId: sId,
seriesName: series?.name || null,
- phase: phase === 'terminal' ? 'at the terminal' : `after the ${stepKind} step`,
+ phase: terminal ? 'at the terminal' : `after the ${stepKind} step`,
outcome,
outcomeReason: reason,
counts,
@@ -254,7 +234,7 @@ export async function runObserverPass(sId, record, { phase, stepKind = null, out
};
if (result) {
if (!rs.observerFindings) rs.observerFindings = [];
- if (rs.observerFindings.length < OBSERVER_MAX_FINDINGS) rs.observerFindings.push(summary);
+ if (rs.observerFindings.length < DIAGNOSIS_MAX_FILED) 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'}`);
diff --git a/server/services/pipeline/seriesAutopilot/observer.test.js b/server/services/pipeline/seriesAutopilot/observer.test.js
index 489d589db4..002d5b858f 100644
--- a/server/services/pipeline/seriesAutopilot/observer.test.js
+++ b/server/services/pipeline/seriesAutopilot/observer.test.js
@@ -150,9 +150,7 @@ describe('isDispatchable', () => {
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);
+ expect(OBSERVER_AREAS).toEqual([...SELF_IMPROVE_AREAS, 'ui']);
});
});
@@ -208,12 +206,18 @@ describe('runObserverPass (mid-run)', () => {
expect(run.runState.observerPassesRun).toBe(0);
});
- it('spends nothing when the daily budget is exhausted', async () => {
+ it('spends nothing when the daily budget is exhausted, and latches mid-run passes off', 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();
+ // The untaken trigger frame must not re-poll the usage file on every
+ // remaining step — the run is latched off for mid-run passes…
+ expect(run.runState.observerBudgetExhausted).toBe(true);
+ expect(shouldObserveStep(run)).toBe(false);
+ // …but the terminal pass re-checks once (the budget may have rolled over).
+ expect(shouldObserveTerminal(run, 'paused')).toBe(true);
});
it('dispatches an auto-approved task, bills one action and consumes the window', async () => {
diff --git a/server/services/pipeline/seriesAutopilot/orchestrator.js b/server/services/pipeline/seriesAutopilot/orchestrator.js
index 2614a3313d..b124d8adb6 100644
--- a/server/services/pipeline/seriesAutopilot/orchestrator.js
+++ b/server/services/pipeline/seriesAutopilot/orchestrator.js
@@ -21,7 +21,7 @@ import {
resolveAutopilotUnlockForRun, resolveAutopilotSelfImprove, resolveAutopilotObserver,
} from './config.js';
import { runSelfImproveDiagnosis } from './selfImprove.js';
-import { runObserverPass, summarizeObserver } from './observer.js';
+import { observerEnabled, 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';
@@ -200,7 +200,11 @@ export async function startSeriesAutopilot(sId, options = {}) {
// 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) {
+ if (observerEnabled(record)) {
+ // Let any in-flight mid-run pass land first — its frames must precede
+ // the terminal frame (SSE replays only the last payload), and its filing
+ // must be in the summary the marker persists.
+ await observerIdle();
await runObserverPass(sId, record, { phase: 'terminal', outcome, reason })
.catch((err) => {
console.log(`⚠️ autopilot: observer terminal pass failed for ${sId.slice(0, 12)}: ${err.message}`);
@@ -217,13 +221,26 @@ export async function startSeriesAutopilot(sId, options = {}) {
// 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: observer pass failed for ${sId.slice(0, 12)}: ${err.message}`);
- return null;
- });
+ // observer.js#shouldObserveStep — a clean step costs nothing). NOT awaited in
+ // the step loop — the pass rides a per-run promise chain so a heavy-model
+ // diagnosis never stalls the next pipeline step (the whole point is fixing
+ // the pipeline WHILE the run continues); the gate re-evaluates when the
+ // chained pass actually runs, so back-to-back enqueues collapse into cheap
+ // no-ops once the first pass consumes the window. Best-effort like the
+ // post-mortem: observing must never break the run.
+ let observerChain = Promise.resolve();
+ const observeStep = (step) => {
+ if (!observerEnabled(record)) return;
+ observerChain = observerChain
+ .then(() => runObserverPass(sId, record, { phase: 'step', stepKind: step.kind }))
+ .catch((err) => {
+ console.log(`⚠️ autopilot: observer pass failed for ${sId.slice(0, 12)}: ${err.message}`);
+ return null;
+ });
+ };
+ // Every terminal awaits this before broadcasting: a pass landing after the
+ // terminal frame would clobber the SSE replay payload clients resume from.
+ const observerIdle = () => observerChain.catch(() => null);
// Fire-and-forget coordinator. The try/catch is the permitted boundary use —
// an unhandled LLM rejection here would crash the process on Node ≥15.
@@ -369,10 +386,12 @@ 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);
+ observeStep(step);
}
- // Cancelled.
+ // Cancelled. No post-mortem (nothing to explain), but an in-flight
+ // observer pass must still land before the terminal frame.
+ await observerIdle();
await persistMarker(sId, { status: 'paused', runId, currentStep: null, lastError: 'canceled by user' });
broadcast(sId, { type: 'canceled', runId, steps: ordinal, completedAt: new Date().toISOString() });
console.log(`🛑 autopilot canceled — series=${sId.slice(0, 12)} after ${ordinal} steps`);
diff --git a/server/services/pipeline/seriesAutopilot/selfImprove.js b/server/services/pipeline/seriesAutopilot/selfImprove.js
index 5ae6ff9167..ae41a62a05 100644
--- a/server/services/pipeline/seriesAutopilot/selfImprove.js
+++ b/server/services/pipeline/seriesAutopilot/selfImprove.js
@@ -28,14 +28,19 @@
* 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.
+ * CoS approval queue, not a per-series checkbox. (The observing orchestrator
+ * — `observer.js` — is the ONE deliberate exception: the user opts into its
+ * unattended dispatch explicitly, and it supersedes this pass at the
+ * terminal when both are enabled.)
*
* The signal log is captured passively: `state.js#noteSignal`, called from
* `session.js#broadcast`, retains the same SSE frames the run already emits — so
* a telemetry frame a future step adds becomes diagnosable evidence with no
* extra instrumentation. It lives in `state.js` (the run-registry owner) rather
* than here so this module can import the registry instead of the registry
- * importing the diagnosis.
+ * importing the diagnosis. The vocabulary, shape, and task/prompt frames shared
+ * with the observer live in `diagnosisCore.js` (a deliberate leaf — see its
+ * header) and are re-exported here for the existing import surface.
*
* PRIVACY: the diagnosis prompt asks for a defect report about PortOS's code and
* prompts, explicitly NOT about the story — and `shapeDiagnosis` bounds every
@@ -43,210 +48,67 @@
* 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 {
+ SELF_IMPROVE_AREAS, buildDiagnosisStageVars, buildDiagnosisTask,
+ hasAutomationSignals, isActionableDiagnosis, shapeDiagnosis, terminalWarrantsDiagnosis,
+} from './diagnosisCore.js';
+
+// Re-export the shared diagnosis vocabulary under this module's established
+// import surface (tests and the barrel reach it here).
+export { SELF_IMPROVE_AREAS, hasAutomationSignals, shapeDiagnosis };
const SELF_IMPROVE_STAGE = 'pipeline-self-improve';
/**
- * Does this run carry evidence worth spending a diagnosis call on? Pure.
- *
- * `outcome` is the run's terminal disposition: 'done' | 'paused' | 'error'. A
- * cancel is never diagnosed — the user stopped it, so there is no failure to
- * explain. A pause or an error always is. A `done` run only qualifies when its
- * telemetry says the automation limped: a check threw, a child had to be
- * retried/escalated, a step was skipped, or the advisory craft gate filed gaps.
+ * Does this run carry evidence worth spending a diagnosis call on? Pure — the
+ * 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;
- if (outcome === 'paused' || outcome === 'error') return true;
- if (outcome !== 'done') return false;
- 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) => (
- s.type === 'child:retry' || s.type === 'child:escalate' || s.type === 'step:skip'
- || (s.type === 'check:complete' && s.error)
- ));
+ return terminalWarrantsDiagnosis(record, outcome);
}
-// 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. 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. 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',
-]);
-
// 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;
-/**
- * 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. `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, 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;
- const confidence = Number.isFinite(raw.confidence)
- ? Math.min(1, Math.max(0, raw.confidence))
- : 0;
- return {
- verdict,
- confidence,
- area: areas.includes(raw.area) ? raw.area : 'pipeline-step',
- title: trimToClause(raw.title, 160),
- problem: trimToClause(raw.problem, 2000),
- evidence: Array.isArray(raw.evidence)
- ? raw.evidence.map((e) => trimToClause(e, 400)).filter(Boolean).slice(0, 8)
- : [],
- proposedChange: trimToClause(raw.proposedChange, 2000),
- risks: trimToClause(raw.risks, 800),
- };
-}
-
/**
* Should this shaped diagnosis produce a CoS task? Pure — a pipeline verdict
* that clears the confidence bar and actually says what to change.
*/
export function isFilable(diagnosis) {
- return !!diagnosis
- && diagnosis.verdict === 'pipeline'
- && diagnosis.confidence >= SELF_IMPROVE_MIN_CONFIDENCE
- && !!diagnosis.title
- && !!diagnosis.proposedChange;
+ return isActionableDiagnosis(diagnosis, SELF_IMPROVE_MIN_CONFIDENCE);
}
/**
- * Shape the CoS task for a filable diagnosis. Pure, so the dedup key and the
- * agent-facing brief are testable without a task store.
- *
- * `description` is ONE LINE, and that is a hard requirement, not a style choice:
- * `generateTasksMarkdown` writes the description verbatim into a single
- * `- [ ] #id | PRIORITY | <description>` row (only *metadata* values go through
- * `escapeNewlines`). A multi-line description therefore spills its tail into
- * TASKS.md as stray un-parsed lines AND is truncated to its first line on the
- * next read — silently dropping the entire brief, so the agent would receive a
- * defect report with no defect in it. The brief lives in `context`, which is
- * newline-escaped and round-trips intact.
- *
- * That one line is also 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. The slug is the
- * kebab-cased title, so the row stays readable in TASKS.md.
+ * Shape the approval-gated CoS task for a filable diagnosis. Pure. The dedup
+ * key/one-line-description contract and the brief layout live in
+ * `diagnosisCore.js#buildDiagnosisTask`; this supplies the post-mortem's
+ * wording and its `approvalRequired: true` policy (see the module header).
*/
export function buildSelfImproveTask({ diagnosis, seriesId, seriesName, outcome, outcomeReason, counts }) {
- const slug = slugify(diagnosis.title);
- const brief = [
- `Series Autopilot diagnosed a PortOS automation defect: ${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(
- '',
- `Diagnosed from an autopilot run on series ${seriesId}${seriesName ? ` ("${seriesName}")` : ''} that ended \`${outcome}\`${outcomeReason ? ` — ${trimToClause(outcomeReason, 500)}` : ''}.`,
- `Signal counts: ${JSON.stringify(counts)}.`,
- 'Confirm the defect in the code before changing anything: this brief is one LLM\'s read of a single run\'s telemetry, not a reproduction.',
- );
- return {
- description: `Pipeline self-improvement (${diagnosis.area}/${slug})`,
- context: brief.join('\n').slice(0, 4000),
- app: PORTOS_APP_ID,
- priority: 'MEDIUM',
- // 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,
+ return buildDiagnosisTask({
+ diagnosis,
+ descriptionPrefix: 'Pipeline self-improvement',
+ leadLine: `Series Autopilot diagnosed a PortOS automation defect: ${diagnosis.title}`,
+ tailLines: [
+ `Diagnosed from an autopilot run on series ${seriesId}${seriesName ? ` ("${seriesName}")` : ''} that ended \`${outcome}\`${outcomeReason ? ` — ${trimToClause(outcomeReason, 500)}` : ''}.`,
+ `Signal counts: ${JSON.stringify(counts)}.`,
+ 'Confirm the defect in the code before changing anything: this brief is one LLM\'s read of a single run\'s telemetry, not a reproduction.',
+ ],
approvalRequired: true,
- };
+ });
}
-// 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. 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',
- 'foundationGate — weighted judge of world/characters/arc before drafting',
- 'beatSheet — per-volume beat sheets',
- 'beatContinuity — whole-manuscript beat-level continuity loop',
- 'textStages — per-issue prose + scripts',
- 'scriptVerify — structural page/panel parse gate + advisory craft gate',
- 'editorialReview — series-level manuscript completeness review → fix loop',
- 'reverseOutline — refresh scene segmentation for the checks that consume it',
- 'editorialChecks — registry-driven editorial checks (deterministic + LLM)',
- 'editorialHealthGate — readiness gate over open blocking findings',
- 'revisionCycle — opt-in iterate-to-quality adversarial cut + judge loop',
- 'canonVerify — every drawn canon noun has a description',
- 'visualDraft — queue draft renders for covers + interior pages',
- 'produceTeaser — opt-in Creative Director teaser video',
-].join('\n');
-
-// The run's effective gate configuration, as the diagnosis context. Only the
-// knobs that shape WHICH steps ran and how hard they tried — enough for the
-// model to tell "this gate is off" from "this gate ran and failed". Exported
-// for the observer, whose prompt carries the same context.
-export const gateConfigOf = (options) => ({
- maxArcVerifyRounds: options.maxArcVerifyRounds,
- maxBeatContinuityRounds: options.maxBeatContinuityRounds,
- maxEditorialRounds: options.maxEditorialRounds,
- maxFoundationRounds: options.maxFoundationRounds,
- foundationGate: options.foundationGate,
- foundationThreshold: options.foundationThreshold,
- readinessGate: options.readinessGate,
- checkFindingsPauseThreshold: options.checkFindingsPauseThreshold,
- revisionEnabled: options.revisionEnabled,
- includeVisual: options.includeVisual,
- target: options.target,
-});
-
/**
* Run the meta-diagnosis at a run's terminal and file a PortOS task when the
* verdict says the automation is at fault.
@@ -278,22 +140,9 @@ export async function runSelfImproveDiagnosis(sId, record, { outcome, reason = n
broadcast(sId, { type: 'selfimprove:start', runId: record.runId, outcome, signals: signals.length });
const { content } = await runStagedLLM(SELF_IMPROVE_STAGE, {
- seriesName: series?.name || 'unknown',
- targetFormat: series?.targetFormat || 'unknown',
+ ...buildDiagnosisStageVars(record, { series, checkPlan, signals, counts, dropped }),
outcome,
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',
- // 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',
- craftGapIssues: record.runState?.scriptCraftGapIssues?.size || 0,
}, { ...providerOverrideOpts(record), returnsJson: true, source: SELF_IMPROVE_STAGE });
await recordDomainUsage('cos', { actions: 1 });