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
stop filing CoS tasks at an app id that doesn't exist, and block the ones that are
[._.]/ Adam Eivyfb7a7c318695
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 15d62c3529..d1afd87c4c 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -31,3 +31,6 @@- Four sentinel/lifecycle gaps from the v2.40.0 diff are closed. A redirected X handoff (login wall, X redirect) left the Chrome tab it owned open forever, because `openXHandoff` verifies the landing path *after* taking ownership with `closeAfterRead: false` — the tab is now closed before the verification error bubbles. A pending-merge PR whose `gh pr view` fails permanently (deleted PR, renamed repo, revoked token) never ticked, so `MAX_PENDING_MERGE_TICKS` never fired and the entry re-shelled to `gh` forever with nothing surfaced; an unreadable cycle now counts as a tick and times out with a notification naming the PR. The `collaborators` author filter fetched the 100 *oldest* issues by any author and filtered them in memory, hiding a claimable collaborator-filed issue on any busy repo while `self` worked fine — it now fans out one server-side `--author` query per trusted login (capped at 25, with the truncation logged) and merges. And an `api` provider whose `/models` returns HTTP 200 with a non-JSON or unrecognized body no longer overwrites the stored model list with `[]` under a "Models refreshed" toast; it throws with the real reason and leaves the list untouched, the same posture the CLI arms already take. A genuinely empty catalog still saves as empty.- Three behaviors that shipped with a suite that stayed green when they were deleted now have tests that fail without them. The X reach feature's two safety gates — the 24h stale-approval window and the state-transition guard that stop an approval the user no longer intends from opening a compose window — plus its sync/draft-open re-entrancy guards and the numeric-status-id filter on ingested posts; the review loop's per-reviewer reasoning-effort map, whose whole feature could be dropped from the resolved options with nothing failing; and the remaining provider-benching cases, which asserted against hand-written `{ category, origin }` objects instead of running a transcript through the real detector — the exact pattern that let a genuine usage-limit regression ship green. Each new test was verified by deleting the line it names and watching it fail.+- **CoS tasks filed for PortOS's own work now actually run.** Two producers used `metadata.app` as a feature tag when it is workspace routing — it has to name a record in `data/apps.json`. The Series Pipeline autopilot filed every gap it found (unparseable script, stalled verify, failed render, run-ending error) at `app: pipeline`, and the auto-fixer filed its AI-provider investigations at `app: portos`, which matches neither the seeded app id (`portos-default`) nor its name. Both were harmless until the wrong-repo guard (#3180) closed the silent fall-through to the PortOS root: since then each of these tasks was filed and then rejected at every spawn attempt, so the one mechanism that surfaces an autopilot capability gap never reached an agent. Both now file with no app — which resolves to the PortOS workspace they were always meant to run in — and migration 234 un-routes the ones already queued on existing installs (re-stamping them so the fix wins the sync merge against a peer that hasn't upgraded).++- A CoS task naming an app that doesn't resolve to a repository directory is now **parked as blocked** instead of retried forever. The spawn guard refused to start the agent (correctly — it would otherwise commit into the PortOS checkout) but left the task `pending`, so the scheduler re-dequeued it every tick and reprinted the same error, while the fix was only visible in that task's own log. It now lands in the Blocked list, and the message covers both ways an app resolves to nothing: no Repository Path set, or nothing in Apps matching that id/name at all (in which case the fix is to clear the app from the task, not to register a path).diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.mdindex 3c723a711a..3008b999b1 100644--- a/docs/TROUBLESHOOTING.md+++ b/docs/TROUBLESHOOTING.md@@ -172,7 +172,7 @@ PortOS no longer falls back silently, so a misconfigured app now surfaces as one|---|---|| `❌ Workspace path does not exist: <path>` (run fails immediately) | The Repository Path points somewhere that isn't there. Fix it in Apps and re-run. || `❌ Workspace path is not a directory: <path>` | The Repository Path points at a file. Set it to the repo folder. |-| `❌ App '<id>' has no usable Repository Path` (CoS task is **blocked**, no agent starts) | The app record has an empty Repository Path, or couldn't be found at all. Set it in Apps, then re-run the task. |+| `❌ App '<id>' didn't resolve to a repository directory` (CoS task is **blocked**, no agent starts) | The app record has an empty Repository Path, or nothing in Apps matches that id/name at all. Set the path in Apps — or clear the app from the task if it doesn't belong to one — then re-run it. The task stays in **Blocked** until you do. |**Note for Windows**: use a real filesystem path with a drive letter (`C:\...`). Both `C:\Users\...` and `C:/Users/...` work, as does a leading `~`; a path inside OneDrive-redirected folders is fine as long as it exists locally.diff --git a/scripts/migrations/234-autopilot-gap-task-app-routing.js b/scripts/migrations/234-autopilot-gap-task-app-routing.jsnew file mode 100644index 0000000000..41ceeff403--- /dev/null+++ b/scripts/migrations/234-autopilot-gap-task-app-routing.js@@ -0,0 +1,155 @@+/**+ * Migration 234 — un-strand the CoS tasks routed at an app that doesn't exist.+ *+ * Background:+ * `metadata.app` on a CoS task is WORKSPACE ROUTING: it must name a record in+ * `data/apps.json`. Two producers used it as a feature/product TAG instead —+ * the series-autopilot gap filer (`app: 'pipeline'`, a PortOS feature, not a+ * managed app) and the auto-fixer's AI-provider investigation (`app: 'portos'`,+ * which matches neither the seeded id `portos-default` nor the name `PortOS`).+ *+ * That was harmless while an unresolvable app fell through to the PortOS root,+ * which is where both kinds of work belong anyway — until the #3180 guard+ * closed the fall-through: `prepareAgentWorkspace` now refuses to spawn an+ * agent whose app doesn't resolve to a repo path, precisely so an agent can't+ * silently commit into the PortOS checkout while claiming to work on someone's+ * app. Since then both kinds were filed and then rejected at every spawn.+ *+ * Both producers now pass no app (which resolves to the PortOS root), but+ * nothing rewrites the tasks already on disk, and every install that ran an+ * autopilot with `fileGaps` on — or hit a provider failure — has one or more+ * sitting in its queue that can never spawn.+ *+ * What it writes:+ * `data/TASKS.md` and `data/COS-TASKS.md` — deletes the mis-routed `- app: …`+ * metadata line from NON-COMPLETED tasks whose headline identifies one of the+ * two producers, and re-stamps `updatedAt` on each so the un-routed 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). Completed tasks keep theirs: they already ran, and their metadata is+ * history, not routing.+ *+ * Scoped to those headlines rather than to the app value outright, so an+ * install that legitimately registered an app *named* `pipeline` or `portos`+ * keeps its own tasks routed.+ *+ * A text-level rewrite rather than a parse/regenerate round-trip (the choice+ * migrations 146 and 225 made for these files): regenerating would reorder,+ * re-escape and re-sort every task in the user's live queue. The one thing+ * that costs us is moving a task between sections, so a task already BLOCKED+ * for this reason keeps its block — it is un-routed here and revived by the+ * user (or aged out by the blocked-task reaper) rather than being teleported+ * from `## Blocked` to `## Pending` by a text edit.+ *+ * Idempotent: a task with no mis-routed app line 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';++// 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*(.*)$/;++// The two mis-routed producers, keyed by the stable first line each writes.+// `fileGap` (seriesAutopilot/session.js) names a gap kind and a series uuid;+// `createAIProviderInvestigationTask` (autoFixer.js) names the provider/model.+const STRANDED = [+ { file: 'TASKS.md', headline: /^Autopilot \S+ gap — series \S+/, app: 'pipeline' },+ { file: 'COS-TASKS.md', headline: /^Investigate AI provider failure:/, app: 'portos' },+];++/**+ * Delete the mis-routed app line from every non-completed task of one producer,+ * re-stamping `updatedAt` on the ones changed. Pure — exported for the test.+ *+ * @param {string} markdown raw TASKS.md / COS-TASKS.md+ * @param {{ headline: RegExp, app: string, stamp: string }} producer+ * @returns {{ markdown: string, unrouted: string[] }} ids of the tasks fixed+ */+export function unrouteTasks(markdown, { headline, app, stamp }) {+ const lines = markdown.split('\n');+ const out = [];+ const unrouted = [];+ // Id of the task whose metadata block we are currently inside, when that task+ // is one this producer stranded; null everywhere else.+ let target = null;+ // Indices in `out` of the current target's app / updatedAt lines, so the+ // rewrite happens once the whole block has been seen.+ let appAt = -1;+ let stampAt = -1;+ let indent = ' ';++ // Drop the app line and refresh (or add) the LWW stamp on the block we just+ // finished walking. No-op unless this block actually carried the bad app.+ const finish = () => {+ if (target && appAt >= 0) {+ out.splice(appAt, 1);+ const stampLine = `${indent}- updatedAt: ${stamp}`;+ if (stampAt >= 0) out[stampAt > appAt ? stampAt - 1 : stampAt] = stampLine;+ else out.push(stampLine);+ unrouted.push(target);+ }+ target = null;+ appAt = -1;+ stampAt = -1;+ };++ for (const line of lines) {+ const meta = target ? line.match(METADATA_LINE) : null;+ if (meta) {+ indent = meta[1];+ if (meta[2] === 'app' && meta[3].trim() === app) appAt = out.length;+ else if (meta[2] === 'updatedAt') stampAt = out.length;+ out.push(line);+ continue;+ }+ // Any non-metadata line ends the block: the next task, a section heading,+ // or a blank line.+ finish();+ out.push(line);+ const header = line.match(TASK_LINE);+ // Completed tasks already ran; their metadata is history, not routing.+ if (header && header[1] !== 'x' && headline.test(header[3].trim())) target = header[2];+ }+ finish();++ return { markdown: out.join('\n'), unrouted };+}++export default {+ async up({ rootDir, now = new Date().toISOString() }) {+ const unrouted = [];+ let seenAFile = false;++ for (const producer of STRANDED) {+ const file = join(rootDir, 'data', producer.file);+ 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 = unrouteTasks(raw, { ...producer, stamp: now });+ if (!result.unrouted.length) continue;+ await atomicWrite(file, result.markdown);+ unrouted.push(...result.unrouted);+ }++ if (!seenAFile) {+ console.log('🔥 migration 234: no task queue on this install — nothing to un-route');+ return { ok: true, reason: 'no-task-file' };+ }+ if (!unrouted.length) {+ console.log('🔥 migration 234: no mis-routed tasks');+ return { ok: true, reason: 'already-unrouted', unrouted: 0 };+ }+ console.log(`🔥 migration 234: un-routed ${unrouted.length} task(s) from an app that does not exist`);+ return { ok: true, unrouted: unrouted.length };+ },+};diff --git a/scripts/migrations/234-autopilot-gap-task-app-routing.test.js b/scripts/migrations/234-autopilot-gap-task-app-routing.test.jsnew file mode 100644index 0000000000..5281e06cb7--- /dev/null+++ b/scripts/migrations/234-autopilot-gap-task-app-routing.test.js@@ -0,0 +1,116 @@+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, { unrouteTasks } from './234-autopilot-gap-task-app-routing.js';+import { parseTasksMarkdown } from '../../server/lib/taskParser.js';++const STAMP = '2026-08-09T12:00:00.000Z';+const GAP = { headline: /^Autopilot \S+ gap — series \S+/, app: 'pipeline', stamp: STAMP };++const gapTask = (id, { mark = ' ', app = 'pipeline', updatedAt = '2026-08-01T00:00:00.000Z' } = {}) => [+ `- [${mark}] #${id} | MEDIUM | Autopilot script-unparseable gap — series 11111111-2222-3333-4444-555555555555`,+ ' - context: the comic script has no parseable pages',+ ...(app ? [` - app: ${app}`] : []),+ ...(updatedAt ? [` - updatedAt: ${updatedAt}`] : []),+].join('\n');++const queue = (...tasks) => ['# Tasks', '', '## Pending', ...tasks, ''].join('\n');++describe('unrouteTasks', () => {+ it('drops the mis-routed app line and keeps the rest of the task', () => {+ const { markdown, unrouted } = unrouteTasks(queue(gapTask('task-1')), GAP);+ expect(unrouted).toEqual(['task-1']);+ // Parsed back through the REAL parser — the surviving metadata has to still+ // read, not merely look right in the raw text.+ const [task] = parseTasksMarkdown(markdown);+ expect(task.metadata.app).toBeUndefined();+ expect(task.metadata.context).toBe('the comic script has no parseable pages');+ });++ // A peer that hasn't migrated still holds the routed 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 un-routed copy wins the federation merge', () => {+ const { markdown } = unrouteTasks(queue(gapTask('task-1')), GAP);+ expect(parseTasksMarkdown(markdown)[0].metadata.updatedAt).toBe(STAMP);+ });++ it('adds the stamp when the task carries none', () => {+ const { markdown, unrouted } = unrouteTasks(queue(gapTask('task-1', { updatedAt: null })), GAP);+ expect(unrouted).toEqual(['task-1']);+ const [task] = parseTasksMarkdown(markdown);+ expect(task.metadata.app).toBeUndefined();+ expect(task.metadata.updatedAt).toBe(STAMP);+ });++ it('un-routes in-progress, blocked and challenged tasks too', () => {+ const md = queue(gapTask('task-p'), gapTask('task-i', { mark: '~' }), gapTask('task-b', { mark: '!' }), gapTask('task-c', { mark: '?' }));+ expect(unrouteTasks(md, GAP).unrouted).toEqual(['task-p', 'task-i', 'task-b', 'task-c']);+ });++ it('leaves a completed task alone — it already ran, its metadata is history', () => {+ const md = queue(gapTask('task-done', { mark: 'x' }));+ expect(unrouteTasks(md, GAP)).toEqual({ markdown: md, unrouted: [] });+ });++ it('leaves every task from another producer routed, including one on a real app named pipeline', () => {+ const other = ['- [ ] #task-2 | HIGH | Fix the failing test', ' - app: pipeline'].join('\n');+ const { markdown, unrouted } = unrouteTasks(queue(gapTask('task-1'), other), GAP);+ expect(unrouted).toEqual(['task-1']);+ expect(parseTasksMarkdown(markdown).find((t) => t.id === 'task-2').metadata.app).toBe('pipeline');+ });++ it('leaves a gap task routed at a different app alone', () => {+ const md = queue(gapTask('task-1', { app: 'booklooom' }));+ expect(unrouteTasks(md, GAP)).toEqual({ markdown: md, unrouted: [] });+ });++ it('skips a gap task that carries no app line', () => {+ const md = queue(gapTask('task-1', { app: null }));+ expect(unrouteTasks(md, GAP)).toEqual({ markdown: md, unrouted: [] });+ });+});++describe('migration 234 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-234-'));+ 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('unsticks a gap task that can never spawn while it names a non-existent app', async () => {+ await writeFile(userTasks(), queue(gapTask('task-msl2dqxk')));+ await expect(migration.up({ rootDir })).resolves.toMatchObject({ ok: true, unrouted: 1 });+ const [task] = parseTasksMarkdown(await readFile(userTasks(), 'utf-8'));+ expect(task.metadata.app).toBeUndefined();+ });++ // The auto-fixer's provider investigations were stranded the same way, on the+ // internal queue, at an app id no install has ('portos' vs 'portos-default').+ it('un-routes the auto-fixer provider investigations in the internal queue', async () => {+ const investigation = [+ '- [ ] #sys-1 | MEDIUM | APPROVAL | Investigate AI provider failure: claude (claude-opus-5)',+ ' - app: portos',+ ' - updatedAt: 2026-08-01T00:00:00.000Z',+ ].join('\n');+ await writeFile(cosTasks(), queue(investigation));+ await expect(migration.up({ rootDir })).resolves.toMatchObject({ ok: true, unrouted: 1 });+ const [task] = parseTasksMarkdown(await readFile(cosTasks(), 'utf-8'));+ expect(task.metadata.app).toBeUndefined();+ });++ it('is idempotent — a second run leaves the file byte-identical', async () => {+ await writeFile(userTasks(), queue(gapTask('task-1')));+ await migration.up({ rootDir });+ const first = await readFile(userTasks(), 'utf-8');+ await expect(migration.up({ rootDir })).resolves.toMatchObject({ reason: 'already-unrouted' });+ expect(await readFile(userTasks(), 'utf-8')).toBe(first);+ });+});diff --git a/server/services/agentWorkspacePrep.js b/server/services/agentWorkspacePrep.jsindex ca0b7b99e9..6e346025dd 100644--- a/server/services/agentWorkspacePrep.js+++ b/server/services/agentWorkspacePrep.js@@ -39,6 +39,29 @@ import { getAppWorkspace, getAppDataForTask, createJiraTicketForTask } from './aconst ROOT_DIR = PATHS.root;+/**+ * Park a task this module refuses to spawn, so the refusal is durable and+ * visible rather than a log line the scheduler reprints every tick.+ *+ * An un-persisted `blocked` outcome leaves the task `pending`: it is+ * re-dequeued, re-prepped and re-rejected forever, and the thing that would fix+ * it ("set the Repository Path in Apps") is only reachable from that task's own+ * log. Blocking puts it in the Blocked list carrying the instruction and leaves+ * it revivable once the config is fixed. Best-effort — the caller's block+ * outcome must stand even if the write fails.+ */+async function blockTask(task, reason, blockedCategory) {+ await updateTask(task.id, {+ status: 'blocked',+ metadata: {+ ...task.metadata,+ blockedReason: reason,+ blockedCategory,+ blockedAt: new Date().toISOString(),+ },+ }, task.taskType || 'user').catch(() => {});+}+/*** Prepare the workspace (and any worktree/JIRA branch) for an agent task.*@@ -63,9 +86,16 @@ export async function prepareAgentWorkspace({ agentId, task }) {// each of the three spawn helpers (TUI / runner / direct), which all take// their cwd from this function.if (task.metadata?.app && !workspacePath) {- const reason = `App '${task.metadata.app}' has no usable Repository Path — set it in Apps, then re-run this task. `+ // The reason line is now the whole Blocked card, so it has to cover both+ // ways this resolves to nothing: the app is registered but carries no+ // Repository Path, OR nothing in Apps matches that id/name at all (the+ // shape a task gets when a producer used `app` as a feature tag rather+ // than as routing — see migration 234).+ const reason = `App '${task.metadata.app}' didn't resolve to a repository directory — it must name an app in Apps `+ + `that has a Repository Path set. Fix the app (or clear it from the task), then re-run this task. `+ `(The agent was not started, so it could not write into the PortOS directory by mistake.)`;emitLog('error', `❌ ${reason}`, { taskId: task.id });+ await blockTask(task, reason, 'app-unresolved');return { outcome: 'blocked', reason };}// Same resolver the /runs spawn paths use, so a `~/Projects/App` repoPath@@ -78,6 +108,10 @@ export async function prepareAgentWorkspace({ agentId, task }) {} catch (err) {const reason = `${err.message} (Task blocked before the agent started, so it could not write into the PortOS directory by mistake.)`;emitLog('error', `❌ ${reason}`, { taskId: task.id, workspace: workspacePath });+ // A task with no `app` lands here only if the PortOS root itself is+ // unusable, which is a different problem than a mis-configured app record —+ // don't file it under the app category.+ await blockTask(task, reason, task.metadata?.app ? 'app-unresolved' : 'workspace-invalid');return { outcome: 'blocked', reason };}@@ -281,15 +315,7 @@ export async function prepareAgentWorkspace({ agentId, task }) {// since there the worktree was only a recommendation, not a request.)const reason = `Worktree creation failed for task ${task.id}; refusing to run in the shared workspace because isolation was explicitly requested`;emitLog('warn', `🌳 ${reason}`, { taskId: task.id });- await updateTask(task.id, {- status: 'blocked',- metadata: {- ...task.metadata,- blockedReason: 'Worktree creation failed — isolation was explicitly requested',- blockedCategory: 'worktree-failed',- blockedAt: new Date().toISOString(),- },- }, task.taskType || 'user').catch(() => {});+ await blockTask(task, 'Worktree creation failed — isolation was explicitly requested', 'worktree-failed');return { outcome: 'blocked', reason };}} else if (!jiraBranchName && !isFalsyMeta(task.metadata?.useWorktree)) {diff --git a/server/services/agentWorkspacePrep.test.js b/server/services/agentWorkspacePrep.test.jsindex e6e7b65359..9a3fc5a555 100644--- a/server/services/agentWorkspacePrep.test.js+++ b/server/services/agentWorkspacePrep.test.js@@ -35,6 +35,7 @@ vi.mock('./agentPromptBuilder.js', () => ({}));import { prepareAgentWorkspace } from './agentWorkspacePrep.js';+import { updateTask } from './cos.js';import { ensureLatest } from './git.js';import { detectConflicts } from './taskConflict.js';import { getAppWorkspace } from './agentPromptBuilder.js';@@ -124,6 +125,33 @@ describe('prepareAgentWorkspace — workspace validation (#3180)', () => {expect(r.outcome).toBe('ready');expect(r.workspacePath).toBe(process.cwd());});++ // Returning `blocked` without persisting it left the task `pending`, so the+ // scheduler re-dequeued it every tick and re-logged the same ❌ forever — the+ // instruction ("set it in Apps") only ever reachable from that log.+ it('parks the task as blocked so it stops being re-dequeued every tick', async () => {+ getAppWorkspace.mockResolvedValue(null);+ const task = { id: 't-park', taskType: 'user', metadata: { app: 'pipeline', context: 'keep me' } };+ await prepareAgentWorkspace({ agentId: 'agent-park', task });+ expect(updateTask).toHaveBeenCalledWith('t-park', expect.objectContaining({+ status: 'blocked',+ metadata: expect.objectContaining({+ blockedCategory: 'app-unresolved',+ blockedReason: expect.stringContaining('Repository Path'),+ context: 'keep me',+ }),+ }), 'user');+ });++ it('parks the task as blocked when the repo path exists in Apps but not on disk', async () => {+ getAppWorkspace.mockResolvedValue('/definitely/not/a/real/repo/path');+ const task = { id: 't-park2', taskType: 'user', metadata: { app: 'primes' } };+ await prepareAgentWorkspace({ agentId: 'agent-park2', task });+ expect(updateTask).toHaveBeenCalledWith('t-park2', expect.objectContaining({+ status: 'blocked',+ metadata: expect.objectContaining({ blockedCategory: 'app-unresolved' }),+ }), 'user');+ });});// A run killed by a server restart never reaches its completion hook, so itsdiff --git a/server/services/autoFixer.js b/server/services/autoFixer.jsindex 050ccece3e..2562342c91 100644--- a/server/services/autoFixer.js+++ b/server/services/autoFixer.js@@ -528,7 +528,15 @@ async function createAIProviderInvestigationTask(error) {priority: 'MEDIUM',context,diagnostics,- app: 'portos', // Associate with PortOS app+ // No `app`. `metadata.app` is WORKSPACE ROUTING — it must name a record in+ // `data/apps.json` — and 'portos' matches neither the seeded id+ // ('portos-default') nor its name ('PortOS'), so it resolved to nothing.+ // That was harmless while an unresolvable app fell through to the PortOS+ // root, which is where this work belongs anyway; since the #3180 guard,+ // `prepareAgentWorkspace` refuses to spawn an agent whose app doesn't+ // resolve to a repo path, so every provider investigation was filed and+ // then rejected. Absent `app` resolves to that same PortOS root, and+ // matches the other two task producers in this file.approvalRequired: true // Require user approval before investigating};diff --git a/server/services/pipeline/seriesAutopilot.test.js b/server/services/pipeline/seriesAutopilot.test.jsindex b3b29abf9a..9dc57867bd 100644--- a/server/services/pipeline/seriesAutopilot.test.js+++ b/server/services/pipeline/seriesAutopilot.test.js@@ -2209,6 +2209,21 @@ describe('autopilot conductor', () => {expect(addTask.mock.calls[0][0].description).toMatch(/verifyArc-stalled/);});+ // `metadata.app` is workspace routing, not a feature tag: it must name a+ // record in data/apps.json. Filing these at 'pipeline' made every gap task+ // unspawnable once prepareAgentWorkspace started refusing an app that+ // resolves to no repo path (#3180) — the task was filed, then blocked.+ it('files gap tasks with no app so they run in the PortOS workspace', async () => {+ verifyFindings = [{ severity: 'high', problem: 'unresolved plot hole' }];+ const { seriesId } = await seedComplete();+ await autopilot.startSeriesAutopilot(seriesId, { fileGaps: true, maxArcVerifyRounds: 1 });+ await waitFor(runFinished(seriesId));+ expect(addTask).toHaveBeenCalled();+ for (const [taskData] of addTask.mock.calls) {+ expect(taskData.app).toBeUndefined();+ }+ });+it('recoverStuckAutopilots demotes a running marker to paused', async () => {const series = await seriesSvc.createSeries({ name: 'S', logline: 'L', premise: 'P' });await seriesSvc.updateSeries(series.id, { autopilot: { status: 'running', runId: 'dead' } });diff --git a/server/services/pipeline/seriesAutopilot/session.js b/server/services/pipeline/seriesAutopilot/session.jsindex 4e0580f482..6eba5bf168 100644--- a/server/services/pipeline/seriesAutopilot/session.js+++ b/server/services/pipeline/seriesAutopilot/session.js@@ -104,11 +104,20 @@ export async function persistMarker(seriesId, patch) {// issue) so cosTaskStore.addTask's pending/in_progress dedup collapses repeats// instead of spamming a task per page / per run. Best-effort — a task-store// failure must never abort the autopilot.+//+// No `app` is passed. `metadata.app` is WORKSPACE ROUTING — it must name a+// record in `data/apps.json` — not a feature tag. These gaps are work on+// PortOS's own pipeline code, so the correct workspace is the PortOS root,+// which is exactly what an absent `app` resolves to. Passing the feature name+// `'pipeline'` made every gap task unrunnable once the #3180 guard landed:+// `prepareAgentWorkspace` refuses to spawn an agent whose app doesn't resolve+// to a repo path, so the task was filed and then blocked at every spawn+// attempt. Same reasoning as the investigation tasks in agentErrorAnalysis.js.export async function fileGap(record, sId, { gapKind, issueId = null, summary, context = '' }) {if (!record.options.fileGaps || record.mode !== 'execute') return;const idTag = `series ${sId}${issueId ? ` issue ${issueId}` : ''}`;const description = `Autopilot ${gapKind} gap — ${idTag}\n\n${summary}`;- const result = await cosTaskStore.addTask({ description, context, app: 'pipeline' }, 'user')+ const result = await cosTaskStore.addTask({ description, context }, 'user').catch((err) => { console.log(`⚠️ autopilot: fileGap (${gapKind}) failed: ${err.message}`); return null; });if (result && !result.duplicate) {broadcast(sId, { type: 'gap:filed', gapKind, issueId, taskId: result.id });