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-781]): Writers Room live continuation suggestions with opt-in + budget
[._.]/ Adam Eivy3c529a2d6666
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex d535f39091..c0df282dd4 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,7 @@## Added+- **[issue-781] Writers Room live director** — turn on "Live Director" for a work and, whenever you pause while writing, the Creative Director offers a few short ways to continue from your cursor: a beat to take, a ready-to-insert line of prose, or a bit of dialogue. It's off by default and opt-in per work, waits until you stop typing before asking, and respects a daily suggestion budget so it never runs away with your AI usage.- **[issue-709] Review Hub "Needs Attention" queue** — the Review Hub now opens with a cross-domain queue that pulls everything currently waiting on you into one list: Brain inbox items that need classifying, Ask answers ready to promote, CoS tasks awaiting approval, unsent message drafts, critical/high health anomalies, and failed backups. The most urgent items sort to the top, each row opens straight to where you handle it, and you can dismiss anything you don't want to act on right now. A slow or unavailable source is noted instead of blocking the rest.- **[issue-708] Digital Twin personas** — give your twin named contexts — Professional, Casual, Family, or your own — each with instructions for how it should modulate voice and behavior. Activate one from the new Personas tab and your CoS agents adopt that context when they act on your behalf, while building your base identity stays unaffected. Create, edit, switch, and clear personas at any time.- **[issue-708] Digital Twin values-alignment tests** — the Digital Twin's Test tab gains a second test mode: instead of only checking whether your twin *sounds* like you, it poses ethical dilemmas and grades whether the twin's choice is consistent with your ranked values. Each dilemma names the values at stake and ships an "aligned" and "misaligned" reference, and runs score against the values hierarchy from your Identity tab — so you can see, per model, where your twin holds your values and where it drifts. Ships a starter dilemma suite you can customize.diff --git a/client/src/components/writers-room/LiveContinuationPanel.jsx b/client/src/components/writers-room/LiveContinuationPanel.jsxnew file mode 100644index 0000000000..b1dc6360a7--- /dev/null+++ b/client/src/components/writers-room/LiveContinuationPanel.jsx@@ -0,0 +1,153 @@+import { useCallback, useEffect, useRef, useState } from 'react';+import { Sparkles, Loader2, Plus } from 'lucide-react';+import toast from '../ui/Toast';+import { suggestWritersRoomContinuation } from '../../services/apiWritersRoom';+import useMounted from '../../hooks/useMounted';++const KIND_LABEL = { beat: 'Beat', prose: 'Prose', dialogue: 'Dialogue' };+const KIND_TONE = {+ beat: 'text-port-accent border-port-accent/40',+ prose: 'text-port-success border-port-success/40',+ dialogue: 'text-port-warning border-port-warning/40',+};++// Phase 5 live Creative Director panel. While the work has live mode opted in,+// the editor calls `requestSuggest` on a debounce after the writer pauses; this+// panel renders the returned options and lets the writer insert one at the+// cursor. It owns NO timers itself — the debounce + cursor-context capture live+// in WorkEditor (which holds the textarea ref). It's a pure presentation ++// fetch shell driven by an imperative trigger passed up via `registerTrigger`.+export default function LiveContinuationPanel({+ workId,+ liveMode,+ getCursorContext,+ onInsert,+ registerTrigger,+}) {+ const [options, setOptions] = useState([]);+ const [loading, setLoading] = useState(false);+ const [usage, setUsage] = useState(liveMode?.usage || null);+ const [notice, setNotice] = useState(null);+ const mountedRef = useMounted();+ // Guard against overlapping suggest calls: a fast typist can trigger a second+ // debounce-fire before the first response lands. Ignore the request while one+ // is in flight (the next pause re-triggers anyway).+ const inFlightRef = useRef(false);++ const requestSuggest = useCallback(async () => {+ if (inFlightRef.current) return;+ const ctx = getCursorContext?.();+ if (!ctx || (!ctx.before?.trim() && !ctx.after?.trim() && !ctx.selection?.trim())) return;+ inFlightRef.current = true;+ setLoading(true);+ setNotice(null);+ const res = await suggestWritersRoomContinuation(workId, ctx, { silent: true }).catch((err) => {+ // 429 budget / 409 off are expected control-flow, not crashes — show them+ // inline rather than as a red toast.+ if (mountedRef.current) {+ if (err?.status === 429) setNotice('Daily suggestion budget reached — resets at UTC midnight.');+ else if (err?.status === 409) setNotice('Live mode is off for this work.');+ else toast.error(`Suggestion failed: ${err.message}`);+ }+ return null;+ });+ inFlightRef.current = false;+ if (!mountedRef.current) return;+ setLoading(false);+ if (!res) return;+ setOptions(res.options || []);+ if (res.usage) setUsage(res.usage);+ if ((res.options || []).length === 0) setNotice('No suggestions this time — keep writing and pause again.');+ }, [workId, getCursorContext, mountedRef]);++ // Expose the imperative trigger to the parent so its debounce timer can fire+ // a suggest without this component owning the cursor/textarea.+ useEffect(() => {+ registerTrigger?.(requestSuggest);+ return () => registerTrigger?.(null);+ }, [registerTrigger, requestSuggest]);++ // When live mode flips off, clear any stale suggestions so the panel doesn't+ // keep advertising stale options against prose the writer has moved past.+ useEffect(() => {+ if (!liveMode?.enabled) {+ setOptions([]);+ setNotice(null);+ }+ }, [liveMode?.enabled]);++ const budget = liveMode?.dailyCallBudget ?? 0;+ const spent = usage?.count ?? 0;+ const remainingLabel = budget > 0 ? `${Math.max(0, budget - spent)} / ${budget} left today` : 'unlimited';++ if (!liveMode?.enabled) {+ return (+ <div className="p-3 text-[11px] text-gray-500 italic">+ Live mode is off. Enable it from the work menu to get continuation suggestions as you pause.+ </div>+ );+ }++ return (+ <div className="flex flex-col h-full min-h-0">+ <div className="flex items-center justify-between gap-2 px-3 py-2 border-b border-port-border">+ <div className="flex items-center gap-1.5 text-[11px] font-semibold text-port-accent">+ <Sparkles size={12} /> Live Director+ </div>+ <div className="flex items-center gap-2">+ <span className="text-[10px] text-gray-500" title="Daily suggestion budget">{remainingLabel}</span>+ <button+ type="button"+ onClick={requestSuggest}+ disabled={loading}+ className="flex items-center gap-1 px-2 py-0.5 text-[10px] rounded bg-port-bg border border-port-border text-gray-300 hover:text-white disabled:opacity-50"+ title="Suggest a continuation from the cursor"+ >+ {loading ? <Loader2 size={10} className="animate-spin" /> : <Sparkles size={10} />}+ Suggest+ </button>+ </div>+ </div>++ <div className="flex-1 min-h-0 overflow-y-auto p-2 space-y-2">+ {notice && (+ <div className="px-2 py-1.5 text-[11px] text-gray-400 bg-port-bg/60 border border-port-border rounded">+ {notice}+ </div>+ )}+ {!notice && options.length === 0 && !loading && (+ <div className="px-2 py-3 text-[11px] text-gray-500 italic">+ Pause while writing (or click Suggest) and the Creative Director will offer a few ways to continue from the cursor.+ </div>+ )}+ {options.map((opt, i) => (+ <div+ key={i}+ className="rounded border border-port-border bg-port-card/60 p-2 hover:border-port-accent/40 transition-colors"+ >+ <div className="flex items-center justify-between gap-2 mb-1">+ <span className={`px-1.5 py-0.5 rounded border text-[9px] uppercase tracking-wide ${KIND_TONE[opt.kind] || KIND_TONE.beat}`}>+ {KIND_LABEL[opt.kind] || 'Beat'}+ </span>+ {(opt.kind === 'prose' || opt.kind === 'dialogue') && (+ <button+ type="button"+ onClick={() => onInsert?.(opt)}+ className="flex items-center gap-1 px-1.5 py-0.5 text-[10px] rounded bg-port-accent/15 text-port-accent hover:bg-port-accent/25"+ title="Insert at cursor"+ >+ <Plus size={10} /> Insert+ </button>+ )}+ </div>+ {opt.label && <div className="text-[11px] font-medium text-gray-200">{opt.label}</div>}+ <div className="text-[11px] text-gray-400 whitespace-pre-wrap mt-0.5">{opt.text}</div>+ {opt.rationale && (+ <div className="text-[10px] text-gray-600 italic mt-1">{opt.rationale}</div>+ )}+ </div>+ ))}+ </div>+ </div>+ );+}diff --git a/client/src/components/writers-room/WorkEditor.jsx b/client/src/components/writers-room/WorkEditor.jsxindex 2e2d98dc5a..dcd1dad822 100644--- a/client/src/components/writers-room/WorkEditor.jsx+++ b/client/src/components/writers-room/WorkEditor.jsx@@ -22,6 +22,7 @@ import {Columns3,Film,ExternalLink,+ Zap,} from 'lucide-react';import toast from '../ui/Toast';import ProseEditor from '../ui/ProseEditor';@@ -43,6 +44,7 @@ import { listCatalogIngredientsForRef } from '../../services/apiCatalog';import { STATUS_LABELS } from './labels';import { countWords } from '../../utils/formatters';import StoryboardPanel, { STORYBOARD_TAB, STORYBOARD_TAB_VALUES } from './StoryboardPanel';+import LiveContinuationPanel from './LiveContinuationPanel';import AnalysisHistory from './AnalysisHistory';import ProseReader from './ProseReader';import SyncedReview from './SyncedReview';@@ -141,6 +143,16 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseOstopOne: queueStopOne,} = useImageGenQueue();+ // Phase 5 live mode — opt-in, per-work Creative Director continuation+ // suggestions. Optimistic mirror of work.liveMode so the toggle flips+ // instantly; re-synced from the prop. `liveTriggerRef` holds the panel's+ // imperative suggest fn; `liveTimerRef` is the post-typing debounce.+ const [liveMode, setLiveMode] = useState(work.liveMode || null);+ useEffect(() => { setLiveMode(work.liveMode || null); }, [work.liveMode]);+ const liveTriggerRef = useRef(null);+ const liveTimerRef = useRef(null);+ const registerLiveTrigger = useCallback((fn) => { liveTriggerRef.current = fn; }, []);+// View mode (Edit | Read | Review) is URL-driven so it deep-links and// survives reloads. ?view=read → ProseReader; ?view=review → SyncedReview// (Phase 4 prose/script/media surface); default is the existing textarea.@@ -437,6 +449,82 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO}};+ // --- Phase 5 live mode ---++ const liveEnabled = liveMode?.enabled === true;+ const liveDebounceMs = Number.isInteger(liveMode?.debounceMs) ? liveMode.debounceMs : 2500;++ // Snapshot the prose window around the caret for the live-suggest call. We+ // send a bounded window (not the whole manuscript) — enough context for the+ // director without shipping a long body on every pause.+ const getCursorContext = useCallback(() => {+ const ta = textareaRef.current;+ if (!ta) return null;+ const start = ta.selectionStart ?? body.length;+ const end = ta.selectionEnd ?? start;+ const WINDOW = 4000;+ return {+ before: body.slice(Math.max(0, start - WINDOW), start),+ after: body.slice(end, end + WINDOW),+ selection: body.slice(start, end),+ };+ }, [body]);++ // Insert a suggested snippet at the caret (replacing any selection), then+ // restore focus + caret after the inserted text so the writer keeps flowing.+ const insertAtCursor = useCallback((opt) => {+ const ta = textareaRef.current;+ const snippet = opt?.text || '';+ if (!snippet) return;+ const start = ta?.selectionStart ?? body.length;+ const end = ta?.selectionEnd ?? start;+ // Space-pad so an inserted snippet doesn't weld onto the preceding word.+ const needsLeadingSpace = start > 0 && !/\s$/.test(body.slice(0, start));+ const piece = (needsLeadingSpace ? ' ' : '') + snippet;+ const next = body.slice(0, start) + piece + body.slice(end);+ setBody(next);+ const caret = start + piece.length;+ requestAnimationFrame(() => {+ const el = textareaRef.current;+ if (!el) return;+ el.focus();+ el.setSelectionRange(caret, caret);+ });+ toast('Inserted — save to persist', { icon: '✍️' });+ }, [body]);++ // Debounce a suggest after the writer pauses typing. Only arms while live+ // mode is on and we're in the edit textarea; cleared on every keystroke and+ // on unmount so a deferred fire can't hit a dead/closed editor.+ const scheduleLiveSuggest = useCallback(() => {+ if (!liveEnabled || viewMode !== 'edit') return;+ if (liveTimerRef.current) clearTimeout(liveTimerRef.current);+ liveTimerRef.current = setTimeout(() => {+ liveTimerRef.current = null;+ if (mountedRef.current) liveTriggerRef.current?.();+ }, liveDebounceMs);+ }, [liveEnabled, viewMode, liveDebounceMs, mountedRef]);++ useEffect(() => () => { if (liveTimerRef.current) clearTimeout(liveTimerRef.current); }, []);++ const toggleLiveMode = useCallback(async () => {+ const nextEnabled = !liveEnabled;+ // Optimistic flip; the PATCH returns the persisted liveMode (with defaults+ // filled in for a first opt-in) which we fold back through onChange.+ setLiveMode((prev) => ({ ...(prev || {}), enabled: nextEnabled }));+ const updated = await updateWritersRoomWork(work.id, { liveMode: { enabled: nextEnabled } }).catch((err) => {+ if (mountedRef.current) {+ toast.error(`Live mode save failed: ${err.message}`);+ setLiveMode(work.liveMode || null);+ }+ return null;+ });+ if (!updated || !mountedRef.current) return;+ setLiveMode(updated.liveMode || null);+ onChange?.({ ...updated, activeDraftBody: body });+ toast.success(nextEnabled ? 'Live director on' : 'Live director off');+ }, [liveEnabled, work.id, work.liveMode, body, onChange, mountedRef]);+const commitStatus = async (next) => {if (next === status) return;setStatus(next);@@ -742,6 +830,7 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO<MenuItem icon={MapPin} label="Refresh places" running={runningKind === ANALYSIS_KIND.PLACES} onClick={closeOverflowAnd(() => runAnalysis(ANALYSIS_KIND.PLACES))} /><MenuItem icon={Sparkles} label="Editorial pass" running={runningKind === ANALYSIS_KIND.EVALUATE} onClick={closeOverflowAnd(() => runAnalysis(ANALYSIS_KIND.EVALUATE))} /><MenuItem icon={FileSignature} label="Format pass" running={runningKind === ANALYSIS_KIND.FORMAT} onClick={closeOverflowAnd(() => runAnalysis(ANALYSIS_KIND.FORMAT))} />+ <MenuItem icon={Zap} label={liveEnabled ? 'Disable live director' : 'Enable live director'} active={liveEnabled} onClick={closeOverflowAnd(toggleLiveMode)} /></MenuSection><MenuSection label="Open"><MenuItem icon={Clock} label="Versions" onClick={closeOverflowAnd(() => setDrawer(DRAWER.VERSIONS))} />@@ -828,7 +917,7 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO<ProseEditorref={textareaRef}value={body}- onChange={(e) => setBody(e.target.value)}+ onChange={(e) => { setBody(e.target.value); scheduleLiveSuggest(); }}readingTheme={readingTheme}className="w-full h-full resize-none px-6 py-6 text-base focus:outline-none"/>@@ -868,6 +957,17 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseOmobileTab === MOBILE_TAB.WRITING ? 'hidden lg:flex' : 'flex'}`}>+ {liveEnabled && viewMode === 'edit' && (+ <div className="shrink-0 max-h-[40%] min-h-0 border-b border-port-border overflow-hidden flex flex-col">+ <LiveContinuationPanel+ workId={work.id}+ liveMode={liveMode}+ getCursorContext={getCursorContext}+ onInsert={insertAtCursor}+ registerTrigger={registerLiveTrigger}+ />+ </div>+ )}<StoryboardPanelwork={work}characters={characters}diff --git a/client/src/services/apiWritersRoom.js b/client/src/services/apiWritersRoom.jsindex 4039dd12e4..09a62d707d 100644--- a/client/src/services/apiWritersRoom.js+++ b/client/src/services/apiWritersRoom.js@@ -60,6 +60,18 @@ export const runWritersRoomAnalysis = (workId, data) =>});export const getWritersRoomAnalysis = (workId, analysisId) =>request(`/writers-room/works/${enc(workId)}/analysis/${enc(analysisId)}`);++// Live continuation (Phase 5): opt-in, debounced Creative Director feedback+// from the prose around the cursor. Returns { options, usage, budget }. The+// server gates on the per-work live-mode toggle (409) and daily budget (429);+// callers own their own error UI, so pass { silent: true } to avoid a double+// toast.+export const suggestWritersRoomContinuation = (workId, context, options) =>+ request(`/writers-room/works/${enc(workId)}/live-suggest`, {+ method: 'POST',+ body: JSON.stringify(context || {}),+ ...(options || {}),+ });export const attachWritersRoomSceneImage = (workId, analysisId, payload) =>request(`/writers-room/works/${enc(workId)}/analysis/${enc(analysisId)}/scene-image`, {method: 'POST',diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.jsonindex bdf7da1443..087fc76420 100644--- a/data.reference/prompts/stage-config.json+++ b/data.reference/prompts/stage-config.json@@ -42,6 +42,13 @@"returnsJson": true,"variables": []},+ "writers-room-continue": {+ "name": "Writers Room — Live Continuation",+ "description": "Live Creative Director feedback: from the prose around the cursor, propose 2–4 short optional continuation beats, prose snippets, or dialogue lines the writer can accept. Drives the opt-in live-mode side panel in the editor.",+ "model": "quick",+ "returnsJson": true,+ "variables": []+ },"catalog-ideas-scenes-concepts": {"name": "Catalog Ingest — Ideas / Scenes / Concepts","description": "Extract reusable narrative fragments — ideas (premises), scenes (dramatic beats), and concepts (lore, magic systems, factions) — from a raw user-pasted scrap into the Creative Ingredients Catalog. Runs alongside the character/place/object writers-room passes during catalog ingest.",diff --git a/data.reference/prompts/stages/writers-room-continue.md b/data.reference/prompts/stages/writers-room-continue.mdnew file mode 100644index 0000000000..9e0c2716ae--- /dev/null+++ b/data.reference/prompts/stages/writers-room-continue.md@@ -0,0 +1,51 @@+# Writers Room — Live Continuation++You are a Creative Director sitting beside the writer as they draft. They have paused at a cursor and want a few short, optional suggestions for how the story could continue from here. You are a collaborator, not a ghostwriter — offer directions, never hijack the voice.++## Work being written++- Title: {{work.title}}+- Kind: {{work.kind}}+- Status: {{work.status}}++## Prose before the cursor++```+{{before}}+```++## Prose after the cursor++```+{{after}}+```++## Selected passage (the writer is focused here — may be empty)++```+{{selection}}+```++## Task++Read the surrounding prose and propose **2 to 4** short continuation options the writer could take from the cursor. Each option is one possible next beat — a sentence or two of *direction* plus, when it helps, a short snippet of drafted prose the writer can accept verbatim.++Match the established voice, tense, and point of view. Do not contradict what comes after the cursor. Prefer concrete, scene-level moves (an action, a line of dialogue, a turn) over abstract advice. If the selected passage is non-empty, treat it as the focus and suggest how to extend or pivot from it specifically.++Each option has:+- `kind`: "beat" (a direction to take) | "prose" (a ready-to-insert snippet) | "dialogue" (a suggested line)+- `label`: a 3–8 word summary of the direction+- `text`: the suggestion itself — for `prose`/`dialogue`, the verbatim text to insert; for `beat`, a 1–2 sentence description of the move+- `rationale`: one sentence on why this fits the story so far (optional)++## Output contract++Return ONLY valid JSON matching this shape — no prose, no markdown fence, no commentary:++```json+{+ "options": [+ { "kind": "beat|prose|dialogue", "label": "string", "text": "string", "rationale": "string" }+ ]+}+```diff --git a/docs/features/writers-room.md b/docs/features/writers-room.mdindex ede6b60f3f..59c063b585 100644--- a/docs/features/writers-room.md+++ b/docs/features/writers-room.md@@ -540,15 +540,37 @@ Exit criteria:Goal: evolve from manual passes to controlled live assistance.-- Optional live story continuation suggestions while writing.-- Optional render previews on selected scenes.+- Optional live story continuation suggestions while writing. **[shipped]**+- Optional render previews on selected scenes. *(planned)*- Creative Director can propose next beats, alternate scenes, and visual- treatments from the active cursor context.-- Add throttling, debouncing, budget controls, and explicit opt-in per work.+ treatments from the active cursor context. *(planned)*+- Add throttling, debouncing, budget controls, and explicit opt-in per work. **[shipped]**This phase should wait until manual analysis quality, mapping, and render costsare proven.+**Shipped (live continuation slice):** the editor has an opt-in "Live Director"+mode (per work, off by default) that, while the writer pauses, asks for 2–4+short continuation options from the prose around the cursor — beats to take,+ready-to-insert prose snippets, or dialogue lines. Suggestions surface in a side+panel; `prose`/`dialogue` options insert at the caret. Controls:++- Per-work opt-in toggle (work menu → "Enable live director").+- A client debounce after typing stops (`liveMode.debounceMs`, default 2.5s) so+ no call fires on every keystroke.+- A server-enforced daily call budget (`liveMode.dailyCallBudget`, default 100,+ `0` = unlimited) that rolls over at UTC midnight. Opt-in and budget are+ enforced server-side, not just in the UI — the debounce is convenience only.++Backed by the `writers-room-continue` prompt stage (quick tier) and+`server/services/writersRoom/liveDirector.js`; per-work live config persists on+the work manifest.++**Still planned for this phase:** live render previews on selected scenes from+the cursor context, and a Creative Director bridge that proposes next+beats/alternate scenes/visual treatments (injecting into a CD treatment) rather+than only prose continuations.+## Test PlanBackend:diff --git a/scripts/migrations/065-writers-room-continue-prompt.js b/scripts/migrations/065-writers-room-continue-prompt.jsnew file mode 100644index 0000000000..d4f8e29c2c--- /dev/null+++ b/scripts/migrations/065-writers-room-continue-prompt.js@@ -0,0 +1,83 @@+/**+ * Seed the Writers Room live-continuation prompt stage into existing installs.+ *+ * Single-stage sibling of the other writers-room prompt seeds: copies the+ * `writers-room-continue.md` template from `data.reference/prompts/stages/` and+ * merges its stage-config entry into `data/prompts/stage-config.json`. Boot runs+ * migrations (server/index.js) but NOT `setup-data.js`, so an upgrade that pulls+ * + `pm2 restart`s (rather than running the full setup) would otherwise leave+ * the new stage unseeded and the first live-suggest call would throw+ * "Stage not found".+ *+ * FIRST-SHIPMENT SEED ONLY — no MD5 hashing: it copies the template only when+ * missing and never overwrites an install's existing prompt. A FUTURE migration+ * that AMENDS this prompt must follow migration 003's hash-driven pattern+ * (normalize line endings, ship OLD + NEW shipped hashes) instead.+ */++import { access, copyFile, mkdir, readFile, constants } from 'fs/promises';+import { dirname, join } from 'path';+import { atomicWrite } from '../../server/lib/fileUtils.js';++// The prompt file's basename doubles as its stage-config key (sans `.md`).+const STAGE = 'writers-room-continue';++export default {+ async up({ rootDir }) {+ const stagesDir = join(rootDir, 'data', 'prompts', 'stages');+ await mkdir(stagesDir, { recursive: true });++ // 1. Copy the prompt template if it's missing.+ const filename = `${STAGE}.md`;+ const dataPath = join(stagesDir, filename);+ const samplePath = join(rootDir, 'data.reference', 'prompts', 'stages', filename);+ const exists = await access(dataPath, constants.F_OK).then(() => true, () => false);+ if (exists) {+ console.log(`📝 writers-room prompt: ${filename} already present`);+ } else {+ const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);+ if (!sampleExists) {+ console.warn(`⚠️ writers-room: sample missing for ${filename} — skipping copy`);+ } else {+ try {+ await copyFile(samplePath, dataPath);+ console.log(`✅ seeded ${filename}`);+ } catch (err) {+ console.warn(`⚠️ writers-room: copy failed for ${filename}: ${err.message}`);+ }+ }+ }++ // 2. Merge the stage-config entry if it's missing.+ const installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');+ const sampleConfigPath = join(rootDir, 'data.reference', 'prompts', 'stage-config.json');+ const sampleConfigExists = await access(sampleConfigPath, constants.F_OK).then(() => true, () => false);+ if (!sampleConfigExists) {+ console.warn('⚠️ writers-room: data.reference stage-config.json missing — skipping config write');+ return;+ }+ try {+ const sample = JSON.parse(await readFile(sampleConfigPath, 'utf8'));+ const installedExists = await access(installedConfigPath, constants.F_OK).then(() => true, () => false);+ const installed = installedExists+ ? JSON.parse(await readFile(installedConfigPath, 'utf8'))+ : { stages: {} };+ installed.stages = installed.stages || {};+ if (installed.stages[STAGE]) {+ console.log(`📝 writers-room stage-config: ${STAGE} already present`);+ return;+ }+ if (!sample?.stages?.[STAGE]) {+ console.warn(`⚠️ writers-room: sample stage-config missing ${STAGE} — skipping`);+ return;+ }+ installed.stages[STAGE] = sample.stages[STAGE];+ await mkdir(dirname(installedConfigPath), { recursive: true });+ await atomicWrite(installedConfigPath, `${JSON.stringify(installed, null, 2)}\n`);+ const action = installedExists ? 'merged' : 'created';+ console.log(`📝 writers-room stage-config (${action}): ${STAGE} added`);+ } catch (err) {+ console.warn(`⚠️ writers-room: stage-config merge failed: ${err.message}`);+ }+ },+};diff --git a/scripts/migrations/065-writers-room-continue-prompt.test.js b/scripts/migrations/065-writers-room-continue-prompt.test.jsnew file mode 100644index 0000000000..becc68fa28--- /dev/null+++ b/scripts/migrations/065-writers-room-continue-prompt.test.js@@ -0,0 +1,58 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync, existsSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++import migration from './065-writers-room-continue-prompt.js';++const STAGE = 'writers-room-continue';+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));++describe('migration 065 — seed Writers Room live-continuation prompt', () => {+ let rootDir;+ let installedStagesDir;+ let installedConfigPath;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-065-'));+ const refStagesDir = join(rootDir, 'data.reference', 'prompts', 'stages');+ mkdirSync(refStagesDir, { recursive: true });+ writeFileSync(join(refStagesDir, `${STAGE}.md`), `# ${STAGE}\n\nbody\n`);+ const refConfig = { stages: { [STAGE]: { name: STAGE, model: 'quick', returnsJson: true, variables: [] } } };+ writeFileSync(join(rootDir, 'data.reference', 'prompts', 'stage-config.json'), JSON.stringify(refConfig, null, 2) + '\n');++ installedStagesDir = join(rootDir, 'data', 'prompts', 'stages');+ installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');+ });++ afterEach(() => {+ rmSync(rootDir, { recursive: true, force: true });+ });++ it('seeds the prompt file + stage-config entry on a fresh install', async () => {+ await migration.up({ rootDir });+ expect(existsSync(join(installedStagesDir, `${STAGE}.md`))).toBe(true);+ expect(readJson(installedConfigPath).stages[STAGE]).toBeTruthy();+ });++ it('merges into an existing stage-config without clobbering other stages', async () => {+ mkdirSync(installedStagesDir, { recursive: true });+ writeFileSync(installedConfigPath, JSON.stringify({ stages: { 'pipeline-prose': { name: 'Prose' } } }, null, 2) + '\n');+ await migration.up({ rootDir });+ const config = readJson(installedConfigPath);+ expect(config.stages['pipeline-prose']).toBeTruthy();+ expect(config.stages[STAGE]).toBeTruthy();+ });++ it('is idempotent and preserves a user-customized installed prompt', async () => {+ mkdirSync(installedStagesDir, { recursive: true });+ const customPath = join(installedStagesDir, `${STAGE}.md`);+ writeFileSync(customPath, '# CUSTOM continuation\n');+ await migration.up({ rootDir });+ expect(readFileSync(customPath, 'utf-8')).toContain('CUSTOM');+ // Second run is a clean no-op.+ await migration.up({ rootDir });+ expect(readFileSync(customPath, 'utf-8')).toContain('CUSTOM');+ expect(readJson(installedConfigPath).stages[STAGE]).toBeTruthy();+ });+});diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 558baed415..11513a692f 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -842,12 +842,36 @@ export const writersRoomImageStyleSchema = z.object({negativePrompt: z.string().max(2000).default(''),}).strict();+// Phase 5 live-mode opt-in (per work). `enabled` gates the editor's+// background continuation suggestions; `debounceMs` is the client's+// idle-after-typing throttle before it asks; `dailyCallBudget` caps how many+// suggest calls the server will run per UTC day (0 = unlimited). The+// server-tracked `usage` counter is NOT user-editable — it's bumped by the+// suggest path and reset on a new day — so it lives outside this update schema+// (mirrors how `pipelineSeriesId` is set by linkToPipeline, not updateWork).+export const writersRoomLiveModeSchema = z.object({+ enabled: z.boolean().default(false),+ debounceMs: z.number().int().min(800).max(30_000).default(2500),+ dailyCallBudget: z.number().int().min(0).max(10_000).default(100),+}).strict();+export const writersRoomWorkUpdateSchema = z.object({title: z.string().trim().min(1).max(300).optional(),kind: writersRoomWorkKindSchema.optional(),status: writersRoomWorkStatusSchema.optional(),folderId: wrIdNullable.optional(),imageStyle: writersRoomImageStyleSchema.optional(),+ liveMode: writersRoomLiveModeSchema.partial().optional(),+}).strict();++// Cursor-context payload for the live continuation suggest route. The three+// prose slices are bounded so a runaway editor can't ship a multi-MB body on+// every keystroke — the server only needs a window around the cursor, not the+// whole manuscript.+export const writersRoomLiveSuggestSchema = z.object({+ before: z.string().max(12_000).optional().default(''),+ after: z.string().max(12_000).optional().default(''),+ selection: z.string().max(8_000).optional().default(''),}).strict();export const writersRoomDraftSaveSchema = z.object({diff --git a/server/routes/writersRoom.js b/server/routes/writersRoom.jsindex 954e1db4ca..a153bd394f 100644--- a/server/routes/writersRoom.js+++ b/server/routes/writersRoom.js@@ -16,6 +16,7 @@ import {writersRoomExerciseCreateSchema,writersRoomExerciseFinishSchema,writersRoomAnalysisCreateSchema,+ writersRoomLiveSuggestSchema,writersRoomCharacterCreateSchema,writersRoomCharacterUpdateSchema,writersRoomPlaceCreateSchema,@@ -34,6 +35,7 @@ import {runAnalysis, listAnalyses, getAnalysis, attachSceneImage,} from '../services/writersRoom/evaluator.js';import { getSyncedReview } from '../services/writersRoom/syncedReview.js';+import { suggestContinuation } from '../services/writersRoom/liveDirector.js';import {listCharacters, createCharacter, updateCharacter, deleteCharacter,} from '../services/writersRoom/characters.js';@@ -189,6 +191,17 @@ router.get('/works/:id/analysis/:analysisId', asyncHandler(async (req, res) => {res.json(await getAnalysis(req.params.id, req.params.analysisId));}));+// ---------- live continuation (Phase 5: opt-in Creative Director feedback) ----------++// Throttled, opt-in live suggestions from the cursor context. The service+// enforces both the per-work opt-in (409 if off) and the daily budget (429 if+// spent) — the editor debounce is a convenience, not the gate. Stateless apart+// from the daily budget counter the service bumps on a productive call.+router.post('/works/:id/live-suggest', asyncHandler(async (req, res) => {+ const data = validateRequest(writersRoomLiveSuggestSchema, req.body || {});+ res.json(await suggestContinuation(req.params.id, data));+}));+// ---------- synced review (Phase 4: prose ↔ script ↔ media) ----------// Read-model assembled on demand from the active draft's segment index and thediff --git a/server/routes/writersRoom.test.js b/server/routes/writersRoom.test.jsindex 195f6f4b18..a485e2aee5 100644--- a/server/routes/writersRoom.test.js+++ b/server/routes/writersRoom.test.js@@ -60,10 +60,20 @@ vi.mock('../services/catalogExtraction.js', () => ({scanProseForIngredientRefs: vi.fn(async () => []),}));+// Mock the live-director service so the suggest route doesn't reach a provider.+vi.mock('../services/writersRoom/liveDirector.js', () => ({+ suggestContinuation: vi.fn(async () => ({+ options: [{ kind: 'beat', label: 'Next', text: 'A move.', rationale: '' }],+ usage: { date: '2026-06-03', count: 1 },+ budget: 100,+ })),+}));+import * as svc from '../services/writersRoom/local.js';import * as catalogExtraction from '../services/catalogExtraction.js';import * as charSvc from '../services/writersRoom/characters.js';import * as placesSvc from '../services/writersRoom/places.js';+import * as liveSvc from '../services/writersRoom/liveDirector.js';import writersRoomRoutes from './writersRoom.js';describe('writersRoom routes', () => {@@ -371,4 +381,40 @@ describe('writersRoom routes', () => {expect(r.body.error || r.body.message).toMatch(/no prose/i);});});++ describe('live mode (Phase 5)', () => {+ it('PATCH /works/:id accepts a partial liveMode patch', async () => {+ const r = await request(app)+ .patch('/api/writers-room/works/wr-work-1')+ .send({ liveMode: { enabled: true, debounceMs: 3000 } });+ expect(r.status).toBe(200);+ expect(svc.updateWork).toHaveBeenCalledWith('wr-work-1', { liveMode: { enabled: true, debounceMs: 3000 } });+ });++ it('PATCH /works/:id rejects an out-of-range debounceMs', async () => {+ const r = await request(app)+ .patch('/api/writers-room/works/wr-work-1')+ .send({ liveMode: { debounceMs: 10 } });+ expect(r.status).toBe(400);+ });++ it('POST /works/:id/live-suggest forwards the cursor context and returns options', async () => {+ const r = await request(app)+ .post('/api/writers-room/works/wr-work-1/live-suggest')+ .send({ before: 'The door opened.', after: '', selection: '' });+ expect(r.status).toBe(200);+ expect(r.body.options[0].text).toBe('A move.');+ expect(liveSvc.suggestContinuation).toHaveBeenCalledWith('wr-work-1', {+ before: 'The door opened.', after: '', selection: '',+ });+ });++ it('POST /works/:id/live-suggest rejects an over-long before window', async () => {+ const r = await request(app)+ .post('/api/writers-room/works/wr-work-1/live-suggest')+ .send({ before: 'x'.repeat(12_001) });+ expect(r.status).toBe(400);+ expect(liveSvc.suggestContinuation).not.toHaveBeenCalled();+ });+ });});diff --git a/server/services/writersRoom/liveDirector.js b/server/services/writersRoom/liveDirector.jsnew file mode 100644index 0000000000..0183a441d0--- /dev/null+++ b/server/services/writersRoom/liveDirector.js@@ -0,0 +1,99 @@+/**+ * Writers Room — Phase 5 live Creative Director feedback.+ *+ * On an explicit, throttled client request (NOT on every keystroke — the+ * editor debounces and only asks while live-mode is opted in), take the prose+ * window around the writer's cursor and propose a few short continuation+ * options. Stateless: nothing is persisted except the per-work daily budget+ * counter (`recordLiveModeUsage`), so a suggestion the writer ignores leaves+ * no trace. This is the spine the later live-render-preview and Creative+ * Director beat/scene bridge build on.+ *+ * Budget + opt-in are enforced server-side here, not just in the UI — a client+ * that ignores the toggle or the debounce still can't run unbounded LLM calls.+ */++import { ServerError } from '../../lib/errorHandler.js';+import { runStagedLLM } from '../../lib/stageRunner.js';+import { getWork, resolveLiveMode, recordLiveModeUsage } from './local.js';+import { badRequest } from './_shared.js';++const STAGE = 'writers-room-continue';+const MAX_OPTIONS = 4;++// Surface the two soft-failure modes as typed codes so the route can map them+// to the right HTTP status (live-mode off → 409 conflict; budget spent → 429).+export const ERR_LIVE_MODE_OFF = 'LIVE_MODE_OFF';+export const ERR_BUDGET_EXCEEDED = 'LIVE_BUDGET_EXCEEDED';++function shapeOptions(parsed) {+ const raw = Array.isArray(parsed?.options) ? parsed.options : [];+ return raw+ .filter((o) => o && typeof o === 'object')+ .map((o) => ({+ kind: ['beat', 'prose', 'dialogue'].includes(o.kind) ? o.kind : 'beat',+ label: typeof o.label === 'string' ? o.label.trim() : '',+ text: typeof o.text === 'string' ? o.text.trim() : '',+ rationale: typeof o.rationale === 'string' ? o.rationale.trim() : '',+ }))+ .filter((o) => o.text)+ .slice(0, MAX_OPTIONS);+}++/**+ * Generate live continuation suggestions from the cursor context.+ * Throws a coded ServerError when live mode is off or the daily budget is+ * spent (the route translates the code to a status). On success returns+ * `{ options, usage, budget }` so the client can render remaining budget.+ */+export async function suggestContinuation(workId, { before = '', after = '', selection = '' } = {}) {+ const manifest = await getWork(workId); // 404s if the work is missing+ const live = resolveLiveMode(manifest);++ if (!live.enabled) {+ throw new ServerError('Live mode is off for this work', { status: 409, code: ERR_LIVE_MODE_OFF });+ }++ // Daily budget gate. 0 means unlimited. The counter rolls over per UTC day+ // inside recordLiveModeUsage; here we just compare today's count against the+ // cap before spending an LLM call. Reading the resolved usage (which is not+ // date-normalized) would let yesterday's count block today, so treat a+ // stale-date counter as 0 spent-today.+ const today = new Date().toISOString().slice(0, 10);+ const spentToday = live.usage.date === today ? live.usage.count : 0;+ if (live.dailyCallBudget > 0 && spentToday >= live.dailyCallBudget) {+ throw new ServerError(+ `Live suggestion budget reached (${live.dailyCallBudget}/day) — resets at UTC midnight`,+ { status: 429, code: ERR_BUDGET_EXCEEDED },+ );+ }++ if (!before.trim() && !after.trim() && !selection.trim()) {+ throw badRequest('Need some prose around the cursor to suggest a continuation');+ }++ const variables = {+ work: { title: manifest.title, kind: manifest.kind, status: manifest.status },+ before, after, selection,+ returnsJson: true,+ };+ const { content } = await runStagedLLM(STAGE, variables, {+ source: 'writers-room-continue',+ returnsJson: true,+ });+ const options = shapeOptions(content);++ // Only spend budget on a call that actually produced something — a parse+ // that yields zero options shouldn't burn the writer's daily allowance.+ // recordLiveModeUsage returns the full resolved config; we surface just the+ // usage sub-object so the response shape is identical on both branches.+ const usage = options.length > 0+ ? (await recordLiveModeUsage(workId)).usage+ : live.usage;++ return {+ options,+ usage,+ budget: live.dailyCallBudget,+ };+}diff --git a/server/services/writersRoom/liveDirector.test.js b/server/services/writersRoom/liveDirector.test.jsnew file mode 100644index 0000000000..74ce04e9eb--- /dev/null+++ b/server/services/writersRoom/liveDirector.test.js@@ -0,0 +1,116 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { mkdtempSync, rmSync, existsSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { makePathsProxy } from '../../lib/mockPathsDataRoot.js';++let tempRoot;++vi.mock('../../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../../lib/fileUtils.js');+ return makePathsProxy(actual, { dataRoot: () => tempRoot });+});++// Stub the staged-LLM runner so the suggest path doesn't reach a real provider.+const runStagedLLM = vi.fn();+vi.mock('../../lib/stageRunner.js', () => ({ runStagedLLM: (...a) => runStagedLLM(...a) }));++const local = await import('./local.js');+const { createWork, updateWork, getWork } = local;+const { suggestContinuation, ERR_LIVE_MODE_OFF, ERR_BUDGET_EXCEEDED } = await import('./liveDirector.js');++beforeEach(() => {+ tempRoot = mkdtempSync(join(tmpdir(), 'wr-live-test-'));+ runStagedLLM.mockReset();+});++afterEach(() => {+ if (tempRoot && existsSync(tempRoot)) rmSync(tempRoot, { recursive: true, force: true });+ vi.useRealTimers();+});++const OPTIONS_RESPONSE = {+ content: {+ options: [+ { kind: 'prose', label: 'Push into the storm', text: 'She stepped into the rain.', rationale: 'raises stakes' },+ { kind: 'beat', label: 'Cut to the antagonist', text: 'Reveal the watcher across the street.' },+ ],+ },+};++describe('suggestContinuation', () => {+ it('throws LIVE_MODE_OFF when the work has not opted in', async () => {+ const work = await createWork({ title: 'Off' });+ await expect(suggestContinuation(work.id, { before: 'words here' }))+ .rejects.toMatchObject({ code: ERR_LIVE_MODE_OFF, status: 409 });+ expect(runStagedLLM).not.toHaveBeenCalled();+ });++ it('runs the stage, shapes options, and bumps usage on success', async () => {+ runStagedLLM.mockResolvedValue(OPTIONS_RESPONSE);+ const work = await createWork({ title: 'On' });+ await updateWork(work.id, { liveMode: { enabled: true } });++ const res = await suggestContinuation(work.id, { before: 'The door creaked open.' });+ expect(res.options).toHaveLength(2);+ expect(res.options[0]).toMatchObject({ kind: 'prose', text: 'She stepped into the rain.' });+ expect(res.usage.count).toBe(1);+ expect(runStagedLLM).toHaveBeenCalledOnce();+ });++ it('does not spend budget when the model returns zero usable options', async () => {+ runStagedLLM.mockResolvedValue({ content: { options: [] } });+ const work = await createWork({ title: 'Empty' });+ await updateWork(work.id, { liveMode: { enabled: true } });++ const res = await suggestContinuation(work.id, { before: 'Nothing comes of this.' });+ expect(res.options).toHaveLength(0);+ expect(res.usage.count).toBe(0); // counter untouched+ });++ it('enforces the daily budget and rejects with BUDGET_EXCEEDED once spent', async () => {+ runStagedLLM.mockResolvedValue(OPTIONS_RESPONSE);+ const work = await createWork({ title: 'Capped' });+ await updateWork(work.id, { liveMode: { enabled: true, dailyCallBudget: 1 } });++ await suggestContinuation(work.id, { before: 'First call.' }); // count -> 1+ await expect(suggestContinuation(work.id, { before: 'Second call.' }))+ .rejects.toMatchObject({ code: ERR_BUDGET_EXCEEDED, status: 429 });+ expect(runStagedLLM).toHaveBeenCalledOnce(); // the blocked call never ran the stage+ });++ it('treats dailyCallBudget 0 as unlimited', async () => {+ runStagedLLM.mockResolvedValue(OPTIONS_RESPONSE);+ const work = await createWork({ title: 'Unlimited' });+ await updateWork(work.id, { liveMode: { enabled: true, dailyCallBudget: 0 } });++ await suggestContinuation(work.id, { before: 'a' });+ await suggestContinuation(work.id, { before: 'b' });+ const res = await suggestContinuation(work.id, { before: 'c' });+ expect(res.usage.count).toBe(3);+ });++ it('rejects an empty cursor context before spending an LLM call', async () => {+ const work = await createWork({ title: 'Blank' });+ await updateWork(work.id, { liveMode: { enabled: true } });+ await expect(suggestContinuation(work.id, { before: ' ', after: '', selection: '' }))+ .rejects.toThrow(/prose around the cursor/);+ expect(runStagedLLM).not.toHaveBeenCalled();+ });++ it('rolls the budget over on a new UTC day', async () => {+ runStagedLLM.mockResolvedValue(OPTIONS_RESPONSE);+ const work = await createWork({ title: 'Rollover' });+ await updateWork(work.id, { liveMode: { enabled: true, dailyCallBudget: 1 } });++ vi.useFakeTimers();+ vi.setSystemTime(new Date('2026-06-03T12:00:00Z'));+ await suggestContinuation(work.id, { before: 'day one' });+ await expect(suggestContinuation(work.id, { before: 'day one again' }))+ .rejects.toMatchObject({ code: ERR_BUDGET_EXCEEDED });++ vi.setSystemTime(new Date('2026-06-04T00:01:00Z'));+ const res = await suggestContinuation(work.id, { before: 'day two' });+ expect(res.usage).toMatchObject({ date: '2026-06-04', count: 1 });+ });+});diff --git a/server/services/writersRoom/local.js b/server/services/writersRoom/local.jsindex 6fe95afc81..5f570a7d3e 100644--- a/server/services/writersRoom/local.js+++ b/server/services/writersRoom/local.js@@ -312,6 +312,30 @@ export async function createWork({ folderId = null, title, kind = 'short-story'return manifest;}+// Default Phase 5 live-mode config. Stored on the manifest only once the user+// opts in; readers (the suggest path) fall back to this when the field is+// absent. `usage` is the server-tracked daily budget counter — never accepted+// from the client (updateWork strips it; only recordLiveModeUsage writes it).+export const DEFAULT_LIVE_MODE = Object.freeze({+ enabled: false,+ debounceMs: 2500,+ dailyCallBudget: 100,+ usage: Object.freeze({ date: null, count: 0 }),+});++export function resolveLiveMode(manifest) {+ const stored = manifest?.liveMode || {};+ return {+ enabled: stored.enabled === true,+ debounceMs: Number.isInteger(stored.debounceMs) ? stored.debounceMs : DEFAULT_LIVE_MODE.debounceMs,+ dailyCallBudget: Number.isInteger(stored.dailyCallBudget) ? stored.dailyCallBudget : DEFAULT_LIVE_MODE.dailyCallBudget,+ usage: {+ date: typeof stored.usage?.date === 'string' ? stored.usage.date : null,+ count: Number.isInteger(stored.usage?.count) ? stored.usage.count : 0,+ },+ };+}+export async function updateWork(id, patch) {const manifest = await getWork(id);const allowed = ['title', 'folderId', 'kind', 'status', 'imageStyle'];@@ -322,6 +346,20 @@ export async function updateWork(id, patch) {if (key === 'status' && !WORK_STATUSES.includes(patch.status)) throw badRequest(`Invalid status: ${patch.status}`);next[key] = patch[key];}+ // liveMode is a partial merge (the UI PATCHes one knob at a time) onto the+ // resolved current config — and the client-supplied `usage` is dropped so a+ // crafted PATCH can't reset the server-side daily budget counter. Only the+ // three user-editable knobs flow through.+ if (patch.liveMode !== undefined && patch.liveMode !== null) {+ const current = resolveLiveMode(manifest);+ const p = patch.liveMode;+ next.liveMode = {+ enabled: typeof p.enabled === 'boolean' ? p.enabled : current.enabled,+ debounceMs: Number.isInteger(p.debounceMs) ? p.debounceMs : current.debounceMs,+ dailyCallBudget: Number.isInteger(p.dailyCallBudget) ? p.dailyCallBudget : current.dailyCallBudget,+ usage: current.usage,+ };+ }// Trim title and reject if it becomes empty after trim — keeps parity with// createWork's "title required" guard so a PATCH can't blank a title out.if (patch.title !== undefined) {@@ -357,6 +395,29 @@ export async function linkToPipeline(id, { seriesId = null, issueId = null } = {return next;}+// UTC day key (YYYY-MM-DD) for the daily budget window. UTC (not local) so the+// reset boundary is deterministic across machines a single user federates.+function utcDayKey() {+ return nowIso().slice(0, 10);+}++/**+ * Bump the live-mode daily usage counter for a work, rolling over to a fresh+ * count when the stored date is not today (UTC). Set once per successful+ * suggest call by the live-director path — distinct from `updateWork` because+ * the counter is server-owned, not user-editable. Returns the resolved live+ * config with the new usage so the caller can echo remaining budget.+ */+export async function recordLiveModeUsage(id) {+ const manifest = await getWork(id);+ const live = resolveLiveMode(manifest);+ const today = utcDayKey();+ const count = live.usage.date === today ? live.usage.count + 1 : 1;+ const nextLive = { ...live, usage: { date: today, count } };+ await saveManifest(id, { ...manifest, liveMode: nextLive, updatedAt: nowIso() });+ return nextLive;+}+export async function deleteWork(id) {// 404 the caller if the manifest is missing; rm() with force:true would// silently succeed on a non-existent dir and the user gets no signal.diff --git a/server/services/writersRoom/local.test.js b/server/services/writersRoom/local.test.jsindex 8ff58694d4..068f960ebe 100644--- a/server/services/writersRoom/local.test.js+++ b/server/services/writersRoom/local.test.js@@ -18,6 +18,7 @@ const {listWorks, createWork, getWork, getWorkWithBody, updateWork, deleteWork,saveDraftBody, snapshotDraft, setActiveDraft, getDraftBody,listExercises, createExercise, finishExercise, discardExercise,+ resolveLiveMode, recordLiveModeUsage, DEFAULT_LIVE_MODE,} = local;beforeEach(() => {@@ -356,3 +357,51 @@ describe('exercise sessions', () => {expect(await listExercises()).toHaveLength(3);});});++describe('live mode (Phase 5)', () => {+ it('resolveLiveMode falls back to defaults for a work that never opted in', async () => {+ const work = await createWork({ title: 'Fresh' });+ const live = resolveLiveMode(work);+ expect(live.enabled).toBe(false);+ expect(live.debounceMs).toBe(DEFAULT_LIVE_MODE.debounceMs);+ expect(live.dailyCallBudget).toBe(DEFAULT_LIVE_MODE.dailyCallBudget);+ expect(live.usage).toEqual({ date: null, count: 0 });+ });++ it('updateWork partial-merges liveMode knobs without clobbering siblings', async () => {+ const work = await createWork({ title: 'Live' });+ const a = await updateWork(work.id, { liveMode: { enabled: true } });+ expect(a.liveMode.enabled).toBe(true);+ expect(a.liveMode.debounceMs).toBe(DEFAULT_LIVE_MODE.debounceMs);++ const b = await updateWork(work.id, { liveMode: { debounceMs: 5000 } });+ expect(b.liveMode.enabled).toBe(true); // preserved+ expect(b.liveMode.debounceMs).toBe(5000);+ });++ it('updateWork strips a client-supplied usage counter (server-owned)', async () => {+ const work = await createWork({ title: 'Guard' });+ await recordLiveModeUsage(work.id); // count -> 1 today+ const tampered = await updateWork(work.id, {+ liveMode: { enabled: true, usage: { date: '1999-01-01', count: 9999 } },+ });+ // The crafted usage is dropped — the real counter is preserved.+ expect(tampered.liveMode.usage.count).toBe(1);+ expect(tampered.liveMode.usage.date).not.toBe('1999-01-01');+ });++ it('recordLiveModeUsage increments within a day and rolls over on a new UTC day', async () => {+ const work = await createWork({ title: 'Budget' });+ vi.useFakeTimers();+ vi.setSystemTime(new Date('2026-06-03T10:00:00Z'));+ const u1 = await recordLiveModeUsage(work.id);+ expect(u1.usage).toEqual({ date: '2026-06-03', count: 1 });+ const u2 = await recordLiveModeUsage(work.id);+ expect(u2.usage).toEqual({ date: '2026-06-03', count: 2 });++ // New UTC day resets the counter to 1.+ vi.setSystemTime(new Date('2026-06-04T00:05:00Z'));+ const u3 = await recordLiveModeUsage(work.id);+ expect(u3.usage).toEqual({ date: '2026-06-04', count: 1 });+ });+});