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 multi-line task descriptions on update instead of corrupting the task file (#7240)
[._.]/ Adam Eivy098f406ccf9b
diff --git a/server/lib/taskParser.js b/server/lib/taskParser.jsindex 9f56afe3fb..8b10787e0b 100644--- a/server/lib/taskParser.js+++ b/server/lib/taskParser.js@@ -279,6 +279,26 @@ export function sortByPriority(tasks) {return [...tasks].sort((a, b) => b.priorityValue - a.priorityValue);}+/**+ * Last-resort write-side guard: a task row is a ONE-LINE record, so a newline in+ * `description` does not merely look wrong — it re-parses as file structure. The+ * lines after the break are read as the task's own metadata (` - app: x`+ * re-targets which app the agent runs against) or, for a `- [ ] #id | …` row, as+ * a whole extra auto-approved task the spawner will run, while the description+ * itself is silently truncated to its first line (#7240).+ *+ * Callers normalize first (`cosTaskStore.addTask` / `writeTaskUpdate` re-home the+ * body into the newline-safe `metadata.prompt` / `metadata.context`); this only+ * stops a future writer from reintroducing the corruption, and says so loudly+ * because reaching it means the body was NOT preserved anywhere.+ */+function flattenDescription(task) {+ const description = task.description;+ if (typeof description !== 'string' || !/\r?\n/.test(description)) return description;+ console.warn(`⚠️ Flattened newline(s) in task ${task.id} description for single-line markdown storage`);+ return description.replace(/\r?\n/g, ' ');+}+/*** Generate TASKS.md content from tasks array* @param {boolean} includeApprovalFlags - Whether to include AUTO/APPROVAL flags (for internal CoS tasks)@@ -314,7 +334,7 @@ export function generateTasksMarkdown(tasks, includeApprovalFlags = false) {const approvalFlag = includeApprovalFlags && (task.approvalRequired || task.autoApproved !== undefined)? ` | ${task.approvalRequired ? 'APPROVAL' : 'AUTO'}`: '';- lines.push(`- ${checkbox} #${task.id} | ${task.priority}${approvalFlag} | ${task.description}`);+ lines.push(`- ${checkbox} #${task.id} | ${task.priority}${approvalFlag} | ${flattenDescription(task)}`);// Add metadata (escape newlines in values for single-line storage).// Pass the raw value — escapeNewlines JSON-encodes arrays/objects itself;diff --git a/server/lib/taskParser.test.js b/server/lib/taskParser.test.jsindex c8f64526d7..71679ac856 100644--- a/server/lib/taskParser.test.js+++ b/server/lib/taskParser.test.js@@ -1,4 +1,4 @@-import { describe, it, expect } from 'vitest';+import { describe, it, expect, vi } from 'vitest';import {parseTasksMarkdown,groupTasksByStatus,@@ -335,6 +335,32 @@ describe('Task Parser', () => {expect(markdown).toContain('- app: my-app');});+ // #7240 — a newline in `description` is not a cosmetic problem: the lines+ // after the break re-parse as FILE STRUCTURE. Callers normalize first+ // (cosTaskStore re-homes the body into metadata); this is the write-side+ // backstop that stops a future writer from reintroducing the corruption.+ it('flattens a newline in description so the row can never become file structure', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const description = 'Fix the login flow\nAlso update:\n - app: other-app\n- [ ] #task-999 | HIGH | phantom task';+ const markdown = generateTasksMarkdown([+ { id: 'task-001', status: 'pending', priority: 'HIGH', priorityValue: 3, description, metadata: { context: 'note', app: 'my-app' } }+ ]);+ const warnCalls = warn.mock.calls;+ warn.mockRestore(); // before the assertions, so a failure can't leave console.warn mocked++ // One warn per flattened description, and no row carrying a line break.+ expect(warnCalls).toHaveLength(1);+ expect(warnCalls[0][0]).toContain('task-001');+ expect(markdown.split('\n').filter(l => l.startsWith('- ['))).toHaveLength(1);++ // The file still holds exactly one task, with its own metadata intact and+ // no phantom task minted out of the pasted checklist row.+ const parsed = parseTasksMarkdown(markdown);+ expect(parsed).toHaveLength(1);+ expect(parsed[0].metadata.app).toBe('my-app');+ expect(parsed[0].metadata.context).toBe('note');+ });+it('should escape newlines in metadata values for round-trip preservation', () => {const multiLineContext = '## Additional Instructions\nFix the bug\n\n## Previous Context\nAgent ID: agent-123';const tasks = [diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.jsindex 05347f72c7..d379741f8e 100644--- a/server/services/cosTaskStore.js+++ b/server/services/cosTaskStore.js@@ -26,7 +26,7 @@ import { REQUEUED_AT_KEY } from '../lib/taskRequeue.js';import { resolveTaskStatusTransition, isTerminalTaskStatus } from '../lib/taskStatusTransition.js';import { isInvestigationTask } from '../lib/investigationTasks.js';import { PAUSED_BLOCKED_CATEGORIES, USER_DECISION_BLOCKED_CATEGORIES } from '../lib/taskBlockCategories.js';-import { splitTaskPromptFields } from '../lib/cosTaskPrompt.js';+import { splitTaskPromptFields, TASK_PROMPT_KEY, TASK_CONTEXT_KEY } from '../lib/cosTaskPrompt.js';import { normalizeOrchestrationMode, normalizeOrchestrationProfile } from '../lib/orchestrationProfile.js';import { loadState, withStateLock, ROOT_DIR } from './cosState.js';import { cosEvents } from './cosEvents.js';@@ -43,6 +43,50 @@ export const firstLine = (s) => (s || '').split('\n').map(l => l.trim()).find(lconst CLAIM_KEY_SET = new Set(CLAIM_METADATA_KEYS);+// Heading the update path stamps on text it lifts out of a multi-line description+// edit and into the newline-safe note, so the provenance survives a later read.+const DESCRIPTION_OVERFLOW_HEADING = '(from description)';++/**+ * Normalize a multi-line `description` on the UPDATE path, preserving the body.+ *+ * Markdown task rows are ONE-LINE records: `generateTasksMarkdown` emits the+ * description into `- [ ] #id | PRIORITY | <description>` and+ * `parseTasksMarkdown` reads only that first line. `addTask` has collapsed a+ * multi-line description for exactly that reason since #4153 — `writeTaskUpdate`+ * did not, so saving a multi-line edit from the task editor's textarea wrote the+ * extra lines into the file as free text. Reparsing then silently truncated the+ * description, scraped any ` - key: value` line into the task's OWN metadata+ * (re-targeting its app/provider/prompt), and minted a phantom auto-approved+ * task out of any pasted `- [ ] #id | …` row that the spawner would then run+ * (#7240).+ *+ * Unlike `addTask` this never DROPS the remainder. The full submitted text goes+ * to `metadata.prompt` when the task has none; when it already has one, the text+ * is appended to `metadata.context` instead, because `updateTask` must not+ * overwrite a real prompt (the contract in `server/lib/cosTaskPrompt.js`). Both+ * fields round-trip newlines through the JSON sentinel, and `taskContextBlock`+ * already renders prompt + note together — nothing is lost and nothing is+ * silently replaced. An explicitly-cleared prompt (`''`) counts as present, the+ * same absent-vs-cleared rule the rest of the store follows.+ *+ * Returns `null` when there is nothing to normalize; never mutates its input.+ */+function normalizeUpdatedDescription(description, metadata) {+ if (typeof description !== 'string' || !description.includes('\n')) return null;+ const nextMetadata = { ...metadata };+ if (typeof nextMetadata[TASK_PROMPT_KEY] === 'string') {+ const block = `${DESCRIPTION_OVERFLOW_HEADING}\n${description}`;+ const existing = typeof nextMetadata[TASK_CONTEXT_KEY] === 'string' ? nextMetadata[TASK_CONTEXT_KEY] : '';+ // Re-saving the same edit must not grow the note without bound.+ if (!existing.includes(block)) {+ nextMetadata[TASK_CONTEXT_KEY] = existing ? `${existing}\n\n${block}` : block;+ }+ } else {+ nextMetadata[TASK_PROMPT_KEY] = description;+ }+ return { description: firstLine(description), metadata: nextMetadata };+}// The `blockedCategory` vocabulary lives in `lib/taskBlockCategories.js` — the// pause logic, the failure reaper below, and the investigation auto-retry all@@ -637,16 +681,22 @@ async function writeTaskUpdate(taskId, updates, taskType, { now, suppressDequeueif (updatedMetadata[key] === undefined) delete updatedMetadata[key];});+ // Collapse a multi-line description to the one-line record the markdown row can+ // hold, re-homing the body into prompt/context rather than dropping it (#7240).+ const normalizedDescription = normalizeUpdatedDescription(updates.description, updatedMetadata);+ const nextMetadata = normalizedDescription ? normalizedDescription.metadata : updatedMetadata;+ const nextDescription = normalizedDescription ? normalizedDescription.description : updates.description;+// Update the taskconst updatedTask = {...tasks[taskIndex],- ...(updates.description && { description: updates.description }),+ ...(updates.description && { description: nextDescription }),...(updates.priority && {priority: updates.priority.toUpperCase(),priorityValue: PRIORITY_VALUES[updates.priority.toUpperCase()] || 2}),...(updates.status && { status: updates.status }),- metadata: updatedMetadata+ metadata: nextMetadata};tasks[taskIndex] = updatedTask;diff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.jsindex 17eddd8126..9063644134 100644--- a/server/services/cosTaskStore.test.js+++ b/server/services/cosTaskStore.test.js@@ -121,6 +121,7 @@ import {} from './cosTaskStore.js';import { aggregateAutoFixDiagnostics, getAutoFixMetrics } from './autoFixMetrics.js';import { PRIORITY_VALUES, generateTasksMarkdown } from '../lib/taskParser.js';+import { getTaskPrompt, getTaskContextNote } from '../lib/cosTaskPrompt.js';import { AGENT_PAUSED_CATEGORY, PAUSE_METADATA_KEYS, registerPauseReleaseAdapter, __resetPauseReleaseAdapter } from '../lib/taskPauseHold.js';import { MAX_TOTAL_SPAWNS } from '../lib/cosValidation.js';@@ -665,6 +666,71 @@ describe('cosTaskStore.addTask', () => {expect(updated.metadata.prompt).toBe(AGENT_BODY);});+ // The task editor renders the description as an AutoSizeTextarea, so Enter+ // and paste put newlines into the ORDINARY edit path. Before #7240 the+ // update path wrote them straight into the one-line markdown row: the+ // description silently truncated, the body's ` - key: value` lines were+ // scraped into the task's OWN metadata, and a pasted `- [ ] #id | …` row+ // minted a phantom auto-approved task the spawner would run.+ const CORRUPTING_DESCRIPTION = [+ 'Fix the login flow',+ 'Also update:',+ ' - app: other-app',+ ' - provider: openai',+ '- [ ] #task-999 | HIGH | phantom task',+ ].join('\n');++ it('normalizes a multi-line description on update without corrupting the task file', async () => {+ await addTask(+ { description: 'Fix the login flow', id: 'task-multiline-desc', app: 'my-app', provider: 'claude', context: 'note' },+ 'user'+ );+ const updated = await updateTask('task-multiline-desc', { description: CORRUPTING_DESCRIPTION }, 'user');++ // The row stays a one-line record, so the file reparses to exactly one task.+ expect(updated.description).toBe('Fix the login flow');+ const { tasks } = await getUserTasks();+ expect(tasks).toHaveLength(1);+ expect(tasks[0].id).toBe('task-multiline-desc');++ // The description body no longer re-targets the task's own execution metadata.+ expect(tasks[0].metadata.app).toBe('my-app');+ expect(tasks[0].metadata.provider).toBe('claude');++ // And the submitted text is fully recoverable — nothing silently truncated.+ expect(getTaskPrompt(tasks[0])).toBe(CORRUPTING_DESCRIPTION);+ });++ it('appends a multi-line description edit to the note when the task already has a prompt', async () => {+ await addTask(+ { description: 'claim', id: 'task-desc-with-prompt', prompt: AGENT_BODY, context: 'note' },+ 'user'+ );+ const updated = await updateTask('task-desc-with-prompt', { description: CORRUPTING_DESCRIPTION }, 'user');++ // `updateTask` must never overwrite a real prompt (cosTaskPrompt.js contract).+ expect(updated.metadata.prompt).toBe(AGENT_BODY);+ expect(updated.description).toBe('Fix the login flow');+ const reloaded = await getTaskById('task-desc-with-prompt');+ expect(getTaskContextNote(reloaded)).toBe(`note\n\n(from description)\n${CORRUPTING_DESCRIPTION}`);+ expect((await getUserTasks()).tasks).toHaveLength(1);+ });++ it('does not re-append the same description overflow on a repeated save', async () => {+ await addTask({ description: 'claim', id: 'task-desc-resave', prompt: AGENT_BODY }, 'user');+ await updateTask('task-desc-resave', { description: CORRUPTING_DESCRIPTION }, 'user');+ const again = await updateTask('task-desc-resave', { description: CORRUPTING_DESCRIPTION }, 'user');+ expect(again.metadata.context).toBe(`(from description)\n${CORRUPTING_DESCRIPTION}`);+ });++ it('leaves a single-line description edit untouched', async () => {+ await addTask({ description: 'claim', id: 'task-desc-single', context: 'note' }, 'user');+ const updated = await updateTask('task-desc-single', { description: 'renamed' }, 'user');+ expect(updated.description).toBe('renamed');+ expect(updated.metadata.prompt).toBeUndefined();+ expect(updated.metadata.context).toBe('note');+ });+it('treats prompt as a legacy direct field on update (edit stamp + clear)', async () => {const T0 = Date.parse('2026-08-15T00:00:00.000Z');const T1 = Date.parse('2026-08-15T06:00:00.000Z');