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

show a live milestone map while Autonomous mode runs a series

[._.]/ Adam Eivy5cd8923c7a70
diff --git a/.changelog/next/added-agent-0a0b28c7.md b/.changelog/next/added-agent-0a0b28c7.md
new file mode 100644
index 0000000000..5132021caf
--- /dev/null
+++ b/.changelog/next/added-agent-0a0b28c7.md
@@ -0,0 +1 @@
+- Autonomous mode now shows a live milestone map — every step the run projected, what each gate validated, where it is now, and what is left
diff --git a/PLAN.md b/PLAN.md
index 31194d1c47..b0b3c16f71 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -359,3 +359,11 @@ is not reliably announced.
### Classify non-Node app types so the standardize offer knows what it is looking at
- [ ] `streamingDetect.js` emits `vite+express` / `vite` / `single-node-server` / `nextjs`, the four Apple types, or `unknown` (the initialized default, ~line 1096) — there is no `python`, `go`, `docker`, or `static`. `usesPm2()` is the negation of `NON_PM2_TYPES` (the four Apple types), so *everything unrecognized is treated as a PM2 app*: a Python service, Docker stack, Go binary, or static site all come back `unknown` and are still offered PM2 standardization in the Add App wizard. That matters because the standardizer's prompt opens with "You are analyzing a **Node.js** application" (`server/services/pm2Standardizer.js`) — on a Python repo it doesn't fail, it confidently writes a Node ecosystem config. The auto-fire is gone (standardizing is now an explicit button whose copy says "skip it for Docker stacks, static sites, or anything you start another way"), so this is no longer a data-loss path, but the prose is doing a type check's job. **The call to make:** don't widen `NON_PM2_TYPES` — its three other consumers (`appDeployer.js`'s `deploy.sh`, `SlashDoPanel.jsx`'s `isSwiftApp`, `apps.js`'s `xed .` editor launch) mean "Apple", not "not PM2". Teach `streamingDetect` to classify `python` / `go` / `docker` / `static` from marker files (`pyproject.toml`/`requirements.txt`, `go.mod`, `docker-compose.yml` with no package.json, `index.html` with no server) so `unknown` stops being the catch-all, then add a positive `isStandardizable(type)` predicate over the Node types and gate both the wizard card and `standardizeRefusalFor()` on it. Note `type` is persisted on the app record, so an existing `unknown` app keeps that type until re-detected — the predicate must stay permissive for `unknown` or offer a re-detect. Surfaced by the /simplify altitude review on the opt-in-standardization change.
+
+### Persist the autopilot milestone map so a paused run still has one after a reload
+
+- [ ] The Autonomous-mode card draws a milestone map from two in-memory halves: the projected plan on the run's `start` frame (retained as `record.startPayload`) and the progress snapshot folded onto `record.progress` (`server/services/pipeline/seriesAutopilot/state.js#noteProgress`). Both are served only while the run is alive — `activeRunStart` / `activeRunProgress` return null once `run.finished`, and the panel's mount effect bails on `!s.active`. So the map answers "where is it now" perfectly while the panel is open, and answers nothing the morning after: a run that paused overnight shows the persisted banner (`Paused at Judging foundation`) with no map beside it, which is exactly when "how far did it get, and what is left" is the question being asked. **The call to make:** stamp a compact `{ plan, progress }` onto the persisted marker at the pause/complete/error terminals, in the same `persistMarker` call that already writes `status` / `currentStep` / `residualFindings` (`seriesAutopilot/session.js`), and have the panel fall back to `series.autopilot.plan` / `.progress` when no run is active. Keep it compact — the plan is ~16 `{kind,count,note,estActions}` rows and the snapshot is bounded by the step vocabulary — and add it to `sanitizeAutopilot` in `server/services/pipeline/series.js` so the shape survives a round-trip; the marker federates, so check whether the size warrants a `SCHEMA_VERSIONS` bump before shipping. Surfaced by the /simplify altitude review on the milestone-map change.
+
+### Extract the hand-rolled progress meter into a shared ui primitive
+
+- [ ] There is no progress-bar component in `client/src/components/ui/`, so every surface that needs one re-implements the same `h-1.5 rounded-full` track + `style={{ width: `${pct}%` }}` fill: `client/src/pages/Loras.jsx`, `client/src/components/pipeline/manuscript/ManuscriptReadAloud.jsx`, `client/src/components/pipeline/stages/EpisodeVideoStage.jsx`, `client/src/components/meatspace/post/PostLlmDrillRunner.jsx`, `client/src/components/meatspace/post/MemoryPractice.jsx`, and now `client/src/components/pipeline/AutopilotMilestones.jsx` — six copies. They already disagree on accessibility: only two carry `role="progressbar"` with `aria-valuenow`, so the rest are invisible to a screen reader. **The call to make:** add `client/src/components/ui/ProgressBar.jsx` taking `{ percent, tone, label }`, always emitting the ARIA trio, and migrate the six call sites (each is 3-8 lines of markup, no behavior change); register it in the ui README the way the other primitives are. Surfaced by the /simplify reuse review on the milestone-map change.
diff --git a/client/src/components/pipeline/AutopilotMilestones.jsx b/client/src/components/pipeline/AutopilotMilestones.jsx
new file mode 100644
index 0000000000..8e0e1d4440
--- /dev/null
+++ b/client/src/components/pipeline/AutopilotMilestones.jsx
@@ -0,0 +1,121 @@
+import { useMemo } from 'react';
+import { CheckCircle2, Loader2, Circle, MinusCircle, AlertCircle } from 'lucide-react';
+import {
+ buildAutopilotMilestones,
+ summarizeAutopilotMilestones,
+ describeAutopilotVerification,
+ autopilotStepLabel,
+ isStoppedTerminal,
+ MILESTONE_STATUS,
+} from '../../lib/autopilotMilestones';
+
+// Per-status chrome in ONE table — icon and tones together, so a new status
+// can't get a row color and no icon (or the reverse). `blocked` reuses the
+// warning tone the pause banner uses, so the step a run stopped on reads the
+// same in both places.
+const STATUS_CHROME = {
+ [MILESTONE_STATUS.DONE]: { Icon: CheckCircle2, row: 'text-gray-400', icon: 'text-port-success' },
+ [MILESTONE_STATUS.ACTIVE]: { Icon: Loader2, row: 'text-white', icon: 'text-port-accent animate-spin' },
+ [MILESTONE_STATUS.BLOCKED]: { Icon: AlertCircle, row: 'text-port-warning', icon: 'text-port-warning' },
+ [MILESTONE_STATUS.SKIPPED]: { Icon: MinusCircle, row: 'text-gray-600', icon: 'text-gray-600' },
+ [MILESTONE_STATUS.PENDING]: { Icon: Circle, row: 'text-gray-500', icon: 'text-gray-600' },
+};
+
+/**
+ * The Autonomous-mode milestone map: every step the run projected at start, what
+ * it has finished, what each gate validated, where it is now, and what is left.
+ *
+ * Renders for a live run AND for the plan a dry-run produced (which has no
+ * progress yet — every row is pending, i.e. the old "dry-run plan" list). The
+ * fold itself is pure and lives in `lib/autopilotMilestones.js`.
+ */
+export default function AutopilotMilestones({ plan, planTotals, progress, terminal, dryRun = false }) {
+ const { rows, summary } = useMemo(() => {
+ const built = buildAutopilotMilestones(plan, progress, { terminal });
+ return { rows: built, summary: summarizeAutopilotMilestones(built) };
+ }, [plan, progress, terminal]);
+ if (!rows.length) return null;
+
+ return (
+ <div className="px-3 pb-3 border-t border-port-border pt-2 text-[11px] text-gray-400">
+ <div className="flex items-center gap-2 flex-wrap">
+ <span className="uppercase tracking-wider text-gray-500">
+ {dryRun ? 'Dry-run plan' : 'Story progress'}
+ </span>
+ {/* A dry-run has nothing to measure — it never ran a step. */}
+ {!dryRun ? (
+ <span className="text-gray-400">
+ {summary.stepsDone} of {summary.steps} milestone(s) · {summary.percent}%
+ </span>
+ ) : null}
+ </div>
+
+ {/* Overall meter. A plan snapshot can under-count a step the run repeats,
+ so this is honest about milestones settled — not a time estimate. */}
+ {!dryRun ? (
+ <div
+ className="mt-1.5 h-1.5 w-full rounded-full bg-port-bg overflow-hidden"
+ role="progressbar"
+ aria-label="Autopilot story progress"
+ aria-valuenow={summary.percent}
+ aria-valuemin={0}
+ aria-valuemax={100}
+ >
+ <div
+ className={`h-full rounded-full transition-all duration-500 ${isStoppedTerminal(terminal) ? 'bg-port-warning' : 'bg-port-accent'}`}
+ style={{ width: `${summary.percent}%` }}
+ />
+ </div>
+ ) : null}
+
+ {/* Capped so a long plan (a comic series can project 16 milestones) can't
+ push the readiness + schedule sections below the fold. */}
+ <ul className="mt-2 space-y-1 max-h-72 overflow-y-auto">
+ {rows.map((row) => {
+ const verification = describeAutopilotVerification(row.kind, row.verification);
+ const active = row.status === MILESTONE_STATUS.ACTIVE || row.status === MILESTONE_STATUS.BLOCKED;
+ const { Icon, row: rowTone, icon: iconTone } = STATUS_CHROME[row.status];
+ return (
+ <li key={row.kind} className={rowTone}>
+ <div className="flex items-start gap-1.5">
+ <span className="mt-0.5"><Icon size={12} className={`${iconTone} shrink-0`} /></span>
+ <span className={active ? 'font-medium' : ''}>{autopilotStepLabel(row.kind)}</span>
+ {row.count > 1 ? (
+ <span className="text-gray-500 whitespace-nowrap">{row.done}/{row.count}</span>
+ ) : null}
+ {row.skipped > 0 ? (
+ <span className="text-gray-600 whitespace-nowrap">· {row.skipped} skipped</span>
+ ) : null}
+ {row.estActions > 0 && row.status === MILESTONE_STATUS.PENDING ? (
+ <span className="text-gray-600 ml-auto whitespace-nowrap">≈{row.estActions} act</span>
+ ) : null}
+ </div>
+ {/* What the gate actually validated — the half of "progress" a
+ step counter can't show (a gate can complete with residual
+ findings the user still has to look at). */}
+ {verification ? (
+ <div className="ml-[18px] text-gray-500">{verification}</div>
+ ) : null}
+ {!verification && row.note && row.status === MILESTONE_STATUS.PENDING ? (
+ <div className="ml-[18px] text-gray-600">{row.note}</div>
+ ) : null}
+ </li>
+ );
+ })}
+ </ul>
+
+ {/* #1576 — estimated budget cost so a large series on a small daily cap can
+ see, before starting, whether it will exhaust the cos action budget on
+ text/verify and never reach editorial. */}
+ {planTotals && (Number.isFinite(planTotals.estActions) || Number.isFinite(planTotals.estLlmCalls)) ? (
+ <div className="mt-1.5 pt-1.5 border-t border-port-border/60 text-gray-400 flex items-center gap-1.5">
+ <span className="uppercase tracking-wider text-gray-500">Est. budget</span>
+ <span className="ml-auto whitespace-nowrap">
+ ≈{planTotals.estActions || 0} cos action(s)
+ {planTotals.estLlmCalls ? ` · ~${planTotals.estLlmCalls} editorial-check LLM call(s)` : ''}
+ </span>
+ </div>
+ ) : null}
+ </div>
+ );
+}
diff --git a/client/src/components/pipeline/AutopilotPanel.jsx b/client/src/components/pipeline/AutopilotPanel.jsx
index ee2e2414e7..a34f9c942d 100644
--- a/client/src/components/pipeline/AutopilotPanel.jsx
+++ b/client/src/components/pipeline/AutopilotPanel.jsx
@@ -22,8 +22,10 @@ import {
patchSettingsSlice,
} from '../../services/api';
import { providerDisplayName, providerModelLabel, assignmentModelOptions, resolveSeriesRunLlm, resolveCliEffort } from '../../utils/providers';
+import { autopilotStepLabel, describeAutopilotVerification } from '../../lib/autopilotMilestones';
import Pill from '../ui/Pill';
import ProviderModelSelector from '../ProviderModelSelector';
+import AutopilotMilestones from './AutopilotMilestones';
import SeriesAutopilotSchedule from './SeriesAutopilotSchedule';
// Convergence-round bounds — mirror the server (seriesAutopilot.js + the
@@ -270,30 +272,9 @@ const SEVERITY_COLORS = {
low: 'text-gray-400 border-gray-500/30 bg-gray-700/20',
};
-// Human labels for each conductor step kind (matches seriesAutopilot.js).
-const STEP_LABELS = {
- unlockLocks: 'Unlocking series records',
- characterFoundation: 'Establishing character foundation',
- generateArc: 'Generating arc',
- repairArcStructure: 'Repairing volume structure',
- generateEpisodes: 'Generating episodes',
- verifyArcSpine: 'Checking arc spine',
- verifyArc: 'Verifying arc',
- foundationGate: 'Judging foundation',
- beatSheet: 'Generating beat sheets',
- textStages: 'Writing prose + scripts',
- scriptVerify: 'Verifying scripts',
- editorialReview: 'Editorial review',
- reverseOutline: 'Refreshing scene segmentation',
- editorialChecks: 'Editorial checks',
- editorialHealthGate: 'Editorial health gate',
- revisionCycle: 'Iterate-to-quality revision',
- canonVerify: 'Checking canon descriptions',
- visualDraft: 'Drafting comic art',
- produceTeaser: 'Producing teaser video',
-};
-
-const stepLabel = (kind) => STEP_LABELS[kind] || kind;
+// Step labels are shared with the milestone map (lib/autopilotMilestones.js) so
+// the live status line and the map can't name the same step differently.
+const stepLabel = autopilotStepLabel;
// The record kinds one auto-resolve round can rewrite, in the order a reader
// scans them: the arc first, then down to the episodes.
@@ -317,16 +298,23 @@ const NO_CHANGE_LABELS = {
'no-edits-returned': 'it proposed no edits at all',
};
-// Turn an SSE frame into a one-line status string.
+// Turn an SSE frame into a one-line status string. Null means "nothing to say" —
+// the frame is state for another surface, not activity worth a status line.
function frameLabel(f) {
if (!f) return null;
switch (f.type) {
+ // The milestone map's cursor (server: seriesAutopilot/state.js). It follows
+ // the frame that moved it, so labeling it would just overwrite that frame's
+ // own status line with a duplicate.
+ case 'progress': return null;
case 'start': return f.mode === 'dry-run' ? 'Planning (dry-run)…' : 'Starting…';
case 'note': return f.message;
case 'step:start': return `${stepLabel(f.kind)}…`;
case 'step:complete': return `${stepLabel(f.kind)} done`;
case 'step:skip': return `Skipped ${stepLabel(f.kind)}${f.reason ? ` — ${f.reason}` : ''}`;
- case 'verify:round': return `${f.scope} check — ${f.blocking} blocking of ${f.findings} finding(s)${f.errored > 0 ? ` · ⚠️ ${f.errored} errored` : ''}`;
+ // Same formatter the milestone row uses — the two render the SAME telemetry
+ // in one card, so a second phrasing of it here is drift waiting to happen.
+ case 'verify:round': return `${f.scope} check — ${describeAutopilotVerification(f.scope, f)}`;
// What the auto-resolve round actually wrote. An episode count alone was
// meaningless at the arc-spine gate (whose resolver may not touch episodes),
// so name every record kind that moved — and when nothing moved, say why
@@ -361,7 +349,7 @@ function frameLabel(f) {
? `discarded before it was applied: ${f.reason}`
: `${f.before} → ${f.after} blocking finding(s), ${f.kept ? 'kept' : 'reverted'}`);
// #2176 — foundation-gate telemetry.
- case 'foundation:round': return `Foundation round ${f.round} — weighted ${f.weightedScore}/${f.threshold}${f.weakest ? ` · next target: ${f.weakest}` : ''}`;
+ case 'foundation:round': return `Foundation round ${f.round} — ${describeAutopilotVerification('foundationGate', f)}`;
case 'foundation:fix': return `${f.phase === 'pre-arc' ? 'Pre-arc foundation' : 'Foundation fix'} — ${f.dimension}${f.applied ? ' applied' : ` skipped${f.reason ? ` (${f.reason})` : ''}`}`;
// A repair whose re-judge showed no gain is rewound. Like resolve:rollback,
// say whether the gate is retrying from the restored checkpoint — otherwise
@@ -420,6 +408,10 @@ function frameLabel(f) {
const RUN_ENDED = new Set(['complete', 'canceled', 'error', 'paused']);
+// How many recent frames the live activity log shows. Also the stopping point
+// for the backward frame walk that builds it.
+const ACTIVITY_LINES = 6;
+
// Pause kinds worth calling out beside the status line — the ones where "Paused"
// alone doesn't tell the user what state the draft is in. A kind with no entry
// (maxRounds, childFailed, planningOscillation) is fully explained by the reason
@@ -511,6 +503,12 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
const [mode, setMode] = useState(null);
const [plan, setPlan] = useState(null);
const [planTotals, setPlanTotals] = useState(null);
+ // Milestone-map state. `seedProgress` is the snapshot the status route hands a
+ // panel that attaches MID-RUN (SSE replays one frame, so the live `progress`
+ // frames alone would start the map at zero); `terminal` is how the tracked run
+ // ended, which turns the step it stopped on from "running" into "blocked".
+ const [seedProgress, setSeedProgress] = useState(null);
+ const [terminal, setTerminal] = useState(null);
const [showOpts, setShowOpts] = useState(false);
const [includeVisual, setIncludeVisual] = useState(true);
const [fileGaps, setFileGaps] = useState(false);
@@ -754,6 +752,32 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
const { latest, frames } = usePipelineProgress(pipelineAutopilotSseUrl, [seriesId], { enabled: active });
+ // One backward walk per frame batch yields everything the live section needs:
+ // the newest `progress` frame (the milestone map's cursor) and the last few
+ // labelled frames (the activity log, whose last line is also the status line).
+ // Walking backward and stopping early matters — `frames` is uncapped, so
+ // labelling the whole array on every arriving frame is quadratic over a run.
+ const { snapshot, activityLines } = useMemo(() => {
+ const lines = [];
+ let found = null;
+ for (let i = frames.length - 1; i >= 0; i -= 1) {
+ const f = frames[i];
+ if (!found && f?.type === 'progress') found = f;
+ if (lines.length < ACTIVITY_LINES) {
+ const label = frameLabel(f);
+ if (label) lines.unshift(label);
+ } else if (found) break;
+ }
+ return { snapshot: found, activityLines: lines };
+ }, [frames]);
+ // Fall back to the status route's snapshot until this stream emits one of its
+ // own — a panel attaching mid-run has no frames yet.
+ const progress = snapshot || seedProgress;
+ // A `progress` frame is deliberately label-less, so the status line keeps
+ // naming the last frame that had something to say. `latest` covers a stream
+ // whose frames were never collected.
+ const latestLabel = activityLines.at(-1) || frameLabel(latest);
+
const onSeriesUpdateRef = useRef(onSeriesUpdate);
const onIssuesUpdateRef = useRef(onIssuesUpdate);
onSeriesUpdateRef.current = onSeriesUpdate;
@@ -790,6 +814,10 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
// SSE replays only the last frame, so the run's `start` frame comes back
// on the status payload instead — same shape, same reader.
if (s.start) applyStartFrame(s.start);
+ // …and its position in that plan, so the map opens where the run
+ // actually is instead of claiming nothing has happened yet.
+ if (s.progress) setSeedProgress(s.progress);
+ setTerminal(null);
setPausePending(s.pauseRequested === true);
setActive(true);
})
@@ -804,6 +832,10 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
if (latest?.type === 'start') {
applyStartFrame(latest);
} else if (latest?.type === 'complete' && latest.dryRun && Array.isArray(latest.plan)) {
+ // A fast dry-run can finish before the client attaches, so this terminal
+ // frame is the only place the plan (and the fact that it WAS a dry-run,
+ // which is what makes the map a plan rather than a progress meter) lands.
+ setMode('dry-run');
setPlan(latest.plan);
if (latest.planTotals) setPlanTotals(latest.planTotals);
}
@@ -816,6 +848,10 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
if (activeRunIdRef.current && latest.runId && latest.runId !== activeRunIdRef.current) return;
setActive(false);
setPausePending(false);
+ // Freeze the map on how this run ended: a paused/errored run keeps its
+ // milestones on screen with the step it stopped on flagged, rather than the
+ // list vanishing the moment the stream closes.
+ setTerminal(latest.type);
getPipelineSeries(seriesId, { silent: true }).then((s) => { if (s) onSeriesUpdateRef.current?.(s); }).catch(() => null);
listPipelineIssues(seriesId, { silent: true }).then((is) => onIssuesUpdateRef.current?.(Array.isArray(is) ? is : [])).catch(() => null);
if (latest.type === 'complete') {
@@ -840,6 +876,10 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
setStarting(true);
setPlan(null);
setPlanTotals(null);
+ // The previous run's map must not bleed into this one — the fresh run
+ // rebuilds both halves (plan on its start frame, progress from its frames).
+ setSeedProgress(null);
+ setTerminal(null);
// ONLY the options the user edited (clamped, real values — never the display
// defaults of untouched options, which would mask a saved setting). Send them
// as per-run overrides AND persist them: the override makes the edit effective
@@ -915,7 +955,7 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
if (!seriesId) return null;
const ap = series.autopilot;
- const liveLabel = active ? (frameLabel(latest) || 'Working…') : null;
+ const liveLabel = active ? (latestLabel || 'Working…') : null;
// #1617 — once the server acks the cancel, switch the Stop button to a
// disabled "Cancelling…" state so the user gets feedback (and can't re-fire
// cancel) while the active step finishes and the terminal frame arrives.
@@ -1357,44 +1397,31 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
) : null}
</div>
) : null}
- {frames?.length ? (
+ {activityLines.length ? (
<div className="mt-2 max-h-28 overflow-y-auto text-[11px] text-gray-500 space-y-0.5">
- {frames.slice(-6).map((f, i) => <div key={i}>{frameLabel(f)}</div>)}
+ {activityLines.map((line, i) => <div key={i}>{line}</div>)}
</div>
) : null}
</div>
) : null}
- {/* Dry-run plan — rendered whenever a plan exists, so it survives after the
- dry-run stream closes (a dry-run persists no marker and completes
- immediately). Cleared when the next run starts. */}
- {plan?.length ? (
- <div className="px-3 pb-3 border-t border-port-border pt-2 text-[11px] text-gray-400">
- <div className="uppercase tracking-wider text-gray-500 mb-1">{active ? 'Planned steps' : 'Dry-run plan'}</div>
- <ul className="space-y-0.5">
- {plan.map((p, i) => (
- <li key={i} className="flex items-center gap-1.5">
- <ChevronRight size={10} /> {stepLabel(p.kind)} ×{p.count}{p.note ? ` — ${p.note}` : ''}
- {Number.isFinite(p.estActions) && p.estActions > 0 ? (
- <span className="text-gray-500 ml-auto whitespace-nowrap">≈{p.estActions} act</span>
- ) : null}
- </li>
- ))}
- </ul>
- {/* #1576 — estimated budget cost so a large series on a small daily cap
- can see, before starting, whether it will exhaust the cos action
- budget on text/verify and never reach editorial. */}
- {planTotals && (Number.isFinite(planTotals.estActions) || Number.isFinite(planTotals.estLlmCalls)) ? (
- <div className="mt-1.5 pt-1.5 border-t border-port-border/60 text-gray-400 flex items-center gap-1.5">
- <span className="uppercase tracking-wider text-gray-500">Est. budget</span>
- <span className="ml-auto whitespace-nowrap">
- ≈{planTotals.estActions || 0} cos action(s)
- {planTotals.estLlmCalls ? ` · ~${planTotals.estLlmCalls} editorial-check LLM call(s)` : ''}
- </span>
- </div>
- ) : null}
- </div>
- ) : null}
+ {/* Milestone map — the run's whole job (the plan its `start` frame
+ projected) measured against where it actually is. Rendered whenever a
+ plan exists, so it survives after the stream closes: a dry-run persists
+ no marker and completes immediately, and a run that pauses while the
+ panel is open keeps its map beside the banner. Both halves are
+ in-memory on the server, so a reload after the run ended shows the
+ persisted banner alone — see PLAN.md for persisting the map itself.
+ Cleared when the next run starts. `planTotals` carries the #1576
+ estimated cos-action budget so a large series on a small daily cap can
+ see, before starting, whether it will run out before editorial. */}
+ <AutopilotMilestones
+ plan={plan}
+ planTotals={planTotals}
+ progress={progress}
+ terminal={terminal}
+ dryRun={mode === 'dry-run'}
+ />
{/* Persisted status banner (paused / done / error). A `done` run that
filed blocking script-craft gaps (#1572) is shown as a caution, not
diff --git a/client/src/components/pipeline/AutopilotPanel.test.jsx b/client/src/components/pipeline/AutopilotPanel.test.jsx
index 8875daf7d1..fe4c87ad52 100644
--- a/client/src/components/pipeline/AutopilotPanel.test.jsx
+++ b/client/src/components/pipeline/AutopilotPanel.test.jsx
@@ -710,6 +710,89 @@ describe('AutopilotPanel', () => {
expect(screen.getByText(/~6 editorial-check LLM call/i)).toBeInTheDocument();
});
+ // The milestone map: the plan the run projected, measured against the progress
+ // snapshot, so "where are we in the story" is answerable at a glance.
+ describe('milestone map', () => {
+ const PLAN = [
+ { kind: 'verifyArcSpine', count: 1, estActions: 4 },
+ { kind: 'foundationGate', count: 1, estActions: 4 },
+ { kind: 'textStages', count: 2, estActions: 2 },
+ ];
+
+ it('draws the map from the status payload when the panel attaches mid-run', async () => {
+ getPipelineAutopilotStatus.mockResolvedValue({
+ autopilot: { status: 'running', runId: 'r1' },
+ active: true,
+ start: { type: 'start', runId: 'r1', mode: 'execute', plan: PLAN },
+ progress: {
+ currentStep: 'foundationGate',
+ completed: { verifyArcSpine: 1 },
+ verified: { verifyArcSpine: { round: 2, findings: 5, blocking: 0 } },
+ },
+ });
+ renderPanel({ id: 's1', targetFormat: 'comic' });
+ expect(await screen.findByText(/Story progress/i)).toBeInTheDocument();
+ // 1 of 3 milestones settled → 1 of 4 counted units.
+ expect(screen.getByText(/1 of 3 milestone\(s\) · 25%/i)).toBeInTheDocument();
+ expect(screen.getByRole('progressbar', { name: /story progress/i })).toHaveAttribute('aria-valuenow', '25');
+ // What the finished gate actually validated, not just that it ran.
+ expect(screen.getByText(/0 blocking of 5 finding\(s\)/i)).toBeInTheDocument();
+ });
+
+ it('advances the map on a live progress frame', async () => {
+ getPipelineAutopilotStatus.mockResolvedValue({
+ autopilot: { status: 'running', runId: 'r1' },
+ active: true,
+ start: { type: 'start', runId: 'r1', mode: 'execute', plan: PLAN },
+ progress: { currentStep: 'verifyArcSpine', completed: {} },
+ });
+ sseFrames = [
+ { type: 'step:complete', kind: 'foundationGate', runId: 'r1' },
+ {
+ type: 'progress',
+ runId: 'r1',
+ currentStep: 'textStages',
+ completed: { verifyArcSpine: 1, foundationGate: 1, textStages: 1 },
+ },
+ ];
+ sseLatest = sseFrames[1];
+ renderPanel({ id: 's1', targetFormat: 'comic' });
+ // The newest progress frame wins over the status seed: 2 settled + 1 of 2
+ // text stages = 3 of 4 units.
+ expect(await screen.findByText(/2 of 3 milestone\(s\) · 75%/i)).toBeInTheDocument();
+ expect(screen.getByText('1/2')).toBeInTheDocument();
+ // A progress frame carries no status text of its own, so the live line
+ // keeps naming the last frame that did.
+ // (the status line and the recent-activity log both render it)
+ expect(screen.getAllByText(/Judging foundation done/i).length).toBeGreaterThan(0);
+ });
+
+ it('leaves a paused run on screen with the step it stopped on', async () => {
+ getPipelineAutopilotStatus.mockResolvedValue({
+ autopilot: { status: 'running', runId: 'r1' },
+ active: true,
+ start: { type: 'start', runId: 'r1', mode: 'execute', plan: PLAN },
+ progress: { currentStep: 'foundationGate', completed: { verifyArcSpine: 1 } },
+ });
+ const view = renderPanel({ id: 's1', targetFormat: 'comic' });
+ await screen.findByText(/Story progress/i);
+ // The run pauses; the map must survive the stream closing rather than
+ // vanishing and leaving only a one-line banner.
+ sseLatest = { type: 'paused', runId: 'r1', reason: 'foundation gate could not converge' };
+ sseFrames = [sseLatest];
+ view.rerender(
+ <MemoryRouter>
+ <AutopilotPanel series={{ id: 's1', targetFormat: 'comic' }} onSeriesUpdate={vi.fn()} onIssuesUpdate={vi.fn()} />
+ </MemoryRouter>,
+ );
+ await waitFor(() => expect(toast.warning).toHaveBeenCalledWith(expect.stringMatching(/paused/i)));
+ expect(screen.getByText(/Story progress/i)).toBeInTheDocument();
+ expect(screen.getByText(/Judging foundation/i)).toBeInTheDocument();
+ // The run is over — no Stop/Pause affordances, but the map is still there.
+ expect(screen.getByRole('button', { name: /run autopilot/i })).toBeInTheDocument();
+ });
+ });
+
// #1578 — per-check editorial telemetry forwarded up the autopilot SSE stream
// renders as a live label with the severity breakdown, not the raw frame type.
it('renders a forwarded per-check editorial frame with its severity breakdown', async () => {
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index e50d1c1710..fcea6070d6 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -34,6 +34,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `shotGrammar.js` | Client mirror of the controlled vocabularies in `server/lib/shotGrammar.js` (#1315): `SHOT_TYPES` / `SCREEN_DIRECTIONS` enums (in sync with the server so a hand-set value passes `storyboardShotSchema`) + `SHOT_TYPE_LABELS` / `SCREEN_DIRECTION_LABELS` for the storyboards shot-grammar editor selects (#1468). |
| `universeStylePreset.js` | Build the client-side style preset that `composeStyledPrompt` layers on top. |
| `universeRunTag.js` | `buildUniverseSectionRenderTag(universe, kindKey, entry)` — the durable `universeRun` job tag the canon-render call sites (UniverseCanonSection, NounsStage, Story Builder characters step) pass to `generateImage` so the server auto-files the render into the universe collection AND appends it to the entry's `imageRefs[]` (no client follow-up PATCH). |
+| `autopilotMilestones.js` | Series-Autopilot milestone map. `buildAutopilotMilestones(plan, progress, {terminal})` folds the run's projected plan (the `start` frame) and its live progress snapshot (`progress` frames / the status route) into ordered rows with a `MILESTONE_STATUS` each — a furthest-index cursor, so a gate the run revisits can't un-finish the milestones after it; `summarizeAutopilotMilestones(rows)` rolls them into the header meter (a settled-but-unstepped milestone counts as complete); `describeAutopilotVerification(kind, verification)` renders what a gate actually validated — shared with the panel's `frameLabel`, since the milestone row and the activity log render the same telemetry; `isStoppedTerminal(terminal)` is the one definition of "the run stopped mid-plan". Also owns `AUTOPILOT_STEP_LABELS` / `autopilotStepLabel(kind)`, the one set of human labels for conductor step kinds (shared by the map and the panel's live status line). Used by `components/pipeline/AutopilotMilestones.jsx` + `AutopilotPanel.jsx`. |
| `beatColors.js` | `BEAT_KIND_COLORS` + `getBeatKindColor(kind)` — per-kind display colors for reader-map emotional beats (kinds defined server-side in `storyArc.js`). Keeps every beat visualization consistent. |
| `beatGrid.js` | Music-video beat-quantized timeline arranger (#1854). `buildBeatGridPoints(audioAnalysis)` merges beats/downbeats/section edges into one ranked snap-point list; `snapTimeToGrid(timeSec, gridPoints, toleranceSec)` finds the nearest point within tolerance; `computeSceneSpans(scenes, durationSec)` lays out scenes without a persisted `startSec`/`endSec` contiguously as a display-only fallback; `computeDragSpan({kind, startSpan, deltaSec, gridPoints, ...})` resolves a timeline drag gesture (`'move'` or `'right'` — no `'left'`, since the render can only trim from a clip's own frame 0) into a new span; `shouldMarkBeatAligned({kind, snapped, wasPersisted})` gates the `beatAligned` flag so a reposition-only drag can't silently promote an unpersisted scene's placeholder fallback duration into a "saved exactly" render duration; `autoArrangeScenes(scenes, audioAnalysis)` proposes a full `{ sceneId, startSec, endSec, beatAligned }[]` arrangement by distributing scenes across song sections weighted by each section's `energy` (#1915). Used by `components/musicVideo/BeatTimeline.jsx` and `pages/MusicVideo.jsx`. |
| `bibleLimits.js` | Mirror of `server/lib/storyBible.js` `BIBLE_LIMITS`, plus `capImageRefs` / `appendImageRefById` for the optimistic imageRefs-append paths. |
diff --git a/client/src/lib/autopilotMilestones.js b/client/src/lib/autopilotMilestones.js
new file mode 100644
index 0000000000..3503c0e45a
--- /dev/null
+++ b/client/src/lib/autopilotMilestones.js
@@ -0,0 +1,176 @@
+/**
+ * Autopilot milestone map — fold a run's projected plan plus its live
+ * progress snapshot into the ordered rows the Autonomous-mode card renders.
+ *
+ * The two inputs both come from the server and are never re-derived here:
+ * - `plan` rides the run's `start` frame (server: seriesAutopilot/dryRun.js) —
+ * every step the run expects to take, in resolver order, with its count.
+ * - `progress` rides the `progress` frames and the status route (server:
+ * seriesAutopilot/state.js#noteProgress) — completed counts per step kind,
+ * the step running now, and each gate's latest verification.
+ *
+ * Pure: no React, no fetching. The point of keeping the fold here is that a run
+ * can revisit an earlier step (the foundation gate re-checks after arc repairs)
+ * and the plan is a snapshot taken at start, so "which milestone are we on" is
+ * a cursor question rather than a running tally — and that rule deserves tests
+ * rather than living inline in JSX.
+ */
+
+import { clamp } from '../utils/formatters';
+
+// Human labels for each conductor step kind (mirrors the `kind` values
+// seriesAutopilot/stepResolver.js can return). Lives here rather than in a
+// component because both the milestone map and the panel's live status line
+// name the same steps — two copies would drift the moment a step is renamed.
+export const AUTOPILOT_STEP_LABELS = Object.freeze({
+ unlockLocks: 'Unlocking series records',
+ characterFoundation: 'Establishing character foundation',
+ generateArc: 'Generating arc',
+ repairArcStructure: 'Repairing volume structure',
+ generateEpisodes: 'Generating episodes',
+ verifyArcSpine: 'Checking arc spine',
+ verifyArc: 'Verifying arc',
+ foundationGate: 'Judging foundation',
+ beatSheet: 'Generating beat sheets',
+ beatContinuity: 'Beat continuity',
+ textStages: 'Writing prose + scripts',
+ scriptVerify: 'Verifying scripts',
+ editorialReview: 'Editorial review',
+ reverseOutline: 'Refreshing scene segmentation',
+ editorialChecks: 'Editorial checks',
+ editorialHealthGate: 'Editorial health gate',
+ revisionCycle: 'Iterate-to-quality revision',
+ canonVerify: 'Checking canon descriptions',
+ visualDraft: 'Drafting comic art',
+ produceTeaser: 'Producing teaser video',
+});
+
+/** Display label for a conductor step kind; falls back to the raw kind. */
+export const autopilotStepLabel = (kind) => AUTOPILOT_STEP_LABELS[kind] || kind;
+
+/** A milestone's display state. `blocked` is the step a paused/errored run stopped on. */
+export const MILESTONE_STATUS = Object.freeze({
+ DONE: 'done',
+ ACTIVE: 'active',
+ BLOCKED: 'blocked',
+ SKIPPED: 'skipped',
+ PENDING: 'pending',
+});
+
+const SETTLED = new Set([MILESTONE_STATUS.DONE, MILESTONE_STATUS.SKIPPED]);
+
+// Terminal frame types that mean the run stopped ON a step rather than through it.
+const STOPPED_TERMINALS = new Set(['paused', 'error', 'canceled']);
+
+/** Did the run stop mid-plan? Drives both the blocked row and the meter's tone. */
+export const isStoppedTerminal = (terminal) => STOPPED_TERMINALS.has(terminal);
+
+const countOf = (map, key) => {
+ const n = map?.[key];
+ return Number.isFinite(n) && n > 0 ? n : 0;
+};
+
+/**
+ * Ordered milestone rows for a plan + progress pair.
+ *
+ * @param {Array<{kind:string,count:number,note?:string,estActions?:number}>} plan
+ * @param {{currentStep?:string|null, completed?:Object, skipped?:Object, verified?:Object}} progress
+ * @param {{terminal?:string|null}} [opts] terminal frame type of a finished run
+ * @returns {Array<{kind,count,done,skipped,note,estActions,status,verification}>}
+ */
+export function buildAutopilotMilestones(plan, progress = {}, { terminal = null } = {}) {
+ const rows = Array.isArray(plan) ? plan : [];
+ const completed = progress?.completed || {};
+ const skipped = progress?.skipped || {};
+ const verified = progress?.verified || {};
+ const currentStep = progress?.currentStep || null;
+ // `currentStep` survives its own completion (the server keeps it so a run that
+ // ends right there can still name the step). This is the flag that says which
+ // reading applies — mid-step, or finished and about to move on.
+ const currentStepRunning = !!currentStep && progress?.currentStepComplete !== true;
+ const stopped = isStoppedTerminal(terminal);
+ // How far the run has reached. A revisited earlier step must not un-finish the
+ // milestones after it, so the cursor is the FURTHEST index with evidence — the
+ // running step, or any step that has completed at least once. Ascending scan,
+ // so the last match is the furthest one.
+ let cursor = -1;
+ rows.forEach((row, i) => {
+ if (row?.kind === currentStep || countOf(completed, row?.kind) > 0) cursor = i;
+ });
+
+ return rows.map((row, i) => {
+ const kind = row?.kind;
+ const count = Number.isFinite(row?.count) && row.count > 0 ? row.count : 1;
+ const done = countOf(completed, kind);
+ let status;
+ if (kind === currentStep && stopped) {
+ status = MILESTONE_STATUS.BLOCKED;
+ } else if (kind === currentStep && currentStepRunning) {
+ status = MILESTONE_STATUS.ACTIVE;
+ } else if (terminal === 'complete' || i <= cursor) {
+ // Settled: the run is past this milestone — either it stepped through it,
+ // or (a completed run, or one the cursor has overtaken) the resolver
+ // decided against it. Not work still owed either way.
+ status = done > 0 ? MILESTONE_STATUS.DONE : MILESTONE_STATUS.SKIPPED;
+ } else {
+ status = MILESTONE_STATUS.PENDING;
+ }
+ return {
+ kind,
+ count,
+ done: Math.min(done, count),
+ skipped: countOf(skipped, kind),
+ note: row?.note || null,
+ estActions: Number.isFinite(row?.estActions) ? row.estActions : null,
+ status,
+ verification: verified[kind] || null,
+ };
+ });
+}
+
+/**
+ * Roll milestone rows into the header meter. A settled-but-unstepped milestone
+ * (`skipped`) counts as complete — the run is not going back for it, so leaving
+ * it out would park the bar short of 100% on a finished run.
+ */
+export function summarizeAutopilotMilestones(rows) {
+ const list = Array.isArray(rows) ? rows : [];
+ let total = 0;
+ let done = 0;
+ for (const row of list) {
+ total += row.count;
+ done += SETTLED.has(row.status) ? row.count : Math.min(row.done, row.count);
+ }
+ return {
+ total,
+ done,
+ steps: list.length,
+ stepsDone: list.filter((r) => SETTLED.has(r.status)).length,
+ percent: total > 0 ? clamp(Math.round((done / total) * 100), 0, 100) : 0,
+ };
+}
+
+/**
+ * One short line for what a gate actually validated, or null when it hasn't run
+ * yet. The foundation gate scores rather than counts findings, so it reads
+ * differently from every other gate.
+ *
+ * Shared with the panel's live status line (`frameLabel`): the milestone row and
+ * the activity log render the SAME telemetry, a round apart, so two phrasings of
+ * it in one card is a drift bug waiting to happen. Both take the raw frame /
+ * stored verification — the fields are identical.
+ */
+export function describeAutopilotVerification(kind, verification) {
+ if (!verification) return null;
+ if (kind === 'foundationGate') {
+ const { weightedScore, threshold, weakest } = verification;
+ if (!Number.isFinite(weightedScore)) return null;
+ const bar = Number.isFinite(threshold) ? `/${threshold}` : '';
+ return `weighted ${weightedScore}${bar}${weakest ? ` · next target: ${weakest}` : ''}`;
+ }
+ const { findings, blocking, errored } = verification;
+ if (!Number.isFinite(findings)) return null;
+ const tail = errored > 0 ? ` · ⚠️ ${errored} errored` : '';
+ if (!Number.isFinite(blocking)) return `${findings} finding(s)${tail}`;
+ return `${blocking} blocking of ${findings} finding(s)${tail}`;
+}
diff --git a/client/src/lib/autopilotMilestones.test.js b/client/src/lib/autopilotMilestones.test.js
new file mode 100644
index 0000000000..912082d23e
--- /dev/null
+++ b/client/src/lib/autopilotMilestones.test.js
@@ -0,0 +1,153 @@
+import { describe, it, expect } from 'vitest';
+import {
+ buildAutopilotMilestones,
+ summarizeAutopilotMilestones,
+ describeAutopilotVerification,
+ autopilotStepLabel,
+ MILESTONE_STATUS,
+} from './autopilotMilestones';
+
+const PLAN = [
+ { kind: 'generateArc', count: 1, estActions: 1 },
+ { kind: 'verifyArcSpine', count: 1, note: 'up to 3 round(s)', estActions: 4 },
+ { kind: 'foundationGate', count: 1, estActions: 4 },
+ { kind: 'textStages', count: 4, estActions: 4 },
+ { kind: 'editorialReview', count: 1, estActions: 3 },
+];
+
+const statuses = (rows) => Object.fromEntries(rows.map((r) => [r.kind, r.status]));
+
+describe('buildAutopilotMilestones', () => {
+ it('is all-pending for a plan with no progress yet (the dry-run case)', () => {
+ const rows = buildAutopilotMilestones(PLAN, {});
+ expect(rows.every((r) => r.status === MILESTONE_STATUS.PENDING)).toBe(true);
+ expect(summarizeAutopilotMilestones(rows)).toMatchObject({ done: 0, percent: 0, steps: 5 });
+ });
+
+ it('marks finished steps done, the running step active, and the rest pending', () => {
+ const rows = buildAutopilotMilestones(PLAN, {
+ completed: { generateArc: 1, verifyArcSpine: 1, foundationGate: 1, textStages: 1 },
+ currentStep: 'textStages',
+ });
+ expect(statuses(rows)).toEqual({
+ generateArc: MILESTONE_STATUS.DONE,
+ verifyArcSpine: MILESTONE_STATUS.DONE,
+ foundationGate: MILESTONE_STATUS.DONE,
+ textStages: MILESTONE_STATUS.ACTIVE,
+ editorialReview: MILESTONE_STATUS.PENDING,
+ });
+ // The active multi-count step reports its own partial progress.
+ expect(rows.find((r) => r.kind === 'textStages')).toMatchObject({ done: 1, count: 4 });
+ });
+
+ it('settles the running step once it reports complete', () => {
+ const rows = buildAutopilotMilestones(PLAN, {
+ completed: { generateArc: 1, verifyArcSpine: 1, foundationGate: 1, textStages: 4 },
+ currentStep: 'textStages',
+ currentStepComplete: true,
+ });
+ expect(statuses(rows).textStages).toBe(MILESTONE_STATUS.DONE);
+ });
+
+ it('does not un-finish later milestones when the run revisits an earlier gate', () => {
+ // The foundation gate re-checks after an arc repair, so `currentStep` moves
+ // BACKWARDS while later steps already have completions.
+ const rows = buildAutopilotMilestones(PLAN, {
+ completed: { generateArc: 1, verifyArcSpine: 1, foundationGate: 1, textStages: 4, editorialReview: 1 },
+ currentStep: 'foundationGate',
+ });
+ expect(statuses(rows)).toMatchObject({
+ textStages: MILESTONE_STATUS.DONE,
+ editorialReview: MILESTONE_STATUS.DONE,
+ });
+ // …and the revisited gate is still shown as the one doing work.
+ expect(statuses(rows).foundationGate).toBe(MILESTONE_STATUS.ACTIVE);
+ });
+
+ it('flags the step a paused run stopped on as blocked, not active', () => {
+ const rows = buildAutopilotMilestones(
+ PLAN,
+ { completed: { generateArc: 1 }, currentStep: 'verifyArcSpine' },
+ { terminal: 'paused' },
+ );
+ expect(statuses(rows).verifyArcSpine).toBe(MILESTONE_STATUS.BLOCKED);
+ expect(statuses(rows).editorialReview).toBe(MILESTONE_STATUS.PENDING);
+ });
+
+ it('settles every milestone of a completed run, skipping ones it never stepped through', () => {
+ const rows = buildAutopilotMilestones(
+ PLAN,
+ { completed: { generateArc: 1, verifyArcSpine: 1, textStages: 4, editorialReview: 1 } },
+ { terminal: 'complete' },
+ );
+ expect(statuses(rows).foundationGate).toBe(MILESTONE_STATUS.SKIPPED);
+ // A settled-but-unstepped milestone still counts toward the meter, or a
+ // finished run would sit permanently short of 100%.
+ expect(summarizeAutopilotMilestones(rows).percent).toBe(100);
+ });
+
+ it('counts a step the run passed without completing as skipped, not still-owed', () => {
+ const rows = buildAutopilotMilestones(PLAN, {
+ completed: { generateArc: 1, foundationGate: 1 },
+ currentStep: 'foundationGate',
+ });
+ expect(statuses(rows).verifyArcSpine).toBe(MILESTONE_STATUS.SKIPPED);
+ });
+
+ it('surfaces sub-step skips and the gate verification on their own milestone', () => {
+ const rows = buildAutopilotMilestones(PLAN, {
+ completed: { generateArc: 1, verifyArcSpine: 1 },
+ skipped: { textStages: 2 },
+ verified: { verifyArcSpine: { round: 2, findings: 5, blocking: 0 } },
+ currentStep: 'verifyArcSpine',
+ });
+ expect(rows.find((r) => r.kind === 'textStages').skipped).toBe(2);
+ expect(rows.find((r) => r.kind === 'verifyArcSpine').verification)
+ .toEqual({ round: 2, findings: 5, blocking: 0 });
+ });
+
+ it('weights the meter by step count, not by milestone', () => {
+ const rows = buildAutopilotMilestones(PLAN, {
+ completed: { generateArc: 1, verifyArcSpine: 1, foundationGate: 1, textStages: 2 },
+ currentStep: 'textStages',
+ });
+ // 3 single-count steps + 2 of 4 text stages, out of 8 units.
+ expect(summarizeAutopilotMilestones(rows)).toMatchObject({ total: 8, done: 5, percent: 63, stepsDone: 3 });
+ });
+
+ it('tolerates a missing/empty plan', () => {
+ expect(buildAutopilotMilestones(null, { completed: { generateArc: 1 } })).toEqual([]);
+ expect(summarizeAutopilotMilestones(null)).toMatchObject({ total: 0, percent: 0 });
+ });
+});
+
+describe('describeAutopilotVerification', () => {
+ it('reads a gate by its blocking count', () => {
+ expect(describeAutopilotVerification('verifyArc', { findings: 4, blocking: 0 }))
+ .toBe('0 blocking of 4 finding(s)');
+ expect(describeAutopilotVerification('verifyArc', { findings: 9, blocking: 3 }))
+ .toBe('3 blocking of 9 finding(s)');
+ });
+
+ it('calls out checks that errored — an unevaluated dimension is not "clean"', () => {
+ expect(describeAutopilotVerification('editorialChecks', { findings: 2, blocking: 0, errored: 1 }))
+ .toContain('1 errored');
+ });
+
+ it('scores the foundation gate instead of counting findings', () => {
+ expect(describeAutopilotVerification('foundationGate', { weightedScore: 8.1, threshold: 7.5, weakest: 'craft' }))
+ .toBe('weighted 8.1/7.5 · next target: craft');
+ });
+
+ it('is null for a gate that has not reported yet', () => {
+ expect(describeAutopilotVerification('verifyArc', null)).toBe(null);
+ expect(describeAutopilotVerification('verifyArc', {})).toBe(null);
+ });
+});
+
+describe('autopilotStepLabel', () => {
+ it('labels known step kinds and falls back to the raw kind', () => {
+ expect(autopilotStepLabel('editorialHealthGate')).toBe('Editorial health gate');
+ expect(autopilotStepLabel('somethingNew')).toBe('somethingNew');
+ });
+});
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 69c432623d..f3bb2bf8b9 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -18,6 +18,7 @@ export * from './universeRunTag.js';
export * from './universeStylePreset.js';
// === Pipeline / image-gen defaults ===
+export * from './autopilotMilestones.js';
export * from './beatColors.js';
export * from './beatGrid.js';
export * from './bibleLimits.js';
diff --git a/server/lib/sseUtils.js b/server/lib/sseUtils.js
index 98425551dc..8feb81532a 100644
--- a/server/lib/sseUtils.js
+++ b/server/lib/sseUtils.js
@@ -26,12 +26,18 @@ export const PYTHON_NOISE_RE = /xformers|xFormers|triton|Triton|bitsandbytes|Ple
// `job.lastPayload`) instead of hanging until timeout.
export const SSE_CLEANUP_DELAY_MS = 5000;
-export const broadcastSse = (job, payload) => {
+export const broadcastSse = (job, payload, { retain = true } = {}) => {
// Cache the most recent payload on the job so attachSseClient can replay
// it to a client that connects after this fired. Without this, a client
// that races with `complete` would hang waiting for a frame that already
// shipped.
- job.lastPayload = payload;
+ //
+ // `retain: false` is for frames that are a running SNAPSHOT of state a late
+ // client can fetch another way (the autopilot's `progress` frame, whose
+ // content the status route also serves). Retaining those would let them
+ // occupy the single replay slot and hide the last frame that said what the
+ // run is actually doing.
+ if (retain) job.lastPayload = payload;
const msg = `data: ${JSON.stringify(payload)}\n\n`;
for (const c of job.clients) c.write(msg);
};
diff --git a/server/routes/pipeline/autopilot.js b/server/routes/pipeline/autopilot.js
index d569fc0f45..5859e12d21 100644
--- a/server/routes/pipeline/autopilot.js
+++ b/server/routes/pipeline/autopilot.js
@@ -15,10 +15,12 @@
* POST /series/:id/autopilot/pause → { pauseRequested }
* Finishes the active step/transaction
* without stopping its provider run.
- * GET /series/:id/autopilot/status → { autopilot, active, start }
+ * GET /series/:id/autopilot/status → { autopilot, active, start, progress }
* (resume / paused UI; `start` is the
* in-flight run's start frame, which
- * names its provider/model)
+ * names its provider/model and carries
+ * the projected plan; `progress` is the
+ * run's position in that plan)
*/
import { Router } from 'express';
@@ -253,10 +255,14 @@ router.get('/series/:id/autopilot/status', asyncHandler(async (req, res) => {
autopilot: series.autopilot || null,
active: autopilot.isAutopilotActive(req.params.id),
pauseRequested: autopilot.isAutopilotPauseRequested(req.params.id),
- // The in-flight run's `start` frame (mode, target, resolved provider/model),
- // so a client attaching mid-run can describe a run it never saw begin — SSE
- // replays only the last frame. null when no run is active.
+ // The in-flight run's `start` frame (mode, target, resolved provider/model,
+ // the projected plan), so a client attaching mid-run can describe a run it
+ // never saw begin — SSE replays only the last frame. null when none active.
start: autopilot.activeRunStart(req.params.id),
+ // Where that run currently IS against the plan — completed counts per step,
+ // the running step, and each gate's latest verification. Without it a panel
+ // opened mid-run would draw every milestone as still pending.
+ progress: autopilot.activeRunProgress(req.params.id),
});
}));
diff --git a/server/services/pipeline/seriesAutopilot.test.js b/server/services/pipeline/seriesAutopilot.test.js
index b781506394..76b1af4c32 100644
--- a/server/services/pipeline/seriesAutopilot.test.js
+++ b/server/services/pipeline/seriesAutopilot.test.js
@@ -1224,6 +1224,143 @@ describe('autopilotEvents in-process bus (#2185)', () => {
});
});
+// ---------------------------------------------------------------------------
+// Milestone map — the plan an EXECUTE run projects + the progress
+// snapshot the panel measures against it.
+// ---------------------------------------------------------------------------
+describe('noteProgress (pure fold)', () => {
+ const { noteProgress, emptyProgress } = autopilot;
+
+ it('marks the running step and clears its complete flag when the run RE-ENTERS a gate', () => {
+ const run = { progress: emptyProgress() };
+ noteProgress(run, { type: 'step:start', kind: 'foundationGate', ordinal: 3 });
+ noteProgress(run, { type: 'step:complete', kind: 'foundationGate' });
+ expect(run.progress).toMatchObject({
+ currentStep: 'foundationGate', currentStepComplete: true, completed: { foundationGate: 1 },
+ });
+ // The arc repair sends it back through the same gate — the map must show it
+ // working again rather than reading as the step it just finished.
+ noteProgress(run, { type: 'step:start', kind: 'foundationGate', ordinal: 5 });
+ expect(run.progress).toMatchObject({ currentStep: 'foundationGate', currentStepComplete: false });
+ });
+
+ it('files each gate verification under the step it was measured in', () => {
+ const run = { progress: emptyProgress() };
+ noteProgress(run, { type: 'step:start', kind: 'verifyArcSpine' });
+ noteProgress(run, { type: 'verify:round', scope: 'arcSpine', round: 2, findings: 5, blocking: 0 });
+ noteProgress(run, { type: 'step:start', kind: 'foundationGate' });
+ noteProgress(run, { type: 'foundation:round', round: 1, weightedScore: 8.1, threshold: 7.5, weakest: 'craft' });
+ expect(run.progress.verified).toEqual({
+ verifyArcSpine: { round: 2, findings: 5, blocking: 0 },
+ foundationGate: { round: 1, weightedScore: 8.1, threshold: 7.5, weakest: 'craft' },
+ });
+ });
+
+ it('drops gate telemetry that arrives outside a step rather than filing it nowhere', () => {
+ const run = { progress: emptyProgress() };
+ expect(noteProgress(run, { type: 'verify:round', scope: 'arc', findings: 1, blocking: 1 })).toBe(false);
+ expect(run.progress.verified).toEqual({});
+ });
+
+ it('counts sub-step skips without advancing the milestone', () => {
+ const run = { progress: emptyProgress() };
+ noteProgress(run, { type: 'step:skip', kind: 'visualDraft', reason: 'locked' });
+ expect(run.progress).toMatchObject({ skipped: { visualDraft: 1 }, completed: {} });
+ });
+
+ it('ignores frames the map does not track — including every terminal', () => {
+ const run = { progress: emptyProgress() };
+ for (const type of ['note', 'check:complete', 'complete', 'paused', 'canceled', 'error']) {
+ expect(noteProgress(run, { type })).toBe(false);
+ }
+ expect(run.progress).toEqual(emptyProgress());
+ });
+});
+
+describe('milestone map telemetry', () => {
+ const collectFrames = (seriesId) => {
+ const frames = [];
+ autopilot.autopilotEvents.on(seriesId, (p) => frames.push(p));
+ return frames;
+ };
+
+ it('carries the projected plan on an EXECUTE start frame, not only a dry-run', async () => {
+ const { seriesId } = await seedComplete();
+ const frames = collectFrames(seriesId);
+ await autopilot.startSeriesAutopilot(seriesId, { includeVisual: false });
+ await waitFor(runFinished(seriesId));
+ const start = frames.find((f) => f.type === 'start');
+ expect(start.mode).toBe('execute');
+ // Same projection the dry-run emits — the panel draws it as the milestone map.
+ expect(start.plan.map((p) => p.kind)).toEqual(
+ expect.arrayContaining(['verifyArcSpine', 'verifyArc', 'editorialReview']),
+ );
+ expect(start.planTotals.estActions).toBeGreaterThan(0);
+ });
+
+ it('publishes a progress snapshot as the run advances', async () => {
+ const { seriesId } = await seedComplete();
+ const frames = collectFrames(seriesId);
+ await autopilot.startSeriesAutopilot(seriesId, { includeVisual: false });
+ await waitFor(runFinished(seriesId));
+ const progressFrames = frames.filter((f) => f.type === 'progress');
+ expect(progressFrames.length).toBeGreaterThan(0);
+ const final = progressFrames.at(-1);
+ expect(final.completed.verifyArcSpine).toBe(1);
+ expect(final.completed.editorialReview).toBe(1);
+ // …and what each gate actually validated, keyed by step kind.
+ expect(final.verified.verifyArcSpine).toMatchObject({ blocking: 0 });
+ });
+
+ it('publishes DETACHED snapshots — a later step cannot rewrite a delivered frame', async () => {
+ const { seriesId } = await seedComplete();
+ const frames = collectFrames(seriesId);
+ await autopilot.startSeriesAutopilot(seriesId, { includeVisual: false });
+ await waitFor(runFinished(seriesId));
+ const progressFrames = frames.filter((f) => f.type === 'progress');
+ const first = progressFrames[0];
+ const last = progressFrames.at(-1);
+ // The fold mutates the maps it owns; if the frames shared them, the first
+ // frame would report the final run's counts and the map would jump.
+ expect(first.completed).not.toBe(last.completed);
+ expect(Object.keys(first.completed).length).toBeLessThan(Object.keys(last.completed).length);
+ });
+
+ it('never emits a progress frame after the terminal one (SSE replays only the last payload)', async () => {
+ const { seriesId } = await seedComplete();
+ const frames = collectFrames(seriesId);
+ await autopilot.startSeriesAutopilot(seriesId, { includeVisual: false });
+ await waitFor(runFinished(seriesId));
+ const terminalAt = frames.findIndex((f) => autopilot.AUTOPILOT_TERMINAL_TYPES.has(f.type));
+ expect(terminalAt).toBeGreaterThan(-1);
+ expect(frames.slice(terminalAt + 1).some((f) => f.type === 'progress')).toBe(false);
+ expect(autopilot.__testing.runs.get(seriesId)?.lastPayload?.type).toBe('complete');
+ });
+
+ it('does not let a progress frame take the SSE replay slot from a real frame', async () => {
+ const { seriesId } = await seedComplete();
+ await autopilot.startSeriesAutopilot(seriesId, { includeVisual: false });
+ await waitFor(runFinished(seriesId));
+ // A client attaching late replays `lastPayload`; a snapshot there would hide
+ // what the run was doing (and, at the end, that it finished at all).
+ expect(autopilot.__testing.runs.get(seriesId)?.lastPayload?.type).not.toBe('progress');
+ });
+
+ it('serves the snapshot to a client attaching mid-run, and nothing once the run is over', async () => {
+ const { seriesId } = await seedComplete();
+ let midRun = null;
+ // Sample the accessor from inside the run — the mid-run attach the status
+ // route serves — rather than after it, when the record is finished.
+ autopilot.autopilotEvents.on(seriesId, (f) => {
+ if (f.type === 'step:complete' && !midRun) midRun = autopilot.activeRunProgress(seriesId);
+ });
+ await autopilot.startSeriesAutopilot(seriesId, { includeVisual: false });
+ await waitFor(runFinished(seriesId));
+ expect(midRun.currentStep).toBeTruthy();
+ expect(autopilot.activeRunProgress(seriesId)).toBe(null);
+ });
+});
+
describe('dry-run plan ↔ resolveNextStep drift guard (#1577)', () => {
// buildDryRunPlan is kept in sync with resolveNextStep BY HAND (see the comment
// above buildDryRunPlan). This guard runs BOTH against the same fixtures and
diff --git a/server/services/pipeline/seriesAutopilot/orchestrator.js b/server/services/pipeline/seriesAutopilot/orchestrator.js
index c19501a7f9..6d6c175d5e 100644
--- a/server/services/pipeline/seriesAutopilot/orchestrator.js
+++ b/server/services/pipeline/seriesAutopilot/orchestrator.js
@@ -15,7 +15,7 @@ import { getSettings } from '../../settings.js';
import { getSeries, updateSeries } from '../series.js';
import { listIssues } from '../issues.js';
import { buildEditorialCheckPlan } from '../editorial/checkRunner.js';
-import { runs } from './state.js';
+import { runs, emptyProgress } from './state.js';
import {
resolveAutopilotRounds, resolveAutopilotFoundationGate, resolveAutopilotFoundationThreshold,
resolveAutopilotReadinessGate, resolveAutopilotCheckPauseThreshold, resolveAutopilotNotifyOnPause,
@@ -169,6 +169,9 @@ export async function startSeriesAutopilot(sId, options = {}) {
// that didn't opt in.
signals: [],
signalsDropped: 0,
+ // Milestone-map cursor (see state.js#noteProgress) — folded from this run's
+ // own frames by `broadcast`, and readable mid-run off the status route.
+ progress: emptyProgress(),
runState: {
// Unlock-everything pre-pass (opt-in, see unlockPass.js) has run this
// run. Boolean latch like arcVerified so the resolver routes there at
@@ -254,6 +257,20 @@ export async function startSeriesAutopilot(sId, options = {}) {
};
};
+ // The projected plan — every step this run expects to take, in order, with its
+ // count and cost estimate. A dry-run emits it as its whole product; an EXECUTE
+ // run emits the same thing as the milestone map the panel measures progress
+ // against ("what it has validated, where it is, what is left"). Pure reads plus
+ // one already-loaded settings object: no LLM spend, and every caller treats a
+ // failure as "no map" rather than a reason not to run.
+ const projectPlan = async (series, issues) => {
+ const checkPlan = await buildEditorialCheckPlan(sId, { checkIds: editorialSubsetIds(runOptions), settings })
+ .catch(() => null);
+ const editorialLlmCheckCount = checkPlan ? checkPlan.checks.filter((c) => c.kind === 'llm').length : undefined;
+ const plan = buildDryRunPlan(series, issues, runOptions, { editorialLlmCheckCount });
+ return { plan, planTotals: summarizePlanCost(plan) };
+ };
+
// Post-mortem hook for the opt-in diagnosis passes. Best-effort by contract:
// a diagnosis that throws must never turn a completed run into a failed one,
// so every terminal calls it through these catches. Never fires on a cancel
@@ -322,16 +339,8 @@ export async function startSeriesAutopilot(sId, options = {}) {
try {
// DRY-RUN: enumerate the plan, no side effects.
if (mode === 'dry-run') {
- const series = await getSeries(sId);
- const issues = await listIssues({ seriesId: sId });
- // Resolve the enabled LLM-check count (#1576) so the plan's editorialChecks
- // step can estimate its issues × checks LLM fan-out. Mirrors the actual
- // pass: same subset (editorialSubsetIds) and same settings the checks read.
- const settings = await getSettings().catch(() => null);
- const checkPlan = await buildEditorialCheckPlan(sId, { checkIds: editorialSubsetIds(runOptions), settings }).catch(() => null);
- const editorialLlmCheckCount = checkPlan ? checkPlan.checks.filter((c) => c.kind === 'llm').length : undefined;
- const plan = buildDryRunPlan(series, issues, runOptions, { editorialLlmCheckCount });
- const planTotals = summarizePlanCost(plan);
+ const [series, issues] = await Promise.all([getSeries(sId), listIssues({ seriesId: sId })]);
+ const { plan, planTotals } = await projectPlan(series, issues);
broadcastStart(sId, startFrame(series.targetFormat, { plan, planTotals }));
// Carry the plan on the terminal frame too: a dry-run emits start +
// complete synchronously, often before the client attaches, and
@@ -343,8 +352,16 @@ export async function startSeriesAutopilot(sId, options = {}) {
}
// EXECUTE.
- const series0 = await getSeries(sId);
- broadcastStart(sId, startFrame(series0.targetFormat));
+ const [series0, issues0] = await Promise.all([getSeries(sId), listIssues({ seriesId: sId })]);
+ // Same projection the dry-run produces, carried on the start frame so the
+ // panel can draw the milestone map (and the estimated budget) for a run
+ // that is actually working — not only for a preview. Best-effort: a run
+ // must never fail to start because its map couldn't be drawn.
+ const projected = await projectPlan(series0, issues0).catch((err) => {
+ console.log(`⚠️ autopilot: plan projection failed for ${sId.slice(0, 12)}: ${err.message}`);
+ return {};
+ });
+ broadcastStart(sId, startFrame(series0.targetFormat, projected));
await persistMarker(sId, { status: 'running', runId, currentStep: null, residualFindings: [], lastError: null });
// A resume is a fresh start: drop any stale pause banner up front so a run
// that completes/errors without re-pausing doesn't leave a dead resume link.
@@ -358,9 +375,15 @@ export async function startSeriesAutopilot(sId, options = {}) {
broadcast(sId, { type: 'note', message: 'Draft visual rendering is not enabled in this build — running to text-ready + editorial review.' });
}
+ // The projection above read the very state the first iteration wants, and
+ // nothing between here and there touches series/issues — so hand it over
+ // rather than re-loading every issue (with its stage run history) twice at
+ // every run start. Cleared on use; every later iteration reads fresh.
+ let preloaded = { series: series0, issues: issues0 };
while (!record.cancelRequested && !record.pauseRequested) {
- const series = await getSeries(sId);
- const issues = await listIssues({ seriesId: sId });
+ const series = preloaded?.series || await getSeries(sId);
+ const issues = preloaded?.issues || await listIssues({ seriesId: sId });
+ preloaded = null;
const step = resolveNextStep(series, issues, record.runState, runOptions);
if (step.kind === 'done') {
diff --git a/server/services/pipeline/seriesAutopilot/session.js b/server/services/pipeline/seriesAutopilot/session.js
index a32975286c..1e08e0143b 100644
--- a/server/services/pipeline/seriesAutopilot/session.js
+++ b/server/services/pipeline/seriesAutopilot/session.js
@@ -12,7 +12,7 @@ import { getSeries, updateSeries } from '../series.js';
import * as volumeBeatsRunner from '../volumeBeatsRunner.js';
import * as autoRunner from '../autoRunner.js';
import { patchRunMetadata, stopRun } from '../../runner.js';
-import { runs, autopilotEvents, noteSignal } from './state.js';
+import { runs, autopilotEvents, noteSignal, noteProgress, snapshotProgress } from './state.js';
// ---------------------------------------------------------------------------
// Run registry helpers (mirror editorialAnalysisRunner.js).
@@ -40,6 +40,17 @@ export function activeRunStart(seriesId) {
return run.startPayload || null;
}
+// The live progress snapshot of an IN-FLIGHT run (null when none is active) —
+// the milestone map's cursor: completed counts per step kind, the step running
+// now, and what each gate last verified. Same object the `progress` frame
+// carries, so a client attaching mid-run starts from the run's real position
+// instead of an empty map.
+export function activeRunProgress(seriesId) {
+ const run = runs.get(seriesId);
+ if (!run || run.finished) return null;
+ return snapshotProgress(run);
+}
+
export function attachClient(seriesId, res) {
return attachSseClient(runs, seriesId, res);
}
@@ -86,10 +97,8 @@ export function pauseSeriesAutopilot(seriesId) {
return true;
}
-export function broadcast(seriesId, payload) {
- const run = runs.get(seriesId);
- if (!run) return;
- broadcastSse(run, payload);
+function emitFrame(run, seriesId, payload, sseOpts) {
+ broadcastSse(run, payload, sseOpts);
// Retain the diagnosable frames for the opt-in self-improvement pass. A single
// tap here (rather than instrumenting each step runner) means any telemetry
// frame a future step emits is diagnosable evidence for free. No-op unless the
@@ -107,6 +116,23 @@ export function broadcast(seriesId, payload) {
}
}
+export function broadcast(seriesId, payload) {
+ const run = runs.get(seriesId);
+ if (!run) return;
+ emitFrame(run, seriesId, payload);
+ // Milestone map: fold the frame into the run's progress snapshot and, when it
+ // moved, follow it with the snapshot itself. Emitted as its own frame (rather
+ // than stamped onto every frame) so the existing frame shapes — and the
+ // diagnosis evidence read off them — are untouched, and NOT retained for SSE
+ // replay: it follows nearly every meaningful frame, so retaining it would take
+ // the single replay slot and leave a late-attaching client with a snapshot
+ // instead of the frame that says what the run is doing. That client reads the
+ // same snapshot off the status route.
+ if (noteProgress(run, payload)) {
+ emitFrame(run, seriesId, { type: 'progress', runId: run.runId, ...snapshotProgress(run) }, { retain: false });
+ }
+}
+
// Broadcast the run's `start` frame AND retain it on the run record, so a
// client attaching mid-run can still read it back via `activeRunStart`.
export function broadcastStart(seriesId, payload) {
diff --git a/server/services/pipeline/seriesAutopilot/state.js b/server/services/pipeline/seriesAutopilot/state.js
index a991eb8bbd..070d1b376a 100644
--- a/server/services/pipeline/seriesAutopilot/state.js
+++ b/server/services/pipeline/seriesAutopilot/state.js
@@ -114,3 +114,98 @@ export function summarizeSignals(run) {
for (const s of signals) counts[s.type] = (counts[s.type] || 0) + 1;
return { signals, counts, dropped: run?.signalsDropped || 0 };
}
+
+// ---------------------------------------------------------------------------
+// Live progress snapshot — the milestone map's "where are we" half (the plan on
+// the `start` frame is the "what's the whole job" half).
+//
+// Everything here is already derivable from frames the run broadcasts, but only
+// by a client that watched the WHOLE stream: SSE replays a single payload, so a
+// panel opened mid-run (the normal case for a long unattended run) would show an
+// empty map. Folding it onto the run record instead means the snapshot has ONE
+// implementation, published two ways — a `progress` frame after every frame that
+// moves it, and the same object on the status route for a mid-run attach.
+// ---------------------------------------------------------------------------
+
+/** A fresh, empty progress snapshot (the shape every consumer can assume). */
+export const emptyProgress = () => ({
+ currentStep: null,
+ currentStepComplete: false,
+ completed: {},
+ skipped: {},
+ verified: {},
+});
+
+/**
+ * A detached copy of the run's live progress. The fold MUTATES the maps it owns,
+ * so handing the live object to an SSE payload / event listener would let a
+ * later step silently rewrite a frame that was already delivered — the reader
+ * would see counts from the future. One shallow clone per published snapshot.
+ */
+export function snapshotProgress(run) {
+ const p = run?.progress;
+ if (!p) return null;
+ return { ...p, completed: { ...p.completed }, skipped: { ...p.skipped }, verified: { ...p.verified } };
+}
+
+/**
+ * Fold one broadcast frame into the run's progress snapshot. Returns true when
+ * the snapshot MOVED (so the caller publishes it) and false otherwise, which is
+ * the common case — most frames are chatter the map doesn't track.
+ *
+ * Deliberately never folds a terminal frame: the caller publishes the snapshot
+ * as a follow-up frame, and SSE replay keeps only the last payload, so a
+ * `progress` frame emitted after `complete`/`paused` would hide the terminal
+ * from a client that attaches late.
+ */
+export function noteProgress(run, payload) {
+ if (!run || !payload) return false;
+ if (!run.progress) run.progress = emptyProgress();
+ const p = run.progress;
+ switch (payload.type) {
+ case 'step:start':
+ p.currentStep = payload.kind || null;
+ p.currentStepComplete = false;
+ return true;
+ case 'step:complete':
+ // `currentStep` is deliberately NOT cleared: the next step:start replaces
+ // it within the same tick, and leaving it set means a run that pauses or
+ // ends right here still names the step it was on. `currentStepComplete` is
+ // what separates the two readings — without it, a gate the run RE-ENTERS
+ // (the foundation gate re-checks after an arc repair) is indistinguishable
+ // from one it just finished, and the map shows the wrong row working.
+ if (payload.kind) p.completed[payload.kind] = (p.completed[payload.kind] || 0) + 1;
+ if (!payload.kind || payload.kind === p.currentStep) p.currentStepComplete = true;
+ return true;
+ case 'step:skip':
+ // Sub-step skips (one issue's render, one script's craft pass) — the step
+ // itself still completes, so these annotate a milestone rather than
+ // advancing it.
+ if (payload.kind) p.skipped[payload.kind] = (p.skipped[payload.kind] || 0) + 1;
+ return true;
+ // Both gate-telemetry frames are broadcast from INSIDE the step they
+ // measure, so the step already being tracked IS the milestone they belong
+ // to. Keying off it (rather than translating the frame's `scope`) means a
+ // new gate needs no naming table kept in sync with its emitter.
+ case 'verify:round':
+ if (!p.currentStep) return false;
+ p.verified[p.currentStep] = {
+ round: payload.round ?? null,
+ findings: payload.findings ?? null,
+ blocking: payload.blocking ?? null,
+ ...(payload.errored ? { errored: payload.errored } : {}),
+ };
+ return true;
+ case 'foundation:round':
+ if (!p.currentStep) return false;
+ p.verified[p.currentStep] = {
+ round: payload.round ?? null,
+ weightedScore: payload.weightedScore ?? null,
+ threshold: payload.threshold ?? null,
+ ...(payload.weakest ? { weakest: payload.weakest } : {}),
+ };
+ return true;
+ default:
+ return false;
+ }
+}