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
perf([issue-3497]): cache parsed TASKS.md / COS-TASKS.md instead of re-parsing on every read
[._.]/ Adam Eivy12685e6648d8
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 005272a1b0..966dd95a3e 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -81,3 +81,7 @@## Three.js Models- **[issue-3483] Take a generated model apart and click any piece to find out what it is.** The preview used to render a finished model as one inert lump — the only way to check it was actually built from parts, rather than fused into a single shape, was to export the source and read it. An Explode slider now separates the assembly, and clicking any surface names the part it belongs to and lights up that whole component. Separation scales the layout outward from the model's centre instead of shoving every piece the same distance, so parts that were touching genuinely come apart, pieces sitting at the centre still clear their neighbours, and the camera re-frames to whatever the disassembly actually grew to. Surface detail — serrations, stria, trim, port floors — rides the part it belongs to instead of shattering into loose slivers, and clicking it selects that part; models are now generated with that distinction marked, and exported models carry it too.++## Internal++- **[issue-3497] The Chief of Staff stops re-reading and re-parsing its task lists dozens of times a minute.** Every daemon evaluation tick, scheduler sweep, and agent status update read both task files off disk and parsed them from scratch — work that grows with the task list and was already the single busiest thing the idle daemon did. Parsed tasks are now kept in memory and reused while the file on disk is unchanged, so an unchanged list costs a file-timestamp check instead of a full re-parse. Edits made outside PortOS (a text editor, a restore, a sync peer) are still picked up, because the check keys on both the file's timestamp and its size, and every write PortOS makes drops the remembered copy outright rather than trusting a timestamp that some filesystems only record to the nearest second.diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.jsindex f364c797a3..7560dab15d 100644--- a/server/services/cosTaskStore.js+++ b/server/services/cosTaskStore.js@@ -12,7 +12,7 @@* logic stays in cos.js while persistence lives here.*/-import { readFile, writeFile } from 'fs/promises';+import { readFile, writeFile, stat } from 'fs/promises';import { existsSync } from 'fs';import { join } from 'path';import { parseTasksMarkdown, groupTasksByStatus, getAutoApprovedTasks, getAwaitingApprovalTasks, generateTasksMarkdown, hasKnownPrefix } from '../lib/taskParser.js';@@ -102,6 +102,66 @@ function isContentEdit(updates, existingMetadata = {}) {return false;}+// ── Parsed-task cache (issue #3497) ─────────────────────────────────────────+//+// `getUserTasks`/`getCosTasks`/`getTaskById` run on every daemon evaluation+// tick, scheduler sweep, and agent state update, and each call used to do a+// full `readFile` + regex-heavy `parseTasksMarkdown` of a `COS-TASKS.md` that+// grows to hundreds of tasks carrying prompt bodies and JSON metadata strings.+// Cache the parsed array per file so an unchanged file costs one `stat` plus a+// structured clone instead of a read + full parse.+//+// One server process, one user (CLAUDE.md trust model) — no locking, no atomic+// write dance. Correctness rests on two independent invalidation signals:+//+// 1. The stamp (`mtimeMs` + `size`) catches writes this module did NOT make —+// a user editing `TASKS.md` in an editor, a restore, a peer's direct write.+// 2. Every write through `writeTaskFile` DROPS the entry outright. mtime can+// be as coarse as one second on some filesystems, so a write-then-read in+// the same tick must not depend on the stamp having moved.+const parsedTaskCache = new Map(); // filePath -> { stamp, tasks }++// `null` = could not stat (missing/unreadable) → do not cache, distinct from a+// legitimately empty file, which stamps normally and caches its empty parse.+const taskFileStamp = async (filePath) => {+ const stats = await stat(filePath).catch(() => null);+ return stats ? `${stats.mtimeMs}:${stats.size}` : null;+};++/**+ * Read + parse a task markdown file, serving the cached parse when the file is+ * unchanged on disk.+ *+ * Always returns a DEEP COPY. Callers (`addTask`, `updateTask`, `reorderTasks`,+ * the sweeps) mutate both the array and the task objects in place; handing out+ * the cached originals would let one caller's in-flight edits leak into every+ * later reader — including edits that were never persisted.+ */+async function readTaskFile(filePath) {+ const stamp = await taskFileStamp(filePath);+ const cached = parsedTaskCache.get(filePath);+ if (stamp && cached?.stamp === stamp) return structuredClone(cached.tasks);++ const tasks = parseTasksMarkdown(await readFile(filePath, 'utf-8'));+ if (stamp) parsedTaskCache.set(filePath, { stamp, tasks });+ else parsedTaskCache.delete(filePath);+ return structuredClone(tasks);+}++/**+ * Write task markdown, dropping the now-stale parse for that file. Every write+ * path in this module goes through here — see invalidation signal 2 above.+ */+async function writeTaskFile(filePath, markdown) {+ parsedTaskCache.delete(filePath);+ await writeFile(filePath, markdown);+}++/** Test hook: forget every cached parse. */+export function __resetTaskCache() {+ parsedTaskCache.clear();+}+/*** Get user tasks from TASKS.md*/@@ -113,8 +173,7 @@ export async function getUserTasks(tasksFilePath = null) {return { tasks: [], grouped: groupTasksByStatus([]), file: filePath, exists: false, type: 'user' };}- const content = await readFile(filePath, 'utf-8');- const tasks = parseTasksMarkdown(content);+ const tasks = await readTaskFile(filePath);const grouped = groupTasksByStatus(tasks);return { tasks, grouped, file: filePath, exists: true, type: 'user' };@@ -131,8 +190,7 @@ export async function getCosTasks(tasksFilePath = null) {return { tasks: [], grouped: groupTasksByStatus([]), file: filePath, exists: false, type: 'internal' };}- const content = await readFile(filePath, 'utf-8');- const tasks = parseTasksMarkdown(content);+ const tasks = await readTaskFile(filePath);const grouped = groupTasksByStatus(tasks);const autoApproved = getAutoApprovedTasks(tasks);const awaitingApproval = getAwaitingApprovalTasks(tasks);@@ -192,8 +250,7 @@ export async function addTask(taskData, taskType = 'user', { raw = false, ignore// Read existing tasks or start freshlet tasks = [];if (existsSync(filePath)) {- const content = await readFile(filePath, 'utf-8');- tasks = parseTasksMarkdown(content);+ tasks = await readTaskFile(filePath);}// Reject duplicate: same first-line description AND same target app already@@ -406,7 +463,7 @@ export async function addTask(taskData, taskType = 'user', { raw = false, ignore// Write back to fileconst includeApprovalFlags = taskType === 'internal';const markdown = generateTasksMarkdown(tasks, includeApprovalFlags);- await writeFile(filePath, markdown);+ await writeTaskFile(filePath, markdown);// cos.js init listens for this event. For user tasks it fires// tryImmediateSpawn so the task starts instantly if slots are available,@@ -432,8 +489,7 @@ export async function updateTask(taskId, updates, taskType = 'user', { now = Datreturn { error: 'Task file not found' };}- const content = await readFile(filePath, 'utf-8');- let tasks = parseTasksMarkdown(content);+ let tasks = await readTaskFile(filePath);const taskIndex = tasks.findIndex(t => t.id === taskId);if (taskIndex === -1) {@@ -557,7 +613,7 @@ export async function updateTask(taskId, updates, taskType = 'user', { now = Dat// Write back to fileconst includeApprovalFlags = taskType === 'internal';const markdown = generateTasksMarkdown(tasks, includeApprovalFlags);- await writeFile(filePath, markdown);+ await writeTaskFile(filePath, markdown);// A blocked → pending flip is a revive: the task is newly spawnable, exactly// like an approval. Emit a distinct action so cos.init's listener re-runs the@@ -633,7 +689,7 @@ export async function mergePeerTasks(taskType, remoteTasks, { now = Date.now() }: join(ROOT_DIR, state.config.cosTasksFile);const localTasks = existsSync(filePath)- ? parseTasksMarkdown(await readFile(filePath, 'utf-8'))+ ? await readTaskFile(filePath): [];const merged = mergeTaskLists(localTasks, remoteTasks, { now });@@ -649,7 +705,7 @@ export async function mergePeerTasks(taskType, remoteTasks, { now = Date.now() }// never catch up). Re-offering is cheap: the consumer is a durable no-op after the first.if (mergedMarkdown === localMarkdown) return { changed: false, merged };- await writeFile(filePath, mergedMarkdown);+ await writeTaskFile(filePath, mergedMarkdown);cosEvents.emit('tasks:changed', { type: taskType, action: 'peer-merged' });return { changed: true, count: merged.length, merged };});@@ -689,8 +745,7 @@ export async function deleteTask(taskId, taskType = 'user') {return { error: 'Task file not found' };}- const content = await readFile(filePath, 'utf-8');- let tasks = parseTasksMarkdown(content);+ let tasks = await readTaskFile(filePath);const taskToDelete = tasks.find(t => t.id === taskId);if (!taskToDelete) {@@ -702,7 +757,7 @@ export async function deleteTask(taskId, taskType = 'user') {// Write back to fileconst includeApprovalFlags = taskType === 'internal';const markdown = generateTasksMarkdown(tasks, includeApprovalFlags);- await writeFile(filePath, markdown);+ await writeTaskFile(filePath, markdown);cosEvents.emit('tasks:changed', { type: taskType, action: 'deleted', taskId });return { success: true, taskId };@@ -858,8 +913,7 @@ export async function reorderTasks(taskIds) {return { error: 'Task file not found' };}- const content = await readFile(filePath, 'utf-8');- const tasks = parseTasksMarkdown(content);+ const tasks = await readTaskFile(filePath);// Create a map of tasks by ID for quick lookup. parseTasksMarkdown guarantees// unique ids (it suffixes any duplicate it encounters), so this Map can't@@ -883,7 +937,7 @@ export async function reorderTasks(taskIds) {// Write back to fileconst markdown = generateTasksMarkdown(reorderedTasks, false);- await writeFile(filePath, markdown);+ await writeTaskFile(filePath, markdown);cosEvents.emit('tasks:changed', { type: 'user', action: 'reordered' });return { success: true, order: reorderedTasks.map(t => t.id) };@@ -906,8 +960,7 @@ export async function approveTask(taskId, { now = Date.now() } = {}) {return { error: 'CoS task file not found' };}- const content = await readFile(filePath, 'utf-8');- let tasks = parseTasksMarkdown(content);+ let tasks = await readTaskFile(filePath);const taskIndex = tasks.findIndex(t => t.id === taskId);if (taskIndex === -1) {@@ -931,7 +984,7 @@ export async function approveTask(taskId, { now = Date.now() } = {}) {// Write back to fileconst markdown = generateTasksMarkdown(tasks, true);- await writeFile(filePath, markdown);+ await writeTaskFile(filePath, markdown);cosEvents.emit('tasks:changed', { type: 'internal', action: 'approved', task: tasks[taskIndex] });diff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.jsindex 791022675b..4380736a74 100644--- a/server/services/cosTaskStore.test.js+++ b/server/services/cosTaskStore.test.js@@ -16,6 +16,11 @@ import { dirname, join } from 'path';const mock = vi.hoisted(() => ({files: new Map(),+ // Mocked mtimes for the parsed-task cache (#3497). Each mocked write bumps the+ // path's stamp; a test that wants to simulate an EXTERNAL edit sets it itself.+ mtimes: new Map(),+ // Counts real parses so the cache tests can prove a hit did no work.+ parseCalls: 0,state: null,events: [],// Controls the mocked codeReview.js for resolveTaskChallengeWithRecheck (#2471).@@ -41,9 +46,27 @@ vi.mock('fs/promises', () => ({if (!mock.files.has(p)) throw new Error(`ENOENT: ${p}`);return mock.files.get(p);}),- writeFile: vi.fn(async (p, content) => { mock.files.set(p, content); })+ writeFile: vi.fn(async (p, content) => {+ mock.files.set(p, content);+ mock.mtimes.set(p, (mock.mtimes.get(p) || 0) + 1000);+ }),+ // The parsed-task cache stamps on mtimeMs + size, so the mock must model both.+ stat: vi.fn(async (p) => {+ if (!mock.files.has(p)) throw new Error(`ENOENT: ${p}`);+ return { mtimeMs: mock.mtimes.get(p) || 0, size: mock.files.get(p).length };+ })}));+// Counts parseTasksMarkdown calls (cache-hit assertions) while keeping every+// other taskParser export real — the store's whole read path depends on them.+vi.mock('../lib/taskParser.js', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...actual,+ parseTasksMarkdown: (content) => { mock.parseCalls += 1; return actual.parseTasksMarkdown(content); }+ };+});+vi.mock('./cosState.js', () => ({loadState: vi.fn(async () => mock.state),withStateLock: async (fn) => fn(),@@ -90,7 +113,8 @@ import {isReapableBlockedFailure,isReapableInvestigation,sweepResolvedFailureTasks,- DEFAULT_FAILURE_TASK_MAX_AGE_MS+ DEFAULT_FAILURE_TASK_MAX_AGE_MS,+ __resetTaskCache} from './cosTaskStore.js';import { MAX_TOTAL_SPAWNS } from '../lib/cosValidation.js';@@ -103,6 +127,11 @@ const baseState = () => ({beforeEach(() => {mock.files = new Map();+ mock.mtimes = new Map();+ mock.parseCalls = 0;+ // The parse cache is module-level state; a leftover entry from the previous+ // test would answer for a path this test just re-created from scratch.+ __resetTaskCache();mock.state = baseState();mock.events = [];mock.review = { ok: true, findings: 'No findings.' };@@ -153,6 +182,95 @@ describe('cosTaskStore.getUserTasks / getCosTasks', () => {});});+// Parsed-task cache (#3497). The daemon's evaluation tick re-reads both task+// files many times a minute; these pin that an unchanged file is parsed once,+// that every invalidation signal fires, and that a cached read can never leak a+// caller's in-place mutations into the next reader.+describe('cosTaskStore parsed-task cache (#3497)', () => {+ it('serves a cached parse while the file is unchanged', async () => {+ await addTask({ description: 'cached thing' }, 'user');+ mock.parseCalls = 0;++ const first = await getUserTasks();+ expect(mock.parseCalls).toBe(1);++ const second = await getUserTasks();+ expect(mock.parseCalls).toBe(1); // no re-parse — the file did not move+ expect(second.tasks).toEqual(first.tasks);+ });++ it('re-parses after an external edit bumps mtime', async () => {+ await addTask({ description: 'first' }, 'user');+ await getUserTasks();+ mock.parseCalls = 0;++ // Simulate an out-of-band write (user editing TASKS.md, a restore, a peer).+ mock.files.set(USER_FILE, mock.files.get(USER_FILE).replace('first', 'edited outside the store'));+ mock.mtimes.set(USER_FILE, mock.mtimes.get(USER_FILE) + 5000);++ const after = await getUserTasks();+ expect(mock.parseCalls).toBe(1);+ expect(after.tasks[0].description).toBe('edited outside the store');+ });++ it('re-parses after a write through the store even when mtime has not moved', async () => {+ await addTask({ description: 'original' }, 'user');+ await getUserTasks();++ // Freeze mtime+size across the update: a coarse-granularity filesystem can+ // report an identical stamp for a same-second, same-length rewrite, so the+ // write path must drop the entry itself rather than trust the stamp.+ const frozenMtime = mock.mtimes.get(USER_FILE);+ const created = (await getUserTasks()).tasks[0];+ await updateTask(created.id, { description: 'original' }, 'user');+ mock.mtimes.set(USER_FILE, frozenMtime);+ mock.files.set(USER_FILE, mock.files.get(USER_FILE).replace('original', 'rewritten'));+ mock.parseCalls = 0;++ const after = await getUserTasks();+ expect(mock.parseCalls).toBe(1);+ expect(after.tasks[0].description).toBe('rewritten');+ });++ it('invalidates on deleteTask so the removed task never comes back cached', async () => {+ const created = await addTask({ description: 'doomed' }, 'user');+ expect((await getUserTasks()).tasks).toHaveLength(1);++ await deleteTask(created.id, 'user');+ expect((await getUserTasks()).tasks).toHaveLength(0);+ });++ it('invalidates on mergePeerTasks so a merged peer task is visible immediately', async () => {+ await addTask({ description: 'local one', id: 'task-local' }, 'user');+ await getUserTasks();++ await mergePeerTasks('user', [{+ id: 'task-remote',+ description: 'remote one',+ status: 'pending',+ priority: 'MEDIUM',+ metadata: { updatedAt: new Date(Date.now()).toISOString() }+ }]);++ const after = await getUserTasks();+ expect(after.tasks.some(t => t.id === 'task-remote')).toBe(true);+ });++ it('hands every reader its own copy, so mutating one result cannot poison the cache', async () => {+ await addTask({ description: 'pristine' }, 'user');++ const first = await getUserTasks();+ first.tasks[0].description = 'mutated in place';+ first.tasks[0].metadata.injected = 'nope';+ first.tasks.push({ id: 'task-ghost' });++ const second = await getUserTasks();+ expect(second.tasks).toHaveLength(1);+ expect(second.tasks[0].description).toBe('pristine');+ expect(second.tasks[0].metadata.injected).toBeUndefined();+ });+});+describe('cosTaskStore.getAllTasks / getTasks / getTaskById', () => {it('getTasks aliases getUserTasks', () => {expect(getTasks).toBe(getUserTasks);@@ -756,6 +874,42 @@ describe('cosTaskStore.approveTask', () => {const __dirname = dirname(fileURLToPath(import.meta.url));const STORE_SRC = realReadFileSync(join(__dirname, 'cosTaskStore.js'), 'utf-8');+describe('parsed-task cache — no bypass (source guards, #3497)', () => {+ // Everything outside the two cache accessors. Any fs call the rest of the+ // module makes to the task files is a bypass by definition.+ const ACCESSOR_START = 'async function readTaskFile';+ const ACCESSOR_END = '/** Test hook: forget every cached parse. */';+ const outsideAccessors = (() => {+ const start = STORE_SRC.indexOf(ACCESSOR_START);+ const end = STORE_SRC.indexOf(ACCESSOR_END);+ if (start === -1 || end <= start) return null; // asserted below, not thrown here+ return (STORE_SRC.slice(0, start) + STORE_SRC.slice(end))+ .split('\n')+ .filter(line => !line.trim().startsWith('//') && !line.trim().startsWith('*'));+ })();++ it('locates the cache accessors it is guarding', () => {+ // If this fails the two guards below are vacuous — the anchors drifted.+ expect(outsideAccessors, `anchors "${ACCESSOR_START}" / "${ACCESSOR_END}" not found in order`).not.toBeNull();+ });++ it('every task-file read goes through readTaskFile', () => {+ // A read path calling readFile + parseTasksMarkdown directly still works,+ // but pays the full parse the cache exists to avoid and skips the+ // copy-on-read that keeps a caller's in-place mutations out of the cache.+ const bypasses = outsideAccessors.filter(line => /\breadFile\(/.test(line));+ expect(bypasses, `direct readFile call(s): ${bypasses.join(' | ')}`).toEqual([]);+ });++ it('every task-file write goes through writeTaskFile', () => {+ // A write calling writeFile directly leaves the previous parse cached, and+ // mtime granularity is too coarse to be relied on to catch it — the next+ // read would serve pre-write tasks.+ const bypasses = outsideAccessors.filter(line => /\bwriteFile\(/.test(line));+ expect(bypasses, `direct writeFile call(s): ${bypasses.join(' | ')}`).toEqual([]);+ });+});+describe('addTask — first-line dedup (source guards)', () => {it('addTask uses firstLine for dedup', () => {// addTask's signature destructuring (`{ raw = false } = {}`) confuses a