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: normalize taskType for direct task:ready emits so internal tasks write to COS-TASKS.md (#2633)

Adam Eivyf8a019613e9d
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 4624898cff..7a59d8a700 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -39,6 +39,8 @@
- **Retry lazy route chunks before failing on flaky mobile networks.** Lazy-loaded pages fetch their JS chunk on demand, and on a weak cellular/Wi-Fi link that fetch can fail on a transient blip ("Importing a module script failed" on Safari, "Failed to fetch dynamically imported module" on Chrome) even though the chunk still exists — a page reload can't fix a network hiccup, so once the one-shot stale-chunk reload was spent for a build, the next blip stranded the user on the error screen. `lazyWithReload` now retries the dynamic import twice with a short backoff before treating the failure as terminal, so a transient mobile-network failure recovers silently without a jarring reload; a genuinely stale chunk (renamed by a rebuild) still 404s on each quick retry and falls through to the existing reload-once path. New `importWithRetry` helper with unit coverage.
- **[issue-2643] De-flake the Wiki vault-default test under full-suite load.** `Wiki.test.jsx`'s "defaults to the first vault" (and the sibling "restores the selected vault") assertions checked `scanNotesVault` synchronously right after `await waitFor(...)` on the rendered vault id. That mock call is fired by a *separate* `useEffect` keyed on the selected vault, so the committed overview render can land before the passive effect flushes — reliably true in isolation, but on a CPU-saturated full client run the bare assertion raced ahead of the effect and failed (`expected vi.fn() to be called with arguments`). The two mock-call assertions now sit inside their own `waitFor`, awaiting the async side-effect instead of sampling it. Test-only change (no `test.retry` or timeout inflation) — no runtime behavior change.
+
+- **[issue-2633] Direct `task:ready` emits now claim against the right task file.** The Creative Director bridge, the on-demand `dequeueNextTask`, and `spawnPriority0OnDemand` publish task records with no `taskType`, so an internal (`sys-*`/`cd-*`/`app-improve-*`) task's claim/in_progress `updateTask` fell back to `'user'`, targeted TASKS.md instead of COS-TASKS.md, missed the record, and returned a truthy `{ error }` object the `if (!updateResult)` check silently swallowed — leaving the task un-claimed while the agent spawned anyway. `runAgentSpawn` now normalizes `taskType` from the id via `isInternalTaskId` up front (mirroring the completion path), and the in_progress-claim check rejects the `{ error }` shape (not just `null`) and warn-logs the miss so it's no longer silent.
- **[issue-2540] Stop full-JSONB table loads for pipeline issue id sweeps and bound the multi-account message inbox aggregate.** `listIssueIds` (the conflict-journal orphan-base-hash sweep + tombstone GC) went through `readState()` → `loadAll()`, pulling every issue's full `data` JSONB — up to ~12MB of stage `runHistory` each — into memory only to read the ids; it now sources the store's `SELECT id` projection, with the PG backend filtering tombstones via the mirrored `deleted` column (`listIds({ includeDeleted })`) so the whole-record load is skipped entirely for the default live sweep. Separately, `messageSync.getMessages`'s multi-account inbox spread every message from every account into one array and globally sorted it before slicing a page; it now bounds each account's contribution to the top `offset+limit` by date and merges those heads, so a paged inbox reads `accounts × (offset+limit)` messages into the merge instead of the full cross-account total (the exact `total` count is preserved).
- **[issue-2538] Bound Spotify auth and privacy-broker fetches, and single-flight token refresh.** The Spotify token endpoint (`spotifyAuth.js`) and the BADBOOL / CA-registry broker fetchers (`privacyBrokers.js`) used bare `fetch` with no timeout, so a hung `accounts.spotify.com` could stall an OAuth callback or a history-sync refresh — and a broker source that never responded could hang a user-triggered refresh — indefinitely. All three now go through the shared `fetchWithTimeout` helper with a 15s cap. Separately, concurrent `getAccessToken()` callers that all found the token expired each POSTed their own refresh, and since Spotify rotates the grant the losers persisted a stale token (last-write-wins); refreshes now share one in-flight `refreshPromise` (single-flight), so the grant is rotated exactly once and the guard is released on settle so a failed refresh can retry.
- **[issue-2552] Enlarge above-the-fold mobile touch targets to 44px.** The GoalDetailPanel close button (`p-1` + a 16px icon, ~24px) and the notification bell (40px min) were below the 44×44 touch-target minimum the shell's other chrome controls already meet. The close button now uses `min-h-[44px] min-w-[44px]` centered around its icon (matching the shared `Drawer` control sizing), and the bell's mobile hit area is bumped 40→44px (its `sm:` desktop shrink is unchanged). The notification panel also gains `max-w-[calc(100vw-2rem)]` so its `w-80` width can't overflow a narrow mobile sidebar, and the ⌘K result rows get a `min-h-[44px]` so each is comfortably tappable.
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 84f1be84d3..db441eab4a 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -142,6 +142,18 @@ export async function spawnAgentForTask(task) {
* early `return null` and any throw is covered by the wrapper's release.
*/
async function runAgentSpawn(task) {
+ // Normalize taskType once, up front (issue #2633). Direct `task:ready` emits —
+ // the Creative Director bridge, `dequeueNextTask`, and `spawnPriority0OnDemand` —
+ // publish task records without a `taskType`. Every claim/in_progress `updateTask`
+ // below falls back to `task.taskType || 'user'`, so an internal-file (`sys-*`)
+ // task without taskType would target TASKS.md instead of COS-TASKS.md, miss the
+ // record, and return a truthy `{ error }` object the `if (!updateResult)` check
+ // does not catch. Derive the type from the id here (mirrors the completion path,
+ // ~line 1084) so every write below routes to the correct file.
+ if (task && !task.taskType) {
+ task.taskType = isInternalTaskId(task.id || '') ? 'internal' : 'user';
+ }
+
// Cross-instance claim guard (issue #1563, acceptance criterion 2). When this
// task list is shared with a federated peer (full-sync mode, #1561), the peer
// may already be working this task. Refuse to spawn while another instance
@@ -490,7 +502,14 @@ async function runAgentSpawn(task) {
console.error(`❌ Failed to mark task ${task.id} as in_progress: ${err.message}`);
return null;
});
- if (!updateResult) {
+ // Catch BOTH failure shapes: a null from the `.catch` above (updateTask threw)
+ // and a truthy `{ error }` object from a silent miss — e.g. the task id isn't
+ // present in the file for `task.taskType` (issue #2633). A bare `if (!updateResult)`
+ // lets the error object through, so the spawn proceeds against an unclaimed task.
+ if (!updateResult || updateResult.error) {
+ if (updateResult?.error) {
+ emitLog('warn', `⚠️ in_progress claim for task ${task.id} returned an error (taskType=${task.taskType}): ${updateResult.error}`, { taskId: task.id, error: updateResult.error });
+ }
await cleanupOnError('Failed to update task status');
return null;
}
diff --git a/server/services/agentLifecycle.test.js b/server/services/agentLifecycle.test.js
index cb7796a321..707961eb7a 100644
--- a/server/services/agentLifecycle.test.js
+++ b/server/services/agentLifecycle.test.js
@@ -31,6 +31,7 @@ import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import { spawningTasks, runnerAgents } from './agentState.js';
import { withSpawnDedupGuard, withMapEntryCleanup, SPAWN_DEDUP_SKIP } from './agentGuards.js';
+import { isInternalTaskId } from '../lib/taskParser.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
const AGENT_LIFECYCLE_SRC = readFileSync(join(__dirname, 'agentLifecycle.js'), 'utf-8');
@@ -427,3 +428,74 @@ describe('agentLifecycle — runner OpenCode Ollama env (#2243 / #2190)', () =>
.toBeLessThan(fnBody.indexOf('...provider.envVars'));
});
});
+
+// ─── taskType normalization for direct task:ready emits (issue #2633) ────────
+//
+// Direct `task:ready` emitters (Creative Director bridge, dequeueNextTask,
+// spawnPriority0OnDemand) publish task records with no `taskType`. Every
+// claim/in_progress `updateTask` in runAgentSpawn falls back to
+// `task.taskType || 'user'`, so an internal (`sys-*`) task without taskType
+// would write to TASKS.md, miss the record, and return a truthy `{ error }`
+// object the `if (!updateResult)` check silently swallowed. The fix normalizes
+// taskType at the top of runAgentSpawn via the real isInternalTaskId classifier.
+describe('taskType normalization — behavior (issue #2633)', () => {
+ // Mirrors the normalization at the top of runAgentSpawn against the REAL
+ // isInternalTaskId import, so a change to the internal-prefix list stays in
+ // sync with what the spawn path routes on (inline-pure-logic pattern).
+ const normalizeTaskType = (task) => {
+ if (task && !task.taskType) {
+ task.taskType = isInternalTaskId(task.id || '') ? 'internal' : 'user';
+ }
+ return task;
+ };
+
+ it('routes a sys-* id with no taskType to the internal file (COS-TASKS.md)', () => {
+ const task = { id: 'sys-002', description: 'internal task' };
+ normalizeTaskType(task);
+ expect(task.taskType, "sys-* must resolve to 'internal' so updateTask targets COS-TASKS.md").toBe('internal');
+ });
+
+ it('routes cd-* and app-improve-* ids (other internal prefixes) to internal', () => {
+ expect(normalizeTaskType({ id: 'cd-42' }).taskType).toBe('internal');
+ expect(normalizeTaskType({ id: 'app-improve-9' }).taskType).toBe('internal');
+ });
+
+ it('leaves a user task-* id defaulting to user (unchanged spawn behavior)', () => {
+ const task = { id: 'task-abc' };
+ normalizeTaskType(task);
+ expect(task.taskType).toBe('user');
+ });
+
+ it('preserves an already-present taskType (does not reclassify an explicit user task)', () => {
+ const task = { id: 'sys-003', taskType: 'user' };
+ normalizeTaskType(task);
+ expect(task.taskType, 'an explicit taskType must win over id-based inference').toBe('user');
+ });
+
+ it('defaults a missing id to user rather than throwing', () => {
+ expect(normalizeTaskType({}).taskType).toBe('user');
+ });
+});
+
+describe('runAgentSpawn source — taskType normalization + claim-miss guard (issue #2633)', () => {
+ it('normalizes taskType at the top, BEFORE the first claim updateTask', () => {
+ const normalizeIdx = RUN_SPAWN_BODY.indexOf('isInternalTaskId(task.id');
+ const firstUpdateIdx = RUN_SPAWN_BODY.indexOf('await updateTask(task.id');
+ expect(normalizeIdx, 'runAgentSpawn must derive taskType from the id via isInternalTaskId').toBeGreaterThan(-1);
+ expect(firstUpdateIdx, 'runAgentSpawn must call updateTask').toBeGreaterThan(-1);
+ expect(normalizeIdx, 'taskType must be normalized BEFORE any updateTask write so every claim routes to the right file')
+ .toBeLessThan(firstUpdateIdx);
+ });
+
+ it('the in_progress claim check catches a truthy { error } object, not just null', () => {
+ const guardIdx = RUN_SPAWN_BODY.indexOf('if (!updateResult || updateResult.error)');
+ expect(guardIdx, 'the claim result must be rejected when it carries an { error } (silent miss)').toBeGreaterThan(-1);
+ });
+
+ it('warn-logs when the in_progress claim returns an { error } object so silent misses are visible', () => {
+ const guardIdx = RUN_SPAWN_BODY.indexOf('if (!updateResult || updateResult.error)');
+ const body = RUN_SPAWN_BODY.slice(guardIdx, guardIdx + 400);
+ expect(body).toMatch(/emitLog\('warn'/);
+ expect(body).toContain('updateResult.error');
+ });
+});