Skip to content

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

refactor: split CoS task metadata.context into prompt vs note fields (#4153)

Adam Eivy87dc6ec47b8d
diff --git a/.changelog/next/changed-issue-4153.md b/.changelog/next/changed-issue-4153.md
new file mode 100644
index 0000000000..94affae05d
--- /dev/null
+++ b/.changelog/next/changed-issue-4153.md
@@ -0,0 +1 @@
+- CoS tasks: split the overloaded `metadata.context` into `metadata.prompt` (the full agent-facing payload) and `metadata.context` (a one-line human note), with a reader fallback for pre-split tasks and a migration for existing queues (#4153)
diff --git a/client/src/components/cos/tabs/TaskItem.jsx b/client/src/components/cos/tabs/TaskItem.jsx
index d97ef9ff7e..d82bcf262f 100644
--- a/client/src/components/cos/tabs/TaskItem.jsx
+++ b/client/src/components/cos/tabs/TaskItem.jsx
@@ -72,8 +72,16 @@ export default function TaskItem({ task, isSystem, onRefresh, providers, duratio
setEditingInternal(val);
onEditingChange?.(val);
}, [onEditingChange]);
+ // A task written since the #4153 split keeps its full agent-facing payload in
+ // `metadata.prompt` and only a short human note in `metadata.context`. Legacy
+ // tasks (and peers still on the old code) have no `prompt` at all — their
+ // payload is still in `context` — so the Prompt field is offered ONLY when the
+ // task actually carries one, and is omitted from the PATCH otherwise rather
+ // than writing an empty `prompt` key onto every task the user edits.
+ const hasPromptField = typeof task.metadata?.prompt === 'string';
const [editData, setEditData] = useState({
description: task.description,
+ prompt: task.metadata?.prompt || '',
context: task.metadata?.context || '',
model: task.metadata?.model || '',
provider: task.metadata?.provider || ''
@@ -172,7 +180,9 @@ export default function TaskItem({ task, isSystem, onRefresh, providers, duratio
};
const handleSave = async () => {
- const result = await api.updateCosTask(task.id, { ...editData, type: taskSource }, { silent: true }).catch(err => {
+ const { prompt, ...rest } = editData;
+ const payload = hasPromptField ? { ...rest, prompt, type: taskSource } : { ...rest, type: taskSource };
+ const result = await api.updateCosTask(task.id, payload, { silent: true }).catch(err => {
toast.error(err.message);
return null;
});
@@ -187,6 +197,7 @@ export default function TaskItem({ task, isSystem, onRefresh, providers, duratio
// changed something, so an unmodified Cancel still discards with no friction.
const hasUnsavedEdits =
editData.description !== task.description ||
+ (hasPromptField && editData.prompt !== (task.metadata?.prompt || '')) ||
editData.context !== (task.metadata?.context || '') ||
editData.model !== (task.metadata?.model || '') ||
editData.provider !== (task.metadata?.provider || '');
@@ -207,6 +218,7 @@ export default function TaskItem({ task, isSystem, onRefresh, providers, duratio
confirmDiscard(() => {
setEditData({
description: task.description,
+ prompt: task.metadata?.prompt || '',
context: task.metadata?.context || '',
model: task.metadata?.model || '',
provider: task.metadata?.provider || ''
@@ -339,13 +351,24 @@ export default function TaskItem({ task, isSystem, onRefresh, providers, duratio
onChange={e => setEditData(d => ({ ...d, description: e.target.value }))}
className="w-full px-2 py-1 bg-port-bg border border-port-border rounded text-white text-sm"
/>
- {/* A textarea, not an input: for orchestrator tasks the context
- holds the task's entire multi-line prompt, which is unreadable
- and unnavigable in a single-line field. Bounded rows + its own
+ {/* A textarea, not an input: for orchestrator tasks this holds the
+ task's entire multi-line prompt, which is unreadable and
+ unnavigable in a single-line field. Bounded rows + its own
scroll so editing a long prompt doesn't stretch the card. */}
+ {hasPromptField && (
+ <textarea
+ rows={4}
+ placeholder="Prompt"
+ aria-label="Task prompt"
+ value={editData.prompt}
+ onChange={e => setEditData(d => ({ ...d, prompt: e.target.value }))}
+ className="w-full px-2 py-1 bg-port-bg border border-port-border rounded text-white text-sm font-mono resize-y overflow-auto"
+ />
+ )}
<textarea
rows={4}
placeholder="Context"
+ aria-label="Task context"
value={editData.context}
onChange={e => setEditData(d => ({ ...d, context: e.target.value }))}
className="w-full px-2 py-1 bg-port-bg border border-port-border rounded text-white text-sm font-mono resize-y overflow-auto"
@@ -407,10 +430,18 @@ export default function TaskItem({ task, isSystem, onRefresh, providers, duratio
text={task.description}
className="text-white"
/>
- {/* The context often carries the task's full prompt (hundreds of
- lines for orchestrator tasks), so it gets the same clamp as the
- description — an unclamped one turns the pending list into a
- wall of text the user has to scroll past. */}
+ {/* The prompt runs to hundreds of lines for orchestrator tasks, so
+ it gets the same clamp as the description — an unclamped one
+ turns the pending list into a wall of text the user has to
+ scroll past. The note below it gets the same treatment, since a
+ legacy task still carries its payload there. */}
+ {task.metadata?.prompt && (
+ <CollapsibleText
+ id={`task-prompt-${idScope}-${task.id}`}
+ text={task.metadata.prompt}
+ className="text-sm text-gray-500 mt-1"
+ />
+ )}
{task.metadata?.context && (
<CollapsibleText
id={`task-context-${idScope}-${task.id}`}
diff --git a/client/src/components/cos/tabs/TaskItem.test.jsx b/client/src/components/cos/tabs/TaskItem.test.jsx
index 85022ad58e..fc01c4da2d 100644
--- a/client/src/components/cos/tabs/TaskItem.test.jsx
+++ b/client/src/components/cos/tabs/TaskItem.test.jsx
@@ -267,6 +267,68 @@ describe('TaskItem long-text clamping', () => {
});
});
+// #4153 — the agent-facing payload moved to `metadata.prompt`; `metadata.context`
+// is now the one-line human note. A task written before the split has no
+// `prompt` at all, so the field must not appear (and must not be PATCHed) then.
+describe('TaskItem prompt field (#4153)', () => {
+ const split = {
+ ...task,
+ id: 'sys-split',
+ metadata: { prompt: 'the agent body\nsecond line', context: 'a short note' },
+ };
+
+ it('renders the prompt and the note as separate blocks', () => {
+ render(<TaskItem task={split} isSystem onRefresh={vi.fn()} providers={providers} />);
+ expect(screen.getByText(/the agent body/)).toBeInTheDocument();
+ expect(screen.getByText('a short note')).toBeInTheDocument();
+ });
+
+ it('offers a Prompt textarea in edit mode and PATCHes the edit', async () => {
+ const onRefresh = vi.fn();
+ render(<TaskItem task={split} isSystem onRefresh={onRefresh} providers={providers} />);
+
+ fireEvent.click(screen.getByRole('button', { name: 'Edit task' }));
+ const promptField = screen.getByPlaceholderText('Prompt');
+ expect(promptField.tagName).toBe('TEXTAREA');
+ expect(promptField).toHaveValue('the agent body\nsecond line');
+
+ fireEvent.change(promptField, { target: { value: 'rewritten body' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));
+
+ await waitFor(() => expect(api.updateCosTask).toHaveBeenCalledWith(
+ 'sys-split',
+ expect.objectContaining({ prompt: 'rewritten body', context: 'a short note' }),
+ { silent: true }
+ ));
+ });
+
+ it('shows the confirm row when only the prompt field changed', () => {
+ render(<TaskItem task={split} isSystem onRefresh={vi.fn()} providers={providers} />);
+ fireEvent.click(screen.getByRole('button', { name: 'Edit task' }));
+ fireEvent.change(screen.getByPlaceholderText('Prompt'), { target: { value: 'edited' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
+ expect(screen.getByRole('group', { name: 'Confirm discard task edits' })).toBeInTheDocument();
+ });
+
+ // Writing `prompt: ''` onto every legacy task the user edits would create an
+ // empty key the markdown store then serializes — absent must stay absent.
+ it('omits the Prompt field, and the prompt key, for a legacy context-only task', async () => {
+ const legacy = { ...task, id: 'sys-legacy', metadata: { context: 'legacy body' } };
+ render(<TaskItem task={legacy} isSystem onRefresh={vi.fn()} providers={providers} />);
+
+ fireEvent.click(screen.getByRole('button', { name: 'Edit task' }));
+ expect(screen.queryByPlaceholderText('Prompt')).not.toBeInTheDocument();
+
+ fireEvent.change(screen.getByPlaceholderText('Context'), { target: { value: 'edited note' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));
+
+ await waitFor(() => expect(api.updateCosTask).toHaveBeenCalled());
+ const [, payload] = api.updateCosTask.mock.calls.at(-1);
+ expect(payload).not.toHaveProperty('prompt');
+ expect(payload.context).toBe('edited note');
+ });
+});
+
describe('TaskItem cancel-edit confirmation (#4037)', () => {
it('discards immediately when Cancel is clicked with no unsaved changes', () => {
render(<TaskItem task={task} isSystem onRefresh={vi.fn()} providers={providers} />);
diff --git a/scripts/migrations/270-cos-task-prompt-split.js b/scripts/migrations/270-cos-task-prompt-split.js
new file mode 100644
index 0000000000..4296716288
--- /dev/null
+++ b/scripts/migrations/270-cos-task-prompt-split.js
@@ -0,0 +1,205 @@
+/**
+ * Migration 270 — move on-disk CoS task PROMPT payloads out of `metadata.context`
+ * and into `metadata.prompt` (issue #4153).
+ *
+ * Background:
+ * `metadata.context` carried two unrelated kinds of content: a one-line human
+ * note, and a multi-thousand-character agent prompt (the generator's Phase 1–7
+ * body, a `/do:*` claim prompt, a repo-study brief). The prompt landed there
+ * because `generateTasksMarkdown` flattens `description` onto one line, so a
+ * multi-line description would corrupt the queue file — `metadata.context` was
+ * the newline-escaped escape hatch that survived serialization.
+ *
+ * The two are now separate fields (`server/lib/cosTaskPrompt.js`), and
+ * `cosTaskStore.addTask` routes new tasks at write time. This migration does
+ * the same for the tasks already queued on this install.
+ *
+ * What it writes:
+ * `data/TASKS.md` and `data/COS-TASKS.md` — renames the `- context: …`
+ * metadata line to `- prompt: …` on every task whose context value is a PROMPT
+ * payload, and re-stamps `updatedAt` on each so the migrated copy wins the
+ * last-write federation merge against a peer that hasn't migrated yet
+ * (`pickContentBase` in `cosTaskMerge.js` breaks an equal-status tie on that
+ * stamp). `PORTOS_SCHEMA_VERSIONS.cosTasks` is bumped to 5 in the same change,
+ * so a not-yet-upgraded peer skips cos-task sync rather than receiving a
+ * `metadata.prompt` its prompt builder cannot read.
+ *
+ * The classification is `isPromptPayload` from `server/lib/cosTaskPrompt.js` —
+ * the SAME predicate the store's write path uses, so a task can't be sorted
+ * one way at creation and the other way here. A single-line context is a note
+ * and is left exactly where it is.
+ *
+ * A text-level rewrite rather than a parse/regenerate round-trip (the choice
+ * migration 234 made for these files): regenerating would reorder, re-escape
+ * and re-sort every task in the user's live queue.
+ *
+ * Safety:
+ * Under-migrating is harmless — every reader goes through `getTaskPrompt`,
+ * which falls back to `metadata.context`. So a task this skips (or an install
+ * that never runs it) keeps resolving correctly; the rewrite just makes the
+ * file on disk say what the code means.
+ *
+ * Idempotent: a task that already carries a `prompt:` line, or whose context is
+ * a one-line note, is skipped — so a second run changes nothing and the files
+ * are left untouched when there is nothing to do.
+ */
+
+import { readFile } from 'fs/promises';
+import { join } from 'path';
+import { atomicWrite } from '../../server/lib/fileUtils.js';
+import { isPromptPayload, TASK_PROMPT_KEY, TASK_CONTEXT_KEY } from '../../server/lib/cosTaskPrompt.js';
+
+// The task header line, per `server/lib/taskParser.js`. Both spellings — with
+// and without the AUTO/APPROVAL flag — since internal tasks carry it and the
+// legacy shape does not.
+const TASK_LINE = /^-\s*\[([ x~!?])\]\s*#([\w-]+)\s*\|\s*(?:CRITICAL|HIGH|MEDIUM|LOW)\s*\|\s*(?:(?:AUTO|APPROVAL)\s*\|\s*)?(.+)$/i;
+const METADATA_LINE = /^(\s+)-\s*(\w+):\s*(.*)$/;
+
+// Sentinel prefix `taskParser.js#escapeNewlines` writes in front of a
+// JSON-encoded metadata value. Every multi-line value written since that
+// encoding landed carries it; older ones use bare `\n` escapes.
+const JSON_SENTINEL = '__json__:';
+
+const QUEUE_FILES = [
+ { configKey: 'userTasksFile', file: 'data/TASKS.md' },
+ { configKey: 'cosTasksFile', file: 'data/COS-TASKS.md' },
+];
+
+/**
+ * Decode a persisted metadata value back to the string a reader would see.
+ * Mirrors `unescapeNewlines` in `server/lib/taskParser.js` — the sentinel form
+ * first, then the legacy bare-`\n` form. Returns null for anything that does not
+ * decode to a string, so a JSON-encoded array/object can never be reclassified.
+ */
+function decodeMetadataValue(raw) {
+ if (raw.startsWith(JSON_SENTINEL)) {
+ let parsed;
+ try { parsed = JSON.parse(raw.slice(JSON_SENTINEL.length)); } catch { return null; }
+ return typeof parsed === 'string' ? parsed : null;
+ }
+ if (raw === 'null' || raw === 'undefined') return null;
+ return raw.replace(/\\n/g, '\n');
+}
+
+/**
+ * Rename the prompt-carrying `context:` metadata line to `prompt:` on every task
+ * that has one, re-stamping `updatedAt` on the ones changed. Pure — exported for
+ * the test.
+ *
+ * @param {string} markdown raw TASKS.md / COS-TASKS.md
+ * @param {{ stamp: string }} options
+ * @returns {{ markdown: string, split: string[] }} ids of the tasks rewritten
+ */
+export function splitPromptMetadata(markdown, { stamp }) {
+ const lines = markdown.split('\n');
+ const out = [];
+ const split = [];
+ // Id of the task whose block we are currently inside.
+ let taskId = null;
+ // Indices in `out` of the current task's context / prompt / updatedAt / last
+ // metadata lines, so the rewrite happens once the whole block has been seen.
+ let contextAt = -1;
+ let hasPrompt = false;
+ let stampAt = -1;
+ let lastMetaAt = -1;
+ let indent = ' ';
+
+ // Rewrite the block we just finished walking. No-op unless it carried a
+ // prompt payload under `context` and no `prompt` of its own.
+ const finish = () => {
+ if (taskId && contextAt >= 0 && !hasPrompt) {
+ const meta = out[contextAt].match(METADATA_LINE);
+ out[contextAt] = `${meta[1]}- ${TASK_PROMPT_KEY}: ${meta[3]}`;
+ const stampLine = `${indent}- updatedAt: ${stamp}`;
+ if (stampAt >= 0) out[stampAt] = stampLine;
+ // No stamp yet — insert directly after the last metadata line rather than
+ // at the end of the block, so it can't land after a description that
+ // spilled onto its own lines (see the block-scan note below).
+ else out.splice(lastMetaAt + 1, 0, stampLine);
+ split.push(taskId);
+ }
+ taskId = null;
+ contextAt = -1;
+ hasPrompt = false;
+ stampAt = -1;
+ lastMetaAt = -1;
+ };
+
+ for (const line of lines) {
+ const header = line.match(TASK_LINE);
+ // A task's block runs to the NEXT task header or section heading — not to
+ // the first non-metadata line. A description written with embedded newlines
+ // is interpolated into the file verbatim by `generateTasksMarkdown`, so a
+ // freshly-filed task can carry blank/prose lines between its header and its
+ // metadata (they are dropped on the next parse round-trip, but a migration
+ // may well run before that happens).
+ if (header || line.startsWith('#')) {
+ finish();
+ out.push(line);
+ if (header) taskId = header[2];
+ continue;
+ }
+ const meta = taskId ? line.match(METADATA_LINE) : null;
+ if (meta) {
+ indent = meta[1];
+ lastMetaAt = out.length;
+ const key = meta[2];
+ if (key === TASK_PROMPT_KEY) hasPrompt = true;
+ else if (key === TASK_CONTEXT_KEY) {
+ const decoded = decodeMetadataValue(meta[3].trim());
+ if (isPromptPayload(decoded)) contextAt = out.length;
+ } else if (key === 'updatedAt') stampAt = out.length;
+ }
+ out.push(line);
+ }
+ finish();
+
+ return { markdown: out.join('\n'), split };
+}
+
+/**
+ * Repo-relative path of a queue file, honouring an install that moved it in
+ * `data/cos/state.json` (`config.userTasksFile` / `config.cosTasksFile` — the
+ * same values `cosTaskStore` reads). Migrating only the defaults would record
+ * this migration as applied while the live queue stayed unsplit.
+ */
+async function queuePaths(rootDir) {
+ const raw = await readFile(join(rootDir, 'data', 'cos', 'state.json'), 'utf-8').catch(() => null);
+ const config = raw ? JSON.parse(raw)?.config ?? {} : {};
+ return QUEUE_FILES.map(({ configKey, file }) => (
+ typeof config[configKey] === 'string' && config[configKey] ? config[configKey] : file
+ ));
+}
+
+export default {
+ async up({ rootDir, now = new Date().toISOString() }) {
+ const split = [];
+ let seenAFile = false;
+
+ for (const relPath of await queuePaths(rootDir)) {
+ const file = join(rootDir, relPath);
+ const raw = await readFile(file, 'utf-8').catch((err) => {
+ if (err.code === 'ENOENT') return null;
+ throw err;
+ });
+ if (raw == null) continue;
+ seenAFile = true;
+
+ const result = splitPromptMetadata(raw, { stamp: now });
+ if (!result.split.length) continue;
+ await atomicWrite(file, result.markdown);
+ split.push(...result.split);
+ }
+
+ if (!seenAFile) {
+ console.log('🧩 migration 270: no task queue on this install — nothing to split');
+ return { ok: true, reason: 'no-task-file' };
+ }
+ if (!split.length) {
+ console.log('🧩 migration 270: no task carries a prompt payload under `context`');
+ return { ok: true, reason: 'already-split', split: 0 };
+ }
+ console.log(`🧩 migration 270: moved ${split.length} task prompt payload(s) from metadata.context to metadata.prompt`);
+ return { ok: true, split: split.length };
+ },
+};
diff --git a/scripts/migrations/270-cos-task-prompt-split.test.js b/scripts/migrations/270-cos-task-prompt-split.test.js
new file mode 100644
index 0000000000..73079f571c
--- /dev/null
+++ b/scripts/migrations/270-cos-task-prompt-split.test.js
@@ -0,0 +1,164 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'fs/promises';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import migration, { splitPromptMetadata } from './270-cos-task-prompt-split.js';
+import { parseTasksMarkdown, generateTasksMarkdown } from '../../server/lib/taskParser.js';
+
+const STAMP = '2026-08-15T12:00:00.000Z';
+const AGENT_BODY = 'Improve Example App\n\n## Phase 1\n- Read PLAN.md\n## Phase 2\nShip a PR.';
+
+// Build the queue file the way the store does, so the metadata escaping under
+// test is the REAL escaping (JSON sentinel) rather than a hand-rolled guess.
+const queue = (...tasks) => generateTasksMarkdown(tasks, true);
+
+const task = (id, metadata, { status = 'pending', description = 'Improve Example App' } = {}) => ({
+ id,
+ status,
+ priority: 'MEDIUM',
+ priorityValue: 2,
+ description,
+ autoApproved: true,
+ approvalRequired: false,
+ metadata,
+});
+
+describe('splitPromptMetadata', () => {
+ it('moves a multi-line context payload to prompt', () => {
+ const md = queue(task('sys-1', { context: AGENT_BODY, app: 'a1' }));
+ const { markdown, split } = splitPromptMetadata(md, { stamp: STAMP });
+ expect(split).toEqual(['sys-1']);
+ // Parsed back through the REAL parser — the rewritten line has to still
+ // read, not merely look right in the raw text.
+ const [parsed] = parseTasksMarkdown(markdown);
+ expect(parsed.metadata.prompt).toBe(AGENT_BODY);
+ expect(parsed.metadata.context).toBeUndefined();
+ expect(parsed.metadata.app).toBe('a1');
+ });
+
+ it('leaves a one-line human note as context', () => {
+ const md = queue(task('sys-1', { context: 'Manually triggered autonomous job: nightly' }));
+ expect(splitPromptMetadata(md, { stamp: STAMP })).toEqual({ markdown: md, split: [] });
+ });
+
+ it('re-stamps updatedAt so the migrated copy wins the federation merge', () => {
+ const md = queue(task('sys-1', { context: AGENT_BODY, updatedAt: '2026-08-01T00:00:00.000Z' }));
+ const { markdown } = splitPromptMetadata(md, { stamp: STAMP });
+ expect(parseTasksMarkdown(markdown)[0].metadata.updatedAt).toBe(STAMP);
+ });
+
+ it('adds the stamp when the task carries none', () => {
+ const md = queue(task('sys-1', { context: AGENT_BODY }));
+ const { markdown } = splitPromptMetadata(md, { stamp: STAMP });
+ expect(parseTasksMarkdown(markdown)[0].metadata.updatedAt).toBe(STAMP);
+ });
+
+ it('is idempotent — a second run changes nothing', () => {
+ const md = queue(task('sys-1', { context: AGENT_BODY }));
+ const once = splitPromptMetadata(md, { stamp: STAMP });
+ const twice = splitPromptMetadata(once.markdown, { stamp: '2026-09-09T00:00:00.000Z' });
+ expect(twice).toEqual({ markdown: once.markdown, split: [] });
+ });
+
+ it('never overwrites a task that already carries a prompt', () => {
+ const md = queue(task('sys-1', { prompt: 'explicit prompt', context: AGENT_BODY }));
+ expect(splitPromptMetadata(md, { stamp: STAMP })).toEqual({ markdown: md, split: [] });
+ });
+
+ it('migrates every non-completed status, and completed ones too', () => {
+ const md = queue(
+ task('sys-p', { context: AGENT_BODY }),
+ task('sys-i', { context: AGENT_BODY }, { status: 'in_progress' }),
+ task('sys-b', { context: AGENT_BODY }, { status: 'blocked' }),
+ task('sys-x', { context: AGENT_BODY }, { status: 'completed' }),
+ );
+ expect(splitPromptMetadata(md, { stamp: STAMP }).split.sort())
+ .toEqual(['sys-b', 'sys-i', 'sys-p', 'sys-x']);
+ });
+
+ it('ignores a JSON-encoded array value that happens to serialize with a newline escape', () => {
+ const md = queue(task('sys-1', { context: 'short note', reviewers: ['claude', 'codex'] }));
+ expect(splitPromptMetadata(md, { stamp: STAMP })).toEqual({ markdown: md, split: [] });
+ });
+
+ // `generateTasksMarkdown` interpolates the description verbatim, so a task
+ // filed with embedded newlines sits in the file with prose/blank lines between
+ // its header and its metadata until the next parse round-trip flattens it. A
+ // scan that stopped at the first non-metadata line would walk past the
+ // `context:` line and leave the payload unsplit.
+ it('reaches the metadata past a description that spilled onto its own lines', () => {
+ const spilled = [
+ '# Tasks',
+ '',
+ '## Pending',
+ '- [ ] #sys-1 | MEDIUM | AUTO | Improve Example App',
+ '',
+ 'Some prose the producer left behind.',
+ ' - context: __json__:"line one\\nline two"',
+ '',
+ ].join('\n');
+ const { markdown, split } = splitPromptMetadata(spilled, { stamp: STAMP });
+ expect(split).toEqual(['sys-1']);
+ expect(markdown).toContain('- prompt: __json__:"line one\\nline two"');
+ expect(markdown).toContain(`- updatedAt: ${STAMP}`);
+ expect(markdown).toContain('Some prose the producer left behind.');
+ });
+
+ it('handles a legacy pre-sentinel escaped value', () => {
+ const legacy = [
+ '# Tasks',
+ '',
+ '## Pending',
+ '- [ ] #sys-1 | MEDIUM | AUTO | Improve Example App',
+ ' - context: line one\\nline two',
+ '',
+ ].join('\n');
+ const { markdown, split } = splitPromptMetadata(legacy, { stamp: STAMP });
+ expect(split).toEqual(['sys-1']);
+ expect(parseTasksMarkdown(markdown)[0].metadata.prompt).toBe('line one\nline two');
+ });
+});
+
+describe('migration 270 up()', () => {
+ let rootDir;
+ const userTasks = () => join(rootDir, 'data', 'TASKS.md');
+ const cosTasks = () => join(rootDir, 'data', 'COS-TASKS.md');
+
+ beforeEach(async () => {
+ rootDir = await mkdtemp(join(tmpdir(), 'portos-270-'));
+ await mkdir(join(rootDir, 'data'), { recursive: true });
+ });
+ afterEach(async () => { await rm(rootDir, { recursive: true, force: true }); });
+
+ it('no-ops when the install has no task queue at all', async () => {
+ await expect(migration.up({ rootDir })).resolves.toMatchObject({ ok: true, reason: 'no-task-file' });
+ });
+
+ it('splits both queues', async () => {
+ await writeFile(userTasks(), queue(task('task-1', { context: AGENT_BODY })));
+ await writeFile(cosTasks(), queue(task('sys-1', { context: AGENT_BODY })));
+ await expect(migration.up({ rootDir, now: STAMP })).resolves.toMatchObject({ ok: true, split: 2 });
+ expect(parseTasksMarkdown(await readFile(userTasks(), 'utf-8'))[0].metadata.prompt).toBe(AGENT_BODY);
+ expect(parseTasksMarkdown(await readFile(cosTasks(), 'utf-8'))[0].metadata.prompt).toBe(AGENT_BODY);
+ });
+
+ it('reports already-split when nothing carries a prompt payload', async () => {
+ await writeFile(cosTasks(), queue(task('sys-1', { context: 'one-line note' })));
+ await expect(migration.up({ rootDir, now: STAMP }))
+ .resolves.toMatchObject({ ok: true, reason: 'already-split', split: 0 });
+ });
+
+ // An install that moved its queue in data/cos/state.json must be migrated
+ // there, not at the default path.
+ it('honours a relocated queue file', async () => {
+ await mkdir(join(rootDir, 'data', 'cos'), { recursive: true });
+ await writeFile(
+ join(rootDir, 'data', 'cos', 'state.json'),
+ JSON.stringify({ config: { cosTasksFile: 'data/cos/MY-TASKS.md' } })
+ );
+ const moved = join(rootDir, 'data', 'cos', 'MY-TASKS.md');
+ await writeFile(moved, queue(task('sys-1', { context: AGENT_BODY })));
+ await expect(migration.up({ rootDir, now: STAMP })).resolves.toMatchObject({ ok: true, split: 1 });
+ expect(parseTasksMarkdown(await readFile(moved, 'utf-8'))[0].metadata.prompt).toBe(AGENT_BODY);
+ });
+});
diff --git a/server/lib/README.md b/server/lib/README.md
index 46465093f5..66917fe37a 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -250,6 +250,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `htmlToText.js` | Shared HTML → plain-text converter. `htmlToText(html, { extraEntities?, paragraphBreak?, collapseSpaces? })` — strips script/style/head/noscript blocks, converts `<br>`/block closes to newlines, strips remaining tags, decodes entities via `decodeXmlEntities`, collapses 3+ newlines, trims. Options preserve caller-specific output (Gmail: `paragraphBreak: '\n\n'` + `collapseSpaces`; SongBook import: defaults — space runs preserved for tab alignment). |
| `jsonExtract.js` | Pull JSON blocks out of LLM responses. `findBalancedBlocks` walks top-level blocks and stops at the first unbalanced one; `findAllBalancedBlocks` is the stack-based variant that scans past stray braces and returns nested blocks in closing order (reverse it for outermost-newest-first). |
| `taskParser.js` | Parse `TASKS.md` format. |
+| `cosTaskPrompt.js` | The CoS task prompt/note split (#4153) — `metadata.prompt` is the full agent-facing payload, `metadata.context` the one-line human note. `isPromptPayload(value)` is the single discriminator (a newline means it's a prompt, not a note), shared by the store's write path and the on-disk migration so they can't classify the same task differently. `getTaskPrompt(task)` prefers `metadata.prompt` and falls back to a legacy `metadata.context`; `getTaskContextNote(task)` returns the note only on an already-split task; `taskContextBlock(task)` renders both as one block so prompt templates (including customized ones) never see the split; `splitTaskPromptFields(metadata)` routes a multi-line `context` to `prompt` at CREATE time only. Pure, dependency-free. |
| `taskPauseHold.js` | The user-PAUSE hold — pure metadata helpers shared by the writer (`pauseAgent`), the reader (`resumeAgent`), and the clearer (`updateTask`). `AGENT_PAUSED_CATEGORY` is the `blockedCategory` a pause stamps; `PAUSE_METADATA_KEYS` names every key it writes; `pauseMetadata({agentId, pausedAt, workspacePath, runId})` arms it and `clearedPauseMetadata()` releases it (undefined-valued, so `updateTask` deletes rather than serializing `"null"`); `isAgentPausedTask(task)` / `isResumablePausedTask(task, agentId)` answer whether a pause is still live and whether it is THIS agent's. `updateTask` clears the whole set whenever the task leaves `blocked`, so a revive by any path (dedupe, cooldown expiry, manual unblock) can't leave a task running under a stale pause. Also carries the cycle-safe RELEASE adapter (#3730) `agentManagement.js` registers at load — `resolvePausedTaskResume(task)` hands `updateTask` the paused run's resume pointer before the write (so any un-block resumes on the preserved worktree, not just the Resume dialog) and `retirePausedAgent(agentId, taskId, branchName)` retires the paused record after it. |
| `taskBlockCategories.js` | The `blockedCategory` vocabulary — which blocks are the system's to clear and which are a person's, read by the pause logic, the failure reaper, and the investigation auto-retry so they can't drift into three literal sets. `PAUSED_BLOCKED_CATEGORIES` (paused until something outside the task changes — keeps the resume pointer), `USER_DECISION_BLOCKED_CATEGORIES` (user intent / open decision — the reaper's exemption), `NON_AUTO_RETRY_BLOCK_CATEGORIES` (their union — a completed investigation must never revive these), `TIMED_COOLDOWN_BLOCKED_CATEGORIES` (a timer clears these — the cooldown sweeper revives them, so block reporters stay quiet). Pure. |
| `taskRequeue.js` | The REQUEUE stamp (#3376) — pure metadata helpers for the one BACKWARD lifecycle step (`in_progress → pending`, performed by the orphan sweep and the retry-hold release). `REQUEUED_AT_KEY` / `LAST_SPAWNED_AT_KEY` name the two stamps; `isPostSpawnRequeue(pendingTask, inProgressTask)` answers whether the requeue happened strictly AFTER that spawn, which is how the federated merge tells a real requeue apart from an ordinary edit landing on a peer's stale `pending` copy. Returns false when either stamp is missing, so callers fall back to the lifecycle rank. |
diff --git a/server/lib/cosTaskPrompt.js b/server/lib/cosTaskPrompt.js
new file mode 100644
index 0000000000..46937b3da0
--- /dev/null
+++ b/server/lib/cosTaskPrompt.js
@@ -0,0 +1,109 @@
+/**
+ * The CoS task prompt/note split (#4153).
+ *
+ * `metadata.context` used to carry two unrelated kinds of content:
+ *
+ * 1. A one-line human note ("Manually triggered autonomous job: …").
+ * 2. A multi-thousand-character AGENT PROMPT — the generator's Phase 1–7 body,
+ * a `/do:*` claim prompt, a repo-study brief. It landed there because
+ * `generateTasksMarkdown` flattens `description` onto one line and
+ * `parseTasksMarkdown` only matches a `- [ ]` block's first line, so a
+ * newline in `description` corrupts `COS-TASKS.md`. `metadata.context` is
+ * newline-escaped through the JSON sentinel, so it was the escape hatch
+ * that survived serialization.
+ *
+ * The two are now separate fields:
+ *
+ * - `metadata.prompt` — the full agent-facing payload.
+ * - `metadata.context` — the one-line human note.
+ *
+ * **Reads stay tolerant of the legacy shape.** PortOS is distributed software:
+ * other installs and federated peers hold tasks written before the split, and
+ * `scripts/migrations/270-cos-task-prompt-split.js` only rewrites the local
+ * install's files. So every reader goes through `getTaskPrompt`, which prefers
+ * `metadata.prompt` and falls back to `metadata.context`.
+ *
+ * Pure and side-effect free — no imports, safe for the migration to reuse.
+ */
+
+/** Metadata key holding the full agent-facing payload. */
+export const TASK_PROMPT_KEY = 'prompt';
+
+/** Metadata key holding the one-line human note. */
+export const TASK_CONTEXT_KEY = 'context';
+
+/**
+ * Is this value a prompt payload rather than a one-line note?
+ *
+ * The discriminator is a newline: the `context` contract is explicitly "one line
+ * of human note", so anything with a line break is by construction the other
+ * thing. This is the SINGLE definition — the store's write path and the on-disk
+ * migration both call it, so a task classified one way at creation can't be
+ * classified the other way by the migration.
+ *
+ * Note `''` is NOT a prompt: an intentionally-cleared note stays a note (the
+ * absent-vs-present-but-empty rule in CLAUDE.md).
+ */
+export const isPromptPayload = (value) => typeof value === 'string' && value.includes('\n');
+
+/**
+ * The full agent-facing payload for a task, or `null` when it has none.
+ *
+ * Prefers `metadata.prompt`; falls back to `metadata.context` for tasks written
+ * before the split (and for peers still on the old code). Returns `''` — not
+ * `null` — when the field is present but empty, so a deliberate clear is
+ * distinguishable from an absent field.
+ */
+export function getTaskPrompt(task) {
+ const metadata = task?.metadata;
+ if (typeof metadata?.[TASK_PROMPT_KEY] === 'string') return metadata[TASK_PROMPT_KEY];
+ if (typeof metadata?.[TASK_CONTEXT_KEY] === 'string') return metadata[TASK_CONTEXT_KEY];
+ return null;
+}
+
+/**
+ * The one-line human note for a task, or `null` when it has none.
+ *
+ * Only a task that ALREADY carries `metadata.prompt` can have a distinct note —
+ * on a legacy task `metadata.context` IS the prompt (see `getTaskPrompt`), and
+ * returning it here as well would render the same body twice.
+ */
+export function getTaskContextNote(task) {
+ const metadata = task?.metadata;
+ if (typeof metadata?.[TASK_PROMPT_KEY] !== 'string') return null;
+ return typeof metadata[TASK_CONTEXT_KEY] === 'string' ? metadata[TASK_CONTEXT_KEY] : null;
+}
+
+/**
+ * The task's prompt + note rendered as ONE block, or `null` when the task has
+ * neither. Every prompt-building path uses this so the split is invisible to the
+ * templates (including the ones an install has customized): a legacy task
+ * renders exactly what it rendered before, and a split task renders its payload
+ * followed by its note.
+ */
+export function taskContextBlock(task) {
+ const parts = [getTaskPrompt(task), getTaskContextNote(task)]
+ .filter(v => typeof v === 'string' && v.trim() !== '');
+ return parts.length ? parts.join('\n\n') : null;
+}
+
+/**
+ * Route a freshly-built task's metadata to the right field: a multi-line
+ * `context` is the agent prompt, so it moves to `prompt`.
+ *
+ * Applied at CREATE only (`cosTaskStore.addTask`), never on update — the task
+ * editor's textarea is seeded from the NOTE, and re-classifying a multi-line
+ * edit of it would overwrite the task's real prompt. Producers that already
+ * write `metadata.prompt` are left alone, so an explicit split always wins over
+ * the inference.
+ *
+ * Returns the same object when nothing moved; otherwise a shallow clone (never
+ * mutates the caller's metadata).
+ */
+export function splitTaskPromptFields(metadata) {
+ if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) return metadata;
+ if (typeof metadata[TASK_PROMPT_KEY] === 'string') return metadata;
+ if (!isPromptPayload(metadata[TASK_CONTEXT_KEY])) return metadata;
+ const { [TASK_CONTEXT_KEY]: payload, ...rest } = metadata;
+ return { ...rest, [TASK_PROMPT_KEY]: payload };
+}
diff --git a/server/lib/cosTaskPrompt.test.js b/server/lib/cosTaskPrompt.test.js
new file mode 100644
index 0000000000..c527a95d20
--- /dev/null
+++ b/server/lib/cosTaskPrompt.test.js
@@ -0,0 +1,103 @@
+import { describe, it, expect } from 'vitest';
+import {
+ TASK_PROMPT_KEY,
+ TASK_CONTEXT_KEY,
+ isPromptPayload,
+ getTaskPrompt,
+ getTaskContextNote,
+ taskContextBlock,
+ splitTaskPromptFields,
+} from './cosTaskPrompt.js';
+
+const AGENT_BODY = 'Ship the thing\n\n## Phase 1\nRead the repo.';
+
+describe('isPromptPayload', () => {
+ it('classifies a multi-line value as a prompt', () => {
+ expect(isPromptPayload(AGENT_BODY)).toBe(true);
+ });
+
+ it('classifies a one-line note as NOT a prompt', () => {
+ expect(isPromptPayload('Manually triggered autonomous job: nightly')).toBe(false);
+ });
+
+ it('treats an intentionally-cleared note as a note, not a prompt', () => {
+ // Absent vs present-but-empty: '' is a cleared NOTE and must stay one.
+ expect(isPromptPayload('')).toBe(false);
+ expect(isPromptPayload(undefined)).toBe(false);
+ expect(isPromptPayload(null)).toBe(false);
+ });
+});
+
+describe('getTaskPrompt', () => {
+ it('prefers metadata.prompt', () => {
+ const task = { metadata: { [TASK_PROMPT_KEY]: AGENT_BODY, [TASK_CONTEXT_KEY]: 'a note' } };
+ expect(getTaskPrompt(task)).toBe(AGENT_BODY);
+ });
+
+ it('falls back to a legacy metadata.context payload', () => {
+ expect(getTaskPrompt({ metadata: { [TASK_CONTEXT_KEY]: AGENT_BODY } })).toBe(AGENT_BODY);
+ });
+
+ it('distinguishes an absent field from a present-but-empty one', () => {
+ expect(getTaskPrompt({ metadata: {} })).toBeNull();
+ expect(getTaskPrompt({})).toBeNull();
+ expect(getTaskPrompt(null)).toBeNull();
+ expect(getTaskPrompt({ metadata: { [TASK_PROMPT_KEY]: '' } })).toBe('');
+ });
+});
+
+describe('getTaskContextNote', () => {
+ it('returns the note only once the task is split', () => {
+ const task = { metadata: { [TASK_PROMPT_KEY]: AGENT_BODY, [TASK_CONTEXT_KEY]: 'a note' } };
+ expect(getTaskContextNote(task)).toBe('a note');
+ });
+
+ it('returns null on a legacy task so the payload is not rendered twice', () => {
+ expect(getTaskContextNote({ metadata: { [TASK_CONTEXT_KEY]: AGENT_BODY } })).toBeNull();
+ });
+});
+
+describe('taskContextBlock', () => {
+ it('renders prompt then note', () => {
+ const task = { metadata: { [TASK_PROMPT_KEY]: AGENT_BODY, [TASK_CONTEXT_KEY]: 'a note' } };
+ expect(taskContextBlock(task)).toBe(`${AGENT_BODY}\n\na note`);
+ });
+
+ it('renders a legacy context-as-prompt unchanged', () => {
+ expect(taskContextBlock({ metadata: { [TASK_CONTEXT_KEY]: AGENT_BODY } })).toBe(AGENT_BODY);
+ });
+
+ it('returns null when the task carries neither', () => {
+ expect(taskContextBlock({ metadata: {} })).toBeNull();
+ expect(taskContextBlock({ metadata: { [TASK_PROMPT_KEY]: ' ' } })).toBeNull();
+ });
+});
+
+describe('splitTaskPromptFields', () => {
+ it('moves a multi-line context to prompt', () => {
+ const out = splitTaskPromptFields({ [TASK_CONTEXT_KEY]: AGENT_BODY, app: 'a1' });
+ expect(out).toEqual({ [TASK_PROMPT_KEY]: AGENT_BODY, app: 'a1' });
+ });
+
+ it('leaves a one-line note alone', () => {
+ const metadata = { [TASK_CONTEXT_KEY]: 'short note' };
+ expect(splitTaskPromptFields(metadata)).toBe(metadata);
+ });
+
+ it('never overwrites an explicit prompt', () => {
+ const metadata = { [TASK_PROMPT_KEY]: 'explicit', [TASK_CONTEXT_KEY]: AGENT_BODY };
+ expect(splitTaskPromptFields(metadata)).toBe(metadata);
+ });
+
+ it('does not mutate the caller metadata', () => {
+ const metadata = { [TASK_CONTEXT_KEY]: AGENT_BODY };
+ splitTaskPromptFields(metadata);
+ expect(metadata[TASK_CONTEXT_KEY]).toBe(AGENT_BODY);
+ expect(metadata[TASK_PROMPT_KEY]).toBeUndefined();
+ });
+
+ it('passes through a non-object', () => {
+ expect(splitTaskPromptFields(null)).toBeNull();
+ expect(splitTaskPromptFields([1])).toEqual([1]);
+ });
+});
diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.js
index 279502630b..093736dd57 100644
--- a/server/lib/cosValidation.js
+++ b/server/lib/cosValidation.js
@@ -964,7 +964,11 @@ export const createCosTaskSchema = z.object({
description: z.string().min(1),
diagnostics: cosTaskDiagnosticsSchema.optional(),
priority: z.string().optional(),
+ // `context` is the one-line human note; `prompt` is the full agent-facing
+ // payload (#4153). A producer that passes a multi-line `context` is still
+ // accepted — `cosTaskStore.addTask` routes it to `metadata.prompt`.
context: z.string().optional(),
+ prompt: z.string().optional(),
model: z.string().optional(),
provider: z.string().optional(),
effort: effortInputSchema,
@@ -1074,6 +1078,7 @@ export const updateCosTaskSchema = z.object({
priority: z.string().optional(),
status: z.string().optional(),
context: z.string().optional(),
+ prompt: z.string().optional(),
model: z.string().optional(),
provider: z.string().optional(),
effort: effortUpdateSchema,
diff --git a/server/lib/index.js b/server/lib/index.js
index 157d679642..822e3d1449 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -235,6 +235,7 @@ export * from './vectorMath.js';
export * from './htmlToText.js';
export * from './jsonExtract.js';
export * from './taskParser.js';
+export * from './cosTaskPrompt.js';
export * from './taskPauseHold.js';
export * from './taskBlockCategories.js';
export * from './taskRequeue.js';
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index 12403ff6c5..1b1792539a 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -547,7 +547,18 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// reviewer CLI's default effort instead of the pinned tier, silently downgrading
// a review the user deliberately strengthened. Per-category gate → only cos-tasks
// sync pauses until the peer upgrades.
- cosTasks: 4,
+ // v5 = the `metadata.prompt` / `metadata.context` split (#4153): the full
+ // agent-facing payload now rides `prompt` and `context` reverts to the
+ // one-line human note. Same EXECUTION-semantics break as v3/v4 — `prompt`
+ // rides the permissive `metadata` map, so a ≤v4 receiver validates and stores
+ // the task fine and then MIS-RUNS it: its prompt builder only knows
+ // `metadata.context`, so the agent is handed a one-line description with the
+ // entire Phase 1–7 body (or `/do:*` claim prompt) missing, does the wrong
+ // work, and LWW-pushes that damaged state back onto the v5 peer. Readers on
+ // v5 fall back to `metadata.context`, so the reverse direction degrades
+ // gracefully — the gate exists for the forward one. Per-category gate → only
+ // cos-tasks sync pauses until the peer upgrades.
+ cosTasks: 5,
// NOTE: `videoHistory` is intentionally NOT listed here. The version gate
// rejects the ENTIRE snapshot/push payload on ANY ahead-mismatch (the
// comparator walks the union of keys), so declaring a brand-new key would
diff --git a/server/lib/taskParser.test.js b/server/lib/taskParser.test.js
index 28e58ae387..c8f64526d7 100644
--- a/server/lib/taskParser.test.js
+++ b/server/lib/taskParser.test.js
@@ -352,6 +352,21 @@ describe('Task Parser', () => {
expect(parsed[0].metadata.context).toBe(multiLineContext);
});
+ // #4153 — the agent-facing payload moved from `metadata.context` to
+ // `metadata.prompt`. Round-trip safety is the whole reason it lives in
+ // metadata rather than `description`, so pin it for the new key too.
+ it('should round-trip a multi-line metadata.prompt alongside a one-line metadata.context', () => {
+ const prompt = 'Ship the thing\n\n## Phase 1\n- Read PLAN.md\n- [ ] not a task line';
+ const markdown = generateTasksMarkdown([
+ { id: 'task-001', status: 'pending', priority: 'MEDIUM', priorityValue: 2, description: 'Ship the thing', metadata: { prompt, context: 'a short note' } }
+ ]);
+ // The embedded `- [ ]` and `##` lines must NOT become a task/section.
+ const parsed = parseTasksMarkdown(markdown);
+ expect(parsed).toHaveLength(1);
+ expect(parsed[0].metadata.prompt).toBe(prompt);
+ expect(parsed[0].metadata.context).toBe('a short note');
+ });
+
it('should round-trip array and object metadata values (screenshots, attachments, reviewers)', () => {
const tasks = [
{
diff --git a/server/routes/cos.test.js b/server/routes/cos.test.js
index 807c939732..b5b7c8c2b3 100644
--- a/server/routes/cos.test.js
+++ b/server/routes/cos.test.js
@@ -1082,10 +1082,12 @@ describe('CoS Routes', () => {
// The raw do:next body must NOT be inlined for the next command.
expect(loadSlashdoCommand).not.toHaveBeenCalledWith('next');
const [taskData] = cos.addTask.mock.calls.at(-1);
- expect(taskData.context).toBe('CLAIM ISSUE PROMPT');
+ // The claim body is the agent PROMPT, not the one-line human note (#4153).
+ expect(taskData.prompt).toBe('CLAIM ISSUE PROMPT');
+ expect(taskData.context).toBeUndefined();
expect(taskData.description).toContain('GitHub Issues');
// `next` is the one genuinely special command: its claim prompt IS the
- // context, so it must NOT also carry a slashdoCommand (which would make the
+ // task prompt, so it must NOT also carry a slashdoCommand (which would make the
// prompt builder append the whole /do:next body on top of the claim prompt).
expect(taskData.slashdoCommand).toBeUndefined();
expect(taskData.description).not.toContain('/do:');
@@ -1251,10 +1253,10 @@ describe('CoS Routes', () => {
const [taskData, taskType] = cos.addTask.mock.calls.at(-1);
expect(taskType).toBe('user');
// Placeholders substituted, ticket constraint appended.
- expect(taskData.context).toContain('Work MyApp at /repo (app my-app); reviewers: claude.');
- expect(taskData.context).not.toMatch(/\{appName\}|\{repoPath\}|\{appId\}|\{reviewers\}/);
- expect(taskData.context).toContain('Target Ticket Constraint');
- expect(taskData.context).toContain('PROJ-123');
+ expect(taskData.prompt).toContain('Work MyApp at /repo (app my-app); reviewers: claude.');
+ expect(taskData.prompt).not.toMatch(/\{appName\}|\{repoPath\}|\{appId\}|\{reviewers\}/);
+ expect(taskData.prompt).toContain('Target Ticket Constraint');
+ expect(taskData.prompt).toContain('PROJ-123');
expect(taskData.description).toContain('PROJ-123');
// claim-issue-jira self-manages its worktree + PR.
expect(taskData.useWorktree).toBe(false);
@@ -1274,7 +1276,7 @@ describe('CoS Routes', () => {
expect(response.status).toBe(200);
const [taskData] = cos.addTask.mock.calls.at(-1);
expect(taskData.description).toContain('PROJ-7');
- expect(taskData.context).toContain('PROJ-7');
+ expect(taskData.prompt).toContain('PROJ-7');
});
it('returns 404 for an unknown app', async () => {
diff --git a/server/routes/cosTaskRoutes.js b/server/routes/cosTaskRoutes.js
index 467e84cf39..658374243b 100644
--- a/server/routes/cosTaskRoutes.js
+++ b/server/routes/cosTaskRoutes.js
@@ -156,7 +156,7 @@ router.post('/tasks/slashdo', asyncHandler(async (req, res) => {
// through the same workTracker-aware logic the scheduled `claim-work` flow
// uses, so the manual button honors the app's per-app Work Tracker (PLAN.md /
// GitHub / GitLab / JIRA) instead of always draining PLAN.md. Its assembled
- // claim prompt IS the context, so it carries NO `slashdoCommand` — adding one
+ // claim prompt IS the task prompt, so it carries NO `slashdoCommand` — adding one
// would append the whole `/do:next` body on top of the claim prompt.
// - Every other command carries only the bare `slashdoCommand` and lets the
// prompt builder render the invocation + inline the body once the provider is
@@ -183,7 +183,9 @@ router.post('/tasks/slashdo', asyncHandler(async (req, res) => {
: `claim next ${workTrackerLabel(claim.tracker)} item`;
shape = {
description: `${workflow.label} for ${appObj.name} — ${scope} and ship a PR`,
- context: claim.prompt,
+ // The claim body is the agent's PROMPT, not a human note (#4153) — see
+ // server/lib/cosTaskPrompt.js for the field split.
+ prompt: claim.prompt,
// claim.taskMetadata overrides the catalog posture only where it carries a
// key. All current claim flows (plan-task / claim-issue / claim-issue-gitlab
// / claim-issue-jira) self-manage their worktree + MR/PR, so false/false
@@ -207,7 +209,7 @@ router.post('/tasks/slashdo', asyncHandler(async (req, res) => {
const taskData = {
description: shape.description,
app,
- context: shape.context,
+ prompt: shape.prompt,
slashdoCommand: shape.slashdoCommand,
...shape.taskMetadata,
provider, model, effort,
@@ -247,7 +249,7 @@ router.post('/tasks/jira-ticket', asyncHandler(async (req, res) => {
const taskData = {
description: `Claim JIRA ticket ${key} for ${appObj.name} — implement and ship a PR`,
app,
- context: prompt,
+ prompt,
...taskMetadata,
simplify: false,
reviewLoop: false,
@@ -287,6 +289,7 @@ router.put('/tasks/:id', asyncHandler(async (req, res) => {
if (fields.priority !== undefined) updates.priority = fields.priority;
if (fields.status !== undefined) updates.status = fields.status;
if (fields.context !== undefined) updates.context = fields.context;
+ if (fields.prompt !== undefined) updates.prompt = fields.prompt;
if (fields.model !== undefined) updates.model = fields.model;
if (fields.provider !== undefined) updates.provider = fields.provider;
if (fields.effort !== undefined) updates.effort = fields.effort;
diff --git a/server/services/agentManagement.js b/server/services/agentManagement.js
index ae857d0bec..0ddfd0ca02 100644
--- a/server/services/agentManagement.js
+++ b/server/services/agentManagement.js
@@ -428,10 +428,13 @@ async function replacePausedTask({ agentId, task, taskType, overrides }) {
const description = overrides.description
|| task?.description
|| `Resume ${agentId}`;
- const { context, provider, model, effort, app } = task?.metadata || {};
+ // `prompt` rides along with `context` (#4153): on a task written by current
+ // code the agent-facing payload lives there, and a replacement queued without
+ // it would run with nothing but the one-line description.
+ const { context, prompt, provider, model, effort, app } = task?.metadata || {};
const created = await addTask({
description,
- context, provider, model, effort, app,
+ context, prompt, provider, model, effort, app,
...resumeOverrideMetadata(overrides, context)
}, taskType);
if (created?.error) {
@@ -446,9 +449,11 @@ async function replacePausedTask({ agentId, task, taskType, overrides }) {
* The dialog's edits as a task-metadata patch. Every field is "unchanged unless
* supplied" — the dialog seeds its selects from the paused run, so a blank value
* is absence rather than an intentional clear (CLAUDE.md's absent-vs-empty rule).
- * `context` APPENDS to `existingContext`: the task's own context is what the
+ * `context` APPENDS to `existingContext`: the task's own note is what the
* original run was given, and dropping it would resume with less information than
- * the run that paused.
+ * the run that paused. It never touches `metadata.prompt` — the dialog edits the
+ * NOTE, and folding a note into the agent-facing payload would make the two
+ * indistinguishable again (#4153).
*/
function resumeOverrideMetadata({ context, provider, model, effort, app, screenshots }, existingContext) {
const patch = {};
diff --git a/server/services/agentModelSelection.js b/server/services/agentModelSelection.js
index 1754802d50..d5eeccbfbc 100644
--- a/server/services/agentModelSelection.js
+++ b/server/services/agentModelSelection.js
@@ -10,6 +10,7 @@ import { suggestModelTier } from './taskLearning.js';
// Imported from the store submodule (not the mocked barrel) so the spawn-time key
// mirrors the exact same classification the completion records under.
import { classifyUntypedTask } from './taskLearning/store.js';
+import { taskContextBlock } from '../lib/cosTaskPrompt.js';
/**
* Extract task type key for learning lookup.
@@ -48,7 +49,9 @@ export function extractTaskTypeKey(task) {
*/
export async function selectModelForTask(task, provider, agent = {}) {
const desc = (task.description || '').toLowerCase();
- const context = task.metadata?.context || '';
+ // Prompt payload + human note (#4153) — complexity scales with everything the
+ // agent is handed, and a legacy `metadata.context`-as-prompt still counts.
+ const context = taskContextBlock(task) || '';
const contextLen = context.length;
const priority = task.priority || 'MEDIUM';
diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.js
index 5bfb2c49d7..df047e24f7 100644
--- a/server/services/agentPromptBuilder.js
+++ b/server/services/agentPromptBuilder.js
@@ -22,6 +22,7 @@ import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';
import { doneSentinelName } from '../lib/agentSentinel.js';
import { canTypeSlashCommands, agentOwnsPrWorkflow, resolveSlashdoInvocation, buildSlashdoSection, oversizedBodyPointer, unreachableReviewerIncludes, SLASHDO_INLINE_BUDGET_CHARS } from '../lib/slashdoInvocation.js';
import { shellQuote } from '../lib/shellQuote.js';
+import { TASK_PROMPT_KEY, TASK_CONTEXT_KEY, taskContextBlock } from '../lib/cosTaskPrompt.js';
import { detectForgeCli } from '../lib/gitForge.js';
import { PR_COMPLETIONS, leavesPrForHuman, resolvePrCompletion } from '../lib/prDisposition.js';
import * as jiraService from './jira.js';
@@ -378,32 +379,43 @@ function resolveTaskFileRef(ref) {
/**
* Undo the COS-TASKS.md round-trip split before rendering. The queue path in
* `cosTaskGenerator.js` persists a generated multi-line prompt by moving the
- * full body into `metadata.context` and keeping only its first line as
- * `description`, so the markdown stays one-line-per-task. Coming back out,
- * `context` therefore *leads with a verbatim copy* of `description` — and every
+ * full body into `metadata.prompt` (`metadata.context` before the #4153 split)
+ * and keeping only its first line as
+ * `description`, so the markdown stays one-line-per-task. Coming back out, the
+ * payload therefore *leads with a verbatim copy* of `description` — and every
* render path emits both (the task block, then the full body again under a
* `### Context` header). For a swarm task that surfaces as the reported
* double `# ⚡ SWARM MODE …` header; the same duplication hits any other
* generated/scheduled/system task that round-trips through the queue.
*
- * When the split signature is present (`context` is a string whose first
- * non-empty line equals `description`), fold `context` back into `description`
- * and drop the redundant `metadata.context` so the prompt renders once, as one
- * clean body with no spurious header. A genuinely-separate user-supplied
- * `context` (first line differs from `description`) is left untouched.
+ * When the split signature is present (the payload's first non-empty line
+ * equals `description`), fold it back into `description` and drop the redundant
+ * metadata key so the prompt renders once, as one clean body with no spurious
+ * header. A genuinely-separate user-supplied note (first line differs from
+ * `description`) is left untouched.
*
* Pure and idempotent: returns the same task when nothing matched, otherwise a
* shallow clone (never mutates the caller's task, so the stored task keeps its
* one-line `description` for the task-list UI).
*/
export function reconcileSplitContext(task) {
- const context = task?.metadata?.context;
- if (typeof context !== 'string' || typeof task.description !== 'string') return task;
- // Mirror firstLine() in cosTaskStore.js: first non-empty, trimmed line.
- const firstNonEmpty = context.split('\n').map(l => l.trim()).find(Boolean) || '';
- if (firstNonEmpty !== task.description.trim()) return task;
- const { context: _dropped, ...restMeta } = task.metadata;
- return { ...task, description: context, metadata: restMeta };
+ if (typeof task?.description !== 'string') return task;
+ const description = task.description.trim();
+ // `prompt` first: that is where the payload lives on a task written by
+ // current code (#4153). `context` stays in the loop so a task written before
+ // the split — or synced from a peer still on the old code — reconciles too.
+ // Only the key that CARRIED the payload is dropped, so a split task's short
+ // `metadata.context` note survives and still renders.
+ for (const key of [TASK_PROMPT_KEY, TASK_CONTEXT_KEY]) {
+ const payload = task.metadata?.[key];
+ if (typeof payload !== 'string') continue;
+ // Mirror firstLine() in cosTaskStore.js: first non-empty, trimmed line.
+ const firstNonEmpty = payload.split('\n').map(l => l.trim()).find(Boolean) || '';
+ if (firstNonEmpty !== description) continue;
+ const { [key]: _dropped, ...restMeta } = task.metadata;
+ return { ...task, description: payload, metadata: restMeta };
+ }
+ return task;
}
/**
@@ -1737,8 +1749,18 @@ ${task.metadata.jiraBranch ? 'Commit your changes to this branch. Do NOT switch
// template references — only the stock heading gates on this.
const briefingApp = task.metadata?.app;
const targetAppLabel = briefingApp && briefingApp !== PORTOS_APP_ID ? briefingApp : '';
+ // The task's prompt payload + human note as ONE string (#4153). Templates —
+ // the shipped `cos-agent-briefing.md` AND every copy an install has since
+ // customized — reference `{{task.metadata.context}}`, so the split is folded
+ // back into that key for rendering instead of being pushed out to every
+ // template on every install. `metadata.prompt` still travels untouched for a
+ // custom template that wants to address it directly.
+ const contextBlock = taskContextBlock(task);
+ const briefingTask = contextBlock === (task.metadata?.[TASK_CONTEXT_KEY] ?? null)
+ ? task
+ : { ...task, metadata: { ...task.metadata, [TASK_CONTEXT_KEY]: contextBlock } };
const promptData = isReviewLoopFollowUp ? null : await buildPrompt('cos-agent-briefing', {
- task,
+ task: briefingTask,
targetAppLabel,
config,
memorySection,
@@ -1771,7 +1793,7 @@ ${task.metadata.jiraBranch ? 'Commit your changes to this branch. Do NOT switch
${memorySection || ''}
${taskBlock.description}
-${task.metadata?.context ? (task.metadata.context.includes('\n') ? `\n### Task Context\n\n${task.metadata.context.trimEnd()}\n` : `\n### Task Context\n\n${task.metadata.context}\n`) : ''}
+${contextBlock ? (contextBlock.includes('\n') ? `\n### Task Context\n\n${contextBlock.trimEnd()}\n` : `\n### Task Context\n\n${contextBlock}\n`) : ''}
${taskBlock.targetApp}
${taskBlock.screenshots}
${taskBlock.attachments}
@@ -1975,7 +1997,9 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet
sections.push(taskBlock.description);
if (taskBlock.targetApp) sections.push(taskBlock.targetApp);
- const context = task.metadata?.context;
+ // The task's prompt payload + human note as one block (#4153), so the split is
+ // invisible here and a legacy `metadata.context`-as-prompt still renders.
+ const context = taskContextBlock(task);
if (context) {
sections.push(context.includes('\n')
? `### Context\n\n${context.trimEnd()}`
diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.js
index e8181ef902..d7d330531b 100644
--- a/server/services/agentPromptBuilder.test.js
+++ b/server/services/agentPromptBuilder.test.js
@@ -138,6 +138,32 @@ describe('reconcileSplitContext', () => {
const task = { description: 'Title', metadata: {} };
expect(reconcileSplitContext(task)).toBe(task);
});
+
+ // #4153 — the payload now lands in `metadata.prompt`; `metadata.context`
+ // stays supported so a pre-split task (or a peer still on the old code)
+ // reconciles the same way.
+ it('folds metadata.prompt back into description and keeps the separate note', () => {
+ const body = 'Line one is the title\n\nLine two is the body.';
+ const task = { description: 'Line one is the title', metadata: { prompt: body, context: 'a note', app: 'comics' } };
+ const out = reconcileSplitContext(task);
+ expect(out.description).toBe(body);
+ expect(out.metadata.prompt).toBeUndefined();
+ expect(out.metadata.context).toBe('a note'); // the note is NOT the payload
+ expect(out.metadata.app).toBe('comics');
+ });
+
+ it('prefers metadata.prompt over a same-shaped legacy context', () => {
+ const body = 'Title\n\nNew body.';
+ const legacy = 'Title\n\nOld body.';
+ const out = reconcileSplitContext({ description: 'Title', metadata: { prompt: body, context: legacy } });
+ expect(out.description).toBe(body);
+ expect(out.metadata.context).toBe(legacy);
+ });
+
+ it('leaves a genuinely-separate prompt untouched', () => {
+ const task = { description: 'Add a button', metadata: { prompt: 'Do the thing\nsomehow' } };
+ expect(reconcileSplitContext(task)).toBe(task);
+ });
});
describe('no-code / API-action task completion (CD agents must NOT be told to /do:push)', () => {
@@ -251,8 +277,20 @@ describe('buildLightContextPrompt', () => {
expect(multi).toMatch(/### Context\n\nline one\nline two/);
});
- it('does NOT double-render a queue-path split prompt (description == firstLine(context))', () => {
- // The queue path stores `description = firstLine(body)` + `context = body`
+ // #4153 — the agent-facing payload lives in `metadata.prompt`; a legacy
+ // `metadata.context` payload must keep rendering identically.
+ it('renders metadata.prompt, and the note after it', () => {
+ const promptOnly = buildLightContextPrompt(
+ makeTask({ metadata: { prompt: 'line one\nline two' } }), '/r', null, isTruthyMeta);
+ expect(promptOnly).toMatch(/### Context\n\nline one\nline two/);
+
+ const both = buildLightContextPrompt(
+ makeTask({ metadata: { prompt: 'line one\nline two', context: 'a short note' } }), '/r', null, isTruthyMeta);
+ expect(both).toMatch(/### Context\n\nline one\nline two\n\na short note/);
+ });
+
+ it('does NOT double-render a queue-path split prompt (description == firstLine(payload))', () => {
+ // The queue path stores `description = firstLine(body)` + the body
// so COS-TASKS.md stays one-line-per-task. Rendering both would print the
// first line twice (the reported double `# ⚡ SWARM MODE …` header).
const body = '# ⚡ SWARM MODE — claim and ship up to 3 independent issues in parallel\n\n**This run operates in slashdo mode.** Do the work.';
@@ -264,6 +302,14 @@ describe('buildLightContextPrompt', () => {
expect(prompt).not.toMatch(/### Context/);
// The full body still renders (nothing dropped).
expect(prompt).toMatch(/\*\*This run operates in slashdo mode\.\*\* Do the work\./);
+
+ // Same task written by post-#4153 code: payload in `metadata.prompt`.
+ const split = buildLightContextPrompt(
+ makeTask({ description: '# ⚡ SWARM MODE — claim and ship up to 3 independent issues in parallel', metadata: { prompt: body } }),
+ '/r', null, isTruthyMeta);
+ expect(split.match(/# ⚡ SWARM MODE/g)).toHaveLength(1);
+ expect(split).not.toMatch(/### Context/);
+ expect(split).toMatch(/\*\*This run operates in slashdo mode\.\*\* Do the work\./);
});
it('lists screenshot file paths so the agent can read them via its own tools', () => {
@@ -1575,6 +1621,29 @@ describe('buildAgentPrompt — provider type routing', () => {
expect(context.task.metadata.app).toBe('comics');
});
+ // #4153 — every shipped AND user-customized `cos-agent-briefing.md` addresses
+ // `{{task.metadata.context}}`. Folding the split back into that key at render
+ // time is what keeps the payload reaching the agent without pushing a template
+ // change (and a prompt migration) onto every install.
+ it('folds metadata.prompt into the briefing template\'s task.metadata.context', async () => {
+ vi.mocked(buildPrompt).mockClear();
+ await buildAgentPrompt(
+ makeTask({ metadata: { prompt: 'the agent body\nsecond line', context: 'a short note' } }),
+ {}, '/r', null, isTruthyMeta, { providerType: 'api' });
+ const [, context] = vi.mocked(buildPrompt).mock.calls.at(-1);
+ expect(context.task.metadata.context).toBe('the agent body\nsecond line\n\na short note');
+ // The raw field still travels for a custom template that addresses it.
+ expect(context.task.metadata.prompt).toBe('the agent body\nsecond line');
+ });
+
+ it('leaves a legacy context-only task untouched on the briefing template path', async () => {
+ vi.mocked(buildPrompt).mockClear();
+ const task = makeTask({ metadata: { context: 'legacy body\nsecond line' } });
+ await buildAgentPrompt(task, {}, '/r', null, isTruthyMeta, { providerType: 'api' });
+ const [, context] = vi.mocked(buildPrompt).mock.calls.at(-1);
+ expect(context.task.metadata.context).toBe('legacy body\nsecond line');
+ });
+
it('passes an empty targetAppLabel to the api-path briefing template for the PortOS default app', async () => {
vi.mocked(buildPrompt).mockClear();
await buildAgentPrompt(
diff --git a/server/services/cos.test.js b/server/services/cos.test.js
index bffd5a7da8..581486c3da 100644
--- a/server/services/cos.test.js
+++ b/server/services/cos.test.js
@@ -954,13 +954,15 @@ describe('cos.js source — priority + capacity invariants', () => {
// description onto a single `- [ ]` line and the parser only matches the
// first line, so persisting a multi-line description corrupts the file
// AND truncates the prompt on the next `dequeueNextTask` re-read. The
- // queue path must move the body to `metadata.context` (which IS
+ // queue path must move the body to `metadata.prompt` (which IS
// newline-escaped) so the agent prompt builder reconstitutes it on
- // dispatch. Pin both halves of the split.
+ // dispatch. `prompt`, not `context` — the two were split in #4153 so a
+ // multi-thousand-character agent payload is distinguishable from the
+ // one-line human note. Pin both halves of the split.
expect(
fnBody,
- 'queue path must move multi-line description body to metadata.context (survives markdown round-trip)'
- ).toMatch(/metadata\.context\s*=\s*\w+\.description/);
+ 'queue path must move multi-line description body to metadata.prompt (survives markdown round-trip)'
+ ).toMatch(/metadata\.prompt\s*=\s*\w+\.description/);
expect(
fnBody,
'queue path must collapse description to a single line via firstLine()'
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index 27dee4ef36..b5c16fd4f5 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -1613,7 +1613,7 @@ export async function queueEligibleImprovementTasks(state, cosTaskData, { ignore
task.priorityValue = PRIORITY_VALUES.LOW;
task.id = `sys-${app.id.slice(0, 8)}-${nextType}-${Date.now().toString(36)}`;
- // Move the generator's multi-line prompt into `metadata.context` so it
+ // Move the generator's multi-line prompt into `metadata.prompt` so it
// survives the COS-TASKS.md round-trip. The on-demand path dispatches the
// in-memory task immediately (cosEvents.emit('task:ready', task) with the
// unparsed object), so it never round-trips through the markdown — but
@@ -1623,16 +1623,22 @@ export async function queueEligibleImprovementTasks(state, cosTaskData, { ignore
// `parseTasksMarkdown` only matches the first line of a `- [ ]` block —
// so any newline in `description` corrupts the file (stray `## Phase`
// lines become section headers, `- ` lines become new tasks) AND silently
- // strips the Phase 1–7 instructions on the re-read. `metadata.context` is
+ // strips the Phase 1–7 instructions on the re-read. Task metadata is
// newline-escaped via `escapeNewlines`/`unescapeNewlines` (JSON-sentinel
// encoding) so it round-trips losslessly. The agent prompt builder
// (`cos-agent-briefing.md` + the built-in fallback in
- // `agentPromptBuilder.js`) renders both `task.description` AND
- // `task.metadata.context` into the agent's prompt, so the agent still
- // sees the full Phase 1–7 body.
+ // `agentPromptBuilder.js`) renders both `task.description` AND the task's
+ // context block into the agent's prompt, so the agent still sees the full
+ // Phase 1–7 body.
+ //
+ // The payload lands in `metadata.prompt`, NOT `metadata.context` (#4153):
+ // `context` is the one-line human note, and overloading it made a
+ // multi-thousand-character agent prompt indistinguishable from one. Readers
+ // go through `getTaskPrompt` (server/lib/cosTaskPrompt.js), which falls back
+ // to `metadata.context` for tasks written before the split.
if (typeof task.description === 'string' && task.description.includes('\n')) {
task.metadata = task.metadata || {};
- task.metadata.context = task.description;
+ task.metadata.prompt = task.description;
task.description = firstLine(task.description);
}
diff --git a/server/services/cosTaskMerge.js b/server/services/cosTaskMerge.js
index e5fd9ff5e5..87d15b8b75 100644
--- a/server/services/cosTaskMerge.js
+++ b/server/services/cosTaskMerge.js
@@ -239,8 +239,10 @@ function pickContentBase(local, remote) {
const rp = PRIORITY_VALUES[remote.priority] || 0;
if (lp !== rp) return rp > lp ? remote : local;
// Same status + priority: break the tie over ALL remaining editable content
- // (description, approval flags, AND non-claim metadata — `app`, `context`,
- // `reviewers`, `useWorktree`, … which all affect how a task is spawned) via a
+ // (description, approval flags, AND non-claim metadata — `app`, `prompt`,
+ // `context`, `reviewers`, `useWorktree`, … which all affect how a task is
+ // spawned; `contentSignature` walks every non-claim key, so the #4153
+ // prompt/note split needs no special case here) via a
// canonical, side-independent signature so a content-only edit converges.
// Claim metadata is excluded — it's resolved separately by lease in resolveClaim.
const ls = contentSignature(local);
diff --git a/server/services/cosTaskMerge.test.js b/server/services/cosTaskMerge.test.js
index e44906e7bb..07aeeb92af 100644
--- a/server/services/cosTaskMerge.test.js
+++ b/server/services/cosTaskMerge.test.js
@@ -174,6 +174,27 @@ describe('mergeTaskLists', () => {
expect(fromA.metadata.context).toBe(fromB.metadata.context);
});
+ // #4153 — the prompt/note split adds a metadata key; `contentSignature` walks
+ // every non-claim key, so it must converge with no special case, and a peer
+ // still holding the payload under `context` must not lose it.
+ it('converges on a same-status metadata.prompt edit', () => {
+ const a = [task('task-1', 'pending', { metadata: { prompt: 'body-A\nmore' } })];
+ const b = [task('task-1', 'pending', { metadata: { prompt: 'body-B\nmore' } })];
+ const [fromA] = mergeTaskLists(a, b, { now: NOW });
+ const [fromB] = mergeTaskLists(b, a, { now: NOW });
+ expect(fromA.metadata.prompt).toBe(fromB.metadata.prompt);
+ });
+
+ it('keeps the freshest side whole when one peer is split and the other is legacy', () => {
+ const split = task('task-1', 'pending', { metadata: { prompt: 'body\nmore', updatedAt: future(5000) } });
+ const legacy = task('task-1', 'pending', { metadata: { context: 'body\nmore', updatedAt: past(5000) } });
+ const [fromSplit] = mergeTaskLists([split], [legacy], { now: NOW });
+ const [fromLegacy] = mergeTaskLists([legacy], [split], { now: NOW });
+ expect(fromSplit.metadata.prompt).toBe('body\nmore');
+ expect(fromSplit.metadata.context).toBeUndefined();
+ expect(fromLegacy.metadata.prompt).toBe('body\nmore');
+ });
+
it('newest-edit-wins: larger updatedAt wins a same-status tie, regardless of initiator', () => {
// Same pending status; the fresher edit (larger updatedAt) is authoritative
// even though it carries the LOWER priority — the #1714 upgrade over the
diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.js
index 02bcb1f2ee..ef031aaba6 100644
--- a/server/services/cosTaskStore.js
+++ b/server/services/cosTaskStore.js
@@ -24,6 +24,7 @@ import { AGENT_PAUSED_CATEGORY, PAUSE_METADATA_KEYS, isAgentPausedTask, resolveP
import { REQUEUED_AT_KEY } from '../lib/taskRequeue.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 { loadState, withStateLock, ROOT_DIR } from './cosState.js';
import { cosEvents } from './cosEvents.js';
import { CLAIM_METADATA_KEYS } from './cosTaskClaim.js';
@@ -60,10 +61,13 @@ export { PAUSED_BLOCKED_CATEGORIES };
// both are legitimate execution outcomes worth recording).
const isTerminalTaskStatus = (status) => status === 'completed' || status === 'blocked';
-// Legacy fields an `updateTask` patch may carry directly (vs nested under
-// `metadata`); they're normalized into `metadata` on write. Listed once so the
-// content-edit detector and the normalizer below can't drift apart.
-const LEGACY_DIRECT_FIELDS = ['context', 'model', 'provider', 'effort', 'app'];
+// Fields an `updateTask` patch may carry directly (vs nested under `metadata`);
+// they're normalized into `metadata` on write. Listed once so the content-edit
+// detector and the normalizer below can't drift apart. `prompt` joined the list
+// with the #4153 split so the task editor can edit the agent-facing payload the
+// same way it edits the human note — deliberately WITHOUT re-classification, so
+// a multi-line note edit can't overwrite the payload (see `splitTaskPromptFields`).
+const LEGACY_DIRECT_FIELDS = ['context', 'prompt', 'model', 'provider', 'effort', 'app'];
// Equality for metadata values across a fresh markdown re-parse: primitives by
// ===, arrays/objects (reviewers[], screenshots[], …) by JSON since the two
@@ -318,6 +322,10 @@ export async function addTask(taskData, taskType = 'user', { raw = false, ignore
// Build metadata object
const metadata = {};
if (taskData.context) metadata.context = taskData.context;
+ // The full agent-facing payload, when the producer names it explicitly
+ // (#4153). Producers that still pass a multi-line `context` are classified
+ // by `splitTaskPromptFields` below, so both call shapes converge.
+ if (taskData.prompt) metadata.prompt = taskData.prompt;
if (taskData.model) metadata.model = taskData.model;
if (taskData.provider) metadata.provider = taskData.provider;
if (taskData.effort) metadata.effort = taskData.effort;
@@ -491,6 +499,18 @@ export async function addTask(taskData, taskType = 'user', { raw = false, ignore
};
}
+ // Route a multi-line context payload to `metadata.prompt` (#4153). Applied to
+ // BOTH branches — the raw path is how the generator, the reference-watch
+ // analysis, and the repo-study filer queue their pre-built tasks, and they
+ // carry the same kind of multi-thousand-character body the direct-write path
+ // does. One classification, at CREATE only: `updateTask` deliberately leaves
+ // both fields alone, because the task editor's textarea is seeded from the
+ // NOTE and re-classifying a multi-line edit of it would overwrite the task's
+ // real prompt. A producer that already wrote `metadata.prompt` wins over the
+ // inference. See `server/lib/cosTaskPrompt.js` for the full contract.
+ const splitMetadata = splitTaskPromptFields(newTask.metadata);
+ if (splitMetadata !== newTask.metadata) newTask = { ...newTask, metadata: splitMetadata };
+
// Add task to top or bottom based on position parameter
if (taskData.position === 'top') {
tasks.unshift(newTask);
diff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.js
index 0a58cecd5f..83feea3d6b 100644
--- a/server/services/cosTaskStore.test.js
+++ b/server/services/cosTaskStore.test.js
@@ -323,6 +323,74 @@ describe('cosTaskStore.addTask', () => {
expect(mock.events.some(e => e.name === 'tasks:changed' && e.payload.action === 'added' && e.payload.type === 'user')).toBe(true);
});
+ describe('prompt / context split (#4153)', () => {
+ const AGENT_BODY = 'Improve Example App\n\n## Phase 1\nRead PLAN.md.';
+
+ it('routes a multi-line context payload to metadata.prompt and round-trips it through markdown', async () => {
+ const created = await addTask({ description: 'Improve Example App', id: 'task-split', context: AGENT_BODY }, 'user');
+ expect(created.metadata.prompt).toBe(AGENT_BODY);
+ expect(created.metadata.context).toBeUndefined();
+ const reloaded = await getTaskById('task-split');
+ expect(reloaded.metadata.prompt).toBe(AGENT_BODY);
+ expect(reloaded.metadata.context).toBeUndefined();
+ });
+
+ it('leaves a one-line human note on metadata.context', async () => {
+ const created = await addTask({ description: 'job', id: 'task-note', context: 'Manually triggered job: nightly' }, 'user');
+ expect(created.metadata.context).toBe('Manually triggered job: nightly');
+ expect(created.metadata.prompt).toBeUndefined();
+ });
+
+ it('accepts an explicit prompt alongside a note and never re-classifies it', async () => {
+ const created = await addTask(
+ { description: 'claim', id: 'task-explicit', prompt: AGENT_BODY, context: 'one-line note' },
+ 'user'
+ );
+ expect(created.metadata.prompt).toBe(AGENT_BODY);
+ expect(created.metadata.context).toBe('one-line note');
+ });
+
+ // The generator, the reference-watch filer and the repo-study filer all queue
+ // pre-built (raw) tasks carrying the same multi-thousand-character body.
+ it('classifies a raw pre-built task too, without mutating the caller object', async () => {
+ const raw = {
+ id: 'sys-raw',
+ status: 'pending',
+ priority: 'LOW',
+ priorityValue: 1,
+ description: 'Improve Example App',
+ autoApproved: true,
+ metadata: { context: AGENT_BODY, app: 'a1' },
+ section: 'pending',
+ };
+ const created = await addTask(raw, 'internal', { raw: true });
+ expect(created.metadata.prompt).toBe(AGENT_BODY);
+ expect(created.metadata.context).toBeUndefined();
+ expect(created.metadata.app).toBe('a1');
+ expect(raw.metadata.context).toBe(AGENT_BODY); // caller's object untouched
+ });
+
+ // The task editor's textarea is seeded from the NOTE; re-classifying a
+ // multi-line edit of it would silently overwrite the task's real prompt.
+ it('does NOT re-classify on update — a multi-line note edit stays a note', async () => {
+ await addTask({ description: 'claim', id: 'task-edit', prompt: AGENT_BODY, context: 'note' }, 'user');
+ const updated = await updateTask('task-edit', { context: 'note\nsecond line' }, 'user');
+ expect(updated.metadata.context).toBe('note\nsecond line');
+ expect(updated.metadata.prompt).toBe(AGENT_BODY);
+ });
+
+ 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');
+ await addTask({ description: 'claim', id: 'task-prompt-edit', prompt: AGENT_BODY }, 'user', { now: T0 });
+ const edited = await updateTask('task-prompt-edit', { prompt: 'rewritten\nbody' }, 'user', { now: T1 });
+ expect(edited.metadata.prompt).toBe('rewritten\nbody');
+ expect(edited.metadata.updatedAt).toBe(new Date(T1).toISOString());
+ const cleared = await updateTask('task-prompt-edit', { prompt: '' }, 'user');
+ expect(cleared.metadata.prompt).toBe('');
+ });
+ });
+
it('persists structured auto-fix diagnostics into metadata and round-trips them through markdown (#2328)', async () => {
const diagnostics = {
triggerEvent: 'AI_PROVIDER_EXECUTION_FAILED',
diff --git a/server/services/referenceRepos.js b/server/services/referenceRepos.js
index 990265ef76..ce3e3d22c8 100644
--- a/server/services/referenceRepos.js
+++ b/server/services/referenceRepos.js
@@ -652,6 +652,9 @@ export async function triggerReferenceAnalysis(app, ref, snapshot) {
// Without this the TUI idle reaper records a run that did its whole job as
// `idle-no-changes` failure (#3102).
worktreeChangesExpected: isFileTracker(workTracker.resolved),
+ // A multi-line payload here is the agent PROMPT, not the one-line human
+ // note — `cosTaskStore.addTask` routes it to `metadata.prompt` on write
+ // (#4153, server/lib/cosTaskPrompt.js).
context: fullPrompt,
},
autoApproved: true,
diff --git a/server/services/repoIntake.js b/server/services/repoIntake.js
index 1e7ee6c2a0..d7d4ea6dcb 100644
--- a/server/services/repoIntake.js
+++ b/server/services/repoIntake.js
@@ -69,6 +69,8 @@ Use that path as SCAN_DIR. Adhere to every Operational Invariant in the workflow
const result = await cos.addTask(
{
description: `Malware scan: ${repoLabel(link)}`,
+ // Multi-line ⇒ the agent PROMPT: `cosTaskStore.addTask` routes it to
+ // `metadata.prompt` on write (#4153, server/lib/cosTaskPrompt.js).
context,
slashdoCommand: 'scan',
slashdoArgs: `--report-path-allow-anywhere --report-path ${JSON.stringify(reportPath)}`,
diff --git a/server/services/sharing/cosTasksSync.test.js b/server/services/sharing/cosTasksSync.test.js
index df5f69b912..695e75007e 100644
--- a/server/services/sharing/cosTasksSync.test.js
+++ b/server/services/sharing/cosTasksSync.test.js
@@ -69,7 +69,7 @@ describe('buildCosTasksPayload', () => {
vi.mocked(getUserTasks).mockResolvedValue({ tasks: [task('task-a', 'pending')] });
vi.mocked(getCosTasks).mockResolvedValue({ tasks: [task('sys-b', 'in_progress', { metadata: { claimedBy: 'i1' } })] });
const p = await buildCosTasksPayload();
- expect(p.schemaVersion).toBe(4); // v4: workTracker dispatch marker + reviewerEfforts pins
+ expect(p.schemaVersion).toBe(5); // v5: metadata.prompt / metadata.context split (#4153)
expect(p.listHash).toMatch(/^[a-f0-9]{64}$/);
expect(p.tasks).toHaveLength(2);
const user = p.tasks.find((t) => t.id === 'task-a');
@@ -104,7 +104,7 @@ describe('buildCosTasksPayload', () => {
it('returns an empty payload when there are no tasks', async () => {
const p = await buildCosTasksPayload();
expect(p.tasks).toEqual([]);
- expect(p.schemaVersion).toBe(4); // v4: workTracker dispatch marker + reviewerEfforts pins
+ expect(p.schemaVersion).toBe(5); // v5: metadata.prompt / metadata.context split (#4153)
});
});