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

route auto-queued plan-task through rich generator so in-flight scan runs (#428)

[._.]/ Adam Eivy921e407e15bd
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 4cc43f03d3..b5a33e546f 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -35,5 +35,6 @@
- **[ansistrip-osc-alternative-unreachable] TUI output no longer leaks window-title and hyperlink escape bodies** — terminal OSC sequences (the ones CLIs use to set window titles or emit clickable links) are now stripped in full instead of leaving fragments like `0;title␇` visible in agent/TUI transcripts, prompt-runner logs, and arc-planner output.
- **Migration 003 no longer crashes `update.sh` when a stage prompt was renamed upstream.** `pipeline-tv-script.md` was renamed to `pipeline-teleplay.md` in a later commit, leaving older installs unable to run migration 003 (ENOENT on the missing sample file). The migration now treats a sample-side rename/retirement as a soft delete: unmodified copies of the old file are removed cleanly, customized copies emit a warning so edits can be merged into the replacement manually.
- **[agent-spawn-widen-try-finally-guard] A failed agent spawn no longer permanently blocks the task that triggered it.** Previously, when an agent failed to start due to a transient I/O or disk error mid-setup, the autonomous task scheduler could enter a state where that specific task was treated as "already spawning" forever and was silently skipped until the server restarted. Now any such failure releases the in-flight guard immediately so the next scheduler tick can retry the task.
+- **[queueEligibleImprovementTasks-route-through-rich-generator] Auto-queued `plan-task` and `feature-ideas` agents pick distinct PLAN.md slugs again — no more duplicate PRs against the same item.** The scheduler's queue path (`sys-*` task ids) was writing a one-line stub description and skipping the rich generator entirely, so the agent it dispatched had no `analysisType`/`planId` metadata and no Phase 1-7 instructions — the in-flight scan (`git branch -a` + `gh pr list` matching documented `claim/<slug>` / `cos/<task>/<slug>/<agent>` refs) never ran. Two `plan-task` agents 2h apart could both pick the same slug; the second branched as `worktree-<slug>` and opened an overlapping PR for already-claimed work. The queue path now routes through `generateManagedAppImprovementTaskForType` so `applyPlanIdMetadata` pre-picks the planId (and silently skips when every slug is blocked or already in flight) and the agent receives the full prompt template with `{planConstraint}` substituted. Regression-pinned in `services/cos.test.js`.
## Removed
diff --git a/PLAN.md b/PLAN.md
index a961ba4568..b58fead172 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -18,7 +18,6 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [.changel
- [ ] [voice-cos-tool-expansion-calendar-today-calendar] **Voice CoS tool expansion** — `calendar_today` / `calendar_next` (existing Google Calendar MCP), `meatspace_log_workout` (wraps `meatspaceHealth.js`), `weather_now` (pick API: OpenWeather / WeatherKit / NWS), `timer_set` (reuses `agentActionExecutor.js`).
- [ ] [voice-agent-vision-fallback-ui-describe-visually] **Voice agent vision fallback** — `ui_describe_visually`: screenshot tab and send to a vision-capable model so "what's on this chart?" works on CyberCity / graph views.
- [ ] [apple-health-integration-live-sync] **Apple Health integration for MeatSpace.** iOS live sync (HealthKit Shortcut → `POST /api/meatspace/apple-health` endpoint) plus a bulk historical import path for an exported `export.xml`. Wire into existing MeatSpace tabs so steps / sleep / heart rate / VO2 max / resting HR show alongside the alcohol / blood / body / epigenetic tracks already shipped. GOALS.md flags this as a documented Secondary Goal ("Apple Health integration planned") but no implementation tracking existed until this entry.
-
## Deferred Architecture (human-led planning)
God-file decomposition candidates — none are bugs; pick up when touching the file for unrelated reasons.
diff --git a/server/services/appActivity.js b/server/services/appActivity.js
index c641165421..2c07586a1e 100644
--- a/server/services/appActivity.js
+++ b/server/services/appActivity.js
@@ -152,12 +152,17 @@ export async function clearStaleActiveAgents(liveAgentIds) {
}
/**
- * Check if an app is on cooldown
+ * Pure cooldown predicate — takes a per-app activity record (already
+ * extracted from an `apps` map) plus the cooldown window and returns
+ * true/false without any disk I/O. The async `isAppOnCooldown` below is
+ * a thin wrapper that loads the activity snapshot from disk and delegates
+ * here. Loops that iterate over many apps in one tick (e.g.
+ * `queueEligibleImprovementTasks` in cos.js) should load
+ * `loadAppActivity()` *once* before the loop and call this predicate per
+ * app, instead of calling `isAppOnCooldown` per app (which re-reads
+ * the same JSON file N times). See cos.js for the canonical usage.
*/
-export async function isAppOnCooldown(appId, cooldownMs) {
- const activity = await loadAppActivity();
- const appActivity = activity.apps[appId];
-
+export function isAppActivityOnCooldown(appActivity, cooldownMs) {
if (!appActivity) return false;
const now = Date.now();
@@ -188,6 +193,20 @@ export async function isAppOnCooldown(appId, cooldownMs) {
return false;
}
+/**
+ * Check if an app is on cooldown by `appId`. Loads the activity snapshot
+ * from disk and delegates to the pure predicate. For loops over many
+ * apps, prefer hoisting `loadAppActivity()` once and calling
+ * `isAppActivityOnCooldown(activity.apps?.[appId], cooldownMs)` directly.
+ */
+export async function isAppOnCooldown(appId, cooldownMs) {
+ const activity = await loadAppActivity();
+ // Optional chain — a hand-edited / corrupted activity.json could lose
+ // the `apps` field, and `null.appId` would throw before the predicate's
+ // own falsy guard ran.
+ return isAppActivityOnCooldown(activity.apps?.[appId], cooldownMs);
+}
+
/**
* Get the next app eligible for review (not on cooldown, oldest review first)
*/
diff --git a/server/services/cos.js b/server/services/cos.js
index 53346d84f0..e9e00a47d4 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -20,7 +20,16 @@ import { promisify } from 'util';
import { v4 as uuidv4 } from '../lib/uuid.js';
import { getActiveProvider } from './providers.js';
import { parseTasksMarkdown, groupTasksByStatus, getNextTask, getAutoApprovedTasks, getAwaitingApprovalTasks, updateTaskStatus, generateTasksMarkdown, hasKnownPrefix, isInternalTaskId } from '../lib/taskParser.js';
-import { isAppOnCooldown, getNextAppForReview, markAppReviewStarted, markIdleReviewStarted, clearStaleActiveAgents } from './appActivity.js';
+// NOTE: `getAppActivityById` + `updateAppActivity` are deliberately NOT
+// listed here even though they're used elsewhere in this file. The two
+// other call sites (in `generateManagedAppImprovementTask` and
+// `generateManagedAppImprovementTaskForType`) load them via a sibling
+// dynamic `import('./appActivity.js')` for unrelated reasons. Hoisting
+// them to the static import would leave them unreferenced at the
+// top-level scope of the queue path (which now reads the snapshot via
+// `loadAppActivity` + the pure predicate) and trip "unused import"
+// warnings. The dynamic-import sites stay self-contained.
+import { isAppOnCooldown, getNextAppForReview, markAppReviewStarted, markIdleReviewStarted, clearStaleActiveAgents, loadAppActivity, isAppActivityOnCooldown } from './appActivity.js';
import { getActiveApps, getAppTaskTypeOverrides } from './apps.js';
import { getAdaptiveCooldownMultiplier, getSkippedTaskTypes, getPerformanceSummary, checkAndRehabilitateSkippedTasks, getLearningInsights, getTaskTypeConfidence } from './taskLearning.js';
import { schedule as scheduleEvent, cancel as cancelEvent, getStats as getSchedulerStats, parseCronToNextRun } from './eventScheduler.js';
@@ -1070,7 +1079,7 @@ async function generateIdleReviewTask(state) {
* Tasks are queued to COS-TASKS.md and will be picked up in Priority 2
*/
async function queueEligibleImprovementTasks(state, cosTaskData) {
- const { getDueTasks, shouldRunTask, getNextTaskType, recordExecution } = await import('./taskSchedule.js');
+ const { getNextTaskType, recordExecution } = await import('./taskSchedule.js');
if (!isImprovementEnabled(state)) return;
@@ -1102,6 +1111,18 @@ async function queueEligibleImprovementTasks(state, cosTaskData) {
let queued = 0;
+ // Load the activity snapshot ONCE before the per-app loop. Both the
+ // cooldown gate and the rotation `lastType` lookup are derived from
+ // `data/app-activity.json`; before this hoist, each app paid two
+ // separate disk reads (one via `isAppOnCooldown` + one via
+ // `getAppActivityById`), so a 10-app deployment did 20 reads of the
+ // same file per scheduler tick. With the snapshot pinned, the cost
+ // is O(1) read per `queueEligibleImprovementTasks` invocation. Falls
+ // back to an empty `apps` map on disk error so the loop's per-app
+ // lookups uniformly return `undefined` (both gates treat that as
+ // "no activity yet — not on cooldown, no last type").
+ const activitySnapshot = await loadAppActivity().catch(() => ({ apps: {} }));
+
// Queue eligible improvement tasks for all managed apps (including PortOS)
const apps = await getActiveApps().catch(() => []);
for (const app of apps) {
@@ -1113,12 +1134,26 @@ async function queueEligibleImprovementTasks(state, cosTaskData) {
continue;
}
- // Check if app is on cooldown
- const onCooldown = await isAppOnCooldown(app.id, state.config.appReviewCooldownMs);
- if (onCooldown) continue;
-
- // Get next eligible improvement type for this app
- const nextTypeResult = await getNextTaskType(app.id).catch(() => null);
+ // Derive both gates from the single shared snapshot. The async
+ // `isAppOnCooldown` would also work, but it loads the activity file
+ // again per app — see comment on `activitySnapshot` above.
+ // Optional chain on `.apps` — `loadAppActivity()` spreads
+ // `DEFAULT_ACTIVITY` over the file contents, but a hand-edited
+ // activity.json that explicitly sets `apps: null` (or any non-object)
+ // would still surface here; both gates treat `undefined` as
+ // "no activity yet."
+ const appActivity = activitySnapshot.apps?.[app.id];
+ if (isAppActivityOnCooldown(appActivity, state.config.appReviewCooldownMs)) continue;
+
+ // Get next eligible improvement type for this app. `getNextTaskType`
+ // falls back to ROTATION when nothing is time-due, and the rotation
+ // pointer is derived from the `lastType` argument — without it, the
+ // rotation always restarts from index 0 and starves every other
+ // rotation type for the app. Mirror `generateManagedAppTask` (the
+ // legacy direct-spawn caller above) which threads the per-app
+ // `lastImprovementType` in.
+ const lastType = appActivity?.lastImprovementType || '';
+ const nextTypeResult = await getNextTaskType(app.id, lastType).catch(() => null);
if (!nextTypeResult) continue;
const nextType = nextTypeResult.taskType;
@@ -1128,19 +1163,46 @@ async function queueEligibleImprovementTasks(state, cosTaskData) {
continue;
}
- // Generate task description
- const taskDesc = getTaskDescription(nextType, app.name);
- if (!taskDesc) continue;
+ // Route through the rich generator so `applyPlanIdMetadata` runs — it
+ // scans open `claim/<slug>` branches + PRs and excludes in-flight slugs
+ // from the pick. The old stub path skipped this and let two plan-task
+ // agents claim the same slug (2026-05-21 incident). The generator
+ // returns null on plan-gate / precondition skip; we silently continue.
+ // Regression-pinned in cos.test.js.
+ const task = await generateManagedAppImprovementTaskForType(nextType, app, state);
+ if (!task) continue;
+
+ // Queue-path invariants override the generator's direct-spawn defaults
+ // (which use MEDIUM priority + `app-improve-*` id).
+ task.priority = 'LOW';
+ task.priorityValue = PRIORITY_VALUES.LOW;
+ task.id = `sys-${app.id.slice(0, 8)}-${nextType}-${Date.now().toString(36)}`;
+
+ // Move the generator's multi-line prompt into `metadata.context` so it
+ // survives the COS-TASKS.md round-trip. The on-demand path dispatches the
+ // in-memory task immediately (cosEvents.emit('task:ready', task) with the
+ // unparsed object), so it never round-trips through the markdown — but
+ // the queue path persists first and re-reads from disk on the next
+ // `dequeueNextTask` tick. `generateTasksMarkdown` interpolates the full
+ // `task.description` onto a single line (taskParser.js:268) and
+ // `parseTasksMarkdown` only matches the first line of a `- [ ]` block —
+ // so any newline in `description` corrupts the file (stray `## Phase`
+ // lines become section headers, `- ` lines become new tasks) AND silently
+ // strips the Phase 1–7 instructions on the re-read. `metadata.context` is
+ // newline-escaped via `escapeNewlines`/`unescapeNewlines` (JSON-sentinel
+ // encoding) so it round-trips losslessly. The agent prompt builder
+ // (`cos-agent-briefing.md` + the built-in fallback in
+ // `agentPromptBuilder.js`) renders both `task.description` AND
+ // `task.metadata.context` into the agent's prompt, so the agent still
+ // sees the full Phase 1–7 body.
+ if (typeof task.description === 'string' && task.description.includes('\n')) {
+ task.metadata = task.metadata || {};
+ task.metadata.context = task.description;
+ task.description = firstLine(task.description);
+ }
- // Add to COS-TASKS.md
- const newTask = await addTask({
- id: `sys-${app.id.slice(0, 8)}-${nextType}-${Date.now().toString(36)}`,
- description: taskDesc,
- priority: 'LOW',
- app: app.id,
- context: `Auto-generated improvement task for ${app.name}. Type: ${nextType}`,
- approvalRequired: false
- }, 'internal');
+ const newTask = await addTask(task, 'internal', { raw: true });
+ if (newTask?.duplicate) continue;
await recordExecution(`task:${nextType}`, app.id);
@@ -1157,57 +1219,6 @@ async function queueEligibleImprovementTasks(state, cosTaskData) {
}
}
-/**
- * Get task description for a self-improvement or app improvement type.
- * When appName is provided, returns app-scoped descriptions; otherwise returns PortOS self-improvement descriptions.
- */
-function getTaskDescription(taskType, appName) {
- if (appName) {
- const descriptions = {
- 'security': `Security audit for ${appName}: check for vulnerabilities`,
- 'code-quality': `Code quality review for ${appName}: DRY violations, dead code`,
- 'test-coverage': `Add missing tests for ${appName}`,
- 'performance': `Performance optimization for ${appName}`,
- 'accessibility': `Accessibility audit for ${appName}`,
- 'console-errors': `Fix console errors in ${appName}`,
- 'dependency-updates': `Update dependencies for ${appName}`,
- 'documentation': `Update documentation for ${appName}`,
- 'error-handling': `Improve error handling in ${appName}`,
- 'typing': `Add/fix TypeScript types in ${appName}`,
- 'ui-bugs': `Review UI for visual bugs in ${appName}`,
- 'mobile-responsive': `Check mobile responsiveness of ${appName}`,
- 'feature-ideas': `Implement a feature idea for ${appName} aligned with GOALS.md and PLAN.md (worktree+PR)`,
- 'plan-task': `Execute next PLAN.md item for ${appName}, remove it from PLAN.md, log to changelog (worktree+PR)`,
- 'release-check': `Verify release readiness for ${appName}`,
- 'jira-sprint-manager': `Triage and implement JIRA sprint tickets for ${appName} (worktree+PR)`,
- 'jira-status-report': `Generate JIRA weekly status report for ${appName}`,
- 'do-replan': `Replan: audit PLAN.md for ${appName}, prune completed and stale work (worktree+PR)`
- };
- return descriptions[taskType] ?? null;
- }
- const descriptions = {
- 'ui-bugs': 'Review UI for visual bugs, layout issues, and UX improvements',
- 'mobile-responsive': 'Check mobile responsiveness and fix layout issues on smaller screens',
- 'security': 'Audit codebase for security vulnerabilities (XSS, injection, auth issues)',
- 'code-quality': 'Review code for DRY violations, dead code, and refactoring opportunities',
- 'console-errors': 'Check browser console and fix JavaScript errors and warnings',
- 'performance': 'Profile and optimize slow components, queries, and renders',
- 'test-coverage': 'Add missing tests for uncovered code paths',
- 'documentation': 'Update documentation, comments, and README files',
- 'feature-ideas': 'Implement a feature idea aligned with GOALS.md and PLAN.md (worktree+PR)',
- 'plan-task': 'Execute next PLAN.md item, remove it from PLAN.md, log to changelog (worktree+PR)',
- 'accessibility': 'Audit and fix accessibility issues (ARIA, keyboard nav, contrast)',
- 'dependency-updates': 'Check for and safely update outdated dependencies',
- 'error-handling': 'Improve error handling patterns and recovery logic',
- 'typing': 'Add or fix TypeScript/JSDoc type annotations',
- 'release-check': 'Verify release readiness (changelog, version, tests)',
- 'jira-sprint-manager': 'Triage and implement JIRA sprint tickets (worktree+PR)',
- 'jira-status-report': 'Generate JIRA weekly status report',
- 'do-replan': 'Replan: audit PLAN.md, prune completed and stale work (worktree+PR)'
- };
- return descriptions[taskType] ?? null;
-}
-
// Unified improvement task types (rotates through these)
// Organized by goal priority from GOALS.md
const IMPROVEMENT_TYPES = [
@@ -1991,12 +2002,20 @@ async function generateManagedAppImprovementTaskForType(taskType, app, state, {
const { updateAppActivity } = await import('./appActivity.js');
const taskSchedule = await import('./taskSchedule.js');
- // Update app activity with new type
- await updateAppActivity(app.id, {
- lastImprovementType: taskType
- });
-
- emitLog('info', `Generating improvement task for ${app.name}: ${taskType} (on-demand)`, { appId: app.id, analysisType: taskType });
+ // NOTE: `updateAppActivity` + the "Generating improvement task" log are
+ // intentionally deferred until AFTER every gate returns non-null (see end
+ // of function). The original code stamped both eagerly, which was tolerable
+ // when only the on-demand path called this — the user explicitly asked for
+ // a task, so logging + rotation-pointer advance was correct even when the
+ // generator decided not to produce one. Now `queueEligibleImprovementTasks`
+ // routes through this every scheduler tick, so an eager update would (a)
+ // advance the per-app rotation pointer on every skip (biasing
+ // `getNextTaskType` away from a type with nothing actionable to do, but
+ // also away from types that *could* run on a future tick) and (b) emit a
+ // misleading "Generating improvement task" line for skipped types. The
+ // single-call ordering at the bottom keeps both paths in sync — a returned
+ // task means rotation advanced; a `return null` short-circuit means it
+ // didn't.
// Get interval settings to determine provider/model and pipeline config
const interval = await taskSchedule.getTaskInterval(taskType);
@@ -2109,6 +2128,12 @@ async function generateManagedAppImprovementTaskForType(taskType, app, state, {
const approval = await resolveConfidenceApproval(state, `app-improve:${taskType}`, `Task app-improve:${taskType} for ${app.name}`);
+ // All gates passed — record the rotation-pointer advance + emit the
+ // generation log. Deferred from the top of the function (see note there);
+ // every `return null` above this point intentionally leaves both untouched.
+ await updateAppActivity(app.id, { lastImprovementType: taskType });
+ emitLog('info', `Generating improvement task for ${app.name}: ${taskType}`, { appId: app.id, analysisType: taskType });
+
const task = {
id: `app-improve-${app.id}-${taskType}-${Date.now().toString(36)}`,
status: 'pending',
diff --git a/server/services/cos.test.js b/server/services/cos.test.js
index adbab013ed..2fb2fb3e44 100644
--- a/server/services/cos.test.js
+++ b/server/services/cos.test.js
@@ -648,6 +648,142 @@ describe('cos.js source — priority + capacity invariants', () => {
expect(dequeueFn).toMatch(/spawned\s*===\s*0\s*&&\s*state\.config\.idleReviewEnabled/);
expect(evalFn).toMatch(/tasksToSpawn\.length\s*===\s*0\s*&&\s*state\.config\.idleReviewEnabled/);
});
+
+ it('queueEligibleImprovementTasks routes through generateManagedAppImprovementTaskForType', () => {
+ // Regression guard: a 2026-05-21 incident saw two `plan-task` agents both
+ // open PRs for the same PLAN.md slug because the queue path was writing
+ // a one-line stub description with no `analysisType` / `planId`. The
+ // agent it dispatched got the Phase 1-7 prompt (with in-flight scan)
+ // stripped, picked the same slug as a sibling that already had an open
+ // `claim/<slug>` PR, and produced a duplicate. The fix routes the queue
+ // path through the shared generator so `applyPlanIdMetadata` runs and
+ // the full prompt + planId metadata land on the queued task.
+ const fnStart = COS_SRC.indexOf('async function queueEligibleImprovementTasks');
+ expect(fnStart, 'queueEligibleImprovementTasks must exist').toBeGreaterThan(-1);
+ const fnBody = extractFnBody(COS_SRC, fnStart);
+
+ expect(
+ fnBody,
+ 'queue path must call generateManagedAppImprovementTaskForType so applyPlanIdMetadata runs + the full prompt is used'
+ ).toMatch(/generateManagedAppImprovementTaskForType\s*\(/);
+
+ // Match the call shape, not the specific variable name — `task` could
+ // legitimately be renamed (e.g. `queuedTask`) in a behavior-preserving
+ // refactor. The contract being pinned is "raw:true addTask call to the
+ // internal lane," not the identifier.
+ expect(
+ fnBody,
+ 'queue path must persist via addTask with raw:true so the enriched task object survives serialization'
+ ).toMatch(/addTask\s*\(\s*\w+\s*,\s*['"]internal['"]\s*,\s*\{\s*raw:\s*true\s*\}/);
+
+ // The old buggy path called `getTaskDescription` to build a one-line
+ // description and then passed app/context/approvalRequired fields to
+ // addTask's non-raw constructor. Pin both as absent so we can't regress.
+ expect(
+ fnBody,
+ 'queue path must NOT use getTaskDescription (one-line stub bypasses prompt enrichment)'
+ ).not.toMatch(/getTaskDescription\s*\(/);
+
+ // The generator returns a multi-line `description` (the full Phase 1–7
+ // prompt template). COS-TASKS.md serialization interpolates the whole
+ // description onto a single `- [ ]` line and the parser only matches the
+ // first line, so persisting a multi-line description corrupts the file
+ // AND truncates the prompt on the next `dequeueNextTask` re-read. The
+ // queue path must move the body to `metadata.context` (which IS
+ // newline-escaped) so the agent prompt builder reconstitutes it on
+ // dispatch. Pin both halves of the split.
+ expect(
+ fnBody,
+ 'queue path must move multi-line description body to metadata.context (survives markdown round-trip)'
+ ).toMatch(/metadata\.context\s*=\s*\w+\.description/);
+ expect(
+ fnBody,
+ 'queue path must collapse description to a single line via firstLine()'
+ ).toMatch(/\.description\s*=\s*firstLine\(/);
+
+ // `getNextTaskType` falls back to ROTATION when nothing is time-due, and
+ // the rotation pointer is derived from the `lastType` argument. The queue
+ // path MUST thread the per-app `lastImprovementType` through, otherwise
+ // every tick restarts the rotation at index 0 and starves every other
+ // rotation type for the app. Mirrors the legacy direct-spawn caller.
+ expect(
+ fnBody,
+ 'queue path must pass the loaded lastType through to getNextTaskType so rotation advances'
+ ).toMatch(/getNextTaskType\(app\.id,\s*\w+\s*\)/);
+
+ // appActivity helpers must come from the file-level static import (line ~23),
+ // NOT a dynamic `await import('./appActivity.js')` *inside* the per-app
+ // loop. Dynamic imports are cached but still add an extra microtask + a
+ // promise allocation per iteration, and they hide the real dependency
+ // graph at file scope.
+ expect(
+ fnBody,
+ 'queue path must not dynamically import ./appActivity.js inside the per-app loop'
+ ).not.toMatch(/await\s+import\(['"]\.\/appActivity\.js['"]\)/);
+
+ // The cooldown check + lastImprovementType lookup both come from the
+ // same `data/app-activity.json` file. Before snapshotting, each app
+ // paid two separate disk reads per tick (one via `isAppOnCooldown`, one
+ // via `getAppActivityById`), so a 10-app install did 20 reads per
+ // scheduler tick. The queue path must (a) call `loadAppActivity()`
+ // exactly ONCE before the per-app loop and (b) drive the per-app
+ // cooldown gate via the pure `isAppActivityOnCooldown` predicate
+ // (which takes the per-app activity record from the snapshot), NOT
+ // the async `isAppOnCooldown` (which re-reads the file).
+ expect(
+ fnBody,
+ 'queue path must hoist loadAppActivity() before the per-app loop'
+ ).toMatch(/loadAppActivity\(\)/);
+ expect(
+ fnBody,
+ 'queue path must gate cooldown via the pure isAppActivityOnCooldown predicate, not the disk-reading isAppOnCooldown'
+ ).toMatch(/isAppActivityOnCooldown\(/);
+ expect(
+ fnBody,
+ 'queue path must not call the disk-reading isAppOnCooldown per app'
+ ).not.toMatch(/await\s+isAppOnCooldown\(/);
+ });
+
+ it('generateManagedAppImprovementTaskForType defers updateAppActivity until after gates', () => {
+ // Regression guard: the rotation pointer + "Generating improvement task"
+ // log must only advance when a real task is queued. The eager call at
+ // the top of the function was tolerable when only the on-demand path
+ // hit it (user explicitly picked the type), but now the per-tick queue
+ // path routes through it too — so every plan-task skip (no available
+ // slug), every precondition fail, and every reference-watch "no refs"
+ // exit would silently rotate the pick + emit a misleading log. Pin
+ // both the absence of the early call AND the presence of the gated
+ // late call so a future refactor can't accidentally restore the
+ // pre-gate ordering.
+ //
+ // Use sliceFn instead of extractFnBody because the function body
+ // contains a `for (...) { try { ... } catch }` block and the
+ // brace-balanced scanner doesn't always match the right closer when
+ // there are template-literal braces nested inside.
+ const fnStart = COS_SRC.indexOf('async function generateManagedAppImprovementTaskForType');
+ expect(fnStart, 'generateManagedAppImprovementTaskForType must exist').toBeGreaterThan(-1);
+ const fnEnd = COS_SRC.indexOf('\nasync function ', fnStart + 1);
+ const fnBody = COS_SRC.slice(fnStart, fnEnd === -1 ? undefined : fnEnd);
+
+ // The updateAppActivity call must appear AFTER applyPlanIdMetadata —
+ // otherwise a `planMeta.skipReason` early-return still rotates the pointer.
+ const planMetaIdx = fnBody.indexOf('applyPlanIdMetadata(');
+ const updateActivityIdx = fnBody.indexOf('updateAppActivity(app.id,');
+ expect(planMetaIdx, 'applyPlanIdMetadata must appear in the function').toBeGreaterThan(-1);
+ expect(updateActivityIdx, 'updateAppActivity must appear in the function').toBeGreaterThan(-1);
+ expect(
+ updateActivityIdx,
+ 'updateAppActivity must run after applyPlanIdMetadata so rotation only advances on a real queue'
+ ).toBeGreaterThan(planMetaIdx);
+
+ // The "(on-demand)" suffix on the generation log was misleading once
+ // the queue path started routing through this function. Pin the suffix
+ // as absent.
+ expect(
+ fnBody,
+ 'Generation log must not claim "(on-demand)" — function is shared by queue + on-demand callers'
+ ).not.toMatch(/Generating improvement task[^`'"\n]*\(on-demand\)/);
+ });
});
describe('addTask — first-line dedup', () => {