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

refactor: extract helpers from generateManagedAppImprovementTaskForType (#2836)

[._.]/ Adam Eivyfdadcb15a11c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 2c12a49986..cbc8c495b6 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -39,3 +39,4 @@
- **[issue-2832] Split the boot-schema DDL into per-domain modules** — the ~1265-line inline `CREATE TABLE`/`CREATE INDEX`/trigger block in `ensureSchemaImpl()` (`server/lib/db.js`) is extracted into per-domain modules under `server/lib/db/schema/` (catalog, media, universes, writers-room, pipeline, privacy, tribe, audit, …), each exporting a statement array; `ensureSchemaImpl` is now a thin composer. Statement text and order are byte-identical, so the composed schema is unchanged.
- **[issue-2834] Split the ~1990-line `VideoGen.jsx` into hooks + subcomponents** — the client-side batch-queue orchestration moves into `useVideoGenQueue`, the pure model-memory / FFLF frame-budget / mode-compat helpers into `lib/videoGenParams.js`, and four presentational blocks into `components/videoGen/` (`RuntimeFingerprint`, `ModelRepairBanner`, `VideoPreviewPanel`, `VideoGenGallery`). The inline runtime-status `fetch()` now routes through a `getVideoGenRuntimeStatus` service wrapper, and the Seed input gains a proper `<label htmlFor>`/`id` pairing. Behavior and deep-link routing are unchanged.
- **[issue-2835] Split the ~2875-line `ArcCanvas.jsx` into per-component files** — each of the 32 subcomponents/helpers (ArcHeader, EditorialRoadmapPanel, SeasonRow, IssueRow, VolumeCoversPanel, …) now lives in its own file under `client/src/components/pipeline/arcCanvas/`, with the shared severity-color map in `arcCanvas/shared.js`. `ArcCanvas.jsx` (default export) is now a thin 122-line composer and still re-exports `ArcRoadmapChart` so its public import path is unchanged. Pure mechanical, behavior-preserving refactor — no rendered-output change.
+- **[issue-2836] Extract helpers from `generateManagedAppImprovementTaskForType()`** — the ~533-line function in `server/services/cosTaskGenerator.js` is decomposed into named metadata-building and gate-checking helpers (`buildImprovementTaskMetadata`, `resolveTaskInputHook`, `resolveClaimWorkRouting`, `applyPerpetualWorkGate`, `resolveBranchReconcileBlock`, `resolveIssueReconcileBlock`, `resolveReferenceWatchBlock`, `resolvePrWatcherBlock`), each returning a `{ skip }` / prompt-block result so the main function reads as a thin orchestrator. Behavior-preserving — no change to task generation, park/convergence semantics, or dispatch ordering.
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index 6b02342e00..37c831f6a8 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -1728,29 +1728,13 @@ export async function emitOnDemandEmpty({ taskScheduleMod, request, targetApp, t
});
}
-export async function generateManagedAppImprovementTaskForType(taskType, app, state, { skipPreconditions = false } = {}) {
- const { updateAppActivity } = await import('./appActivity.js');
- const taskSchedule = await import('./taskSchedule.js');
- const { getTaskPrompt, getStagePrompt } = await import('./taskPromptService.js');
-
- // 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);
-
+/**
+ * Assemble the base improvement-task metadata and layer the sanitized global
+ * (schedule interval) + per-app taskMetadata overrides on top. Per-app strips
+ * managed-agent fields first (see the sibling generateManagedAppTask path for
+ * the rationale). Pure assembly — no gating, no early return.
+ */
+async function buildImprovementTaskMetadata(taskType, app, interval, taskSchedule) {
const metadata = {
app: app.id,
appName: app.name,
@@ -1767,8 +1751,6 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, st
}
// Apply sanitized per-app taskMetadata overrides (merge on top of global).
- // Strip managed-agent fields first — see comment in the sibling
- // generateManagedAppTask path for the full rationale.
const appOverrides = await getAppTaskTypeOverrides(app.id);
const strippedAppOverride = taskSchedule.stripManagedAgentOptionsFromOverride(
taskType, appOverrides[taskType]?.taskMetadata
@@ -1777,264 +1759,372 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, st
if (sanitizedAppMeta) {
Object.assign(metadata, sanitizedAppMeta);
}
+ return metadata;
+}
- initializePipelineMetadata(metadata);
- if (!skipPreconditions && shouldSkipForPrecondition(metadata, app, taskType)) return null;
-
- // Programmatic-I/O input hook. A task type may register a buildTaskInput hook
- // (taskTypeHooks.js) that does deterministic pre-agent data collection — the
- // same shape as the inline pre-steps reference-watch/pr-watcher/branch-reconcile
- // run below (gather → maybe skip → contribute prompt), but as a reusable seam.
- // The hook OWNS its full prompt (it replaces the template) and has one `skip`
- // outcome; the inline steps that instead INJECT a token block into a template
- // they still own, or need perpetual park/convergence semantics, stay inline for
- // now (future candidates if the hook grows a block-injection return). When it
- // skips we record execution so cadence advances (mirrors pr-watcher's no-
- // dispatch recordPoll), then return null — no agent is spawned.
- let hookPrompt = null;
- // The hook may pin the app's chosen provider/model (LI option A: they live in
- // the per-app taskTypeOverrides, not the global schedule interval). Captured
- // here but APPLIED AFTER the global-interval provider/model block below, so the
- // per-app choice wins over a global schedule provider rather than being clobbered
- // by it.
- let hookOverride = {};
- {
- const { getTaskInputHook } = await import('./taskTypeHooks.js');
- const inputHook = await getTaskInputHook(taskType);
- if (inputHook) {
- const input = await inputHook({ app, taskType }).catch((err) => {
- emitLog('warn', `buildTaskInput hook failed for ${taskType}/${app.name}: ${err.message}`, { appId: app.id, analysisType: taskType });
- return { skip: { reason: 'input-hook-error' } };
- });
- if (input?.skip) {
- emitLog('info', `Skipping ${taskType} for ${app.name}: ${input.skip.reason}`, { appId: app.id, analysisType: taskType });
- await taskSchedule.recordExecution(taskType, app.id);
- return null;
- }
- hookPrompt = input?.prompt || null;
- hookOverride = { providerId: input?.providerId || null, model: input?.model || null };
- }
+/**
+ * Run a task type's registered buildTaskInput hook (taskTypeHooks.js) for
+ * deterministic pre-agent data collection. Returns `{ skip: true }` when the
+ * hook opts out (execution recorded so cadence advances), otherwise
+ * `{ skip: false, hookPrompt, hookOverride }` — the hook may fully own the
+ * rendered prompt and/or pin the app's per-app provider/model.
+ */
+async function resolveTaskInputHook(app, taskType, taskSchedule) {
+ const { getTaskInputHook } = await import('./taskTypeHooks.js');
+ const inputHook = await getTaskInputHook(taskType);
+ if (!inputHook) return { skip: false, hookPrompt: null, hookOverride: {} };
+ const input = await inputHook({ app, taskType }).catch((err) => {
+ emitLog('warn', `buildTaskInput hook failed for ${taskType}/${app.name}: ${err.message}`, { appId: app.id, analysisType: taskType });
+ return { skip: { reason: 'input-hook-error' } };
+ });
+ if (input?.skip) {
+ emitLog('info', `Skipping ${taskType} for ${app.name}: ${input.skip.reason}`, { appId: app.id, analysisType: taskType });
+ await taskSchedule.recordExecution(taskType, app.id);
+ return { skip: true };
}
+ return {
+ skip: false,
+ hookPrompt: input?.prompt || null,
+ hookOverride: { providerId: input?.providerId || null, model: input?.model || null }
+ };
+}
- // claim-work is the single-source router: one toggle that ships the next
- // work item from whatever tracker the app is configured for. Resolve
- // the app's workTracker (default 'auto' → git origin host) and delegate to the
- // concrete claim flow's prompt body. `taskType` stays 'claim-work' for
- // interval/cadence/recording; `promptTaskType` drives prompt selection, PLAN
- // gating, and the forge-specific author-filter directive below.
- let promptTaskType = taskType;
- if (taskType === 'claim-work') {
- const { resolveAppWorkTracker, trackerToClaimTaskType } = await import('../lib/workTracker.js');
- const wt = await resolveAppWorkTracker(app);
- promptTaskType = trackerToClaimTaskType(wt.resolved) || 'plan-task';
- emitLog('info', `claim-work for ${app.name}: tracker=${wt.resolved} (${wt.source}) → ${promptTaskType}`, { appId: app.id, analysisType: taskType });
- // Inherit the resolved flow's isolation posture, overriding claim-work's
- // own useWorktree/openPR=false defaults. All four concrete claim prompts
- // (plan-task / claim-issue / claim-issue-gitlab / claim-issue-jira)
- // self-manage their own worktree + MR/PR, so the self-managed false/false
- // posture is correct for every tracker. This hook stays in place so a
- // future delegated type that DOES carry a CoS-managed DEFAULT_TASK_INTERVALS
- // entry (useWorktree/openPR true) would have it applied; a prompt-only type
- // with no entry (claim-issue-gitlab, claim-issue-jira) keeps false/false.
- const delegatedMeta = taskSchedule.DEFAULT_TASK_INTERVALS[promptTaskType]?.taskMetadata;
- if (delegatedMeta) {
- if ('useWorktree' in delegatedMeta) metadata.useWorktree = delegatedMeta.useWorktree;
- if ('openPR' in delegatedMeta) metadata.openPR = delegatedMeta.openPR;
- }
- }
- // Perpetual (drain-until-done) gate. When this task type runs on the
- // 'perpetual' interval, a programmatic work-detector decides whether there's
- // anything to claim BEFORE we build the (expensive) prompt or burn an agent:
- // - actionable → clear any park so the back-to-back drain continues, and
- // stamp metadata.perpetual so the post-completion cooldown is skipped
- // (agentCompletion.js) and the next tick re-dispatches promptly.
- // - idle (definitive) → PARK on the recheck cadence and skip this dispatch.
- // - transient probe failure (gh down) → skip WITHOUT parking so the next
- // tick retries instead of waiting out a full recheck cadence.
- // The detector keys on the RESOLVED promptTaskType so a claim-work router run
- // probes the concrete tracker (claim-issue → GitHub issues, plan-task → PLAN.md).
- // branch-reconcile and issue-reconcile are PERPETUAL but are NOT gated by the
- // generic work-detector registry — for each, the "detector" and the actual
- // work are the SAME scan (the deterministic reconcile below), so splitting them
- // would double the git/gh I/O. Their dedicated blocks further down do the
- // park/clear themselves.
- if (interval.type === taskSchedule.INTERVAL_TYPES.PERPETUAL
- && taskType !== 'branch-reconcile' && taskType !== 'issue-reconcile') {
- const { detectActionableWork } = await import('./perpetualWork.js');
- const detection = await detectActionableWork(promptTaskType, app, {
- issueAuthorFilter: metadata.issueAuthorFilter || 'self'
- });
- if (detection.actionable) {
- await taskSchedule.clearPerpetualPark(taskType, app.id);
- metadata.perpetual = true;
- } else if (detection.transient) {
- emitLog('debug', `Perpetual ${taskType} skip for ${app.name} (transient: ${detection.reason})`, { appId: app.id });
- return null;
- } else {
- // Carry the detector's open/in-flight/filtered breakdown into the park so
- // an explicit "Run" can explain WHY a non-empty queue yielded no work.
- const counts = detection.total != null
- ? { open: detection.total, inFlight: detection.inFlightCount ?? 0, filtered: detection.filteredCount ?? 0 }
- : null;
- await taskSchedule.parkPerpetual(taskType, app.id, { reason: detection.reason, actionableCount: detection.count, counts });
- emitLog('info', `Perpetual ${taskType} parked for ${app.name}: ${detection.reason}`, { appId: app.id });
- return null;
- }
+/**
+ * claim-work single-source router: resolve the app's workTracker (default
+ * 'auto' → git origin host) and delegate to the concrete claim flow. Mutates
+ * `metadata` with the delegated flow's isolation posture (useWorktree/openPR)
+ * and returns the resolved promptTaskType (=== taskType for every
+ * non-claim-work type). The hook stays even though all four concrete claim
+ * prompts self-manage worktree+PR, so a future delegated type carrying a
+ * CoS-managed DEFAULT_TASK_INTERVALS entry would have its posture applied.
+ */
+async function resolveClaimWorkRouting(app, taskType, metadata, taskSchedule) {
+ if (taskType !== 'claim-work') return taskType;
+ const { resolveAppWorkTracker, trackerToClaimTaskType } = await import('../lib/workTracker.js');
+ const wt = await resolveAppWorkTracker(app);
+ const promptTaskType = trackerToClaimTaskType(wt.resolved) || 'plan-task';
+ emitLog('info', `claim-work for ${app.name}: tracker=${wt.resolved} (${wt.source}) → ${promptTaskType}`, { appId: app.id, analysisType: taskType });
+ const delegatedMeta = taskSchedule.DEFAULT_TASK_INTERVALS[promptTaskType]?.taskMetadata;
+ if (delegatedMeta) {
+ if ('useWorktree' in delegatedMeta) metadata.useWorktree = delegatedMeta.useWorktree;
+ if ('openPR' in delegatedMeta) metadata.openPR = delegatedMeta.openPR;
}
+ return promptTaskType;
+}
- // branch-reconcile: deterministic pre-step (the migrated Tier-1 core). Run the
- // peer-safe reconcile on THIS app's repo — remove fully-merged orphaned local
- // branches + their worktrees, then classify the rest. The coordinator agent is
- // dispatched only while actionable in-flight branches remain; when none do, the
- // perpetual drain PARKS on the recheck cadence. `{inFlightBranches}` carries the
- // actionable set into the prompt. Runs in the app's live checkout (no LLM here —
- // git/gh only), mirroring how pr-watcher/reference-watch do their programmatic
- // work in the generator before dispatch.
- let inFlightBranchesBlock = '';
- if (taskType === 'branch-reconcile') {
- const { reconcile, filterActionable, formatInFlightForPrompt, actionableSignature } = await import('./branchReconcile.js');
- const { getActiveAgentIds } = await import('./agentState.js');
- // Action toggles were merged (global → per-app override) + value-constrained
- // by sanitizeTaskMetadata into `metadata`; each is ON unless explicitly false.
- const actions = {
- cleanupMerged: metadata.cleanupMerged,
- openPr: metadata.openPr,
- resolveConflicts: metadata.resolveConflicts,
- autoMerge: metadata.autoMerge
- };
- const result = await reconcile(app.repoPath, {
- cleanup: actions.cleanupMerged !== false,
- activeAgentIds: new Set(getActiveAgentIds())
- }).catch((err) => {
- emitLog('warn', `branch-reconcile pre-step failed for ${app.name}: ${err.message}`, { appId: app.id });
- return null;
- });
- // A failed scan is treated as transient (git/gh blip) — skip WITHOUT parking
- // so the next tick retries instead of waiting out a full recheck cadence.
- // Trade-off: a PERSISTENT failure (bad repoPath, broken gh auth, non-git dir)
- // re-probes git every tick. That's git/gh-only cost (no LLM), and parking on
- // the first failure would delay recovery from a genuine blip by a full
- // recheck cadence — so transient-skip is the intentional choice here.
- if (!result) return null;
- if (result.cleaned.length) {
- emitLog('info', `🔀 branch-reconcile ${app.name}: cleaned ${result.cleaned.length} merged branch(es)`, { appId: app.id, analysisType: taskType });
- }
- const actionable = filterActionable(result.inFlight, actions);
- if (actionable.length === 0) {
- // Definitive idle: nothing in-flight to drive. Park on the recheck cadence
- // and clear the progress signature so a fresh set later dispatches.
- await taskSchedule.parkPerpetual(taskType, app.id, { reason: 'no-in-flight-branches', actionableCount: 0, signature: null });
- // Surface merged branches held back by a protection guard (locked / recent
- // human-claim / active-agent / dirty) so a lingering worktree isn't an
- // invisible "cleaned 0" — the exact confusion behind the stale-claim reaper.
- const heldBack = (result.skipped || []).filter((s) => s.reason?.startsWith('worktree-'));
- const heldSuffix = heldBack.length
- ? `, ${heldBack.length} merged branch(es) held back (${[...new Set(heldBack.map((s) => s.reason))].join(', ')})`
- : '';
- emitLog('info', `🔀 branch-reconcile parked for ${app.name}: nothing in-flight (cleaned ${result.cleaned.length}${heldSuffix})`, { appId: app.id });
- return null;
- }
- // Convergence guard — kills the back-to-back re-dispatch loop WITHOUT stalling
- // slow PRs. The signature (branch:state:pr#:mergeable) is stored at dispatch;
- // when the perpetual-drain refill fires right after the coordinator completes
- // (metadata.perpetual bypasses the post-completion cooldown), we compare:
- // - signature CHANGED → the run made progress (branch advanced
- // NEEDS_PR→IN_REVIEW→merged/cleaned, conflicts resolved, PR became
- // mergeable) → keep draining back-to-back.
- // - signature UNCHANGED → the run left the same branches in the same states
- // (a NEEDS_PR branch judged "not ready", an IN_REVIEW PR blocked on human
- // review / red CI). Park on the recheck cadence AND CLEAR the stored
- // signature — so the next DAILY recheck re-dispatches unconditionally
- // (re-driving the PR in case CI turned green / review cleared overnight),
- // rather than seeing the same signature and re-parking forever. The
- // signature only suppresses the immediate back-to-back refill; it never
- // suppresses a recheck.
- const signature = actionableSignature(actionable);
- const lastSignature = await taskSchedule.getPerpetualSignature(taskType, app.id);
- if (signature === lastSignature) {
- await taskSchedule.parkPerpetual(taskType, app.id, { reason: 'no-progress', actionableCount: actionable.length, signature: null });
- emitLog('info', `🔀 branch-reconcile parked for ${app.name}: ${actionable.length} branch(es) unchanged since last run (no progress — will re-drive on next recheck)`, { appId: app.id });
- return null;
- }
- // New or advanced actionable set — drive it. Resume the drain (clear any park)
- // and record the signature so an unproductive back-to-back refill parks instead
- // of looping. Skip the post-completion cooldown so productive progress drains
- // back-to-back.
- await taskSchedule.clearPerpetualPark(taskType, app.id);
- await taskSchedule.setPerpetualSignature(taskType, app.id, signature);
- metadata.perpetual = true;
- inFlightBranchesBlock = formatInFlightForPrompt(actionable, { defaultBranch: result.defaultBranch, actions });
- emitLog('info', `🔀 branch-reconcile dispatching for ${app.name}: ${actionable.length} in-flight branch(es)`, { appId: app.id, analysisType: taskType });
- }
-
- // issue-reconcile: deterministic pre-step — scan the app's forge repo (GitHub
- // via `gh` OR GitLab via `glab`, resolved from the origin host inside reconcile)
- // for ZOMBIE issues (open + `in-progress` yet with their PR/MR merged and no
- // live claim anywhere) and hand the set to the coordinator agent. Same perpetual
- // drain shape as branch-reconcile: the scan IS the work-detector (gh/glab/git
- // only, no LLM), and the coordinator dispatches only while zombies remain — else
- // it PARKS on the daily recheckCron. `{zombieIssues}` carries the set (with the
- // resolved forge) into the prompt. No worktree: the coordinator mutates issue
- // state over `gh`/`glab` only.
- let zombieIssuesBlock = '';
- if (taskType === 'issue-reconcile') {
- const { reconcile, zombieSignature, formatZombiesForPrompt } = await import('./issueReconcile.js');
- // The live-claim guard (open PR + local/remote/CoS claim branch, scanned via
- // for-each-ref inside reconcile) already covers every agent past Phase 2 of
- // the claim flow — the point at which it creates its claim/worktree branch.
- // The sub-minute pre-branch window is left to the coordinator's per-zombie
- // re-verification, so no separate active-agent set is threaded here.
- const autoClose = metadata.autoClose !== false;
- // Routing mirrors resolveAppWorkTracker: JIRA is NEVER auto-selected from the
- // git host — it needs explicit per-app config (workTracker 'jira' + enabled
- // jira.instanceId/projectKey). When resolved to JIRA, hand the gatherer the
- // JIRA coordinates so it scans status-based zombies via the PortOS JIRA API;
- // otherwise reconcile resolves GitHub/GitLab from the origin host as before.
- const { resolveAppWorkTracker } = await import('../lib/workTracker.js');
- const wt = await resolveAppWorkTracker(app).catch(() => null);
- const jira = (wt?.resolved === 'jira' && app.jira?.enabled && app.jira?.instanceId && app.jira?.projectKey)
- ? { instanceId: app.jira.instanceId, projectKey: app.jira.projectKey }
- : null;
- const result = await reconcile(app.repoPath, { jira }).catch((err) => {
- emitLog('warn', `issue-reconcile pre-step failed for ${app.name}: ${err.message}`, { appId: app.id });
- return null;
- });
- // null = unsupported remote (not GitHub/GitLab, no JIRA config) OR transient
- // gh/glab/JIRA failure → skip WITHOUT parking so the next tick retries
- // (gh/glab/git/JIRA-API-only cost), mirroring branch-reconcile.
- if (!result) return null;
- if (result.stalled.length) {
- // In-progress issues with NO merged PR and NO live claim — a different stuck
- // state (claimed, nothing shipped) that issue-reconcile deliberately does
- // NOT auto-heal. Surface them so they're not silently ignored.
- emitLog('info', `🧟 issue-reconcile ${app.name}: ${result.stalled.length} stalled in-progress issue(s) with no merged PR (left for human/branch-reconcile)`, { appId: app.id, analysisType: taskType });
- }
- if (result.zombies.length === 0) {
- await taskSchedule.parkPerpetual(taskType, app.id, { reason: 'no-zombie-issues', actionableCount: 0, signature: null });
- emitLog('info', `🧟 issue-reconcile parked for ${app.name}: no zombie issues`, { appId: app.id });
- return null;
- }
- // Convergence guard — identical to branch-reconcile's: a productive run closes
- // or releases zombies (changing the signature) → keep draining; an unchanged
- // signature (coordinator errored, or a case it punted to a human) → park on
- // the recheck cadence and CLEAR the signature so the next daily recheck
- // re-drives unconditionally rather than re-parking forever.
- const signature = zombieSignature(result.zombies);
- const lastSignature = await taskSchedule.getPerpetualSignature(taskType, app.id);
- if (signature === lastSignature) {
- await taskSchedule.parkPerpetual(taskType, app.id, { reason: 'no-progress', actionableCount: result.zombies.length, signature: null });
- emitLog('info', `🧟 issue-reconcile parked for ${app.name}: ${result.zombies.length} zombie issue(s) unchanged since last run (no progress — will re-drive on next recheck)`, { appId: app.id });
- return null;
- }
+/**
+ * Perpetual (drain-until-done) work-detector gate. For a task type running on
+ * the 'perpetual' interval — excluding branch-/issue-reconcile, whose own scan
+ * IS the detector — a programmatic detector decides whether there's anything to
+ * claim BEFORE building the (expensive) prompt or burning an agent:
+ * - actionable → clear any park, stamp metadata.perpetual (skip cooldown), proceed;
+ * - idle (definitive) → PARK on the recheck cadence, skip;
+ * - transient probe failure → skip WITHOUT parking so the next tick retries.
+ * The detector keys on the RESOLVED promptTaskType. Returns `{ skip }` and
+ * mutates `metadata.perpetual` on the actionable path.
+ */
+async function applyPerpetualWorkGate(app, taskType, promptTaskType, metadata, interval, taskSchedule) {
+ if (interval.type !== taskSchedule.INTERVAL_TYPES.PERPETUAL
+ || taskType === 'branch-reconcile' || taskType === 'issue-reconcile') {
+ return { skip: false };
+ }
+ const { detectActionableWork } = await import('./perpetualWork.js');
+ const detection = await detectActionableWork(promptTaskType, app, {
+ issueAuthorFilter: metadata.issueAuthorFilter || 'self'
+ });
+ if (detection.actionable) {
await taskSchedule.clearPerpetualPark(taskType, app.id);
- await taskSchedule.setPerpetualSignature(taskType, app.id, signature);
metadata.perpetual = true;
- zombieIssuesBlock = formatZombiesForPrompt(result.zombies, {
+ return { skip: false };
+ }
+ if (detection.transient) {
+ emitLog('debug', `Perpetual ${taskType} skip for ${app.name} (transient: ${detection.reason})`, { appId: app.id });
+ return { skip: true };
+ }
+ // Carry the detector's open/in-flight/filtered breakdown into the park so an
+ // explicit "Run" can explain WHY a non-empty queue yielded no work.
+ const counts = detection.total != null
+ ? { open: detection.total, inFlight: detection.inFlightCount ?? 0, filtered: detection.filteredCount ?? 0 }
+ : null;
+ await taskSchedule.parkPerpetual(taskType, app.id, { reason: detection.reason, actionableCount: detection.count, counts });
+ emitLog('info', `Perpetual ${taskType} parked for ${app.name}: ${detection.reason}`, { appId: app.id });
+ return { skip: true };
+}
+
+/**
+ * branch-reconcile deterministic pre-step: run the peer-safe reconcile on the
+ * app's repo (remove fully-merged orphaned local branches + worktrees, classify
+ * the rest), then perpetual-drain semantics — dispatch only while an actionable
+ * in-flight set remains and its signature advanced; else PARK on the recheck
+ * cadence. Returns `{ skip }` for every no-dispatch path (own park/log inside),
+ * or `{ skip: false, block }` with `{inFlightBranches}`. Empty block for every
+ * non-branch-reconcile type.
+ */
+async function resolveBranchReconcileBlock(app, taskType, metadata, taskSchedule) {
+ if (taskType !== 'branch-reconcile') return { skip: false, block: '' };
+ const { reconcile, filterActionable, formatInFlightForPrompt, actionableSignature } = await import('./branchReconcile.js');
+ const { getActiveAgentIds } = await import('./agentState.js');
+ // Action toggles were merged (global → per-app override) + value-constrained
+ // by sanitizeTaskMetadata into `metadata`; each is ON unless explicitly false.
+ const actions = {
+ cleanupMerged: metadata.cleanupMerged,
+ openPr: metadata.openPr,
+ resolveConflicts: metadata.resolveConflicts,
+ autoMerge: metadata.autoMerge
+ };
+ const result = await reconcile(app.repoPath, {
+ cleanup: actions.cleanupMerged !== false,
+ activeAgentIds: new Set(getActiveAgentIds())
+ }).catch((err) => {
+ emitLog('warn', `branch-reconcile pre-step failed for ${app.name}: ${err.message}`, { appId: app.id });
+ return null;
+ });
+ // A failed scan is treated as transient (git/gh blip) — skip WITHOUT parking
+ // so the next tick retries instead of waiting out a full recheck cadence.
+ if (!result) return { skip: true };
+ if (result.cleaned.length) {
+ emitLog('info', `🔀 branch-reconcile ${app.name}: cleaned ${result.cleaned.length} merged branch(es)`, { appId: app.id, analysisType: taskType });
+ }
+ const actionable = filterActionable(result.inFlight, actions);
+ if (actionable.length === 0) {
+ // Definitive idle: nothing in-flight to drive. Park on the recheck cadence
+ // and clear the progress signature so a fresh set later dispatches.
+ await taskSchedule.parkPerpetual(taskType, app.id, { reason: 'no-in-flight-branches', actionableCount: 0, signature: null });
+ // Surface merged branches held back by a protection guard so a lingering
+ // worktree isn't an invisible "cleaned 0".
+ const heldBack = (result.skipped || []).filter((s) => s.reason?.startsWith('worktree-'));
+ const heldSuffix = heldBack.length
+ ? `, ${heldBack.length} merged branch(es) held back (${[...new Set(heldBack.map((s) => s.reason))].join(', ')})`
+ : '';
+ emitLog('info', `🔀 branch-reconcile parked for ${app.name}: nothing in-flight (cleaned ${result.cleaned.length}${heldSuffix})`, { appId: app.id });
+ return { skip: true };
+ }
+ // Convergence guard — kills the back-to-back re-dispatch loop WITHOUT stalling
+ // slow PRs. Signature UNCHANGED → park + CLEAR the signature so the next
+ // recheck re-drives; CHANGED → progress, keep draining.
+ const signature = actionableSignature(actionable);
+ const lastSignature = await taskSchedule.getPerpetualSignature(taskType, app.id);
+ if (signature === lastSignature) {
+ await taskSchedule.parkPerpetual(taskType, app.id, { reason: 'no-progress', actionableCount: actionable.length, signature: null });
+ emitLog('info', `🔀 branch-reconcile parked for ${app.name}: ${actionable.length} branch(es) unchanged since last run (no progress — will re-drive on next recheck)`, { appId: app.id });
+ return { skip: true };
+ }
+ // New or advanced actionable set — drive it. Resume the drain, record the
+ // signature, skip the post-completion cooldown so progress drains back-to-back.
+ await taskSchedule.clearPerpetualPark(taskType, app.id);
+ await taskSchedule.setPerpetualSignature(taskType, app.id, signature);
+ metadata.perpetual = true;
+ emitLog('info', `🔀 branch-reconcile dispatching for ${app.name}: ${actionable.length} in-flight branch(es)`, { appId: app.id, analysisType: taskType });
+ return { skip: false, block: formatInFlightForPrompt(actionable, { defaultBranch: result.defaultBranch, actions }) };
+}
+
+/**
+ * issue-reconcile deterministic pre-step — scan the app's forge repo (GitHub via
+ * `gh`, GitLab via `glab`, or JIRA when explicitly configured) for ZOMBIE issues
+ * (open + in-progress yet PR/MR merged with no live claim) and hand the set to
+ * the coordinator. Same perpetual-drain shape as branch-reconcile. Returns
+ * `{ skip }` for every no-dispatch path, or `{ skip: false, block }` with
+ * `{zombieIssues}`. Empty block for every non-issue-reconcile type.
+ */
+async function resolveIssueReconcileBlock(app, taskType, metadata, taskSchedule) {
+ if (taskType !== 'issue-reconcile') return { skip: false, block: '' };
+ const { reconcile, zombieSignature, formatZombiesForPrompt } = await import('./issueReconcile.js');
+ const autoClose = metadata.autoClose !== false;
+ // Routing mirrors resolveAppWorkTracker: JIRA is NEVER auto-selected from the
+ // git host — it needs explicit per-app config.
+ const { resolveAppWorkTracker } = await import('../lib/workTracker.js');
+ const wt = await resolveAppWorkTracker(app).catch(() => null);
+ const jira = (wt?.resolved === 'jira' && app.jira?.enabled && app.jira?.instanceId && app.jira?.projectKey)
+ ? { instanceId: app.jira.instanceId, projectKey: app.jira.projectKey }
+ : null;
+ const result = await reconcile(app.repoPath, { jira }).catch((err) => {
+ emitLog('warn', `issue-reconcile pre-step failed for ${app.name}: ${err.message}`, { appId: app.id });
+ return null;
+ });
+ // null = unsupported remote OR transient failure → skip WITHOUT parking.
+ if (!result) return { skip: true };
+ if (result.stalled.length) {
+ // In-progress issues with NO merged PR and NO live claim — a different stuck
+ // state issue-reconcile deliberately does NOT auto-heal. Surface them.
+ emitLog('info', `🧟 issue-reconcile ${app.name}: ${result.stalled.length} stalled in-progress issue(s) with no merged PR (left for human/branch-reconcile)`, { appId: app.id, analysisType: taskType });
+ }
+ if (result.zombies.length === 0) {
+ await taskSchedule.parkPerpetual(taskType, app.id, { reason: 'no-zombie-issues', actionableCount: 0, signature: null });
+ emitLog('info', `🧟 issue-reconcile parked for ${app.name}: no zombie issues`, { appId: app.id });
+ return { skip: true };
+ }
+ // Convergence guard — identical to branch-reconcile's.
+ const signature = zombieSignature(result.zombies);
+ const lastSignature = await taskSchedule.getPerpetualSignature(taskType, app.id);
+ if (signature === lastSignature) {
+ await taskSchedule.parkPerpetual(taskType, app.id, { reason: 'no-progress', actionableCount: result.zombies.length, signature: null });
+ emitLog('info', `🧟 issue-reconcile parked for ${app.name}: ${result.zombies.length} zombie issue(s) unchanged since last run (no progress — will re-drive on next recheck)`, { appId: app.id });
+ return { skip: true };
+ }
+ await taskSchedule.clearPerpetualPark(taskType, app.id);
+ await taskSchedule.setPerpetualSignature(taskType, app.id, signature);
+ metadata.perpetual = true;
+ emitLog('info', `🧟 issue-reconcile dispatching for ${app.name}: ${result.zombies.length} zombie issue(s) on ${result.forge}`, { appId: app.id, analysisType: taskType });
+ return {
+ skip: false,
+ block: formatZombiesForPrompt(result.zombies, {
fullName: result.fullName, forge: result.forge, autoClose,
projectKey: jira?.projectKey, instanceId: jira?.instanceId,
- });
- emitLog('info', `🧟 issue-reconcile dispatching for ${app.name}: ${result.zombies.length} zombie issue(s) on ${result.forge}`, { appId: app.id, analysisType: taskType });
+ })
+ };
+}
+
+/**
+ * reference-watch: dynamically build {referenceData} — a Markdown chunk per ref
+ * configured on the app + commits since lastReviewedSha. The check persists
+ * status/lastError so a bad URL surfaces in the UI even when dispatch is skipped.
+ * Returns `{ skip }` when no ref produced reviewable commits, else
+ * `{ skip: false, block }`. Empty block for every non-reference-watch type.
+ */
+async function resolveReferenceWatchBlock(app, taskType) {
+ if (taskType !== 'reference-watch') return { skip: false, block: '' };
+ const refs = Array.isArray(app.referenceRepos) ? app.referenceRepos : [];
+ if (refs.length === 0) {
+ emitLog('info', `Skipping reference-watch for ${app.name}: no reference repos configured`, { appId: app.id });
+ return { skip: true };
}
+ const referenceRepos = await import('./referenceRepos.js');
+ const blocks = [];
+ let anySuccessWithCommits = false;
+ for (const ref of refs) {
+ try {
+ // eslint-disable-next-line no-await-in-loop
+ const snapshot = await referenceRepos.checkReferenceRepo(app.id, ref.id);
+ if (snapshot.commitCount > 0) {
+ blocks.push(referenceRepos.formatReferenceForPrompt(ref, snapshot));
+ anySuccessWithCommits = true;
+ }
+ } catch (err) {
+ emitLog('warn', `Reference check failed for ${ref.name}: ${err.message}`, { appId: app.id, refId: ref.id });
+ blocks.push(`## Reference: ${ref.name}\n\n_Check failed: ${err.message}_`);
+ }
+ }
+ // Don't burn an agent dispatch when there's nothing actionable — either every
+ // ref is up-to-date OR every ref errored (its lastError already surfaced).
+ if (!anySuccessWithCommits) {
+ emitLog('info', `Skipping reference-watch for ${app.name}: no refs produced reviewable commits`, { appId: app.id });
+ return { skip: true };
+ }
+ return { skip: false, block: blocks.join('\n\n---\n\n') };
+}
+
+/**
+ * pr-watcher: poll the app's GitHub repo for PRs newly opened against the
+ * default branch, gated on authorship. The gh poll IS the cadence-bearing work,
+ * so every no-dispatch path records execution before returning `{ skip }`.
+ * Returns `{ skip: false, block, repoFullName, defaultBranch }` on dispatch
+ * (injects {prData}/{repoFullName}/{defaultBranch}). Empty for other types.
+ */
+async function resolvePrWatcherBlock(app, taskType, metadata, taskSchedule) {
+ if (taskType !== 'pr-watcher') return { skip: false, block: '', repoFullName: '', defaultBranch: '' };
+ const prWatcher = await import('./prWatcher.js');
+ // prAuthorFilter was already merged + value-constrained into `metadata`.
+ const authorFilter = metadata.prAuthorFilter || 'any';
+ const check = await prWatcher.checkPullRequests(app, { authorFilter });
+ const checkedAt = new Date().toISOString();
+ // The gh poll IS the cadence-bearing work — a poll that dispatches nothing
+ // still has to advance the interval, else a CUSTOM task re-polls every tick.
+ const recordPoll = () => taskSchedule.recordExecution(taskType, app.id);
+
+ if (!check.ok) {
+ await prWatcher.persistPrWatcherState(app.id, { lastCheckedAt: checkedAt, lastError: check.reason });
+ await recordPoll();
+ emitLog('info', `Skipping pr-watcher for ${app.name}: ${check.reason}`, { appId: app.id });
+ return { skip: true };
+ }
+
+ // Always advance the high-water mark + clear any prior error.
+ await prWatcher.persistPrWatcherState(app.id, {
+ lastSeenPrNumber: check.newLastSeen,
+ lastCheckedAt: checkedAt,
+ lastError: null
+ });
+
+ if (check.firstRun) {
+ await recordPoll();
+ emitLog('info', `pr-watcher baselined ${app.name} at PR #${check.newLastSeen} — no dispatch on first run`, { appId: app.id });
+ return { skip: true };
+ }
+ if (check.newPrs.length === 0) {
+ await recordPoll();
+ emitLog('info', `Skipping pr-watcher for ${app.name}: no new PRs (author filter: ${authorFilter})`, { appId: app.id });
+ return { skip: true };
+ }
+
+ emitLog('info', `pr-watcher dispatching for ${app.name}: ${check.newPrs.length} new PR(s)`, { appId: app.id, analysisType: taskType });
+ return {
+ skip: false,
+ block: prWatcher.formatPullRequestsForPrompt(check.newPrs, {
+ repoFullName: check.repoFullName, defaultBranch: check.defaultBranch
+ }),
+ repoFullName: check.repoFullName,
+ defaultBranch: check.defaultBranch
+ };
+}
+
+export async function generateManagedAppImprovementTaskForType(taskType, app, state, { skipPreconditions = false } = {}) {
+ const { updateAppActivity } = await import('./appActivity.js');
+ const taskSchedule = await import('./taskSchedule.js');
+ const { getTaskPrompt, getStagePrompt } = await import('./taskPromptService.js');
+
+ // 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);
+ const metadata = await buildImprovementTaskMetadata(taskType, app, interval, taskSchedule);
+
+ initializePipelineMetadata(metadata);
+ if (!skipPreconditions && shouldSkipForPrecondition(metadata, app, taskType)) return null;
+
+ // Programmatic-I/O input hook. A task type may register a buildTaskInput hook
+ // (taskTypeHooks.js) that does deterministic pre-agent data collection and
+ // fully OWNS its prompt. `hookOverride` may pin the app's per-app
+ // provider/model — captured here but APPLIED AFTER the global-interval
+ // provider/model block below, so the per-app choice wins.
+ const inputHook = await resolveTaskInputHook(app, taskType, taskSchedule);
+ if (inputHook.skip) return null;
+ const { hookPrompt, hookOverride } = inputHook;
+
+ // claim-work single-source router: `taskType` stays 'claim-work' for
+ // interval/cadence/recording; `promptTaskType` drives prompt selection, PLAN
+ // gating, and the forge-specific author-filter directive below.
+ const promptTaskType = await resolveClaimWorkRouting(app, taskType, metadata, taskSchedule);
+
+ // Perpetual (drain-until-done) gate — probes for actionable work before
+ // building the prompt or burning an agent (branch-/issue-reconcile self-gate
+ // in their own blocks, so this excludes them).
+ const perpetualGate = await applyPerpetualWorkGate(app, taskType, promptTaskType, metadata, interval, taskSchedule);
+ if (perpetualGate.skip) return null;
+
+ // branch-reconcile: deterministic git/gh pre-step that carries the actionable
+ // in-flight set into the prompt via {inFlightBranches}.
+ const branchReconcile = await resolveBranchReconcileBlock(app, taskType, metadata, taskSchedule);
+ if (branchReconcile.skip) return null;
+ const inFlightBranchesBlock = branchReconcile.block;
+
+ // issue-reconcile: deterministic forge pre-step that carries the zombie-issue
+ // set into the prompt via {zombieIssues}.
+ const issueReconcile = await resolveIssueReconcileBlock(app, taskType, metadata, taskSchedule);
+ if (issueReconcile.skip) return null;
+ const zombieIssuesBlock = issueReconcile.block;
// Honor a direct claim-work prompt customization if the user set one;
// otherwise delegate to the resolved tracker's prompt body via
@@ -2056,103 +2146,17 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, st
// reference-watch: dynamically inject {referenceData} — a Markdown chunk
// describing each ref configured on the app + commits since lastReviewedSha.
- // The check itself fetches each upstream and persists status/lastError, so
- // a bad URL surfaces in the UI even if the agent dispatch is skipped below.
- let referenceDataBlock = '';
- if (taskType === 'reference-watch') {
- const refs = Array.isArray(app.referenceRepos) ? app.referenceRepos : [];
- if (refs.length === 0) {
- emitLog('info', `Skipping reference-watch for ${app.name}: no reference repos configured`, { appId: app.id });
- return null;
- }
- const referenceRepos = await import('./referenceRepos.js');
- const blocks = [];
- let anySuccessWithCommits = false;
- for (const ref of refs) {
- try {
- // eslint-disable-next-line no-await-in-loop
- const snapshot = await referenceRepos.checkReferenceRepo(app.id, ref.id);
- if (snapshot.commitCount > 0) {
- blocks.push(referenceRepos.formatReferenceForPrompt(ref, snapshot));
- anySuccessWithCommits = true;
- }
- } catch (err) {
- emitLog('warn', `Reference check failed for ${ref.name}: ${err.message}`, { appId: app.id, refId: ref.id });
- blocks.push(`## Reference: ${ref.name}\n\n_Check failed: ${err.message}_`);
- }
- }
- // Don't burn an agent dispatch when there's nothing actionable —
- // either every ref is up-to-date OR every ref errored. Errored refs
- // already surfaced their lastError in the UI via checkReferenceRepo,
- // so the user can fix configs without an agent involved.
- if (!anySuccessWithCommits) {
- emitLog('info', `Skipping reference-watch for ${app.name}: no refs produced reviewable commits`, { appId: app.id });
- return null;
- }
- referenceDataBlock = blocks.join('\n\n---\n\n');
- }
+ const referenceWatch = await resolveReferenceWatchBlock(app, taskType);
+ if (referenceWatch.skip) return null;
+ const referenceDataBlock = referenceWatch.block;
// pr-watcher: poll the app's GitHub repo for PRs newly opened against the
- // default branch, gated on authorship (self / others / any). Dispatches one
- // agent run covering all new PRs; injects {prData}/{repoFullName}/
- // {defaultBranch}. State (the lastSeenPrNumber high-water mark) is persisted
- // inline on the app, mirroring reference-watch's lastReviewedSha.
- let prDataBlock = '';
- let prRepoFullName = '';
- let prDefaultBranch = '';
- if (taskType === 'pr-watcher') {
- const prWatcher = await import('./prWatcher.js');
- // prAuthorFilter was already merged (global → per-app override) and
- // value-constrained into `metadata` by sanitizeTaskMetadata above, so read
- // it from there rather than re-merging the raw configs.
- const authorFilter = metadata.prAuthorFilter || 'any';
-
- const check = await prWatcher.checkPullRequests(app, { authorFilter });
- const checkedAt = new Date().toISOString();
-
- // The gh poll IS the cadence-bearing work for pr-watcher, so a poll that
- // dispatches nothing still has to advance the interval. The queue path
- // (queueEligibleImprovementTasks) only records execution AFTER a task is
- // queued, so a bare `return null` would leave lastRun unset — and a CUSTOM
- // task with no lastRun reads as perpetually "due", re-polling GitHub every
- // scheduler tick and (being CUSTOM-priority) starving the app's other task
- // types until a PR appears. Record the poll here on every no-dispatch path.
- const recordPoll = () => taskSchedule.recordExecution(taskType, app.id);
-
- if (!check.ok) {
- await prWatcher.persistPrWatcherState(app.id, { lastCheckedAt: checkedAt, lastError: check.reason });
- await recordPoll();
- emitLog('info', `Skipping pr-watcher for ${app.name}: ${check.reason}`, { appId: app.id });
- return null;
- }
-
- // Always advance the high-water mark + clear any prior error. First run
- // baselines silently; later runs mark every evaluated PR (dispatched AND
- // gated-out) as seen so a fixed author filter doesn't re-fire them.
- await prWatcher.persistPrWatcherState(app.id, {
- lastSeenPrNumber: check.newLastSeen,
- lastCheckedAt: checkedAt,
- lastError: null
- });
-
- if (check.firstRun) {
- await recordPoll();
- emitLog('info', `pr-watcher baselined ${app.name} at PR #${check.newLastSeen} — no dispatch on first run`, { appId: app.id });
- return null;
- }
- if (check.newPrs.length === 0) {
- await recordPoll();
- emitLog('info', `Skipping pr-watcher for ${app.name}: no new PRs (author filter: ${authorFilter})`, { appId: app.id });
- return null;
- }
-
- prDataBlock = prWatcher.formatPullRequestsForPrompt(check.newPrs, {
- repoFullName: check.repoFullName, defaultBranch: check.defaultBranch
- });
- prRepoFullName = check.repoFullName;
- prDefaultBranch = check.defaultBranch;
- emitLog('info', `pr-watcher dispatching for ${app.name}: ${check.newPrs.length} new PR(s)`, { appId: app.id, analysisType: taskType });
- }
+ // default branch; injects {prData}/{repoFullName}/{defaultBranch}.
+ const prWatch = await resolvePrWatcherBlock(app, taskType, metadata, taskSchedule);
+ if (prWatch.skip) return null;
+ const prDataBlock = prWatch.block;
+ const prRepoFullName = prWatch.repoFullName;
+ const prDefaultBranch = prWatch.defaultBranch;
// Gate on PLAN.md using the RESOLVED type so a claim-work run routed to the
// PLAN.md flow still skips cleanly on an empty/all-in-flight queue. For