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
fix: normalize malformed mission records on read so getStats() can't throw (#3690)
[._.]/ Adam Eivyc786368096f3
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 63540c2e34..f5c06d845f 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -82,3 +82,5 @@- Internal: the series-autopilot unlock-pass test suite no longer reads the checkout's real `data/` directory. It partial-mocked `fileUtils.js` with an in-memory store but left `PATHS.data` pointing at the repo, and the series collection store enumerates that directory with a real `readdir` the mock never intercepts — so on any checkout with real series on disk, two sole-universe-ownership tests failed with what looked like a regression on whatever branch happened to be checked out. CI never saw it because a fresh checkout has no `data/`. `PATHS.data` now resolves to a per-run temp dir via the shared `makePathsProxy` helper, and three added assertions pin the isolation so it cannot quietly come back. The three sibling pipeline suites named as suspects were audited and are already isolated — they replace `series.js` outright and never reach the store. Test-only change; no production code touched.- Internal: audited the whole server test suite for the "test reads the checkout's real `data/`" class that #3683 fixed one instance of, and closed the one case that was actually a bug. The audit was empirical rather than static — a full-suite baseline against an empty `data/`, then a second run with obviously-fake probe records planted in all 74 `data/` subdirectories a service enumerates (prefix-aware, so the stores whose id allowlists require `iss-`/`ser-`/`stb-`/`game-` were actually reached, and including the dirs `data.reference/` seeds rather than only the ones the `PATHS` table names) — and exactly one of 1301 test files failed only in the second run: the missions suite, which addressed `<repo>/data/cos/missions` directly with no mock at all, so it read the developer's live missions *and* wrote its own fixtures into them. It now runs against a per-run temp root, with assertions pinning both the path it writes to and the set it reads back. The 67 suites that partial-mock `fileUtils.js` without redirecting `PATHS` were cleared by the same two-run diff — they replace the service graph wholesale and never reach a real `readdir`. Two further suites do read the live install on purpose and are left alone: the creative-director prompt suite prefers the installed prompt so it catches drift against a local edit, and the opt-in vision integration test enumerates real screenshots to feed a real model. Neither writes anything back. A new repo-wide guard now fails the suite when any other test names the checkout's own `data/` directory, through an install-root anchor or a parent-directory climb, with those two exemptions documented in place. It deliberately does not police the third spelling, importing the real `PATHS` and reading a data-rooted member: 50 files do that, nearly all safely, so that one stays covered by the two-run probe, whose recipe is now recorded beside the guard so it can be re-run. Test-only change; no production code touched.++- One malformed file in the CoS missions directory no longer takes out the whole Missions overview. `getStats()` dereferenced `mission.subTasks.length` on every record `loadMissions()` handed back, and that loader passed through anything that parsed as JSON — so a hand-edited file, a half-written record, or one written in an older shape threw a `TypeError` and blanked the page instead of costing one row. Records are now normalized at the single door they come through: `subTasks`, `goals` and `metrics` coerce to their expected shapes, `progress` to a finite number (no more `NaN%` average), and an absent status buckets under `unknown` rather than an `undefined` key. Anything that isn't a usable mission object is dropped with one `⚠️` line naming the file, so a corrupt record is visible rather than silently missing.diff --git a/server/services/missions.js b/server/services/missions.jsindex 6272379d23..28aaa442a4 100644--- a/server/services/missions.js+++ b/server/services/missions.js@@ -16,6 +16,42 @@ const DATA_DIR = PATHS.missions// In-memory cachelet missionsCache = null+const isPlainObject = value =>+ typeof value === 'object' && value !== null && !Array.isArray(value)++const DEFAULT_METRICS = { tasksGenerated: 0, tasksCompleted: 0, successRate: 0 }++/**+ * Coerce a parsed mission record into the shape every consumer assumes.+ *+ * `loadMissions` is the single door into this service — `getStats`,+ * `completeSubTask`, `generateMissionTask` and `archiveCompletedMissions` all+ * iterate the records it hands back and dereference `subTasks` / `goals` /+ * `metrics` unguarded. Normalizing here (rather than scattering `?.length ?? 0`+ * across the call sites) keeps "invalid" distinguishable from "legitimately+ * empty": only the loader knows a record was malformed on disk, so only the+ * loader can warn about it.+ *+ * @param {*} record - Parsed JSON from a mission file+ * @returns {Object|null} - Normalized mission, or null if unusable+ */+function normalizeMission(record) {+ if (!isPlainObject(record)) return null++ return {+ ...record,+ status: typeof record.status === 'string' ? record.status : 'unknown',+ progress: Number.isFinite(record.progress) ? record.progress : 0,+ goals: Array.isArray(record.goals) ? record.goals : [],+ subTasks: Array.isArray(record.subTasks)+ ? record.subTasks.filter(isPlainObject)+ : [],+ metrics: isPlainObject(record.metrics)+ ? { ...DEFAULT_METRICS, ...record.metrics }+ : { ...DEFAULT_METRICS }+ }+}+/*** Load all missions* @returns {Promise<Array>} - All missions@@ -35,7 +71,12 @@ async function loadMissions() {.map(async file => {const content = await tryReadFile(path.join(DATA_DIR, file))if (!content) return null- return safeJSONParse(content, null, { context: `mission:${file}` })+ const parsed = safeJSONParse(content, null, { context: `mission:${file}` })+ const mission = normalizeMission(parsed)+ // A file that parsed but isn't a usable mission object is dropped, not+ // silently counted — name it so a corrupt record is visible.+ if (!mission) console.warn(`⚠️ Skipping malformed mission record: ${file}`)+ return mission}))diff --git a/server/services/missions.test.js b/server/services/missions.test.jsindex d77de32a89..8ce7af0108 100644--- a/server/services/missions.test.js+++ b/server/services/missions.test.js@@ -1,5 +1,5 @@import { describe, it, expect, beforeEach, afterEach, afterAll, vi } from 'vitest';-import { existsSync, rmSync } from 'fs';+import { existsSync, mkdirSync, rmSync, writeFileSync } from 'fs';import path from 'path';import { mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';@@ -356,6 +356,133 @@ describe('Missions Service', () => {});});+ // #3690 — `loadMissions` used to hand every parsed `.json` straight through, so+ // a hand-edited / half-written / older-shape record took out the whole Missions+ // overview instead of one row. Fixtures are written with `writeFileSync`+ // deliberately: the point is a record PortOS itself would never produce.+ describe('malformed records on disk', () => {+ const writeRaw = (file, contents) => {+ mkdirSync(DATA_DIR, { recursive: true });+ writeFileSync(path.join(DATA_DIR, file), contents);+ invalidateCache();+ };++ it('does not throw on a record with no subTasks array', async () => {+ writeRaw('test-no-subtasks.json', JSON.stringify({+ id: 'test-no-subtasks',+ appId: 'test-app',+ name: 'No SubTasks',+ status: 'active',+ progress: 40+ }));++ const stats = await getStats();+ expect(stats.totalMissions).toBe(1);+ expect(stats.totalSubTasks).toBe(0);+ expect(stats.completedSubTasks).toBe(0);+ expect(stats.overallCompletion).toBe('0%');+ });++ it('never reports averageProgress as NaN for a non-numeric progress', async () => {+ writeRaw('test-bad-progress.json', JSON.stringify({+ id: 'test-bad-progress',+ appId: 'test-app',+ name: 'Bad Progress',+ status: 'active',+ progress: 'halfway',+ subTasks: []+ }));++ const stats = await getStats();+ expect(stats.averageProgress).toBe('0.0%');+ expect(stats.averageProgress).not.toContain('NaN');+ });++ it('buckets a status-less record under a named key, not undefined', async () => {+ writeRaw('test-no-status.json', JSON.stringify({+ id: 'test-no-status',+ appId: 'test-app',+ name: 'No Status',+ subTasks: []+ }));++ const stats = await getStats();+ expect(Object.keys(stats.byStatus)).toEqual(['unknown']);+ expect(stats.byStatus.unknown).toBe(1);+ });++ it.each([+ ['an array', '[]'],+ ['a bare string', '"just a string"'],+ ['a number', '42'],+ ['unparseable bytes', '{ not json at all']+ ])('drops %s with one warning line naming the file, and keeps the good records', async (_label, contents) => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});++ writeRaw('test-not-a-mission.json', contents);+ await createMission({ id: 'test-good-mission', appId: 'test-app', name: 'Good Mission' });++ const stats = await getStats();+ expect(stats.totalMissions).toBe(1);++ const dropWarnings = warn.mock.calls.filter(([msg]) =>+ typeof msg === 'string' && msg.includes('test-not-a-mission.json')+ );+ expect(dropWarnings.length).toBe(1);+ expect(dropWarnings[0][0]).toContain('⚠️');++ warn.mockRestore();+ await deleteMission('test-good-mission');+ });++ it('ignores non-object entries inside subTasks rather than throwing', async () => {+ writeRaw('test-bad-subtask-entries.json', JSON.stringify({+ id: 'test-bad-subtask-entries',+ appId: 'test-app',+ name: 'Bad SubTask Entries',+ status: 'active',+ progress: 50,+ subTasks: [null, 'not-a-task', { id: 'a', status: 'completed' }, { id: 'b', status: 'pending' }]+ }));++ const stats = await getStats();+ expect(stats.totalSubTasks).toBe(2);+ expect(stats.completedSubTasks).toBe(1);+ expect(stats.overallCompletion).toBe('50.0%');+ });++ it('preserves the unrelated fields of a record it normalizes', async () => {+ writeRaw('test-partial-record.json', JSON.stringify({+ id: 'test-partial-record',+ appId: 'test-app',+ name: 'Partial Record',+ description: 'kept as-is'+ }));++ const mission = await getMission('test-partial-record');+ expect(mission.description).toBe('kept as-is');+ expect(mission.subTasks).toEqual([]);+ expect(mission.goals).toEqual([]);+ expect(mission.metrics).toEqual({ tasksGenerated: 0, tasksCompleted: 0, successRate: 0 });+ });++ // The normalized record has to survive the mutating paths too — `addSubTask`+ // pushes onto `subTasks` and bumps `metrics.tasksGenerated`, both of which+ // threw on a record that arrived without them.+ it('lets a normalized record take a new sub-task', async () => {+ writeRaw('test-normalized-mutation.json', JSON.stringify({+ id: 'test-normalized-mutation',+ appId: 'test-app',+ name: 'Normalized Mutation',+ status: 'active'+ }));++ const updated = await addSubTask('test-normalized-mutation', { description: 'First task' });+ expect(updated.subTasks.length).toBe(1);+ expect(updated.metrics.tasksGenerated).toBe(1);+ });+ });+describe('deleteMission', () => {it('should delete a mission', async () => {await createMission({