Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([issue-1289]): model the arc ticking clock / countdown the reader anticipates
[._.]/ Adam Eivyba354e9a0eec
diff --git a/client/src/components/pipeline/ArcCanvas.jsx b/client/src/components/pipeline/ArcCanvas.jsxindex 56272efb0f..8e87c945e7 100644--- a/client/src/components/pipeline/ArcCanvas.jsx+++ b/client/src/components/pipeline/ArcCanvas.jsx@@ -30,6 +30,7 @@ import {Plus, Trash2, Loader2, Sparkles, ShieldCheck, ChevronRight, ChevronDown,ChevronsUpDown, AlertCircle, Wand2, Info, ListChecks, X, Lock, Unlock,ImageIcon, Layers, FileDown, BookOpen, ChartSpline, FileSearch, BookText, FileText,+ Clock,} from 'lucide-react';import toast from '../ui/Toast';import { timeAgo } from '../../utils/formatters';@@ -1294,6 +1295,133 @@ function FieldLockToggle({ series, field, label, onSeriesUpdate }) {);}+// Mirror of TICKING_CLOCK_KINDS in server/lib/storyArc.js. The server is the+// validation authority (unknown kinds fall back to 'custom'); this list only+// drives the picker options.+const TICKING_CLOCK_KINDS = ['deadline', 'event', 'countdown', 'prophecy', 'bomb', 'custom'];++// Inline editor for the arc's singular ticking clock / countdown. Edits merge+// into a single `tickingClock` object the parent stores under `draft`; the+// reminder beats themselves are authored via the reader map, so this editor+// shows their count but doesn't manage the list.+function TickingClockEditor({ clock, disabled, onChange }) {+ const c = clock || {};+ const enabled = c.enabled === true;+ const patch = (p) => onChange({ ...c, ...p });+ const numOrNull = (v) => (v === '' ? null : Math.max(0, Math.min(9999, Math.floor(Number(v) || 0))));+ return (+ <fieldset className="rounded border border-port-border bg-port-bg/50 p-2 space-y-2">+ <label className="flex items-center gap-2 text-xs text-gray-300 cursor-pointer">+ <input+ type="checkbox"+ checked={enabled}+ disabled={disabled}+ onChange={(e) => patch({ enabled: e.target.checked })}+ />+ <span className="inline-flex items-center gap-1.5"><Clock size={12} /> Ticking clock / countdown</span>+ </label>+ {enabled ? (+ <div className="space-y-2 pl-1">+ <input+ id="ticking-clock-label"+ type="text"+ value={c.label || ''}+ onChange={(e) => patch({ label: e.target.value })}+ placeholder="What the reader counts down to (e.g. “The storm makes landfall”)"+ maxLength={200}+ disabled={disabled}+ className="w-full px-2 py-1 bg-port-bg border border-port-border rounded text-white text-sm"+ />+ <div className="flex flex-wrap gap-x-3 gap-y-2">+ <div className="flex items-center gap-1.5">+ <label htmlFor="ticking-clock-kind" className="text-[10px] uppercase tracking-wider text-gray-500">Kind</label>+ <select+ id="ticking-clock-kind"+ value={c.kind || 'custom'}+ onChange={(e) => patch({ kind: e.target.value })}+ disabled={disabled}+ className="px-2 py-1 bg-port-bg border border-port-border rounded text-white text-xs"+ >+ {TICKING_CLOCK_KINDS.map((k) => <option key={k} value={k}>{k}</option>)}+ </select>+ </div>+ <div className="flex items-center gap-1.5">+ <label htmlFor="ticking-clock-planted" className="text-[10px] uppercase tracking-wider text-gray-500">Planted at</label>+ <input+ id="ticking-clock-planted"+ type="number"+ min={0}+ max={9999}+ value={c.plantedAtArcPosition ?? ''}+ onChange={(e) => patch({ plantedAtArcPosition: numOrNull(e.target.value) })}+ disabled={disabled}+ className="w-20 px-2 py-1 bg-port-bg border border-port-border rounded text-white text-xs"+ />+ </div>+ <div className="flex items-center gap-1.5">+ <label htmlFor="ticking-clock-due" className="text-[10px] uppercase tracking-wider text-gray-500">Due at</label>+ <input+ id="ticking-clock-due"+ type="number"+ min={0}+ max={9999}+ value={c.dueAtArcPosition ?? ''}+ onChange={(e) => patch({ dueAtArcPosition: numOrNull(e.target.value) })}+ disabled={disabled}+ className="w-20 px-2 py-1 bg-port-bg border border-port-border rounded text-white text-xs"+ />+ </div>+ </div>+ <textarea+ id="ticking-clock-stakes"+ value={c.stakes || ''}+ onChange={(e) => patch({ stakes: e.target.value })}+ placeholder="Stakes — what happens if the clock runs out"+ rows={2}+ maxLength={1000}+ disabled={disabled}+ className="w-full px-2 py-1 bg-port-bg border border-port-border rounded text-white text-sm"+ />+ {Array.isArray(c.reminders) && c.reminders.length ? (+ <p className="text-[10px] text-gray-500 italic">{c.reminders.length} reminder beat(s) — authored via the reader map.</p>+ ) : null}+ </div>+ ) : null}+ </fieldset>+ );+}++// Read-only ticking-clock card for the arc view. Hidden unless the clock is+// enabled (a disabled/absent clock means "this story has no countdown").+function TickingClockCard({ clock, series, onSeriesUpdate }) {+ if (!clock || clock.enabled !== true) return null;+ const span = clock.plantedAtArcPosition != null || clock.dueAtArcPosition != null+ ? `${clock.plantedAtArcPosition ?? '?'} → ${clock.dueAtArcPosition ?? '?'}`+ : null;+ const reminders = Array.isArray(clock.reminders) ? clock.reminders : [];+ return (+ <div className="rounded border border-port-warning/40 bg-port-bg/50 px-2 py-1.5 space-y-1">+ <div className="flex items-center gap-1.5">+ <Clock size={12} className="text-port-warning shrink-0" />+ <span className="text-xs font-medium text-white truncate">{clock.label || 'Ticking clock'}</span>+ <span className="text-[10px] uppercase tracking-wider text-gray-500">{clock.kind || 'custom'}</span>+ {span ? <span className="text-[10px] text-gray-400 ml-auto">arc {span}</span> : null}+ <span className={span ? '' : 'ml-auto'}>+ <FieldLockToggle series={series} field="tickingClock" label="Ticking clock" onSeriesUpdate={onSeriesUpdate} />+ </span>+ </div>+ {clock.stakes ? <p className="text-[11px] text-gray-400 whitespace-pre-wrap">{clock.stakes}</p> : null}+ {reminders.length ? (+ <ul className="text-[11px] text-gray-500 list-disc list-inside">+ {reminders.map((r) => (+ <li key={r.id}>{r.note || `Reminder at issue ${r.atIssue ?? '?'}`}{r.note && r.atIssue != null ? ` (issue ${r.atIssue})` : ''}</li>+ ))}+ </ul>+ ) : null}+ </div>+ );+}+function ArcContent({ series, onSeriesUpdate }) {const arc = series.arc;const [editing, setEditing] = useState(false);@@ -1356,6 +1484,11 @@ function ArcContent({ series, onSeriesUpdate }) {onChange={(shape) => setDraft({ ...draft, shape })}disabled={saving}/>+ <TickingClockEditor+ clock={draft.tickingClock}+ disabled={saving}+ onChange={(tickingClock) => setDraft({ ...draft, tickingClock })}+ /><p className="text-[10px] text-gray-500 italic">Themes are edited inline above — click a pill to rename, hover for ×, or use the dashed “+ Add theme” chip.</p><div className="flex items-center gap-2"><button@@ -1403,6 +1536,7 @@ function ArcContent({ series, onSeriesUpdate }) {<FieldLockToggle series={series} field="shape" label="Shape" onSeriesUpdate={onSeriesUpdate} /></div>) : null}+ <TickingClockCard clock={arc.tickingClock} series={series} onSeriesUpdate={onSeriesUpdate} /><div className="grid grid-cols-1 md:grid-cols-2 gap-2">{arc.summary ? (<detailsdiff --git a/client/src/pages/StoryBuilder.jsx b/client/src/pages/StoryBuilder.jsxindex 596fc9e1bc..25b1e3a282 100644--- a/client/src/pages/StoryBuilder.jsx+++ b/client/src/pages/StoryBuilder.jsx@@ -464,8 +464,30 @@ function ReaderMapBeatTimeline({ readerMap }) {);}-function ReaderMapView({ readerMap }) {- if (!readerMap) return <p className="text-gray-600 italic text-sm">No reader map yet. Generate one to plan the audience experience.</p>;+// Compact read-only summary of the arc's ticking clock — shown above the reader+// map so the countdown the reader anticipates sits alongside the hooks/payoffs+// it threads through. Authored in the Arc Canvas; null/disabled clocks hide.+function TickingClockSummary({ clock }) {+ if (!clock || clock.enabled !== true) return null;+ const span = clock.plantedAtArcPosition != null || clock.dueAtArcPosition != null+ ? ` · arc ${clock.plantedAtArcPosition ?? '?'} → ${clock.dueAtArcPosition ?? '?'}` : '';+ const reminderCount = Array.isArray(clock.reminders) ? clock.reminders.length : 0;+ return (+ <div className="rounded border border-port-warning/40 bg-port-bg/50 px-2 py-1.5">+ <div className="text-xs uppercase tracking-wide text-gray-500 mb-0.5">Ticking clock</div>+ <div className="text-sm text-gray-300">+ ⏱ {clock.label || '(unnamed countdown)'} <span className="text-gray-500">({clock.kind || 'custom'}{span})</span>+ </div>+ {clock.stakes ? <div className="text-xs text-gray-400 mt-0.5">{clock.stakes}</div> : null}+ {reminderCount ? <div className="text-[11px] text-gray-500 mt-0.5">{reminderCount} reminder beat(s)</div> : null}+ </div>+ );+}++function ReaderMapView({ readerMap, tickingClock }) {+ if (!readerMap && !(tickingClock && tickingClock.enabled === true)) {+ return <p className="text-gray-600 italic text-sm">No reader map yet. Generate one to plan the audience experience.</p>;+ }const Section = ({ title, items, render }) => (items?.length ? (<div>@@ -476,10 +498,11 @@ function ReaderMapView({ readerMap }) {);return (<div className="space-y-3">- <Section title="Hooks" items={readerMap.hooks} render={(h) => `${h.atArcPosition != null ? `@${h.atArcPosition} · ` : ''}${h.label}${h.note ? ` — ${h.note}` : ''}`} />- <Section title="Payoffs" items={readerMap.payoffs} render={(p) => `${p.atArcPosition != null ? `@${p.atArcPosition} · ` : ''}${p.label}`} />- <Section title="Beats" items={readerMap.beats} render={(b) => `[${b.kind}${b.intensity != null ? ` ${Math.round(b.intensity * 100)}%` : ''}] ${b.note || ''}`} />- <Section title="Cliffhangers" items={readerMap.cliffhangers} render={(c) => `after #${c.atIssueBoundary ?? '?'} — ${c.note || ''}`} />+ <TickingClockSummary clock={tickingClock} />+ <Section title="Hooks" items={readerMap?.hooks} render={(h) => `${h.atArcPosition != null ? `@${h.atArcPosition} · ` : ''}${h.label}${h.note ? ` — ${h.note}` : ''}`} />+ <Section title="Payoffs" items={readerMap?.payoffs} render={(p) => `${p.atArcPosition != null ? `@${p.atArcPosition} · ` : ''}${p.label}`} />+ <Section title="Beats" items={readerMap?.beats} render={(b) => `[${b.kind}${b.intensity != null ? ` ${Math.round(b.intensity * 100)}%` : ''}] ${b.note || ''}`} />+ <Section title="Cliffhangers" items={readerMap?.cliffhangers} render={(c) => `after #${c.atIssueBoundary ?? '?'} — ${c.note || ''}`} /></div>);}@@ -729,7 +752,7 @@ function StepPanel({ session, universe, series, issues, stepId, locked, onChangereturn (<div className="space-y-3"><ReaderMapBeatTimeline readerMap={arc.readerMap} />- <ReaderMapView readerMap={arc.readerMap} />+ <ReaderMapView readerMap={arc.readerMap} tickingClock={arc.tickingClock} />{!locked && genButton('Generate reader map', Boolean(arc.readerMap))}{!locked && arc.readerMap && <RefineBox onRefine={(fb) => runRefine(fb)} busy={busy} running={isRunning('refine')} phase={phase} />}</div>diff --git a/server/lib/editorial/checkRegistry.js b/server/lib/editorial/checkRegistry.jsindex c02e2baff0..9f3514eb7e 100644--- a/server/lib/editorial/checkRegistry.js+++ b/server/lib/editorial/checkRegistry.js@@ -251,6 +251,99 @@ export const EDITORIAL_CHECKS = [return findings;},},+ {+ id: 'arc.ticking-clock-hygiene',+ label: 'Ticking-clock hygiene',+ description:+ 'Advisory — checks the series ticking clock/countdown is fully specified: named, with stakes, a plant→due span, and reminder beats so the reader does not forget it through the long middle.',+ scope: 'series',+ kind: 'deterministic',+ category: 'arc',+ severityDefault: 'low',+ defaultEnabled: true,+ configSchema: z.object({+ // How many reminder beats an enabled clock should carry. 0 disables the+ // reminder-count check while keeping the named/stakes/span checks.+ minReminders: z.number().int().min(0).max(20).default(1),+ }),+ configFields: [+ {+ key: 'minReminders',+ label: 'Minimum reminder beats',+ type: 'number',+ min: 0,+ max: 20,+ step: 1,+ help: 'How many reminder beats an enabled ticking clock should have so the reader does not forget it through the long middle.',+ },+ ],+ // Only audit a clock the author turned on — a disabled/absent clock means+ // "this story has no countdown", which is a valid choice, not a problem.+ gate: (ctx) => ctx.series?.arc?.tickingClock?.enabled === true,+ run: (ctx) => {+ const clock = ctx.series?.arc?.tickingClock;+ if (!clock || clock.enabled !== true) return [];+ const minReminders = ctx.config?.minReminders ?? 1;+ const label = clock.label || 'the ticking clock';+ const location = `Series arc: ${clock.label || 'ticking clock'}`;+ const findings = [];+ const flag = (problem, suggestion) => findings.push({+ severity: ctx.severityDefault,+ category: 'arc',+ location,+ problem,+ suggestion,+ anchorQuote: clock.label || '',+ issueNumber: null,+ });+ if (!clock.label) {+ flag(+ 'The ticking clock is enabled but unnamed — the reader needs a concrete thing to count down to.',+ 'Give the countdown a specific label (e.g. "The storm makes landfall").',+ );+ }+ if (!clock.stakes) {+ flag(+ `The ticking clock "${label}" has no stakes — it is unclear what the reader fears if it runs out.`,+ 'State what happens when the clock hits zero so the countdown carries dread.',+ );+ }+ if (clock.plantedAtArcPosition == null) {+ flag(+ `The ticking clock "${label}" has no plant position — the reader never learns the countdown has started.`,+ 'Set where the reader first learns of the countdown (plantedAtArcPosition).',+ );+ }+ if (clock.dueAtArcPosition == null) {+ flag(+ `The ticking clock "${label}" has no due position — there is no moment it lands.`,+ 'Set where the countdown pays off (dueAtArcPosition).',+ );+ }+ // Plant and due share the arc-position coordinate space, so they're+ // directly comparable; a due at/before the plant leaves no span for+ // tension to build. (Reminders use issue numbers, a different axis, so+ // they're intentionally NOT compared against the plant/due span here.)+ if (+ clock.plantedAtArcPosition != null+ && clock.dueAtArcPosition != null+ && clock.dueAtArcPosition <= clock.plantedAtArcPosition+ ) {+ flag(+ `The ticking clock "${label}" is due (arc position ${clock.dueAtArcPosition}) at or before it is planted (${clock.plantedAtArcPosition}) — there is no span for tension to build.`,+ 'Set the due position after the plant position.',+ );+ }+ const reminders = Array.isArray(clock.reminders) ? clock.reminders : [];+ if (reminders.length < minReminders) {+ flag(+ `The ticking clock "${label}" has ${reminders.length} reminder beat(s) (expected at least ${minReminders}) — without periodic reminders the reader forgets it through the long middle.`,+ 'Add reminder beats between the plant and due to keep the countdown alive in the reader’s mind.',+ );+ }+ return findings;+ },+ },{id: 'prose.info-dumping',label: 'Info-dumping / "as you know, Bob" exposition',diff --git a/server/lib/editorial/checkRegistry.test.js b/server/lib/editorial/checkRegistry.test.jsindex bd1a10c240..014158bc26 100644--- a/server/lib/editorial/checkRegistry.test.js+++ b/server/lib/editorial/checkRegistry.test.js@@ -320,3 +320,65 @@ describe('relationships.opposition-reversal — deterministic advisory', () => {expect(getCheck('relationships.opposition-reversal').defaultEnabled).toBe(false);});});++describe('arc.ticking-clock-hygiene — deterministic advisory', () => {+ const CLOCK = 'arc.ticking-clock-hygiene';+ const run = (tickingClock, config = { minReminders: 1 }) =>+ getCheck(CLOCK).run({ series: { arc: { tickingClock } }, config, severityDefault: 'low' });+ const check = getCheck(CLOCK);+ const gate = (tickingClock) => check.gate({ series: { arc: { tickingClock } } });++ it('gate fires only for an enabled clock', () => {+ expect(gate(undefined)).toBe(false);+ expect(gate({ enabled: false, label: 'x' })).toBe(false);+ expect(gate({ enabled: true })).toBe(true);+ });++ it('returns nothing for a fully-specified clock', () => {+ const findings = run({+ enabled: true,+ label: 'The storm makes landfall',+ kind: 'event',+ plantedAtArcPosition: 1,+ dueAtArcPosition: 8,+ stakes: 'The town floods.',+ reminders: [{ id: 'rm-1', atIssue: 4, note: 'barometer drops' }],+ });+ expect(findings).toEqual([]);+ });++ it('flags an enabled clock missing name, stakes, plant, due, and reminders', () => {+ const findings = run({ enabled: true });+ const problems = findings.map((f) => f.problem).join(' | ');+ expect(problems).toMatch(/unnamed/i);+ expect(problems).toMatch(/no stakes/i);+ expect(problems).toMatch(/no plant position/i);+ expect(problems).toMatch(/no due position/i);+ expect(problems).toMatch(/reminder beat/i);+ for (const f of findings) {+ expect(f.category).toBe('arc');+ expect(f.severity).toBe('low');+ }+ });++ it('flags a due position at or before the plant position', () => {+ const findings = run({+ enabled: true, label: 'x', stakes: 's',+ plantedAtArcPosition: 5, dueAtArcPosition: 5,+ reminders: [{ id: 'rm-1', note: 'tick' }],+ });+ expect(findings.some((f) => /at or before it is planted/i.test(f.problem))).toBe(true);+ });++ it('respects minReminders: 0 (skips the reminder-count finding)', () => {+ const findings = run(+ { enabled: true, label: 'x', stakes: 's', plantedAtArcPosition: 1, dueAtArcPosition: 4 },+ { minReminders: 0 },+ );+ expect(findings.some((f) => /reminder beat/i.test(f.problem))).toBe(false);+ });++ it('is enabled by default', () => {+ expect(getCheck(CLOCK).defaultEnabled).toBe(true);+ });+});diff --git a/server/lib/storyArc.js b/server/lib/storyArc.jsindex ab6f8576e2..8573924046 100644--- a/server/lib/storyArc.js+++ b/server/lib/storyArc.js@@ -58,6 +58,22 @@ export const READER_MAP_LIMITS = Object.freeze({export const READER_MAP_BEAT_KINDS = Object.freeze(['hook', 'reveal', 'payoff', 'emotional', 'cliffhanger']);export const READER_MAP_STATUSES = Object.freeze(['draft', 'verified']);+// Ticking clock — the known future event the reader is building toward (a+// deadline, a prophecy's hour, an incoming storm, "what is the story building+// up to"). Where `readerMap.cliffhangers` are local issue-boundary tugs, the+// ticking clock is a *first-class arc concept*: a single countdown planted+// early, reminded through the middle, and paid off at a due position. Lives at+// `series.arc.tickingClock` (a singular object, not a list).+export const TICKING_CLOCK_LIMITS = Object.freeze({+ LABEL_MAX: 200,+ STAKES_MAX: 1000,+ REMINDER_NOTE_MAX: 500,+ REMINDERS_MAX: 40,+ ARC_POSITION_MAX: 9999,+ ISSUE_MAX: 9999,+});+export const TICKING_CLOCK_KINDS = Object.freeze(['deadline', 'event', 'countdown', 'prophecy', 'bomb', 'custom']);+// Per-episode arc roles produced by the season-episodes generator and// persisted on the issue so downstream stages (idea-expansion in particular)// know whether they're writing a pilot vs. midpoint vs. finale episode.@@ -332,6 +348,65 @@ export function sanitizeReaderMap(raw) {return { hooks, payoffs, beats, cliffhangers, status };}+// One reminder beat that keeps the countdown alive in the reader's mind.+// Reuses the `rm-<uuid>` id minter (reminders are reader-map-flavored entries)+// so the client has a stable list key. Dropped when it carries no note and no+// issue pointer — an empty reminder has nothing to render or reason about.+function sanitizeTickingClockReminder(raw) {+ if (!raw || typeof raw !== 'object') return null;+ const note = trimTo(raw.note, TICKING_CLOCK_LIMITS.REMINDER_NOTE_MAX);+ const atIssue = optPosition(raw.atIssue, TICKING_CLOCK_LIMITS.ISSUE_MAX);+ if (!note && atIssue == null) return null;+ return { id: ensureRmId(raw.id), atIssue, note };+}++/**+ * Sanitize the optional singular `series.arc.tickingClock`. Returns `null` when+ * the clock carries no identifying content (disabled, no label/stakes/positions+ * and no reminders) so callers store `null` to mean "no ticking clock" —+ * mirroring `sanitizeReaderMap`. An explicit `enabled: true` is identifying+ * content on its own (the author declared the story *has* a countdown), so a+ * toggled-on-but-otherwise-blank clock survives. Unknown `kind` falls back to+ * `custom` rather than dropping the clock.+ */+export function sanitizeTickingClock(raw) {+ if (raw == null || typeof raw !== 'object') return null;+ const label = trimTo(raw.label, TICKING_CLOCK_LIMITS.LABEL_MAX);+ const stakes = trimTo(raw.stakes, TICKING_CLOCK_LIMITS.STAKES_MAX);+ const kind = TICKING_CLOCK_KINDS.includes(raw.kind) ? raw.kind : 'custom';+ const plantedAtArcPosition = optPosition(raw.plantedAtArcPosition, TICKING_CLOCK_LIMITS.ARC_POSITION_MAX);+ const dueAtArcPosition = optPosition(raw.dueAtArcPosition, TICKING_CLOCK_LIMITS.ARC_POSITION_MAX);+ const reminders = cleanReaderMapList(raw.reminders, sanitizeTickingClockReminder, TICKING_CLOCK_LIMITS.REMINDERS_MAX);+ const enabled = raw.enabled === true;+ if (!enabled && !label && !stakes && plantedAtArcPosition == null && dueAtArcPosition == null && reminders.length === 0) {+ return null;+ }+ return { enabled, label, kind, plantedAtArcPosition, dueAtArcPosition, stakes, reminders };+}++/**+ * Block of ticking-clock guidance for prompt contexts. Returns a single-line+ * string only when the clock is *enabled* (a disabled draft clock must not+ * steer generation), or null otherwise — call sites OR-fold it into the+ * existing `shapeGuidance` block so no stage-prompt template needs a new+ * variable (and thus no migration). Mirrors `renderArcShapeGuidance`.+ */+export function renderTickingClock(clock) {+ if (!clock || clock.enabled !== true) return null;+ const parts = [`Ticking clock / countdown the reader is anticipating: **${clock.label || '(unnamed countdown)'}** (${clock.kind || 'custom'}).`];+ if (clock.stakes) parts.push(`Stakes if it runs out: ${clock.stakes}.`);+ const span = [];+ if (clock.plantedAtArcPosition != null) span.push(`planted at arc position ${clock.plantedAtArcPosition}`);+ if (clock.dueAtArcPosition != null) span.push(`due at arc position ${clock.dueAtArcPosition}`);+ if (span.length) parts.push(`Timing: ${span.join(', ')}.`);+ if (Array.isArray(clock.reminders) && clock.reminders.length) {+ const notes = clock.reminders.map((r) => r.note || `(issue ${r.atIssue ?? '?'})`).join('; ');+ parts.push(`Reminder beats keeping it in the reader's mind: ${notes}.`);+ }+ parts.push('Reinforce this countdown: plant it early, remind the reader through the middle, and pay it off at the due position.');+ return parts.join(' ');+}+/*** Sanitize the optional `series.arc` field. Returns `null` if the input is* empty (no identifying fields) — callers store `null` to mean "no arc yet."@@ -355,9 +430,12 @@ export function sanitizeArc(raw) {// The reader map is identifying content too — an arc that has only a reader// map (e.g. the Story Builder generated it before any logline) must survive.const readerMap = sanitizeReaderMap(raw.readerMap);- if (!logline && !summary && !protagonistArc && themes.length === 0 && !shape && !readerMap) return null;+ // The ticking clock is identifying content as well — an arc whose only+ // authored decision is "this story has a countdown" must round-trip.+ const tickingClock = sanitizeTickingClock(raw.tickingClock);+ if (!logline && !summary && !protagonistArc && themes.length === 0 && !shape && !readerMap && !tickingClock) return null;const status = ARC_STATUSES.includes(raw.status) ? raw.status : 'draft';- return { logline, summary, protagonistArc, themes, shape, readerMap, status };+ return { logline, summary, protagonistArc, themes, shape, readerMap, tickingClock, status };}/**diff --git a/server/lib/storyArc.test.js b/server/lib/storyArc.test.jsindex 5fc78000c9..2f4f4f879e 100644--- a/server/lib/storyArc.test.js+++ b/server/lib/storyArc.test.js@@ -16,6 +16,10 @@ const {sanitizeSeasonList,buildSeason,sanitizeReaderMap,+ sanitizeTickingClock,+ renderTickingClock,+ TICKING_CLOCK_LIMITS,+ TICKING_CLOCK_KINDS,ARC_LIMITS,ARC_SHAPES,ARC_SHAPE_IDS,@@ -49,6 +53,7 @@ describe('storyArc — sanitizeArc', () => {themes: [],shape: null,readerMap: null,+ tickingClock: null,status: 'draft',});});@@ -98,6 +103,100 @@ describe('storyArc — sanitizeArc', () => {// An empty reader map alone is NOT identifying content.expect(sanitizeArc({ readerMap: { hooks: [], payoffs: [], beats: [], cliffhangers: [] } })).toBe(null);});++ it('includes tickingClock (null when absent) and survives an arc with only an enabled clock', () => {+ expect(sanitizeArc({ logline: 'x' }).tickingClock).toBe(null);+ const arc = sanitizeArc({ tickingClock: { enabled: true, label: 'The storm lands' } });+ expect(arc).not.toBe(null);+ expect(arc.logline).toBe('');+ expect(arc.tickingClock.enabled).toBe(true);+ expect(arc.tickingClock.label).toBe('The storm lands');+ // A disabled, content-free clock is NOT identifying content.+ expect(sanitizeArc({ tickingClock: { enabled: false } })).toBe(null);+ });+});++describe('storyArc — sanitizeTickingClock', () => {+ it('returns null for non-objects and content-free disabled clocks', () => {+ expect(sanitizeTickingClock(null)).toBe(null);+ expect(sanitizeTickingClock('x')).toBe(null);+ expect(sanitizeTickingClock({})).toBe(null);+ expect(sanitizeTickingClock({ enabled: false, label: '', stakes: '' })).toBe(null);+ });++ it('keeps an enabled clock even when otherwise blank', () => {+ const c = sanitizeTickingClock({ enabled: true });+ expect(c).not.toBe(null);+ expect(c.enabled).toBe(true);+ expect(c.kind).toBe('custom');+ expect(c.label).toBe('');+ expect(c.plantedAtArcPosition).toBe(null);+ expect(c.reminders).toEqual([]);+ });++ it('keeps a disabled-but-authored clock (label is identifying content)', () => {+ const c = sanitizeTickingClock({ enabled: false, label: 'Drafted countdown' });+ expect(c).not.toBe(null);+ expect(c.enabled).toBe(false);+ expect(c.label).toBe('Drafted countdown');+ });++ it('round-trips fields, defaults unknown kind to custom, and clamps positions', () => {+ const c = sanitizeTickingClock({+ enabled: true,+ label: 'The prophecy hour',+ kind: 'not-a-kind',+ plantedAtArcPosition: -5,+ dueAtArcPosition: 99999,+ stakes: 'The seal breaks.',+ reminders: [{ atIssue: 3, note: 'omen' }, { note: '' }],+ });+ expect(c.kind).toBe('custom');+ expect(c.plantedAtArcPosition).toBe(0);+ expect(c.dueAtArcPosition).toBe(TICKING_CLOCK_LIMITS.ARC_POSITION_MAX);+ expect(c.stakes).toBe('The seal breaks.');+ // The empty reminder (no note, no issue) is dropped; the valid one keeps a minted id.+ expect(c.reminders).toHaveLength(1);+ expect(c.reminders[0].atIssue).toBe(3);+ expect(c.reminders[0].id).toMatch(/^rm-/);+ });++ it('preserves a known kind and caps the reminders list', () => {+ expect(sanitizeTickingClock({ enabled: true, kind: 'deadline' }).kind).toBe('deadline');+ const many = Array.from({ length: TICKING_CLOCK_LIMITS.REMINDERS_MAX + 5 }, (_, i) => ({ note: `r${i}` }));+ expect(sanitizeTickingClock({ enabled: true, reminders: many }).reminders)+ .toHaveLength(TICKING_CLOCK_LIMITS.REMINDERS_MAX);+ });++ it('exposes a non-empty kind vocabulary', () => {+ expect(TICKING_CLOCK_KINDS).toContain('deadline');+ expect(TICKING_CLOCK_KINDS).toContain('custom');+ });+});++describe('storyArc — renderTickingClock', () => {+ it('returns null when absent or disabled', () => {+ expect(renderTickingClock(null)).toBe(null);+ expect(renderTickingClock({ enabled: false, label: 'x' })).toBe(null);+ });++ it('renders a guidance line with label, stakes, span, and reminders when enabled', () => {+ const text = renderTickingClock({+ enabled: true,+ label: 'The storm makes landfall',+ kind: 'event',+ plantedAtArcPosition: 1,+ dueAtArcPosition: 8,+ stakes: 'The town floods.',+ reminders: [{ atIssue: 4, note: 'barometer drops' }],+ });+ expect(text).toContain('The storm makes landfall');+ expect(text).toContain('event');+ expect(text).toContain('The town floods.');+ expect(text).toContain('arc position 1');+ expect(text).toContain('arc position 8');+ expect(text).toContain('barometer drops');+ });});describe('storyArc — sanitizeReaderMap', () => {diff --git a/server/routes/pipeline/series.js b/server/routes/pipeline/series.jsindex b19bcbbacc..c03701c2d2 100644--- a/server/routes/pipeline/series.js+++ b/server/routes/pipeline/series.js@@ -54,6 +54,11 @@ const arcSchema = z.object({// be listed here or Zod's default key-stripping would silently drop it on any// arc PATCH, and updateSeries's wholesale arc replace would then wipe it.readerMap: z.object({}).passthrough().nullable().optional(),+ // Ticking clock (the countdown the reader anticipates). Same defer-to-service+ // pattern as readerMap above: accepted as an opaque object and sanitized by+ // sanitizeTickingClock (storyArc.js). Listed here so Zod doesn't strip it on+ // an arc PATCH and updateSeries's wholesale arc replace doesn't wipe it.+ tickingClock: z.object({}).passthrough().nullable().optional(),status: z.enum(ARC_STATUSES).optional(),});diff --git a/server/services/pipeline/arcPlanner/context.js b/server/services/pipeline/arcPlanner/context.jsindex b390b3b03c..fdcc9d5bc2 100644--- a/server/services/pipeline/arcPlanner/context.js+++ b/server/services/pipeline/arcPlanner/context.js@@ -9,7 +9,7 @@import { MANUSCRIPT_TYPES } from '../series.js';import { listIssues } from '../issues.js';-import { ARC_ROLES as ARC_ROLE_LIST, ARC_SHAPE_IDS, READER_MAP_BEAT_KINDS, buildSeason, renderArcShapeGuidance, sanitizeSeasonList } from '../../../lib/storyArc.js';+import { ARC_ROLES as ARC_ROLE_LIST, ARC_SHAPE_IDS, READER_MAP_BEAT_KINDS, buildSeason, renderArcShapeGuidance, renderTickingClock, sanitizeSeasonList } from '../../../lib/storyArc.js';import { describeStructure, recommendStructure } from '../../../lib/seasonStructure.js';import { DEFAULT_LENGTH_PROFILE, LENGTH_PROFILE_NAMES } from '../../../lib/issueLength.js';import { getUniverse } from '../../universeBuilder.js';@@ -275,10 +275,21 @@ export async function collectManuscriptByType(seriesId) {// "the bible block" — both passes must see the same series identity.export const SHAPE_GUIDANCE_NONE = '(no Vonnegut story shape selected — the verifier should not flag shape adherence)';+// Append the ticking-clock guidance (only when the clock is enabled) to an+// arc-level shape-guidance block. Every arc/reader-map prompt already renders+// `{{{shapeGuidance}}}`, so folding the countdown in here surfaces it to+// generation without adding a new template variable — and therefore without a+// stage-prompt migration. Returns the guidance unchanged when there's no+// enabled clock.+function appendTickingClock(shapeGuidance, arc) {+ const clock = renderTickingClock(arc?.tickingClock);+ return clock ? `${shapeGuidance}\n\n${clock}` : shapeGuidance;+}+export async function buildArcBaseContext(series, preloadedWorld) {const arc = series.arc || {};const world = await resolveWorldContext(series, preloadedWorld);- const shapeGuidance = renderArcShapeGuidance(arc.shape) || SHAPE_GUIDANCE_NONE;+ const shapeGuidance = appendTickingClock(renderArcShapeGuidance(arc.shape) || SHAPE_GUIDANCE_NONE, arc);return {series: {name: series.name,@@ -311,8 +322,11 @@ export async function buildArcOverviewContext(series, preloadedWorld) {// section fires (honor mode); when it's empty the `{{^pickedShapeId}}`// inverted section fires (propose mode). promptTemplate.js treats `''` as// falsy per Mustache spec, so the empty string is the right sentinel.- const shapeGuidance = renderArcShapeGuidance(arc.shape)- || `(no shape selected — you must propose one of: ${ARC_SHAPE_IDS.join(', ')}. Return your pick as the JSON field "shape". Choose the shape that best matches the premise's emotional trajectory.)`;+ const shapeGuidance = appendTickingClock(+ renderArcShapeGuidance(arc.shape)+ || `(no shape selected — you must propose one of: ${ARC_SHAPE_IDS.join(', ')}. Return your pick as the JSON field "shape". Choose the shape that best matches the premise's emotional trajectory.)`,+ arc,+ );return {series: {name: series.name,@@ -383,7 +397,7 @@ export async function buildReaderMapContext(series, preloadedWorld) {themesCsv: Array.isArray(arc.themes) ? arc.themes.join(', ') : '',shape: arc.shape || '',},- shapeGuidance: renderArcShapeGuidance(arc.shape) || SHAPE_GUIDANCE_NONE,+ shapeGuidance: appendTickingClock(renderArcShapeGuidance(arc.shape) || SHAPE_GUIDANCE_NONE, arc),issueBoundaries,beatKindsCsv: READER_MAP_BEAT_KINDS.join(', '),existingReaderMapJson: arc.readerMap ? JSON.stringify(arc.readerMap, null, 2) : '(none yet)',diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.jsindex 2f3989fbc3..9cc334a54c 100644--- a/server/services/pipeline/series.js+++ b/server/services/pipeline/series.js@@ -87,7 +87,7 @@ export const LOCKABLE_STAGES = Object.freeze(['arc']);// while preserving locked ones verbatim. Sibling to the binary `locked.arc`// (which freezes everything); the two stack — `locked.arc: true` always wins.export const ARC_LOCKABLE_FIELDS = Object.freeze([- 'logline', 'summary', 'protagonistArc', 'themes', 'shape', 'readerMap',+ 'logline', 'summary', 'protagonistArc', 'themes', 'shape', 'readerMap', 'tickingClock',]);// Series Autopilot run marker (full autonomous mode). A thin, persisted