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: stop an unknown task status or priority from deleting the task (#7239)
[._.]/ Adam Eivydb89f88450f5
diff --git a/server/lib/README.md b/server/lib/README.mdindex 1fc558da93..e4b10683ca 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -421,7 +421,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and| `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. `extractNonPlaceholderJson(raw, { field })` skips echoed schema placeholders and distinguishes placeholder-only from parse failures. `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). || `streamJsonParser.js` | Stream-JSON parser for Claude CLI `--output-format stream-json`. `createStreamJsonParser()` returns a stateful parser with `processChunk`/`flush`/`getFinalResult` that extracts human-readable lines from streaming NDJSON events (text deltas, tool-use markers, tool input summaries, intermediate assistant results). Also exports `summarizeToolInput(toolName, input)` for concise tool-call descriptions and `safeParse(str)` as a plain `JSON.parse` try/catch. Shared by `cos-runner/index.js` and `services/agentCliSpawning.js`. |-| `taskParser.js` | Parse `TASKS.md` format. |+| `taskParser.js` | Parse and generate the `TASKS.md` format, and own the vocabularies it can represent: `TASK_STATUS_VALUES` / `TASK_PRIORITY_VALUES` (derived from `STATUS_MAP` / `PRIORITY_VALUES`, read by `cosValidation.js` and `peerSyncValidation.js` so the HTTP and wire enums cannot drift from the store), plus `UNKNOWN_STATUS_BLOCKED_CATEGORY` — the marker `generateTasksMarkdown` stamps when it REPAIRS an unrepresentable task instead of dropping its row (#7239). || `taskGenerationOverrides.js` | `applyTaskGenerationOverrides(provider, metadata)` — the per-RUN `temperature` / `thinking` / `effort` a task form or schedule entry pins, layered onto a COPY of the provider record (the saved record is shared by every other run; the child-env composer turns the copy into OpenCode’s dynamic `agent.build` config downstream). Every value arrives untrusted — a COS-TASKS.md round-trip hands back strings — so each override applies only when it validates, and an empty temperature field is absent rather than `0`, which would otherwise pin greedy decoding on a task whose author just cleared the box. || `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. |diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.jsindex 5a0410b7ba..0620b82292 100644--- a/server/lib/cosValidation.js+++ b/server/lib/cosValidation.js@@ -18,6 +18,7 @@ import { QUEUEABLE_IMAGE_MODES } from './generationModes.js';import { PUBLIC_REVIEW_EXECUTION_PROFILES } from './agentExecutionProfiles.js';import { ORCHESTRATION_MODES, ORCHESTRATION_ROLES } from './orchestrationProfile.js';import { AGENT_RUN_EVENT_KINDS, RUN_EVENT_READ_LIMITS } from './agentRunEvents.js';+import { TASK_STATUS_VALUES, TASK_PRIORITY_VALUES } from './taskParser.js';import { recurrenceRuleSchema } from './recurrenceValidation.js';import { JOB_INTERVAL_VALUES } from './autonomousJobIntervals.js';import { TASK_DATA_INPUT_DEFINITIONS, TASK_DATA_INPUT_IDS } from './taskDataInputCatalog.js';@@ -160,13 +161,36 @@ const orchestrationModeUpdateSchema = z.preprocess(emptyToNull, z.enum(ORCHESTRAconst reviewerSchema = z.string().refine(isReviewer, 'Unknown reviewer');+// Priority and status are bounded by what TASKS.md can REPRESENT, not by a free+// string. The markdown store is the only copy of a queued task, and a value+// outside these vocabularies used to delete the task and its `metadata.prompt`+// on the next full-file rewrite — a 200 response for irreversible data loss+// (#7239). `generateTasksMarkdown` now repairs rather than drops, but the+// request that would have caused it belongs at the boundary as a 400.+//+// Case-insensitive with a trim, because real callers already send `'high'`+// (apps/tabs/GitTab.jsx, GitRecoveryAction.jsx) alongside `'MEDIUM'`; an empty+// string is the form's unset and stays absent rather than becoming a rejection.+const normalizeEnumInput = transform => value =>+ typeof value === 'string' ? (transform(value.trim()) || undefined) : value;++const taskPriorityInputSchema = z.preprocess(+ normalizeEnumInput(v => v.toUpperCase()),+ z.enum(TASK_PRIORITY_VALUES).optional()+);++const taskStatusInputSchema = z.preprocess(+ normalizeEnumInput(v => v.toLowerCase()),+ z.enum(TASK_STATUS_VALUES).optional()+);+// The metadata-bound fields below are carried onto the task by// `services/cosTaskIntake.js#buildTaskMetadata`; its test fails when a field is// added here without a mapping there (or an explicit non-metadata verdict).export const createCosTaskSchema = z.object({description: z.string().min(1),diagnostics: cosTaskDiagnosticsSchema.optional(),- priority: z.string().optional(),+ priority: taskPriorityInputSchema,// `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`.@@ -307,8 +331,8 @@ export const createCosTaskSchema = z.object({export const updateCosTaskSchema = z.object({description: z.string().min(1).optional(),- priority: z.string().optional(),- status: z.string().optional(),+ priority: taskPriorityInputSchema,+ status: taskStatusInputSchema,context: z.string().optional(),prompt: z.string().optional(),model: z.string().optional(),diff --git a/server/lib/cosValidation.test.js b/server/lib/cosValidation.test.jsindex fcc5f5449b..0cef1f2ed6 100644--- a/server/lib/cosValidation.test.js+++ b/server/lib/cosValidation.test.js@@ -9,6 +9,7 @@ import {} from './cosValidation.js';import { EFFORT_LEVELS } from './providerModels.js';import { JOB_INTERVAL_VALUES, ON_DEMAND_INTERVAL } from './autonomousJobIntervals.js';+import { TASK_STATUS_VALUES, TASK_PRIORITY_VALUES } from './taskParser.js';describe('cosValidation effort field', () => {it('accepts every EFFORT_LEVELS value on create and rejects unknown values', () => {@@ -345,3 +346,38 @@ describe('scheduled slashdo metadata', () => {expect(sanitizeTaskMetadata({ slashdoArgs: 'x'.repeat(4001) })).toBeNull();});});++describe('cosValidation task status/priority vocabulary (#7239)', () => {+ // A value TASKS.md cannot represent used to be a 200 that irreversibly deleted+ // the task and its prompt payload on the next full-file rewrite. The store now+ // repairs rather than drops, but the request still belongs at the boundary as a+ // 400 — and the vocabularies must come from the format, not a local copy.+ it('accepts every representable priority on create and update, in any case', () => {+ for (const priority of TASK_PRIORITY_VALUES) {+ expect(createCosTaskSchema.parse({ description: 'x', priority: priority.toLowerCase() }).priority).toBe(priority);+ expect(updateCosTaskSchema.parse({ priority: ` ${priority} ` }).priority).toBe(priority);+ }+ });++ it('accepts every representable status on update, in any case', () => {+ for (const status of TASK_STATUS_VALUES) {+ expect(updateCosTaskSchema.parse({ status: status.toUpperCase() }).status).toBe(status);+ }+ });++ it('rejects a priority or status outside the vocabulary', () => {+ expect(createCosTaskSchema.safeParse({ description: 'x', priority: 'URGENT' }).success).toBe(false);+ // A trailing space used to survive `.toUpperCase()` and reach the store.+ expect(createCosTaskSchema.safeParse({ description: 'x', priority: 'urgent ' }).success).toBe(false);+ expect(updateCosTaskSchema.safeParse({ priority: 'URGENT' }).success).toBe(false);+ expect(updateCosTaskSchema.safeParse({ status: 'done' }).success).toBe(false);+ expect(updateCosTaskSchema.safeParse({ status: 'archived' }).success).toBe(false);+ });++ it("treats the form's empty selection as absent, not as a rejection", () => {+ // Same shape the effort field asserts above: the route gates on `!== undefined`,+ // so an undefined-valued key is absent as far as the store is concerned.+ expect(createCosTaskSchema.parse({ description: 'x', priority: '' }).priority).toBeUndefined();+ expect(updateCosTaskSchema.parse({ status: '' }).status).toBeUndefined();+ });+});diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.jsindex a22ba0bcda..3431b0f67a 100644--- a/server/lib/importScoping.test.js+++ b/server/lib/importScoping.test.js@@ -435,7 +435,16 @@ describe('deferred imports stay deferred (#6156)', () => {// closures; the measured baseline 103,190 -> 103,228 is the shutdown module// itself in 38 additional suite closures, not a new heavy subtree. Preserve// the existing headroom by accounting for exactly that additive lifecycle edge.-const MAX_STATIC_INSTANTIATIONS = 103240;+// #7239 points cosValidation.js, peerSyncValidation.js and taskBlockCategories.js+// at the task vocabularies declared in lib/taskParser.js, so the HTTP enum, the+// peer wire enum and the block-category set cannot drift from what TASKS.md can+// actually represent. taskParser.js is a zero-import leaf, so each edge costs+// exactly one module in a suite that did not already reach it: this branch's own+// delta is +92 — 60 such suites plus the new lib/peerSyncValidation.test.js+// closure (32). There is nothing to narrow — the leaf IS the narrow form — so+// raise by exactly that delta and keep the existing headroom. The measured total+// is 103,356 after rebasing onto a main that grew by 36 on its own.+const MAX_STATIC_INSTANTIATIONS = 103368;const SKIP_DIRS = new Set(['node_modules', 'coverage', 'dist', 'data']);diff --git a/server/lib/peerSyncValidation.js b/server/lib/peerSyncValidation.jsindex 0d0db9fddb..3cc75a7330 100644--- a/server/lib/peerSyncValidation.js+++ b/server/lib/peerSyncValidation.js@@ -1,5 +1,6 @@import { z } from 'zod';import { catalogSyncIngredientSchema, catalogSyncRefSchema } from './catalogValidation.js';+import { TASK_STATUS_VALUES, TASK_PRIORITY_VALUES } from './taskParser.js';// =============================================================================// PEER SYNC SCHEMAS@@ -374,13 +375,15 @@ export const peerCosHistoryManifestSchema = z.object({// `challenged` (#2441) rides the wire like any other status — the challenge// case + resolution live in `metadata` (permissive record below), so they// federate verbatim with no extra top-level fields.-const TASK_STATUSES = ['pending', 'in_progress', 'challenged', 'blocked', 'completed'];-const TASK_PRIORITIES = ['CRITICAL', 'HIGH', 'MEDIUM', 'LOW'];+// The vocabularies come from taskParser.js — the module that DEFINES what a+// TASKS.md row can hold — rather than a hand-written copy here. A wire value the+// markdown store cannot represent is a task the receiver would drop on its next+// file write (#7239), so the two lists must not be able to drift.const peerCosTaskEntrySchema = z.object({id: z.string().trim().min(1).max(200),taskType: z.enum(['user', 'internal']),- status: z.enum(TASK_STATUSES),- priority: z.enum(TASK_PRIORITIES),+ status: z.enum(TASK_STATUS_VALUES),+ priority: z.enum(TASK_PRIORITY_VALUES),description: z.string().max(20_000),approvalRequired: z.boolean().optional(),autoApproved: z.boolean().optional(),diff --git a/server/lib/peerSyncValidation.test.js b/server/lib/peerSyncValidation.test.jsnew file mode 100644index 0000000000..aa3892393f--- /dev/null+++ b/server/lib/peerSyncValidation.test.js@@ -0,0 +1,30 @@+import { describe, it, expect } from 'vitest';+import { peerCosTasksSchema } from './peerSyncValidation.js';+import { TASK_STATUS_VALUES, TASK_PRIORITY_VALUES } from './taskParser.js';++// The wire vocabulary and the markdown store's vocabulary must be the same list.+// They were two hand-written copies, and a peer entry the receiver accepts but+// `generateTasksMarkdown` cannot represent is a task the receiver deletes on its+// very next file write — with no deletion to federate back, so no peer can+// restore it (#7239).+describe('peer CoS task wire vocabulary tracks the markdown store', () => {+ const payload = tasks => ({ schemaVersion: 1, listHash: 'a'.repeat(64), tasks });+ const entry = overrides => ({+ id: 'task-1', taskType: 'user', status: 'pending', priority: 'HIGH',+ description: 'x', metadata: {}, ...overrides,+ });++ it('accepts every status the store can represent, and nothing else', () => {+ for (const status of TASK_STATUS_VALUES) {+ expect(peerCosTasksSchema.safeParse(payload([entry({ status })])).success).toBe(true);+ }+ expect(peerCosTasksSchema.safeParse(payload([entry({ status: 'archived' })])).success).toBe(false);+ });++ it('accepts every priority the store can represent, and nothing else', () => {+ for (const priority of TASK_PRIORITY_VALUES) {+ expect(peerCosTasksSchema.safeParse(payload([entry({ priority })])).success).toBe(true);+ }+ expect(peerCosTasksSchema.safeParse(payload([entry({ priority: 'URGENT' })])).success).toBe(false);+ });+});diff --git a/server/lib/taskBlockCategories.js b/server/lib/taskBlockCategories.jsindex 695584931c..c6cbf494d9 100644--- a/server/lib/taskBlockCategories.js+++ b/server/lib/taskBlockCategories.js@@ -11,11 +11,13 @@* matches nothing — the real category is `agent-paused` — and silently missed* `challenge-escalation` entirely.*- * Pure and dependency-free (beyond the pause category it shares with- * `taskPauseHold.js`) so all three read ONE vocabulary.+ * Pure and dependency-free (beyond the two categories it shares with+ * `taskPauseHold.js` and `taskParser.js`, both themselves dependency-free) so+ * all three read ONE vocabulary.*/import { AGENT_PAUSED_CATEGORY } from './taskPauseHold.js';+import { UNKNOWN_STATUS_BLOCKED_CATEGORY } from './taskParser.js';/*** A PERMANENT provider-config failure: the task's resolved provider cannot run@@ -84,6 +86,11 @@ export const USER_DECISION_BLOCKED_CATEGORIES = new Set(['challenge-escalation', // parked awaiting the user's arbitration'app-unresolved','workspace-invalid',+ // A task the markdown store could not represent, parked here by+ // generateTasksMarkdown's repair instead of being deleted (#7239). Its real+ // status is unknown, so auto-expiring it to `completed` at 14 days would+ // silently retire — and federate as done — the very work the repair rescued.+ UNKNOWN_STATUS_BLOCKED_CATEGORY,// Same shape: a config error only the user can clear. Exempt from the 14-day// `sweepResolvedFailureTasks` auto-expiry (cosTaskStore.js), which would// otherwise flip it to `completed` with `resolution: 'auto-expired'` anddiff --git a/server/lib/taskParser.js b/server/lib/taskParser.jsindex 8b10787e0b..e11dba670c 100644--- a/server/lib/taskParser.js+++ b/server/lib/taskParser.js@@ -53,48 +53,143 @@ export const PRIORITY_VALUES = {};/**- * Parse a single task line+ * The canonical task vocabularies, derived from the two maps above so nothing+ * can re-declare a drifting copy.+ *+ * These exist because `generateTasksMarkdown` can only REPRESENT these values:+ * a status outside the set lands in no section and a priority outside it fails+ * `matchTaskLine`'s regex on the next read. TASKS.md is the only store for a+ * queued task, so an unrepresentable value used to delete the task and its+ * `metadata.prompt` outright (#7239). Validate against these at every boundary+ * that can set a status or priority — the HTTP schemas (cosValidation.js) and+ * the peer wire schema (peerSyncValidation.js) both read them from here.+ */+export const TASK_STATUS_VALUES = Object.freeze([...new Set(Object.values(STATUS_MAP))]);+export const TASK_PRIORITY_VALUES = Object.freeze(Object.keys(PRIORITY_VALUES));++/**+ * The `blockedCategory` stamped on a task whose status was outside+ * TASK_STATUS_VALUES when the file was written. The task is parked rather than+ * dropped, and its original status is preserved in `metadata.unrepresentableStatus`+ * so a human (or a later migration) can resolve what it should have been.+ */+export const UNKNOWN_STATUS_BLOCKED_CATEGORY = 'unknown-status';++const REPAIRED_STATUS = 'blocked';+const REPAIRED_PRIORITY = 'MEDIUM';++/**+ * Write-side backstop: return a task the markdown format can actually represent.+ *+ * Coerce rather than throw. A peer or an install that already holds a task with+ * an out-of-vocabulary value must be repaired on READ, not made to crash every+ * subsequent task-file write — and a row that cannot be written is a row that is+ * silently deleted, which is the failure this guard exists to stop.+ *+ * Never mutates its argument; a representable task is returned as-is, so the+ * common path allocates nothing. Exported because the two places that CONSTRUCT+ * a task (`cosTaskIntake.buildQueuedTask`, `cosTaskStore.updateTask`) run it on+ * the object they are about to persist, so the task they return and emit on+ * `tasks:changed` says exactly what the file says. Applying it here as well keeps+ * it a backstop for rows an older install or a peer already wrote.+ */+export function toRepresentableTask(task) {+ const statusOk = TASK_STATUS_VALUES.includes(task?.status);+ const priorityOk = TASK_PRIORITY_VALUES.includes(task?.priority);+ if (statusOk && priorityOk) return task;++ const repairs = [];+ if (!statusOk) repairs.push(`status \`${String(task?.status)}\` -> ${REPAIRED_STATUS}`);+ if (!priorityOk) repairs.push(`priority \`${String(task?.priority)}\` -> ${REPAIRED_PRIORITY}`);+ console.warn(`⚠️ Task ${task?.id} is not representable in TASKS.md; repairing ${repairs.join(', ')}`);++ return {+ ...task,+ status: statusOk ? task.status : REPAIRED_STATUS,+ priority: priorityOk ? task.priority : REPAIRED_PRIORITY,+ priorityValue: priorityOk ? task.priorityValue : PRIORITY_VALUES[REPAIRED_PRIORITY],+ // A status repair ALWAYS stamps `unknown-status`, never defers to a category+ // the task already carried: that prior value is arbitrary (it describes some+ // earlier block, not this one) and a reapable one would let the 14-day+ // auto-expiry flip the rescued task to `completed` — the exact loss the+ // exemption in taskBlockCategories.js exists to prevent. The old value is kept+ // beside it rather than discarded.+ metadata: statusOk ? (task.metadata || {}) : {+ ...task?.metadata,+ ...(task?.metadata?.blockedCategory ? { priorBlockedCategory: task.metadata.blockedCategory } : {}),+ blockedCategory: UNKNOWN_STATUS_BLOCKED_CATEGORY,+ unrepresentableStatus: String(task?.status)+ }+ };+}++/**+ * Match a single task line into a raw task (no repair — see `pushTask`).* Format: - [ ] #task-001 | HIGH | Description* Or with approval flag: - [ ] #sys-001 | HIGH | AUTO | Description+ *+ * The four patterns are tried in order, and the first two are the format as+ * written — a well-formed file never reaches the others, so their behavior is+ * unchanged. The last two are the RECOVERY path (#7239) for a row an older+ * install already wrote, or a hand edit: they accept any priority field and any+ * checkbox character, so the row and its indented metadata (which includes+ * `metadata.prompt`, the whole agent-facing payload) survive to be repaired+ * instead of being dropped along with everything indented under it.+ *+ * Recovery accepts ANY non-pipe priority field, because the boundary that wrote+ * these rows accepted any string — `VERY HIGH`, `123` and `URGENT!` were all+ * reachable through the route before this issue, and a narrower pattern would+ * leave exactly those rows to be deleted by the next write.*/-function parseTaskLine(line) {- // First try: - [status] #id | PRIORITY | APPROVAL_FLAG | description- let match = line.match(/^-\s*\[([ x~!?])\]\s*#([\w-]+)\s*\|\s*(CRITICAL|HIGH|MEDIUM|LOW)\s*\|\s*(AUTO|APPROVAL)\s*\|\s*(.+)$/i);-- if (match) {- const [, statusChar, id, priority, approvalFlag, description] = match;- const statusKey = `[${statusChar}]`;+const TASK_LINE_PATTERNS = [+ { withFlag: true, re: /^-\s*\[([ x~!?])\]\s*#([\w-]+)\s*\|\s*(CRITICAL|HIGH|MEDIUM|LOW)\s*\|\s*(AUTO|APPROVAL)\s*\|\s*(.+)$/i },+ { withFlag: false, re: /^-\s*\[([ x~!?])\]\s*#([\w-]+)\s*\|\s*(CRITICAL|HIGH|MEDIUM|LOW)\s*\|\s*(.+)$/i },+ { withFlag: true, recovery: true, re: /^-\s*\[([^\]])\]\s*#([\w-]+)\s*\|\s*([^|]+)\|\s*(AUTO|APPROVAL)\s*\|\s*(.+)$/i },+ { withFlag: false, recovery: true, re: /^-\s*\[([^\]])\]\s*#([\w-]+)\s*\|\s*([^|]+)\|\s*(.+)$/i }+];++function matchTaskLine(line) {+ for (const { re, withFlag, recovery } of TASK_LINE_PATTERNS) {+ const match = line.match(re);+ if (!match) continue;++ const [, statusChar, id, priority, ...rest] = match;+ // Lower-cased because the patterns are case-insensitive: a hand-written [X]+ // means completed, not an unknown marker. A marker that really is unknown+ // stays as its raw token so toRepresentableTask parks the row as blocked+ // rather than defaulting it to pending, which would make a hand-edited row+ // auto-approved and runnable.+ const statusKey = `[${statusChar.toLowerCase()}]`;+ const approvalFlag = withFlag ? rest[0].toUpperCase() : null;+ const description = withFlag ? rest[1] : rest[0];++ const taskId = hasKnownPrefix(id) ? id : `task-${id}`;return {- id: hasKnownPrefix(id) ? id : `task-${id}`,- status: STATUS_MAP[statusKey] || 'pending',- priority: priority.toUpperCase(),- priorityValue: PRIORITY_VALUES[priority.toUpperCase()] || 2,- approvalRequired: approvalFlag.toUpperCase() === 'APPROVAL',- autoApproved: approvalFlag.toUpperCase() === 'AUTO',+ id: taskId,+ status: STATUS_MAP[statusKey] ?? statusKey,+ priority: priority.trim().toUpperCase(),+ priorityValue: PRIORITY_VALUES[priority.trim().toUpperCase()] || 2,+ // A recovered row is an ambiguous split — the priority field could itself+ // have held a pipe ('UR|GENT', 'UR|AUTO' were both reachable through the old+ // free-string boundary), so which segment was the approval flag is a guess.+ // Recovery must never make a row MORE permissive than it was, so a recovered+ // INTERNAL task lands in the approval queue rather than the dequeue: those+ // are the rows where the flag gates an agent spawn, and the flag is written+ // back (includeApprovalFlags), so the hold survives the next read.+ //+ // A user task carries no flag in the format at all — every one is+ // auto-approved by construction — so holding one here would be a claim the+ // next write erases. Its row is restored to the ordinary user queue, which+ // is exactly what it was before the corruption. A strict match on either+ // kind keeps its exact prior semantics.+ approvalRequired: (recovery && isInternalTaskId(taskId)) || approvalFlag === 'APPROVAL',+ autoApproved: !(recovery && isInternalTaskId(taskId)) && (withFlag ? approvalFlag === 'AUTO' : true),description: description.trim(),metadata: {}};}-- // Fallback: - [status] #id | PRIORITY | description (no approval flag)- match = line.match(/^-\s*\[([ x~!?])\]\s*#([\w-]+)\s*\|\s*(CRITICAL|HIGH|MEDIUM|LOW)\s*\|\s*(.+)$/i);-- if (!match) return null;-- const [, statusChar, id, priority, description] = match;- const statusKey = `[${statusChar}]`;-- return {- id: hasKnownPrefix(id) ? id : `task-${id}`,- status: STATUS_MAP[statusKey] || 'pending',- priority: priority.toUpperCase(),- priorityValue: PRIORITY_VALUES[priority.toUpperCase()] || 2,- approvalRequired: false,- autoApproved: true,- description: description.trim(),- metadata: {}- };+ return null;}// Sentinel prefix for JSON-encoded metadata values@@ -194,7 +289,7 @@ export function parseTasksMarkdown(content) {const rawIds = new Set();for (const line of lines) {if (line.startsWith('- [')) {- const parsed = parseTaskLine(line);+ const parsed = matchTaskLine(line);if (parsed) rawIds.add(parsed.id);}}@@ -219,7 +314,12 @@ export function parseTasksMarkdown(content) {console.warn(`⚠️ Duplicate task id "${originalId}" in tasks markdown — renamed to "${task.id}"`);}seenIds.add(task.id);- tasks.push(task);+ // Repair HERE, not at match time: the row's indented metadata lines are+ // attached between the two, and one of them can be a `blockedCategory` left+ // over from an earlier block. Repairing first would let that line overwrite+ // the `unknown-status` hold the repair just stamped, dropping the rescued+ // task back into the 14-day auto-expiry it is exempt from.+ tasks.push(toRepresentableTask(task));};for (const line of lines) {@@ -237,7 +337,7 @@ export function parseTasksMarkdown(content) {// Task lineif (line.startsWith('- [')) {pushTask(currentTask);- currentTask = parseTaskLine(line);+ currentTask = matchTaskLine(line);if (currentTask) {currentTask.section = currentSection;}@@ -304,7 +404,10 @@ function flattenDescription(task) {* @param {boolean} includeApprovalFlags - Whether to include AUTO/APPROVAL flags (for internal CoS tasks)*/export function generateTasksMarkdown(tasks, includeApprovalFlags = false) {- const grouped = groupTasksByStatus(tasks);+ // Repair BEFORE grouping: groupTasksByStatus buckets only the five known+ // statuses, so an unrepresentable task would fall out of every bucket and be+ // written nowhere. Every task handed in gets a row (#7239).+ const grouped = groupTasksByStatus(tasks.map(toRepresentableTask));const lines = ['# Tasks', ''];const statusToCheckbox = {@@ -464,12 +567,17 @@ export function validateTask(task) {errors.push('Task must have a description');}- if (!['pending', 'in_progress', 'challenged', 'blocked', 'completed'].includes(task.status)) {+ // Both read the vocabularies above rather than a hand-written list — this was+ // the fourth copy of the same five statuses in the tree (#7239).+ if (!TASK_STATUS_VALUES.includes(task.status)) {errors.push('Invalid task status');}- if (!Object.keys(PRIORITY_VALUES).includes(task.priority)) {- errors.push('Invalid priority (must be CRITICAL, HIGH, MEDIUM, or LOW)');+ if (!TASK_PRIORITY_VALUES.includes(task.priority)) {+ // Derived, but phrased exactly as before — this message is the one a user reads.+ const options = [...TASK_PRIORITY_VALUES];+ const last = options.pop();+ errors.push(`Invalid priority (must be ${[...options, `or ${last}`].join(', ')})`);}return {diff --git a/server/lib/taskParser.test.js b/server/lib/taskParser.test.jsindex 71679ac856..676f46c3ed 100644--- a/server/lib/taskParser.test.js+++ b/server/lib/taskParser.test.js@@ -10,7 +10,10 @@ import {addTask,removeTask,getNextTask,- validateTask+ validateTask,+ TASK_STATUS_VALUES,+ TASK_PRIORITY_VALUES,+ UNKNOWN_STATUS_BLOCKED_CATEGORY} from './taskParser.js';describe('Task Parser', () => {@@ -823,3 +826,240 @@ describe('Task Parser — challenged status (#2441)', () => {expect(result.valid).toBe(true);});});++describe('unrepresentable status/priority never drops a task (#7239)', () => {+ // TASKS.md is the ONLY store for a queued task and every write is a full-file+ // rewrite, so a value the format cannot represent used to delete the task and+ // its `metadata.prompt` outright: an unknown status fell out of every bucket in+ // `groupTasksByStatus` and was written nowhere; an unknown priority reached the+ // file and then failed `parseTaskLine`'s regex on the next read.+ const tasks = [+ { id: 'task-A', status: 'pending', priority: 'HIGH', priorityValue: 3, description: 'keep me', metadata: { context: 'a' } },+ { id: 'task-B', status: 'archived', priority: 'HIGH', priorityValue: 3, description: 'unknown status', metadata: { prompt: 'the agent-facing payload' } },+ { id: 'task-C', status: 'pending', priority: 'URGENT', priorityValue: 2, description: 'unknown priority', metadata: { context: 'c' } },+ ];++ it('survives a generate -> parse round trip with its metadata intact', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const reparsed = parseTasksMarkdown(generateTasksMarkdown(tasks));+ warn.mockRestore();++ expect(reparsed.map(t => t.id).sort()).toEqual(['task-A', 'task-B', 'task-C']);+ // The whole point: the prompt payload is not lost with the row.+ expect(reparsed.find(t => t.id === 'task-B').metadata.prompt).toBe('the agent-facing payload');+ });++ it('parks the unknown status as blocked and records what it was', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const repaired = parseTasksMarkdown(generateTasksMarkdown(tasks)).find(t => t.id === 'task-B');+ warn.mockRestore();++ expect(repaired.status).toBe('blocked');+ expect(repaired.metadata.blockedCategory).toBe(UNKNOWN_STATUS_BLOCKED_CATEGORY);+ expect(repaired.metadata.unrepresentableStatus).toBe('archived');+ });++ it('recovers a row an older install already wrote to disk, with its prompt payload', () => {+ // The write-side repair cannot help a row that is ALREADY on disk: an unknown+ // priority fails parseTaskLine's regex, so the task and every indented+ // metadata line under it were dropped on read and deleted by the next write.+ // PortOS is distributed software — installs that predate the fix hold these.+ const onDisk = [+ '# Tasks',+ '',+ '## Pending',+ '- [ ] #task-A | HIGH | representable',+ '- [ ] #task-C | URGENT | written before the fix',+ ' - prompt: the agent-facing payload',+ '- [a] #task-D | HIGH | hand-edited checkbox',+ ' - prompt: also worth keeping',+ ''+ ].join('\n');++ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const parsed = parseTasksMarkdown(onDisk);+ warn.mockRestore();++ expect(parsed.map(t => t.id)).toEqual(['task-A', 'task-C', 'task-D']);+ expect(parsed.find(t => t.id === 'task-C').priority).toBe('MEDIUM');+ expect(parsed.find(t => t.id === 'task-C').metadata.prompt).toBe('the agent-facing payload');+ // An unrecognized checkbox already defaults to pending, so only the row itself+ // was at risk there.+ expect(parsed.find(t => t.id === 'task-D').metadata.prompt).toBe('also worth keeping');+ });++ it('repairs a recovered row once per parse, not once per scan pass', () => {+ // parseTasksMarkdown walks the lines twice (an id pre-scan, then the real+ // parse); only the second pass may repair, or every read doubles the log.+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ parseTasksMarkdown('# Tasks\n\n## Pending\n- [ ] #task-C | URGENT | one row\n');+ expect(warn).toHaveBeenCalledTimes(1);+ warn.mockRestore();+ });++ it('recovers every priority the old boundary could write, not just single words', () => {+ // `priority: z.string()` accepted anything and updateTask wrote it verbatim:+ // 'VERY HIGH', '123' and 'URGENT!' are all rows a pre-fix install can hold.+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const parsed = parseTasksMarkdown([+ '# Tasks', '', '## Pending',+ '- [ ] #task-B | VERY HIGH | multiword',+ ' - prompt: payload B',+ '- [ ] #task-C | 123 | numeric',+ ' - prompt: payload C',+ '- [ ] #task-E | URGENT! | punctuated',+ ''+ ].join('\n'));+ warn.mockRestore();++ expect(parsed.map(t => t.id)).toEqual(['task-B', 'task-C', 'task-E']);+ expect(parsed.every(t => t.priority === 'MEDIUM')).toBe(true);+ expect(parsed[0].metadata.prompt).toBe('payload B');+ });++ it.each([+ ['a pipe before the flag', '- [ ] #sys-1 | UR|GENT | APPROVAL | work'],+ ['a pipe that looks like a flag', '- [ ] #sys-2 | UR|AUTO | APPROVAL | work'],+ ])('recovers an internal row with %s into the approval queue, and keeps it there', (_label, line) => {+ // A recovered row is an ambiguous split: the priority field itself could have+ // held a pipe, so which segment was the approval flag is a guess. For an+ // INTERNAL task that flag gates an agent spawn, so recovery must not make the+ // row more permissive — and the hold has to survive the write that heals the+ // file, or the next read releases it.+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const recovered = parseTasksMarkdown('# Tasks\n\n## Pending\n' + line + '\n - prompt: payload\n');+ warn.mockRestore();++ expect(recovered[0].approvalRequired).toBe(true);+ expect(getAutoApprovedTasks(recovered)).toEqual([]);+ expect(getAwaitingApprovalTasks(recovered)).toHaveLength(1);+ expect(recovered[0].metadata.prompt).toBe('payload');++ // Internal files are written WITH approval flags, so the healed row re-reads+ // as approval-required rather than silently returning to the dequeue.+ const reread = parseTasksMarkdown(generateTasksMarkdown(recovered, true));+ expect(reread[0].approvalRequired).toBe(true);+ expect(getAutoApprovedTasks(reread)).toEqual([]);+ });++ it('restores a recovered USER row to the ordinary queue', () => {+ // A user task carries no approval flag in the format at all — every one is+ // auto-approved by construction — so holding one would be a claim the next+ // write erases. The row goes back to being exactly what it was.+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const [recovered] = parseTasksMarkdown('# Tasks\n\n## Pending\n- [ ] #task-C | URGENT | plain user row\n - prompt: payload\n');+ warn.mockRestore();++ expect(recovered.autoApproved).toBe(true);+ expect(recovered.approvalRequired).toBe(false);+ expect(recovered.metadata.prompt).toBe('payload');+ });++ it("leaves a STRICT row's approval semantics exactly as they were", () => {+ // The recovery rule must not touch the format as written — a description that+ // happens to contain '| AUTO |' is still an ordinary auto-approved user row.+ const wellFormed = parseTasksMarkdown([+ '# Tasks', '', '## Pending',+ '- [ ] #task-1 | HIGH | Explain | AUTO | behavior',+ '- [ ] #sys-3 | HIGH | AUTO | normal internal',+ ''+ ].join('\n'));+ expect(wellFormed.map(t => t.autoApproved)).toEqual([true, true]);+ expect(wellFormed.map(t => t.approvalRequired)).toEqual([false, false]);+ expect(getAutoApprovedTasks(wellFormed)).toHaveLength(2);+ });++ it('parks an unrecognized checkbox instead of making it a runnable pending task', () => {+ // Defaulting an unknown marker to 'pending' would recover the row straight+ // into the dequeue — a hand-edited line would spawn an agent. It has to land+ // on the unknown-status hold, which is blocked and therefore never dequeued.+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const [parked] = parseTasksMarkdown('# Tasks\n\n## Pending\n- [a] #task-D | HIGH | AUTO | work\n - prompt: payload D\n');+ warn.mockRestore();++ expect(parked.status).toBe('blocked');+ expect(parked.metadata.blockedCategory).toBe(UNKNOWN_STATUS_BLOCKED_CATEGORY);+ expect(parked.metadata.unrepresentableStatus).toBe('[a]');+ expect(parked.metadata.prompt).toBe('payload D');+ expect(getAutoApprovedTasks([parked])).toEqual([]);+ });++ it('is not overwritten by a blockedCategory line further down the same row', () => {+ // The row's indented metadata is attached AFTER the line is matched, so a+ // stale category from an earlier block would clobber the unknown-status hold+ // if the repair ran at match time — putting the rescued task back into the+ // 14-day auto-expiry it is exempt from.+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const [parked] = parseTasksMarkdown([+ '# Tasks', '', '## Pending',+ '- [a] #task-D | HIGH | work',+ ' - blockedCategory: worktree-failed',+ ' - prompt: preserved payload',+ ''+ ].join('\n'));+ warn.mockRestore();++ expect(parked.metadata.blockedCategory).toBe(UNKNOWN_STATUS_BLOCKED_CATEGORY);+ expect(parked.metadata.priorBlockedCategory).toBe('worktree-failed');+ expect(parked.metadata.prompt).toBe('preserved payload');+ });++ it('reads a hand-written [X] as completed rather than an unknown marker', () => {+ // The patterns are case-insensitive, so [X] always matched — it just fell+ // through STATUS_MAP and silently resurrected a finished task as pending.+ expect(parseTasksMarkdown('# Tasks\n\n## Completed\n- [X] #task-E | HIGH | done\n')[0].status).toBe('completed');+ });++ it('still refuses a line that is not a task row at all', () => {+ expect(parseTasksMarkdown('# Tasks\n\n## Pending\n- [ ] no-hash-id | HIGH | desc\n')).toEqual([]);+ expect(parseTasksMarkdown('# Tasks\n\n## Pending\n- [ ] #task-X | only two fields\n')).toEqual([]);+ });++ it('overrides a block category the task already carried, keeping the old one beside it', () => {+ // A category left over from an earlier block says nothing about THIS repair,+ // and a reapable one (worktree-failed) would let the 14-day auto-expiry flip+ // the rescued task to completed — the loss the exemption exists to prevent.+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const md = generateTasksMarkdown([{+ id: 'task-D', status: 'archived', priority: 'HIGH', priorityValue: 3,+ description: 'stale category', metadata: { blockedCategory: 'worktree-failed' },+ }]);+ warn.mockRestore();++ const repaired = parseTasksMarkdown(md)[0];+ expect(repaired.metadata.blockedCategory).toBe(UNKNOWN_STATUS_BLOCKED_CATEGORY);+ expect(repaired.metadata.priorBlockedCategory).toBe('worktree-failed');+ });++ it('coerces the unknown priority to MEDIUM without touching its status', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const repaired = parseTasksMarkdown(generateTasksMarkdown(tasks)).find(t => t.id === 'task-C');+ warn.mockRestore();++ expect(repaired.status).toBe('pending');+ expect(repaired.priority).toBe('MEDIUM');+ // A priority-only repair must not park the task or stamp a block category.+ expect(repaired.metadata.blockedCategory).toBeUndefined();+ });++ it('warns once per repaired task and stays silent when every task is representable', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ generateTasksMarkdown(tasks);+ expect(warn.mock.calls.map(([line]) => line)).toEqual([+ expect.stringContaining('task-B'),+ expect.stringContaining('task-C'),+ ]);++ warn.mockClear();+ generateTasksMarkdown([tasks[0]]);+ expect(warn).not.toHaveBeenCalled();+ warn.mockRestore();+ });++ it('derives the vocabularies from the format itself', () => {+ expect([...TASK_STATUS_VALUES].sort())+ .toEqual(['blocked', 'challenged', 'completed', 'in_progress', 'pending']);+ expect([...TASK_PRIORITY_VALUES].sort())+ .toEqual(['CRITICAL', 'HIGH', 'LOW', 'MEDIUM']);+ });+});diff --git a/server/services/cosTaskIntake.js b/server/services/cosTaskIntake.jsindex b2b88555ac..f7bc8271cc 100644--- a/server/services/cosTaskIntake.js+++ b/server/services/cosTaskIntake.js@@ -21,7 +21,7 @@* description → `metadata.prompt` classification stay in `cosTaskStore.js`.*/-import { hasKnownPrefix, PRIORITY_VALUES } from '../lib/taskParser.js';+import { hasKnownPrefix, PRIORITY_VALUES, toRepresentableTask } from '../lib/taskParser.js';import { SWARM_COUNT_MAX, SWARM_COUNT_MIN } from '../lib/cosValidation.js';import { KEYED_REVIEWER_PINS, REVIEW_STOP_MODES, normalizeReviewers, normalizeReviewUsernames, normalizeOptionalReviewers } from '../lib/reviewerConfig.js';import { isPlainObject } from '../lib/objects.js';@@ -294,7 +294,11 @@ export function buildQueuedTask(taskData, taskType, { now = Date.now() } = {}) {// Generate a unique ID if not providedconst id = taskData.id || `${taskType === 'user' ? 'task' : 'sys'}-${Date.now().toString(36)}`;const metadata = buildTaskMetadata(taskData, taskType, { now });- return {+ // Through `toRepresentableTask` so the object we return is the one TASKS.md will+ // hold: an internal producer that bypasses the HTTP schema can still hand us a+ // priority the format cannot write, and repairing only at write time would make+ // the returned task disagree with the file (#7239).+ return toRepresentableTask({id: hasKnownPrefix(id) ? id : `${taskType === 'user' ? 'task' : 'sys'}-${id}`,status: 'pending',priority: (taskData.priority || 'MEDIUM').toUpperCase(),@@ -304,5 +308,5 @@ export function buildQueuedTask(taskData, taskType, { now = Date.now() } = {}) {approvalRequired: taskType === 'internal' && taskData.approvalRequired,autoApproved: taskType === 'internal' && !taskData.approvalRequired,section: 'pending'- };+ });}diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.jsindex d379741f8e..cd60e738fc 100644--- a/server/services/cosTaskStore.js+++ b/server/services/cosTaskStore.js@@ -17,7 +17,7 @@ import { reviewerModelsFromDefaults } from '../lib/reviewerConfig.js';import { readFile, writeFile, stat } from 'fs/promises';import { existsSync } from 'fs';import { join } from 'path';-import { parseTasksMarkdown, groupTasksByStatus, getAutoApprovedTasks, getAwaitingApprovalTasks, generateTasksMarkdown, PRIORITY_VALUES } from '../lib/taskParser.js';+import { parseTasksMarkdown, groupTasksByStatus, getAutoApprovedTasks, getAwaitingApprovalTasks, generateTasksMarkdown, toRepresentableTask, PRIORITY_VALUES } from '../lib/taskParser.js';import { MAX_TOTAL_SPAWNS } from '../lib/validation.js';import { RETRY_HOLD_KEY, RETRY_HOLD_SINCE_KEY } from '../lib/taskRetryHold.js';import { resolveTaskTargetBranch, shouldStripTaskTargetBranch } from '../lib/taskTargetBranch.js';@@ -687,8 +687,11 @@ async function writeTaskUpdate(taskId, updates, taskType, { now, suppressDequeueconst nextMetadata = normalizedDescription ? normalizedDescription.metadata : updatedMetadata;const nextDescription = normalizedDescription ? normalizedDescription.description : updates.description;- // Update the task- const updatedTask = {+ // Update the task. Through `toRepresentableTask` so the object we return and+ // emit on `tasks:changed` is the one the file will hold — repairing only inside+ // generateTasksMarkdown would leave every consumer reading the pre-repair status+ // until something re-read the file (#7239).+ const updatedTask = toRepresentableTask({...tasks[taskIndex],...(updates.description && { description: nextDescription }),...(updates.priority && {@@ -697,7 +700,7 @@ async function writeTaskUpdate(taskId, updates, taskType, { now, suppressDequeue}),...(updates.status && { status: updates.status }),metadata: nextMetadata- };+ });tasks[taskIndex] = updatedTask;diff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.jsindex 9063644134..29e322c7d4 100644--- a/server/services/cosTaskStore.test.js+++ b/server/services/cosTaskStore.test.js@@ -2275,3 +2275,34 @@ describe('cosTaskStore.resolveTaskChallengeWithRecheck (#2471)', () => {expect(mock.reviewCalls.length).toBe(0);});});++describe('cosTaskStore — a repaired task is returned exactly as it is persisted (#7239)', () => {+ // The markdown store can only represent five statuses and four priorities, and+ // every write rewrites the whole file. Repairing only inside+ // generateTasksMarkdown would write one thing and hand back another, so every+ // consumer of the return value / `tasks:changed` would read the pre-repair+ // status until something re-read the file.+ it('updateTask returns the parked status, not the unrepresentable one it was given', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const created = await addTask({ description: 'work worth keeping' }, 'user');+ const updated = await updateTask(created.id, { status: 'archived' }, 'user');+ warn.mockRestore();++ expect(updated.status).toBe('blocked');+ expect(updated.metadata.unrepresentableStatus).toBe('archived');+ // And a fresh read of the file agrees with what the call returned.+ expect(await getTaskById(created.id)).toMatchObject({+ status: updated.status,+ metadata: expect.objectContaining({ unrepresentableStatus: 'archived' }),+ });+ });++ it('addTask returns the coerced priority for a producer that bypasses the route schema', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const created = await addTask({ description: 'urgent-ish', priority: 'URGENT' }, 'user');+ warn.mockRestore();++ expect(created.priority).toBe('MEDIUM');+ expect((await getTaskById(created.id)).priority).toBe('MEDIUM');+ });+});