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

address review (codex): reach spilled metadata, honour a relocated queue, and treat a workspace block as a pause

[._.]/ Adam Eivy644b24b5682b
diff --git a/scripts/migrations/234-autopilot-gap-task-app-routing.js b/scripts/migrations/234-autopilot-gap-task-app-routing.js
index 41ceeff403..343e7bf8e0 100644
--- a/scripts/migrations/234-autopilot-gap-task-app-routing.js
+++ b/scripts/migrations/234-autopilot-gap-task-app-routing.js
@@ -59,10 +59,27 @@ const METADATA_LINE = /^(\s+)-\s*(\w+):\s*(.*)$/;
// `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' },
+ { configKey: 'userTasksFile', file: 'data/TASKS.md', headline: /^Autopilot \S+ gap — series \S+/, app: 'pipeline' },
+ { configKey: 'cosTasksFile', file: 'data/COS-TASKS.md', headline: /^Investigate AI provider failure:/, app: 'portos' },
];
+/**
+ * Repo-relative path of a queue file, honouring an install that moved it in
+ * `data/cos/state.json` (`config.userTasksFile` / `config.cosTasksFile` — the
+ * same values `cosTaskStore` reads). Migrating only the defaults would record
+ * this migration as applied while the live queue stayed 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 STRANDED.map((producer) => ({
+ ...producer,
+ file: typeof config[producer.configKey] === 'string' && config[producer.configKey]
+ ? config[producer.configKey]
+ : producer.file,
+ }));
+}
+
/**
* 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.
@@ -75,13 +92,14 @@ 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.
+ // Id of the task whose 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.
+ // Indices in `out` of the current target's app / updatedAt / last metadata
+ // lines, so the rewrite happens once the whole block has been seen.
let appAt = -1;
let stampAt = -1;
+ let lastMetaAt = -1;
let indent = ' ';
// Drop the app line and refresh (or add) the LWW stamp on the block we just
@@ -89,32 +107,48 @@ export function unrouteTasks(markdown, { headline, app, stamp }) {
const finish = () => {
if (target && appAt >= 0) {
out.splice(appAt, 1);
+ const shift = (i) => (i > appAt ? i - 1 : i);
const stampLine = `${indent}- updatedAt: ${stamp}`;
- if (stampAt >= 0) out[stampAt > appAt ? stampAt - 1 : stampAt] = stampLine;
- else out.push(stampLine);
+ if (stampAt >= 0) out[shift(stampAt)] = stampLine;
+ // No stamp yet — insert one directly after the last metadata line rather
+ // than at the end of the block, so it can't land after a description that
+ // spilled onto its own lines (see the block-scan note below). `lastMetaAt`
+ // is the right index post-splice either way: when a later metadata line
+ // exists it shifted down one, so inserting there lands just after it; when
+ // the app line WAS the last metadata line, that index is the hole it left.
+ else out.splice(lastMetaAt, 0, stampLine);
unrouted.push(target);
}
target = null;
appAt = -1;
stampAt = -1;
+ lastMetaAt = -1;
};
for (const line of lines) {
+ const header = line.match(TASK_LINE);
+ // A task's block runs to the NEXT task header or section heading — not to
+ // the first non-metadata line. A description written with embedded newlines
+ // is interpolated into the file verbatim by `generateTasksMarkdown`, so a
+ // freshly-filed task can carry blank/prose lines between its header and its
+ // metadata (they are dropped on the next parse round-trip, but a migration
+ // may well run before that happens). Ending the block at those lines would
+ // walk right past the `app:` line this migration exists to remove.
+ if (header || line.startsWith('#')) {
+ finish();
+ out.push(line);
+ // Completed tasks already ran; their metadata is history, not routing.
+ if (header && header[1] !== 'x' && headline.test(header[3].trim())) target = header[2];
+ continue;
+ }
const meta = target ? line.match(METADATA_LINE) : null;
if (meta) {
indent = meta[1];
+ lastMetaAt = out.length;
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();
@@ -126,8 +160,8 @@ export default {
const unrouted = [];
let seenAFile = false;
- for (const producer of STRANDED) {
- const file = join(rootDir, 'data', producer.file);
+ for (const producer of await queuePaths(rootDir)) {
+ const file = join(rootDir, producer.file);
const raw = await readFile(file, 'utf-8').catch((err) => {
if (err.code === 'ENOENT') return null;
throw err;
diff --git a/scripts/migrations/234-autopilot-gap-task-app-routing.test.js b/scripts/migrations/234-autopilot-gap-task-app-routing.test.js
index 5281e06cb7..be6048a7a8 100644
--- a/scripts/migrations/234-autopilot-gap-task-app-routing.test.js
+++ b/scripts/migrations/234-autopilot-gap-task-app-routing.test.js
@@ -69,6 +69,37 @@ describe('unrouteTasks', () => {
const md = queue(gapTask('task-1', { app: null }));
expect(unrouteTasks(md, GAP)).toEqual({ markdown: md, unrouted: [] });
});
+
+ // `generateTasksMarkdown` interpolates the description verbatim, so a task
+ // filed with embedded newlines sits in the file with prose/blank lines between
+ // its header and its metadata until the next parse round-trip flattens it. A
+ // scan that stopped at the first non-metadata line would walk right past the
+ // `app:` line and leave the task stranded.
+ it('reaches the metadata past a description that spilled onto its own lines', () => {
+ const spilled = [
+ '- [ ] #task-1 | MEDIUM | Autopilot script-unparseable gap — series 11111111-2222-3333-4444-555555555555',
+ '',
+ 'The comic script has no parseable pages.',
+ ' - app: pipeline',
+ ' - updatedAt: 2026-08-01T00:00:00.000Z',
+ ].join('\n');
+ const { markdown, unrouted } = unrouteTasks(queue(spilled), GAP);
+ expect(unrouted).toEqual(['task-1']);
+ expect(markdown).not.toContain('- app: pipeline');
+ expect(markdown).toContain(`- updatedAt: ${STAMP}`);
+ expect(markdown).toContain('The comic script has no parseable pages.');
+ });
+
+ it('inserts a missing stamp with the metadata, not after trailing prose', () => {
+ const spilled = [
+ '- [ ] #task-1 | MEDIUM | Autopilot script-unparseable gap — series 11111111-2222-3333-4444-555555555555',
+ ' - app: pipeline',
+ 'trailing prose line',
+ ].join('\n');
+ const { markdown } = unrouteTasks(queue(spilled), GAP);
+ const lines = markdown.split('\n');
+ expect(lines[lines.indexOf('trailing prose line') - 1]).toBe(` - updatedAt: ${STAMP}`);
+ });
});
describe('migration 234 up()', () => {
@@ -106,6 +137,21 @@ describe('migration 234 up()', () => {
expect(task.metadata.app).toBeUndefined();
});
+ // An install that moved its queue in data/cos/state.json must be migrated
+ // there — migrating only the default path records this as applied while the
+ // live queue stays stranded.
+ it('follows a relocated queue path from the CoS config', async () => {
+ await mkdir(join(rootDir, 'data', 'cos'), { recursive: true });
+ await writeFile(join(rootDir, 'data', 'cos', 'state.json'),
+ JSON.stringify({ config: { userTasksFile: 'data/cos/MY-TASKS.md' } }));
+ const relocated = join(rootDir, 'data', 'cos', 'MY-TASKS.md');
+ await writeFile(relocated, queue(gapTask('task-1')));
+ await writeFile(userTasks(), queue(gapTask('task-untouched')));
+ await expect(migration.up({ rootDir })).resolves.toMatchObject({ ok: true, unrouted: 1 });
+ expect(parseTasksMarkdown(await readFile(relocated, 'utf-8'))[0].metadata.app).toBeUndefined();
+ expect(parseTasksMarkdown(await readFile(userTasks(), 'utf-8'))[0].metadata.app).toBe('pipeline');
+ });
+
it('is idempotent — a second run leaves the file byte-identical', async () => {
await writeFile(userTasks(), queue(gapTask('task-1')));
await migration.up({ rootDir });
diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.js
index acf1627633..7c4cb29b18 100644
--- a/server/services/cosTaskStore.js
+++ b/server/services/cosTaskStore.js
@@ -44,6 +44,17 @@ export const PRIORITY_VALUES = {
const CLAIM_KEY_SET = new Set(CLAIM_METADATA_KEYS);
+// Blocked categories that mean "paused until something outside the task
+// changes", not "this task is finished with". A pause keeps the resume pointer
+// (see updateTask) and is never auto-expired by the failure reaper (see
+// NON_REAPABLE_BLOCKED_CATEGORIES, which includes these) — the task is expected
+// to run again once the cooldown lapses or the user fixes the config.
+export const PAUSED_BLOCKED_CATEGORIES = new Set([
+ 'orphan-cooldown', // timed cooldown; unblockExpiredOrphanCooldowns revives it
+ 'app-unresolved', // the task's app has no usable Repository Path
+ 'workspace-invalid' // the resolved workspace isn't a usable directory
+]);
+
// A task is terminal once it is completed or blocked — the same set cosTaskMerge's
// release-on-transition uses. Consumed by the LI cross-peer verdict consume (#2779) to
// spot a non-terminal→terminal ADOPTION (a failed hand-off blocks, a clean one completes;
@@ -545,12 +556,16 @@ export async function updateTask(taskId, updates, taskType = 'user', { now = Dat
// long-merged branch. Only cleared on terminal statuses — a `pending` retry is
// exactly who needs the pointer intact.
//
- // An `orphan-cooldown` block is the exception: it is a TIMED PAUSE, not a
- // terminal state — `unblockExpiredOrphanCooldowns` (cosTaskGenerator.js) flips it
- // back to `pending` on its own once `cooldownUntil` passes. Stripping the pointer
- // there means the revived task starts clean and abandons the worktree its dead
- // agent left behind, which is exactly the recovery this mechanism exists for.
- if (isTerminalTaskStatus(updates.status) && updatedMetadata.blockedCategory !== 'orphan-cooldown') {
+ // PAUSE-shaped blocks are the exception (`PAUSED_BLOCKED_CATEGORIES`): the task
+ // is waiting on something outside itself and is expected to run again, so its
+ // pointer is not spent. `orphan-cooldown` is a TIMED pause —
+ // `unblockExpiredOrphanCooldowns` (cosTaskGenerator.js) flips it back to
+ // `pending` once `cooldownUntil` passes. The workspace blocks are a CONFIG pause:
+ // the app's Repository Path is missing/unreachable, and the user fixes it and
+ // revives the task. Stripping the pointer in either case means the revived task
+ // starts clean and abandons the worktree its dead agent left behind — which is
+ // exactly the recovery this mechanism exists for.
+ if (isTerminalTaskStatus(updates.status) && !PAUSED_BLOCKED_CATEGORIES.has(updatedMetadata.blockedCategory)) {
delete updatedMetadata.existingBranch;
delete updatedMetadata.resumedFromAgentId;
delete updatedMetadata.resumeWorktreePath;
@@ -805,7 +820,14 @@ export const DEFAULT_REAP_LIMIT = 50;
const NON_REAPABLE_BLOCKED_CATEGORIES = new Set([
'user-terminated', // user explicitly stopped the agent
'agent-paused', // user paused; resumable on demand
- 'challenge-escalation' // parked awaiting the user's arbitration
+ 'challenge-escalation', // parked awaiting the user's arbitration
+ // The workspace blocks are an OPEN user decision, not a stale failure: the task
+ // is waiting for the app's Repository Path to be fixed, and auto-completing it
+ // at 14 days would silently retire work nobody decided to drop. (The third
+ // pause category, `orphan-cooldown`, stays reapable — it revives itself in
+ // ~30 minutes, so one still sitting there after 14 days IS stale.)
+ 'app-unresolved',
+ 'workspace-invalid'
]);
// Durable marker + legacy-headline fallback for an investigation task. Kept
diff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.js
index 167e3ca8e6..c271ece5ac 100644
--- a/server/services/cosTaskStore.test.js
+++ b/server/services/cosTaskStore.test.js
@@ -713,6 +713,23 @@ describe('cosTaskStore.updateTask', () => {
expect(cooled.metadata.resumeWorktreePath).toBe('/w/agent-x');
});
+ // A workspace block is a CONFIG pause on the same footing: the app's Repository
+ // Path is missing/unreachable, the user fixes it and revives the task. Dropping
+ // the pointer there abandons the uncommitted work in the leftover worktree for a
+ // problem that had nothing to do with the task.
+ it('keeps the resume pointer through an app-unresolved block', async () => {
+ await addTask({ description: 'unrouted', id: 'task-unrouted' }, 'user');
+ await updateTask('task-unrouted', {
+ metadata: { existingBranch: 'cos/b', resumedFromAgentId: 'agent-x', resumeWorktreePath: '/w/agent-x' }
+ }, 'user');
+ const blocked = await updateTask('task-unrouted', {
+ status: 'blocked',
+ metadata: { blockedCategory: 'app-unresolved' }
+ }, 'user');
+ expect(blocked.metadata.existingBranch).toBe('cos/b');
+ expect(blocked.metadata.resumeWorktreePath).toBe('/w/agent-x');
+ });
+
it('releases the federation claim/lease when a task leaves in_progress (#1563)', async () => {
await addTask({ description: 'claimed', id: 'task-claimed' }, 'user');
// Spawn-time claim: status in_progress carries the claim metadata.
@@ -1095,7 +1112,10 @@ describe('cosTaskStore — stale failure-artifact reaper (#2619)', () => {
});
it('leaves user-intent / open-decision categories alone', () => {
- for (const cat of ['user-terminated', 'agent-paused', 'challenge-escalation']) {
+ // The workspace blocks are an open decision too: the task waits for the
+ // user to fix the app's Repository Path, so auto-completing it at 14 days
+ // would silently retire work nobody decided to drop.
+ for (const cat of ['user-terminated', 'agent-paused', 'challenge-escalation', 'app-unresolved', 'workspace-invalid']) {
expect(blockedFailureAgeMs(blocked(cat, daysAgo(30)), NOW)).toBeNull();
expect(isReapableBlockedFailure(blocked(cat, daysAgo(30)), { now: NOW })).toBe(false);
}