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
bring back the autobiography story prompt as a configurable daily task
[._.]/ Adam Eivyabc05c0acfb4
diff --git a/client/src/components/digital-twin/StoryCraftPanel.jsx b/client/src/components/digital-twin/StoryCraftPanel.jsxnew file mode 100644index 0000000000..2c647af449--- /dev/null+++ b/client/src/components/digital-twin/StoryCraftPanel.jsx@@ -0,0 +1,79 @@+import { Gauge } from 'lucide-react';+import Pill from '../ui/Pill';+import ProgressBar from '../ui/ProgressBar';++/**+ * Renders one autobiography story's storytelling-craft score: the seven moves+ * with a meter and a concrete revision suggestion each, the CART structure as+ * present/absent chips, and the single highest-leverage rewrite.+ *+ * The rubric lives server-side (`server/lib/storytellingCraft.js`) and the+ * evaluation carries its own `label` per row, so adding a move there shows up+ * here with no edit — this component renders whatever rows it is handed.+ */+export default function StoryCraftPanel({ evaluation }) {+ if (!evaluation) return null;++ return (+ <div className="mt-3 bg-port-bg border border-emerald-500/30 rounded-lg p-4 space-y-3">+ <div className="flex flex-wrap items-center gap-2">+ <Gauge size={14} className="text-emerald-400" />+ <span className="text-sm font-medium text-emerald-300">+ Storytelling craft: {evaluation.overallScore}/{evaluation.maxScore}+ </span>+ {evaluation.answersQuestion === false && (+ <Pill tone="warning">Doesn't answer its question yet</Pill>+ )}+ </div>++ <div className="space-y-2">+ {evaluation.moves?.map((move) => (+ <div key={move.id} className="space-y-1">+ <div className="flex items-center justify-between gap-2">+ <span className="text-xs text-gray-300">{move.label}</span>+ <span className="text-xs text-gray-500 shrink-0">+ {move.score}/{evaluation.maxScore}+ </span>+ </div>+ <ProgressBar+ percent={(move.score / evaluation.maxScore) * 100}+ tone="success"+ track="border"+ label={`${move.label} score`}+ />+ {move.evidence && (+ <p className="text-xs text-gray-500">{move.evidence}</p>+ )}+ {move.suggestion && (+ <p className="text-xs text-gray-400">+ <span className="text-emerald-300/80">Try: </span>+ {move.suggestion}+ </p>+ )}+ </div>+ ))}+ </div>++ {evaluation.cart?.length > 0 && (+ <div className="flex flex-wrap gap-1.5">+ {evaluation.cart.map((stage) => (+ <Pill+ key={stage.id}+ tone={stage.present ? 'success' : 'note'}+ title={stage.note || undefined}+ >+ {stage.label}+ </Pill>+ ))}+ </div>+ )}++ {evaluation.revision && (+ <p className="text-xs text-gray-400 leading-relaxed">+ <span className="text-emerald-300">Next revision: </span>+ {evaluation.revision}+ </p>+ )}+ </div>+ );+}diff --git a/client/src/components/digital-twin/StoryCraftPanel.test.jsx b/client/src/components/digital-twin/StoryCraftPanel.test.jsxnew file mode 100644index 0000000000..8eed1cec6a--- /dev/null+++ b/client/src/components/digital-twin/StoryCraftPanel.test.jsx@@ -0,0 +1,52 @@+import { describe, it, expect } from 'vitest';+import { render, screen } from '@testing-library/react';+import StoryCraftPanel from './StoryCraftPanel';++const evaluation = {+ overallScore: 3.1,+ maxScore: 5,+ answersQuestion: true,+ revision: 'End on what the taste stands in for.',+ moves: [+ { id: 'curiosity', label: 'Create curiosity', score: 4, evidence: 'opens on a question', suggestion: 'hold the answer longer' },+ { id: 'takeaway', label: 'Land with a takeaway', score: 0, evidence: '', suggestion: 'say what it meant' }+ ],+ cart: [+ { id: 'context', label: 'Context', present: true, note: 'kitchen table' },+ { id: 'takeaway', label: 'Takeaway', present: false, note: 'missing' }+ ]+};++describe('StoryCraftPanel', () => {+ it('renders a labeled meter per move, including a zero-scored one', () => {+ render(<StoryCraftPanel evaluation={evaluation} />);++ // A zero score must still draw its row — the rubric is the fixed seven+ // moves, and a missing row would read as "not part of the rubric" rather+ // than "you didn't do this".+ expect(screen.getByRole('progressbar', { name: 'Create curiosity score' })).toHaveAttribute('aria-valuenow', '80');+ expect(screen.getByRole('progressbar', { name: 'Land with a takeaway score' })).toHaveAttribute('aria-valuenow', '0');+ });++ it('shows each move\'s evidence and suggestion when the model gave them', () => {+ render(<StoryCraftPanel evaluation={evaluation} />);++ expect(screen.getByText('opens on a question')).toBeInTheDocument();+ expect(screen.getByText(/hold the answer longer/)).toBeInTheDocument();+ expect(screen.getByText(/End on what the taste stands in for/)).toBeInTheDocument();+ });++ it('flags a story that does not answer its question, and stays quiet when it does', () => {+ const { rerender } = render(<StoryCraftPanel evaluation={evaluation} />);+ expect(screen.queryByText(/answer its question/)).not.toBeInTheDocument();++ rerender(<StoryCraftPanel evaluation={{ ...evaluation, answersQuestion: false }} />);+ expect(screen.getByText(/answer its question/)).toBeInTheDocument();+ });++ it('renders nothing before a story has been scored', () => {+ const { container } = render(<StoryCraftPanel evaluation={null} />);++ expect(container).toBeEmptyDOMElement();+ });+});diff --git a/client/src/components/digital-twin/tabs/AutobiographyTab.jsx b/client/src/components/digital-twin/tabs/AutobiographyTab.jsxindex 319a5908de..40c51cc345 100644--- a/client/src/components/digital-twin/tabs/AutobiographyTab.jsx+++ b/client/src/components/digital-twin/tabs/AutobiographyTab.jsx@@ -14,9 +14,13 @@ import {BookOpen,Sparkles,Link2,MessageCircle,- ScrollText} from 'lucide-react';+ ScrollText,+ HelpCircle,+ Lightbulb,+ Gauge} from 'lucide-react';import BrailleSpinner from '../../BrailleSpinner';import InlineConfirmRow from '../../ui/InlineConfirmRow';+import StoryCraftPanel from '../StoryCraftPanel';import * as api from '../../../services/api';import { copyToClipboard } from '../../../lib/clipboard';import { countWords } from '../../../lib/textUtils';@@ -24,6 +28,14 @@ import toast from '../../ui/Toast';import { useConfirmDelete } from '../../../hooks/useConfirmDelete';import { formatCount, formatDateTime, formatDateNumeric } from '../../../utils/formatters';+// Mirrors the server's reminder default and its strict HH:MM schema+// (server/services/autobiography.js DEFAULT_CONFIG, server/lib/timezone.js).+const DEFAULT_REMINDER_TIME = '09:00';+// Matches CUSTOM_PROMPT_ID in server/services/autobiography.js — the promptId a+// story written against the user's own question is saved under.+const CUSTOM_PROMPT_ID = 'custom';+const HHMM_RE = /^([01]\d|2[0-3]):[0-5]\d$/;+export default function AutobiographyTab({ onRefresh }) {const [searchParams, setSearchParams] = useSearchParams();const [stats, setStats] = useState(null);@@ -38,9 +50,17 @@ export default function AutobiographyTab({ onRefresh }) {const [storyContent, setStoryContent] = useState('');const [saving, setSaving] = useState(false);+ // Story ideas — the same menu the daily prompt notification offers+ const [suggestions, setSuggestions] = useState([]);+ const [ownQuestion, setOwnQuestion] = useState('');++ // Storytelling-craft evaluation, keyed by story id while it runs+ const [evaluatingStoryId, setEvaluatingStoryId] = useState(null);+// Config stateconst [showConfig, setShowConfig] = useState(false);const [config, setConfig] = useState(null);+ const [reminderTimeDraft, setReminderTimeDraft] = useState(DEFAULT_REMINDER_TIME);// Edit stateconst [editingStory, setEditingStory] = useState(null);@@ -71,13 +91,26 @@ export default function AutobiographyTab({ onRefresh }) {setStories(storiesData);setThemes(themesData);setConfig(configData);+ setReminderTimeDraft(configData?.reminder?.time || DEFAULT_REMINDER_TIME);setLoading(false);}, [filterTheme]);+ // Suggestions come from the prompt bank and what's already been written —+ // never from the theme filter, so this stays out of `loadData` and its+ // filterTheme dependency. It refreshes on mount and after a save, which is+ // exactly when the set can actually change.+ const refreshSuggestions = useCallback(async () => {+ setSuggestions(await api.getAutobiographySuggestions({ silent: true }).catch(() => []));+ }, []);+useEffect(() => {loadData();}, [loadData]);+ useEffect(() => {+ refreshSuggestions();+ }, [refreshSuggestions]);+// Auto-load prompt from URL param (when arriving from notification)useEffect(() => {const promptParam = searchParams.get('prompt');@@ -87,13 +120,21 @@ export default function AutobiographyTab({ onRefresh }) {}}, [loading, searchParams, setSearchParams]);+ // The one place a writing session starts. Every entry point below just+ // produces the question to answer and hands it here, so per-session state+ // can't drift between them — which it already had: two of the five reset+ // `parentStoryId` and the other two didn't, leaving a fresh bank prompt+ // saved as a follow-up of whatever was last open.+ const beginWriting = (prompt, { parentStoryId: parent = null } = {}) => {+ setCurrentPrompt(prompt);+ setParentStoryId(parent);+ setWriting(true);+ setStoryContent('');+ };+const loadPromptById = async (promptId) => {const prompt = await api.getAutobiographyPromptById(promptId).catch(() => null);- if (prompt) {- setCurrentPrompt(prompt);- setWriting(true);- setStoryContent('');- }+ if (prompt) beginWriting(prompt);};const startWriting = async () => {@@ -101,11 +142,24 @@ export default function AutobiographyTab({ onRefresh }) {toast.error(err.message);return null;});- if (prompt) {- setCurrentPrompt(prompt);- setWriting(true);- setStoryContent('');+ if (prompt) beginWriting(prompt);+ };++ // Write against a question the user typed themselves. The story still answers+ // a question — it's just theirs rather than one from the bank.+ const startOwnQuestion = () => {+ const question = ownQuestion.trim();+ if (!question) {+ toast.error('Write a question first');+ return;}+ beginWriting({+ id: CUSTOM_PROMPT_ID,+ themeId: CUSTOM_PROMPT_ID,+ themeLabel: 'Your Own Question',+ text: question+ });+ setOwnQuestion('');};const skipPrompt = async () => {@@ -124,8 +178,10 @@ export default function AutobiographyTab({ onRefresh }) {return;}setSaving(true);- const opts = parentStoryId- ? { parentStoryId, customPromptText: currentPrompt.text }+ // A follow-up and a user-written question both carry their question text in+ // customPromptText — neither has a bank prompt the server could look it up from.+ const opts = (parentStoryId || currentPrompt.id === CUSTOM_PROMPT_ID)+ ? { parentStoryId: parentStoryId || undefined, customPromptText: currentPrompt.text }: {};const result = await api.saveAutobiographyStory(currentPrompt.id, storyContent.trim(), opts, { silent: true }).catch((err) => { toast.error(err.message); return null; });@@ -140,6 +196,8 @@ export default function AutobiographyTab({ onRefresh }) {setFollowUps({ storyId: result.id, prompts: result.followUpPrompts || null });setExpandedStory(result.id);loadData();+ // The prompt just used drops out of the bank, so the menu changes here.+ refreshSuggestions();onRefresh?.();}setSaving(false);@@ -161,6 +219,17 @@ export default function AutobiographyTab({ onRefresh }) {setGeneratingFollowUps(false);};+ const handleEvaluateStory = async (storyId) => {+ setEvaluatingStoryId(storyId);+ const result = await api.evaluateAutobiographyStory(storyId, undefined, { silent: true })+ .catch((err) => { toast.error(err.message); return null; });+ if (result?.evaluation) {+ setStories(prev => prev.map(s => (s.id === storyId ? { ...s, evaluation: result.evaluation } : s)));+ toast.success(`Storytelling score: ${result.evaluation.overallScore}/${result.evaluation.maxScore}`);+ }+ setEvaluatingStoryId(null);+ };+const handleWeaveNarrative = async (storyId) => {setWeavingStoryId(storyId);// request() already toasts on failure; the catch only swallows so the@@ -179,15 +248,10 @@ export default function AutobiographyTab({ onRefresh }) {), [stories]);const startFollowUp = (parentId, questionText, themeId, themeLabel) => {- setParentStoryId(parentId);- setCurrentPrompt({- id: `followup-${parentId}`,- themeId,- themeLabel,- text: questionText- });- setWriting(true);- setStoryContent('');+ beginWriting(+ { id: `followup-${parentId}`, themeId, themeLabel, text: questionText },+ { parentStoryId: parentId }+ );setFollowUps(null);};@@ -212,6 +276,22 @@ export default function AutobiographyTab({ onRefresh }) {}};+ // A `type="time"` input fires onChange for every intermediate keystroke,+ // including the empty string while the hour is being retyped — PATCHing each+ // one would 400 against the server's strict HH:MM schema mid-edit, restamp+ // the reminder's updatedAt, and re-register the cron on every partial value.+ // So the field is a local draft that commits on blur, and an unusable value+ // reverts to what is saved rather than being sent.+ const commitReminderTime = () => {+ const saved = config?.reminder?.time || DEFAULT_REMINDER_TIME;+ if (!HHMM_RE.test(reminderTimeDraft)) {+ setReminderTimeDraft(saved);+ return;+ }+ if (reminderTimeDraft === saved) return;+ handleConfigUpdate({ reminder: { time: reminderTimeDraft } });+ };+const handleConfigUpdate = async (updates) => {const result = await api.updateAutobiographyConfig(updates, { silent: true }).catch((err) => { toast.error(err.message); return null; });@@ -293,6 +373,33 @@ export default function AutobiographyTab({ onRefresh }) {</select></label></div>+ <div className="flex flex-wrap items-center gap-4 pt-3 border-t border-port-border">+ <label className="flex items-center gap-2 text-sm text-gray-300" htmlFor="autobiography-reminder-enabled">+ <input+ id="autobiography-reminder-enabled"+ type="checkbox"+ checked={config.reminder?.enabled === true}+ onChange={(e) => handleConfigUpdate({ reminder: { enabled: e.target.checked } })}+ className="rounded border-port-border"+ />+ Daily story prompt+ </label>+ <label className="flex items-center gap-2 text-sm text-gray-300" htmlFor="autobiography-reminder-time">+ at+ <input+ id="autobiography-reminder-time"+ type="time"+ value={reminderTimeDraft}+ onChange={(e) => setReminderTimeDraft(e.target.value)}+ onBlur={commitReminderTime}+ disabled={config.reminder?.enabled !== true}+ className="bg-port-bg border border-port-border rounded px-2 py-1 text-sm text-white disabled:opacity-50"+ />+ </label>+ </div>+ <p className="text-xs text-gray-500">+ Skipped on any day you already wrote a story.+ </p>{config.lastPromptAt && (<p className="text-xs text-gray-500">Last prompt: {formatDateTime(config.lastPromptAt)}@@ -301,6 +408,61 @@ export default function AutobiographyTab({ onRefresh }) {</div>)}+ {/* Story ideas — the same menu the daily prompt offers, plus your own question */}+ {!writing && (+ <div className="bg-port-card border border-port-border rounded-lg p-5 space-y-4">+ <div className="flex items-center gap-2">+ <Lightbulb className="w-4 h-4 text-amber-400" />+ <span className="text-sm font-medium text-white">Story ideas</span>+ <span className="text-xs text-gray-500">Every story answers a question</span>+ </div>+ {suggestions.length > 0 && (+ <div className="space-y-2">+ {suggestions.map((prompt) => (+ <button+ key={prompt.id}+ onClick={() => beginWriting(prompt)}+ className="w-full text-left p-3 rounded-lg bg-port-bg border border-port-border hover:border-port-accent/50 transition-colors group"+ >+ <div className="flex items-start gap-2">+ <PenLine size={14} className="mt-0.5 text-port-accent/60 group-hover:text-port-accent shrink-0" />+ <span className="text-sm text-gray-300 group-hover:text-white">+ <span className="text-xs text-port-accent mr-2">{prompt.themeLabel}</span>+ {prompt.text}+ </span>+ </div>+ </button>+ ))}+ </div>+ )}+ <div className="space-y-2">+ <label htmlFor="autobiography-own-question" className="flex items-center gap-1.5 text-xs text-gray-400">+ <HelpCircle size={12} />+ Or answer your own question+ </label>+ <div className="flex flex-col sm:flex-row gap-2">+ <input+ id="autobiography-own-question"+ type="text"+ value={ownQuestion}+ maxLength={500}+ onChange={(e) => setOwnQuestion(e.target.value)}+ onKeyDown={(e) => { if (e.key === 'Enter') startOwnQuestion(); }}+ placeholder="Why do I like black licorice?"+ className="flex-1 bg-port-bg border border-port-border rounded px-3 py-2 text-sm text-white placeholder-gray-600 focus:outline-hidden focus:border-port-accent/50"+ />+ <button+ onClick={startOwnQuestion}+ disabled={!ownQuestion.trim()}+ className="px-3 py-2 bg-port-accent text-white rounded text-sm font-medium hover:bg-port-accent/80 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"+ >+ Answer it+ </button>+ </div>+ </div>+ </div>+ )}+{/* Follow-up Suggestions (shown after saving a story) */}{followUps && !writing && (<div className="bg-port-card border border-amber-500/30 rounded-lg p-5 space-y-3">@@ -397,14 +559,18 @@ export default function AutobiographyTab({ onRefresh }) {<span>~{Math.max(1, Math.round(wordCount / 150))} min read</span></div><div className="flex items-center gap-2">- <button- onClick={skipPrompt}- className="flex items-center gap-1 px-3 py-2 text-sm text-gray-400 hover:text-white transition-colors"- title="Get a different prompt"- >- <SkipForward size={14} />- Skip- </button>+ {/* Skip swaps in a different BANK prompt — meaningless for a+ follow-up or a question the user wrote themselves. */}+ {!parentStoryId && currentPrompt.id !== CUSTOM_PROMPT_ID && (+ <button+ onClick={skipPrompt}+ className="flex items-center gap-1 px-3 py-2 text-sm text-gray-400 hover:text-white transition-colors"+ title="Get a different prompt"+ >+ <SkipForward size={14} />+ Skip+ </button>+ )}<buttononClick={saveStory}disabled={saving || !storyContent.trim()}@@ -543,6 +709,9 @@ export default function AutobiographyTab({ onRefresh }) {</div>)}+ {/* Storytelling-craft score */}+ <StoryCraftPanel evaluation={story.evaluation} />+{/* Woven narrative for this chain */}{narrative?.storyId === story.id && (<div className="mt-3 bg-port-bg border border-amber-500/30 rounded-lg p-4 space-y-2">@@ -573,7 +742,16 @@ export default function AutobiographyTab({ onRefresh }) {</div>)}- <div className="flex items-center gap-2 justify-end pt-2 border-t border-port-border/50">+ <div className="flex flex-wrap items-center gap-2 justify-end pt-2 border-t border-port-border/50">+ <button+ onClick={() => handleEvaluateStory(story.id)}+ disabled={evaluatingStoryId === story.id}+ className="flex items-center gap-1 px-2 py-1 text-xs text-emerald-400/70 hover:text-emerald-400 transition-colors disabled:opacity-50"+ title="Score this story against the seven storytelling moves and CART"+ >+ {evaluatingStoryId === story.id ? <BrailleSpinner /> : <Gauge size={12} />}+ {story.evaluation ? 'Re-score' : 'Score craft'}+ </button>{isChainable(story) && (<buttononClick={() => handleWeaveNarrative(story.id)}diff --git a/client/src/services/apiDigitalTwin.js b/client/src/services/apiDigitalTwin.jsindex 39d31a7a31..5ea038b62e 100644--- a/client/src/services/apiDigitalTwin.js+++ b/client/src/services/apiDigitalTwin.js@@ -257,6 +257,8 @@ export const getAutobiographyThemes = () => request('/digital-twin/autobiographyexport const getAutobiographyPrompt = (exclude, options = {}) =>request(`/digital-twin/autobiography/prompt${exclude ? `?exclude=${exclude}` : ''}`, options);export const getAutobiographyPromptById = (id) => request(`/digital-twin/autobiography/prompt/${id}`);+export const getAutobiographySuggestions = (options = {}) =>+ request('/digital-twin/autobiography/suggestions', options);export const getAutobiographyStories = (theme = null) =>request(`/digital-twin/autobiography/stories${theme ? `?theme=${theme}` : ''}`);export const saveAutobiographyStory = (promptId, content, { parentStoryId, customPromptText } = {}, options = {}) =>@@ -285,6 +287,12 @@ export const weaveAutobiographyNarrative = (storyId, providerId) =>method: 'POST',body: JSON.stringify({ providerId })});+export const evaluateAutobiographyStory = (storyId, providerId, options = {}) =>+ request(`/digital-twin/autobiography/stories/${storyId}/evaluate`, {+ method: 'POST',+ body: JSON.stringify({ providerId }),+ ...options+ });// Digital Twin - Assessment Analyzerexport const analyzeAssessment = (content, providerId, model, options = {}) =>diff --git a/server/lib/README.md b/server/lib/README.mdindex 5866445e5f..f19a2eec83 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -145,6 +145,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `storyArcLimits.js` | Pure canonical length/count caps and series-design field/mode contract shared by sanitizers, schemas and browser editors. || `styleGuide.js` | Per-series house style (tense/POV/audience/rating/reading-level/tone/conventions): `sanitizeStyleGuide` + `renderStyleGuide` generation block + enums. || `storyBuilderSteps.js` | Unified Story Builder ordered step definitions + helpers (`STEPS`, `STEP_IDS`, `STEP_STATUSES`, `isValidStepId`, `stepIndex`). |+| `storytellingCraft.js` | The storytelling rubric the autobiography feature scores a story against, pure and dependency-free: `STORY_CRAFT_MOVES` (the seven moves — curiosity, tension, specificity, pace, the unexpected, the warmth-closing personal detail, the takeaway), `CART_STAGES` (Context/Action/Result/Takeaway), `buildStoryCraftEvaluationPrompt({question, story})` and `normalizeStoryCraftEvaluation(parsed)`. Rubric source: Shannon Jenkins, [How to Tell Stories Better Than 99% of People](https://youtu.be/lghSjBl9yGM). The normalizer emits every move and stage in canonical order whether or not the model returned it, so a truncated answer reads as uncredited rather than silently shortening the rubric. || `streamLines.js` | `createLineReader(onLine, {splitRe?, maxCarry?})` + `createOutputTail({budget?})` — buffered chunk→line splitter for child-process stdout/stderr. Carries the partial trailing line across `data` chunks and `flush()`es the final unterminated line on `close`; carry clamp guards a newline-less runaway stream. One reader per stream (a shared buffer corrupts marker lines). `splitRe: /[\r\n]+/` handles torch/tqdm bare-`\r` progress redraws. `createOutputTail` is the sibling rolling buffer of recent lines (char-budgeted, decoration-only lines skipped so an ASCII-art banner cannot push the real error out) that turns "exited with code 1" into what the tool actually printed — used by `streamingSpawn.js`. || `storyBuilderIntegrity.js` | Pure staleness hashing for the Story Builder (`hashUpstream`, `computeStaleSteps`, `computeSyncDrift`). || `projectStoreKit.js` | Shared project-store sync normalization, LWW batch decisions, and tombstone selection for file and PostgreSQL adapters. |@@ -562,7 +563,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and| `portosUrls.js` | `PORTOS_UI_URL` / `PORTOS_API_URL` — the origins PortOS interpolates into prompts and links, resolved from `PORTOS_*` / `PORT` at module load. Split out of `ports.js` so that module stays free of module-scope `process.env` reads and can be re-exported to the client. || `platform.js` | Platform/OS detection helpers — listening-port probes plus `isAppleSilicon()` (arm64 darwin; gates MLX model features, detect at the route boundary). || `signalCrypto.js` | Pure, dependency-free crypto for reading Signal Desktop's encrypted chat DB (#2154): SQLCipher-4 page decryption (`decryptSqlcipherDatabase`, `deriveSqlcipherKeys`, `sqlcipherPageHmac` — PBKDF2-SHA512 HMAC key + AES-256-CBC per page + HMAC-SHA512 verify → plaintext SQLite buffer the built-in `node:sqlite` can open) and Chromium/Electron `safeStorage` unwrap (`decryptSafeStorageValue`, `deriveSafeStorageKey` — macOS AES-128-CBC + PBKDF2-SHA1 over the keychain password). All functions return `{ ok, ... }` reports (never throw) for graceful degradation. Consumed by `services/signalSync.js`. |-| `timezone.js` | Timezone utilities for scheduling. `getLocalParts(utcDate, timezone)` / `getUtcOffsetMs(utcDate, timezone)` are the primitives; `nextLocalTime(afterMs, hours, minutes, timezone)` finds the next UTC instant matching a local HH:MM. `anchorLocalMidnightUtc(dayStr, tz)` resolves the first UTC instant belonging to a local date, including zones whose DST transition skips 00:00; `localDayWindowUtc(timezone, atDate?)` exposes an inclusive ISO-string window, while `localDayRangeUtc(dateStr, timezone)` returns a validated half-open `{ start, end }` `Date` pair ending at the next local-date boundary so 23h/25h transition days remain exact. Also owns `HHMM_RE`/`HHMM_STRICT_RE`, `parseHHMM`, and `isWithinTimeWindow` (mirrored client-side in `client/src/utils/timeWindow.js`). |+| `timezone.js` | Timezone utilities for scheduling. `getLocalParts(utcDate, timezone)` / `getUtcOffsetMs(utcDate, timezone)` are the primitives; `nextLocalTime(afterMs, hours, minutes, timezone)` finds the next UTC instant matching a local HH:MM. `anchorLocalMidnightUtc(dayStr, tz)` resolves the first UTC instant belonging to a local date, including zones whose DST transition skips 00:00; `localDayWindowUtc(timezone, atDate?)` exposes an inclusive ISO-string window, while `localDayRangeUtc(dateStr, timezone)` returns a validated half-open `{ start, end }` `Date` pair ending at the next local-date boundary so 23h/25h transition days remain exact. Also owns `HHMM_RE`/`HHMM_STRICT_RE`, `parseHHMM`, `dailyCronFromHHMM(time)` (the one strict "HH:MM" → `"M H * * *"` conversion every daily-reminder scheduler registers through, null on malformed input so the caller cancels rather than firing in some other slot), and `isWithinTimeWindow` (mirrored client-side in `client/src/utils/timeWindow.js`). || `tribeCadence.js` | Authoritative, pure Tribe care-cadence rules (single source of truth, mirrored to `client/src/lib/tribeCadence.js`): `cadenceStatus(entity)` → `{ state: external/missing/overdue/soon/steady, daysRemaining, daysOverdue }`, `daysSinceDate(dateStr)`, `DEFAULT_CADENCE_DAYS` (45), `SOON_WINDOW_DAYS` (7). Consumed by `personCadenceStatus` / `getCareSummary` in `services/tribe.js` (proactive alert + Care widget) and by the client Tribe page/map. || `tribeMatch.js` | Pure, deterministic matcher mapping a calendar attendee / message counterpart (`{ email, phone, name }`) to a tracked Tribe person for auto-logged touchpoints (#2033, #2151): `buildPersonMatchIndex(people)` → `{ byIdentifier, byPhone, byName }`, `matchPerson(identity, index)` (email/handle authoritative, then E.164 phone, then exact unique name fallback — no fuzzy matching), `matchPeople(identities, index)` → de-duplicated Set of personIds, `normalizeIdentifier(value)`, `normalizePhone(value)` (E.164 normalization for iMessage/Signal handles), `identityFromHandle(handle)` (classify a raw `chat.db` handle into email-or-phone). Also `resolveLinkedPersonId(tribePersonId, tribePersonDeleted)` — the shared soft-delete predicate a `beeper_participants` row's `tribe_person_id` cache must pass through everywhere it is shaped, so a soft-deleted Tribe person reads as unlinked in both `services/beeperConversations.js` and `services/beeperTribe.js`. Consumed by `autoLogTouchpoints` in `services/tribe.js` from the calendar, message, and iMessage sync producers. || `viteAllowedHosts.js` | Detect and remediate a managed app's Vite `server.allowedHosts`. `findViteConfig(repoPath)` locates the config; `parseAllowedHosts(src)` / `hostIsAllowed(parsed, host)` decide whether a Tailscale/IP host would be accepted (mirrors Vite's localhost+IP-always-allowed and leading-dot-suffix rules); `rewriteAllowedHosts(src)` deterministically injects `allowedHosts: true` (or bails `ok:false` on ambiguous shapes so the caller can fall back to an LLM fix); `checkViteHost(repoPath, host)` is the one-shot status used by `GET /api/apps/:id/vite-host-check`. |diff --git a/server/lib/index.js b/server/lib/index.jsindex b915ee5381..d1801f9541 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -129,6 +129,7 @@ export * from './storyArcLimits.js';export * from './styleGuide.js';export * from './storyBuilderIntegrity.js';export * from './storyBuilderSteps.js';+export * from './storytellingCraft.js';export * from './streamLines.js';export * from './taskDataInputCatalog.js';// The canon field caps storyBible.js sanitizes against, as a pure leaf.diff --git a/server/lib/instanceFeatureRegistry.js b/server/lib/instanceFeatureRegistry.jsindex b9d479c405..ebbbe5c050 100644--- a/server/lib/instanceFeatureRegistry.js+++ b/server/lib/instanceFeatureRegistry.js@@ -36,6 +36,15 @@ export const INSTANCE_FEATURES = Object.freeze([description: 'Daily cognitive practice, progress metrics, and reminder prompts.',defaultEnabled: true,}),+ Object.freeze({+ id: 'autobiography',+ label: 'Autobiography',+ description: 'A daily prompt to write one short life story, with suggested questions and storytelling-craft feedback.',+ // Default ON, like POST: turning the FEATURE off hides the tab and silences+ // the scheduler entirely, while the daily prompt itself stays separately+ // opt-in (config.reminder) so an enabled feature never nudges uninvited.+ defaultEnabled: true,+ }),Object.freeze({id: 'datadog',label: 'DataDog',diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex 4f9a90cffa..853f5ed79f 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -228,7 +228,7 @@ const RAW_NAV_COMMANDS = [{ id: 'nav.twin.import', path: '/digital-twin/import', label: 'Import', section: 'Identity', tabGroup: 'digital-twin', tabId: 'import', aliases: ['twin-import'], keywords: ['sources'] },{ id: 'nav.twin.accounts', path: '/digital-twin/accounts', label: 'Accounts', section: 'Identity', tabGroup: 'digital-twin', tabId: 'accounts', aliases: ['twin-accounts'], keywords: ['sources'] },{ id: 'nav.twin.interview', path: '/digital-twin/interview', label: 'Interview', section: 'Identity', tabGroup: 'digital-twin', tabId: 'interview', aliases: ['twin-interview'], keywords: ['sources'] },- { id: 'nav.twin.autobiography', path: '/digital-twin/autobiography', label: 'Autobiography', section: 'Identity', tabGroup: 'digital-twin', tabId: 'autobiography', aliases: ['twin-autobiography', 'autobiography'], keywords: ['sources'] },+ { id: 'nav.twin.autobiography', path: '/digital-twin/autobiography', label: 'Autobiography', section: 'Identity', feature: 'autobiography', tabGroup: 'digital-twin', tabId: 'autobiography', aliases: ['twin-autobiography', 'autobiography'], keywords: ['sources'] },{ id: 'nav.twin.enrich', path: '/digital-twin/enrich', label: 'Enrich', section: 'Identity', tabGroup: 'digital-twin', tabId: 'enrich', aliases: ['twin-enrich'], keywords: ['sources'] },{ id: 'nav.twin.test', path: '/digital-twin/test', label: 'Test', section: 'Identity', tabGroup: 'digital-twin', tabId: 'test', aliases: ['twin-assessment', 'twin-test'], keywords: ['assessment'] },{ id: 'nav.twin.personality', path: '/digital-twin/personality', label: 'Personality', section: 'Identity', tabGroup: 'digital-twin', tabId: 'personality', aliases: ['twin-personality', 'personality', 'model-personality'], keywords: ['assessment', 'llm', 'model', 'traits', 'radar', 'alignment', 'self-profile', 'compare', 'sycophancy'] },diff --git a/server/lib/storytellingCraft.js b/server/lib/storytellingCraft.jsnew file mode 100644index 0000000000..97599b637d--- /dev/null+++ b/server/lib/storytellingCraft.js@@ -0,0 +1,208 @@+/**+ * Storytelling craft rubric — pure: no I/O, no clock, no provider call.+ *+ * Declares the seven moves and the CART structure the autobiography feature+ * scores a written story against, plus the prompt builder and the normalizer+ * that turns an LLM's JSON answer into a shape the UI can render without+ * re-checking every field.+ *+ * Source of the rubric: Shannon Jenkins, "How to Tell Stories Better Than 99%+ * of People" (https://youtu.be/lghSjBl9yGM) — the two Ted Lasso scenes it+ * breaks down end on a seven-move summary plus the CART framework (Context,+ * Action, Result, Takeaway).+ *+ * It lives in lib/ rather than beside the service because it is the contract+ * two sides share: the service builds a provider prompt from it, and the+ * client renders a score row per move. A move added here shows up in both+ * without either side re-listing the vocabulary.+ */++import { trimToClause } from './textUtils.js';++/** Highest per-move score the rubric uses. Scores are integers in 0..5. */+export const STORY_CRAFT_MAX_SCORE = 5;++/**+ * The seven moves, in the order the video lands them. `id` is the stable key+ * the LLM answers with and the client keys rows on — never renumber it.+ */+export const STORY_CRAFT_MOVES = Object.freeze([+ Object.freeze({+ id: 'curiosity',+ label: 'Create curiosity',+ description: 'An unanswered question, information deliberately held back, or a destination the reader wants to be taken to.',+ }),+ Object.freeze({+ id: 'tension',+ label: 'Create tension',+ description: 'A reason to care what happens next — something uncertain, something at stake, something the reader wants resolved.',+ }),+ Object.freeze({+ id: 'specificity',+ label: 'Zoom in to a specific moment',+ description: 'One concrete scene — the particular conversation, room, or instant something changed — instead of a helicopter-view summary.',+ }),+ Object.freeze({+ id: 'pace',+ label: 'Change the pace',+ description: 'Slow down around the moments the reader should experience; move fast through the connective tissue they only need in order to follow.',+ }),+ Object.freeze({+ id: 'unexpected',+ label: 'Introduce something unexpected',+ description: 'A twist, a surprising detail, or an opening nobody saw coming — including a reveal that makes the reader reinterpret what came before.',+ }),+ Object.freeze({+ id: 'personal',+ label: 'Close the warmth gap',+ description: 'A well-chosen personal detail that lets the human being show through. Personal, not private — one revealing detail beats confession.',+ }),+ Object.freeze({+ id: 'takeaway',+ label: 'Land with a takeaway',+ description: 'What it meant and why you told it — the ending that makes the whole story click into place.',+ }),+]);++export const STORY_CRAFT_MOVE_IDS = Object.freeze(STORY_CRAFT_MOVES.map((m) => m.id));++/**+ * CART — the structural spine underneath the seven moves. Scored as+ * present/absent with a one-line note rather than 0..5: a story either takes+ * the reader through the stage or it doesn't.+ */+export const CART_STAGES = Object.freeze([+ Object.freeze({ id: 'context', label: 'Context', description: 'Who, where, when — just enough for the rest to land.' }),+ Object.freeze({ id: 'action', label: 'Action', description: 'What actually happened, in scene.' }),+ Object.freeze({ id: 'result', label: 'Result', description: 'How it turned out.' }),+ Object.freeze({ id: 'takeaway', label: 'Takeaway', description: 'What it means for whoever is listening. The stage people most often drop.' }),+]);++export const CART_STAGE_IDS = Object.freeze(CART_STAGES.map((s) => s.id));++const clampScore = (value) => {+ const n = Math.round(Number(value));+ if (!Number.isFinite(n)) return 0;+ return Math.min(STORY_CRAFT_MAX_SCORE, Math.max(0, n));+};++// Every prose field here comes straight off an LLM and is persisted into+// stories.json, so bound it where it enters the system rather than capping+// downstream. `trimToClause` rather than `trimTo`: these are sentences the user+// reads as advice, and a cut that lands mid-thought reads as a bug in the+// coaching. Non-strings normalize to '' inside the helper, so an absent field+// reads as empty, never as `undefined`.+const MAX_MOVE_NOTE = 400;+const MAX_REVISION = 1000;+const cleanText = (value, max = MAX_MOVE_NOTE) => trimToClause(value, max);++/**+ * Build the evaluation prompt for one story.+ *+ * `question` is the question the story answers — the autobiography feature+ * treats every story as an answer to a question, direct ("Why do I like black+ * licorice?") or implied ("Describe the house you grew up in"), so the rubric+ * can judge whether the piece actually answers it.+ */+export function buildStoryCraftEvaluationPrompt({ question, story }) {+ const moveLines = STORY_CRAFT_MOVES+ .map((m, i) => `${i + 1}. ${m.id} — ${m.label}: ${m.description}`)+ .join('\n');+ const cartLines = CART_STAGES+ .map((s) => `- ${s.id} (${s.label}): ${s.description}`)+ .join('\n');++ return `You are a storytelling coach. Evaluate the personal story below against a fixed rubric of seven moves and the CART structure. Be a generous reader but an honest scorer — say what is actually on the page, not what a charitable reading could infer.++THE QUESTION THE STORY IS ANSWERING:+${question || '(none given — infer the implied question the story answers)'}++THE STORY:+"""+${story}+"""++THE SEVEN MOVES (score each 0-${STORY_CRAFT_MAX_SCORE}, where 0 = absent, 3 = present but ordinary, ${STORY_CRAFT_MAX_SCORE} = executed the way a great storyteller would):+${moveLines}++CART STRUCTURE (present: true/false for each):+${cartLines}++For every move give:+- score: integer 0-${STORY_CRAFT_MAX_SCORE}+- evidence: a short quote or paraphrase from the story showing what earned that score (or what is missing)+- suggestion: one concrete, specific revision the writer could make. Name the sentence or beat to change. No generic advice.++Also give:+- answersQuestion: true/false — does the story actually answer the question above?+- revision: two or three sentences describing the single highest-leverage rewrite.++Return ONLY JSON, no prose or markdown fences, in exactly this shape:+{+ "moves": { ${STORY_CRAFT_MOVE_IDS.map((id) => `"${id}": { "score": 0, "evidence": "", "suggestion": "" }`).join(', ')} },+ "cart": { ${CART_STAGE_IDS.map((id) => `"${id}": { "present": true, "note": "" }`).join(', ')} },+ "answersQuestion": true,+ "revision": ""+}`;+}++/**+ * Normalize a parsed LLM answer into the render-ready evaluation.+ *+ * Every move and CART stage is emitted in canonical order whether or not the+ * model returned it — a missing move scores 0 with an empty note rather than+ * vanishing from the row list, so a truncated answer reads as "not assessed+ * and therefore not credited" instead of silently shortening the rubric.+ *+ * `overallScore` is the mean move score to one decimal. Returns null when the+ * payload is not an object at all, which is the caller's signal to report a+ * parse failure rather than persist an all-zero evaluation.+ */+export function normalizeStoryCraftEvaluation(parsed) {+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;++ const rawMoves = (parsed.moves && typeof parsed.moves === 'object') ? parsed.moves : {};+ const moves = STORY_CRAFT_MOVES.map((move) => {+ const entry = rawMoves[move.id];+ const source = (entry && typeof entry === 'object') ? entry : {};+ return {+ id: move.id,+ label: move.label,+ score: clampScore(source.score),+ evidence: cleanText(source.evidence),+ suggestion: cleanText(source.suggestion),+ };+ });++ const rawCart = (parsed.cart && typeof parsed.cart === 'object') ? parsed.cart : {};+ const cart = CART_STAGES.map((stage) => {+ const entry = rawCart[stage.id];+ const source = (entry && typeof entry === 'object') ? entry : {};+ return {+ id: stage.id,+ label: stage.label,+ present: source.present === true,+ note: cleanText(source.note),+ };+ });++ const total = moves.reduce((sum, m) => sum + m.score, 0);+ const overallScore = Math.round((total / moves.length) * 10) / 10;++ // Strongest/weakest are the row the writer should keep doing and the row to+ // work on next. Ties resolve to rubric order, which is the order the video+ // teaches them in — a deterministic answer beats an arbitrary one.+ const strongest = moves.reduce((best, m) => (m.score > best.score ? m : best), moves[0]);+ const weakest = moves.reduce((worst, m) => (m.score < worst.score ? m : worst), moves[0]);++ return {+ moves,+ cart,+ overallScore,+ maxScore: STORY_CRAFT_MAX_SCORE,+ strongestMoveId: strongest.id,+ weakestMoveId: weakest.id,+ answersQuestion: parsed.answersQuestion !== false,+ revision: cleanText(parsed.revision, MAX_REVISION),+ };+}diff --git a/server/lib/storytellingCraft.test.js b/server/lib/storytellingCraft.test.jsnew file mode 100644index 0000000000..9fe45622dc--- /dev/null+++ b/server/lib/storytellingCraft.test.js@@ -0,0 +1,146 @@+/**+ * Tests for the storytelling-craft rubric. The prompt builder and the+ * normalizer sit either side of an LLM round trip, so the assertions here are+ * about what the rubric GUARANTEES regardless of what the model returns: every+ * move and CART stage present in canonical order, scores bounded, and a+ * non-object payload rejected rather than persisted as an all-zero score.+ */++import { describe, it, expect } from 'vitest';+import {+ STORY_CRAFT_MOVES,+ STORY_CRAFT_MOVE_IDS,+ STORY_CRAFT_MAX_SCORE,+ CART_STAGE_IDS,+ buildStoryCraftEvaluationPrompt,+ normalizeStoryCraftEvaluation+} from './storytellingCraft.js';++const fullAnswer = (scores) => ({+ moves: Object.fromEntries(+ STORY_CRAFT_MOVE_IDS.map((id, i) => [id, {+ score: scores[i],+ evidence: ` evidence ${id} `,+ suggestion: `suggestion ${id}`+ }])+ ),+ cart: Object.fromEntries(CART_STAGE_IDS.map(id => [id, { present: true, note: `note ${id}` }])),+ answersQuestion: true,+ revision: ' tighten the opening '+});++describe('buildStoryCraftEvaluationPrompt', () => {+ it('names every move id so the model answers in the keys the normalizer reads', () => {+ const prompt = buildStoryCraftEvaluationPrompt({ question: 'Why do I like black licorice?', story: 'A story.' });++ for (const id of STORY_CRAFT_MOVE_IDS) {+ expect(prompt).toContain(id);+ }+ for (const id of CART_STAGE_IDS) {+ expect(prompt).toContain(id);+ }+ });++ it('includes the question and the story text', () => {+ const prompt = buildStoryCraftEvaluationPrompt({+ question: 'Why do I like black licorice?',+ story: 'It started at my grandmother’s kitchen table.'+ });++ expect(prompt).toContain('Why do I like black licorice?');+ expect(prompt).toContain('It started at my grandmother’s kitchen table.');+ });++ it('tells the model to infer the implied question when none was given', () => {+ const prompt = buildStoryCraftEvaluationPrompt({ question: '', story: 'A story.' });++ expect(prompt).toMatch(/infer the implied question/i);+ });+});++describe('normalizeStoryCraftEvaluation', () => {+ it('rejects a non-object payload rather than scoring it zero', () => {+ expect(normalizeStoryCraftEvaluation(null)).toBeNull();+ expect(normalizeStoryCraftEvaluation('not json')).toBeNull();+ expect(normalizeStoryCraftEvaluation([1, 2, 3])).toBeNull();+ });++ it('returns every move and CART stage in canonical order', () => {+ const result = normalizeStoryCraftEvaluation(fullAnswer([5, 4, 3, 2, 1, 0, 5]));++ expect(result.moves.map(m => m.id)).toEqual([...STORY_CRAFT_MOVE_IDS]);+ expect(result.cart.map(s => s.id)).toEqual([...CART_STAGE_IDS]);+ expect(result.moves[0].label).toBe(STORY_CRAFT_MOVES[0].label);+ });++ it('credits a move the model omitted as zero instead of dropping the row', () => {+ const partial = fullAnswer([5, 5, 5, 5, 5, 5, 5]);+ delete partial.moves.takeaway;++ const result = normalizeStoryCraftEvaluation(partial);++ expect(result.moves).toHaveLength(STORY_CRAFT_MOVE_IDS.length);+ const takeaway = result.moves.find(m => m.id === 'takeaway');+ expect(takeaway.score).toBe(0);+ expect(takeaway.evidence).toBe('');+ });++ it('bounds a score the model returned out of range', () => {+ const wild = fullAnswer([99, -4, 3, 3, 3, 3, 3]);++ const result = normalizeStoryCraftEvaluation(wild);++ expect(result.moves[0].score).toBe(STORY_CRAFT_MAX_SCORE);+ expect(result.moves[1].score).toBe(0);+ });++ it('treats a non-numeric score as zero rather than NaN', () => {+ const wild = fullAnswer(['great', 3, 3, 3, 3, 3, 3]);++ expect(normalizeStoryCraftEvaluation(wild).moves[0].score).toBe(0);+ });++ it('averages the move scores to one decimal', () => {+ // 5+4+3+2+1+0+5 = 20 over 7 moves = 2.857… → 2.9+ const result = normalizeStoryCraftEvaluation(fullAnswer([5, 4, 3, 2, 1, 0, 5]));++ expect(result.overallScore).toBe(2.9);+ expect(result.maxScore).toBe(STORY_CRAFT_MAX_SCORE);+ });++ it('names the strongest and weakest move, breaking ties in rubric order', () => {+ const result = normalizeStoryCraftEvaluation(fullAnswer([5, 5, 1, 1, 3, 3, 3]));++ expect(result.strongestMoveId).toBe(STORY_CRAFT_MOVE_IDS[0]);+ expect(result.weakestMoveId).toBe(STORY_CRAFT_MOVE_IDS[2]);+ });++ it('trims prose and defaults answersQuestion to true when the model omits it', () => {+ const answer = fullAnswer([3, 3, 3, 3, 3, 3, 3]);+ delete answer.answersQuestion;++ const result = normalizeStoryCraftEvaluation(answer);++ expect(result.revision).toBe('tighten the opening');+ expect(result.moves[0].evidence).toBe(`evidence ${STORY_CRAFT_MOVE_IDS[0]}`);+ expect(result.answersQuestion).toBe(true);+ });++ it('carries an explicit answersQuestion:false through', () => {+ const answer = { ...fullAnswer([3, 3, 3, 3, 3, 3, 3]), answersQuestion: false };++ expect(normalizeStoryCraftEvaluation(answer).answersQuestion).toBe(false);+ });++ it('treats a CART stage as absent unless the model said true', () => {+ const answer = fullAnswer([3, 3, 3, 3, 3, 3, 3]);+ answer.cart.takeaway = { present: 'yes', note: 'ambiguous' };+ delete answer.cart.result;++ const result = normalizeStoryCraftEvaluation(answer);++ expect(result.cart.find(s => s.id === 'takeaway').present).toBe(false);+ expect(result.cart.find(s => s.id === 'result').present).toBe(false);+ expect(result.cart.find(s => s.id === 'context').present).toBe(true);+ });+});diff --git a/server/routes/autobiography.js b/server/routes/autobiography.jsindex 9036df0d7a..2585a3788a 100644--- a/server/routes/autobiography.js+++ b/server/routes/autobiography.js@@ -13,16 +13,22 @@ import { z } from 'zod';import * as autobiographyService from '../services/autobiography.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';+import { HHMM_STRICT_RE } from '../lib/timezone.js';const router = Router();// Validation schemasconst saveStorySchema = z.object({+ // Either a bank prompt id, `followup-<id>`, or the `custom` sentinel when the+ // user wrote their own question — in which case `customPromptText` carries it.promptId: z.string().min(1),content: z.string().min(1).max(50000),parentStoryId: z.string().optional(),- customPromptText: z.string().optional()-});+ customPromptText: z.string().max(500).optional()+}).refine(+ (v) => v.promptId !== autobiographyService.CUSTOM_PROMPT_ID || !!v.customPromptText?.trim(),+ { message: 'customPromptText is required when promptId is "custom"', path: ['customPromptText'] }+);const generateFollowUpsSchema = z.object({providerId: z.string().optional()@@ -36,9 +42,19 @@ const updateStorySchema = z.object({content: z.string().min(1).max(50000)});+const evaluateStorySchema = z.object({+ providerId: z.string().optional()+});+const updateConfigSchema = z.object({enabled: z.boolean().optional(),- intervalHours: z.number().min(1).max(168).optional()+ intervalHours: z.number().min(1).max(168).optional(),+ reminder: z.object({+ enabled: z.boolean().optional(),+ // Strict "HH:MM" — the scheduler refuses to register anything else, so a+ // malformed time has to fail here rather than silently disable the cron.+ time: z.string().regex(HHMM_STRICT_RE, 'Expected a 24-hour HH:MM time').optional()+ }).optional()});// =============================================================================@@ -95,6 +111,15 @@ router.get('/prompt', asyncHandler(async (req, res) => {res.json(prompt);}));+/**+ * GET /api/digital-twin/autobiography/suggestions+ * Get a short menu of story ideas (the same set the daily prompt offers)+ */+router.get('/suggestions', asyncHandler(async (req, res) => {+ const suggestions = await autobiographyService.getPromptSuggestions();+ res.json(suggestions);+}));+/*** GET /api/digital-twin/autobiography/prompt/:id* Get a specific prompt by ID@@ -160,6 +185,19 @@ router.delete('/stories/:id', asyncHandler(async (req, res) => {res.json({ success: true, story });}));+/**+ * POST /api/digital-twin/autobiography/stories/:id/evaluate+ * Score the story against the storytelling-craft rubric (seven moves + CART)+ */+router.post('/stories/:id/evaluate', asyncHandler(async (req, res) => {+ const validated = validateRequest(evaluateStorySchema, req.body);+ const result = await autobiographyService.evaluateStory(req.params.id, validated.providerId);+ if (result.error) {+ throw new ServerError(result.error, { status: 400, code: 'EVALUATION_ERROR' });+ }+ res.json(result);+}));+// =============================================================================// FOLLOW-UP CHAINS// =============================================================================diff --git a/server/services/autobiography.js b/server/services/autobiography.jsindex 18fcbc8825..6d1e4977a6 100644--- a/server/services/autobiography.js+++ b/server/services/autobiography.js@@ -1,25 +1,51 @@/*** Autobiography Service*- * Prompts the user on a regular basis to write 5-minute life stories- * based on thematic prompts, building an autobiography over time.+ * Prompts the user on a regular basis to write 5-minute life stories, building+ * an autobiography over time. Every story answers a QUESTION — either one of+ * the thematic prompts below (where the question is often implied: "Describe+ * the house you grew up in") or a question the user writes themselves ("Why do+ * I like black licorice?"). That framing is what the storytelling-craft+ * evaluation scores against: a story that never answers its question has not+ * landed, however well written it is.** Stories are stored as part of the digital twin data.*/+import { EventEmitter } from 'events';import { join } from 'path';import { v4 as uuidv4 } from '../lib/uuid.js';import { atomicWrite, ensureDir, PATHS, readJSONFile } from '../lib/fileUtils.js';+import { deepMerge } from '../lib/objects.js';import { recordTombstone } from '../lib/tombstones.js';import { countWords } from '../lib/textUtils.js';+import {+ buildStoryCraftEvaluationPrompt,+ normalizeStoryCraftEvaluation+} from '../lib/storytellingCraft.js';import {queueAutobiographyConfigWrite,queueAutobiographyStoriesWrite} from './autobiographyFileQueues.js';-import { addNotification, NOTIFICATION_TYPES, exists as notificationExists } from './notifications.js';+import { addNotification, NOTIFICATION_TYPES, PRIORITY_LEVELS } from './notifications.js';import { getActiveProvider, getProviderById } from './providers.js';import { callProviderAISimple, parseLLMJSON } from './aiProvider.js';+// Tiny pub/sub, mirroring meatspacePost.js's postConfigEvents: the reminder+// scheduler subscribes so ANY caller of updateConfig() reschedules the cron for+// free, without this module importing back into the scheduler (a service cycle).+export const autobiographyConfigEvents = new EventEmitter();++// How many story ideas a prompt notification offers. One would be a command;+// a short menu is an invitation, and the user picks whichever memory is+// actually live for them today.+export const PROMPT_SUGGESTION_COUNT = 3;++// The promptId stories written against the user's own question carry. Not a+// bank id, so getPromptById() returns null for it and the story's own+// promptText is the only question of record.+export const CUSTOM_PROMPT_ID = 'custom';+const DATA_DIR = join(PATHS.digitalTwin, 'autobiography');const STORIES_FILE = join(DATA_DIR, 'stories.json');const CONFIG_FILE = join(DATA_DIR, 'config.json');@@ -164,7 +190,13 @@ const DEFAULT_CONFIG = {intervalHours: 24,enabled: false,lastPromptAt: null,- lastPromptId: null+ lastPromptId: null,+ // Opt-in daily reminder at a chosen local time (default OFF), the same shape+ // and default the POST reminder uses. `enabled` above still governs the+ // interval-based autonomous job; this slice governs the time-of-day cron in+ // autobiographyReminder.js. Both funnel into sendStoryPrompt(), which is+ // idempotent for the day, so turning on both cannot double-nudge.+ reminder: { enabled: false, time: '09:00' }};const DEFAULT_DATA = {@@ -193,7 +225,13 @@ async function saveStories(data) {async function loadConfig() {await ensureDir(DATA_DIR);- return readJSONFile(CONFIG_FILE, DEFAULT_CONFIG, { strict: true });+ // Deep-merge onto a fresh clone of the defaults so a config written before+ // the `reminder` slice existed still reads back with it — otherwise the+ // scheduler would see `config.reminder` as undefined on every install that+ // saved settings before this shipped.+ const defaults = structuredClone(DEFAULT_CONFIG);+ const stored = await readJSONFile(CONFIG_FILE, defaults, { strict: true });+ return deepMerge(defaults, stored);}async function saveConfig(config) {@@ -201,65 +239,123 @@ async function saveConfig(config) {await atomicWrite(CONFIG_FILE, config);}+// Stories written against a question the user typed themselves file under this+// pseudo-theme rather than 'unknown' — it is a real, nameable category (the+// questions they chose to answer), and it keeps the theme filter honest. Its id+// IS the custom promptId sentinel, so the two can never disagree.+export const CUSTOM_THEME = Object.freeze({ id: CUSTOM_PROMPT_ID, label: 'Your Own Question' });+/**- * Get all available themes with their prompt counts+ * Get all available themes with their prompt counts.+ *+ * The custom pseudo-theme is included with a zero prompt count: it has no bank+ * entries by definition, but stories land in it and the filter row needs a chip+ * to reach them.*/export function getThemes() {- return PROMPT_THEMES.map(theme => ({- id: theme.id,- label: theme.label,- promptCount: theme.prompts.length- }));+ return [+ ...PROMPT_THEMES.map(theme => ({+ id: theme.id,+ label: theme.label,+ promptCount: theme.prompts.length+ })),+ { ...CUSTOM_THEME, promptCount: 0 }+ ];}+// The bank flattened once at module load — it is derived purely from the+// module-level PROMPT_THEMES, so rebuilding its 60 entries per request bought+// nothing. Frozen because callers receive these objects by reference.+const ALL_PROMPTS = Object.freeze(PROMPT_THEMES.flatMap(theme =>+ theme.prompts.map((text, idx) => Object.freeze({+ id: `${theme.id}-${idx}`,+ themeId: theme.id,+ themeLabel: theme.label,+ text+ }))+));+/**- * Pick the next prompt, cycling through themes and avoiding repeats.- * @param {string} [excludePromptId] - Prompt ID to exclude (used by skip to avoid returning the same prompt)+ * Rank every still-unused prompt, least-written theme first, and hand back the+ * top `count`. Shared by getNextPrompt (count 1) and getPromptSuggestions.+ *+ * The ranking itself is a plain read — `getPromptSuggestions` runs on every+ * Autobiography tab open, and taking the stories write queue for it would+ * serialize a read-only page load behind any in-flight story save or+ * digital-twin sync write. Only the bank-exhaustion branch actually writes+ * (it resets `usedPrompts`), so only that branch enters the queue.+ *+ * Suggestions come from DISTINCT themes where the bank allows it: three+ * variations on childhood read as one idea, while childhood/work/travel read+ * as a genuine choice. Once the distinct-theme picks run out (late in a cycle,+ * or with `count` above the theme count) it falls back to the remaining+ * ranking rather than returning short.*/-export async function getNextPrompt(excludePromptId) {- return queueAutobiographyStoriesWrite(async () => {- const data = await loadStories();- const usedPrompts = data.usedPrompts || [];+async function pickPrompts(count, excludePromptId) {+ const data = await loadStories();+ const usedPrompts = new Set(data.usedPrompts || []);++ let available = ALL_PROMPTS.filter(p => !usedPrompts.has(p.id));++ // If all prompts used, reset and start over+ if (available.length === 0) {+ await queueAutobiographyStoriesWrite(async () => {+ // Re-read inside the queue so the reset merges onto the freshest stories+ // rather than clobbering a save that landed while we were ranking.+ const current = await loadStories();+ current.usedPrompts = [];+ await saveStories(current);+ });+ available = [...ALL_PROMPTS];+ }- // Build flat list of all prompts with IDs- const allPrompts = PROMPT_THEMES.flatMap(theme =>- theme.prompts.map((text, idx) => ({- id: `${theme.id}-${idx}`,- themeId: theme.id,- themeLabel: theme.label,- text- }))- );-- // Filter out used prompts- let available = allPrompts.filter(p => !usedPrompts.includes(p.id));-- // If all prompts used, reset and start over- if (available.length === 0) {- data.usedPrompts = [];- await saveStories(data);- available = allPrompts;+ // Exclude the currently displayed prompt so skip returns a different one+ if (excludePromptId) {+ const filtered = available.filter(p => p.id !== excludePromptId);+ if (filtered.length > 0) {+ available = filtered;}+ }- // Exclude the currently displayed prompt so skip returns a different one- if (excludePromptId) {- const filtered = available.filter(p => p.id !== excludePromptId);- if (filtered.length > 0) {- available = filtered;- }- }+ // Pick from the least-used theme to keep balance+ const themeCounts = {};+ for (const story of data.stories) {+ themeCounts[story.themeId] = (themeCounts[story.themeId] || 0) + 1;+ }- // Pick from the least-used theme to keep balance- const themeCounts = {};- for (const story of data.stories) {- themeCounts[story.themeId] = (themeCounts[story.themeId] || 0) + 1;- }+ // Sort available prompts by theme usage (least written first)+ available.sort((a, b) => (themeCounts[a.themeId] || 0) - (themeCounts[b.themeId] || 0));++ // One theme's best prompt first, then everything else in the same ranked+ // order — so the menu reads as a genuine choice rather than three variations+ // on childhood, and still fills to `count` late in a cycle when fewer themes+ // than that are left.+ const seenThemes = new Set();+ const firstPerTheme = [];+ const remainder = [];+ for (const prompt of available) {+ (seenThemes.has(prompt.themeId) ? remainder : firstPerTheme).push(prompt);+ seenThemes.add(prompt.themeId);+ }- // Sort available prompts by theme usage (least written first)- available.sort((a, b) => (themeCounts[a.themeId] || 0) - (themeCounts[b.themeId] || 0));+ return [...firstPerTheme, ...remainder].slice(0, count);+}- return available[0];- });+/**+ * Pick the next prompt, cycling through themes and avoiding repeats.+ * @param {string} [excludePromptId] - Prompt ID to exclude (used by skip to avoid returning the same prompt)+ */+export async function getNextPrompt(excludePromptId) {+ const [prompt] = await pickPrompts(1, excludePromptId);+ return prompt;+}++/**+ * A short menu of story ideas — what the daily prompt offers instead of one+ * assignment, and what the UI shows when the user opens the tab cold.+ */+export async function getPromptSuggestions(count = PROMPT_SUGGESTION_COUNT) {+ return pickPrompts(count);}/**@@ -292,11 +388,21 @@ export async function saveStory({ promptId, content, parentStoryId, customPromptconst isFollowUp = !!parentStoryId;const parentStory = isFollowUp ? data.stories.find(s => s.id === parentStoryId) : null;+ // Resolve which of the three origins owns this story's theme ONCE, so the+ // id and the label can't come from different sources and leave a record+ // that's unfalsifiable after the fact. A follow-up inherits its parent's+ // theme; a bank prompt carries its own; a question the user typed+ // themselves has no bank prompt behind it and files under the custom+ // pseudo-theme, with its own promptText as the only question of record.+ const themeSource = isFollowUp+ ? parentStory+ : (prompt || (customPromptText ? CUSTOM_THEME : null));+const story = {id: uuidv4(),promptId: isFollowUp ? `followup-${parentStoryId}` : promptId,- themeId: isFollowUp ? (parentStory?.themeId || 'unknown') : (prompt?.themeId || 'unknown'),- themeLabel: isFollowUp ? (parentStory?.themeLabel || 'Unknown') : (prompt?.themeLabel || 'Unknown'),+ themeId: themeSource?.themeId ?? themeSource?.id ?? 'unknown',+ themeLabel: themeSource?.themeLabel ?? themeSource?.label ?? 'Unknown',promptText: customPromptText || prompt?.text || '',content,wordCount: countWords(content),@@ -306,10 +412,14 @@ export async function saveStory({ promptId, content, parentStoryId, customPromptdata.stories.push(story);- // Mark prompt as used- if (!data.usedPrompts) data.usedPrompts = [];- if (!data.usedPrompts.includes(promptId)) {- data.usedPrompts.push(promptId);+ // Mark prompt as used — only for real bank prompts. Pushing 'custom' or a+ // `followup-…` id would permanently occupy a slot in the used-list that no+ // bank prompt can ever match, delaying the cycle reset for nothing.+ if (prompt) {+ if (!data.usedPrompts) data.usedPrompts = [];+ if (!data.usedPrompts.includes(promptId)) {+ data.usedPrompts.push(promptId);+ }}await saveStories(data);@@ -428,13 +538,30 @@ export async function getConfig() {* Update configuration*/export async function updateConfig(updates) {- return queueAutobiographyConfigWrite(async () => {+ const updated = await queueAutobiographyConfigWrite(async () => {const config = await loadConfig();- const updated = { ...config, ...updates };- await saveConfig(updated);- console.log(`📖 Autobiography config updated: interval=${updated.intervalHours}h, enabled=${updated.enabled}`);- return updated;+ const merged = { ...config, ...updates };+ if (updates?.reminder) {+ // Merge rather than replace so a patch that only flips `enabled` keeps+ // the saved time, and stamp WHEN the slice last changed — the missed-slot+ // catch-up in autobiographyReminder.js uses it to refuse replaying a slot+ // that elapsed under a different (possibly disabled) configuration.+ merged.reminder = {+ ...config.reminder,+ ...updates.reminder,+ updatedAt: new Date().toISOString()+ };+ }+ await saveConfig(merged);+ console.log(`📖 Autobiography config updated: interval=${merged.intervalHours}h, enabled=${merged.enabled}, reminder=${merged.reminder?.enabled ? merged.reminder.time : 'off'}`);+ return merged;});+ // Emit AFTER the write succeeds so the reminder scheduler never reschedules+ // against a config change that did not persist. `updates` rides along so a+ // subscriber can gate on the slice it cares about instead of rescheduling on+ // every unrelated save.+ autobiographyConfigEvents.emit('autobiography-config:updated', { config: updated, updates });+ return updated;}/**@@ -636,6 +763,73 @@ Rules:return { narrative, storyCount: chain.length };}+/**+ * Send one story-prompt notification offering a short menu of ideas.+ *+ * Deterministic — it picks from the on-disk prompt bank and makes NO provider+ * call, so it is safe on a cold install (AGENTS.md's AI Provider Usage Policy).+ *+ * This is the single notification path — both the interval-based autonomous job+ * (`checkAndPrompt`) and the time-of-day cron (`autobiographyReminder.js`) send+ * through it — but it does NOT decide whether a nudge is due. Each caller owns+ * a cadence guard appropriate to it: the job gates on `intervalHours` since+ * `lastPromptAt`, and the cron gates on whether a prompt already went out on+ * the user's local day (dailyReminderScheduler.js). Because this stamps+ * `lastPromptAt`, an install running both still cannot nudge twice.+ *+ * It deliberately does NOT gate on `notifications.exists(AUTOBIOGRAPHY_PROMPT)`:+ * that matches ANY notification of the type ever created, read or not, so it+ * would silence the daily prompt permanently after its very first nudge.+ */+export async function sendStoryPrompt() {+ return queueAutobiographyConfigWrite(sendStoryPromptUnqueued);+}++/**+ * The body of sendStoryPrompt, minus acquiring the config write queue.+ *+ * checkAndPrompt runs its due-check and this sender inside ONE queue task, so+ * two concurrent due-checks cannot both read the same stale `lastPromptAt` and+ * each send a prompt. The file write queue is a plain tail, not a re-entrant+ * lock, so that task cannot call the queue-acquiring wrapper.+ */+async function sendStoryPromptUnqueued(loadedConfig) {+ const suggestions = await getPromptSuggestions();+ const [prompt, ...alternates] = suggestions;+ if (!prompt) {+ return { prompted: false, reason: 'no_prompts_available' };+ }++ const alternateLine = alternates.length+ ? ` Or: ${alternates.map(p => p.text).join(' · ')}`+ : '';++ await addNotification({+ type: NOTIFICATION_TYPES.AUTOBIOGRAPHY_PROMPT,+ title: '5-Minute Story Time',+ description: `${prompt.themeLabel}: ${prompt.text}${alternateLine}`,+ priority: PRIORITY_LEVELS.LOW,+ link: `/digital-twin/autobiography?prompt=${prompt.id}`,+ metadata: {+ promptId: prompt.id,+ themeId: prompt.themeId,+ suggestions: suggestions.map(p => ({ id: p.id, themeId: p.themeId, themeLabel: p.themeLabel, text: p.text }))+ }+ });++ // checkAndPrompt already read the config inside this same queue task, so it+ // hands it down rather than paying for a second read of a file nothing else+ // can have touched in between.+ const config = loadedConfig || await loadConfig();+ config.lastPromptAt = new Date().toISOString();+ config.lastPromptId = prompt.id;+ await saveConfig(config);++ console.log(`📖 Autobiography prompt sent: ${prompt.themeLabel} - ${prompt.text.substring(0, 50)}... (+${alternates.length} more ideas)`);++ return { prompted: true, prompt, suggestions };+}+/*** Check if a new story prompt is due and create a notification if so.* Called by the autonomous job system or can be triggered manually.@@ -656,35 +850,66 @@ export async function checkAndPrompt() {return { prompted: false, reason: 'not_due' };}- // Check if there's already an unread autobiography notification- const alreadyNotified = await notificationExists(- NOTIFICATION_TYPES.AUTOBIOGRAPHY_PROMPT- );+ return sendStoryPromptUnqueued(config);+ });+}- if (alreadyNotified) {- return { prompted: false, reason: 'pending_notification' };- }+/**+ * Score a story against the storytelling rubric in lib/storytellingCraft.js —+ * the seven moves plus CART — and persist the result on the story.+ *+ * Explicitly user-triggered (a button, or the evaluate route): this is the one+ * provider call the autobiography feature makes outside follow-ups and weaving,+ * and nothing schedules it.+ */+export async function evaluateStory(storyId, providerId) {+ const data = await loadStories();+ const story = data.stories.find(s => s.id === storyId);+ if (!story) return { error: 'Story not found' };- const prompt = await getNextPrompt();-- await addNotification({- type: NOTIFICATION_TYPES.AUTOBIOGRAPHY_PROMPT,- title: '5-Minute Story Time',- description: `${prompt.themeLabel}: ${prompt.text}`,- priority: 'low',- link: `/digital-twin/autobiography?prompt=${prompt.id}`,- metadata: {- promptId: prompt.id,- themeId: prompt.themeId- }- });+ const provider = providerId+ ? await getProviderById(providerId)+ : await getActiveProvider();+ if (!provider) return { error: 'No AI provider available' };++ const result = await callProviderAISimple(+ provider,+ provider.defaultModel,+ buildStoryCraftEvaluationPrompt({ question: story.promptText, story: story.content }),+ {+ // Low temperature: a rubric score the user will act on should be the same+ // answer twice, not a different reading each time they press the button.+ temperature: 0.2,+ max_tokens: 2000,+ op: 'autobiography-evaluate',+ opLabel: 'Scoring your story…'+ }+ );- config.lastPromptAt = new Date().toISOString();- config.lastPromptId = prompt.id;- await saveConfig(config);+ if (result.error) return { error: result.error };- console.log(`📖 Autobiography prompt sent: ${prompt.themeLabel} - ${prompt.text.substring(0, 50)}...`);+ let parsed;+ try { parsed = parseLLMJSON(result.text); } catch { /* invalid JSON */ }+ const evaluation = normalizeStoryCraftEvaluation(parsed);+ if (!evaluation) {+ return { error: 'Failed to parse the story evaluation from the AI response' };+ }+ evaluation.evaluatedAt = new Date().toISOString();- return { prompted: true, prompt };+ // Re-read inside the file queue so a story edit that landed while the+ // provider was running is preserved in the write-back.+ const stored = await queueAutobiographyStoriesWrite(async () => {+ const currentData = await loadStories();+ const currentStory = currentData.stories.find(s => s.id === storyId);+ if (!currentStory) return null;+ currentStory.evaluation = evaluation;+ await saveStories(currentData);+ return currentStory.evaluation;});++ if (!stored) return { error: 'Story not found' };++ console.log(`📖 Autobiography story scored: ${story.themeLabel} — ${stored.overallScore}/${stored.maxScore}`);++ return { evaluation: stored };}diff --git a/server/services/autobiography.test.js b/server/services/autobiography.test.jsindex b134a80a0f..6da4d59bb6 100644--- a/server/services/autobiography.test.js+++ b/server/services/autobiography.test.js@@ -18,6 +18,7 @@ const mockNotificationExists = vi.fn(() => false);vi.mock('./notifications.js', () => ({addNotification: (...args) => mockAddNotification(...args),NOTIFICATION_TYPES: { AUTOBIOGRAPHY_PROMPT: 'autobiography_prompt' },+ PRIORITY_LEVELS: { LOW: 'low', MEDIUM: 'medium', HIGH: 'high', CRITICAL: 'critical' },exists: (...args) => mockNotificationExists(...args)}));@@ -81,7 +82,13 @@ import {depthGuidanceForChain,generateFollowUps,getStoryChain,- weaveChainNarrative+ weaveChainNarrative,+ getPromptSuggestions,+ sendStoryPrompt,+ evaluateStory,+ autobiographyConfigEvents,+ PROMPT_SUGGESTION_COUNT,+ CUSTOM_PROMPT_ID} from './autobiography.js';// Helper: build stories data@@ -111,6 +118,18 @@ const setupMocks = (storiesData, configData) => {});};+// Capture what the service writes to stories.json (config writes are routed to+// the same mocked writeFile, so the discriminator lives here rather than in+// each test). `.value` stays null when nothing was written, which is itself+// the assertion in the "must not persist" cases.+const captureSavedStories = () => {+ const box = { value: null };+ writeFile.mockImplementation(async (filePath, content) => {+ if (!filePath.includes('config.json')) box.value = JSON.parse(content);+ });+ return box;+};+const setupPersistentMocks = (storiesData, configData) => {let storedStories = JSON.parse(JSON.stringify(storiesData));let storedConfig = JSON.parse(JSON.stringify(configData));@@ -133,14 +152,18 @@ const setupPersistentMocks = (storiesData, configData) => {};describe('Autobiography - getThemes', () => {- it('should return all 12 themes with prompt counts', () => {+ it('should return all 12 bank themes with prompt counts, plus the custom pseudo-theme', () => {const themes = getThemes();- expect(themes).toHaveLength(12);+ // 12 bank themes of 5 prompts each, then 'custom' — which has no bank+ // prompts by definition but needs a filter chip for the stories written+ // against a question the user typed themselves.+ expect(themes).toHaveLength(13);expect(themes[0]).toHaveProperty('id');expect(themes[0]).toHaveProperty('label');expect(themes[0]).toHaveProperty('promptCount');- expect(themes.every(t => t.promptCount === 5)).toBe(true);+ expect(themes.slice(0, 12).every(t => t.promptCount === 5)).toBe(true);+ expect(themes[12]).toEqual({ id: 'custom', label: 'Your Own Question', promptCount: 0 });});it('should include expected theme IDs', () => {@@ -638,16 +661,19 @@ describe('Autobiography - checkAndPrompt', () => {expect(result.reason).toBe('not_due');});- it('should return pending_notification when one already exists', async () => {+ // Regression: the cadence guard is the interval since `lastPromptAt`, NOT+ // "does a notification of this type already exist". `notifications.exists`+ // matches ANY notification of the type ever created, read or not — gating on+ // it silenced the daily prompt permanently after its very first nudge.+ it('prompts again on the next interval even though earlier prompts are still in the tray', async () => {mockNotificationExists.mockResolvedValue(true);const oldTime = new Date(Date.now() - 48 * 60 * 60 * 1000).toISOString(); // 48 hours agosetupMocks(makeStoriesData(), makeConfigData({ lastPromptAt: oldTime }));const result = await checkAndPrompt();- expect(result.prompted).toBe(false);- expect(result.reason).toBe('pending_notification');- expect(mockNotificationExists).toHaveBeenCalledWith('autobiography_prompt');+ expect(result.prompted).toBe(true);+ expect(mockAddNotification).toHaveBeenCalledTimes(1);});it('should create notification when prompt is due', async () => {@@ -899,3 +925,236 @@ describe('Autobiography - weaveChainNarrative', () => {expect(result.error).toMatch(/empty narrative/);});});++// =============================================================================+// STORY IDEAS, OWN QUESTIONS, THE DAILY PROMPT, AND CRAFT EVALUATION+// =============================================================================++describe('Autobiography - getPromptSuggestions', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ writeFile.mockImplementation(async () => {});+ });++ it('offers a menu of ideas drawn from DISTINCT themes', async () => {+ setupMocks(makeStoriesData(), makeConfigData());++ const suggestions = await getPromptSuggestions();++ expect(suggestions).toHaveLength(PROMPT_SUGGESTION_COUNT);+ const themeIds = suggestions.map(p => p.themeId);+ expect(new Set(themeIds).size).toBe(themeIds.length);+ });++ it('never re-offers a prompt already written against', async () => {+ const allButThree = getThemes()+ .filter(t => t.promptCount > 0)+ .flatMap(t => Array.from({ length: t.promptCount }, (_, i) => `${t.id}-${i}`))+ .slice(0, -3);+ setupMocks(makeStoriesData({ usedPrompts: allButThree }), makeConfigData());++ const suggestions = await getPromptSuggestions();++ expect(suggestions).toHaveLength(3);+ for (const prompt of suggestions) {+ expect(allButThree).not.toContain(prompt.id);+ }+ });+});++describe('Autobiography - stories answering your own question', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ writeFile.mockImplementation(async () => {});+ });++ it('files a custom-question story under the custom theme with the question as its promptText', async () => {+ setupMocks(makeStoriesData(), makeConfigData());++ const story = await saveStory({+ promptId: CUSTOM_PROMPT_ID,+ content: 'It started at my grandmother’s kitchen table.',+ customPromptText: 'Why do I like black licorice?'+ });++ expect(story.themeId).toBe('custom');+ expect(story.themeLabel).toBe('Your Own Question');+ expect(story.promptText).toBe('Why do I like black licorice?');+ });++ it('does not burn a bank slot on the custom sentinel', async () => {+ const savedStories = captureSavedStories();+ setupMocks(makeStoriesData(), makeConfigData());++ await saveStory({+ promptId: CUSTOM_PROMPT_ID,+ content: 'A story.',+ customPromptText: 'Why do I like black licorice?'+ });++ // 'custom' in usedPrompts would occupy a slot no bank prompt can match,+ // delaying the bank's cycle reset forever.+ expect(savedStories.value.usedPrompts).not.toContain(CUSTOM_PROMPT_ID);+ });+});++describe('Autobiography - sendStoryPrompt', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockAddNotification.mockResolvedValue({});+ mockNotificationExists.mockResolvedValue(false);+ writeFile.mockImplementation(async () => {});+ });++ it('carries the whole menu of ideas, not just the one it leads with', async () => {+ setupMocks(makeStoriesData(), makeConfigData());++ const result = await sendStoryPrompt();++ expect(result.prompted).toBe(true);+ expect(result.suggestions).toHaveLength(PROMPT_SUGGESTION_COUNT);+ const notification = mockAddNotification.mock.calls[0][0];+ expect(notification.metadata.suggestions).toHaveLength(PROMPT_SUGGESTION_COUNT);+ // The alternates are visible in the description too — a notification the+ // user reads without opening the app should still offer the choice.+ expect(notification.description).toContain(result.suggestions[1].text);+ });++ // sendStoryPrompt has no cadence guard of its own by design — each caller+ // owns one appropriate to it (the job's interval, the cron's local-day+ // check). Pinned because the removed `exists(type)` guard was permanent, not+ // per-day, and reinstating it here would silence the reminder for good.+ it('sends regardless of how many earlier prompts are still in the tray', async () => {+ mockNotificationExists.mockResolvedValue(true);+ setupMocks(makeStoriesData(), makeConfigData());++ const result = await sendStoryPrompt();++ expect(result.prompted).toBe(true);+ expect(mockAddNotification).toHaveBeenCalledTimes(1);+ });+});++describe('Autobiography - config reminder slice', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ writeFile.mockImplementation(async () => {});+ });++ it('defaults the reminder to off at 09:00 on a config saved before it existed', async () => {+ setupMocks(makeStoriesData(), makeConfigData());++ const config = await getConfig();++ expect(config.reminder).toEqual({ enabled: false, time: '09:00' });+ });++ it('keeps the saved time when a patch only flips enabled, and stamps updatedAt', async () => {+ setupMocks(makeStoriesData(), makeConfigData({ reminder: { enabled: false, time: '07:30' } }));++ const config = await updateConfig({ reminder: { enabled: true } });++ expect(config.reminder.time).toBe('07:30');+ expect(config.reminder.enabled).toBe(true);+ // The scheduler's catch-up refuses to replay a slot older than this.+ expect(new Date(config.reminder.updatedAt).toISOString()).toBe(config.reminder.updatedAt);+ });++ it('announces the save so the scheduler can re-register without a route hook', async () => {+ setupMocks(makeStoriesData(), makeConfigData());+ const seen = [];+ const listener = (payload) => seen.push(payload);+ autobiographyConfigEvents.on('autobiography-config:updated', listener);++ await updateConfig({ reminder: { time: '06:15' } });+ autobiographyConfigEvents.off('autobiography-config:updated', listener);++ expect(seen).toHaveLength(1);+ expect(seen[0].updates.reminder).toEqual({ time: '06:15' });+ expect(seen[0].config.reminder.time).toBe('06:15');+ });+});++describe('Autobiography - evaluateStory', () => {+ const storyFixture = makeStoriesData({+ stories: [{+ id: 's1',+ promptId: 'custom',+ themeId: 'custom',+ themeLabel: 'Your Own Question',+ promptText: 'Why do I like black licorice?',+ content: 'It started at my grandmother’s kitchen table.',+ wordCount: 7,+ createdAt: '2026-09-01T00:00:00.000Z'+ }]+ });++ const wellFormedAnswer = JSON.stringify({+ moves: {+ curiosity: { score: 4, evidence: 'opens on a question', suggestion: 'hold the answer one beat longer' },+ tension: { score: 3, evidence: '', suggestion: 'raise the stakes' },+ specificity: { score: 5, evidence: 'the kitchen table', suggestion: 'keep it' },+ pace: { score: 3, evidence: '', suggestion: 'slow the tasting' },+ unexpected: { score: 2, evidence: '', suggestion: 'add a turn' },+ personal: { score: 4, evidence: 'grandmother', suggestion: 'name the room' },+ takeaway: { score: 1, evidence: '', suggestion: 'say what it meant' }+ },+ cart: {+ context: { present: true, note: 'kitchen table' },+ action: { present: true, note: 'the first taste' },+ result: { present: true, note: '' },+ takeaway: { present: false, note: 'missing' }+ },+ answersQuestion: true,+ revision: 'End on what the taste stands in for.'+ });++ beforeEach(() => {+ vi.clearAllMocks();+ writeFile.mockImplementation(async () => {});+ mockGetActiveProvider.mockResolvedValue({ id: 'p1', defaultModel: 'm1' });+ mockCallProviderAISimple.mockResolvedValue({ text: wellFormedAnswer });+ });++ it('scores the story and persists the evaluation on it', async () => {+ const savedStories = captureSavedStories();+ setupMocks(storyFixture, makeConfigData());++ const result = await evaluateStory('s1');++ expect(result.evaluation.overallScore).toBe(3.1); // 22/7 = 3.14…+ expect(result.evaluation.moves).toHaveLength(7);+ expect(result.evaluation.weakestMoveId).toBe('takeaway');+ expect(savedStories.value.stories[0].evaluation.overallScore).toBe(3.1);+ });++ it('sends the story and its question to the provider', async () => {+ setupMocks(storyFixture, makeConfigData());++ await evaluateStory('s1');++ const prompt = mockCallProviderAISimple.mock.calls[0][2];+ expect(prompt).toContain('Why do I like black licorice?');+ expect(prompt).toContain('It started at my grandmother’s kitchen table.');+ });++ it('reports an unparseable answer instead of persisting an all-zero score', async () => {+ const savedStories = captureSavedStories();+ setupMocks(storyFixture, makeConfigData());+ mockCallProviderAISimple.mockResolvedValue({ text: 'Sure! Here is my feedback…' });++ const result = await evaluateStory('s1');++ expect(result.error).toMatch(/parse/i);+ expect(savedStories.value).toBeNull();+ });++ it('errors for an unknown story and when no provider is configured', async () => {+ setupMocks(storyFixture, makeConfigData());++ expect((await evaluateStory('nope')).error).toMatch(/not found/i);++ mockGetActiveProvider.mockResolvedValue(null);+ expect((await evaluateStory('s1')).error).toMatch(/provider/i);+ });+});diff --git a/server/services/autobiography.tombstone.test.js b/server/services/autobiography.tombstone.test.jsindex 425ede8dc4..fb15bbdb09 100644--- a/server/services/autobiography.tombstone.test.js+++ b/server/services/autobiography.tombstone.test.js@@ -28,6 +28,7 @@ vi.mock('../lib/fileUtils.js', async () => {vi.mock('./notifications.js', () => ({addNotification: vi.fn(),NOTIFICATION_TYPES: { AUTOBIOGRAPHY_PROMPT: 'autobiography_prompt' },+ PRIORITY_LEVELS: { LOW: 'low', MEDIUM: 'medium', HIGH: 'high', CRITICAL: 'critical' },exists: vi.fn(() => false),}));diff --git a/server/services/autobiographyReminder.js b/server/services/autobiographyReminder.jsnew file mode 100644index 0000000000..f9092746ee--- /dev/null+++ b/server/services/autobiographyReminder.js@@ -0,0 +1,49 @@+/**+ * Autobiography Daily Story Prompt Scheduler+ *+ * Optional, opt-in (default OFF) scheduled nudge: at a user-chosen time of day+ * it sends a single in-app notification offering a few story ideas, unless the+ * user already wrote a story today. Deterministic — the ideas come from the+ * on-disk prompt bank and nothing here calls an AI provider, so it is safe on a+ * cold install; the storytelling-craft evaluation is a separate, explicitly+ * user-triggered button.+ *+ * All the scheduling machinery — cron registration, the feature gate, the+ * fire-time re-read, the day-scoped duplicate guard, the missed-slot catch-up+ * and its `updatedAt` floors, the timezone reconcile — lives in+ * dailyReminderScheduler.js. This module is the two things that are actually+ * specific to autobiography: what "already handled today" means (a story was+ * written) and what the nudge is.+ */++import { createDailyReminderScheduler } from './dailyReminderScheduler.js';+import { isLocalDay } from '../lib/timezone.js';+import { NOTIFICATION_TYPES } from './notifications.js';+import { getConfig, getStories, sendStoryPrompt, autobiographyConfigEvents } from './autobiography.js';++export const AUTOBIOGRAPHY_REMINDER_EVENT_ID = 'autobiography-daily-prompt';++const scheduler = createDailyReminderScheduler({+ id: AUTOBIOGRAPHY_REMINDER_EVENT_ID,+ logPrefix: '📖 Autobiography reminder',+ featureId: 'autobiography',+ notificationType: NOTIFICATION_TYPES.AUTOBIOGRAPHY_PROMPT,+ readReminderSlice: async () => (await getConfig()).reminder,+ // Story `createdAt` is a precise UTC instant, so the local day comes straight+ // from it rather than from any coarser bucket.+ alreadyHandledToday: async ({ timezone, todayStr }) => {+ const stories = await getStories();+ return stories.some(s => isLocalDay(s?.createdAt, timezone, todayStr));+ },+ notify: async () => {+ const result = await sendStoryPrompt();+ if (!result.prompted) {+ console.log(`📖 Autobiography reminder: no nudge (${result.reason})`);+ }+ },+ configEvents: { emitter: autobiographyConfigEvents, event: 'autobiography-config:updated' }+});++export const fireStoryPromptIfNoStoryToday = scheduler.fire;+export const registerAutobiographyReminderSchedule = scheduler.register;+export const stopAutobiographyReminderSchedule = scheduler.stop;diff --git a/server/services/autobiographyReminder.test.js b/server/services/autobiographyReminder.test.jsnew file mode 100644index 0000000000..f5e0710218--- /dev/null+++ b/server/services/autobiographyReminder.test.js@@ -0,0 +1,142 @@+/**+ * Tests for the autobiography story prompt's own contract. The scheduling+ * machinery — registration gates, catch-up floors, day-scoped de-dupe,+ * reconcile — is shared and covered once in dailyReminderScheduler.test.js;+ * what's left here is what only this reminder decides: that "already handled+ * today" means a story was written on the user's LOCAL calendar day, and that+ * the nudge is the shared story-prompt sender.+ *+ * The timezone helpers are deliberately real — the UTC-instant-to-local-day+ * derivation is the thing under test.+ */++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++const settingsEventEmitter = vi.hoisted(() => ({ on() {}, emit() {} }));+const configEventEmitter = vi.hoisted(() => {+ const listeners = {};+ return {+ on(event, fn) { (listeners[event] ||= []).push(fn); },+ emit(event, ...args) { (listeners[event] || []).forEach(fn => fn(...args)); },+ };+});++vi.mock('./eventScheduler.js', () => ({+ schedule: vi.fn(),+ cancel: vi.fn(),+ parseCronToPrevRun: vi.fn()+}));+vi.mock('./userTimezone.js', () => ({+ getUserTimezone: vi.fn().mockResolvedValue('UTC'),+ getTimezoneUpdatedAt: vi.fn().mockResolvedValue(null),+}));+vi.mock('./autobiography.js', () => ({+ getConfig: vi.fn(),+ getStories: vi.fn(),+ sendStoryPrompt: vi.fn(),+ autobiographyConfigEvents: configEventEmitter+}));+vi.mock('./instanceFeatures.js', () => ({+ isInstanceFeatureEnabled: vi.fn().mockResolvedValue(true),+}));+vi.mock('./notifications.js', () => ({+ getNotifications: vi.fn().mockResolvedValue([]),+ NOTIFICATION_TYPES: { AUTOBIOGRAPHY_PROMPT: 'autobiography_prompt' }+}));+vi.mock('./settings.js', () => ({ settingsEvents: settingsEventEmitter }));++const { schedule, cancel } = await import('./eventScheduler.js');+const { getUserTimezone } = await import('./userTimezone.js');+const { getConfig, getStories, sendStoryPrompt } = await import('./autobiography.js');+const { isInstanceFeatureEnabled } = await import('./instanceFeatures.js');+const { getNotifications } = await import('./notifications.js');+const {+ registerAutobiographyReminderSchedule,+ fireStoryPromptIfNoStoryToday,+ stopAutobiographyReminderSchedule,+ AUTOBIOGRAPHY_REMINDER_EVENT_ID+} = await import('./autobiographyReminder.js');++beforeEach(() => {+ stopAutobiographyReminderSchedule();+ vi.clearAllMocks();+ vi.useFakeTimers({ now: new Date('2026-07-01T12:00:00.000Z'), toFake: ['Date'] });+ isInstanceFeatureEnabled.mockResolvedValue(true);+ getUserTimezone.mockResolvedValue('UTC');+ getNotifications.mockResolvedValue([]);+ getStories.mockResolvedValue([]);+ sendStoryPrompt.mockResolvedValue({ prompted: true, prompt: { id: 'childhood-0' } });+ getConfig.mockResolvedValue({ enabled: false, intervalHours: 24, reminder: { enabled: true, time: '09:00' } });+});++afterEach(() => {+ vi.useRealTimers();+});++describe('fireStoryPromptIfNoStoryToday', () => {+ it('sends the story prompt when nothing was written today', async () => {+ getStories.mockResolvedValue([{ createdAt: '2026-06-20T12:00:00.000Z' }]);++ await fireStoryPromptIfNoStoryToday();++ expect(sendStoryPrompt).toHaveBeenCalledTimes(1);+ });++ it('stays silent when a story was already written today', async () => {+ getStories.mockResolvedValue([{ createdAt: '2026-07-01T08:00:00.000Z' }]);++ await fireStoryPromptIfNoStoryToday();++ expect(sendStoryPrompt).not.toHaveBeenCalled();+ });++ it('ignores a story missing createdAt rather than crashing', async () => {+ getStories.mockResolvedValue([{ id: 's1' }]);++ await fireStoryPromptIfNoStoryToday();++ expect(sendStoryPrompt).toHaveBeenCalledTimes(1);+ });++ // Regression: "written today" is the user's LOCAL day. Now is 05:00 on July 1+ // in Los Angeles; a story stamped 2026-07-01T04:00Z was written at 21:00 on+ // JUNE 30 there — yesterday — so today's prompt must still go out. Comparing+ // raw UTC dates would see two 2026-07-01 stamps and skip it every morning in+ // the Americas.+ it('judges "written today" by the local calendar day, not the UTC one', async () => {+ getUserTimezone.mockResolvedValue('America/Los_Angeles');+ getStories.mockResolvedValue([{ createdAt: '2026-07-01T04:00:00.000Z' }]);++ await fireStoryPromptIfNoStoryToday();++ expect(sendStoryPrompt).toHaveBeenCalledTimes(1);+ });+});++describe('registerAutobiographyReminderSchedule', () => {+ it('registers under the autobiography reminder id at the configured time', async () => {+ await registerAutobiographyReminderSchedule();++ expect(schedule.mock.calls[0][0]).toMatchObject({+ id: AUTOBIOGRAPHY_REMINDER_EVENT_ID, cron: '0 9 * * *', timezone: 'UTC'+ });+ });++ it('stays silent on an install where the autobiography feature is off', async () => {+ isInstanceFeatureEnabled.mockResolvedValue(false);++ await registerAutobiographyReminderSchedule();++ expect(isInstanceFeatureEnabled).toHaveBeenCalledWith('autobiography');+ expect(schedule).not.toHaveBeenCalled();+ expect(cancel).toHaveBeenCalledWith(AUTOBIOGRAPHY_REMINDER_EVENT_ID);+ });++ it('reschedules when updateConfig saves a reminder change', async () => {+ configEventEmitter.emit('autobiography-config:updated', {+ updates: { reminder: { time: '07:30' } }+ });++ await vi.waitFor(() => expect(schedule).toHaveBeenCalledTimes(1));+ });+});diff --git a/server/services/autonomousJobs/defaults.js b/server/services/autonomousJobs/defaults.jsindex e400030b08..2c210b8cbb 100644--- a/server/services/autonomousJobs/defaults.js+++ b/server/services/autonomousJobs/defaults.js@@ -194,7 +194,7 @@ Phase 4 — Report:{id: 'job-autobiography-prompt',name: 'Autobiography Story Prompt',- description: 'Send a notification prompting the user to write a 5-minute autobiographical story based on a thematic prompt.',+ description: 'Send a notification offering a few 5-minute autobiographical story ideas drawn from the thematic prompt bank. Interval-based; the time-of-day version lives in the Autobiography tab\'s own reminder setting, and both share one notification so enabling both cannot double-nudge.',category: 'autobiography-prompt',interval: 'daily',intervalMs: DAY,diff --git a/server/services/bootstrap.js b/server/services/bootstrap.jsindex b0957e19e4..5f719e2f1d 100644--- a/server/services/bootstrap.js+++ b/server/services/bootstrap.js@@ -114,6 +114,7 @@ import { startBeeperAttachmentGc } from './beeperAttachmentGc.js';import { initBridge as initBrainMemoryBridge } from './brainMemoryBridge.js';import { initDrillCache } from './meatspacePostDrillCache.js';import { registerPostReminderSchedule } from './meatspacePostReminder.js';+import { registerAutobiographyReminderSchedule } from './autobiographyReminder.js';import { recoverInterruptedRepoClones, recoverStuckClassifications } from './brain.js';import { recoverStuckAnalyses } from './writersRoom/evaluator.js';import { recoverStuckAutoRuns } from './pipeline/autoRunner.js';@@ -440,6 +441,10 @@ const startBackgroundServices = ({ spawnerReady, io }) => {// was down (or during a redeploy) still fires once we're back up, instead of// silently waiting for tomorrow's tick (#2015).registerPostReminderSchedule({ catchUpMissedSlot: true }).catch(err => logBootstrapFailure('❌ POST reminder init failed', err));+ // Register the optional daily autobiography story prompt (opt-in, off by+ // default, and only when the instance feature is on) — deterministic prompt+ // bank, no LLM calls. Same catch-up rationale as the POST reminder above.+ registerAutobiographyReminderSchedule({ catchUpMissedSlot: true }).catch(err => logBootstrapFailure('❌ Autobiography reminder init failed', err));// Initialize backup scheduler for daily data backupsstartBackupScheduler().catch(err => logBootstrapFailure('❌ Backup scheduler init failed', err));// Automatic PortOS self-update — OFF by default. When the user turns it ondiff --git a/server/services/digital-twin-sync.js b/server/services/digital-twin-sync.jsindex cc0dc9ec52..88dbda4eaa 100644--- a/server/services/digital-twin-sync.js+++ b/server/services/digital-twin-sync.js@@ -766,9 +766,10 @@ export async function getDigitalTwinSnapshot() {// re-materialized whenever the dir fingerprint changes (every sync cycle on a// checksum-cache miss), so the parallelism is worth it.// autobiography/config.json (the prompt schedule: enabled, intervalHours,- // lastPromptAt) is deliberately NOT in the snapshot — it is machine-local- // scheduling state, and a fresh peer must not inherit another machine's- // cadence or have prompts enabled without local opt-in. Only the stories sync.+ // lastPromptAt, and the daily reminder's enabled/time) is deliberately NOT in+ // the snapshot — it is machine-local scheduling state, and a fresh peer must+ // not inherit another machine's cadence, wake-up time, or have prompts+ // enabled without local opt-in. Only the stories sync.const [identity, chronotype, longevity, feedback, taste, tasteObserved, chronotypeObserved, meta, documents, stories, socialAccounts] =await Promise.all([readJSONFile(IDENTITY_FILE, null, { strict: true }),diff --git a/server/services/instanceFeatures.test.js b/server/services/instanceFeatures.test.jsindex 9bf5214534..8468f31687 100644--- a/server/services/instanceFeatures.test.js+++ b/server/services/instanceFeatures.test.js@@ -307,7 +307,7 @@ describe('instance features', () => {const { features } = await getInstanceFeatures();expect(Object.fromEntries(features.map((f) => [f.id, f.enabled]))).toEqual({- post: true, datadog: true, jira: false, eidoverse: false, gsd: false, openclaw: false, health: true,+ post: true, autobiography: true, datadog: true, jira: false, eidoverse: false, gsd: false, openclaw: false, health: true,rigging: false, facetime: false, imessage: true, signal: true, x: true, 'stacker-news': true, beeper: false,});});diff --git a/server/services/jobGates.js b/server/services/jobGates.jsindex cf5d2fe9dc..78ddb3cd62 100644--- a/server/services/jobGates.js+++ b/server/services/jobGates.js@@ -61,9 +61,24 @@ async function goalCheckInGate() {return { shouldRun: false, reason: 'No active goals with target dates' };}+/**+ * Autobiography gate: the story prompt is an optional per-install feature, so+ * the job stays silent on an install where the user turned it off — the job's+ * own `enabled` flag governs the cadence, the feature flag governs whether the+ * feature exists here at all.+ */+async function autobiographyPromptGate() {+ const { isInstanceFeatureEnabled } = await import('./instanceFeatures.js');+ if (await isInstanceFeatureEnabled('autobiography')) {+ return { shouldRun: true, reason: 'Autobiography feature enabled' };+ }+ return { shouldRun: false, reason: 'Autobiography feature disabled on this instance' };+}+const GATES = Object.assign(Object.create(null), {'job-brain-review': brainReviewGate,- 'job-goal-check-in': goalCheckInGate+ 'job-goal-check-in': goalCheckInGate,+ 'job-autobiography-prompt': autobiographyPromptGate});/**