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([issue-741]): extract CoS task store from cos.js
[._.]/ Adam Eivy70cf29dc9051
diff --git a/server/services/cos.js b/server/services/cos.jsindex a4914c1683..f635dc5039 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -17,7 +17,7 @@ import { existsSync } from 'fs';import { join } from 'path';import { v4 as uuidv4 } from '../lib/uuid.js';import { getActiveProvider } from './providers.js';-import { parseTasksMarkdown, groupTasksByStatus, getNextTask, getAutoApprovedTasks, getAwaitingApprovalTasks, updateTaskStatus, generateTasksMarkdown, hasKnownPrefix, isInternalTaskId } from '../lib/taskParser.js';+import { parseTasksMarkdown, generateTasksMarkdown, isInternalTaskId } from '../lib/taskParser.js';// NOTE: `getAppActivityById` + `updateAppActivity` are deliberately NOT// listed here even though they're used elsewhere in this file. The two// other call sites (in `generateManagedAppImprovementTask` and@@ -35,7 +35,7 @@ import { generateProactiveTasks as generateMissionTasks, getStats as getMissionSimport { generateTaskFromJob, recordJobExecution, recordJobGateSkip, isScriptJob, executeScriptJob, isShellJob, executeShellJob } from './autonomousJobs.js';import { checkJobGate, hasGate } from './jobGates.js';import { ensureDir, formatDuration, safeJSONParse, PATHS } from '../lib/fileUtils.js';-import { sanitizeTaskMetadata, PIPELINE_BEHAVIOR_FLAGS, MAX_TOTAL_SPAWNS, REVIEW_STOP_MODES, normalizeReviewers } from '../lib/validation.js';+import { sanitizeTaskMetadata, PIPELINE_BEHAVIOR_FLAGS, MAX_TOTAL_SPAWNS, normalizeReviewers } from '../lib/validation.js';import { addNotification, NOTIFICATION_TYPES } from './notifications.js';import { recordDecision, DECISION_TYPES } from './decisionLog.js';import { isRecoveryTask } from './recoveryTasks.js';@@ -60,6 +60,14 @@ export { generateReport, getReport, getTodayReport, listReports, listBriefings,import { runHealthCheck, getHealthStatus } from './cosHealthMonitor.js';export { runHealthCheck, getHealthStatus };+// Task store: CRUD + queue persistence (TASKS.md / COS-TASKS.md). Imported for+// internal use by evaluateTasks/dequeueNextTask/generators and re-exported for+// backward compat with `import * as cos` and the cos route handlers. The store+// emits `tasks:changed`; init() below turns that into tryImmediateSpawn /+// dequeueNextTask so the spawn-side logic stays here, not in the store.+import { firstLine, PRIORITY_VALUES, getUserTasks, getCosTasks, getAllTasks, getTasks, getTaskById, addTask, updateTask, deleteTask, reorderTasks, approveTask } from './cosTaskStore.js';+export { firstLine, getUserTasks, getCosTasks, getAllTasks, getTasks, getTaskById, addTask, updateTask, deleteTask, reorderTasks, approveTask };+const AGENT_ARCHIVE_RETENTION_DAYS = 90;const RESUME_DEQUEUE_DELAY_MS = 500;// CD recovery normally resolves in <100ms; hold start() at most this long so@@ -72,11 +80,6 @@ const POST_STARTUP_QUEUE_DELAY_MS = 30_000;// "recently completed" and protected from resetOrphanedTasks's reaper.const RECENT_COMPLETION_GRACE_MS = 60_000;-// First non-empty line of a string. Used by addTask dedup: stored descriptions-// are flattened to a single line by generateTasksMarkdown, so the comparison-// must normalize on the first line to match multi-line inputs.-export const firstLine = (s) => (s || '').split('\n').map(l => l.trim()).find(l => l) || '';-// MAX_TOTAL_SPAWNS imported from validation.js (shared with subAgentSpawner.js)/**@@ -514,78 +517,6 @@ export async function isPaused() {return state.paused || false;}-/**- * Get user tasks from TASKS.md- */-export async function getUserTasks(tasksFilePath = null) {- const state = await loadState();- const filePath = tasksFilePath || join(ROOT_DIR, state.config.userTasksFile);-- if (!existsSync(filePath)) {- return { tasks: [], grouped: groupTasksByStatus([]), file: filePath, exists: false, type: 'user' };- }-- const content = await readFile(filePath, 'utf-8');- const tasks = parseTasksMarkdown(content);- const grouped = groupTasksByStatus(tasks);-- return { tasks, grouped, file: filePath, exists: true, type: 'user' };-}--/**- * Get CoS internal tasks from COS-TASKS.md- */-export async function getCosTasks(tasksFilePath = null) {- const state = await loadState();- const filePath = tasksFilePath || join(ROOT_DIR, state.config.cosTasksFile);-- if (!existsSync(filePath)) {- return { tasks: [], grouped: groupTasksByStatus([]), file: filePath, exists: false, type: 'internal' };- }-- const content = await readFile(filePath, 'utf-8');- const tasks = parseTasksMarkdown(content);- const grouped = groupTasksByStatus(tasks);- const autoApproved = getAutoApprovedTasks(tasks);- const awaitingApproval = getAwaitingApprovalTasks(tasks);-- return { tasks, grouped, file: filePath, exists: true, type: 'internal', autoApproved, awaitingApproval };-}--/**- * Get all tasks (user + internal)- */-export async function getAllTasks() {- const [userTasks, cosTasks] = await Promise.all([getUserTasks(), getCosTasks()]);- return { user: userTasks, cos: cosTasks };-}--/**- * Alias for backward compatibility- */-export const getTasks = getUserTasks;--/**- * Get a specific task by ID from any task source- */-export async function getTaskById(taskId) {- const { user: userTasks, cos: cosTasks } = await getAllTasks();-- // Search user tasks- const userTask = userTasks.tasks?.find(t => t.id === taskId);- if (userTask) {- return { ...userTask, taskType: 'user' };- }-- // Search CoS internal tasks- const cosTask = cosTasks.tasks?.find(t => t.id === taskId);- if (cosTask) {- return { ...cosTask, taskType: 'internal' };- }-- return null;-}-/*** Force-spawn a pending task by ID, bypassing cooldowns and evaluation intervals.*/@@ -2227,120 +2158,6 @@ export function isRunning() {return isDaemonRunning();}-/**- * Add a new task to TASKS.md or COS-TASKS.md- */-export async function addTask(taskData, taskType = 'user', { raw = false } = {}) {- return withStateLock(async () => {- const state = await loadState();- const filePath = taskType === 'user'- ? join(ROOT_DIR, state.config.userTasksFile)- : join(ROOT_DIR, state.config.cosTasksFile);-- // Read existing tasks or start fresh- let tasks = [];- if (existsSync(filePath)) {- const content = await readFile(filePath, 'utf-8');- tasks = parseTasksMarkdown(content);- }-- // Reject duplicate: same first-line description AND same target app already- // pending or in_progress. The `metadata.app` scope matters — the same- // description against two different apps is two different pieces of work- // (e.g. "fix the failing test" in PortOS vs in BookLoom), and collapsing- // them silently drops the second dispatch.- const normalizedDesc = firstLine(taskData.description).toLowerCase();- const targetApp = taskData.app || null;- const duplicate = tasks.find(t =>- (t.status === 'pending' || t.status === 'in_progress') &&- firstLine(t.description).toLowerCase() === normalizedDesc &&- (t.metadata?.app || null) === targetApp- );- if (duplicate) {- console.log(`⚠️ Duplicate task rejected: "${normalizedDesc.substring(0, 60)}" matches ${duplicate.id}`);- return { ...duplicate, duplicate: true };- }-- // When raw=true, use the pre-built task object directly (for on-demand/generated tasks)- let newTask;- if (raw) {- newTask = taskData;- } else {- // Generate a unique ID if not provided- const id = taskData.id || `${taskType === 'user' ? 'task' : 'sys'}-${Date.now().toString(36)}`;-- // Build metadata object- const metadata = {};- if (taskData.context) metadata.context = taskData.context;- if (taskData.model) metadata.model = taskData.model;- if (taskData.provider) metadata.provider = taskData.provider;- if (taskData.app) metadata.app = taskData.app;- // Tags a task dispatched by the voice code-agent tool so the proactive- // speech layer can announce its completion (see voice/proactiveTriggers.js).- if (taskData.voiceDispatch === true) metadata.voiceDispatch = true;- if (taskData.isRecovery === true) metadata.isRecovery = true;- if (taskData.createJiraTicket) metadata.createJiraTicket = true;- // Boolean flags: persist both true and false so users can explicitly override defaults.- // The string round-trip ('false' from TASKS.md) is handled by isTruthyMeta/isFalsyMeta.- // undefined means "use app defaults".- if (taskData.useWorktree === true) metadata.useWorktree = true;- else if (taskData.useWorktree === false) metadata.useWorktree = false;- if (taskData.openPR === true) metadata.openPR = true;- else if (taskData.openPR === false) metadata.openPR = false;- if (taskData.simplify === true) metadata.simplify = true;- else if (taskData.simplify === false) metadata.simplify = false;- if (taskData.reviewLoop === true) metadata.reviewLoop = true;- else if (taskData.reviewLoop === false) metadata.reviewLoop = false;- // Ordered multi-reviewer list (normalizes legacy single `reviewer` too).- if (Array.isArray(taskData.reviewers) || (typeof taskData.reviewer === 'string' && taskData.reviewer)) {- metadata.reviewers = normalizeReviewers(taskData);- }- if (REVIEW_STOP_MODES.includes(taskData.reviewStopMode)) metadata.reviewStopMode = taskData.reviewStopMode;- if (taskData.reviewerApplies === true) metadata.reviewerApplies = true;- else if (taskData.reviewerApplies === false) metadata.reviewerApplies = false;- if (taskData.jiraTicketId) metadata.jiraTicketId = taskData.jiraTicketId;- if (taskData.jiraTicketUrl) metadata.jiraTicketUrl = taskData.jiraTicketUrl;- if (taskData.screenshots?.length > 0) metadata.screenshots = taskData.screenshots;- if (taskData.attachments?.length > 0) metadata.attachments = taskData.attachments;-- // Create the new task- newTask = {- id: hasKnownPrefix(id) ? id : `${taskType === 'user' ? 'task' : 'sys'}-${id}`,- status: 'pending',- priority: (taskData.priority || 'MEDIUM').toUpperCase(),- priorityValue: PRIORITY_VALUES[taskData.priority?.toUpperCase()] || 2,- description: taskData.description,- metadata,- approvalRequired: taskType === 'internal' && taskData.approvalRequired,- autoApproved: taskType === 'internal' && !taskData.approvalRequired,- section: 'pending'- };- }-- // Add task to top or bottom based on position parameter- if (taskData.position === 'top') {- tasks.unshift(newTask);- } else {- tasks.push(newTask);- }-- // Write back to file- const includeApprovalFlags = taskType === 'internal';- const markdown = generateTasksMarkdown(tasks, includeApprovalFlags);- await writeFile(filePath, markdown);-- cosEvents.emit('tasks:changed', { type: taskType, action: 'added', task: newTask });-- // Immediately attempt to spawn user tasks if slots are available- // This avoids waiting for the next evaluation interval (which is meant for system task generation)- if (taskType === 'user') {- setImmediate(() => tryImmediateSpawn(newTask));- }-- return newTask;- });-}-/*** Attempt to immediately spawn a newly added user task if there are available agent slots.* This bypasses the evaluation interval for user-submitted tasks so they start instantly.@@ -2569,206 +2386,6 @@ async function dequeueNextTask() {}}-const PRIORITY_VALUES = {- 'CRITICAL': 4,- 'HIGH': 3,- 'MEDIUM': 2,- 'LOW': 1-};--/**- * Update an existing task- */-export async function updateTask(taskId, updates, taskType = 'user') {- return withStateLock(async () => {- const state = await loadState();- const filePath = taskType === 'user'- ? join(ROOT_DIR, state.config.userTasksFile)- : join(ROOT_DIR, state.config.cosTasksFile);-- if (!existsSync(filePath)) {- console.log(`⚠️ updateTask: file not found for ${taskId} (taskType=${taskType}, path=${filePath})`);- return { error: 'Task file not found' };- }-- const content = await readFile(filePath, 'utf-8');- let tasks = parseTasksMarkdown(content);-- const taskIndex = tasks.findIndex(t => t.id === taskId);- if (taskIndex === -1) {- console.log(`⚠️ updateTask: task ${taskId} not found in ${filePath} (taskType=${taskType}, parsed ${tasks.length} tasks, status update: ${updates.status || 'none'})`);- return { error: 'Task not found' };- }-- // Build updated metadata - merge existing with any new metadata- const updatedMetadata = {- ...tasks[taskIndex].metadata,- ...(updates.metadata || {})- };- // Handle legacy fields that may be passed directly in updates- if (updates.context !== undefined) updatedMetadata.context = updates.context || undefined;- if (updates.model !== undefined) updatedMetadata.model = updates.model || undefined;- if (updates.provider !== undefined) updatedMetadata.provider = updates.provider || undefined;- if (updates.app !== undefined) updatedMetadata.app = updates.app || undefined;-- // Clear blocked/failure metadata when transitioning out of blocked status- if (updates.status && updates.status !== 'blocked' && tasks[taskIndex].status === 'blocked') {- for (const key of ['blocker', 'blockedReason', 'blockedCategory', 'blockedAt', 'failureCount', 'lastErrorCategory', 'lastFailureAt']) {- delete updatedMetadata[key];- }- }-- // Clean undefined values from metadata- Object.keys(updatedMetadata).forEach(key => {- if (updatedMetadata[key] === undefined) delete updatedMetadata[key];- });-- // Update the task- const updatedTask = {- ...tasks[taskIndex],- ...(updates.description && { description: updates.description }),- ...(updates.priority && {- priority: updates.priority.toUpperCase(),- priorityValue: PRIORITY_VALUES[updates.priority.toUpperCase()] || 2- }),- ...(updates.status && { status: updates.status }),- metadata: updatedMetadata- };-- tasks[taskIndex] = updatedTask;-- // Write back to file- const includeApprovalFlags = taskType === 'internal';- const markdown = generateTasksMarkdown(tasks, includeApprovalFlags);- await writeFile(filePath, markdown);-- cosEvents.emit('tasks:changed', { type: taskType, action: 'updated', task: updatedTask });- return updatedTask;- });-}--/**- * Delete a task- */-export async function deleteTask(taskId, taskType = 'user') {- return withStateLock(async () => {- const state = await loadState();- const filePath = taskType === 'user'- ? join(ROOT_DIR, state.config.userTasksFile)- : join(ROOT_DIR, state.config.cosTasksFile);-- if (!existsSync(filePath)) {- return { error: 'Task file not found' };- }-- const content = await readFile(filePath, 'utf-8');- let tasks = parseTasksMarkdown(content);-- const taskToDelete = tasks.find(t => t.id === taskId);- if (!taskToDelete) {- return { error: 'Task not found' };- }-- tasks = tasks.filter(t => t.id !== taskId);-- // Write back to file- const includeApprovalFlags = taskType === 'internal';- const markdown = generateTasksMarkdown(tasks, includeApprovalFlags);- await writeFile(filePath, markdown);-- cosEvents.emit('tasks:changed', { type: taskType, action: 'deleted', taskId });- return { success: true, taskId };- });-}--/**- * Reorder user tasks based on an array of task IDs- */-export async function reorderTasks(taskIds) {- return withStateLock(async () => {- const state = await loadState();- const filePath = join(ROOT_DIR, state.config.userTasksFile);-- if (!existsSync(filePath)) {- return { error: 'Task file not found' };- }-- const content = await readFile(filePath, 'utf-8');- const tasks = parseTasksMarkdown(content);-- // 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- // silently collapse colliding tasks and drop them on write-back.- const taskMap = new Map(tasks.map(t => [t.id, t]));-- // Reorder based on the provided order- const reorderedTasks = [];- for (const id of taskIds) {- const task = taskMap.get(id);- if (task) {- reorderedTasks.push(task);- taskMap.delete(id);- }- }-- // Append any tasks not in the provided order (shouldn't happen, but safe)- for (const task of taskMap.values()) {- reorderedTasks.push(task);- }-- // Write back to file- const markdown = generateTasksMarkdown(reorderedTasks, false);- await writeFile(filePath, markdown);-- cosEvents.emit('tasks:changed', { type: 'user', action: 'reordered' });- return { success: true, order: reorderedTasks.map(t => t.id) };- });-}--/**- * Approve a task that requires approval (marks it as auto-approved)- */-export async function approveTask(taskId) {- return withStateLock(async () => {- const state = await loadState();- const filePath = join(ROOT_DIR, state.config.cosTasksFile);-- if (!existsSync(filePath)) {- return { error: 'CoS task file not found' };- }-- const content = await readFile(filePath, 'utf-8');- let tasks = parseTasksMarkdown(content);-- const taskIndex = tasks.findIndex(t => t.id === taskId);- if (taskIndex === -1) {- return { error: 'Task not found' };- }-- if (!tasks[taskIndex].approvalRequired) {- return { error: 'Task does not require approval' };- }-- // Update approval flags- tasks[taskIndex] = {- ...tasks[taskIndex],- approvalRequired: false,- autoApproved: true- };-- // Write back to file- const markdown = generateTasksMarkdown(tasks, true);- await writeFile(filePath, markdown);-- cosEvents.emit('tasks:changed', { type: 'internal', action: 'approved', task: tasks[taskIndex] });-- // Immediately attempt to spawn the newly approved task- setImmediate(() => dequeueNextTask());-- return tasks[taskIndex];- });-}-/*** Compute the next fire time for an autonomous job.* Supports two scheduling modes:@@ -3138,9 +2755,21 @@ export async function init() {);});- // Event-driven triggers: task/file changes → dequeueNextTask+ // Event-driven triggers: task/file changes → dequeueNextTask.+ // The task store (cosTaskStore.js) persists tasks and emits this event; the+ // spawn-side reaction lives here so the store stays free of scheduler logic.+ // - 'added': fill open slots via dequeueNextTask, and (for user tasks) also+ // fire tryImmediateSpawn so the just-added task starts instantly, bypassing+ // the evaluation interval that's meant for system task generation.+ // - 'approved': a newly approved internal task can now spawn — re-run dequeue.cosEvents.on('tasks:changed', (data) => {- if (isDaemonRunning() && data?.action === 'added') setImmediate(() => dequeueNextTask());+ if (!isDaemonRunning() || !data?.action) return;+ if (data.action === 'added') {+ if (data.type === 'user' && data.task) setImmediate(() => tryImmediateSpawn(data.task));+ setImmediate(() => dequeueNextTask());+ } else if (data.action === 'approved') {+ setImmediate(() => dequeueNextTask());+ }});cosEvents.on('tasks:user:added', () => {diff --git a/server/services/cos.test.js b/server/services/cos.test.jsindex 7780df564b..eb19420c4c 100644--- a/server/services/cos.test.js+++ b/server/services/cos.test.js@@ -862,30 +862,8 @@ describe('addTask — first-line dedup', () => {expect(firstLine(multi).toLowerCase()).toBe(firstLine(stored).toLowerCase());});- it('addTask uses firstLine for dedup (regression guard)', () => {- // addTask's signature destructuring (`{ raw = false } = {}`) confuses the- // brace-balanced extractFnBody scanner — slice from the declaration to- // the next top-level function instead.- const start = COS_SRC.indexOf('export async function addTask');- expect(start, 'addTask must exist').toBeGreaterThan(-1);- const end = COS_SRC.indexOf('export async function', start + 1);- const fnBody = COS_SRC.slice(start, end === -1 ? undefined : end);- expect(fnBody).toMatch(/firstLine\(taskData\.description\)/);- expect(fnBody).toMatch(/firstLine\(t\.description\)/);- });-- it('addTask scopes dedup by metadata.app (regression guard)', () => {- // Same description against two different apps must NOT trip the- // duplicate check — surfaced by codex review of the- // [voice-code-agent-target-managed-app] PR. Without this scope, the- // voice tool happily speaks "Queued in BookLoom" while returning the- // matched PortOS task.- const start = COS_SRC.indexOf('export async function addTask');- const end = COS_SRC.indexOf('export async function', start + 1);- const fnBody = COS_SRC.slice(start, end === -1 ? undefined : end);- // The dedup `tasks.find(...)` predicate must compare the candidate's- // `metadata?.app` (or null) against the new task's `taskData.app`.- expect(fnBody).toMatch(/t\.metadata\?\.app\s*\|\|\s*null/);- expect(fnBody).toMatch(/taskData\.app\s*\|\|\s*null/);- });+ // The addTask source-level regression guards (firstLine dedup + per-app+ // dedup scope) moved to cosTaskStore.test.js when addTask was extracted into+ // cosTaskStore.js. The firstLine behavioral tests above stay here because+ // cos.js still re-exports firstLine for backward compat.});diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.jsnew file mode 100644index 0000000000..187027d846--- /dev/null+++ b/server/services/cosTaskStore.js@@ -0,0 +1,415 @@+/**+ * CoS Task Store Module+ *+ * Task CRUD + queue persistence extracted from cos.js. Owns the read/write+ * round-trip to the user (TASKS.md) and internal (COS-TASKS.md) task files:+ * parsing, grouping, dedup, ID generation, metadata normalization, and the+ * `tasks:changed` event emissions that drive the scheduler.+ *+ * Self-contained — it emits `tasks:changed` rather than calling the scheduler+ * directly. cos.js's `init()` listens on that event to fire `tryImmediateSpawn`+ * (user-added tasks) and `dequeueNextTask` (approved tasks), so the spawn-side+ * logic stays in cos.js while persistence lives here.+ */++import { readFile, writeFile } from 'fs/promises';+import { existsSync } from 'fs';+import { join } from 'path';+import { parseTasksMarkdown, groupTasksByStatus, getAutoApprovedTasks, getAwaitingApprovalTasks, generateTasksMarkdown, hasKnownPrefix } from '../lib/taskParser.js';+import { REVIEW_STOP_MODES, normalizeReviewers } from '../lib/validation.js';+import { loadState, withStateLock, ROOT_DIR } from './cosState.js';+import { cosEvents } from './cosEvents.js';++// First non-empty line of a string. Used by addTask dedup: stored descriptions+// are flattened to a single line by generateTasksMarkdown, so the comparison+// must normalize on the first line to match multi-line inputs.+export const firstLine = (s) => (s || '').split('\n').map(l => l.trim()).find(l => l) || '';++export const PRIORITY_VALUES = {+ 'CRITICAL': 4,+ 'HIGH': 3,+ 'MEDIUM': 2,+ 'LOW': 1+};++/**+ * Get user tasks from TASKS.md+ */+export async function getUserTasks(tasksFilePath = null) {+ const state = await loadState();+ const filePath = tasksFilePath || join(ROOT_DIR, state.config.userTasksFile);++ if (!existsSync(filePath)) {+ return { tasks: [], grouped: groupTasksByStatus([]), file: filePath, exists: false, type: 'user' };+ }++ const content = await readFile(filePath, 'utf-8');+ const tasks = parseTasksMarkdown(content);+ const grouped = groupTasksByStatus(tasks);++ return { tasks, grouped, file: filePath, exists: true, type: 'user' };+}++/**+ * Get CoS internal tasks from COS-TASKS.md+ */+export async function getCosTasks(tasksFilePath = null) {+ const state = await loadState();+ const filePath = tasksFilePath || join(ROOT_DIR, state.config.cosTasksFile);++ if (!existsSync(filePath)) {+ return { tasks: [], grouped: groupTasksByStatus([]), file: filePath, exists: false, type: 'internal' };+ }++ const content = await readFile(filePath, 'utf-8');+ const tasks = parseTasksMarkdown(content);+ const grouped = groupTasksByStatus(tasks);+ const autoApproved = getAutoApprovedTasks(tasks);+ const awaitingApproval = getAwaitingApprovalTasks(tasks);++ return { tasks, grouped, file: filePath, exists: true, type: 'internal', autoApproved, awaitingApproval };+}++/**+ * Get all tasks (user + internal)+ */+export async function getAllTasks() {+ const [userTasks, cosTasks] = await Promise.all([getUserTasks(), getCosTasks()]);+ return { user: userTasks, cos: cosTasks };+}++/**+ * Alias for backward compatibility+ */+export const getTasks = getUserTasks;++/**+ * Get a specific task by ID from any task source+ */+export async function getTaskById(taskId) {+ const { user: userTasks, cos: cosTasks } = await getAllTasks();++ // Search user tasks+ const userTask = userTasks.tasks?.find(t => t.id === taskId);+ if (userTask) {+ return { ...userTask, taskType: 'user' };+ }++ // Search CoS internal tasks+ const cosTask = cosTasks.tasks?.find(t => t.id === taskId);+ if (cosTask) {+ return { ...cosTask, taskType: 'internal' };+ }++ return null;+}++/**+ * Add a new task to the user or internal queue.+ *+ * Emits `tasks:changed` with `action: 'added'` on success; cos.js's init+ * listener turns that into a `tryImmediateSpawn` for user tasks so a newly+ * submitted task starts instantly instead of waiting for the next evaluation+ * interval.+ */+export async function addTask(taskData, taskType = 'user', { raw = false } = {}) {+ return withStateLock(async () => {+ const state = await loadState();+ const filePath = taskType === 'user'+ ? join(ROOT_DIR, state.config.userTasksFile)+ : join(ROOT_DIR, state.config.cosTasksFile);++ // Read existing tasks or start fresh+ let tasks = [];+ if (existsSync(filePath)) {+ const content = await readFile(filePath, 'utf-8');+ tasks = parseTasksMarkdown(content);+ }++ // Reject duplicate: same first-line description AND same target app already+ // pending or in_progress. The `metadata.app` scope matters — the same+ // description against two different apps is two different pieces of work+ // (e.g. "fix the failing test" in PortOS vs in BookLoom), and collapsing+ // them silently drops the second dispatch.+ const normalizedDesc = firstLine(taskData.description).toLowerCase();+ const targetApp = taskData.app || null;+ const duplicate = tasks.find(t =>+ (t.status === 'pending' || t.status === 'in_progress') &&+ firstLine(t.description).toLowerCase() === normalizedDesc &&+ (t.metadata?.app || null) === targetApp+ );+ if (duplicate) {+ console.log(`⚠️ Duplicate task rejected: "${normalizedDesc.substring(0, 60)}" matches ${duplicate.id}`);+ return { ...duplicate, duplicate: true };+ }++ // When raw=true, use the pre-built task object directly (for on-demand/generated tasks)+ let newTask;+ if (raw) {+ newTask = taskData;+ } else {+ // Generate a unique ID if not provided+ const id = taskData.id || `${taskType === 'user' ? 'task' : 'sys'}-${Date.now().toString(36)}`;++ // Build metadata object+ const metadata = {};+ if (taskData.context) metadata.context = taskData.context;+ if (taskData.model) metadata.model = taskData.model;+ if (taskData.provider) metadata.provider = taskData.provider;+ if (taskData.app) metadata.app = taskData.app;+ // Tags a task dispatched by the voice code-agent tool so the proactive+ // speech layer can announce its completion (see voice/proactiveTriggers.js).+ if (taskData.voiceDispatch === true) metadata.voiceDispatch = true;+ if (taskData.isRecovery === true) metadata.isRecovery = true;+ if (taskData.createJiraTicket) metadata.createJiraTicket = true;+ // Boolean flags: persist both true and false so users can explicitly override defaults.+ // The string round-trip ('false' from TASKS.md) is handled by isTruthyMeta/isFalsyMeta.+ // undefined means "use app defaults".+ if (taskData.useWorktree === true) metadata.useWorktree = true;+ else if (taskData.useWorktree === false) metadata.useWorktree = false;+ if (taskData.openPR === true) metadata.openPR = true;+ else if (taskData.openPR === false) metadata.openPR = false;+ if (taskData.simplify === true) metadata.simplify = true;+ else if (taskData.simplify === false) metadata.simplify = false;+ if (taskData.reviewLoop === true) metadata.reviewLoop = true;+ else if (taskData.reviewLoop === false) metadata.reviewLoop = false;+ // Ordered multi-reviewer list (normalizes legacy single `reviewer` too).+ if (Array.isArray(taskData.reviewers) || (typeof taskData.reviewer === 'string' && taskData.reviewer)) {+ metadata.reviewers = normalizeReviewers(taskData);+ }+ if (REVIEW_STOP_MODES.includes(taskData.reviewStopMode)) metadata.reviewStopMode = taskData.reviewStopMode;+ if (taskData.reviewerApplies === true) metadata.reviewerApplies = true;+ else if (taskData.reviewerApplies === false) metadata.reviewerApplies = false;+ if (taskData.jiraTicketId) metadata.jiraTicketId = taskData.jiraTicketId;+ if (taskData.jiraTicketUrl) metadata.jiraTicketUrl = taskData.jiraTicketUrl;+ if (taskData.screenshots?.length > 0) metadata.screenshots = taskData.screenshots;+ if (taskData.attachments?.length > 0) metadata.attachments = taskData.attachments;++ // Create the new task+ newTask = {+ id: hasKnownPrefix(id) ? id : `${taskType === 'user' ? 'task' : 'sys'}-${id}`,+ status: 'pending',+ priority: (taskData.priority || 'MEDIUM').toUpperCase(),+ priorityValue: PRIORITY_VALUES[taskData.priority?.toUpperCase()] || 2,+ description: taskData.description,+ metadata,+ approvalRequired: taskType === 'internal' && taskData.approvalRequired,+ autoApproved: taskType === 'internal' && !taskData.approvalRequired,+ section: 'pending'+ };+ }++ // Add task to top or bottom based on position parameter+ if (taskData.position === 'top') {+ tasks.unshift(newTask);+ } else {+ tasks.push(newTask);+ }++ // Write back to file+ const includeApprovalFlags = taskType === 'internal';+ const markdown = generateTasksMarkdown(tasks, includeApprovalFlags);+ await writeFile(filePath, markdown);++ // cos.js init listens for this event. For user tasks it fires+ // tryImmediateSpawn so the task starts instantly if slots are available,+ // bypassing the evaluation interval (which is meant for system task generation).+ cosEvents.emit('tasks:changed', { type: taskType, action: 'added', task: newTask });++ return newTask;+ });+}++/**+ * Update an existing task+ */+export async function updateTask(taskId, updates, taskType = 'user') {+ return withStateLock(async () => {+ const state = await loadState();+ const filePath = taskType === 'user'+ ? join(ROOT_DIR, state.config.userTasksFile)+ : join(ROOT_DIR, state.config.cosTasksFile);++ if (!existsSync(filePath)) {+ console.log(`⚠️ updateTask: file not found for ${taskId} (taskType=${taskType}, path=${filePath})`);+ return { error: 'Task file not found' };+ }++ const content = await readFile(filePath, 'utf-8');+ let tasks = parseTasksMarkdown(content);++ const taskIndex = tasks.findIndex(t => t.id === taskId);+ if (taskIndex === -1) {+ console.log(`⚠️ updateTask: task ${taskId} not found in ${filePath} (taskType=${taskType}, parsed ${tasks.length} tasks, status update: ${updates.status || 'none'})`);+ return { error: 'Task not found' };+ }++ // Build updated metadata - merge existing with any new metadata+ const updatedMetadata = {+ ...tasks[taskIndex].metadata,+ ...(updates.metadata || {})+ };+ // Handle legacy fields that may be passed directly in updates+ if (updates.context !== undefined) updatedMetadata.context = updates.context || undefined;+ if (updates.model !== undefined) updatedMetadata.model = updates.model || undefined;+ if (updates.provider !== undefined) updatedMetadata.provider = updates.provider || undefined;+ if (updates.app !== undefined) updatedMetadata.app = updates.app || undefined;++ // Clear blocked/failure metadata when transitioning out of blocked status+ if (updates.status && updates.status !== 'blocked' && tasks[taskIndex].status === 'blocked') {+ for (const key of ['blocker', 'blockedReason', 'blockedCategory', 'blockedAt', 'failureCount', 'lastErrorCategory', 'lastFailureAt']) {+ delete updatedMetadata[key];+ }+ }++ // Clean undefined values from metadata+ Object.keys(updatedMetadata).forEach(key => {+ if (updatedMetadata[key] === undefined) delete updatedMetadata[key];+ });++ // Update the task+ const updatedTask = {+ ...tasks[taskIndex],+ ...(updates.description && { description: updates.description }),+ ...(updates.priority && {+ priority: updates.priority.toUpperCase(),+ priorityValue: PRIORITY_VALUES[updates.priority.toUpperCase()] || 2+ }),+ ...(updates.status && { status: updates.status }),+ metadata: updatedMetadata+ };++ tasks[taskIndex] = updatedTask;++ // Write back to file+ const includeApprovalFlags = taskType === 'internal';+ const markdown = generateTasksMarkdown(tasks, includeApprovalFlags);+ await writeFile(filePath, markdown);++ cosEvents.emit('tasks:changed', { type: taskType, action: 'updated', task: updatedTask });+ return updatedTask;+ });+}++/**+ * Delete a task+ */+export async function deleteTask(taskId, taskType = 'user') {+ return withStateLock(async () => {+ const state = await loadState();+ const filePath = taskType === 'user'+ ? join(ROOT_DIR, state.config.userTasksFile)+ : join(ROOT_DIR, state.config.cosTasksFile);++ if (!existsSync(filePath)) {+ return { error: 'Task file not found' };+ }++ const content = await readFile(filePath, 'utf-8');+ let tasks = parseTasksMarkdown(content);++ const taskToDelete = tasks.find(t => t.id === taskId);+ if (!taskToDelete) {+ return { error: 'Task not found' };+ }++ tasks = tasks.filter(t => t.id !== taskId);++ // Write back to file+ const includeApprovalFlags = taskType === 'internal';+ const markdown = generateTasksMarkdown(tasks, includeApprovalFlags);+ await writeFile(filePath, markdown);++ cosEvents.emit('tasks:changed', { type: taskType, action: 'deleted', taskId });+ return { success: true, taskId };+ });+}++/**+ * Reorder user tasks based on an array of task IDs+ */+export async function reorderTasks(taskIds) {+ return withStateLock(async () => {+ const state = await loadState();+ const filePath = join(ROOT_DIR, state.config.userTasksFile);++ if (!existsSync(filePath)) {+ return { error: 'Task file not found' };+ }++ const content = await readFile(filePath, 'utf-8');+ const tasks = parseTasksMarkdown(content);++ // 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+ // silently collapse colliding tasks and drop them on write-back.+ const taskMap = new Map(tasks.map(t => [t.id, t]));++ // Reorder based on the provided order+ const reorderedTasks = [];+ for (const id of taskIds) {+ const task = taskMap.get(id);+ if (task) {+ reorderedTasks.push(task);+ taskMap.delete(id);+ }+ }++ // Append any tasks not in the provided order (shouldn't happen, but safe)+ for (const task of taskMap.values()) {+ reorderedTasks.push(task);+ }++ // Write back to file+ const markdown = generateTasksMarkdown(reorderedTasks, false);+ await writeFile(filePath, markdown);++ cosEvents.emit('tasks:changed', { type: 'user', action: 'reordered' });+ return { success: true, order: reorderedTasks.map(t => t.id) };+ });+}++/**+ * Approve a task that requires approval (marks it as auto-approved).+ *+ * Emits `tasks:changed` with `action: 'approved'`; cos.js's init listener+ * fires `dequeueNextTask` off that so the newly approved task can spawn+ * immediately.+ */+export async function approveTask(taskId) {+ return withStateLock(async () => {+ const state = await loadState();+ const filePath = join(ROOT_DIR, state.config.cosTasksFile);++ if (!existsSync(filePath)) {+ return { error: 'CoS task file not found' };+ }++ const content = await readFile(filePath, 'utf-8');+ let tasks = parseTasksMarkdown(content);++ const taskIndex = tasks.findIndex(t => t.id === taskId);+ if (taskIndex === -1) {+ return { error: 'Task not found' };+ }++ if (!tasks[taskIndex].approvalRequired) {+ return { error: 'Task does not require approval' };+ }++ // Update approval flags+ tasks[taskIndex] = {+ ...tasks[taskIndex],+ approvalRequired: false,+ autoApproved: true+ };++ // Write back to file+ const markdown = generateTasksMarkdown(tasks, true);+ await writeFile(filePath, markdown);++ cosEvents.emit('tasks:changed', { type: 'internal', action: 'approved', task: tasks[taskIndex] });++ return tasks[taskIndex];+ });+}diff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.jsnew file mode 100644index 0000000000..ba5beff852--- /dev/null+++ b/server/services/cosTaskStore.test.js@@ -0,0 +1,305 @@+/**+ * Tests for cosTaskStore.js — task CRUD + queue persistence extracted from+ * cos.js. Two layers:+ *+ * 1. Behavioral tests with the file/state/event deps mocked (in-memory file+ * map) — exercise the real read/write round-trip, dedup, ID generation,+ * metadata normalization, and the `tasks:changed` emissions.+ * 2. Source-level regression guards (moved here from cos.test.js when addTask+ * was extracted) that pin the first-line dedup + per-app dedup scope.+ */++import { describe, it, expect, beforeEach, vi } from 'vitest';+import { readFileSync as realReadFileSync } from 'node:fs';+import { fileURLToPath } from 'url';+import { dirname, join } from 'path';++const mock = vi.hoisted(() => ({+ files: new Map(),+ state: null,+ events: []+}));++// existsSync is driven by the in-memory file map; readFileSync stays real so+// the source-level regression guards below can read cosTaskStore.js off disk.+vi.mock('fs', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...actual,+ existsSync: (p) => mock.files.has(p)+ };+});++vi.mock('fs/promises', () => ({+ readFile: vi.fn(async (p) => {+ 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); })+}));++vi.mock('./cosState.js', () => ({+ loadState: vi.fn(async () => mock.state),+ withStateLock: async (fn) => fn(),+ ROOT_DIR: '/root'+}));++vi.mock('./cosEvents.js', () => ({+ cosEvents: { emit: (name, payload) => mock.events.push({ name, payload }) }+}));++import {+ firstLine,+ PRIORITY_VALUES,+ getUserTasks,+ getCosTasks,+ getAllTasks,+ getTasks,+ getTaskById,+ addTask,+ updateTask,+ deleteTask,+ reorderTasks,+ approveTask+} from './cosTaskStore.js';++const USER_FILE = '/root/TASKS.md';+const COS_FILE = '/root/COS-TASKS.md';++const baseState = () => ({+ config: { userTasksFile: 'TASKS.md', cosTasksFile: 'COS-TASKS.md' }+});++beforeEach(() => {+ mock.files = new Map();+ mock.state = baseState();+ mock.events = [];+});++describe('cosTaskStore.firstLine', () => {+ it('returns the first non-empty trimmed line', () => {+ expect(firstLine('hello\nworld')).toBe('hello');+ expect(firstLine('\n\n first \nsecond')).toBe('first');+ expect(firstLine('single')).toBe('single');+ });++ it('returns empty string for null/undefined/empty input', () => {+ expect(firstLine(null)).toBe('');+ expect(firstLine(undefined)).toBe('');+ expect(firstLine('')).toBe('');+ expect(firstLine('\n\n\n')).toBe('');+ });+});++describe('cosTaskStore.getUserTasks / getCosTasks', () => {+ it('returns an empty, non-existent result when the file is missing', async () => {+ const result = await getUserTasks();+ expect(result.exists).toBe(false);+ expect(result.tasks).toEqual([]);+ expect(result.type).toBe('user');+ expect(result.file).toBe(USER_FILE);+ });++ it('parses an existing user task file', async () => {+ await addTask({ description: 'do a thing', priority: 'HIGH' }, 'user');+ const result = await getUserTasks();+ expect(result.exists).toBe(true);+ expect(result.tasks).toHaveLength(1);+ expect(result.tasks[0].description).toBe('do a thing');+ expect(result.tasks[0].priority).toBe('HIGH');+ });++ it('surfaces autoApproved + awaitingApproval buckets for internal tasks', async () => {+ await addTask({ description: 'auto sys', approvalRequired: false }, 'internal');+ await addTask({ description: 'needs approval', approvalRequired: true }, 'internal');+ const result = await getCosTasks();+ expect(result.type).toBe('internal');+ expect(result.autoApproved.some(t => t.description === 'auto sys')).toBe(true);+ expect(result.awaitingApproval.some(t => t.description === 'needs approval')).toBe(true);+ });+});++describe('cosTaskStore.getAllTasks / getTasks / getTaskById', () => {+ it('getTasks aliases getUserTasks', () => {+ expect(getTasks).toBe(getUserTasks);+ });++ it('getAllTasks merges user + internal sources', async () => {+ await addTask({ description: 'u1' }, 'user');+ await addTask({ description: 's1', approvalRequired: false }, 'internal');+ const all = await getAllTasks();+ expect(all.user.tasks).toHaveLength(1);+ expect(all.cos.tasks).toHaveLength(1);+ });++ it('getTaskById finds a user task and tags taskType', async () => {+ const created = await addTask({ description: 'find me', id: 'task-find' }, 'user');+ const found = await getTaskById(created.id);+ expect(found.id).toBe(created.id);+ expect(found.taskType).toBe('user');+ });++ it('getTaskById finds an internal task and tags taskType', async () => {+ const created = await addTask({ description: 'sys task', id: 'sys-task', approvalRequired: false }, 'internal');+ const found = await getTaskById(created.id);+ expect(found.taskType).toBe('internal');+ });++ it('getTaskById returns null when no source has the id', async () => {+ expect(await getTaskById('nope')).toBeNull();+ });+});++describe('cosTaskStore.addTask', () => {+ it('generates a prefixed id, default MEDIUM priority, and emits tasks:changed', async () => {+ const task = await addTask({ description: 'plain' }, 'user');+ expect(task.id.startsWith('task-')).toBe(true);+ expect(task.priority).toBe('MEDIUM');+ expect(task.priorityValue).toBe(PRIORITY_VALUES.MEDIUM);+ expect(task.status).toBe('pending');+ expect(mock.events.some(e => e.name === 'tasks:changed' && e.payload.action === 'added' && e.payload.type === 'user')).toBe(true);+ });++ it('rejects a duplicate with the same first-line description and app scope', async () => {+ await addTask({ description: 'dupe me', app: 'portos' }, 'user');+ const second = await addTask({ description: 'dupe me\nextra body', app: 'portos' }, 'user');+ expect(second.duplicate).toBe(true);+ const { tasks } = await getUserTasks();+ expect(tasks).toHaveLength(1);+ });++ it('does NOT treat same description against different apps as a duplicate', async () => {+ await addTask({ description: 'shared', app: 'portos' }, 'user');+ const second = await addTask({ description: 'shared', app: 'bookloom' }, 'user');+ expect(second.duplicate).toBeUndefined();+ const { tasks } = await getUserTasks();+ expect(tasks).toHaveLength(2);+ });++ it('persists boolean override flags (true and false) into metadata', async () => {+ const task = await addTask({ description: 'flagged', useWorktree: false, openPR: true }, 'user');+ expect(task.metadata.useWorktree).toBe(false);+ expect(task.metadata.openPR).toBe(true);+ });++ it('raw=true stores the pre-built object verbatim', async () => {+ const raw = { id: 'sys-raw', description: 'raw\nmultiline', status: 'pending', metadata: { context: 'ctx' } };+ const task = await addTask(raw, 'internal', { raw: true });+ expect(task).toBe(raw);+ expect(task.description).toBe('raw\nmultiline');+ });++ it('position:top unshifts the task to the front', async () => {+ await addTask({ description: 'first', id: 'task-a' }, 'user');+ await addTask({ description: 'second', id: 'task-b', position: 'top' }, 'user');+ const { tasks } = await getUserTasks();+ expect(tasks[0].description).toBe('second');+ });+});++describe('cosTaskStore.updateTask', () => {+ it('updates status + priority and emits tasks:changed updated', async () => {+ const created = await addTask({ description: 'upd', id: 'task-upd' }, 'user');+ const updated = await updateTask(created.id, { status: 'in_progress', priority: 'critical' }, 'user');+ expect(updated.status).toBe('in_progress');+ expect(updated.priority).toBe('CRITICAL');+ expect(updated.priorityValue).toBe(PRIORITY_VALUES.CRITICAL);+ expect(mock.events.some(e => e.name === 'tasks:changed' && e.payload.action === 'updated')).toBe(true);+ });++ it('clears blocked metadata when transitioning out of blocked', async () => {+ await addTask({ description: 'blk', id: 'task-blk' }, 'user');+ await updateTask('task-blk', { status: 'blocked', metadata: { blockedReason: 'x', blockedCategory: 'y' } }, 'user');+ const reopened = await updateTask('task-blk', { status: 'pending' }, 'user');+ expect(reopened.metadata.blockedReason).toBeUndefined();+ expect(reopened.metadata.blockedCategory).toBeUndefined();+ });++ it('returns an error object when the file is missing', async () => {+ const result = await updateTask('task-x', { status: 'completed' }, 'user');+ expect(result.error).toBe('Task file not found');+ });++ it('returns an error object when the task id is absent', async () => {+ await addTask({ description: 'present' }, 'user');+ const result = await updateTask('task-missing', { status: 'completed' }, 'user');+ expect(result.error).toBe('Task not found');+ });+});++describe('cosTaskStore.deleteTask', () => {+ it('removes the task and emits tasks:changed deleted', async () => {+ const created = await addTask({ description: 'del', id: 'task-del' }, 'user');+ const result = await deleteTask(created.id, 'user');+ expect(result.success).toBe(true);+ const { tasks } = await getUserTasks();+ expect(tasks).toHaveLength(0);+ expect(mock.events.some(e => e.name === 'tasks:changed' && e.payload.action === 'deleted')).toBe(true);+ });++ it('returns an error when the task is absent', async () => {+ await addTask({ description: 'keep' }, 'user');+ expect((await deleteTask('nope', 'user')).error).toBe('Task not found');+ });+});++describe('cosTaskStore.reorderTasks', () => {+ it('reorders by id and appends any not listed', async () => {+ await addTask({ description: 'one', id: 'task-1' }, 'user');+ await addTask({ description: 'two', id: 'task-2' }, 'user');+ await addTask({ description: 'three', id: 'task-3' }, 'user');+ const result = await reorderTasks(['task-3', 'task-1']);+ expect(result.success).toBe(true);+ expect(result.order).toEqual(['task-3', 'task-1', 'task-2']);+ expect(mock.events.some(e => e.name === 'tasks:changed' && e.payload.action === 'reordered')).toBe(true);+ });+});++describe('cosTaskStore.approveTask', () => {+ it('flips approvalRequired→false / autoApproved→true and emits approved', async () => {+ await addTask({ description: 'need approve', id: 'sys-ap', approvalRequired: true }, 'internal');+ const approved = await approveTask('sys-ap');+ expect(approved.approvalRequired).toBe(false);+ expect(approved.autoApproved).toBe(true);+ expect(mock.events.some(e => e.name === 'tasks:changed' && e.payload.action === 'approved')).toBe(true);+ });++ it('rejects a task that does not require approval', async () => {+ await addTask({ description: 'auto', id: 'sys-auto', approvalRequired: false }, 'internal');+ expect((await approveTask('sys-auto')).error).toBe('Task does not require approval');+ });++ it('returns an error when the cos task file is missing', async () => {+ expect((await approveTask('sys-x')).error).toBe('CoS task file not found');+ });+});++// ─── Source-level regression guards (moved from cos.test.js) ───────────────++const __dirname = dirname(fileURLToPath(import.meta.url));+const STORE_SRC = realReadFileSync(join(__dirname, 'cosTaskStore.js'), 'utf-8');++describe('addTask — first-line dedup (source guards)', () => {+ it('addTask uses firstLine for dedup', () => {+ // addTask's signature destructuring (`{ raw = false } = {}`) confuses a+ // brace-balanced scanner — slice from the declaration to the next top-level+ // function instead.+ const start = STORE_SRC.indexOf('export async function addTask');+ expect(start, 'addTask must exist').toBeGreaterThan(-1);+ const end = STORE_SRC.indexOf('export async function', start + 1);+ const fnBody = STORE_SRC.slice(start, end === -1 ? undefined : end);+ expect(fnBody).toMatch(/firstLine\(taskData\.description\)/);+ expect(fnBody).toMatch(/firstLine\(t\.description\)/);+ });++ it('addTask scopes dedup by metadata.app', () => {+ // Same description against two different apps must NOT trip the duplicate+ // check — the dedup predicate compares the candidate's `metadata?.app` (or+ // null) against the new task's `taskData.app`.+ const start = STORE_SRC.indexOf('export async function addTask');+ const end = STORE_SRC.indexOf('export async function', start + 1);+ const fnBody = STORE_SRC.slice(start, end === -1 ? undefined : end);+ expect(fnBody).toMatch(/t\.metadata\?\.app\s*\|\|\s*null/);+ expect(fnBody).toMatch(/taskData\.app\s*\|\|\s*null/);+ });+});