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

fix: stop nullish task metadata serializing as the string "null", which stranded merge follow-ups

[._.]/ Adam Eivy742634a0c6ca
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 28c38ddae3..dc2b0b1ceb 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -10,6 +10,10 @@
- The notification panel's "+N more notifications" line is now a "Show N more" button, so the notifications past the first ten can be read and dismissed instead of being permanently unreachable.
- Notification dismiss and "Mark read" buttons are now full-size, always-visible tap targets on touch devices — they were sized to their bare icon, and the dismiss button was only revealed on hover, which a phone has no way to do.
- The notification panel now closes on Escape, and long notification descriptions wrap to two lines instead of being cut off mid-word.
+- Agent tasks run by a provider without slash commands (grok, OpenCode, codex, antigravity) now actually get their pull request merged. PortOS drives the whole push/PR/merge lifecycle for those providers via a follow-up task — and that task was written to the task file with `app: null`, which read back as an app named "null" and blocked the follow-up before it started. The PR, its branch, and its worktree were then left behind with nothing in the system that would ever land them.
+- Merge follow-ups already stranded that way are revived on upgrade, so the pull requests they left open finally land. Their blocking reason was exempt from both the failed-task reaper and the automatic retry, so they would otherwise have sat blocked forever.
+- Task metadata that has no value is no longer written to the task file at all. Any unset field previously became the literal word "null", which every reader then saw as a real value — the same class of bug as the blocked merge follow-up above. Task files an older version already wrote are repaired on read.
+- Blocking a task that exists to merge a pull request now raises a notification naming that PR, so it can be landed by hand instead of going unnoticed. This covers every way a task can get blocked, not just the one fixed above.
## Changed
diff --git a/scripts/migrations/262-revive-null-app-blocked-merge-followups.js b/scripts/migrations/262-revive-null-app-blocked-merge-followups.js
new file mode 100644
index 0000000000..d9c2ed5770
--- /dev/null
+++ b/scripts/migrations/262-revive-null-app-blocked-merge-followups.js
@@ -0,0 +1,249 @@
+/**
+ * Migration 262 — revive the merge follow-ups blocked by an app literally
+ * named "null", so the pull requests they were spawned to land stop leaking.
+ *
+ * Background:
+ * `spawnReviewLoopFollowUp` builds its follow-up task with
+ * `app: originalTask?.metadata?.app || null`, which for a PortOS-local task is
+ * `null`. `generateTasksMarkdown` used to serialize that as the bare word
+ * `null` (`String(null)`), and `parseTasksMarkdown` read it straight back as
+ * the TRUTHY string `'null'` — an app id. `prepareAgentWorkspace` then blocked
+ * the task with `app-unresolved` before it ever started.
+ *
+ * That follow-up IS the merge for every provider without slashdo commands
+ * (grok, OpenCode, codex, antigravity): PortOS owns push → PR → review → merge
+ * on their behalf, so blocking it orphans the PR, its branch, and its worktree
+ * with nothing left in the system that will ever land them.
+ *
+ * The serialization is fixed at the source now (nullish metadata is dropped on
+ * write, and a bare `null` is read back as nullish so files an older install
+ * wrote self-heal). But repairing the VALUE does not repair the STATUS: the
+ * task stays in `## Blocked`, and `app-unresolved` is in BOTH
+ * `PAUSED_BLOCKED_CATEGORIES` and `USER_DECISION_BLOCKED_CATEGORIES`
+ * (`server/lib/taskBlockCategories.js`), so the failure reaper never expires it
+ * and the investigation auto-retry never revives it. Without this migration
+ * those tasks sit blocked forever on every install that hit the bug.
+ *
+ * What it writes:
+ * `data/COS-TASKS.md` (and `data/TASKS.md`, for an install whose follow-ups
+ * landed there) — moves a task back to `## Pending` when ALL of these hold:
+ * - it is `[!]` blocked,
+ * - it carries `reviewLoopPRUrl` (it exists to land a PR),
+ * - its `blockedCategory` is `app-unresolved`,
+ * - it carries a bare `- app: null` line — i.e. the block is provably this
+ * serialization artifact and not a real routing mistake.
+ * The `app`, `blockedReason`, `blockedCategory` and `blockedAt` lines are
+ * dropped and `updatedAt` is re-stamped, so the revived 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).
+ *
+ * Migration 234 deliberately left blocked tasks in place because the block
+ * there encoded a real routing mistake a human had to judge. The opposite is
+ * true here: the four conditions above identify a block that only ever came
+ * from the serialization bug, so reviving is the correct call and nothing else
+ * will ever do it.
+ *
+ * A text-level rewrite rather than a parse/regenerate round-trip (234's
+ * choice, for the same reason): regenerating would reorder, re-escape and
+ * re-sort every task in the user's live queue. Moving a task between sections
+ * is the one thing that costs — handled by lifting the matched blocks out and
+ * re-inserting them under `## Pending`.
+ *
+ * Idempotent: a revived task no longer matches (it is `[ ]` and has no
+ * `blockedCategory`), so a second run changes nothing.
+ */
+
+import { readFile } from 'fs/promises';
+import { join } from 'path';
+import { atomicWrite } from '../../server/lib/fileUtils.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*(.*)$/;
+const SECTION_LINE = /^##\s+(.+?)\s*$/;
+
+// Metadata the revival drops: the bad routing key plus the whole block record.
+// `blocker` is the legacy spelling still accepted by the parser.
+const DROPPED_KEYS = new Set(['app', 'blocker', 'blockedReason', 'blockedCategory', 'blockedAt']);
+
+const QUEUE_FILES = [
+ { configKey: 'cosTasksFile', file: 'data/COS-TASKS.md' },
+ { configKey: 'userTasksFile', file: 'data/TASKS.md' },
+];
+
+/**
+ * Repo-relative paths of the queue files, honouring an install that moved them
+ * in `data/cos/state.json` (`config.cosTasksFile` / `config.userTasksFile` — the
+ * same values `cosTaskStore` reads). Migrating only the defaults would record
+ * this migration as applied while the live queue stayed stranded.
+ */
+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
+ ));
+}
+
+/**
+ * Split a task file into an ordered list of blocks. 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 verbatim by
+ * `generateTasksMarkdown`, so a freshly-filed task can carry blank/prose lines
+ * between its header and its metadata.
+ *
+ * @returns {Array<{ kind: 'section'|'task'|'other', lines: string[], … }>}
+ */
+function splitBlocks(markdown) {
+ const blocks = [];
+ for (const line of markdown.split('\n')) {
+ const section = line.match(SECTION_LINE);
+ if (section) {
+ blocks.push({ kind: 'section', title: section[1], lines: [line] });
+ continue;
+ }
+ const header = line.match(TASK_LINE);
+ if (header) {
+ blocks.push({ kind: 'task', status: header[1], id: header[2], lines: [line] });
+ continue;
+ }
+ if (blocks.length && blocks[blocks.length - 1].kind === 'task') blocks[blocks.length - 1].lines.push(line);
+ else blocks.push({ kind: 'other', lines: [line] });
+ }
+ return blocks;
+}
+
+/** Read a task block's metadata into a flat `{ key: rawValue }` map. */
+function readMetadata(block) {
+ const meta = {};
+ for (const line of block.lines.slice(1)) {
+ const m = line.match(METADATA_LINE);
+ if (m && !(m[2] in meta)) meta[m[2]] = m[3].trim();
+ }
+ return meta;
+}
+
+/**
+ * Is this block a merge follow-up stranded by the `app: null` serialization bug
+ * — as opposed to one blocked for a reason a human still has to judge?
+ */
+function isNullAppStrandedFollowUp(block) {
+ if (block.kind !== 'task' || block.status !== '!') return false;
+ const meta = readMetadata(block);
+ return meta.app === 'null'
+ && meta.blockedCategory === 'app-unresolved'
+ && !!meta.reviewLoopPRUrl;
+}
+
+/**
+ * Rewrite one blocked task block as a pending one: flip the checkbox, drop the
+ * bad routing key and the block record, and re-stamp `updatedAt`.
+ */
+function revive(block, stamp) {
+ const indent = block.lines.slice(1).map(l => l.match(METADATA_LINE)).find(Boolean)?.[1] ?? ' ';
+ const lines = [block.lines[0].replace(/^-\s*\[!\]/, '- [ ]')];
+ let stamped = false;
+ for (const line of block.lines.slice(1)) {
+ const m = line.match(METADATA_LINE);
+ if (m && DROPPED_KEYS.has(m[2])) continue;
+ if (m && m[2] === 'updatedAt') { lines.push(`${indent}- updatedAt: ${stamp}`); stamped = true; continue; }
+ lines.push(line);
+ }
+ // No stamp yet — append one after the last metadata line rather than at the
+ // end of the block, which may hold trailing blank/prose lines.
+ if (!stamped) {
+ const lastMeta = lines.reduce((at, line, i) => (METADATA_LINE.test(line) ? i : at), 0);
+ lines.splice(lastMeta + 1, 0, `${indent}- updatedAt: ${stamp}`);
+ }
+ return { ...block, status: ' ', lines };
+}
+
+/**
+ * Move every `app: null`-stranded merge follow-up out of `## Blocked` and into
+ * `## Pending`. Pure — exported for the test.
+ *
+ * @param {string} markdown raw COS-TASKS.md / TASKS.md
+ * @param {string} stamp ISO timestamp for the `updatedAt` re-stamp
+ * @returns {{ markdown: string, revived: string[] }} ids of the tasks revived
+ */
+export function reviveStrandedFollowUps(markdown, stamp) {
+ const blocks = splitBlocks(markdown);
+ const stranded = blocks.filter(isNullAppStrandedFollowUp);
+ if (!stranded.length) return { markdown, revived: [] };
+
+ const strandedSet = new Set(stranded);
+ const revived = stranded.map(b => revive(b, stamp));
+ const kept = blocks.filter(b => !strandedSet.has(b));
+
+ // Re-insert under `## Pending` — at the END of that section so the queue's
+ // existing priority order is untouched (`generateTasksMarkdown` re-sorts on
+ // the next save anyway). A file with no Pending section gets one, placed
+ // before the first section that exists so it reads in the usual order.
+ const out = [];
+ let inserted = false;
+ for (let i = 0; i < kept.length; i++) {
+ const block = kept[i];
+ // End of the Pending section = the next section heading after it.
+ if (!inserted && block.kind === 'section' && /^pending$/i.test(block.title)) {
+ out.push(block);
+ let j = i + 1;
+ for (; j < kept.length && kept[j].kind !== 'section'; j++) out.push(kept[j]);
+ // Trailing blank line before the next heading belongs after our blocks.
+ const trailing = [];
+ while (out.length && out[out.length - 1].kind === 'other' && out[out.length - 1].lines.every(l => !l.trim())) {
+ trailing.unshift(out.pop());
+ }
+ out.push(...revived, ...trailing);
+ i = j - 1;
+ inserted = true;
+ continue;
+ }
+ if (!inserted && block.kind === 'section') {
+ out.push({ kind: 'section', title: 'Pending', lines: ['## Pending'] }, ...revived, { kind: 'other', lines: [''] });
+ inserted = true;
+ }
+ out.push(block);
+ }
+ if (!inserted) out.push({ kind: 'section', title: 'Pending', lines: ['## Pending'] }, ...revived);
+
+ return {
+ markdown: out.flatMap(b => b.lines).join('\n'),
+ revived: revived.map(b => b.id),
+ };
+}
+
+export default {
+ async up({ rootDir, now = new Date().toISOString() }) {
+ const revived = [];
+ let seenAFile = false;
+
+ for (const relative of await queuePaths(rootDir)) {
+ const file = join(rootDir, relative);
+ 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 = reviveStrandedFollowUps(raw, now);
+ if (!result.revived.length) continue;
+ await atomicWrite(file, result.markdown);
+ revived.push(...result.revived);
+ }
+
+ if (!seenAFile) {
+ console.log('🔥 migration 262: no task queue on this install — nothing to revive');
+ return { ok: true, reason: 'no-task-file' };
+ }
+ if (!revived.length) {
+ console.log('🔥 migration 262: no merge follow-ups stranded by a null app');
+ return { ok: true, reason: 'none-stranded', revived: 0 };
+ }
+ console.log(`🔥 migration 262: revived ${revived.length} merge follow-up(s) whose PR was left orphaned`);
+ return { ok: true, revived: revived.length };
+ },
+};
diff --git a/scripts/migrations/262-revive-null-app-blocked-merge-followups.test.js b/scripts/migrations/262-revive-null-app-blocked-merge-followups.test.js
new file mode 100644
index 0000000000..223f16cde2
--- /dev/null
+++ b/scripts/migrations/262-revive-null-app-blocked-merge-followups.test.js
@@ -0,0 +1,194 @@
+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, { reviveStrandedFollowUps } from './262-revive-null-app-blocked-merge-followups.js';
+import { parseTasksMarkdown } from '../../server/lib/taskParser.js';
+
+const STAMP = '2026-08-12T12:00:00.000Z';
+const PR_URL = 'https://github.com/example-org/example-repo/pull/9';
+
+// The shape spawnReviewLoopFollowUp wrote before the serialization fix: an
+// `app: null` that came back as the app id 'null' and blocked the task.
+const strandedFollowUp = (id, {
+ mark = '!',
+ app = 'null',
+ category = 'app-unresolved',
+ prUrl = PR_URL,
+ updatedAt = '2026-08-01T00:00:00.000Z',
+} = {}) => [
+ `- [${mark}] #${id} | MEDIUM | AUTO | [Review Loop] example task (${prUrl})`,
+ ...(app ? [` - app: ${app}`] : []),
+ ' - useWorktree: true',
+ ' - existingBranch: cos/task-1/agent-1',
+ ...(prUrl ? [` - reviewLoopPRUrl: ${prUrl}`] : []),
+ ' - reviewLoopPRBranch: cos/task-1/agent-1',
+ ...(category ? [` - blockedReason: App 'null' didn't resolve to a repository directory.`, ` - blockedCategory: ${category}`, ' - blockedAt: 2026-08-01T00:00:00.000Z'] : []),
+ ...(updatedAt ? [` - updatedAt: ${updatedAt}`] : []),
+].join('\n');
+
+const queue = (blocked = [], pending = []) => [
+ '# Tasks', '',
+ '## Pending', ...pending, '',
+ '## Blocked', ...blocked, '',
+].join('\n');
+
+describe('reviveStrandedFollowUps', () => {
+ it('moves the stranded follow-up back to pending and clears the block record', () => {
+ const { markdown, revived } = reviveStrandedFollowUps(queue([strandedFollowUp('sys-rl-1')]), STAMP);
+ expect(revived).toEqual(['sys-rl-1']);
+ // Parsed through the REAL parser — the survivor has to still read, not just
+ // look right in the raw text.
+ const [task] = parseTasksMarkdown(markdown);
+ expect(task.id).toBe('sys-rl-1');
+ expect(task.status).toBe('pending');
+ expect(task.metadata.app).toBeUndefined();
+ expect(task.metadata.blockedCategory).toBeUndefined();
+ expect(task.metadata.blockedReason).toBeUndefined();
+ expect(task.metadata.blockedAt).toBeUndefined();
+ // Everything the follow-up needs to actually run survives.
+ expect(task.metadata.reviewLoopPRUrl).toBe(PR_URL);
+ expect(task.metadata.existingBranch).toBe('cos/task-1/agent-1');
+ });
+
+ // A peer that hasn't migrated still holds the blocked copy at the old stamp;
+ // without the bump the equal-status tie can adopt it and re-strand the task.
+ it('re-stamps updatedAt so the revived copy wins the federation merge', () => {
+ const { markdown } = reviveStrandedFollowUps(queue([strandedFollowUp('sys-rl-1')]), STAMP);
+ expect(parseTasksMarkdown(markdown)[0].metadata.updatedAt).toBe(STAMP);
+ });
+
+ it('adds the stamp when the task carries none', () => {
+ const md = queue([strandedFollowUp('sys-rl-1', { updatedAt: null })]);
+ const { markdown, revived } = reviveStrandedFollowUps(md, STAMP);
+ expect(revived).toEqual(['sys-rl-1']);
+ expect(parseTasksMarkdown(markdown)[0].metadata.updatedAt).toBe(STAMP);
+ });
+
+ it('is idempotent — a revived task no longer matches', () => {
+ const once = reviveStrandedFollowUps(queue([strandedFollowUp('sys-rl-1')]), STAMP);
+ expect(reviveStrandedFollowUps(once.markdown, STAMP)).toEqual({ markdown: once.markdown, revived: [] });
+ });
+
+ it('returns the input untouched when nothing is stranded', () => {
+ const md = queue([], ['- [ ] #task-1 | HIGH | Fix the failing test']);
+ expect(reviveStrandedFollowUps(md, STAMP)).toEqual({ markdown: md, revived: [] });
+ });
+
+ // Each of the four conditions is load-bearing: a block that fails any one of
+ // them may encode a real problem a human still has to judge.
+ it('leaves a follow-up blocked at a REAL app alone', () => {
+ const md = queue([strandedFollowUp('sys-rl-1', { app: 'example-app' })]);
+ expect(reviveStrandedFollowUps(md, STAMP).revived).toEqual([]);
+ });
+
+ it('leaves a follow-up blocked for a different reason alone', () => {
+ const md = queue([strandedFollowUp('sys-rl-1', { category: 'max-retries' })]);
+ expect(reviveStrandedFollowUps(md, STAMP).revived).toEqual([]);
+ });
+
+ it('leaves an ordinary app-unresolved task that is not landing a PR alone', () => {
+ const md = queue([strandedFollowUp('sys-1', { prUrl: null })]);
+ expect(reviveStrandedFollowUps(md, STAMP).revived).toEqual([]);
+ });
+
+ it('leaves a follow-up that is not blocked alone', () => {
+ const md = queue([], [strandedFollowUp('sys-rl-1', { mark: ' ' })]);
+ expect(reviveStrandedFollowUps(md, STAMP).revived).toEqual([]);
+ });
+
+ it('keeps the other blocked tasks in the Blocked section', () => {
+ const other = ['- [!] #task-2 | HIGH | Something a human must fix', ' - blockedCategory: needs-input'].join('\n');
+ const { markdown } = reviveStrandedFollowUps(queue([strandedFollowUp('sys-rl-1'), other]), STAMP);
+ const tasks = parseTasksMarkdown(markdown);
+ expect(tasks.find(t => t.id === 'sys-rl-1').status).toBe('pending');
+ expect(tasks.find(t => t.id === 'task-2').status).toBe('blocked');
+ });
+
+ it('preserves the tasks already pending, and their order', () => {
+ const md = queue(
+ [strandedFollowUp('sys-rl-1')],
+ ['- [ ] #task-a | HIGH | First', '- [ ] #task-b | LOW | Second'],
+ );
+ const ids = parseTasksMarkdown(reviveStrandedFollowUps(md, STAMP).markdown).map(t => t.id);
+ expect(ids).toEqual(['task-a', 'task-b', 'sys-rl-1']);
+ });
+
+ it('creates a Pending section when the file has none', () => {
+ const md = ['# Tasks', '', '## Blocked', strandedFollowUp('sys-rl-1'), ''].join('\n');
+ const { markdown, revived } = reviveStrandedFollowUps(md, STAMP);
+ expect(revived).toEqual(['sys-rl-1']);
+ expect(markdown).toContain('## Pending');
+ expect(parseTasksMarkdown(markdown)[0].status).toBe('pending');
+ });
+
+ // `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.
+ it('reaches the metadata past a description that spilled onto its own lines', () => {
+ const spilled = [
+ `- [!] #sys-rl-1 | MEDIUM | AUTO | [Review Loop] example task (${PR_URL})`,
+ '',
+ 'Landing the review fixes.',
+ ' - app: null',
+ ` - reviewLoopPRUrl: ${PR_URL}`,
+ ' - blockedCategory: app-unresolved',
+ ].join('\n');
+ const { markdown, revived } = reviveStrandedFollowUps(queue([spilled]), STAMP);
+ expect(revived).toEqual(['sys-rl-1']);
+ expect(markdown).toContain('Landing the review fixes.');
+ expect(parseTasksMarkdown(markdown)[0].status).toBe('pending');
+ });
+});
+
+describe('migration 262 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-262-'));
+ 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('no-ops when nothing is stranded', async () => {
+ await writeFile(cosTasks(), queue([], ['- [ ] #task-1 | HIGH | Fix the failing test']));
+ await expect(migration.up({ rootDir })).resolves.toMatchObject({ ok: true, reason: 'none-stranded' });
+ });
+
+ it('revives the stranded follow-up on the internal queue', async () => {
+ await writeFile(cosTasks(), queue([strandedFollowUp('sys-rl-msqahye2')]));
+ await expect(migration.up({ rootDir, now: STAMP })).resolves.toMatchObject({ ok: true, revived: 1 });
+ const [task] = parseTasksMarkdown(await readFile(cosTasks(), 'utf-8'));
+ expect(task.status).toBe('pending');
+ expect(task.metadata.app).toBeUndefined();
+ });
+
+ it('revives a follow-up that landed on the user queue too', async () => {
+ await writeFile(userTasks(), queue([strandedFollowUp('sys-rl-1')]));
+ await expect(migration.up({ rootDir, now: STAMP })).resolves.toMatchObject({ ok: true, revived: 1 });
+ expect(parseTasksMarkdown(await readFile(userTasks(), 'utf-8'))[0].status).toBe('pending');
+ });
+
+ // An install that moved its queue in data/cos/state.json must be migrated
+ // where the queue actually lives, not at the default path.
+ it('honours a relocated queue path from data/cos/state.json', async () => {
+ await mkdir(join(rootDir, 'data', 'cos'), { recursive: true });
+ await writeFile(join(rootDir, 'data', 'cos', 'state.json'), JSON.stringify({ config: { cosTasksFile: 'data/custom-cos.md' } }));
+ await writeFile(join(rootDir, 'data', 'custom-cos.md'), queue([strandedFollowUp('sys-rl-1')]));
+ await expect(migration.up({ rootDir, now: STAMP })).resolves.toMatchObject({ ok: true, revived: 1 });
+ expect(parseTasksMarkdown(await readFile(join(rootDir, 'data', 'custom-cos.md'), 'utf-8'))[0].status).toBe('pending');
+ });
+
+ it('is idempotent across runs', async () => {
+ await writeFile(cosTasks(), queue([strandedFollowUp('sys-rl-1')]));
+ await migration.up({ rootDir, now: STAMP });
+ const after = await readFile(cosTasks(), 'utf-8');
+ await expect(migration.up({ rootDir, now: STAMP })).resolves.toMatchObject({ ok: true, reason: 'none-stranded' });
+ expect(await readFile(cosTasks(), 'utf-8')).toBe(after);
+ });
+});
diff --git a/server/lib/taskParser.js b/server/lib/taskParser.js
index 487d03e821..9f56afe3fb 100644
--- a/server/lib/taskParser.js
+++ b/server/lib/taskParser.js
@@ -118,6 +118,13 @@ function unescapeNewlines(value) {
// Fall through to legacy behavior if parsing fails
}
}
+ // Self-heal task files a pre-fix install already wrote, where a nullish value
+ // was persisted as the bare word `null` and read back as a TRUTHY string (see
+ // generateTasksMarkdown for what that broke). A genuine string `"null"` now
+ // round-trips through the JSON sentinel, so an unsentineled bare
+ // `null`/`undefined` is unambiguously the nullish value.
+ if (value === 'null') return null;
+ if (value === 'undefined') return undefined;
// Legacy fallback for backwards compatibility with pre-sentinel data only.
// New values with special characters always use the sentinel prefix (see escapeNewlines),
// so this branch only runs on historical data that was escaped with the old method.
@@ -138,8 +145,10 @@ function escapeNewlines(value) {
return JSON_SENTINEL + JSON.stringify(value);
}
if (typeof value !== 'string') return String(value);
- // Only use JSON encoding if the value contains characters that need escaping
- if (value.includes('\n') || value.includes('\\')) {
+ // Only use JSON encoding if the value contains characters that need escaping,
+ // or would collide with the bare `null`/`undefined` unescapeNewlines reads
+ // back as the nullish value.
+ if (value.includes('\n') || value.includes('\\') || value === 'null' || value === 'undefined') {
return JSON_SENTINEL + JSON.stringify(value);
}
return value;
@@ -311,7 +320,18 @@ export function generateTasksMarkdown(tasks, includeApprovalFlags = false) {
// Pass the raw value — escapeNewlines JSON-encodes arrays/objects itself;
// pre-stringifying here would flatten them to "a,b" or "[object Object]"
// before it ever sees the array/object shape.
+ //
+ // Nullish values are DROPPED rather than written. `String(null)` used to
+ // put the bare word `null` in the file, which re-parsed as the TRUTHY
+ // string `'null'` — so a review-loop follow-up carrying `app: null` came
+ // back as an app id of `'null'`, got blocked with `app-unresolved` before
+ // it started, and the PR it existed to merge was orphaned. Producers
+ // legitimately build metadata with `?? null` placeholders
+ // (spawnReviewLoopFollowUp's `app`, `reviewLoopPRNumber`, …), so this is
+ // the one place that can stop that habit from corrupting task state. An
+ // absent key already means "not set" to every reader.
for (const [key, value] of Object.entries(task.metadata)) {
+ if (value === null || value === undefined) continue;
const escapedValue = escapeNewlines(value);
lines.push(` - ${key}: ${escapedValue}`);
}
diff --git a/server/lib/taskParser.test.js b/server/lib/taskParser.test.js
index efa785863a..28e58ae387 100644
--- a/server/lib/taskParser.test.js
+++ b/server/lib/taskParser.test.js
@@ -379,6 +379,65 @@ describe('Task Parser', () => {
expect(parsed[0].metadata.reviewers).toEqual(['codex', 'claude']);
});
+ it('should drop nullish metadata instead of persisting the word "null"', () => {
+ // Producers build metadata with explicit `?? null` placeholders
+ // (spawnReviewLoopFollowUp's `app`, `reviewLoopPRNumber`, …). Writing
+ // `app: null` made every reader see the TRUTHY string 'null', which
+ // blocked the follow-up with `app-unresolved` and orphaned its PR.
+ const tasks = [
+ {
+ id: 'sys-rl-001', status: 'pending', priority: 'MEDIUM', priorityValue: 2, description: 'Follow-up',
+ metadata: { app: null, reviewLoopReviewerEfforts: undefined, existingBranch: 'cos/task-001/agent-abc' }
+ }
+ ];
+
+ const markdown = generateTasksMarkdown(tasks);
+ expect(markdown).not.toMatch(/- app:/);
+ expect(markdown).not.toMatch(/- reviewLoopReviewerEfforts:/);
+ expect(markdown).toMatch(/- existingBranch: cos\/task-001\/agent-abc/);
+
+ const parsed = parseTasksMarkdown(markdown);
+ expect(parsed[0].metadata.app).toBeUndefined();
+ expect(parsed[0].metadata.existingBranch).toBe('cos/task-001/agent-abc');
+ });
+
+ it('should read a legacy bare "null" metadata value back as null, not the string', () => {
+ // Self-heals task files a pre-fix install already wrote. Without this the
+ // corrupt `app: null` survives every save/load cycle forever.
+ const parsed = parseTasksMarkdown([
+ '# Tasks',
+ '',
+ '## Pending',
+ '- [ ] #sys-rl-001 | MEDIUM | AUTO | Follow-up',
+ ' - app: null',
+ ' - reviewLoopCodexModel: undefined',
+ ' - reviewLoopPRBranch: cos/task-001/agent-abc',
+ ''
+ ].join('\n'));
+
+ expect(parsed[0].metadata.app).toBeNull();
+ expect(parsed[0].metadata.reviewLoopCodexModel).toBeUndefined();
+ expect(parsed[0].metadata.reviewLoopPRBranch).toBe('cos/task-001/agent-abc');
+ });
+
+ it('should round-trip a metadata value that is genuinely the string "null"', () => {
+ // The read-side coercion above must not eat a real value — a legitimate
+ // "null" is written through the JSON sentinel so it stays a string.
+ const tasks = [
+ {
+ id: 'task-001', status: 'pending', priority: 'MEDIUM', priorityValue: 2, description: 'Test',
+ metadata: { app: 'null', context: 'undefined' }
+ }
+ ];
+
+ const markdown = generateTasksMarkdown(tasks);
+ expect(markdown).toMatch(/- app: __json__:"null"/);
+
+ const parsed = parseTasksMarkdown(markdown);
+ expect(parsed[0].metadata.app).toBe('null');
+ expect(parsed[0].metadata.context).toBe('undefined');
+ });
+
it('should sort tasks by priority within sections', () => {
const tasks = [
{ id: 'task-001', status: 'pending', priority: 'LOW', priorityValue: 1, description: 'Low', metadata: {} },
diff --git a/server/lib/taskRetryHold.js b/server/lib/taskRetryHold.js
index 7a56f699ac..235a87d81a 100644
--- a/server/lib/taskRetryHold.js
+++ b/server/lib/taskRetryHold.js
@@ -61,8 +61,10 @@ export function retryHoldMetadata(agentId, now = Date.now()) {
/**
* The metadata patch that RELEASES the hold. `undefined` (not `null`) because
* `updateTask` deletes undefined keys from the merged metadata, whereas a null
- * survives the merge and is serialized into TASKS.md as the literal string
- * `"null"` — which would read back as a live marker.
+ * survives the merge and stays on the in-memory task for the rest of the tick.
+ * (The markdown store no longer persists either one — generateTasksMarkdown
+ * drops nullish values rather than writing the literal word `null` — but the
+ * `!== 'null'` guards below stay for task files an older install already wrote.)
*/
export function clearedRetryHoldMetadata() {
return {
diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.js
index 0e915937b4..d6b0592480 100644
--- a/server/services/agentWorktreeCleanup.js
+++ b/server/services/agentWorktreeCleanup.js
@@ -734,7 +734,13 @@ export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, p
}
if (sourceMeta.effort) providerPins.effort = sourceMeta.effort;
- const appId = originalTask?.metadata?.app || null;
+ // Routing key, and the one field here that turns a serialization slip into a
+ // dead PR: a follow-up whose `app` doesn't resolve is BLOCKED by
+ // prepareAgentWorkspace before it starts, so the PR it exists to land sits
+ // open forever. Left undefined (not `null`) for a PortOS-local task —
+ // generateTasksMarkdown drops nullish metadata, so the key never reaches the
+ // task file to be re-read as an app literally named "null".
+ const appId = originalTask?.metadata?.app;
const sourceTaskDesc = originalTask?.description || 'CoS automated task';
const firstLine = sourceTaskDesc.split(/[\r\n]/).find(l => l.trim()) || sourceTaskDesc;
const followUpTitle = `[${kind.title}] ${firstLine.trim().substring(0, 80)} (${prUrl})`;
diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.js
index 65e8ff9c1d..8faf34190e 100644
--- a/server/services/cleanupAgentWorktree.test.js
+++ b/server/services/cleanupAgentWorktree.test.js
@@ -1523,6 +1523,30 @@ describe('spawnReviewLoopFollowUp', () => {
});
expect(addTask.mock.calls[0][0].priority).toBe('MEDIUM');
});
+
+ it('leaves `app` nullish for a PortOS-local source task so it never reaches the task file', async () => {
+ // `app: null` used to serialize into the task file as the bare word `null`
+ // and re-parse as the app id 'null', which prepareAgentWorkspace blocks with
+ // `app-unresolved` — so the PR this follow-up exists to merge sat open
+ // forever. Most visible on slashdo-free providers (grok/opencode), where the
+ // follow-up IS the entire merge path. generateTasksMarkdown drops nullish
+ // metadata, so what matters is that nothing truthy lands here.
+ await spawnReviewLoopFollowUp({
+ originalAgentId: 'agent-1',
+ originalTask: { id: 'task-1', metadata: {}, description: 'X' },
+ prUrl: 'https://github.com/o/r/pull/9', prBranch: 'cos/task-1/agent-1', sourceWorkspace: '/ws'
+ });
+ expect(addTask.mock.calls[0][0].metadata.app).toBeUndefined();
+ });
+
+ it('carries `app` through when the source task is routed to a managed app', async () => {
+ await spawnReviewLoopFollowUp({
+ originalAgentId: 'agent-1',
+ originalTask: { id: 'task-1', metadata: { app: 'example-app' }, description: 'X' },
+ prUrl: 'https://github.com/o/r/pull/9', prBranch: 'cos/task-1/agent-1', sourceWorkspace: '/ws'
+ });
+ expect(addTask.mock.calls[0][0].metadata.app).toBe('example-app');
+ });
});
describe('spawnMergeRecoveryTask', () => {
diff --git a/server/services/cos.js b/server/services/cos.js
index 3b97f9a217..78b95d9943 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -79,6 +79,7 @@ export { firstLine, getUserTasks, getCosTasks, getAllTasks, getTasks, getTaskByI
import { ensureInstanceId } from './instances.js';
import { isHeldByOther, buildRenewal, buildClaim, getClaimOwner } from './cosTaskClaim.js';
import { retryTasksResolvedByInvestigation } from './investigationRetry.js';
+import { notifyIfPrLeftOrphaned } from './orphanedPrNotifier.js';
const AGENT_ARCHIVE_RETENTION_DAYS = 90;
const RESUME_DEQUEUE_DELAY_MS = 500;
@@ -1481,6 +1482,17 @@ export async function init() {
}
});
+ // A task that was going to MERGE a pull request just got blocked — surface the
+ // PR it left orphaned. Registered separately from the dequeue listener above
+ // because it must fire on a transition that listener has no branch for
+ // (→ blocked), and it is not gated on `isDaemonRunning()`: a block that lands
+ // as the daemon stops still strands its PR. See orphanedPrNotifier.js for why
+ // nothing else ever recovers these.
+ cosEvents.on('tasks:changed', (data) => {
+ notifyIfPrLeftOrphaned(data)
+ .catch(err => console.error(`❌ Orphaned-PR check failed for task ${data?.task?.id}: ${err.message}`));
+ });
+
cosEvents.on('tasks:user:added', () => {
if (isDaemonRunning()) setImmediate(() => dequeueNextTask());
});
diff --git a/server/services/orphanedPrNotifier.js b/server/services/orphanedPrNotifier.js
new file mode 100644
index 0000000000..263876c30b
--- /dev/null
+++ b/server/services/orphanedPrNotifier.js
@@ -0,0 +1,59 @@
+/**
+ * Orphaned-PR notifier.
+ *
+ * A review-loop / merge follow-up task (`spawnReviewLoopFollowUp`) exists for
+ * exactly one reason: to land the pull request named in its `reviewLoopPRUrl`.
+ * Blocking one is therefore not the self-contained "a task got parked" outcome
+ * an ordinary block is — the PR, its branch, and its worktree are left with
+ * nothing in the system that will ever merge them, and the Blocked list is the
+ * only trace.
+ *
+ * Nothing sweeps them up afterwards, either: `app-unresolved` (the category that
+ * produced the incident this was written for) sits in BOTH
+ * `PAUSED_BLOCKED_CATEGORIES` and `USER_DECISION_BLOCKED_CATEGORIES`, so the
+ * failure reaper never expires it and the investigation auto-retry never revives
+ * it. The PR stays open indefinitely.
+ *
+ * Keyed on the `pending|in_progress|… → blocked` TRANSITION off the shared
+ * `tasks:changed` event rather than hung off one blocking call site: ~12 sites
+ * across agentErrorAnalysis / agentManagement / agentLifecycle / agentFinalization
+ * / cosTaskGenerator / agentWorkspacePrep set `status: 'blocked'`, and a follow-up
+ * blocked by `max-retries` or `worktree-failed` strands its PR exactly as hard as
+ * one blocked by `app-unresolved`. One listener covers all of them, and stays
+ * correct as new blocking paths are added.
+ */
+
+import { addNotification, exists as notificationExists, NOTIFICATION_TYPES, PRIORITY_LEVELS } from './notifications.js';
+
+/**
+ * Raise a notification when a task that was going to merge a PR gets blocked.
+ *
+ * Self-guarding: returns `false` without side effects unless the task is a
+ * genuine block transition carrying a PR url. A notification-store failure
+ * rejects rather than being swallowed here, so the caller decides — the
+ * `tasks:changed` listener in cos.js logs it, because a throw from an event
+ * listener has no request lifecycle to bubble to.
+ *
+ * @param {{ task?: object, previousStatus?: string }} change - a `tasks:changed` payload
+ * @returns {Promise<boolean>} whether a notification was raised
+ */
+export async function notifyIfPrLeftOrphaned({ task, previousStatus } = {}) {
+ if (task?.status !== 'blocked' || previousStatus === 'blocked') return false;
+ const prUrl = task.metadata?.reviewLoopPRUrl;
+ if (!prUrl) return false;
+ // One notification per PR, not per block. Fixing the cause and re-running is
+ // the intended recovery, and a re-run that blocks again would otherwise stack
+ // another HIGH card for a PR the user is already looking at.
+ if (await notificationExists(NOTIFICATION_TYPES.AGENT_WARNING, 'prUrl', prUrl)) return false;
+ const why = task.metadata?.blockedReason || `it was blocked (${task.metadata?.blockedCategory || 'no category'}).`;
+ await addNotification({
+ type: NOTIFICATION_TYPES.AGENT_WARNING,
+ title: 'PR left open: its merge follow-up was blocked',
+ description: `Task ${task.id} was going to land ${prUrl}, but ${why} `
+ + `Nothing else will merge this PR — land it manually, or fix the block and re-run the task.`,
+ priority: PRIORITY_LEVELS.HIGH,
+ link: prUrl,
+ metadata: { taskId: task.id, prUrl, prBranch: task.metadata?.reviewLoopPRBranch },
+ });
+ return true;
+}
diff --git a/server/services/orphanedPrNotifier.test.js b/server/services/orphanedPrNotifier.test.js
new file mode 100644
index 0000000000..b93a957913
--- /dev/null
+++ b/server/services/orphanedPrNotifier.test.js
@@ -0,0 +1,102 @@
+/**
+ * Tests for orphanedPrNotifier — the `tasks:changed → blocked` listener that
+ * surfaces a pull request whose merge follow-up got parked.
+ *
+ * The contract these pin: it fires on the TRANSITION into blocked (not the
+ * level), only for a task carrying `reviewLoopPRUrl`, and only once per PR.
+ */
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+vi.mock('./notifications.js', () => ({
+ addNotification: vi.fn().mockResolvedValue({}),
+ exists: vi.fn().mockResolvedValue(false),
+ NOTIFICATION_TYPES: { AGENT_WARNING: 'agent_warning' },
+ PRIORITY_LEVELS: { HIGH: 'high' },
+}));
+
+import { notifyIfPrLeftOrphaned } from './orphanedPrNotifier.js';
+import { addNotification, exists } from './notifications.js';
+
+const PR_URL = 'https://github.com/example-org/example-repo/pull/9';
+
+const followUp = (metadata = {}) => ({
+ id: 'sys-rl-1',
+ status: 'blocked',
+ metadata: {
+ reviewLoopFollowUp: true,
+ reviewLoopPRUrl: PR_URL,
+ reviewLoopPRBranch: 'cos/task-1/agent-1',
+ blockedReason: "App 'null' didn't resolve to a repository directory.",
+ blockedCategory: 'app-unresolved',
+ ...metadata,
+ },
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ exists.mockResolvedValue(false);
+});
+
+describe('notifyIfPrLeftOrphaned', () => {
+ it('notifies with the PR url when a merge follow-up transitions into blocked', async () => {
+ const raised = await notifyIfPrLeftOrphaned({ task: followUp(), previousStatus: 'pending' });
+ expect(raised).toBe(true);
+ expect(addNotification).toHaveBeenCalledWith(expect.objectContaining({
+ type: 'agent_warning',
+ priority: 'high',
+ link: PR_URL,
+ description: expect.stringContaining(PR_URL),
+ metadata: expect.objectContaining({
+ taskId: 'sys-rl-1', prUrl: PR_URL, prBranch: 'cos/task-1/agent-1',
+ }),
+ }));
+ // The block's own explanation is what tells the user how to unstick it.
+ expect(addNotification.mock.calls[0][0].description).toContain("didn't resolve");
+ });
+
+ // ~12 sites set `status: 'blocked'`; a follow-up blocked by max-retries or a
+ // failed worktree strands its PR exactly as hard as an unresolved app does.
+ it('fires for any blocking category, not just app-unresolved', async () => {
+ const task = followUp({ blockedCategory: 'max-retries', blockedReason: 'Task failed 3 times.' });
+ expect(await notifyIfPrLeftOrphaned({ task, previousStatus: 'in_progress' })).toBe(true);
+ });
+
+ it('falls back to the category when the block carries no reason', async () => {
+ const task = followUp({ blockedReason: undefined, blockedCategory: 'worktree-failed' });
+ await notifyIfPrLeftOrphaned({ task, previousStatus: 'pending' });
+ expect(addNotification.mock.calls[0][0].description).toContain('worktree-failed');
+ });
+
+ it('ignores an ordinary blocked task that is not landing a PR', async () => {
+ const task = { id: 't-plain', status: 'blocked', metadata: { blockedCategory: 'app-unresolved' } };
+ expect(await notifyIfPrLeftOrphaned({ task, previousStatus: 'pending' })).toBe(false);
+ expect(addNotification).not.toHaveBeenCalled();
+ });
+
+ it('ignores a task that is not blocked', async () => {
+ const task = { ...followUp(), status: 'pending' };
+ expect(await notifyIfPrLeftOrphaned({ task, previousStatus: 'blocked' })).toBe(false);
+ expect(addNotification).not.toHaveBeenCalled();
+ });
+
+ // `updateTask` re-emits `tasks:changed` on every later write to an already
+ // blocked task (an edit to its description is enough) — keying on the level
+ // rather than the edge would re-notify on each one.
+ it('ignores a re-emit for a task that was already blocked', async () => {
+ expect(await notifyIfPrLeftOrphaned({ task: followUp(), previousStatus: 'blocked' })).toBe(false);
+ expect(addNotification).not.toHaveBeenCalled();
+ });
+
+ it('does not stack a second card for a PR already notified about', async () => {
+ exists.mockResolvedValue(true);
+ expect(await notifyIfPrLeftOrphaned({ task: followUp(), previousStatus: 'pending' })).toBe(false);
+ expect(exists).toHaveBeenCalledWith('agent_warning', 'prUrl', PR_URL);
+ expect(addNotification).not.toHaveBeenCalled();
+ });
+
+ it('tolerates an empty payload', async () => {
+ expect(await notifyIfPrLeftOrphaned()).toBe(false);
+ expect(await notifyIfPrLeftOrphaned({})).toBe(false);
+ });
+});