Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix a queued config write that could erase the autobiography reminder settings

[._.]/ Adam Eivy5c6c67a463c6
diff --git a/server/lib/README.md b/server/lib/README.md
index f19a2eec83..db3d155095 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -145,7 +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. |
+| `storytellingCraft.js` | The storytelling rubric the autobiography feature scores a story against — pure (no I/O, no clock, no provider call): `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. |
diff --git a/server/lib/storytellingCraft.js b/server/lib/storytellingCraft.js
index 97599b637d..1814accbd2 100644
--- a/server/lib/storytellingCraft.js
+++ b/server/lib/storytellingCraft.js
@@ -161,10 +161,16 @@ Return ONLY JSON, no prose or markdown fences, in exactly this shape:
export function normalizeStoryCraftEvaluation(parsed) {
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
- const rawMoves = (parsed.moves && typeof parsed.moves === 'object') ? parsed.moves : {};
+ // One definition of "the model did not give me this entry", so the move and
+ // CART blocks below cannot drift on what missing means.
+ const entryOf = (container, id) => {
+ const bag = (container && typeof container === 'object') ? container : {};
+ const entry = bag[id];
+ return (entry && typeof entry === 'object') ? entry : {};
+ };
+
const moves = STORY_CRAFT_MOVES.map((move) => {
- const entry = rawMoves[move.id];
- const source = (entry && typeof entry === 'object') ? entry : {};
+ const source = entryOf(parsed.moves, move.id);
return {
id: move.id,
label: move.label,
@@ -174,10 +180,8 @@ export function normalizeStoryCraftEvaluation(parsed) {
};
});
- 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 : {};
+ const source = entryOf(parsed.cart, stage.id);
return {
id: stage.id,
label: stage.label,
@@ -189,20 +193,21 @@ export function normalizeStoryCraftEvaluation(parsed) {
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]);
-
+ // No strongest/weakest fields: they are derivable from `moves` at the point
+ // of display, and this object is persisted into every story on every install
+ // that presses the button — a derived field shipped once is a compatibility
+ // surface you keep writing forever.
return {
moves,
cart,
overallScore,
maxScore: STORY_CRAFT_MAX_SCORE,
- strongestMoveId: strongest.id,
- weakestMoveId: weakest.id,
- answersQuestion: parsed.answersQuestion !== false,
+ // Tri-state, for the same reason a missing move scores 0: an ABSENT
+ // judgement is "not assessed", which is neither a pass nor an accusation.
+ // `!== false` claimed the story answered its question on a truncated
+ // response; a bare `=== true` would accuse it of not answering. `null` lets
+ // the UI show the warning only on an explicit false.
+ answersQuestion: typeof parsed.answersQuestion === 'boolean' ? parsed.answersQuestion : null,
revision: cleanText(parsed.revision, MAX_REVISION),
};
}
diff --git a/server/lib/storytellingCraft.test.js b/server/lib/storytellingCraft.test.js
index 9fe45622dc..b34ad49100 100644
--- a/server/lib/storytellingCraft.test.js
+++ b/server/lib/storytellingCraft.test.js
@@ -108,14 +108,18 @@ describe('normalizeStoryCraftEvaluation', () => {
expect(result.maxScore).toBe(STORY_CRAFT_MAX_SCORE);
});
- it('names the strongest and weakest move, breaking ties in rubric order', () => {
+ it('persists only what the UI reads — no derived strongest/weakest fields', () => {
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]);
+ // This object is written into every story, so a derived field shipped once
+ // becomes a compatibility surface. "Your weakest move" is one reduce over
+ // `moves` at the point of display.
+ expect(Object.keys(result).sort()).toEqual(
+ ['answersQuestion', 'cart', 'maxScore', 'moves', 'overallScore', 'revision']
+ );
});
- it('trims prose and defaults answersQuestion to true when the model omits it', () => {
+ it('trims prose, and reports an omitted answersQuestion as not assessed', () => {
const answer = fullAnswer([3, 3, 3, 3, 3, 3, 3]);
delete answer.answersQuestion;
@@ -123,7 +127,14 @@ describe('normalizeStoryCraftEvaluation', () => {
expect(result.revision).toBe('tighten the opening');
expect(result.moves[0].evidence).toBe(`evidence ${STORY_CRAFT_MOVE_IDS[0]}`);
- expect(result.answersQuestion).toBe(true);
+ // null, not true: a truncated response must not CLAIM the story answered
+ // its question, and must not ACCUSE it of failing to either. The UI shows
+ // its warning only on an explicit false.
+ expect(result.answersQuestion).toBeNull();
+ });
+
+ it('carries an explicit answersQuestion:true through', () => {
+ expect(normalizeStoryCraftEvaluation(fullAnswer([3, 3, 3, 3, 3, 3, 3])).answersQuestion).toBe(true);
});
it('carries an explicit answersQuestion:false through', () => {
diff --git a/server/services/autobiography.js b/server/services/autobiography.js
index 6d1e4977a6..6229437798 100644
--- a/server/services/autobiography.js
+++ b/server/services/autobiography.js
@@ -388,21 +388,32 @@ export async function saveStory({ promptId, content, parentStoryId, customPrompt
const 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));
+ // Resolve which of the three origins owns this story's theme ONCE, as an
+ // explicit {themeId, themeLabel} pair, 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.
+ //
+ // Each branch names the fields it reads rather than falling back to a
+ // generic `.id`/`.label`: a parent story's `.id` is a story UUID, so a
+ // generic fallback would stamp a UUID as a themeId on any parent whose own
+ // theme is missing (a peer-synced or hand-edited record), producing a
+ // byTheme bucket no filter chip can reach.
+ const theme = isFollowUp
+ ? { themeId: parentStory?.themeId || 'unknown', themeLabel: parentStory?.themeLabel || 'Unknown' }
+ : prompt
+ ? { themeId: prompt.themeId, themeLabel: prompt.themeLabel }
+ : customPromptText
+ ? { themeId: CUSTOM_THEME.id, themeLabel: CUSTOM_THEME.label }
+ : { themeId: 'unknown', themeLabel: 'Unknown' };
const story = {
id: uuidv4(),
promptId: isFollowUp ? `followup-${parentStoryId}` : promptId,
- themeId: themeSource?.themeId ?? themeSource?.id ?? 'unknown',
- themeLabel: themeSource?.themeLabel ?? themeSource?.label ?? 'Unknown',
+ themeId: theme.themeId,
+ themeLabel: theme.themeLabel,
promptText: customPromptText || prompt?.text || '',
content,
wordCount: countWords(content),
@@ -782,7 +793,14 @@ Rules:
* would silence the daily prompt permanently after its very first nudge.
*/
export async function sendStoryPrompt() {
- return queueAutobiographyConfigWrite(sendStoryPromptUnqueued);
+ // The arrow is load-bearing: createFileWriteQueue runs a task as
+ // `tail.then(fn, fn)`, so a bare function reference is invoked with the
+ // PREVIOUS queued task's resolved value. Passing `sendStoryPromptUnqueued`
+ // directly handed that value in as `loadedConfig` — e.g. checkAndPrompt's
+ // `{ prompted: false, reason: 'not_due' }` — and saveConfig then wrote it
+ // over config.json, silently erasing `enabled`, `intervalHours` and the whole
+ // `reminder` slice (which reads back as the defaults, turning the reminder off).
+ return queueAutobiographyConfigWrite(() => sendStoryPromptUnqueued());
}
/**
diff --git a/server/services/autobiography.test.js b/server/services/autobiography.test.js
index 6da4d59bb6..e9f675d695 100644
--- a/server/services/autobiography.test.js
+++ b/server/services/autobiography.test.js
@@ -1124,7 +1124,7 @@ describe('Autobiography - evaluateStory', () => {
expect(result.evaluation.overallScore).toBe(3.1); // 22/7 = 3.14…
expect(result.evaluation.moves).toHaveLength(7);
- expect(result.evaluation.weakestMoveId).toBe('takeaway');
+ expect(result.evaluation.moves.find(m => m.id === 'takeaway').score).toBe(1);
expect(savedStories.value.stories[0].evaluation.overallScore).toBe(3.1);
});
@@ -1158,3 +1158,83 @@ describe('Autobiography - evaluateStory', () => {
expect((await evaluateStory('s1')).error).toMatch(/provider/i);
});
});
+
+describe('Autobiography - config write-queue task shape', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockAddNotification.mockResolvedValue({});
+ mockNotificationExists.mockResolvedValue(false);
+ });
+
+ // Regression: createFileWriteQueue runs a task as `tail.then(fn, fn)`, so a
+ // task passed BY REFERENCE is invoked with the previous task's resolved
+ // value. sendStoryPrompt used to hand `sendStoryPromptUnqueued` over bare,
+ // which received e.g. checkAndPrompt's `{prompted:false, reason:'not_due'}`
+ // as its config and wrote THAT over config.json — erasing enabled,
+ // intervalHours and the whole reminder slice, which reads back as defaults
+ // and silently turns the daily reminder off.
+ it('never writes a previous queued result over the config file', async () => {
+ const saved = [];
+ writeFile.mockImplementation(async (filePath, content) => {
+ if (filePath.includes('config.json')) saved.push(JSON.parse(content));
+ });
+ setupMocks(makeStoriesData(), makeConfigData({
+ lastPromptAt: new Date(Date.now() - 48 * 60 * 60 * 1000).toISOString(),
+ reminder: { enabled: true, time: '07:30' }
+ }));
+
+ // Two tasks on the same tail: the second is handed the first's return value.
+ await Promise.all([checkAndPrompt(), sendStoryPrompt()]);
+
+ expect(saved.length).toBeGreaterThan(0);
+ for (const config of saved) {
+ expect(config.reminder).toEqual({ enabled: true, time: '07:30' });
+ expect(config.intervalHours).toBe(24);
+ expect(config).not.toHaveProperty('prompted');
+ expect(config).not.toHaveProperty('reason');
+ }
+ });
+});
+
+describe('Autobiography - follow-up theme inheritance', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ writeFile.mockImplementation(async () => {});
+ });
+
+ // Regression: resolving the theme through a generic `.id` fallback stamped
+ // the PARENT STORY's UUID as the follow-up's themeId whenever the parent
+ // carried no theme of its own (a peer-synced or hand-edited record) — a
+ // byTheme bucket keyed on a UUID that no filter chip can ever reach.
+ it('files a follow-up under "unknown" when its parent has no theme, never the parent id', async () => {
+ setupMocks(makeStoriesData({
+ stories: [{ id: 'parent-uuid', content: 'x', createdAt: '2026-09-01T00:00:00.000Z' }]
+ }), makeConfigData());
+
+ const story = await saveStory({
+ promptId: 'ignored',
+ content: 'A follow-up.',
+ parentStoryId: 'parent-uuid',
+ customPromptText: 'What happened next?'
+ });
+
+ expect(story.themeId).toBe('unknown');
+ expect(story.themeLabel).toBe('Unknown');
+ });
+
+ it('inherits the parent theme when the parent has one', async () => {
+ setupMocks(makeStoriesData({
+ stories: [{ id: 'p2', themeId: 'childhood', themeLabel: 'Childhood', content: 'x', createdAt: '2026-09-01T00:00:00.000Z' }]
+ }), makeConfigData());
+
+ const story = await saveStory({
+ promptId: 'ignored',
+ content: 'A follow-up.',
+ parentStoryId: 'p2',
+ customPromptText: 'What happened next?'
+ });
+
+ expect(story.themeId).toBe('childhood');
+ expect(story.themeLabel).toBe('Childhood');
+ });
+});
diff --git a/server/services/autobiographyReminder.js b/server/services/autobiographyReminder.js
index f9092746ee..bf94e078a5 100644
--- a/server/services/autobiographyReminder.js
+++ b/server/services/autobiographyReminder.js
@@ -26,6 +26,7 @@ export const AUTOBIOGRAPHY_REMINDER_EVENT_ID = 'autobiography-daily-prompt';
const scheduler = createDailyReminderScheduler({
id: AUTOBIOGRAPHY_REMINDER_EVENT_ID,
logPrefix: '📖 Autobiography reminder',
+ source: 'autobiographyReminder',
featureId: 'autobiography',
notificationType: NOTIFICATION_TYPES.AUTOBIOGRAPHY_PROMPT,
readReminderSlice: async () => (await getConfig()).reminder,
diff --git a/server/services/dailyReminderScheduler.js b/server/services/dailyReminderScheduler.js
index e1c5c690e2..4fe2ae977a 100644
--- a/server/services/dailyReminderScheduler.js
+++ b/server/services/dailyReminderScheduler.js
@@ -45,6 +45,8 @@ function toMs(value) {
* @param {Object} spec
* @param {string} spec.id - eventScheduler registration id (also the cancel key)
* @param {string} spec.logPrefix - emoji-prefixed label for this reminder's logs
+ * @param {string} spec.source - `metadata.source` recorded on the scheduled event
+ * (the declaring module, which is what the scheduler's own error logs name)
* @param {string} spec.featureId - instance feature that gates the whole reminder
* @param {() => Promise<{enabled?: boolean, time?: string, updatedAt?: string}>} spec.readReminderSlice
* @param {string} spec.notificationType - type used for the day-scoped duplicate guard
@@ -56,6 +58,7 @@ function toMs(value) {
export function createDailyReminderScheduler({
id,
logPrefix,
+ source,
featureId,
readReminderSlice,
notificationType,
@@ -191,8 +194,12 @@ export function createDailyReminderScheduler({
}
const timezone = await getUserTimezone();
+ // Stamped AFTER the registration it describes: if `schedule` throws, the
+ // subscriptions catch and log, and a `lastAppliedTimezone` naming a zone
+ // that was never applied would make every later reconcile short-circuit —
+ // leaving the reminder unregistered until a zone change or a restart.
+ schedule({ id, type: 'cron', cron, timezone, handler: fire, metadata: { source } });
lastAppliedTimezone = timezone;
- schedule({ id, type: 'cron', cron, timezone, handler: fire, metadata: { source: id } });
console.log(`${logPrefix}: registered daily at ${time} (${timezone})`);
if (shouldCatchUp) {
diff --git a/server/services/meatspacePostReminder.js b/server/services/meatspacePostReminder.js
index ac2a9b17a0..93c3316fa8 100644
--- a/server/services/meatspacePostReminder.js
+++ b/server/services/meatspacePostReminder.js
@@ -23,6 +23,7 @@ export const POST_REMINDER_EVENT_ID = 'post-daily-reminder';
const scheduler = createDailyReminderScheduler({
id: POST_REMINDER_EVENT_ID,
logPrefix: '🔔 POST reminder',
+ source: 'meatspacePostReminder',
featureId: 'post',
notificationType: NOTIFICATION_TYPES.DAILY_POST_REMINDER,
readReminderSlice: async () => (await getPostConfig()).reminder,