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
refactor: break two import cycles and move upload I/O out of utils
[._.]/ Adam Eivy480601330b0d
diff --git a/client/src/lib/universeBuilderShared.js b/client/src/lib/universeBuilderShared.jsindex d01b11e4b4..23b7e8ba8f 100644--- a/client/src/lib/universeBuilderShared.js+++ b/client/src/lib/universeBuilderShared.js@@ -1,5 +1,8 @@import { Users, MapPin, Package } from 'lucide-react';-import { WORLD_CATEGORIES, WORLD_CATEGORY_KEY_MAX } from '../services/api';+// Imports direct from apiUniverseBuilder (NOT the global `services/api`+// barrel) — see universeBuilderExpand.js for why: tracing through the+// barrel pulls all ~40 service modules into this lib's dep graph.+import { WORLD_CATEGORIES, WORLD_CATEGORY_KEY_MAX } from '../services/apiUniverseBuilder';// Shared constants + pure category/trunk/composite helpers for the Universe// Builder page and its extracted tab/editor components (#2374). Kept free ofdiff --git a/client/src/services/README.md b/client/src/services/README.mdindex ee0c4a0196..7efbf3e8d7 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -93,7 +93,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire|---|---|| `apiImageVideo.js` | Image-gen local backend extras (gallery, models, LoRAs, cancel, delete). || `apiLoraTraining.js` | Character LoRA training — datasets (CRUD, upload, generate, slice, caption), training runs (start/list/cancel/delete + status), character→LoRA link lookup. |-| `apiMedia.js` | Screenshots + media assets. |+| `apiMedia.js` | Screenshots + media assets. Also owns the multi-file upload orchestration — `processScreenshotUploads` / `processAttachmentUploads` and their single-file variants (`uploadScreenshotFile` / `uploadAttachmentFile`) — moved from `utils/fileUpload.js` since they perform network I/O, not pure transforms. || `apiMediaJobs.js` | Media generation job tracking. || `apiCreativeDirector.js` | Creative Director (video production). || `apiCreativeCommission.js` | Creative Commissions (Autonomous Creation Engine — standing recurring briefs). |diff --git a/client/src/services/apiMedia.js b/client/src/services/apiMedia.jsindex 0fcba2632f..763193c43d 100644--- a/client/src/services/apiMedia.js+++ b/client/src/services/apiMedia.js@@ -1,4 +1,11 @@import { request, API_BASE, maybeRedirectToLogin } from './apiCore.js';+import { formatBytes } from '../utils/formatters.js';+import {+ validateImageFile,+ ALLOWED_ATTACHMENT_EXTENSIONS,+ SCREENSHOT_MAX_FILE_SIZE,+ ATTACHMENT_MAX_FILE_SIZE,+} from '../utils/fileUpload.js';// Screenshotsexport const uploadScreenshot = (base64Data, filename, mimeType) => request('/screenshots', {@@ -15,6 +22,227 @@ export const getAttachment = (filename) => request(`/attachments/${encodeURICompexport const deleteAttachment = (filename) => request(`/attachments/${encodeURIComponent(filename)}`, { method: 'DELETE' });export const listAttachments = () => request('/attachments');+/**+ * Upload a single screenshot file+ *+ * @param {File} file - File to upload+ * @param {Object} options - Upload options+ * @param {Function} options.onSuccess - Callback for successful upload+ * @param {Function} options.onError - Callback for errors+ * @returns {Promise<Object|null>} Uploaded file info or null on failure+ */+export async function uploadScreenshotFile(file, options = {}) {+ const { onSuccess, onError } = options;++ return new Promise((resolve) => {+ const reader = new FileReader();++ reader.onload = async (ev) => {+ const result = ev?.target?.result;+ if (typeof result !== 'string') {+ onError?.('Failed to read file: unexpected result type');+ resolve(null);+ return;+ }++ const parts = result.split(',');+ if (parts.length < 2) {+ onError?.('Failed to read file: invalid data URL format');+ resolve(null);+ return;+ }++ const base64 = parts[1];+ const uploaded = await uploadScreenshot(base64, file.name, file.type).catch((err) => {+ onError?.(`Failed to upload: ${err.message}`);+ return null;+ });++ if (uploaded) {+ const fileInfo = {+ id: uploaded.id,+ filename: uploaded.filename,+ preview: result,+ path: uploaded.path+ };+ onSuccess?.(fileInfo);+ resolve(fileInfo);+ } else {+ resolve(null);+ }+ };++ reader.onerror = () => {+ onError?.('Failed to read file');+ resolve(null);+ };++ reader.readAsDataURL(file);+ });+}++/**+ * Process and upload image files as screenshots+ *+ * @param {FileList|File[]} files - Files to process+ * @param {Object} options - Upload options+ * @param {number} options.maxFileSize - Max file size in bytes (default: 10MB)+ * @param {Function} options.onSuccess - Callback for successful upload (receives uploaded file info)+ * @param {Function} options.onError - Callback for errors (receives error message)+ * @returns {Promise<void>}+ */+export async function processScreenshotUploads(files, options = {}) {+ const {+ maxFileSize = SCREENSHOT_MAX_FILE_SIZE,+ onSuccess,+ onError+ } = options;++ const fileArray = Array.from(files);++ for (const file of fileArray) {+ // Non-image files are skipped SILENTLY here (this runs over a multi-select /+ // drop of mixed content, where naming each non-image is noise) — but an+ // oversized image is reported, since the user clearly meant to upload it.+ if (!file.type.startsWith('image/')) continue;++ const problem = validateImageFile(file, maxFileSize);+ if (problem) {+ onError?.(problem);+ continue;+ }++ await uploadScreenshotFile(file, { onSuccess, onError });+ }+}++/**+ * Check if a file extension is allowed for attachments+ */+function isAllowedAttachmentExtension(filename) {+ const ext = filename.lastIndexOf('.') > -1+ ? filename.slice(filename.lastIndexOf('.')).toLowerCase()+ : '';+ return ALLOWED_ATTACHMENT_EXTENSIONS.includes(ext);+}++/**+ * Get file extension from filename+ */+function getFileExtension(filename) {+ const lastDot = filename.lastIndexOf('.');+ return lastDot > -1 ? filename.slice(lastDot).toLowerCase() : '';+}++/**+ * Check if a file is an image based on extension+ */+function isImageFile(filename) {+ const ext = getFileExtension(filename);+ return ['.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg'].includes(ext);+}++/**+ * Process and upload generic file attachments+ *+ * @param {FileList|File[]} files - Files to process+ * @param {Object} options - Upload options+ * @param {number} options.maxFileSize - Max file size in bytes (default: ATTACHMENT_MAX_FILE_SIZE)+ * @param {Function} options.onSuccess - Callback for successful upload (receives uploaded file info)+ * @param {Function} options.onError - Callback for errors (receives error message)+ * @returns {Promise<void>}+ */+export async function processAttachmentUploads(files, options = {}) {+ const {+ maxFileSize = ATTACHMENT_MAX_FILE_SIZE,+ onSuccess,+ onError+ } = options;++ const fileArray = Array.from(files);++ for (const file of fileArray) {+ // Check file extension is allowed+ if (!isAllowedAttachmentExtension(file.name)) {+ const allowedList = ALLOWED_ATTACHMENT_EXTENSIONS.join(', ');+ onError?.(`File "${file.name}" has unsupported type. Allowed: ${allowedList}`);+ continue;+ }++ // Check file size+ if (file.size > maxFileSize) {+ onError?.(`File "${file.name}" exceeds the ${formatBytes(maxFileSize)} limit`);+ continue;+ }++ await uploadAttachmentFile(file, { onSuccess, onError });+ }+}++/**+ * Upload a single attachment file+ *+ * @param {File} file - File to upload+ * @param {Object} options - Upload options+ * @param {Function} options.onSuccess - Callback for successful upload+ * @param {Function} options.onError - Callback for errors+ * @returns {Promise<Object|null>} Uploaded file info or null on failure+ */+export async function uploadAttachmentFile(file, options = {}) {+ const { onSuccess, onError } = options;++ return new Promise((resolve) => {+ const reader = new FileReader();++ reader.onload = async (ev) => {+ const result = ev?.target?.result;+ if (typeof result !== 'string') {+ onError?.('Failed to read file: unexpected result type');+ resolve(null);+ return;+ }++ const parts = result.split(',');+ if (parts.length < 2) {+ onError?.('Failed to read file: invalid data URL format');+ resolve(null);+ return;+ }++ const base64 = parts[1];+ const uploaded = await uploadAttachment(base64, file.name).catch((err) => {+ onError?.(`Failed to upload: ${err.message}`);+ return null;+ });++ if (uploaded) {+ const fileInfo = {+ id: uploaded.id,+ filename: uploaded.filename,+ originalName: uploaded.originalName || file.name,+ path: uploaded.path,+ size: uploaded.size,+ mimeType: uploaded.mimeType,+ // For images, create preview from the data URL+ preview: isImageFile(file.name) ? result : null,+ isImage: isImageFile(file.name)+ };+ onSuccess?.(fileInfo);+ resolve(fileInfo);+ } else {+ resolve(null);+ }+ };++ reader.onerror = () => {+ onError?.('Failed to read file');+ resolve(null);+ };++ reader.readAsDataURL(file);+ });+}+// Uploads (general file storage)export const uploadFile = (base64Data, filename, options = {}) => request('/uploads', {method: 'POST',diff --git a/client/src/utils/README.md b/client/src/utils/README.mdindex 15fd4f4015..df03b870d3 100644--- a/client/src/utils/README.md+++ b/client/src/utils/README.md@@ -54,7 +54,7 @@ grep -i "what you want to do" client/src/utils/README.md| Module | Purpose ||---|---|-| `fileUpload` | Screenshot/attachment upload helpers: base64 read plus `processScreenshotUploads` / `processAttachmentUploads` and their single-file variants. Also the shared upload constants — `JSON_UPLOAD_MAX_FILE_SIZE` (max file size / wire limit, mirrors `server/lib/uploadLimits.js`), `ATTACHMENT_MAX_FILE_SIZE`, `ALLOWED_ATTACHMENT_EXTENSIONS`, and the `accept` strings `ATTACHMENT_ACCEPT` / `IMAGE_ACCEPT`. |+| `fileUpload` | Pure screenshot/attachment upload helpers: base64 read (`readFileAsBase64`) and image validation (`validateImageFile`). Also the shared upload constants — `JSON_UPLOAD_MAX_FILE_SIZE` (max file size / wire limit, mirrors `server/lib/uploadLimits.js`), `ATTACHMENT_MAX_FILE_SIZE`, `ALLOWED_ATTACHMENT_EXTENSIONS`, and the `accept` strings `ATTACHMENT_ACCEPT` / `IMAGE_ACCEPT`. The actual upload orchestration (`processScreenshotUploads` / `processAttachmentUploads` and their single-file variants) does network I/O and lives in `services/apiMedia.js`; re-exported here for backward compatibility. |## CyberCity — character & avatardiff --git a/client/src/utils/fileUpload.js b/client/src/utils/fileUpload.jsindex 585e2f8456..9ff14b7439 100644--- a/client/src/utils/fileUpload.js+++ b/client/src/utils/fileUpload.js@@ -1,9 +1,14 @@/*** Shared file upload utilities* Used by DevTools Runner and CoS TasksTab for screenshot and attachment uploads+ *+ * This module holds only pure helpers (base64 read, validation, constants) —+ * no I/O. The upload orchestration that actually POSTs to the server+ * (`uploadScreenshotFile` / `processScreenshotUploads` / `uploadAttachmentFile`+ * / `processAttachmentUploads`) lives in `../services/apiMedia.js` and is+ * re-exported below for backward compatibility with existing callers.*/-import * as api from '../services/api';import { formatBytes } from './formatters';// Allowed attachment extensions (should match server)@@ -119,227 +124,16 @@ export function validateImageFile(file, maxFileSize = SCREENSHOT_MAX_FILE_SIZE)return null;}-/**- * Process and upload image files as screenshots- *- * @param {FileList|File[]} files - Files to process- * @param {Object} options - Upload options- * @param {number} options.maxFileSize - Max file size in bytes (default: 10MB)- * @param {Function} options.onSuccess - Callback for successful upload (receives uploaded file info)- * @param {Function} options.onError - Callback for errors (receives error message)- * @returns {Promise<void>}- */-export async function processScreenshotUploads(files, options = {}) {- const {- maxFileSize = SCREENSHOT_MAX_FILE_SIZE,- onSuccess,- onError- } = options;-- const fileArray = Array.from(files);-- for (const file of fileArray) {- // Non-image files are skipped SILENTLY here (this runs over a multi-select /- // drop of mixed content, where naming each non-image is noise) — but an- // oversized image is reported, since the user clearly meant to upload it.- if (!file.type.startsWith('image/')) continue;-- const problem = validateImageFile(file, maxFileSize);- if (problem) {- onError?.(problem);- continue;- }-- await uploadScreenshotFile(file, { onSuccess, onError });- }-}--/**- * Upload a single screenshot file- *- * @param {File} file - File to upload- * @param {Object} options - Upload options- * @param {Function} options.onSuccess - Callback for successful upload- * @param {Function} options.onError - Callback for errors- * @returns {Promise<Object|null>} Uploaded file info or null on failure- */-export async function uploadScreenshotFile(file, options = {}) {- const { onSuccess, onError } = options;-- return new Promise((resolve) => {- const reader = new FileReader();-- reader.onload = async (ev) => {- const result = ev?.target?.result;- if (typeof result !== 'string') {- onError?.('Failed to read file: unexpected result type');- resolve(null);- return;- }-- const parts = result.split(',');- if (parts.length < 2) {- onError?.('Failed to read file: invalid data URL format');- resolve(null);- return;- }-- const base64 = parts[1];- const uploaded = await api.uploadScreenshot(base64, file.name, file.type).catch((err) => {- onError?.(`Failed to upload: ${err.message}`);- return null;- });-- if (uploaded) {- const fileInfo = {- id: uploaded.id,- filename: uploaded.filename,- preview: result,- path: uploaded.path- };- onSuccess?.(fileInfo);- resolve(fileInfo);- } else {- resolve(null);- }- };-- reader.onerror = () => {- onError?.('Failed to read file');- resolve(null);- };-- reader.readAsDataURL(file);- });-}-// Max file size for attachments. Capped by the base64-in-JSON wire limit, not// by any attachment-specific rule — see JSON_UPLOAD_MAX_FILE_SIZE.export const ATTACHMENT_MAX_FILE_SIZE = JSON_UPLOAD_MAX_FILE_SIZE;-/**- * Check if a file extension is allowed for attachments- */-function isAllowedAttachmentExtension(filename) {- const ext = filename.lastIndexOf('.') > -1- ? filename.slice(filename.lastIndexOf('.')).toLowerCase()- : '';- return ALLOWED_ATTACHMENT_EXTENSIONS.includes(ext);-}--/**- * Get file extension from filename- */-function getFileExtension(filename) {- const lastDot = filename.lastIndexOf('.');- return lastDot > -1 ? filename.slice(lastDot).toLowerCase() : '';-}--/**- * Check if a file is an image based on extension- */-function isImageFile(filename) {- const ext = getFileExtension(filename);- return ['.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg'].includes(ext);-}--/**- * Process and upload generic file attachments- *- * @param {FileList|File[]} files - Files to process- * @param {Object} options - Upload options- * @param {number} options.maxFileSize - Max file size in bytes (default: ATTACHMENT_MAX_FILE_SIZE)- * @param {Function} options.onSuccess - Callback for successful upload (receives uploaded file info)- * @param {Function} options.onError - Callback for errors (receives error message)- * @returns {Promise<void>}- */-export async function processAttachmentUploads(files, options = {}) {- const {- maxFileSize = ATTACHMENT_MAX_FILE_SIZE,- onSuccess,- onError- } = options;-- const fileArray = Array.from(files);-- for (const file of fileArray) {- // Check file extension is allowed- if (!isAllowedAttachmentExtension(file.name)) {- const allowedList = ALLOWED_ATTACHMENT_EXTENSIONS.join(', ');- onError?.(`File "${file.name}" has unsupported type. Allowed: ${allowedList}`);- continue;- }-- // Check file size- if (file.size > maxFileSize) {- onError?.(`File "${file.name}" exceeds the ${formatBytes(maxFileSize)} limit`);- continue;- }-- await uploadAttachmentFile(file, { onSuccess, onError });- }-}--/**- * Upload a single attachment file- *- * @param {File} file - File to upload- * @param {Object} options - Upload options- * @param {Function} options.onSuccess - Callback for successful upload- * @param {Function} options.onError - Callback for errors- * @returns {Promise<Object|null>} Uploaded file info or null on failure- */-export async function uploadAttachmentFile(file, options = {}) {- const { onSuccess, onError } = options;-- return new Promise((resolve) => {- const reader = new FileReader();-- reader.onload = async (ev) => {- const result = ev?.target?.result;- if (typeof result !== 'string') {- onError?.('Failed to read file: unexpected result type');- resolve(null);- return;- }-- const parts = result.split(',');- if (parts.length < 2) {- onError?.('Failed to read file: invalid data URL format');- resolve(null);- return;- }-- const base64 = parts[1];- const uploaded = await api.uploadAttachment(base64, file.name).catch((err) => {- onError?.(`Failed to upload: ${err.message}`);- return null;- });-- if (uploaded) {- const fileInfo = {- id: uploaded.id,- filename: uploaded.filename,- originalName: uploaded.originalName || file.name,- path: uploaded.path,- size: uploaded.size,- mimeType: uploaded.mimeType,- // For images, create preview from the data URL- preview: isImageFile(file.name) ? result : null,- isImage: isImageFile(file.name)- };- onSuccess?.(fileInfo);- resolve(fileInfo);- } else {- resolve(null);- }- };-- reader.onerror = () => {- onError?.('Failed to read file');- resolve(null);- };-- reader.readAsDataURL(file);- });-}+// The upload orchestration (network I/O) lives in ../services/apiMedia.js —+// re-exported here so existing callers that import these from utils/fileUpload+// keep working without edits.+export {+ uploadScreenshotFile,+ processScreenshotUploads,+ uploadAttachmentFile,+ processAttachmentUploads,+} from '../services/apiMedia.js';diff --git a/server/lib/storyBible.js b/server/lib/storyBible.jsindex b503d086db..c96890aa2c 100644--- a/server/lib/storyBible.js+++ b/server/lib/storyBible.js@@ -2,9 +2,11 @@* Canonical story-bible shapes (Character / Place / Object) shared by the* Writers Room (per-work bibles) and the Pipeline (per-series bibles).*- * Owns the shape + sanitization + merge-extracted-entries algorithm AND the+ * Owns the shape + sanitization + merge-extracted-entries algorithm. The* `createBibleStore(...)` factory the writers-room domain files build on for- * their CRUD + file I/O. Route exposure stays with the caller.+ * their CRUD + file I/O lives in ../services/bibleStore.js, which imports+ * these sanitizers/transformers from here (this module must stay pure — no+ * data/ file I/O — so it cannot import back from bibleStore.js).*/import { randomUUID } from 'crypto';@@ -1423,9 +1425,3 @@ export function mergeExtractedBible(existing, incoming, kind, {}-// createBibleStore — the per-work CRUD + merge storage factory — moved to-// server/services/bibleStore.js (issue #1154) so this lib stays a pure-// catalog of sanitizers/transformers with no data/ file I/O. Re-exported-// here so existing `import { createBibleStore } from '.../lib/storyBible.js'`-// call sites keep working.-export { createBibleStore } from '../services/bibleStore.js';diff --git a/server/lib/storyBible.test.js b/server/lib/storyBible.test.jsindex 10ff4fdf73..3b514c186d 100644--- a/server/lib/storyBible.test.js+++ b/server/lib/storyBible.test.js@@ -15,6 +15,7 @@ vi.mock('./fileUtils.js', async () => {});const storyBible = await import('./storyBible.js');+const { createBibleStore } = await import('../services/bibleStore.js');const {sanitizeCharacter,sanitizePlace,@@ -27,7 +28,6 @@ const {findBibleEntryByName,BIBLE_LIMITS,BIBLE_KIND,- createBibleStore,pruneStaleReferenceSheets,mergePreservedSheetPointers,stripCanonControlFields,diff --git a/server/services/bibleStore.js b/server/services/bibleStore.jsindex f5f65356d3..36ccc52862 100644--- a/server/services/bibleStore.js+++ b/server/services/bibleStore.js@@ -5,9 +5,8 @@* Extracted from server/lib/storyBible.js (issue #1154) so the lib stays a* pure catalog of sanitizers/transformers and the storage factory (which does* file I/O under data/writers-room/works/) lives in the services layer.- * storyBible.js re-exports `createBibleStore` from here so existing- * `import { createBibleStore } from '../../lib/storyBible.js'` call sites- * (characters.js / places.js / objects.js) keep working.+ * Callers (characters.js / places.js / objects.js) import `createBibleStore`+ * directly from here, and the pure sanitizer names from lib/storyBible.js.*/import { randomUUID } from 'crypto';diff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.jsindex 32b0b9851c..aae1e582e4 100644--- a/server/services/meatspacePost.js+++ b/server/services/meatspacePost.js@@ -30,7 +30,11 @@ import {import { COGNITIVE_DRILL_TYPES, generateCognitiveDrill, scoreCognitiveDrill } from './meatspacePostCognitive.js';import { applySessionToMemoryItems, getMemoryItems, getDueMemoryItems, MASTERY_TARGET_ACCURACY } from './meatspacePostMemory.js';import { applySessionToReviewSchedule, getDueReviews, getRetentionReport } from './meatspacePostReview.js';-import { getAllTrainingEntries } from './meatspacePostTraining.js';+// From postTrainingLogStore.js (NOT meatspacePostTraining.js) — that module+// imports getUnifiedActivityStreak from postActivityStreak.js, which in turn+// needs getPostSessions from this file. Importing getAllTrainingEntries via+// meatspacePostTraining.js would close that into a 3-file circular import.+import { getAllTrainingEntries } from './postTrainingLogStore.js';import { getMorseProgress, MAX_KOCH_LEVEL } from './meatspacePostMorse.js';import { computePostStreaks, computeUnifiedStreak, ymdToUTC, ymdShift } from '../lib/postStreak.js';import { userLocalToday as localToday } from '../lib/timezone.js';@@ -635,19 +639,6 @@ export function deriveTaskAvgResponseMs(task) {return Math.round(timed.reduce((sum, q) => sum + q.responseMs, 0) / timed.length);}-/**- * ONE unified activity streak across scored sessions AND the training log — the- * single number every POST surface (launcher, Morse trainer, dashboard widgets)- * should show, so they can't disagree (issue #2091). A day is active with EITHER- * a scored session or a training-log entry (Morse / memory practice). Computed- * over ALL history, independent of any stats window.- */-export async function getUnifiedActivityStreak(todayStr) {- const day = todayStr ?? await localToday();- const [sessions, training] = await Promise.all([getPostSessions(), getAllTrainingEntries()]);- return computeUnifiedStreak(sessions, training, day);-}-export async function getPostStats(days = 30) {const sessions = await getPostSessions();const todayStr = await localToday();diff --git a/server/services/meatspacePostProgress.test.js b/server/services/meatspacePostProgress.test.jsindex 6e69bf0b50..f8dbdb8b64 100644--- a/server/services/meatspacePostProgress.test.js+++ b/server/services/meatspacePostProgress.test.js@@ -25,8 +25,9 @@ vi.mock('../services/settings.js', () => ({getSettings: () => Promise.resolve({ timezone: 'UTC' }),}));-import { getPostProgress, getPostStats, getUnifiedActivityStreak } from './meatspacePost.js';-import { getTrainingStats } from './meatspacePostTraining.js';+import { getPostProgress, getPostStats } from './meatspacePost.js';+import { getTrainingStats, getAllTrainingEntries } from './meatspacePostTraining.js';+import { getUnifiedActivityStreak } from './postActivityStreak.js';import { postProgressQuerySchema } from '../lib/postValidation.js';const mathTask = (score, questions) => ({ module: 'mental-math', type: 'multiplication', score, questions });@@ -138,7 +139,7 @@ describe('unified streak agrees across every POST surface', () => {getPostStats(30),getTrainingStats(30),getPostProgress({ days: 30 }),- getUnifiedActivityStreak(),+ getAllTrainingEntries().then((entries) => getUnifiedActivityStreak(entries)),]);// 3 consecutive active days (session, practice, session) → streak 3.diff --git a/server/services/meatspacePostTraining.js b/server/services/meatspacePostTraining.jsindex 2d5561412a..7217d288f9 100644--- a/server/services/meatspacePostTraining.js+++ b/server/services/meatspacePostTraining.js@@ -5,34 +5,13 @@* Training mode: progressive difficulty, hints, immediate feedback.*/-import { join } from 'path';import { randomUUID } from 'crypto';-import { atomicWrite, PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';import { userLocalToday } from '../lib/timezone.js';import { ymdShift } from '../lib/postStreak.js';-import { getUnifiedActivityStreak } from './meatspacePost.js';+import { getUnifiedActivityStreak } from './postActivityStreak.js';+import { loadTrainingLog, saveTrainingLog, getAllTrainingEntries } from './postTrainingLogStore.js';-const MEATSPACE_DIR = PATHS.meatspace;-const TRAINING_LOG_FILE = join(MEATSPACE_DIR, 'post-training-log.json');--/**- * @param {{ strict?: boolean }} [options] - `strict: true` throws when the training- * log is present-but-unreadable/corrupt rather than falling back to an empty log.- * See `loadSessions` in meatspacePost.js for the rationale (#2726).- */-async function loadTrainingLog({ strict = false } = {}) {- const data = await readJSONFile(TRAINING_LOG_FILE, { entries: [] }, { allowArray: false, strict });- if (strict && !Array.isArray(data?.entries)) {- throw new Error(`POST training log malformed: ${TRAINING_LOG_FILE}`);- }- if (!Array.isArray(data.entries)) data.entries = [];- return data;-}--async function saveTrainingLog(data) {- await ensureDir(MEATSPACE_DIR);- await atomicWrite(TRAINING_LOG_FILE, data);-}+export { getAllTrainingEntries };/*** Submit a training practice entry after a training-mode drill completes.@@ -42,8 +21,9 @@ export async function submitTrainingEntry(entry) {const nowDate = new Date();const now = nowDate.toISOString();// Stamp the entry's day in the user's local timezone (issue #2681). Training- // entries feed the SHARED unified streak (getUnifiedActivityStreak), which now- // compares against the user's local `today` — a bare UTC-day stamp here would+ // entries feed the SHARED unified streak (getUnifiedActivityStreak in+ // postActivityStreak.js), which now compares against the user's local+ // `today` — a bare UTC-day stamp here would// date a local-evening practice on tomorrow's UTC day and drop it from today's// streak. Derive the day from the SAME `nowDate` used for `timestamp` so a// midnight boundary can't split them onto different days.@@ -77,8 +57,8 @@ export async function submitTrainingEntry(entry) {* Get training stats: per-drill practice counts, streaks, recent activity.** The streak comes from the SHARED unified streak (`getUnifiedActivityStreak` in- * meatspacePost.js) — the exact same number the launcher, dashboard widgets, and- * Progress page show — so the Morse trainer can no longer disagree with them+ * postActivityStreak.js) — the exact same number the launcher, dashboard widgets,+ * and Progress page show — so the Morse trainer can no longer disagree with them* (issue #2091). It counts BOTH scored sessions and training-log entries over* ALL history; only the per-drill breakdown below is windowed.*/@@ -108,7 +88,10 @@ export async function getTrainingStats(days = 30) {}// ONE unified streak across sessions + training (shared helper, ALL history).- const { current: currentStreak, longest: longestStreak } = await getUnifiedActivityStreak();+ // Pass allEntries (already loaded above) rather than re-fetching via+ // getAllTrainingEntries() — postActivityStreak.js takes training as a+ // parameter specifically so it doesn't need to import this module.+ const { current: currentStreak, longest: longestStreak } = await getUnifiedActivityStreak(allEntries);const activeDays = new Set(entries.map(e => String(e.date || '').split('T')[0])).size;// Summarize@@ -140,16 +123,3 @@ export async function getTrainingEntries(limit = 20) {if (!limit) return data.entries.slice().reverse();return data.entries.slice(-limit).reverse();}--/**- * All training-log entries in chronological (append) order — the raw feed the- * unified progress aggregation reads (both meatspacePostTraining and- * meatspacePostMemory practice write to the same `post-training-log.json`).- *- * @param {{ strict?: boolean }} [options] - `strict: true` throws rather than- * reporting an unreadable log as zero entries (#2726).- */-export async function getAllTrainingEntries(options) {- const data = await loadTrainingLog(options);- return data.entries;-}diff --git a/server/services/postActivityStreak.js b/server/services/postActivityStreak.jsnew file mode 100644index 0000000000..214655ce92--- /dev/null+++ b/server/services/postActivityStreak.js@@ -0,0 +1,37 @@+/**+ * Shared unified-activity-streak computation (issue #2091) — ONE definition of+ * the streak across scored POST sessions AND training-log practice, so every+ * surface (launcher, dashboard widgets, Morse trainer, Progress page) agrees.+ *+ * Lives in its own module rather than meatspacePost.js or+ * meatspacePostTraining.js because it needs data from BOTH: sessions (owned by+ * meatspacePost.js) and training-log entries (owned by meatspacePostTraining.js).+ * Defining it in either of those two would force the other to import it back,+ * creating a static circular dependency between them. Instead this module+ * depends one-way on meatspacePost.js for getPostSessions(), and takes the+ * caller's training entries as a parameter — meatspacePostTraining.js already+ * has them in scope from its own training-log load, so it never needs to import+ * this module's sibling for them.+ */+import { getPostSessions } from './meatspacePost.js';+import { computeUnifiedStreak } from '../lib/postStreak.js';+import { userLocalToday as localToday } from '../lib/timezone.js';++/**+ * ONE unified activity streak across scored sessions AND the training log — the+ * single number every POST surface (launcher, Morse trainer, dashboard widgets)+ * should show, so they can't disagree (issue #2091). A day is active with EITHER+ * a scored session or a training-log entry (Morse / memory practice). Computed+ * over ALL history, independent of any stats window.+ *+ * @param {Array} training - training-log entries (e.g. from+ * getAllTrainingEntries() in meatspacePostTraining.js). Taken as a parameter+ * rather than fetched here so this module doesn't need to import+ * meatspacePostTraining.js — see the module docblock above.+ * @param {string} [todayStr] - defaults to the user's local today.+ */+export async function getUnifiedActivityStreak(training, todayStr) {+ const day = todayStr ?? await localToday();+ const sessions = await getPostSessions();+ return computeUnifiedStreak(sessions, training, day);+}diff --git a/server/services/postTrainingLogStore.js b/server/services/postTrainingLogStore.jsnew file mode 100644index 0000000000..b4eb434e4d--- /dev/null+++ b/server/services/postTrainingLogStore.js@@ -0,0 +1,50 @@+/**+ * POST training-log storage primitives — read/write of+ * data/meatspace/post-training-log.json.+ *+ * Extracted out of meatspacePostTraining.js so the raw data access has no+ * dependency on that module. meatspacePost.js (via postActivityStreak.js)+ * needs training-log entries for the unified-streak/progress aggregation;+ * importing them from meatspacePostTraining.js would create a static+ * circular dependency, since meatspacePostTraining.js also needs+ * getUnifiedActivityStreak (which needs meatspacePost.js's session data).+ * This module sits below both, with no imports of either.+ */++import { join } from 'path';+import { atomicWrite, PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';++const MEATSPACE_DIR = PATHS.meatspace;+const TRAINING_LOG_FILE = join(MEATSPACE_DIR, 'post-training-log.json');++/**+ * @param {{ strict?: boolean }} [options] - `strict: true` throws when the training+ * log is present-but-unreadable/corrupt rather than falling back to an empty log.+ * See `loadSessions` in meatspacePost.js for the rationale (#2726).+ */+export async function loadTrainingLog({ strict = false } = {}) {+ const data = await readJSONFile(TRAINING_LOG_FILE, { entries: [] }, { allowArray: false, strict });+ if (strict && !Array.isArray(data?.entries)) {+ throw new Error(`POST training log malformed: ${TRAINING_LOG_FILE}`);+ }+ if (!Array.isArray(data.entries)) data.entries = [];+ return data;+}++export async function saveTrainingLog(data) {+ await ensureDir(MEATSPACE_DIR);+ await atomicWrite(TRAINING_LOG_FILE, data);+}++/**+ * All training-log entries in chronological (append) order — the raw feed the+ * unified progress aggregation reads (both meatspacePostTraining and+ * meatspacePostMemory practice write to the same `post-training-log.json`).+ *+ * @param {{ strict?: boolean }} [options] - `strict: true` throws rather than+ * reporting an unreadable log as zero entries (#2726).+ */+export async function getAllTrainingEntries(options) {+ const data = await loadTrainingLog(options);+ return data.entries;+}diff --git a/server/services/writersRoom/characters.js b/server/services/writersRoom/characters.jsindex bf7edcdd48..c15a9285f0 100644--- a/server/services/writersRoom/characters.js+++ b/server/services/writersRoom/characters.js@@ -6,7 +6,8 @@* `createBibleStore` factory; this module just supplies the per-kind config.*/-import { createBibleStore, BIBLE_KIND, normalizeBibleName } from '../../lib/storyBible.js';+import { BIBLE_KIND, normalizeBibleName } from '../../lib/storyBible.js';+import { createBibleStore } from '../bibleStore.js';export const {list: listCharacters,diff --git a/server/services/writersRoom/objects.js b/server/services/writersRoom/objects.jsindex b03188f596..1249c95c06 100644--- a/server/services/writersRoom/objects.js+++ b/server/services/writersRoom/objects.js@@ -6,7 +6,8 @@* `createBibleStore` factory; this module just supplies the per-kind config.*/-import { createBibleStore, BIBLE_KIND, normalizeBibleName } from '../../lib/storyBible.js';+import { BIBLE_KIND, normalizeBibleName } from '../../lib/storyBible.js';+import { createBibleStore } from '../bibleStore.js';export const {list: listObjects,diff --git a/server/services/writersRoom/places.js b/server/services/writersRoom/places.jsindex 3aaddc7b2e..a21865bae2 100644--- a/server/services/writersRoom/places.js+++ b/server/services/writersRoom/places.js@@ -9,7 +9,8 @@* the name-OR-slugline identifier rule.*/-import { createBibleStore, BIBLE_KIND, normalizeSlugline } from '../../lib/storyBible.js';+import { BIBLE_KIND, normalizeSlugline } from '../../lib/storyBible.js';+import { createBibleStore } from '../bibleStore.js';import { ServerError } from '../../lib/errorHandler.js';// Re-export under the historical name for the existing test + import surface.