Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
Run Layered Intelligence as a visible, TUI-attachable agent instead of an invisible handler
[._.]/ Adam Eivy747e58a7ddee
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 0e151bb617..f9c0bceea7 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -6,6 +6,8 @@## Layered Intelligence+- **Layered Intelligence now runs as a visible agent you can watch — and talk to in a TUI — instead of an invisible in-process handler.** It used to be a "handler-backed" task: on each fire it made one inline reasoning call and filed a tracker issue with no agent record, so it never appeared in the CoS queue or the Active Agents page and couldn't be interacted with mid-run. It's now a normal agent-backed scheduled task with two programmatic slots around the agent — a pre-agent step that gathers the app's goals/telemetry/open issues and builds the reasoning prompt, and a post-agent step that validates the agent's structured output and files exactly one deduplicated tracker issue. The reasoning run shows up as an agent like any other automation, and when you select a TUI provider/model you can attach to its terminal and message it while it thinks (`btw`). The "reasoner never writes code" guarantee is preserved by isolation: the agent runs in a throwaway git worktree that is discarded without a commit, push, or merge, so its only durable output is the structured result the filing step consumes. This generalizes into a reusable "programmatic-I/O task" mechanism (pre-agent input hook + post-agent output hook) for future task types that need deterministic data collection or output processing around an agent. Existing installs inherit the throwaway-worktree posture automatically on upgrade (schedule defaults are backfilled) — no migration needed. Per-app enable/interval/provider/model and behavior config (sources, scopes, rules, hand-off) are unchanged, and the Edit App → Intelligence "Last run" status still reflects filed/parked/skipped/no-op outcomes.+- **[issue-2322] Layered Intelligence is now a per-app scheduled task, not a global sweep.** The self-improvement loop used to run as a single global "Layered Intelligence Loop" job that swept every enabled app on one daily fire, with a confusing split between a global on/off (CoS → System Tasks) and per-app config (Edit App → Intelligence) — a per-app card could read "Enabled · Due now" while nothing ran. It now runs like every other self-improvement automation: a per-app, deterministic, handler-backed task in CoS → Schedule with its own per-app enable, interval, provider/model, and "Run now". Enabling the `layered-intelligence` task in the Schedule (plus per app on the Intelligence tab) drives it; the reasoning model still only returns JSON and files one deduplicated tracker issue — no code, no agent. Per-app behavior (telemetry sources, allowed scopes, guidance rules, hand-off) still lives on the app's Intelligence tab. An install upgrade migrates each app's scheduling into its per-app task override and tombstones the old global job, preserving effective on/off state. Note: because it's now a self-improvement task, the loop runs only while CoS improvement is enabled.- The standalone `/layered-intelligence` page has been removed — with the loop now a per-app scheduled task, its status is seen and managed in CoS → Schedule like every other task, and per-app behavior stays on Edit App → Intelligence. (The dedicated cross-app overview/proposals page and its endpoints are gone; nothing else surfaced there.)- **[issue-2326] The app Automation page now edits per-task provider/model overrides inline.** Each task row on Edit App → Automation gained a "⚙ Configure" disclosure that expands a per-app provider + model override (with "Use default provider" to inherit the global/task default) — previously reachable only from CoS → Schedule → Configure. The `layered-intelligence` row additionally links straight to its behavior config (telemetry sources, allowed scopes, guidance rules) on the Edit App → Intelligence tab, so an app's full self-improvement setup is configurable without leaving the app.diff --git a/client/src/utils/layeredIntelligenceReasons.js b/client/src/utils/layeredIntelligenceReasons.jsindex c1c985f568..f0f3481e0d 100644--- a/client/src/utils/layeredIntelligenceReasons.js+++ b/client/src/utils/layeredIntelligenceReasons.js@@ -1,7 +1,7 @@// Canonical gloss for the Layered Intelligence loop's run-outcome reason tokens.//// The reason vocabulary is authored server-side (server/services/autonomousJobs/-// layeredIntelligenceHandler.js — `no-provider`, `unparseable-response`,+// layeredIntelligenceHooks.js — `no-provider`, `unparseable-response`,// `no-proposal`, `scope-suppressed`, `file-failed`, `duplicate`,// `semantic-duplicate`, `tracker-read-failed`, `blocking-read-failed`,// `jira-not-configured`, `blocking-open`, plus the synthesized `llm-error:<msg>`diff --git a/server/lib/README.md b/server/lib/README.mdindex cd99faf8a4..458cca56ae 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -24,6 +24,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| Module | Purpose ||---|---|| `validation.js` | Catch-all Zod schemas (app/process/provider, social accounts, GitHub, backup/sharing, document/legacy-export) + the `validateRequest` middleware + shared helpers (`optionalBooleanMap`, `isSafeRecordId`, `parsePagination`). Re-exports the per-domain validation files below so existing deep imports keep working. |+| `agentSentinel.js` | The `.agent-done` completion sentinel: `DONE_SENTINEL_NAME` + pure `parseSentinelPayload(contents)` → `{ summary, payload }`. Back-compat — a plain-markdown sentinel yields `payload: null`; a JSON object yields its structured `payload` for a programmatic-I/O task type's `processTaskOutput` hook. || `agentValidation.js` | Social-bot agent schemas (personality, Moltbook/Moltworld accounts, automation schedules, agent tools + Moltworld payloads) and CoS Feature Agent definitions. || `appleHealthValidation.js` | Apple Health import payloads. || `brainValidation.js` | Brain/memory route schemas (search, ingest, edit). |diff --git a/server/lib/agentSentinel.js b/server/lib/agentSentinel.jsnew file mode 100644index 0000000000..cd605c93e8--- /dev/null+++ b/server/lib/agentSentinel.js@@ -0,0 +1,47 @@+/**+ * The `.agent-done` completion sentinel — shared name + parser.+ *+ * A finishing agent writes this file into its workspace to signal completion+ * (see agentTuiSpawning's sentinel poll). Historically it held a plain-markdown+ * task summary that gets appended to the agent's output. Programmatic-I/O task+ * types (see docs/plans/2026-07-09-programmatic-io-scheduled-tasks.md) also need+ * a STRUCTURED result back — e.g. Layered Intelligence's reasoner JSON — so the+ * sentinel may instead be a JSON object `{ summary, payload }` where `payload`+ * is the machine-readable result a `processTaskOutput` hook consumes.+ *+ * `parseSentinelPayload` is pure and back-compat: a plain-text sentinel yields+ * `{ summary: <text>, payload: null }`; a JSON object yields its `summary`+ * (string, if present) plus its `payload`. Anything that fails to shape up+ * (empty, non-object JSON like a bare array/number) degrades to text so an+ * existing markdown sentinel is never misread as structured.+ */++import { safeJSONParse } from './fileUtils.js';++export const DONE_SENTINEL_NAME = '.agent-done';++/**+ * Parse `.agent-done` contents into `{ summary, payload }`.+ * - `summary`: human-readable text for the agent output/card (never null;+ * falls back to the raw trimmed contents).+ * - `payload`: the structured result for a task-type output hook, or null+ * when the sentinel carried no JSON object (the common legacy case).+ * Pure — no I/O. `contents` may be null/undefined (missing file).+ */+export function parseSentinelPayload(contents) {+ const trimmed = typeof contents === 'string' ? contents.trim() : '';+ if (!trimmed) return { summary: '', payload: null };++ // Only a JSON OBJECT counts as structured. `safeJSONParse` with allowArray:false+ // returns the object, or null for a plain markdown summary / bare JSON+ // scalar/array / malformed content — so a legacy sentinel round-trips as text+ // (repo convention: reuse safeJSONParse, no bare try/catch).+ const parsed = safeJSONParse(trimmed, null, { allowArray: false });+ if (parsed) {+ const summary = typeof parsed.summary === 'string' ? parsed.summary : '';+ const payload = 'payload' in parsed ? parsed.payload : null;+ return { summary, payload };+ }++ return { summary: trimmed, payload: null };+}diff --git a/server/lib/agentSentinel.test.js b/server/lib/agentSentinel.test.jsnew file mode 100644index 0000000000..bd17806377--- /dev/null+++ b/server/lib/agentSentinel.test.js@@ -0,0 +1,52 @@+import { describe, it, expect } from 'vitest';+import { DONE_SENTINEL_NAME, parseSentinelPayload } from './agentSentinel.js';++describe('agentSentinel', () => {+ it('exposes the sentinel filename', () => {+ expect(DONE_SENTINEL_NAME).toBe('.agent-done');+ });++ describe('parseSentinelPayload', () => {+ it('returns empty summary + null payload for missing/blank contents', () => {+ expect(parseSentinelPayload(null)).toEqual({ summary: '', payload: null });+ expect(parseSentinelPayload(undefined)).toEqual({ summary: '', payload: null });+ expect(parseSentinelPayload(' \n ')).toEqual({ summary: '', payload: null });+ });++ it('treats a plain-markdown sentinel as text (legacy back-compat)', () => {+ const md = '## Done\n\n- Fixed the bug\n- Opened PR #42';+ expect(parseSentinelPayload(md)).toEqual({ summary: md, payload: null });+ });++ it('does NOT misread a bare JSON array or scalar as structured', () => {+ expect(parseSentinelPayload('[1, 2, 3]')).toEqual({ summary: '[1, 2, 3]', payload: null });+ expect(parseSentinelPayload('42')).toEqual({ summary: '42', payload: null });+ });++ it('extracts summary + payload from a JSON object sentinel', () => {+ const contents = JSON.stringify({+ summary: 'Proposed one improvement',+ payload: { proposal: { slug: 'add-telemetry', title: 'Add telemetry' } }+ });+ expect(parseSentinelPayload(contents)).toEqual({+ summary: 'Proposed one improvement',+ payload: { proposal: { slug: 'add-telemetry', title: 'Add telemetry' } }+ });+ });++ it('tolerates a JSON object missing summary (payload still surfaces)', () => {+ const contents = JSON.stringify({ payload: { proposal: null } });+ expect(parseSentinelPayload(contents)).toEqual({ summary: '', payload: { proposal: null } });+ });++ it('surfaces an explicit null payload as null (not absent)', () => {+ const contents = JSON.stringify({ summary: 'nothing to file', payload: null });+ expect(parseSentinelPayload(contents)).toEqual({ summary: 'nothing to file', payload: null });+ });++ it('degrades malformed JSON that opens with { to text', () => {+ const broken = '{ not valid json';+ expect(parseSentinelPayload(broken)).toEqual({ summary: broken, payload: null });+ });+ });+});diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.jsindex 3de4c11a3e..e2cb656b4c 100644--- a/server/lib/cosValidation.js+++ b/server/lib/cosValidation.js@@ -291,7 +291,11 @@ export const MAX_TOTAL_SPAWNS = 5;// sanitizeTaskMetadata.const ALLOWED_TASK_METADATA_KEYS = [...PIPELINE_BEHAVIOR_FLAGS, 'readOnly',- 'cleanupMerged', 'openPr', 'resolveConflicts', 'autoMerge', 'autoClose'+ 'cleanupMerged', 'openPr', 'resolveConflicts', 'autoMerge', 'autoClose',+ // Throwaway-worktree posture for programmatic-I/O reasoning tasks (layered-+ // intelligence): the worktree is discarded without a merge or PR so a reasoning+ // agent can't land code. See agentWorktreeCleanup.js.+ 'discardWorktree'];// pr-watcher author-gate values. 'self' = PRs opened by the gh-authenticateddiff --git a/server/lib/index.js b/server/lib/index.jsindex e4d8304c4c..07f88aea7a 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -128,6 +128,7 @@ export * from './zipWriter.js';// === Process execution ===export * from './agentGuard/index.js';+export * from './agentSentinel.js';export * from './bashResolver.js';export * from './bufferedSpawn.js';export * from './commandSecurity.js';diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex 5ee13fb30d..d4d573fbd3 100644--- a/server/services/agentCliSpawning.js+++ b/server/services/agentCliSpawning.js@@ -744,6 +744,7 @@ export async function spawnDirectly({isTruthyMetaFn,error: finalError || undefined,completionReason: terminatedByUser ? 'user-terminated' : undefined,+ workspacePath,});} finally {// Clean up worktree if agent was using one. Claude Code CLI agents rundiff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex 86d0aa947a..8356798baa 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -759,6 +759,7 @@ export async function finalizeAgent({isTruthyMetaFn,error,completionReason,+ workspacePath = null,}) {if (success && isTruthyMetaFn) {await persistSimplifySummaries(agentId, task, outputBuffer, isTruthyMetaFn);@@ -824,9 +825,57 @@ export async function finalizeAgent({}}+ // Programmatic-I/O task types (e.g. layered-intelligence) run a deterministic+ // post-agent step on the agent's STRUCTURED output — the parsed `.agent-done`+ // payload — rather than only handling the completion sentinel. Read + dispatch+ // it mode-agnostically here (the single finalize chokepoint for TUI/CLI/runner+ // agents), gated on the task type actually registering an output hook so a+ // normal agent pays no extra I/O. Its side effects (filing an issue, etc.) are+ // isolated from the agent's discarded worktree — the payload is the only+ // durable channel out. Errors are caught: a hook failure must not strand the+ // rest of finalize. See taskTypeHooks.js + the design plan.+ await dispatchTaskOutputHook({ agentId, task, success, workspacePath }).catch(err => {+ emitLog('error', `processTaskOutput hook threw for ${agentId} (${task?.taskType}): ${err.message}`, { agentId, error: err.message });+ });+await processAgentCompletion(agentId, task, success, outputBuffer);}+/**+ * Read the finished agent's `.agent-done` payload and run the task type's+ * `processTaskOutput` hook, if it registers one. No-op for the vast majority of+ * task types (no hook). The hook receives `{ appId, success, payload, ... }` and+ * loads its own app/config — finalizeAgent stays domain-agnostic.+ */+async function dispatchTaskOutputHook({ agentId, task, success, workspacePath }) {+ // The scheduled task type lives in metadata.analysisType (the top-level+ // task.taskType is the CoS queue category, e.g. 'internal'). A programmatic-I/O+ // hook is keyed on the scheduled type.+ const taskType = task?.metadata?.analysisType || task?.taskType;+ if (!taskType) return;+ const { getTaskOutputHook } = await import('./taskTypeHooks.js');+ const hook = await getTaskOutputHook(taskType);+ if (!hook) return;++ const cwd = workspacePath || task?.metadata?.repoPath || null;+ let payload = null;+ if (cwd) {+ const { DONE_SENTINEL_NAME, parseSentinelPayload } = await import('../lib/agentSentinel.js');+ const { tryReadFile } = await import('../lib/fileUtils.js');+ const contents = await tryReadFile(join(cwd, DONE_SENTINEL_NAME));+ payload = parseSentinelPayload(contents).payload;+ }++ await hook({+ appId: task?.metadata?.app || null,+ success,+ payload,+ workspacePath: cwd,+ agentId,+ task,+ });+}+/*** Persist task/simplify summaries for agents that ran with /simplify.* Shared by handleAgentCompletion (runner mode) and spawnDirectly (direct mode).@@ -1019,6 +1068,7 @@ export async function handleAgentCompletion(agentId, exitCode, success, durationoutputBuffer,errorAnalysis,isTruthyMetaFn: isTruthyMeta,+ workspacePath: agent.workspacePath || null,});} catch (err) {finalizeError = err;diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex 9c3478f359..d34d761299 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -17,6 +17,7 @@ import { analyzeAgentFailure } from './agentErrorAnalysis.js';import { finalizeAgent, releaseAgentLane } from './agentLifecycle.js';import { activeAgents, userTerminatedAgents, pausedAgents } from './agentState.js';import { PATHS } from '../lib/fileUtils.js';+import { DONE_SENTINEL_NAME, parseSentinelPayload } from '../lib/agentSentinel.js';import * as git from './git.js';import { shellQuote } from '../lib/shellQuote.js';import { resolveCliModel, resolveBedrockCliModel, prefixOpencodeModel, hasModelFlag, isOpencodeCommand, isClaudeCommand, applyLeanClaudeArgs } from '../lib/providerModels.js';@@ -166,7 +167,7 @@ const OUTPUT_FLUSH_INTERVAL_MS = 250;// when they've finished /simplify + /do:pr (or /do:push) — we poll for it// here so the agent gets cleanly finalized as soon as the work is done,// without waiting on the much longer idle timeout fallback.-const DONE_SENTINEL_NAME = '.agent-done';+// DONE_SENTINEL_NAME is shared from ../lib/agentSentinel.js.const DONE_POLL_INTERVAL_MS = 2000;/**@@ -539,10 +540,15 @@ export async function spawnTuiAgent({console.error(`❌ ingestDoneSentinel readFile failed: ${err.message}`);return '';});- const trimmed = contents.trim();- if (!trimmed) return;+ // A programmatic-I/O task type writes a JSON `{ summary, payload }` sentinel;+ // append only the human `summary` to the agent output (the structured+ // `payload` is consumed separately by the task type's processTaskOutput hook,+ // read mode-agnostically in finalizeAgent). A legacy plain-markdown sentinel+ // parses back as its own text, so this is a no-op change for existing types.+ const { summary } = parseSentinelPayload(contents);+ if (!summary) return;appendLine(`✅ Agent signaled completion`);- const truncated = trimmed.length > 4096 ? `${trimmed.slice(0, 4096)}\n…[truncated]` : trimmed;+ const truncated = summary.length > 4096 ? `${summary.slice(0, 4096)}\n…[truncated]` : summary;for (const line of truncated.split('\n')) appendLine(line);};@@ -652,6 +658,7 @@ export async function spawnTuiAgent({isTruthyMetaFn,error: finalError || undefined,completionReason: reason,+ workspacePath,});} finally {if (workspacePath) await rm(join(workspacePath, DONE_SENTINEL_NAME)).catch(() => {});diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex e102328ea0..0334b2c79b 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -100,8 +100,11 @@ vi.mock('fs/promises', () => ({}),}));-vi.mock('../lib/fileUtils.js', () => ({-tryReadFile: vi.fn().mockResolvedValue(null),+vi.mock('../lib/fileUtils.js', async (importOriginal) => ({+ // Keep the real pure helpers (safeJSONParse — used transitively by+ // agentSentinel.parseSentinelPayload, etc.); only stub the I/O + PATHS.+ ...(await importOriginal()),+ tryReadFile: vi.fn().mockResolvedValue(null),PATHS: { root: '/tmp/portos-root' }}));diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.jsindex 875524e349..3243de1175 100644--- a/server/services/agentWorktreeCleanup.js+++ b/server/services/agentWorktreeCleanup.js@@ -19,6 +19,7 @@ import { emitLog } from './cosEvents.js';import { addTask } from './cos.js';import * as git from './git.js';import { removeWorktree } from './worktreeManager.js';+import { isTruthyMeta } from './agentState.js';import { PATHS } from '../lib/fileUtils.js';import { RECOVERY_TASK_PREFIX } from './recoveryTasks.js';import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, normalizeReviewers } from '../lib/validation.js';@@ -51,6 +52,25 @@ export async function cleanupAgentWorktree(agentId, success, { openPR = false, rconst warnings = [];+ // Throwaway-worktree posture (programmatic-I/O reasoning agents, e.g. layered-+ // intelligence): the agent's edits are NEVER wanted — its only sanctioned output+ // is its structured `.agent-done` payload, consumed by a processTaskOutput hook.+ // Remove the worktree WITHOUT merging or opening a PR (delete the branch too), so+ // a reasoning agent that touched code can't land it. This is the "reasoner never+ // writes code" guarantee, enforced by isolation rather than by not spawning an+ // agent. Overrides openPR/skipMerge — discard always wins. Derived once here from+ // the task metadata (a pure read with no caller-specific logic, unlike openPR/+ // skipMerge) so every spawn-completion path gets it without threading a flag.+ const discardWorktree = isTruthyMeta(originalTask?.metadata?.discardWorktree);+ if (discardWorktree) {+ emitLog('info', `🌳 Discarding worktree for reasoning agent ${agentId} (no merge, no PR)`, { agentId, branchName: worktreeBranch });+ const result = await removeWorktree(agentId, sourceWorkspace, worktreeBranch, { merge: false }).catch(err => {+ emitLog('warn', `🌳 Worktree discard failed for ${agentId}: ${err.message}`, { agentId });+ return { warnings: [`Worktree discard failed: ${err.message}`] };+ });+ return result?.warnings || [];+ }+// When openPR is set and task succeeded, push branch and create PR instead of auto-mergingif (openPR && success) {emitLog('info', `🌳 Opening PR for worktree agent ${agentId} branch ${worktreeBranch}`, { agentId, branchName: worktreeBranch });diff --git a/server/services/autonomousJobs/layeredIntelligenceHandler.js b/server/services/autonomousJobs/layeredIntelligenceHandler.jsdeleted file mode 100644index f5d450b212..0000000000--- a/server/services/autonomousJobs/layeredIntelligenceHandler.js+++ /dev/null@@ -1,402 +0,0 @@-/**- * Layered Intelligence Loop — the per-app deterministic handler.- *- * Driven by the `layered-intelligence` HANDLER-BACKED scheduled task (issue- * #2322): the CoS scheduler tick + on-demand drain call- * `runLayeredIntelligenceForApp(app)` for ONE app whose per-app override is due,- * instead of spawning a coding agent. For that app it runs the four layers:- * GATHER → REASON → DECIDE → ACT. The reasoning model only returns structured- * JSON; all side effects (dedup, scope-gate, pause, filing) are the deterministic- * helpers in ../layeredIntelligence.js.- *- * The scheduler now owns gating (per-app enabled) and cadence (interval / due-ness- * via the task schedule), so this handler does NOT re-check enabled/due — it just- * runs the layers and records `lastRunAt` bookkeeping. Scheduling provider/model- * come from the per-app `taskTypeOverrides['layered-intelligence']` (option A);- * behavior (sources/scopes/rules/handoff) stays in `app.layeredIntelligence`.- *- * Runs OUTSIDE the request lifecycle, so — per the CLAUDE.md no-try/catch rule —- * the scheduler's fire-and-forget wrapper is the async boundary; this stays- * defensive so a partial failure degrades to a no-op outcome. Off by default.- */--import { PORTOS_APP_ID, updateAppLayeredIntelligence } from '../apps.js'-import {- getEffectiveConfig,- buildPrompt,- gatherSources,- listForgeIssues,- listBlockingIssues,- isAppParked,- validateReasonerResponse,- isScopeAllowed,- isProposalDuplicate,- checkSemanticDuplicate,- isHandoffEligible,- buildHandoffTask,- filerForTracker,- trackerSupportsPause,- resolveBlockOnIssue,- fileProposalToForge,- applyBlockingLabel,- appendProposalToPlan,- extractPlanSlugs,- listJiraIssues,- listJiraBlockingIssues,- fileProposalToJira,- resolveJiraBlockKey,- applyJiraBlockingLabel-} from '../layeredIntelligence.js'-import { resolveAppWorkTracker } from '../../lib/workTracker.js'-import { tryReadFile, safeJSONParse } from '../../lib/fileUtils.js'-import { stripCodeFences } from '../../lib/aiProvider.js'-import { join } from 'path'--/**- * Whether an app is DUE this run — its per-app interval has elapsed since the- * last recorded run. A never-run app (no lastRunAt) is always due.- */-export function isAppDue(config, lastRunAt, now = Date.now()) {- if (!lastRunAt) return true- const last = Date.parse(lastRunAt)- if (!Number.isFinite(last)) return true- return now - last >= (config.intervalMs || 0)-}--/**- * Run the Layered Intelligence loop for ONE app end-to-end (the four layers).- * Returns a structured outcome for logging/telemetry: { app, action, ... }.- * Never throws — the scheduler's fire-and-forget wrapper is the async boundary,- * but this stays defensive so a partial failure of one layer degrades to a no-op- * outcome rather than aborting.- *- * Does NOT gate on enabled/due — the scheduler owns per-app enablement + cadence- * now (this only runs when the schedule says the app's task is due). It still- * records `lastRunAt` bookkeeping via updateAppLayeredIntelligence.- *- * Behavior (sources/scopes/rules/handoff) reads from `app.layeredIntelligence`;- * the scheduling provider/model come from the per-app task override- * (taskTypeOverrides['layered-intelligence'], option A) and are overlaid onto the- * effective config here so the LLM step resolves the app-chosen provider.- *- * `deps` is injectable for tests (callLLM, forge listers/filers, plan append).- */-export async function runLayeredIntelligenceForApp(app, deps = {}) {- const {- callLLM,- enqueueHandoff = defaultEnqueueHandoff,- now = Date.now()- } = deps-- const isPortos = app.id === PORTOS_APP_ID- const config = getEffectiveConfig({ ...app, isPortos })-- // Option A: provider/model live in the per-app scheduled-task override, not in- // app.layeredIntelligence. Overlay them so resolveLLM picks the app's choice.- const override = (app.taskTypeOverrides && typeof app.taskTypeOverrides === 'object')- ? (app.taskTypeOverrides['layered-intelligence'] || {})- : {}- if (override.providerId != null) config.providerId = override.providerId- if (override.model != null) config.model = override.model-- // Every terminal path records the run's OUTCOME (not just lastRunAt) and returns- // the same object, so the durable last-run status the UI reads always matches- // what was returned to the on-demand feedback layer. One seam ⇒ no drift.- const settle = async (outcome) => {- await recordRun(app, config, now, outcome)- return { app: app.id, ...outcome }- }-- // Resolve where this app files work — branch up front so a `plan` app never- // hits the forge-only label/issue paths.- const tracker = await resolveAppWorkTracker(app).catch(() => ({ resolved: 'plan', forge: null }))- const filer = filerForTracker(tracker.resolved)- const forgeCli = tracker.forge // 'gh' | 'glab' | null- const cwd = app.repoPath-- // Jira coordinates come from the app's explicit per-app config (never- // auto-detected). A jira-tracked app with no usable instance/project can't file,- // so skip it BEFORE reasoning rather than burn an LLM call on a result we can't- // land. `projectKey` is also needed to resolve integer pause targets to keys.- const jira = (filer === 'jira' && app.jira?.enabled && app.jira?.instanceId && app.jira?.projectKey)- ? { instanceId: app.jira.instanceId, projectKey: app.jira.projectKey, issueType: app.jira.issueType || 'Task' }- : null- if (filer === 'jira' && !jira) {- return settle({ action: 'skipped', reason: 'jira-not-configured' })- }-- // ---- Park check (forge + jira; plan has no issue to block on) ----- if (trackerSupportsPause(tracker.resolved)) {- const blocking = filer === 'jira'- ? await listJiraBlockingIssues({ instanceId: jira.instanceId, projectKey: jira.projectKey })- : (forgeCli ? await listBlockingIssues({ cli: forgeCli, cwd }) : null)- // A FAILED read (ok:false) is not "no blocking issues" — skip this app rather- // than risk resuming work the user parked, and try again next run.- if (blocking && !blocking.ok) {- console.warn(`⚠️ Layered Intelligence: ${app.name} blocking-issue read failed — skipping this run`)- return settle({ action: 'skipped', reason: 'blocking-read-failed' })- }- if (blocking && isAppParked(blocking.issues)) {- console.log(`⏸️ Layered Intelligence: ${app.name} parked on ${blocking.issues.length} blocking issue(s) — skipping`)- return settle({ action: 'parked', reason: 'blocking-open', blocking: blocking.issues.length })- }- }-- // ---- Layer 1: GATHER ----- const sources = await gatherSources(app, config)- let openIssues = []- let existingIssues = []- let trackerReadFailed = false- if (filer === 'forge' && forgeCli) {- const listed = await listForgeIssues({ cli: forgeCli, cwd })- trackerReadFailed = !listed.ok- existingIssues = listed.issues- // Only surface open issues to the reasoner when the openIssues source is on;- // dedup still runs against ALL existing issues regardless of the toggle.- if (config.sources?.openIssues !== false) {- openIssues = existingIssues.filter(i => i.state === 'open')- }- } else if (filer === 'jira') {- const listed = await listJiraIssues({ instanceId: jira.instanceId, projectKey: jira.projectKey })- trackerReadFailed = !listed.ok- existingIssues = listed.issues- if (config.sources?.openIssues !== false) {- openIssues = existingIssues.filter(i => i.state === 'open')- }- } else if (filer === 'plan' && cwd) {- const planContent = await tryReadFile(join(cwd, 'PLAN.md'))- const planSlugs = extractPlanSlugs(planContent || '')- existingIssues = planSlugs.map(slug => ({ slug, state: 'open' }))- }-- // ---- Layer 2: REASON ----- const prompt = buildPrompt({ app, config, sources, openIssues, isPortos })- const llm = await resolveLLM(config, callLLM, cwd)- if (!llm.ok) {- return settle({ action: 'no-op', reason: llm.reason })- }- const llmResult = await llm.call(prompt)- if (llmResult?.error) {- return settle({ action: 'no-op', reason: `llm-error: ${llmResult.error}` })- }-- const parsed = safeParse(llmResult?.text)- const { proposal, pause } = validateReasonerResponse(parsed)-- // ---- Layer 3: DECIDE (scope-gate + dedup) ----- let filedNumber = null // forge: integer issue number- let filedKey = null // jira: string ticket key (PROJ-123)- let filedAction = 'no-op'- // Machine-readable reason for a non-filed terminal outcome, so the durable- // last-run status + the on-demand toast can tell the user WHY nothing was filed- // (the common silent case being a reasoning model that returns no usable JSON).- // `no-proposal` = the reasoner ran fine and proposed nothing; `unparseable-- // response` = it returned text we couldn't parse into a proposal at all.- let reason = parsed == null ? 'unparseable-response' : 'no-proposal'- let handedOff = false- if (proposal) {- const scopeOk = isScopeAllowed({ scope: proposal.scope, allowedScopes: config.allowedScopes, isPortos })- if (!scopeOk) {- console.log(`🚫 Layered Intelligence: ${app.name} proposal scope "${proposal.scope}" not allowed — suppressed`)- reason = 'scope-suppressed'- } else if (trackerReadFailed) {- // Dedup would be blind against a failed tracker read — never file, or a- // transient forge blip files a duplicate. Retry next run (CLAUDE.md sentinel).- console.warn(`⚠️ Layered Intelligence: ${app.name} tracker read failed — suppressing proposal to avoid a blind duplicate`)- filedAction = 'tracker-read-failed'- reason = 'tracker-read-failed'- } else if (isProposalDuplicate({ slug: proposal.slug, existingIssues, now })) {- console.log(`♻️ Layered Intelligence: ${app.name} proposal "${proposal.slug}" is a duplicate — suppressed`)- filedAction = 'duplicate'- reason = 'duplicate'- } else if (await isSemanticDuplicate(app, proposal, existingIssues, now)) {- filedAction = 'semantic-duplicate'- reason = 'semantic-duplicate'- } else {- // ---- Layer 4: ACT (file exactly one) ----- const filed = await fileProposal({ filer, forgeCli, cwd, app, proposal, jira })- if (filed.success) {- filedNumber = filed.number ?? null- filedKey = filed.key ?? null- filedAction = 'filed'- reason = null // filed ⇒ nothing to explain- const ref = filedRef(filedKey, filedNumber) ?? ''- console.log(`📌 Layered Intelligence: ${app.name} filed "${proposal.title}" [${proposal.slug}]${ref ? ` (${ref})` : ''}`)- // ---- Optional Engine-A hand-off: enqueue a coding agent for a- // trivial+safe fix (approval-gated) rather than only filing it. Only- // fires when the app opted in (config.handoff.enabled) and we have a- // concrete filed ref for the agent to work — plan-tracked apps (no- // number/key) fall through to file-only. A plain forge PLAN item is- // still drained by the normal claim-work scheduler.- const issueRef = filedKey || filedNumber- if (isHandoffEligible({ proposal, config, filed: issueRef })) {- const task = await enqueueHandoff(buildHandoffTask({ app, proposal, issueRef }))- .catch((err) => { console.error(`❌ Layered Intelligence: ${app.name} hand-off enqueue failed: ${err.message}`); return null })- if (task && !task.duplicate) {- handedOff = true- console.log(`🤝 Layered Intelligence: ${app.name} handed off ${ref} to a coding agent (task ${task.id})`)- }- }- } else {- console.error(`❌ Layered Intelligence: ${app.name} failed to file proposal: ${filed.error || 'unknown'}`)- reason = 'file-failed'- }- }- }-- // ---- Pause (forge + jira; resolve blockOnIssue after filing) ----- let paused = false- if (pause && filer === 'forge' && forgeCli) {- const number = resolveBlockOnIssue(pause, filedNumber)- if (Number.isInteger(number)) {- const res = await applyBlockingLabel({ cli: forgeCli, cwd, number })- paused = res.success- if (paused) console.log(`⏸️ Layered Intelligence: ${app.name} paused on #${number} — ${pause.reason}`)- }- } else if (pause && filer === 'jira' && jira) {- const key = resolveJiraBlockKey(pause, filedKey, jira.projectKey)- if (key) {- const res = await applyJiraBlockingLabel({ instanceId: jira.instanceId, key })- paused = res.success- if (paused) console.log(`⏸️ Layered Intelligence: ${app.name} paused on ${key} — ${pause.reason}`)- }- }-- return settle({ action: filedAction, reason, filedNumber, filedKey, paused, handedOff })-}--/**- * Default hand-off enqueue: create an approval-gated internal CoS task so an- * Engine-A coding agent picks up the filed proposal. Dynamically imports cos.js- * (heavy — PM2/file/store graph) so the pure handler stays light, matching this- * file's lazy-import pattern for the provider + embeddings deps. Injectable via- * the processApp `enqueueHandoff` dep so tests never touch the real task store.- */-async function defaultEnqueueHandoff(taskData) {- const { addTask } = await import('../cos.js')- return addTask(taskData, 'internal')-}--/**- * Semantic (embedding-similarity) near-duplicate check — the extra dedup layer- * that runs AFTER the exact slug dedup passes. Suppresses a proposal that restates- * an existing dedup-window issue in different words (different slug). Best-effort:- * when embeddings aren't configured it's `available:false` and we DON'T suppress- * (slug dedup already covered the exact case). Returns a boolean "should suppress".- */-async function isSemanticDuplicate(app, proposal, existingIssues, now) {- const semantic = await checkSemanticDuplicate({ proposal, existingIssues, now })- if (!semantic.available || !semantic.duplicate) return false- const m = semantic.match- // `number` is a forge integer (#-prefixed) or a Jira string key (PROJ-123, no #).- const ref = m?.number != null- ? (typeof m.number === 'number' ? `#${m.number}` : String(m.number))- : (m?.slug || 'an existing issue')- const score = typeof m?.score === 'number' ? m.score.toFixed(2) : '?'- console.log(`♻️ Layered Intelligence: ${app.name} proposal "${proposal.slug}" is a near-duplicate of ${ref} (score ${score}) — suppressed`)- return true-}--/** File the proposal via the resolved tracker's filer. */-async function fileProposal({ filer, forgeCli, cwd, app, proposal, jira }) {- if (filer === 'forge' && forgeCli) {- return fileProposalToForge({ cli: forgeCli, cwd, title: proposal.title, body: proposal.body, slug: proposal.slug })- }- if (filer === 'jira' && jira) {- return fileProposalToJira({- instanceId: jira.instanceId, projectKey: jira.projectKey, issueType: jira.issueType,- title: proposal.title, body: proposal.body, slug: proposal.slug- })- }- if (filer === 'plan' && cwd) {- const res = await appendProposalToPlan({ repoPath: cwd, appName: app.name, slug: proposal.slug, title: proposal.title, body: proposal.body })- return { success: res.success, number: null }- }- return { success: false, error: `filer "${filer}" not implemented` }-}--/**- * Resolve the LLM call function. Prefers an injected `callLLM(prompt)`; otherwise- * resolves the active/overridden provider and returns a bound call through the- * unified `runPromptThroughProvider`. Returns `{ ok: false, reason }` when no- * provider is available (a no-op for that app, never a throw).- *- * Routing through runPromptThroughProvider (rather than the api-only- * callProviderAISimple) lets the loop reason with EVERY provider type the user- * can configure — `api` (Ollama, LM Studio), `cli` (Claude Code, Codex,- * OpenCode, Antigravity), and `tui` — not just API providers. It dispatches on- * `provider.type` and returns `{ text }`, throwing on failure; we convert a- * throw back to the `{ error }` shape processApp already branches on. `cwd` is- * the app's repo path so CLI/TUI spawns land in the right directory (no-op for- * API providers).- */-async function resolveLLM(config, injected, cwd) {- if (typeof injected === 'function') return { ok: true, call: injected }- const { getActiveProvider, getProviderById } = await import('../providers.js')- const provider = config.providerId- ? await getProviderById(config.providerId).catch(() => null)- : await getActiveProvider().catch(() => null)- if (!provider) return { ok: false, reason: 'no-provider' }- const model = config.model || provider.defaultModel- const { runPromptThroughProvider } = await import('../../lib/promptRunner.js')- return {- ok: true,- call: (prompt) => runPromptThroughProvider({- provider,- model,- prompt,- source: 'layered-intelligence',- cwd- }).catch(err => ({ error: err.message }))- }-}--/**- * Parse LLM JSON, returning null on failure (a no-op for that app). Reuses the- * shared `stripCodeFences` + `safeJSONParse` helpers rather than a local- * try/catch (repo convention: no non-boundary try/catch).- */-function safeParse(text) {- if (typeof text !== 'string') return null- return safeJSONParse(stripCodeFences(text), null, { logError: false })-}--/**- * The user-facing ref for a filed proposal: the Jira key when present, else- * `#<number>` on a forge, else null (a plain PLAN item files no number/key).- */-function filedRef(key, number) {- return key || (number != null ? `#${number}` : null)-}--/**- * Persist per-app run bookkeeping — run cadence AND the last run's OUTCOME, so a- * user (especially on mobile, where the transient "Run" toast is easy to miss)- * can look up WHY the loop produced nothing after the fact. Routes through- * updateAppLayeredIntelligence so the write RE-READS the current stored config- * and merges ONLY these bookkeeping fields over it, rather than writing back the- * (possibly seconds-stale) snapshot captured at sweep start — so a user config- * edit made mid-sweep isn't clobbered by the run-bookkeeping write.- *- * `lastRunAction` is the terminal action (filed / no-op / duplicate / parked /- * skipped / …); `lastRunReason` is the machine-readable reason for a non-filed- * outcome (or null when it filed / had nothing to explain); `lastRunRef` is the- * filed issue ref (`#123` / `PROJ-1`) when it filed, else null.- */-async function recordRun(app, config, now, outcome = {}) {- const patch = {- lastRunAt: new Date(now).toISOString(),- lastRunAction: outcome.action ?? null,- lastRunReason: outcome.reason ?? null,- lastRunRef: filedRef(outcome.filedKey, outcome.filedNumber)- }- await updateAppLayeredIntelligence(app.id, patch).catch((err) => {- console.error(`❌ Layered Intelligence: failed to record run for ${app.id}: ${err.message}`)- })-}--// Back-compat alias for the per-app entry point. The global cross-app sweep-// (`runLayeredIntelligence`) was removed with the migration to a per-app-// handler-backed scheduled task (#2322) — the scheduler now calls-// runLayeredIntelligenceForApp for one due app at a time.-export const processApp = runLayeredIntelligenceForAppdiff --git a/server/services/autonomousJobs/layeredIntelligenceHandler.test.js b/server/services/autonomousJobs/layeredIntelligenceHandler.test.jsdeleted file mode 100644index dd53443617..0000000000--- a/server/services/autonomousJobs/layeredIntelligenceHandler.test.js+++ /dev/null@@ -1,532 +0,0 @@-import { describe, it, expect, vi, beforeEach } from 'vitest';--// The handler pulls in apps.js (heavy). Mock the surface it uses so tests drive-// pure orchestration without touching disk / PM2 / the app store.-const updateAppMock = vi.fn().mockResolvedValue({});-vi.mock('../apps.js', () => ({- PORTOS_APP_ID: 'portos-default',- getActiveApps: vi.fn().mockResolvedValue([]),- // recordRun routes lastRunAt bookkeeping through updateAppLayeredIntelligence.- updateAppLayeredIntelligence: (...args) => updateAppMock(...args)-}));--// resolveAppWorkTracker is async + shells out to git; stub per-test.-const resolveTrackerMock = vi.fn();-vi.mock('../../lib/workTracker.js', () => ({- resolveAppWorkTracker: (...args) => resolveTrackerMock(...args)-}));--// gatherSources reads the repo; stub to a fixed map. The forge listers/filers-// are exercised in layeredIntelligence.test.js — here we stub them so processApp-// orchestration (park → gather → reason → decide → act → pause) is isolated.-const forgeState = {- existing: [],- existingOk: true,- blocking: [],- blockingOk: true,- fileResult: { success: true, number: 100 },- filed: [],- blockingApplied: [],- // Jira mirrors: separate lister/filer/label spies so the dispatch is asserted per tracker.- jiraExisting: [],- jiraExistingOk: true,- jiraBlocking: [],- jiraBlockingOk: true,- jiraFileResult: { success: true, key: 'PROJ-100' },- jiraFiled: [],- jiraBlockingApplied: [],- // Semantic dedup default: unavailable (embeddings off) → never suppresses.- // The real checkSemanticDuplicate lazy-imports embeddings.js; mock it so- // processApp orchestration is isolated from the embedding provider.- semanticResult: { available: false, duplicate: false, match: null }-};-vi.mock('../layeredIntelligence.js', async (importOriginal) => {- const actual = await importOriginal();- return {- ...actual,- gatherSources: vi.fn().mockResolvedValue({ goals: 'g' }),- // Listers now return { ok, issues }; forgeState.existingOk toggles a failed read.- listForgeIssues: vi.fn(async () => ({ ok: forgeState.existingOk, issues: forgeState.existing })),- listBlockingIssues: vi.fn(async () => ({ ok: forgeState.blockingOk, issues: forgeState.blocking })),- checkSemanticDuplicate: vi.fn(async () => forgeState.semanticResult),- fileProposalToForge: vi.fn(async (opts) => { forgeState.filed.push(opts); return forgeState.fileResult; }),- applyBlockingLabel: vi.fn(async (opts) => { forgeState.blockingApplied.push(opts); return { success: true }; }),- appendProposalToPlan: vi.fn(async () => ({ success: true, duplicate: false })),- listJiraIssues: vi.fn(async () => ({ ok: forgeState.jiraExistingOk, issues: forgeState.jiraExisting })),- listJiraBlockingIssues: vi.fn(async () => ({ ok: forgeState.jiraBlockingOk, issues: forgeState.jiraBlocking })),- fileProposalToJira: vi.fn(async (opts) => { forgeState.jiraFiled.push(opts); return forgeState.jiraFileResult; }),- applyJiraBlockingLabel: vi.fn(async (opts) => { forgeState.jiraBlockingApplied.push(opts); return { success: true }; })- };-});--// resolveLLM lazy-imports these only when NO callLLM is injected. Mocking them-// lets us assert the real provider-resolution path routes through the unified-// runPromptThroughProvider (which supports cli/api/tui) rather than the old-// api-only callProviderAISimple.-const runPromptMock = vi.fn().mockResolvedValue({ text: '{}' });-vi.mock('../../lib/promptRunner.js', () => ({- runPromptThroughProvider: (...args) => runPromptMock(...args)-}));-const getProviderByIdMock = vi.fn();-const getActiveProviderMock = vi.fn();-vi.mock('../providers.js', () => ({- getProviderById: (...args) => getProviderByIdMock(...args),- getActiveProvider: (...args) => getActiveProviderMock(...args)-}));--import { isAppDue, processApp, runLayeredIntelligenceForApp } from './layeredIntelligenceHandler.js';--const DAY = 24 * 60 * 60 * 1000;--function reasoner(response) {- return vi.fn().mockResolvedValue({ text: JSON.stringify(response) });-}--beforeEach(() => {- vi.clearAllMocks();- updateAppMock.mockResolvedValue({});- forgeState.existing = [];- forgeState.existingOk = true;- forgeState.blocking = [];- forgeState.blockingOk = true;- forgeState.fileResult = { success: true, number: 100 };- forgeState.filed = [];- forgeState.blockingApplied = [];- forgeState.jiraExisting = [];- forgeState.jiraExistingOk = true;- forgeState.jiraBlocking = [];- forgeState.jiraBlockingOk = true;- forgeState.jiraFileResult = { success: true, key: 'PROJ-100' };- forgeState.jiraFiled = [];- forgeState.jiraBlockingApplied = [];- forgeState.semanticResult = { available: false, duplicate: false, match: null };- resolveTrackerMock.mockResolvedValue({ resolved: 'github', forge: 'gh' });- runPromptMock.mockResolvedValue({ text: '{}' });- // Default to resolving null (no provider) — mirrors the real async signature so- // resolveLLM's `.catch()` never trips over a non-promise in sweep tests that- // don't inject callLLM.- getProviderByIdMock.mockReset().mockResolvedValue(null);- getActiveProviderMock.mockReset().mockResolvedValue(null);-});--describe('isAppDue', () => {- it('is due when never run', () => {- expect(isAppDue({ intervalMs: DAY }, null)).toBe(true);- expect(isAppDue({ intervalMs: DAY }, 'not-a-date')).toBe(true);- });-- it('is due when the interval has elapsed', () => {- const now = Date.parse('2026-07-07T00:00:00Z');- const lastRun = new Date(now - DAY - 1000).toISOString();- expect(isAppDue({ intervalMs: DAY }, lastRun, now)).toBe(true);- });-- it('is NOT due within the interval', () => {- const now = Date.parse('2026-07-07T00:00:00Z');- const lastRun = new Date(now - DAY / 2).toISOString();- expect(isAppDue({ intervalMs: DAY }, lastRun, now)).toBe(false);- });-});--describe('processApp', () => {- const enabledApp = (extra = {}) => ({- id: 'app-1', name: 'App One', repoPath: '/repo',- layeredIntelligence: { enabled: true, intervalMs: DAY, allowedScopes: ['app-improvement', 'app-data-gap'] },- ...extra- });-- // The scheduler now owns enabled/due gating (#2322) — the handler no longer- // self-gates on config.enabled or interval, so a disabled/not-due app is simply- // never dispatched to it. `runLayeredIntelligenceForApp` (aliased as processApp)- // always runs the layers and records the run.- it('runs the layers even for a config marked disabled (scheduler owns gating)', async () => {- const callLLM = reasoner({ proposal: { scope: 'app-improvement', slug: 'add-x', title: 'Add X', body: 'do it' } });- const out = await runLayeredIntelligenceForApp({ id: 'app-1', name: 'App One', repoPath: '/repo', layeredIntelligence: { enabled: false, allowedScopes: ['app-improvement'] } }, { callLLM });- expect(out.action).toBe('filed');- expect(updateAppMock).toHaveBeenCalled(); // still records the run- });-- it('runs regardless of lastRunAt (cadence is the scheduler\'s job now)', async () => {- const now = Date.parse('2026-07-07T00:00:00Z');- const app = enabledApp();- app.layeredIntelligence.lastRunAt = new Date(now - DAY / 2).toISOString(); // "not due" by old logic- const callLLM = reasoner({ proposal: { scope: 'app-improvement', slug: 'add-x', title: 'Add X', body: 'do it' } });- const out = await processApp(app, { now, callLLM });- expect(out.action).toBe('filed');- });-- it('overlays provider/model from the per-app task override onto the effective config', async () => {- // No callLLM injected → resolveLLM resolves via getProviderById using the- // override's providerId. Assert the override provider is the one looked up.- getProviderByIdMock.mockResolvedValue({ id: 'ov-provider', type: 'api', defaultModel: 'ov-default' });- const app = enabledApp({ taskTypeOverrides: { 'layered-intelligence': { providerId: 'ov-provider', model: 'ov-model' } } });- await runLayeredIntelligenceForApp(app, {});- expect(getProviderByIdMock).toHaveBeenCalledWith('ov-provider');- expect(runPromptMock).toHaveBeenCalledWith(expect.objectContaining({ model: 'ov-model' }));- });-- it('parks (skips reasoning) when a blocking issue is open', async () => {- forgeState.blocking = [{ number: 5, state: 'open' }];- const callLLM = reasoner({ proposal: { scope: 'app-improvement', slug: 's', title: 'T' } });- const out = await processApp(enabledApp(), { callLLM });- expect(out.action).toBe('parked');- expect(callLLM).not.toHaveBeenCalled(); // never reasoned- expect(updateAppMock).toHaveBeenCalled(); // still records the run- });-- it('files ONE issue for a valid, allowed, non-duplicate proposal', async () => {- const callLLM = reasoner({ proposal: { scope: 'app-improvement', slug: 'add-x', title: 'Add X', body: 'do it' } });- const out = await processApp(enabledApp(), { callLLM });- expect(out.action).toBe('filed');- expect(out.filedNumber).toBe(100);- expect(forgeState.filed).toHaveLength(1);- expect(forgeState.filed[0].slug).toBe('add-x');- });-- it('suppresses a proposal whose scope is not allowed (double-enforced)', async () => {- // Non-PortOS app; loop-meta is PortOS-only so it must be blocked even though the model returned it.- const callLLM = reasoner({ proposal: { scope: 'loop-meta', slug: 'meta', title: 'Meta' } });- const out = await processApp(enabledApp(), { callLLM });- expect(out.action).toBe('no-op');- expect(forgeState.filed).toHaveLength(0);- });-- it('suppresses a duplicate proposal', async () => {- forgeState.existing = [{ slug: 'add-x', state: 'open' }];- const callLLM = reasoner({ proposal: { scope: 'app-improvement', slug: 'add-x', title: 'Add X' } });- const out = await processApp(enabledApp(), { callLLM });- expect(out.action).toBe('duplicate');- expect(forgeState.filed).toHaveLength(0);- });-- it('suppresses a semantic near-duplicate (different slug) when embeddings flag it', async () => {- // Slug does NOT match an existing issue, so slug dedup passes; the semantic- // layer reports a near-duplicate and suppresses before filing.- forgeState.existing = [{ number: 7, slug: 'add-widget', title: 'Add widget', body: 'do it', state: 'open' }];- forgeState.semanticResult = { available: true, duplicate: true, match: { number: 7, slug: 'add-widget', score: 0.95 } };- const callLLM = reasoner({ proposal: { scope: 'app-improvement', slug: 'introduce-widget', title: 'Introduce a widget', body: 'do it' } });- const out = await processApp(enabledApp(), { callLLM });- expect(out.action).toBe('semantic-duplicate');- expect(forgeState.filed).toHaveLength(0);- });-- it('files when the semantic layer is unavailable (embeddings off) — best-effort only', async () => {- forgeState.existing = [{ number: 7, slug: 'add-widget', title: 'Add widget', body: 'do it', state: 'open' }];- forgeState.semanticResult = { available: false, duplicate: false, match: null };- const callLLM = reasoner({ proposal: { scope: 'app-improvement', slug: 'introduce-widget', title: 'Introduce a widget', body: 'do it' } });- const out = await processApp(enabledApp(), { callLLM });- expect(out.action).toBe('filed');- expect(forgeState.filed).toHaveLength(1);- });-- it('files AND pauses when the response carries both, blocking on "this"', async () => {- const callLLM = reasoner({- proposal: { scope: 'app-improvement', slug: 'add-x', title: 'Add X' },- pause: { blockOnIssue: 'this', reason: 'need this first' }- });- const out = await processApp(enabledApp(), { callLLM });- expect(out.action).toBe('filed');- expect(out.paused).toBe(true);- expect(forgeState.blockingApplied[0].number).toBe(100); // "this" → filed number- });-- it('is a no-op on invalid JSON but still records the run', async () => {- const callLLM = vi.fn().mockResolvedValue({ text: 'not json{{{' });- const out = await processApp(enabledApp(), { callLLM });- expect(out.action).toBe('no-op');- expect(updateAppMock).toHaveBeenCalled();- });-- it('is a no-op when the LLM errors', async () => {- const callLLM = vi.fn().mockResolvedValue({ error: 'timeout' });- const out = await processApp(enabledApp(), { callLLM });- expect(out.action).toBe('no-op');- expect(out.reason).toContain('timeout');- });-- it('does NOT file when the tracker issue-list read failed (avoids blind duplicate)', async () => {- forgeState.existingOk = false;- const callLLM = reasoner({ proposal: { scope: 'app-improvement', slug: 'add-x', title: 'Add X' } });- const out = await processApp(enabledApp(), { callLLM });- expect(out.action).toBe('tracker-read-failed');- expect(forgeState.filed).toHaveLength(0);- });-- it('skips (does not reason) when the blocking-issue read failed', async () => {- forgeState.blockingOk = false;- const callLLM = reasoner({ proposal: { scope: 'app-improvement', slug: 'add-x', title: 'Add X' } });- const out = await processApp(enabledApp(), { callLLM });- expect(out.action).toBe('skipped');- expect(out.reason).toBe('blocking-read-failed');- expect(callLLM).not.toHaveBeenCalled();- });-- it('does NOT pass open issues to the prompt when the openIssues source is off (but still dedups)', async () => {- forgeState.existing = [{ slug: 'add-x', state: 'open' }];- const app = enabledApp();- app.layeredIntelligence.sources = { openIssues: false };- const callLLM = reasoner({ proposal: { scope: 'app-improvement', slug: 'add-x', title: 'Add X' } });- const out = await processApp(app, { callLLM });- // Dedup still fires against existing issues regardless of the prompt toggle.- expect(out.action).toBe('duplicate');- });-- it('hands a trivial+safe filed proposal to a coding agent when hand-off is enabled', async () => {- const enqueueHandoff = vi.fn().mockResolvedValue({ id: 'sys-1' });- const app = enabledApp();- app.layeredIntelligence.handoff = { enabled: true };- const callLLM = reasoner({ proposal: { scope: 'app-improvement', slug: 'fix-x', title: 'Fix X', body: 'do it', complexity: 'trivial', safe: true } });- const out = await processApp(app, { callLLM, enqueueHandoff });- expect(out.action).toBe('filed');- expect(out.handedOff).toBe(true);- expect(enqueueHandoff).toHaveBeenCalledTimes(1);- expect(enqueueHandoff.mock.calls[0][0]).toMatchObject({ approvalRequired: true, app: 'app-1' });- });-- it('does NOT hand off when the app has not opted in (files only)', async () => {- const enqueueHandoff = vi.fn().mockResolvedValue({ id: 'sys-1' });- const callLLM = reasoner({ proposal: { scope: 'app-improvement', slug: 'fix-x', title: 'Fix X', complexity: 'trivial', safe: true } });- const out = await processApp(enabledApp(), { callLLM, enqueueHandoff });- expect(out.action).toBe('filed');- expect(out.handedOff).toBe(false);- expect(enqueueHandoff).not.toHaveBeenCalled();- });-- it('does NOT hand off a non-trivial proposal even with hand-off enabled', async () => {- const enqueueHandoff = vi.fn().mockResolvedValue({ id: 'sys-1' });- const app = enabledApp();- app.layeredIntelligence.handoff = { enabled: true };- const callLLM = reasoner({ proposal: { scope: 'app-improvement', slug: 'fix-x', title: 'Fix X', complexity: 'moderate', safe: true } });- const out = await processApp(app, { callLLM, enqueueHandoff });- expect(out.handedOff).toBe(false);- expect(enqueueHandoff).not.toHaveBeenCalled();- });-- it('does not mark handedOff when the enqueue is rejected as a duplicate', async () => {- const enqueueHandoff = vi.fn().mockResolvedValue({ id: 'sys-1', duplicate: true });- const app = enabledApp();- app.layeredIntelligence.handoff = { enabled: true };- const callLLM = reasoner({ proposal: { scope: 'app-improvement', slug: 'fix-x', title: 'Fix X', complexity: 'trivial', safe: true } });- const out = await processApp(app, { callLLM, enqueueHandoff });- expect(out.action).toBe('filed');- expect(out.handedOff).toBe(false);- });-- it('files (never throws) when the hand-off enqueue rejects', async () => {- const enqueueHandoff = vi.fn().mockRejectedValue(new Error('store down'));- const app = enabledApp();- app.layeredIntelligence.handoff = { enabled: true };- const callLLM = reasoner({ proposal: { scope: 'app-improvement', slug: 'fix-x', title: 'Fix X', complexity: 'trivial', safe: true } });- const out = await processApp(app, { callLLM, enqueueHandoff });- expect(out.action).toBe('filed');- expect(out.handedOff).toBe(false);- });-- it('does NOT pause a plan-tracked app (no issue to block on)', async () => {- resolveTrackerMock.mockResolvedValue({ resolved: 'plan', forge: null });- const callLLM = reasoner({- proposal: { scope: 'app-improvement', slug: 'add-x', title: 'Add X' },- pause: { blockOnIssue: 'this', reason: 'x' }- });- const out = await processApp(enabledApp(), { callLLM });- expect(out.action).toBe('filed');- expect(out.paused).toBe(false); // pause skipped for plan tracker- expect(forgeState.blockingApplied).toHaveLength(0);- });-});--describe('processApp — provider resolution (no injected callLLM)', () => {- const app = (providerId) => ({- id: 'app-1', name: 'App One', repoPath: '/repo',- layeredIntelligence: { enabled: true, intervalMs: DAY, providerId, allowedScopes: ['app-improvement'] }- });-- it('reasons through runPromptThroughProvider for a non-API (tui) provider', async () => {- getProviderByIdMock.mockResolvedValue({ id: 'claude-code-tui', type: 'tui', defaultModel: null });- runPromptMock.mockResolvedValue({ text: JSON.stringify({ proposal: { scope: 'app-improvement', slug: 'add-x', title: 'Add X', body: 'do it' } }) });- const out = await processApp(app('claude-code-tui'));- expect(getProviderByIdMock).toHaveBeenCalledWith('claude-code-tui');- expect(runPromptMock).toHaveBeenCalledWith(expect.objectContaining({- provider: expect.objectContaining({ id: 'claude-code-tui', type: 'tui' }),- source: 'layered-intelligence',- cwd: '/repo'- }));- expect(out.action).toBe('filed');- });-- it('works for a cli provider too (Claude Code / Codex / OpenCode)', async () => {- getProviderByIdMock.mockResolvedValue({ id: 'opencode-ollama', type: 'cli', defaultModel: null });- runPromptMock.mockResolvedValue({ text: JSON.stringify({ proposal: { scope: 'app-improvement', slug: 'add-y', title: 'Add Y', body: 'do it' } }) });- const out = await processApp(app('opencode-ollama'));- expect(runPromptMock).toHaveBeenCalledWith(expect.objectContaining({ provider: expect.objectContaining({ type: 'cli' }) }));- expect(out.action).toBe('filed');- });-- it('falls back to the active provider when no providerId is set', async () => {- getActiveProviderMock.mockResolvedValue({ id: 'ollama', type: 'api', defaultModel: 'llama3.2' });- runPromptMock.mockResolvedValue({ text: JSON.stringify({ proposal: { scope: 'app-improvement', slug: 'add-z', title: 'Add Z', body: 'do it' } }) });- const out = await processApp(app(null));- expect(getProviderByIdMock).not.toHaveBeenCalled();- expect(getActiveProviderMock).toHaveBeenCalled();- expect(out.action).toBe('filed');- });-- it('no-ops (never throws) when the runner rejects', async () => {- getProviderByIdMock.mockResolvedValue({ id: 'ollama', type: 'api', defaultModel: 'llama3.2' });- runPromptMock.mockRejectedValue(new Error('backend down'));- const out = await processApp(app('ollama'));- expect(out.action).toBe('no-op');- expect(out.reason).toContain('backend down');- });-- it('no-ops when the provider cannot be resolved', async () => {- getProviderByIdMock.mockResolvedValue(null);- const out = await processApp(app('ghost-provider'));- expect(out.action).toBe('no-op');- expect(out.reason).toBe('no-provider');- expect(runPromptMock).not.toHaveBeenCalled();- });-});--describe('processApp — jira tracker', () => {- const jiraApp = (extra = {}) => ({- id: 'app-j', name: 'Jira App', repoPath: '/repo',- jira: { enabled: true, instanceId: 'inst', projectKey: 'PROJ', issueType: 'Task' },- layeredIntelligence: { enabled: true, intervalMs: DAY, allowedScopes: ['app-improvement', 'app-data-gap'] },- ...extra- });-- beforeEach(() => {- resolveTrackerMock.mockResolvedValue({ resolved: 'jira', forge: null });- });-- it('skips a jira-tracked app that has no usable jira config (before reasoning)', async () => {- const callLLM = reasoner({ proposal: { scope: 'app-improvement', slug: 's', title: 'T' } });- const out = await processApp({- id: 'app-j', name: 'Jira App', repoPath: '/repo',- jira: { enabled: false },- layeredIntelligence: { enabled: true, intervalMs: DAY, allowedScopes: ['app-improvement'] }- }, { callLLM });- expect(out.action).toBe('skipped');- expect(out.reason).toBe('jira-not-configured');- expect(callLLM).not.toHaveBeenCalled();- });-- it('files ONE jira ticket for a valid proposal', async () => {- const callLLM = reasoner({ proposal: { scope: 'app-improvement', slug: 'add-x', title: 'Add X', body: 'do it' } });- const out = await processApp(jiraApp(), { callLLM });- expect(out.action).toBe('filed');- expect(out.filedKey).toBe('PROJ-100');- expect(forgeState.jiraFiled).toHaveLength(1);- expect(forgeState.jiraFiled[0]).toMatchObject({ instanceId: 'inst', projectKey: 'PROJ', slug: 'add-x' });- expect(forgeState.filed).toHaveLength(0); // never touches the forge filer- });-- it('parks a jira app when a blocking ticket is open (skips reasoning)', async () => {- forgeState.jiraBlocking = [{ number: 'PROJ-5', state: 'open' }];- const callLLM = reasoner({ proposal: { scope: 'app-improvement', slug: 's', title: 'T' } });- const out = await processApp(jiraApp(), { callLLM });- expect(out.action).toBe('parked');- expect(callLLM).not.toHaveBeenCalled();- });-- it('does NOT file when the jira issue-list read failed (avoids blind duplicate)', async () => {- forgeState.jiraExistingOk = false;- const callLLM = reasoner({ proposal: { scope: 'app-improvement', slug: 'add-x', title: 'Add X' } });- const out = await processApp(jiraApp(), { callLLM });- expect(out.action).toBe('tracker-read-failed');- expect(forgeState.jiraFiled).toHaveLength(0);- });-- it('dedups a jira proposal against existing tickets', async () => {- forgeState.jiraExisting = [{ slug: 'add-x', state: 'open' }];- const callLLM = reasoner({ proposal: { scope: 'app-improvement', slug: 'add-x', title: 'Add X' } });- const out = await processApp(jiraApp(), { callLLM });- expect(out.action).toBe('duplicate');- expect(forgeState.jiraFiled).toHaveLength(0);- });-- it('files AND pauses on the just-filed jira ticket key ("this")', async () => {- const callLLM = reasoner({- proposal: { scope: 'app-improvement', slug: 'add-x', title: 'Add X' },- pause: { blockOnIssue: 'this', reason: 'need this first' }- });- const out = await processApp(jiraApp(), { callLLM });- expect(out.action).toBe('filed');- expect(out.paused).toBe(true);- expect(forgeState.jiraBlockingApplied[0]).toMatchObject({ instanceId: 'inst', key: 'PROJ-100' });- });-- it('resolves an integer pause target to <project>-<n> on an existing jira ticket', async () => {- const callLLM = reasoner({ pause: { blockOnIssue: 7, reason: 'block on an existing ticket' } });- const out = await processApp(jiraApp(), { callLLM });- expect(out.paused).toBe(true);- expect(forgeState.jiraBlockingApplied[0].key).toBe('PROJ-7');- });-});--describe('run outcome reason + persisted bookkeeping', () => {- const enabledApp = (extra = {}) => ({- id: 'app-1', name: 'App One', repoPath: '/repo',- layeredIntelligence: { enabled: true, intervalMs: DAY, allowedScopes: ['app-improvement', 'app-data-gap'] },- ...extra- });-- // The last recordRun patch (updateAppLayeredIntelligence is recordRun's sink).- const lastRunPatch = () => updateAppMock.mock.calls.at(-1)?.[1];-- it('reports unparseable-response when the model returns no usable JSON', async () => {- const callLLM = vi.fn().mockResolvedValue({ text: 'I am thinking… no JSON here.' });- const out = await processApp(enabledApp(), { callLLM });- expect(out.action).toBe('no-op');- expect(out.reason).toBe('unparseable-response');- expect(lastRunPatch()).toMatchObject({ lastRunAction: 'no-op', lastRunReason: 'unparseable-response', lastRunRef: null });- });-- it('reports no-proposal when the reasoner ran but proposed nothing', async () => {- const callLLM = reasoner({ analysis: 'nothing worth doing' });- const out = await processApp(enabledApp(), { callLLM });- expect(out.action).toBe('no-op');- expect(out.reason).toBe('no-proposal');- });-- it('reports scope-suppressed with a reason (was a silent no-op)', async () => {- const callLLM = reasoner({ proposal: { scope: 'loop-meta', slug: 'meta', title: 'Meta' } });- const out = await processApp(enabledApp(), { callLLM });- expect(out.action).toBe('no-op');- expect(out.reason).toBe('scope-suppressed');- });-- it('persists the filed ref + null reason on a successful file', async () => {- const callLLM = reasoner({ proposal: { scope: 'app-improvement', slug: 'add-x', title: 'Add X' } });- const out = await processApp(enabledApp(), { callLLM });- expect(out.action).toBe('filed');- expect(out.reason).toBeNull();- expect(lastRunPatch()).toMatchObject({ lastRunAction: 'filed', lastRunReason: null, lastRunRef: '#100' });- });-- it('carries the llm-error reason through to the persisted outcome', async () => {- const callLLM = vi.fn().mockResolvedValue({ error: 'provider timeout' });- const out = await processApp(enabledApp(), { callLLM });- expect(out.action).toBe('no-op');- expect(out.reason).toBe('llm-error: provider timeout');- expect(lastRunPatch()?.lastRunReason).toBe('llm-error: provider timeout');- });-- it('records the park reason + blocking count in the outcome', async () => {- forgeState.blocking = [{ number: 5, state: 'open' }];- const callLLM = reasoner({ proposal: { scope: 'app-improvement', slug: 's', title: 'T' } });- const out = await processApp(enabledApp(), { callLLM });- expect(out).toMatchObject({ action: 'parked', reason: 'blocking-open', blocking: 1 });- expect(lastRunPatch()).toMatchObject({ lastRunAction: 'parked', lastRunReason: 'blocking-open' });- });-});--describe('runLayeredIntelligenceForApp (removed global sweep)', () => {- it('no longer exports a cross-app sweep — the scheduler drives one app at a time', async () => {- const mod = await import('./layeredIntelligenceHandler.js');- expect(mod.runLayeredIntelligence).toBeUndefined();- expect(typeof mod.runLayeredIntelligenceForApp).toBe('function');- expect(mod.processApp).toBe(mod.runLayeredIntelligenceForApp); // back-compat alias- });-});diff --git a/server/services/autonomousJobs/layeredIntelligenceHooks.js b/server/services/autonomousJobs/layeredIntelligenceHooks.jsnew file mode 100644index 0000000000..138f6dd3ce--- /dev/null+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.js@@ -0,0 +1,354 @@+/**+ * Layered Intelligence as programmatic-I/O hooks (issue-follow-up to #2322).+ *+ * LI used to run as a HANDLER-BACKED task — an inline `runPromptThroughProvider`+ * call wrapped in `runLayeredIntelligenceForApp`, invisible to the CoS queue /+ * Active Agents and un-attachable in a TUI. It is now a NORMAL agent-backed+ * scheduled task with two programmatic slots (see taskTypeHooks.js ++ * docs/plans/2026-07-09-programmatic-io-scheduled-tasks.md):+ *+ * - `buildTaskInput({ app })` — the GATHER layer: park-check (skip if parked),+ * gather the app's sources + open issues, and build the reasoning prompt the+ * agent runs. Returns `{ prompt, skip? }`.+ * - `processTaskOutput({ appId, payload, ... })` — the DECIDE + ACT layers:+ * validate the agent's structured `.agent-done` payload, scope-gate, dedup+ * (exact + semantic), file exactly one tracker issue, pause, optional Engine-A+ * hand-off, and record last-run bookkeeping.+ *+ * The REASON layer is now the agent itself (visible, TUI-capable). Its worktree+ * is discarded without a commit (LI's task metadata sets discardWorktree), so the+ * agent can't land code — the structured payload is its only channel out, exactly+ * the "reasoner never writes code" guarantee the old handler enforced by never+ * spawning an agent at all. Every deterministic side effect stays in these hooks.+ *+ * Runs OUTSIDE the request lifecycle (scheduler tick / agent completion), so per+ * the CLAUDE.md no-try/catch rule the dispatchers own the async boundary; these+ * stay defensive so a partial failure degrades to a recorded no-op.+ */++import { PORTOS_APP_ID, updateAppLayeredIntelligence, getAppById } from '../apps.js'+import {+ getEffectiveConfig,+ buildPrompt,+ gatherSources,+ listForgeIssues,+ listBlockingIssues,+ isAppParked,+ validateReasonerResponse,+ isScopeAllowed,+ isProposalDuplicate,+ checkSemanticDuplicate,+ isHandoffEligible,+ buildHandoffTask,+ filerForTracker,+ trackerSupportsPause,+ resolveBlockOnIssue,+ fileProposalToForge,+ applyBlockingLabel,+ appendProposalToPlan,+ extractPlanSlugs,+ listJiraIssues,+ listJiraBlockingIssues,+ fileProposalToJira,+ resolveJiraBlockKey,+ applyJiraBlockingLabel+} from '../layeredIntelligence.js'+import { resolveAppWorkTracker } from '../../lib/workTracker.js'+import { tryReadFile } from '../../lib/fileUtils.js'+import { join } from 'path'++/**+ * Resolve the per-app LI execution context shared by both hooks: effective+ * config (with the per-app task provider/model overlaid), whether this app IS+ * the PortOS install, the resolved work tracker + filer, and the Jira coords when+ * jira-tracked. Mirrors the old handler's L91–126 setup so the split hooks agree+ * on WHERE work files.+ */+async function resolveLiContext(app) {+ const isPortos = app.id === PORTOS_APP_ID+ const config = getEffectiveConfig({ ...app, isPortos })++ // Option A: provider/model live in the per-app scheduled-task override; overlay+ // them so downstream (prompt + record) sees the app's choice.+ const override = (app.taskTypeOverrides && typeof app.taskTypeOverrides === 'object')+ ? (app.taskTypeOverrides['layered-intelligence'] || {})+ : {}+ if (override.providerId != null) config.providerId = override.providerId+ if (override.model != null) config.model = override.model++ const tracker = await resolveAppWorkTracker(app).catch(() => ({ resolved: 'plan', forge: null }))+ const filer = filerForTracker(tracker.resolved)+ const forgeCli = tracker.forge // 'gh' | 'glab' | null+ const cwd = app.repoPath+ const jira = (filer === 'jira' && app.jira?.enabled && app.jira?.instanceId && app.jira?.projectKey)+ ? { instanceId: app.jira.instanceId, projectKey: app.jira.projectKey, issueType: app.jira.issueType || 'Task' }+ : null++ return { isPortos, config, tracker, filer, forgeCli, cwd, jira }+}++/**+ * Read the app's open + existing tracker issues for the reasoner (open issues) and+ * the dedup guard (all existing). Returns `{ openIssues, existingIssues,+ * trackerReadFailed }`. A failed read is surfaced (never treated as "no issues")+ * so the caller can suppress filing rather than risk a blind duplicate.+ */+async function readIssues({ filer, forgeCli, cwd, jira, config }) {+ let openIssues = []+ let existingIssues = []+ let trackerReadFailed = false+ if (filer === 'forge' && forgeCli) {+ const listed = await listForgeIssues({ cli: forgeCli, cwd })+ trackerReadFailed = !listed.ok+ existingIssues = listed.issues+ if (config.sources?.openIssues !== false) openIssues = existingIssues.filter(i => i.state === 'open')+ } else if (filer === 'jira' && jira) {+ const listed = await listJiraIssues({ instanceId: jira.instanceId, projectKey: jira.projectKey })+ trackerReadFailed = !listed.ok+ existingIssues = listed.issues+ if (config.sources?.openIssues !== false) openIssues = existingIssues.filter(i => i.state === 'open')+ } else if (filer === 'plan' && cwd) {+ const planContent = await tryReadFile(join(cwd, 'PLAN.md'))+ const planSlugs = extractPlanSlugs(planContent || '')+ existingIssues = planSlugs.map(slug => ({ slug, state: 'open' }))+ }+ return { openIssues, existingIssues, trackerReadFailed }+}++/**+ * The completion contract appended to the reasoning prompt: the agent must NOT+ * write code or open a PR (its worktree is discarded anyway) — it reasons and+ * writes its structured result to the `.agent-done` sentinel so the+ * processTaskOutput hook can file it. `payload` is the exact reasoner-JSON shape+ * buildPrompt already documents.+ */+function buildCompletionContract() {+ return [+ '',+ '---',+ '',+ '## How to finish',+ '',+ 'You are a REASONING agent, not a coding agent. Do NOT edit code, run `/do:pr`,',+ 'commit, or open a pull request — any changes you make to this worktree are',+ 'discarded. Your ONLY output is the JSON described above.',+ '',+ 'When you have decided, write a file named `.agent-done` in the current',+ 'directory containing a single JSON object:',+ '',+ '```json',+ '{ "summary": "<one-line human summary of what you proposed, or that you proposed nothing>",',+ ' "payload": <the exact JSON object described above> }',+ '```',+ '',+ 'Then stop. Do nothing else.'+ ].join('\n')+}++/**+ * Pre-agent GATHER hook. Resolves context, skips a parked/unfileable app, gathers+ * sources + open issues, and returns the fully-rendered reasoning prompt for the+ * agent. `{ skip: { reason } }` short-circuits dispatch (no agent spawned).+ */+export async function buildTaskInput({ app } = {}) {+ if (!app) return { skip: { reason: 'no-app' } }+ const ctx = await resolveLiContext(app)+ const { isPortos, config, tracker, filer, forgeCli, cwd, jira } = ctx++ // A skip means no agent spawns, so processTaskOutput never records the run —+ // record the last-run outcome HERE (mirrors the old handler's settle()) so the+ // Intelligence tab's "Last run: parked / skipped" explanation stays accurate.+ const skip = async (action, reason) => {+ await recordRun(app, { action, reason })+ return { skip: { reason } }+ }++ // A jira-tracked app with no usable instance/project can't file — skip before+ // burning an agent on a result we couldn't land.+ if (filer === 'jira' && !jira) return skip('skipped', 'jira-not-configured')++ // Park check (forge + jira; plan has no issue to block on). A FAILED read is not+ // "no blocking issues" — skip rather than resume work the user parked.+ if (trackerSupportsPause(tracker.resolved)) {+ const blocking = filer === 'jira'+ ? await listJiraBlockingIssues({ instanceId: jira.instanceId, projectKey: jira.projectKey })+ : (forgeCli ? await listBlockingIssues({ cli: forgeCli, cwd }) : null)+ if (blocking && !blocking.ok) return skip('skipped', 'blocking-read-failed')+ if (blocking && isAppParked(blocking.issues)) return skip('parked', 'blocking-open')+ }++ // Independent reads (app source set vs the tracker's open-issue list) — overlap+ // them so the non-parked path pays one round-trip, not two.+ const [sources, { openIssues }] = await Promise.all([+ gatherSources(app, config),+ readIssues({ filer, forgeCli, cwd, jira, config })+ ])+ const prompt = buildPrompt({ app, config, sources, openIssues, isPortos }) + buildCompletionContract()+ // Option A: surface the per-app provider/model (resolved onto config in+ // resolveLiContext) so the generator pins the AGENT to the app's choice — LI+ // keeps provider/model in taskTypeOverrides, not the global schedule interval.+ return { prompt, providerId: config.providerId ?? null, model: config.model ?? null }+}++/**+ * File the proposal via the resolved tracker's filer (forge / jira / plan).+ */+async function fileProposal({ filer, forgeCli, cwd, app, proposal, jira }) {+ if (filer === 'forge' && forgeCli) {+ return fileProposalToForge({ cli: forgeCli, cwd, title: proposal.title, body: proposal.body, slug: proposal.slug })+ }+ if (filer === 'jira' && jira) {+ return fileProposalToJira({+ instanceId: jira.instanceId, projectKey: jira.projectKey, issueType: jira.issueType,+ title: proposal.title, body: proposal.body, slug: proposal.slug+ })+ }+ if (filer === 'plan' && cwd) {+ const res = await appendProposalToPlan({ repoPath: cwd, appName: app.name, slug: proposal.slug, title: proposal.title, body: proposal.body })+ return { success: res.success, number: null }+ }+ return { success: false, error: `filer "${filer}" not implemented` }+}++/** Semantic near-duplicate check (embedding similarity), best-effort. */+async function isSemanticDuplicate(app, proposal, existingIssues, now) {+ const semantic = await checkSemanticDuplicate({ proposal, existingIssues, now })+ if (!semantic.available || !semantic.duplicate) return false+ const m = semantic.match+ const ref = m?.number != null+ ? (typeof m.number === 'number' ? `#${m.number}` : String(m.number))+ : (m?.slug || 'an existing issue')+ const score = typeof m?.score === 'number' ? m.score.toFixed(2) : '?'+ console.log(`♻️ Layered Intelligence: ${app.name} proposal "${proposal.slug}" is a near-duplicate of ${ref} (score ${score}) — suppressed`)+ return true+}++/** The user-facing ref for a filed proposal (Jira key, else `#<number>`, else null). */+function filedRef(key, number) {+ return key || (number != null ? `#${number}` : null)+}++/**+ * Persist per-app run bookkeeping — run cadence AND the last run's OUTCOME.+ * Re-reads the current stored config and merges only these fields so a mid-run+ * user config edit isn't clobbered.+ */+async function recordRun(app, outcome = {}) {+ const patch = {+ lastRunAt: new Date().toISOString(),+ lastRunAction: outcome.action ?? null,+ lastRunReason: outcome.reason ?? null,+ lastRunRef: filedRef(outcome.filedKey, outcome.filedNumber)+ }+ await updateAppLayeredIntelligence(app.id, patch).catch((err) => {+ console.error(`❌ Layered Intelligence: failed to record run for ${app.id}: ${err.message}`)+ })+}++/** Default hand-off enqueue: an approval-gated internal CoS task for a coding agent. */+async function defaultEnqueueHandoff(taskData) {+ const { addTask } = await import('../cos.js')+ return addTask(taskData, 'internal')+}++/**+ * Post-agent DECIDE + ACT hook. Validates the agent's `.agent-done` payload+ * (the reasoner JSON), scope-gates, dedups against a FRESH tracker read, files+ * exactly one issue, applies a pause, optionally hands the proposal to a coding+ * agent, and records the run. Every terminal path records an outcome so the UI's+ * last-run status matches what happened. Injectable deps for tests.+ */+export async function processTaskOutput({ appId, success, payload, agentId } = {}, deps = {}) {+ const { enqueueHandoff = defaultEnqueueHandoff, now = Date.now() } = deps+ if (!appId) return { action: 'no-op', reason: 'no-app' }+ const app = await getAppById(appId).catch(() => null)+ if (!app) return { action: 'no-op', reason: 'app-not-found' }++ const settle = async (outcome) => {+ await recordRun(app, outcome)+ return { app: app.id, ...outcome }+ }++ // A failed/aborted agent produced no trustworthy reasoning — record and stop.+ if (success === false) return settle({ action: 'no-op', reason: 'agent-failed' })++ const ctx = await resolveLiContext(app)+ const { isPortos, config, filer, forgeCli, cwd, jira } = ctx++ // The payload IS the reasoner's JSON object (parsed from the sentinel). A null/+ // malformed payload is the "returned nothing usable" case.+ const { proposal, pause } = validateReasonerResponse(+ payload && typeof payload === 'object' ? payload : null+ )++ // Re-read issues NOW (not at gather time) so dedup sees the freshest tracker+ // state — the agent may have run for minutes.+ const { existingIssues, trackerReadFailed } = await readIssues({ filer, forgeCli, cwd, jira, config })++ let filedNumber = null+ let filedKey = null+ let filedAction = 'no-op'+ let reason = payload == null ? 'unparseable-response' : 'no-proposal'+ let handedOff = false++ if (proposal) {+ const scopeOk = isScopeAllowed({ scope: proposal.scope, allowedScopes: config.allowedScopes, isPortos })+ if (!scopeOk) {+ console.log(`🚫 Layered Intelligence: ${app.name} proposal scope "${proposal.scope}" not allowed — suppressed`)+ reason = 'scope-suppressed'+ } else if (trackerReadFailed) {+ console.warn(`⚠️ Layered Intelligence: ${app.name} tracker read failed — suppressing proposal to avoid a blind duplicate`)+ filedAction = 'tracker-read-failed'+ reason = 'tracker-read-failed'+ } else if (isProposalDuplicate({ slug: proposal.slug, existingIssues, now })) {+ console.log(`♻️ Layered Intelligence: ${app.name} proposal "${proposal.slug}" is a duplicate — suppressed`)+ filedAction = 'duplicate'+ reason = 'duplicate'+ } else if (await isSemanticDuplicate(app, proposal, existingIssues, now)) {+ filedAction = 'semantic-duplicate'+ reason = 'semantic-duplicate'+ } else {+ const filed = await fileProposal({ filer, forgeCli, cwd, app, proposal, jira })+ if (filed.success) {+ filedNumber = filed.number ?? null+ filedKey = filed.key ?? null+ filedAction = 'filed'+ reason = null+ const ref = filedRef(filedKey, filedNumber) ?? ''+ console.log(`📌 Layered Intelligence: ${app.name} filed "${proposal.title}" [${proposal.slug}]${ref ? ` (${ref})` : ''}`)+ const issueRef = filedKey || filedNumber+ if (isHandoffEligible({ proposal, config, filed: issueRef })) {+ const task = await enqueueHandoff(buildHandoffTask({ app, proposal, issueRef }))+ .catch((err) => { console.error(`❌ Layered Intelligence: ${app.name} hand-off enqueue failed: ${err.message}`); return null })+ if (task && !task.duplicate) {+ handedOff = true+ console.log(`🤝 Layered Intelligence: ${app.name} handed off ${ref} to a coding agent (task ${task.id})`)+ }+ }+ } else {+ console.error(`❌ Layered Intelligence: ${app.name} failed to file proposal: ${filed.error || 'unknown'}`)+ reason = 'file-failed'+ }+ }+ }++ // Pause (forge + jira; resolve blockOnIssue after filing).+ let paused = false+ if (pause && filer === 'forge' && forgeCli) {+ const number = resolveBlockOnIssue(pause, filedNumber)+ if (Number.isInteger(number)) {+ const res = await applyBlockingLabel({ cli: forgeCli, cwd, number })+ paused = res.success+ if (paused) console.log(`⏸️ Layered Intelligence: ${app.name} paused on #${number} — ${pause.reason}`)+ }+ } else if (pause && filer === 'jira' && jira) {+ const key = resolveJiraBlockKey(pause, filedKey, jira.projectKey)+ if (key) {+ const res = await applyJiraBlockingLabel({ instanceId: jira.instanceId, key })+ paused = res.success+ if (paused) console.log(`⏸️ Layered Intelligence: ${app.name} paused on ${key} — ${pause.reason}`)+ }+ }++ return settle({ action: filedAction, reason, filedNumber, filedKey, paused, handedOff })+}diff --git a/server/services/autonomousJobs/layeredIntelligenceHooks.test.js b/server/services/autonomousJobs/layeredIntelligenceHooks.test.jsnew file mode 100644index 0000000000..3c60bc4436--- /dev/null+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.test.js@@ -0,0 +1,156 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// Mock the heavy dependency graph so the hooks can be driven without a live LLM,+// forge, or app store. Each helper is a controllable spy set up per-test.+vi.mock('../apps.js', () => ({+ PORTOS_APP_ID: 'portos-default',+ getAppById: vi.fn(),+ updateAppLayeredIntelligence: vi.fn().mockResolvedValue(undefined)+}));++vi.mock('../../lib/workTracker.js', () => ({+ resolveAppWorkTracker: vi.fn().mockResolvedValue({ resolved: 'github', forge: 'gh' })+}));++vi.mock('../../lib/fileUtils.js', () => ({+ tryReadFile: vi.fn().mockResolvedValue(null)+}));++vi.mock('../layeredIntelligence.js', () => ({+ getEffectiveConfig: vi.fn(() => ({ providerId: 'ollama', model: 'qwen', allowedScopes: ['app-improvement'], sources: {} })),+ buildPrompt: vi.fn(() => 'REASONING PROMPT'),+ gatherSources: vi.fn().mockResolvedValue({ goals: 'be great' }),+ listForgeIssues: vi.fn().mockResolvedValue({ ok: true, issues: [] }),+ listBlockingIssues: vi.fn().mockResolvedValue({ ok: true, issues: [] }),+ isAppParked: vi.fn(() => false),+ validateReasonerResponse: vi.fn(() => ({ proposal: null, pause: null })),+ isScopeAllowed: vi.fn(() => true),+ isProposalDuplicate: vi.fn(() => false),+ checkSemanticDuplicate: vi.fn().mockResolvedValue({ available: false, duplicate: false }),+ isHandoffEligible: vi.fn(() => false),+ buildHandoffTask: vi.fn(() => ({ description: 'handoff' })),+ filerForTracker: vi.fn((resolved) => (resolved === 'github' || resolved === 'gitlab') ? 'forge' : (resolved === 'jira' ? 'jira' : 'plan')),+ trackerSupportsPause: vi.fn((resolved) => resolved !== 'plan'),+ resolveBlockOnIssue: vi.fn(() => null),+ fileProposalToForge: vi.fn().mockResolvedValue({ success: true, number: 77 }),+ applyBlockingLabel: vi.fn().mockResolvedValue({ success: true }),+ appendProposalToPlan: vi.fn().mockResolvedValue({ success: true }),+ extractPlanSlugs: vi.fn(() => []),+ listJiraIssues: vi.fn().mockResolvedValue({ ok: true, issues: [] }),+ listJiraBlockingIssues: vi.fn().mockResolvedValue({ ok: true, issues: [] }),+ fileProposalToJira: vi.fn().mockResolvedValue({ success: true, key: 'PROJ-1' }),+ resolveJiraBlockKey: vi.fn(() => null),+ applyJiraBlockingLabel: vi.fn().mockResolvedValue({ success: true })+}));++import { buildTaskInput, processTaskOutput } from './layeredIntelligenceHooks.js';+import * as li from '../layeredIntelligence.js';+import * as apps from '../apps.js';+import { resolveAppWorkTracker } from '../../lib/workTracker.js';++const APP = { id: 'app-1', name: 'App One', repoPath: '/repo', taskTypeOverrides: {} };++beforeEach(() => {+ vi.clearAllMocks();+ resolveAppWorkTracker.mockResolvedValue({ resolved: 'github', forge: 'gh' });+ li.getEffectiveConfig.mockReturnValue({ providerId: 'ollama', model: 'qwen', allowedScopes: ['app-improvement'], sources: {} });+ li.filerForTracker.mockImplementation((r) => (r === 'github' || r === 'gitlab') ? 'forge' : (r === 'jira' ? 'jira' : 'plan'));+ li.trackerSupportsPause.mockImplementation((r) => r !== 'plan');+ li.listBlockingIssues.mockResolvedValue({ ok: true, issues: [] });+ li.listForgeIssues.mockResolvedValue({ ok: true, issues: [] });+ li.isAppParked.mockReturnValue(false);+});++describe('buildTaskInput', () => {+ it('skips with no-app when app is missing', async () => {+ expect(await buildTaskInput({})).toEqual({ skip: { reason: 'no-app' } });+ });++ it('skips a parked app before building a prompt', async () => {+ li.listBlockingIssues.mockResolvedValue({ ok: true, issues: [{ number: 5 }] });+ li.isAppParked.mockReturnValue(true);+ const res = await buildTaskInput({ app: APP });+ expect(res).toEqual({ skip: { reason: 'blocking-open' } });+ expect(li.gatherSources).not.toHaveBeenCalled();+ });++ it('skips when a failed blocking read could resume parked work', async () => {+ li.listBlockingIssues.mockResolvedValue({ ok: false, issues: [] });+ expect(await buildTaskInput({ app: APP })).toEqual({ skip: { reason: 'blocking-read-failed' } });+ });++ it('skips a jira-tracked app with no usable jira config', async () => {+ resolveAppWorkTracker.mockResolvedValue({ resolved: 'jira', forge: null });+ const res = await buildTaskInput({ app: { ...APP, jira: { enabled: false } } });+ expect(res).toEqual({ skip: { reason: 'jira-not-configured' } });+ });++ it('returns the reasoning prompt + the app-chosen provider/model on the happy path', async () => {+ const res = await buildTaskInput({ app: APP });+ expect(res.skip).toBeUndefined();+ expect(res.prompt).toContain('REASONING PROMPT');+ // The completion contract instructing the agent to write .agent-done is appended.+ expect(res.prompt).toContain('.agent-done');+ expect(res.providerId).toBe('ollama');+ expect(res.model).toBe('qwen');+ });+});++describe('processTaskOutput', () => {+ beforeEach(() => {+ apps.getAppById.mockResolvedValue(APP);+ });++ it('records a no-op when the agent failed', async () => {+ const out = await processTaskOutput({ appId: 'app-1', success: false, payload: { proposal: {} } });+ expect(out).toMatchObject({ action: 'no-op', reason: 'agent-failed' });+ expect(apps.updateAppLayeredIntelligence).toHaveBeenCalledWith('app-1', expect.objectContaining({ lastRunAction: 'no-op' }));+ expect(li.fileProposalToForge).not.toHaveBeenCalled();+ });++ it('records unparseable-response when the payload is null', async () => {+ li.validateReasonerResponse.mockReturnValue({ proposal: null, pause: null });+ const out = await processTaskOutput({ appId: 'app-1', success: true, payload: null });+ expect(out).toMatchObject({ action: 'no-op', reason: 'unparseable-response' });+ });++ it('files a fresh, in-scope proposal and records the ref', async () => {+ li.validateReasonerResponse.mockReturnValue({+ proposal: { scope: 'app-improvement', slug: 'add-telemetry', title: 'Add telemetry', body: 'do it' },+ pause: null+ });+ li.fileProposalToForge.mockResolvedValue({ success: true, number: 77 });+ const out = await processTaskOutput({ appId: 'app-1', success: true, payload: { proposal: {} } });+ expect(li.fileProposalToForge).toHaveBeenCalled();+ expect(out).toMatchObject({ action: 'filed', filedNumber: 77, reason: null });+ expect(apps.updateAppLayeredIntelligence).toHaveBeenCalledWith('app-1', expect.objectContaining({ lastRunAction: 'filed', lastRunRef: '#77' }));+ });++ it('suppresses an exact-duplicate proposal without filing', async () => {+ li.validateReasonerResponse.mockReturnValue({+ proposal: { scope: 'app-improvement', slug: 'dup', title: 'Dup', body: 'x' },+ pause: null+ });+ li.isProposalDuplicate.mockReturnValue(true);+ const out = await processTaskOutput({ appId: 'app-1', success: true, payload: { proposal: {} } });+ expect(li.fileProposalToForge).not.toHaveBeenCalled();+ expect(out).toMatchObject({ action: 'duplicate', reason: 'duplicate' });+ });++ it('suppresses filing when the tracker read failed (avoids a blind duplicate)', async () => {+ li.validateReasonerResponse.mockReturnValue({+ proposal: { scope: 'app-improvement', slug: 's', title: 'T', body: 'b' },+ pause: null+ });+ li.listForgeIssues.mockResolvedValue({ ok: false, issues: [] });+ const out = await processTaskOutput({ appId: 'app-1', success: true, payload: { proposal: {} } });+ expect(li.fileProposalToForge).not.toHaveBeenCalled();+ expect(out).toMatchObject({ action: 'tracker-read-failed', reason: 'tracker-read-failed' });+ });++ it('no-ops when the app cannot be loaded', async () => {+ apps.getAppById.mockResolvedValue(null);+ const out = await processTaskOutput({ appId: 'missing', success: true, payload: {} });+ expect(out).toEqual({ action: 'no-op', reason: 'app-not-found' });+ });+});diff --git a/server/services/autonomousJobs/scriptHandlers.js b/server/services/autonomousJobs/scriptHandlers.jsindex 4e53d662ae..08ae5db332 100644--- a/server/services/autonomousJobs/scriptHandlers.js+++ b/server/services/autonomousJobs/scriptHandlers.js@@ -140,9 +140,10 @@ const SCRIPT_HANDLERS = {'moltworld-exploration': runMoltworldExploration,'agent-data-cleanup': agentDataCleanup,'goal-check-in': runGoalCheckIn- // 'layered-intelligence' retired (#2322): LI is now a per-app HANDLER-BACKED- // scheduled task, not a global autonomous-job sweep. See taskSchedule.js- // HANDLER_BACKED_TASK_TYPES + cosTaskGenerator.runHandlerBackedTaskForApp.+ // 'layered-intelligence' retired here (#2322): LI is now a per-app scheduled+ // task, not a global autonomous-job sweep. It runs as a normal reasoning agent+ // with programmatic-I/O hooks — see taskTypeHooks.js ++ // autonomousJobs/layeredIntelligenceHooks.js.}export { runMoltworldExploration, agentDataCleanup, SCRIPT_HANDLERS }diff --git a/server/services/cos.js b/server/services/cos.jsindex ef6f676832..6420fa3297 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -93,9 +93,7 @@ import {countRunningAgentsByProject,isWithinProjectLimit,checkStagePrecondition,- applyAppWorktreeDefault,- runHandlerBackedTaskForApp,- emitHandlerBackedOnDemand+ applyAppWorktreeDefault} from './cosTaskGenerator.js';export { evaluateTasks, checkStagePrecondition, applyAppWorktreeDefault };@@ -765,14 +763,6 @@ async function dequeueNextTask() {await taskScheduleMod.clearOnDemandRequest(request.id);- // Handler-backed tasks (layered-intelligence) are inherently per-app — a- // global (no-app) request can't dispatch one, and must NEVER fall through to- // the self-improvement agent path below.- if (taskScheduleMod.HANDLER_BACKED_TASK_TYPES.has(request.taskType) && !targetApp) {- emitLog('info', `On-demand ${request.taskType} skipped — handler-backed tasks require an app`, { requestId: request.id });- continue;- }-if (targetApp) {emitLog('info', `Processing on-demand improvement: ${request.taskType} for ${targetApp.name}`, { requestId: request.id, appId: targetApp.id });// A user-initiated "Run" must re-check live state, never honor a stale@@ -788,15 +778,6 @@ async function dequeueNextTask() {reviewStartedApps.add(targetApp.id);}await taskScheduleMod.recordExecution(`task:${request.taskType}`, targetApp.id);- // HANDLER-BACKED types (layered-intelligence) run a deterministic handler- // for this app instead of generating an agent task. Emit the same ran/- // no-work feedback and move on — no agent enqueue.- if (taskScheduleMod.HANDLER_BACKED_TASK_TYPES.has(request.taskType)) {- const outcome = await runHandlerBackedTaskForApp(request.taskType, targetApp)- .catch((err) => { emitLog('warn', `Handler-backed ${request.taskType} failed for ${targetApp.name}: ${err.message}`, { appId: targetApp.id }); return { action: 'error', error: err.message }; });- await emitHandlerBackedOnDemand({ outcome, request, targetApp });- continue;- }task = await generateManagedAppImprovementTaskForType(request.taskType, targetApp, state, { skipPreconditions: true });if (task) {await bindAppReviewAgent(targetApp.id, `on-demand-${Date.now()}`);diff --git a/server/services/cos.test.js b/server/services/cos.test.jsindex 35de19e0a9..c872bd3e7a 100644--- a/server/services/cos.test.js+++ b/server/services/cos.test.js@@ -846,35 +846,19 @@ describe('cos.js source — priority + capacity invariants', () => {}});- it('queueEligibleImprovementTasks runs HANDLER-BACKED types via the handler, never the agent path', () => {- // #2322: layered-intelligence is a deterministic handler-backed task. When- // getNextTaskType picks a handler-backed type for an app, the queue path MUST- // dispatch the in-process handler and `continue` — BEFORE (and instead of)- // calling generateManagedAppImprovementTaskForType. A bug here can only fail- // to run the handler; it can never spawn a runaway coding agent.- const fnStart = GEN_SRC.indexOf('async function queueEligibleImprovementTasks');- const fnBody = extractFnBody(GEN_SRC, fnStart);-- // Imports HANDLER_BACKED_TASK_TYPES from the schedule and branches on it.- expect(fnBody).toMatch(/HANDLER_BACKED_TASK_TYPES/);- expect(fnBody).toMatch(/HANDLER_BACKED_TASK_TYPES\.has\(nextType\)/);-- // The handler-backed branch dispatches + continues BEFORE the agent-spawn call.- const handlerIdx = fnBody.indexOf('HANDLER_BACKED_TASK_TYPES.has(nextType)');- const dispatchIdx = fnBody.indexOf('dispatchHandlerBackedTask(');- const generatorIdx = fnBody.indexOf('generateManagedAppImprovementTaskForType(');- expect(handlerIdx).toBeGreaterThan(-1);- expect(dispatchIdx).toBeGreaterThan(handlerIdx);- expect(dispatchIdx).toBeLessThan(generatorIdx); // handler dispatched before the agent path-- // The shared runner lazily imports the LI handler (no static import cycle).- expect(GEN_SRC).toMatch(/export async function runHandlerBackedTaskForApp/);- expect(GEN_SRC).toMatch(/import\(['"]\.\/autonomousJobs\/layeredIntelligenceHandler\.js['"]\)/);- // And it never routes a handler-backed type through the agent generator.- const runnerStart = GEN_SRC.indexOf('export async function runHandlerBackedTaskForApp');- const runnerBody = extractFnBody(GEN_SRC, runnerStart);- expect(runnerBody).not.toMatch(/generateManagedAppImprovementTaskForType/);- expect(runnerBody).toMatch(/runLayeredIntelligenceForApp/);+ it('has NO handler-backed dispatch — every task type routes through the agent path', () => {+ // #2322 follow-up: layered-intelligence migrated OFF the handler-backed path+ // onto a normal agent task with programmatic-I/O hooks (taskTypeHooks.js). The+ // queue path no longer special-cases any type: there is no in-process handler+ // dispatch that bypasses the agent-spawn path, so a scheduled reasoning task is+ // a visible, TUI-capable agent like everything else.+ expect(GEN_SRC).not.toMatch(/dispatchHandlerBackedTask/);+ expect(GEN_SRC).not.toMatch(/runHandlerBackedTaskForApp/);+ expect(GEN_SRC).not.toMatch(/layeredIntelligenceHandler\.js/);++ // The generator runs a task type's optional buildTaskInput hook before dispatch+ // (the pre-agent programmatic slot LI's gather layer fills).+ expect(GEN_SRC).toMatch(/getTaskInputHook/);});it('queueEligibleImprovementTasks routes through generateManagedAppImprovementTaskForType', () => {diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex 942b28151a..fc53ca4325 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -533,7 +533,6 @@ async function spawnPriority0OnDemand(ctx) {const { state, availableSlots, tasksToSpawn, canSpawnTask, trackSpawn } = ctx;const taskSchedule = await import('./taskSchedule.js');- const { HANDLER_BACKED_TASK_TYPES } = taskSchedule;const liveSchedule = await taskSchedule.loadSchedule();const onDemandRequests = Array.isArray(liveSchedule?.onDemandRequests) ? liveSchedule.onDemandRequests : [];@@ -573,14 +572,6 @@ async function spawnPriority0OnDemand(ctx) {await taskSchedule.clearOnDemandRequest(request.id);- // Handler-backed tasks (layered-intelligence) are inherently per-app — a- // global (no-app) request can't dispatch one, and must NEVER fall through- // to the self-improvement agent path below.- if (HANDLER_BACKED_TASK_TYPES.has(request.taskType) && !targetApp) {- emitLog('info', `On-demand ${request.taskType} skipped — handler-backed tasks require an app`, { requestId: request.id });- continue;- }-if (targetApp) {emitLog('info', `Processing on-demand improvement: ${request.taskType} for ${targetApp.name}`, { requestId: request.id, appId: targetApp.id });// A user-initiated "Run" must re-check live state — reset any park + the@@ -595,15 +586,6 @@ async function spawnPriority0OnDemand(ctx) {reviewStartedApps.add(targetApp.id);}await taskSchedule.recordExecution(`task:${request.taskType}`, targetApp.id);- // HANDLER-BACKED types run the deterministic handler for this app instead- // of generating an agent task. Emit the same ran/no-work feedback, then- // move to the next request (never enqueue an agent task).- if (HANDLER_BACKED_TASK_TYPES.has(request.taskType)) {- const outcome = await runHandlerBackedTaskForApp(request.taskType, targetApp)- .catch((err) => { console.error(`❌ Handler-backed ${request.taskType} failed for ${targetApp.name}: ${err.message}`); return { action: 'error', error: err.message }; });- await emitHandlerBackedOnDemand({ outcome, request, targetApp });- continue;- }task = await generateManagedAppImprovementTaskForType(request.taskType, targetApp, state, { skipPreconditions: true });if (task) {await bindAppReviewAgent(targetApp.id, `on-demand-${Date.now()}`);@@ -1110,7 +1092,7 @@ export async function generateIdleReviewTask(state) {* Tasks are queued to COS-TASKS.md and will be picked up in Priority 2*/export async function queueEligibleImprovementTasks(state, cosTaskData, { ignoreTaskId = null } = {}) {- const { getNextTaskType, recordExecution, HANDLER_BACKED_TASK_TYPES } = await import('./taskSchedule.js');+ const { getNextTaskType, recordExecution } = await import('./taskSchedule.js');if (!isImprovementEnabled(state)) return;@@ -1211,16 +1193,6 @@ export async function queueEligibleImprovementTasks(state, cosTaskData, { ignoreif (!nextTypeResult) continue;const nextType = nextTypeResult.taskType;- // HANDLER-BACKED types (e.g. layered-intelligence) run a deterministic- // in-process handler for this app instead of spawning a coding agent. Fire- // it and-forget (guarded per-app so the next tick can't double-run it),- // record the execution on completion, and move on — NEVER touch the- // agent-spawn path below. A bug here can only fail to run the handler.- if (HANDLER_BACKED_TASK_TYPES.has(nextType)) {- dispatchHandlerBackedTask(nextType, app, recordExecution);- continue;- }-const taskKey = `app:${app.id}:${nextType}`;if (existingTaskTypes.has(taskKey)) {emitLog('debug', `Improvement task ${nextType} for ${app.name} already queued`);@@ -1547,103 +1519,6 @@ async function generateManagedAppImprovementTask(app, state) {* user-initiated on-demand path, so the client can toast it without* background-park noise.*/-// Per-app in-flight guard for handler-backed tasks so a fire-and-forget run-// started by one scheduler tick (or an on-demand drain) can't be double-started-// by the next tick for the same app before it settles. Keyed by app id.-const handlerBackedInFlight = new Set();--/** True when a handler-backed task is currently running for this app. */-export function isHandlerBackedInFlight(appId) {- return handlerBackedInFlight.has(appId);-}--/**- * Run a HANDLER-BACKED (deterministic, no-agent) scheduled task for ONE app,- * dispatching to the in-process handler for its type instead of spawning a coding- * agent (see taskSchedule.HANDLER_BACKED_TASK_TYPES). Guarded by a module-level- * per-app in-flight Set. Returns the handler's outcome, `{ action: 'in-flight' }`- * when a prior run for this app is still active, or `{ action: 'no-handler' }`- * for an unrecognized type. The handler is lazily imported to avoid a static- * import cycle (the handler pulls in apps.js / providers). Callers that run this- * outside the request lifecycle MUST wrap it (the `finally` clears the guard even- * if the handler throws, but the throw still propagates to the caller's boundary).- */-export async function runHandlerBackedTaskForApp(taskType, app) {- if (handlerBackedInFlight.has(app.id)) return { app: app.id, action: 'in-flight' };- handlerBackedInFlight.add(app.id);- try {- if (taskType === 'layered-intelligence') {- const { runLayeredIntelligenceForApp } = await import('./autonomousJobs/layeredIntelligenceHandler.js');- return await runLayeredIntelligenceForApp(app);- }- return { app: app.id, action: 'no-handler' };- } finally {- handlerBackedInFlight.delete(app.id);- }-}--/**- * Fire-and-forget a handler-backed task from the scheduler tick: run it, record- * the execution (so cadence advances), and log — never throwing into the tick- * loop. Skips the recordExecution when the run was a no-op because another run- * for this app was already in flight. Boundary-wrapped (runs outside the request- * lifecycle). `recordExecution` is passed in (already imported by the caller).- */-function dispatchHandlerBackedTask(taskType, app, recordExecution) {- runHandlerBackedTaskForApp(taskType, app)- .then(async (outcome) => {- if (outcome?.action === 'in-flight') return; // a prior tick is still running- await recordExecution(`task:${taskType}`, app.id);- emitLog('info', `Ran handler-backed ${taskType} for ${app.name} (${outcome?.action || 'done'})`, { appId: app.id, action: outcome?.action });- })- .catch((err) => {- console.error(`❌ Handler-backed ${taskType} failed for ${app.name}: ${err.message}`);- });-}--/**- * On-demand (user "Run now") feedback for a handler-backed task: it produces no- * agent task, so mirror the agent path's "ran / no work" signal. When the run- * filed an issue we toast a success; otherwise we reuse the on-demand-empty- * channel with outcome 'idle' (nothing to do right now). Boundary-safe.- */-export async function emitHandlerBackedOnDemand({ outcome, request, targetApp }) {- const appName = targetApp?.name || null;- const appId = targetApp?.id || null;- const filed = outcome?.action === 'filed';- if (filed) {- cosEvents.emit('schedule:on-demand-ran', {- requestId: request.id,- taskType: request.taskType,- appId,- appName,- action: outcome.action,- filedNumber: outcome.filedNumber ?? null,- filedKey: outcome.filedKey ?? null- });- return;- }- // Non-filed: forward the handler's ACTUAL action + reason so the client can- // explain WHY nothing was filed (llm-error, unparseable-response, duplicate,- // parked, jira-not-configured, …) instead of a blanket "nothing to do". A- // plain `no-op`/`no-proposal` is genuinely idle; everything else is a- // handler-issue the user should see. `error` is the thrown-run shape the- // caller synthesizes when the handler itself rejects.- const action = outcome?.action || 'no-op';- const reason = outcome?.reason ?? outcome?.error ?? null;- const isIdle = action === 'no-op' && (reason == null || reason === 'no-proposal');- cosEvents.emit('schedule:on-demand-empty', {- requestId: request.id,- taskType: request.taskType,- appId,- appName,- outcome: isIdle ? 'idle' : 'handler-issue',- handlerAction: action,- handlerReason: reason,- blocking: outcome?.blocking ?? null- });-}-export async function emitOnDemandEmpty({ taskScheduleMod, request, targetApp, taskConfig }) {const appId = targetApp?.id || null;const parkInfo = await taskScheduleMod.getPerpetualParkInfo(request.taskType, appId).catch(() => null);@@ -1715,6 +1590,41 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, stinitializePipelineMetadata(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 };+ }+ }+// 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@@ -1944,9 +1854,14 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, st// default.)const promptKeyForBody = (taskType === 'claim-work' && !interval.prompt) ? promptTaskType : taskType;- const promptTemplate = metadata.pipeline?.stages- ? await getStagePrompt(taskType, 0)- : await getTaskPrompt(promptKeyForBody);+ // A buildTaskInput hook that returned a fully-rendered prompt wins over the+ // template path — the hook owns its prompt (LI has no DEFAULT_TASK_PROMPTS+ // entry). The token-replacement chain below is a no-op on it (no {tokens}).+ const promptTemplate = hookPrompt+ ? hookPrompt+ : (metadata.pipeline?.stages+ ? await getStagePrompt(taskType, 0)+ : await getTaskPrompt(promptKeyForBody));// reference-watch: dynamically inject {referenceData} — a Markdown chunk// describing each ref configured on the app + commits since lastReviewedSha.@@ -2118,6 +2033,12 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, stmetadata.model = interval.model;}+ // A buildTaskInput hook's per-app provider/model wins over the global interval+ // pin above (per-app is the more specific choice). Applied last so a global+ // schedule provider can't clobber the app's selection.+ if (hookOverride.providerId) { metadata.provider = hookOverride.providerId; metadata.providerId = hookOverride.providerId; }+ if (hookOverride.model) { metadata.model = hookOverride.model; }+const approval = await resolveConfidenceApproval(state, `app-improve:${taskType}`, `Task app-improve:${taskType} for ${app.name}`);// All gates passed — record the rotation-pointer advance + emit thediff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.jsindex b99e58a5bc..e1348a0060 100644--- a/server/services/cosTaskGenerator.test.js+++ b/server/services/cosTaskGenerator.test.js@@ -15,7 +15,7 @@ import { describe, it, expect } from 'vitest';import { readFileSync } from 'fs';import { fileURLToPath } from 'url';import { dirname, join } from 'path';-import { selectDryRunAutoApproved, exceedsMaxSpawns, resolveIssueAuthorFilterBlock, resolveSwarmBlock, isCooldownExemptTask, emitHandlerBackedOnDemand } from './cosTaskGenerator.js';+import { selectDryRunAutoApproved, exceedsMaxSpawns, resolveIssueAuthorFilterBlock, resolveSwarmBlock, isCooldownExemptTask } from './cosTaskGenerator.js';import { cosEvents } from './cosEvents.js';import { MAX_TOTAL_SPAWNS } from '../lib/validation.js';@@ -469,54 +469,9 @@ describe('selectDryRunAutoApproved', () => {});});-// emitHandlerBackedOnDemand is the on-demand feedback bridge for a handler-backed-// task (Layered Intelligence): it files a tracker issue rather than spawning a-// visible agent, so the emitted event is the user's only clue. Before the fix it-// collapsed every non-filed outcome to a bland `outcome:'idle'` and dropped the-// reason; these pin that the real action + reason now reach the client.-describe('emitHandlerBackedOnDemand', () => {- const capture = (event) => {- const seen = [];- const handler = (d) => seen.push(d);- cosEvents.on(event, handler);- return { seen, done: () => cosEvents.off(event, handler) };- };- const request = { id: 'req-1', taskType: 'layered-intelligence' };- const targetApp = { id: 'app-1', name: 'App One' };-- it('emits on-demand-ran with the filed ref on a filed outcome', async () => {- const cap = capture('schedule:on-demand-ran');- await emitHandlerBackedOnDemand({ outcome: { action: 'filed', filedNumber: 42 }, request, targetApp });- cap.done();- expect(cap.seen).toHaveLength(1);- expect(cap.seen[0]).toMatchObject({ action: 'filed', filedNumber: 42, appName: 'App One' });- });-- it('classifies a genuine no-proposal run as idle', async () => {- const cap = capture('schedule:on-demand-empty');- await emitHandlerBackedOnDemand({ outcome: { action: 'no-op', reason: 'no-proposal' }, request, targetApp });- cap.done();- expect(cap.seen[0]).toMatchObject({ outcome: 'idle', handlerAction: 'no-op', handlerReason: 'no-proposal' });- });-- it('forwards the reason for an unparseable-response run as a handler-issue', async () => {- const cap = capture('schedule:on-demand-empty');- await emitHandlerBackedOnDemand({ outcome: { action: 'no-op', reason: 'unparseable-response' }, request, targetApp });- cap.done();- expect(cap.seen[0]).toMatchObject({ outcome: 'handler-issue', handlerAction: 'no-op', handlerReason: 'unparseable-response' });- });-- it('surfaces a park with its blocking count', async () => {- const cap = capture('schedule:on-demand-empty');- await emitHandlerBackedOnDemand({ outcome: { action: 'parked', reason: 'blocking-open', blocking: 3 }, request, targetApp });- cap.done();- expect(cap.seen[0]).toMatchObject({ outcome: 'handler-issue', handlerAction: 'parked', blocking: 3 });- });-- it('maps a thrown-run { error } into a handler-issue reason', async () => {- const cap = capture('schedule:on-demand-empty');- await emitHandlerBackedOnDemand({ outcome: { action: 'error', error: 'store down' }, request, targetApp });- cap.done();- expect(cap.seen[0]).toMatchObject({ outcome: 'handler-issue', handlerAction: 'error', handlerReason: 'store down' });- });-});+// Layered Intelligence's on-demand feedback bridge (emitHandlerBackedOnDemand) was+// removed when LI migrated off the handler-backed path onto a normal agent task+// (see taskTypeHooks.js + layeredIntelligenceHooks.js). A "Run now" now generates a+// visible agent task (or the shared emitOnDemandEmpty no-dispatch feedback when the+// buildTaskInput hook skips), and the filing outcome surfaces via the agent + the+// app's lastRun bookkeeping — so the bespoke bridge is no longer needed.diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.jsindex 24d56472c4..1489b1ae13 100644--- a/server/services/taskSchedule.js+++ b/server/services/taskSchedule.js@@ -168,25 +168,21 @@ export const SELF_IMPROVEMENT_TASK_TYPES = [// PR. No-ops on any repo lacking that catalog file, so enabling it on a// non-PortOS app does nothing. See DEFAULT_TASK_PROMPTS['refresh-local-llm-catalog'].'refresh-local-llm-catalog',- // layered-intelligence is HANDLER-BACKED (deterministic, no coding agent): on- // each per-app fire it reads that app's goals + telemetry, asks a reasoning- // model for the single most-valuable improvement, and files ONE deduplicated- // tracker issue — the model never writes code. Unlike every other type here it- // does NOT spawn an agent (see HANDLER_BACKED_TASK_TYPES + the seam in- // cosTaskGenerator.queueEligibleImprovementTasks). Scheduling (enabled/interval/- // provider/model) lives in the per-app taskTypeOverrides; behavior (sources/- // scopes/rules/handoff) stays in app.layeredIntelligence. Has NO DEFAULT_TASK_PROMPTS- // entry — the prompt is built deterministically by the handler.+ // layered-intelligence is a PROGRAMMATIC-I/O task: it spawns a NORMAL reasoning+ // agent (visible in the CoS queue + Active Agents, TUI-attachable) with two+ // deterministic hooks around it — buildTaskInput gathers the app's goals ++ // telemetry + open issues and builds the reasoning prompt; processTaskOutput+ // validates the agent's `.agent-done` payload, dedups, and files ONE tracker+ // issue. The agent runs in a THROWAWAY worktree (discardWorktree) that is never+ // committed/merged, so the reasoner still can't write code — the structured+ // payload is its only channel out. Scheduling (enabled/interval/provider/model)+ // lives in the per-app taskTypeOverrides; behavior (sources/scopes/rules/handoff)+ // stays in app.layeredIntelligence. Has NO DEFAULT_TASK_PROMPTS entry — the+ // buildTaskInput hook renders the prompt. See taskTypeHooks.js ++ // autonomousJobs/layeredIntelligenceHooks.js.'layered-intelligence'];-// Task types whose scheduled fire runs a deterministic in-process handler instead-// of spawning a coding agent. The scheduler tick + on-demand drain detect these-// and dispatch the handler directly (never generateManagedAppImprovementTaskForType).-// A bug in this path can only fail to run the handler — it can never spawn a-// runaway agent. See server/services/cosTaskGenerator.js#runHandlerBackedTaskForApp.-export const HANDLER_BACKED_TASK_TYPES = new Set(['layered-intelligence']);-// Shared config for code-reviewer-a and code-reviewer-b (two instances for independent provider/model configuration)const CODE_REVIEWER_INTERVAL = { type: INTERVAL_TYPES.WEEKLY, enabled: false, weekdaysOnly: true, providerId: null, model: null, prompt: null, taskMetadata: { useWorktree: true, openPR: true, simplify: true, pipeline: { stages: [{ name: 'Codebase Review', promptKey: 'code-reviewer-review', readOnly: true, providerId: null, model: null, precondition: { fileNotExists: 'REVIEW.md' } }, { name: 'Triage & Implement', promptKey: 'code-reviewer-implement', readOnly: false, providerId: null, model: null, precondition: { fileExists: 'REVIEW.md' } }] } } };@@ -308,12 +304,16 @@ export const DEFAULT_TASK_INTERVALS = {// a PR when the catalog is actually stale, so most runs are no-ops. Off by// default; the user enables it on the PortOS app.'refresh-local-llm-catalog': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { useWorktree: true, openPR: true, simplify: true } },- // layered-intelligence is handler-backed (deterministic, no agent). Daily by- // default; per-app scheduling (enabled/interval/provider/model) is set in the+ // layered-intelligence is a programmatic-I/O task (agent-backed, hooked). Daily+ // by default; per-app scheduling (enabled/interval/provider/model) is set in the// Intelligence tab and stored on the app's taskTypeOverrides['layered-intelligence'].- // No `prompt` field — the handler builds its prompt itself (no DEFAULT_TASK_PROMPTS- // entry, so the prompt-version machinery in loadSchedule skips it).- 'layered-intelligence': { type: INTERVAL_TYPES.DAILY, enabled: false, providerId: null, model: null, prompt: null }+ // No `prompt` field — the buildTaskInput hook renders the prompt (no+ // DEFAULT_TASK_PROMPTS entry, so the prompt-version machinery in loadSchedule+ // skips it). taskMetadata pins the throwaway-worktree posture: the reasoning+ // agent runs in a worktree that is discarded without a commit/merge/PR+ // (discardWorktree), so it can't land code — its `.agent-done` payload is the+ // only sanctioned output (consumed by the processTaskOutput hook).+ 'layered-intelligence': { type: INTERVAL_TYPES.DAILY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { useWorktree: true, openPR: false, discardWorktree: true } }};// Agent-options that a task manages internally — UI locks the toggle, anddiff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.jsindex c9a223fed3..7ebd534b5f 100644--- a/server/services/taskSchedule.test.js+++ b/server/services/taskSchedule.test.js@@ -111,8 +111,7 @@ import {DEFAULT_TASK_INTERVALS,MANAGED_AGENT_OPTIONS,TASK_TYPE_DESCRIPTIONS,- REFERENCE_WATCH_AUDITED_VERSION,- HANDLER_BACKED_TASK_TYPES+ REFERENCE_WATCH_AUDITED_VERSION} from './taskSchedule.js'// Prompt getters moved to taskPromptService.js (issue #744 split, #1083 cycle@@ -216,18 +215,27 @@ describe('taskSchedule', () => {})})- describe('layered-intelligence (handler-backed task type)', () => {+ describe('layered-intelligence (programmatic-I/O agent task)', () => {it('is registered as a self-improvement task with a description and a daily default', () => {expect(SELF_IMPROVEMENT_TASK_TYPES).toContain('layered-intelligence');expect(TASK_TYPE_DESCRIPTIONS['layered-intelligence']).toBeTruthy();expect(DEFAULT_TASK_INTERVALS['layered-intelligence']).toMatchObject({ type: 'daily', enabled: false });});- it('is in HANDLER_BACKED_TASK_TYPES and has NO default prompt (deterministic)', () => {- expect(HANDLER_BACKED_TASK_TYPES.has('layered-intelligence')).toBe(true);+ it('has NO default prompt — the buildTaskInput hook renders it', () => {+ // LI runs as a normal reasoning agent with buildTaskInput/processTaskOutput+ // hooks (taskTypeHooks.js); the handler-backed dispatch was removed entirely.+ // The buildTaskInput hook renders the prompt, so there is no+ // DEFAULT_TASK_PROMPTS entry.expect(DEFAULT_TASK_PROMPTS['layered-intelligence']).toBeUndefined();});+ it('pins the throwaway-worktree posture so the reasoning agent can not land code', () => {+ expect(DEFAULT_TASK_INTERVALS['layered-intelligence'].taskMetadata).toMatchObject({+ useWorktree: true, openPR: false, discardWorktree: true+ });+ });+it('honors a per-app numeric intervalMs override via the CUSTOM branch', async () => {const { getAppTaskTypeInterval, getAppTaskTypeIntervalMs } = await import('./apps.js');mockSchedule({diff --git a/server/services/taskTypeHooks.js b/server/services/taskTypeHooks.jsnew file mode 100644index 0000000000..724e3c6ba6--- /dev/null+++ b/server/services/taskTypeHooks.js@@ -0,0 +1,61 @@+/**+ * Programmatic-I/O hooks per scheduled task type.+ *+ * Most scheduled task types are `prompt → agent → wait for the .agent-done+ * sentinel`. A few need PROGRAMMATIC steps around the agent. A hook module may+ * export either or both of:+ *+ * - `buildTaskInput({ app, taskType })` — runs BEFORE spawn, inside the task+ * generator. Collects data beyond the base prompt (telemetry, open issues, …)+ * and returns `{ prompt?, providerId?, model?, skip? }`:+ * • `prompt` — a fully-rendered prompt that REPLACES the template.+ * • `providerId` / `model` — pin the agent's provider/model (per-app choice).+ * • `skip: { reason }` — short-circuit: no agent is spawned.+ *+ * - `processTaskOutput({ appId, success, payload, workspacePath, agentId, task }, deps?)`+ * — runs AFTER the agent finishes, from the finalize chokepoint. `payload` is+ * the parsed `.agent-done` sentinel payload (the agent's structured output);+ * the hook does deterministic work on it (e.g. filing a tracker issue) and+ * returns an outcome. `deps` is an injectable seam for tests.+ *+ * The agent itself runs through the NORMAL path (visible in the CoS queue ++ * Active Agents, TUI-capable), so a programmatic-I/O task differs from any other+ * scheduled task only in these two slots. See+ * docs/plans/2026-07-09-programmatic-io-scheduled-tasks.md.+ *+ * Hook modules are lazy-imported (their dependency graphs are heavy) and resolved+ * by task type. `HOOK_MODULES` is the single registration point; a new+ * programmatic-I/O task type adds one entry here plus a module that exports the+ * hook(s) above. The resolvers return `null` for any unregistered type without+ * importing anything, so a normal task type pays ~zero cost.+ */++// taskType → () => import('./path/to/hookModule.js'). A module may export either+// or both hooks; a missing export means "no hook of that kind for this type".+const HOOK_MODULES = {+ 'layered-intelligence': () => import('./autonomousJobs/layeredIntelligenceHooks.js'),+};++async function loadHookModule(taskType) {+ const load = HOOK_MODULES[taskType];+ if (!load) return null;+ return load();+}++/**+ * Resolve the pre-agent input hook for a task type, or null if it has none.+ * `buildTaskInput({ app, taskType })` → `{ prompt?, providerId?, model?, skip? }`.+ */+export async function getTaskInputHook(taskType) {+ const mod = await loadHookModule(taskType);+ return mod && typeof mod.buildTaskInput === 'function' ? mod.buildTaskInput : null;+}++/**+ * Resolve the post-agent output hook for a task type, or null if it has none.+ * `processTaskOutput({ appId, success, payload, workspacePath, agentId, task })` → outcome.+ */+export async function getTaskOutputHook(taskType) {+ const mod = await loadHookModule(taskType);+ return mod && typeof mod.processTaskOutput === 'function' ? mod.processTaskOutput : null;+}diff --git a/server/services/taskTypeHooks.test.js b/server/services/taskTypeHooks.test.jsnew file mode 100644index 0000000000..9d9a6d7e94--- /dev/null+++ b/server/services/taskTypeHooks.test.js@@ -0,0 +1,18 @@+import { describe, it, expect } from 'vitest';+import { getTaskInputHook, getTaskOutputHook } from './taskTypeHooks.js';++describe('taskTypeHooks registry', () => {+ it('resolves both hooks for layered-intelligence to callables', async () => {+ const input = await getTaskInputHook('layered-intelligence');+ const output = await getTaskOutputHook('layered-intelligence');+ expect(typeof input).toBe('function');+ expect(typeof output).toBe('function');+ });++ it('returns null for a task type with no registered hooks', async () => {+ expect(await getTaskInputHook('security')).toBeNull();+ expect(await getTaskOutputHook('security')).toBeNull();+ expect(await getTaskInputHook('does-not-exist')).toBeNull();+ expect(await getTaskOutputHook('does-not-exist')).toBeNull();+ });+});