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
feat([issue-2262]): Engine-A trivial-fix hand-off for the Layered Intelligence loop
Adam Eivy20429fed7ad3
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 92f90f1bfb..9dea63eaf9 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -31,6 +31,7 @@## Layered Intelligence+- **[issue-2262] The loop can now hand a trivial, safe fix straight to a coding agent instead of only filing it.** Each app's Intelligence config gains an opt-in "Auto hand-off" toggle (off by default, on top of enabling the loop). When it's on and the reasoner marks its single proposal both `trivial` and `safe`, the loop still files the tracker issue for the audit trail, then also queues an approval-gated CoS coding-agent task to implement that exact issue end-to-end (read → fix → test → PR that closes it, or stop and comment if it turns out non-trivial). The reasoner's JSON now carries `complexity` (`trivial`/`moderate`/`complex`) and `safe` fields, and the prompt only mentions the hand-off path when the app enabled it — so a hand-off-off app's reasoning is unchanged. The hand-off only fires for a concretely-filed forge issue or Jira ticket (a plan-tracked app has no issue number, so it stays file-only and its PLAN item is drained by the normal claim-work scheduler), the enqueued task requires user approval before any code is written, and it's deduped per app so a re-run won't double-queue while the fix is still pending. No cold-bootstrap risk — it only runs inside the already user-enabled scheduled sweep. (`server/services/layeredIntelligence.js` `isHandoffEligible`/`buildHandoffTask`, `server/services/autonomousJobs/layeredIntelligenceHandler.js`, `server/lib/validation.js`, `server/services/apps.js`, `client/src/components/apps/LayeredIntelligenceTab.jsx`)- **[issue-2262] A dedicated Layered Intelligence page now surfaces the self-improvement loop's status across every app.** The perpetual per-app loop was previously visible only inside each app's Edit-App → Intelligence drawer tab, so there was no single place to see which apps had it enabled, when each last ran / is next due, or whether the global sweep job is even on. The new `/layered-intelligence` route (Chief of Staff → Layered Intelligence, `⌘K`/voice-navigable) reads a deterministic cross-app overview — each active app's effective config plus scheduler bookkeeping (`lastRunAt`/`nextDueAt`/due) and the global job's on/off state — with no LLM or forge I/O. It warns when the global job is disabled (per-app configs are inert until it's on), lists enabled apps with their interval, telemetry sources, allowed scopes, and provider, and deep-links each app's "Configure" action straight into its Intelligence tab (`/apps/:id?edit=1&appTab=intelligence`, via a new auto-open trigger on the app-detail drawer). (`server/routes/apps.js`, `server/services/layeredIntelligence.js` `summarizeLoopStatus`, `client/src/pages/LayeredIntelligence.jsx`, `client/src/components/apps/AppDetailView.jsx`, `server/lib/navManifest.js`)- **[issue-2262] The loop now catches near-duplicate proposals worded differently, not just exact-slug repeats.** The DECIDE layer's dedup was purely the reasoner-chosen slug (plus label) — so if the model proposed the same work under a fresh slug ("introduce-widget" vs an open "add-widget"), it slipped past and filed a second tracker issue. A semantic guard now runs *after* the slug guard passes: it embeds the proposal's title+body and each open (or recently-closed, within the same 30-day window) tracker issue via the local embeddings provider, and suppresses the proposal when a candidate's cosine similarity meets a conservative floor (`SEMANTIC_DEDUP_THRESHOLD = 0.9`). It's strictly best-effort and self-gating: when no embeddings provider is configured (or the proposal embed is skipped/fails) the check reports `available:false` and filing proceeds — slug dedup already guarded the exact case, so an unavailable semantic layer only restores prior behavior, never files a slug-duplicate. No cold-bootstrap risk (embeddings degrade to a no-op with no provider, and this only runs inside the user-enabled scheduled sweep), no new config field, and plan-tracked slug-only issues are simply not embeddable so they're skipped. Candidate embedding is capped per run (`SEMANTIC_DEDUP_MAX_CANDIDATES = 50`) so a large backlog can't fan out unboundedly, and the shared `isIssueWithinDedupWindow` helper keeps the semantic and slug guards agreeing on which issues still count. (`server/services/layeredIntelligence.js` `checkSemanticDuplicate`/`findSemanticDuplicate`/`cosineSimilarity`, `server/services/autonomousJobs/layeredIntelligenceHandler.js`)diff --git a/client/src/components/apps/LayeredIntelligenceTab.jsx b/client/src/components/apps/LayeredIntelligenceTab.jsxindex 7d64f840a5..6a6dc97663 100644--- a/client/src/components/apps/LayeredIntelligenceTab.jsx+++ b/client/src/components/apps/LayeredIntelligenceTab.jsx@@ -125,6 +125,10 @@ export function buildLayeredIntelligenceUpdate(baseline, current) {update.allowedScopes = Array.isArray(current.allowedScopes) ? current.allowedScopes : [];}+ if (!!current.handoff?.enabled !== !!baseline.handoff?.enabled) {+ update.handoff = { enabled: !!current.handoff?.enabled };+ }+return Object.keys(update).length > 0 ? update : null;}@@ -354,6 +358,24 @@ export default function LayeredIntelligenceTab({ li, onChange, providers, isPort</Banner>)}</div>++ <div>+ <span className="block text-sm text-gray-400 mb-2">Auto hand-off</span>+ <label className="flex items-start gap-2 cursor-pointer">+ <input+ type="checkbox"+ checked={!!li.handoff?.enabled}+ onChange={e => onChange({ handoff: { ...(li.handoff || {}), enabled: e.target.checked } })}+ className="mt-1 rounded border-port-border bg-port-bg text-port-accent focus:ring-port-accent"+ />+ <span className="text-sm text-white">+ Hand trivial, safe fixes to a coding agent+ <span className="block text-xs text-gray-500">+ When the loop marks a proposal both trivial and safe, also queue an approval-gated CoS coding-agent task to implement it — instead of only filing the issue for later.+ </span>+ </span>+ </label>+ </div></div>);}diff --git a/client/src/components/apps/LayeredIntelligenceTab.test.jsx b/client/src/components/apps/LayeredIntelligenceTab.test.jsxindex 9781ca08ac..67dc89a8b9 100644--- a/client/src/components/apps/LayeredIntelligenceTab.test.jsx+++ b/client/src/components/apps/LayeredIntelligenceTab.test.jsx@@ -32,6 +32,13 @@ describe('buildLayeredIntelligenceUpdate', () => {expect(update).toEqual({ intervalMs: 3600000 });});+ it('emits the hand-off toggle only when it changes', () => {+ const withHandoff = { ...baseline, handoff: { enabled: false } };+ expect(buildLayeredIntelligenceUpdate(withHandoff, { ...withHandoff })).toBeNull();+ const update = buildLayeredIntelligenceUpdate(withHandoff, { ...withHandoff, handoff: { enabled: true } });+ expect(update).toEqual({ handoff: { enabled: true } });+ });+it('normalizes empty provider/model to null and only emits when changed', () => {// '' provider equals the null baseline → no changeexpect(buildLayeredIntelligenceUpdate(baseline, { ...baseline, providerId: '', model: '' })).toBeNull();diff --git a/server/lib/validation.js b/server/lib/validation.jsindex d0462feb82..ba6b9c9e06 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -157,6 +157,11 @@ export const layeredIntelligenceConfigSchema = z.object({}).optional(),rules: z.string().max(8000).optional(),allowedScopes: z.array(z.enum(LAYERED_INTELLIGENCE_SCOPES)).optional(),+ // Engine-A hand-off: when enabled, a reasoner-marked trivial+safe proposal is+ // also enqueued as an approval-gated CoS coding-agent task. Off by default.+ handoff: z.object({+ enabled: z.boolean().optional()+ }).optional(),lastRunAt: z.string().nullable().optional()});diff --git a/server/services/apps.js b/server/services/apps.jsindex 27c128a852..7e039edee5 100644--- a/server/services/apps.js+++ b/server/services/apps.js@@ -466,6 +466,9 @@ export async function updateAppLayeredIntelligence(id, updates = {}) {if (updates.sources && typeof updates.sources === 'object') {merged.sources = { ...(stored.sources && typeof stored.sources === 'object' ? stored.sources : {}), ...updates.sources };}+ if (updates.handoff && typeof updates.handoff === 'object') {+ merged.handoff = { ...(stored.handoff && typeof stored.handoff === 'object' ? stored.handoff : {}), ...updates.handoff };+ }return updateApp(id, { layeredIntelligence: merged });}diff --git a/server/services/autonomousJobs/layeredIntelligenceHandler.js b/server/services/autonomousJobs/layeredIntelligenceHandler.jsindex e56d44164d..17be0d5f19 100644--- a/server/services/autonomousJobs/layeredIntelligenceHandler.js+++ b/server/services/autonomousJobs/layeredIntelligenceHandler.js@@ -25,6 +25,8 @@ import {isScopeAllowed,isProposalDuplicate,checkSemanticDuplicate,+ isHandoffEligible,+ buildHandoffTask,filerForTracker,trackerSupportsPause,resolveBlockOnIssue,@@ -65,6 +67,7 @@ export function isAppDue(config, lastRunAt, now = Date.now()) {export async function processApp(app, deps = {}) {const {callLLM,+ enqueueHandoff = defaultEnqueueHandoff,now = Date.now()} = deps@@ -161,6 +164,7 @@ export async function processApp(app, deps = {}) {let filedNumber = null // forge: integer issue numberlet filedKey = null // jira: string ticket key (PROJ-123)let filedAction = 'no-op'+ let handedOff = falseif (proposal) {const scopeOk = isScopeAllowed({ scope: proposal.scope, allowedScopes: config.allowedScopes, isPortos })if (!scopeOk) {@@ -184,6 +188,21 @@ export async function processApp(app, deps = {}) {filedAction = 'filed'const ref = filedKey || (filedNumber ? `#${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'}`)}@@ -209,7 +228,19 @@ export async function processApp(app, deps = {}) {}await recordRun(app, config, now)- return { app: app.id, action: filedAction, filedNumber, filedKey, paused }+ return { app: app.id, action: filedAction, 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')}/**diff --git a/server/services/autonomousJobs/layeredIntelligenceHandler.test.js b/server/services/autonomousJobs/layeredIntelligenceHandler.test.jsindex 8fc5a50ee8..e7935a4387 100644--- a/server/services/autonomousJobs/layeredIntelligenceHandler.test.js+++ b/server/services/autonomousJobs/layeredIntelligenceHandler.test.js@@ -236,6 +236,57 @@ describe('processApp', () => {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({diff --git a/server/services/layeredIntelligence.js b/server/services/layeredIntelligence.jsindex e38912df3a..261e5f5fc1 100644--- a/server/services/layeredIntelligence.js+++ b/server/services/layeredIntelligence.js@@ -68,6 +68,15 @@ export const PROPOSAL_SCOPES = ['app-improvement', 'app-data-gap', 'loop-meta',// itself (they extend / improve the loop, which lives in the PortOS repo).export const PORTOS_ONLY_SCOPES = ['loop-meta', 'portos-self'];+// The reasoner's honest effort/risk estimate for a proposal. Only a `trivial`+// proposal is ever eligible for the optional Engine-A hand-off (below); anything+// unrecognized normalizes to null (unknown → not trivial → never auto-handed-off).+export const PROPOSAL_COMPLEXITIES = ['trivial', 'moderate', 'complex'];++// The single complexity level that (with `safe: true` and hand-off enabled)+// lets the loop enqueue a coding agent instead of only filing the issue.+export const HANDOFF_COMPLEXITY = 'trivial';+/*** The default per-app config. PortOS (isPortos) additionally gets the meta/self* scopes so the loop can extend itself; every other app is capped at its own@@ -91,7 +100,12 @@ export function defaultLayeredIntelligenceConfig(isPortos = false) {rules: '',allowedScopes: isPortos? ['app-improvement', 'app-data-gap', 'loop-meta', 'portos-self']- : ['app-improvement', 'app-data-gap']+ : ['app-improvement', 'app-data-gap'],+ // Engine-A hand-off. When enabled, a proposal the reasoner marks trivial+safe+ // is ALSO enqueued as a CoS coding-agent task (approval-gated) instead of only+ // being filed for later human triage. Off by default — letting an agent write+ // code from the loop unattended is an extra opt-in on top of enabling the loop.+ handoff: { enabled: false }};}@@ -112,6 +126,12 @@ export function getEffectiveConfig(app) {...base.sources,...(stored.sources && typeof stored.sources === 'object' ? stored.sources : {})};+ // Merge handoff one level deep (like sources) so a partial `{ handoff: {} }`+ // doesn't wipe the default `enabled`.+ merged.handoff = {+ ...base.handoff,+ ...(stored.handoff && typeof stored.handoff === 'object' && !Array.isArray(stored.handoff) ? stored.handoff : {})+ };if (!Array.isArray(merged.sources.custom)) merged.sources.custom = [];if (!Array.isArray(merged.allowedScopes)) merged.allowedScopes = base.allowedScopes;return merged;@@ -143,6 +163,7 @@ export function summarizeLoopStatus({ app, isPortos = false, now = Date.now() }intervalMs: config.intervalMs,providerId: config.providerId || null,model: config.model || null,+ handoffEnabled: !!config.handoff?.enabled,hasRules: !!(typeof config.rules === 'string' && config.rules.trim()),lastRunAt,nextDueAt,@@ -312,7 +333,12 @@ export function validateReasonerResponse(parsed) {slug,title,body: typeof p.body === 'string' ? p.body : '',- value: typeof p.value === 'string' ? p.value : ''+ value: typeof p.value === 'string' ? p.value : '',+ // Hand-off signals. `complexity` normalizes to a known level or null+ // (unknown → never trivial → never auto-handed-off); `safe` is a strict+ // boolean so only an explicit `true` opens the hand-off path.+ complexity: PROPOSAL_COMPLEXITIES.includes(p.complexity) ? p.complexity : null,+ safe: p.safe === true};}}@@ -342,6 +368,56 @@ export function resolveBlockOnIssue(pause, filedIssueNumber) {return Number.isInteger(pause.blockOnIssue) ? pause.blockOnIssue : null;}+/**+ * Whether a filed proposal qualifies for the optional Engine-A hand-off — i.e.+ * the loop should enqueue a coding agent to implement it now, not just file it.+ * Requires ALL of: hand-off enabled in the app's config, an issue actually filed+ * (a concrete `filed` ref for the agent to work), and the reasoner marking the+ * proposal both trivial AND safe. Any missing/false signal falls through to+ * file-only. Pure — the handler feeds it the filed ref.+ */+export function isHandoffEligible({ proposal, config, filed } = {}) {+ if (filed == null || filed === '' || filed === false) return false;+ if (!config?.handoff?.enabled) return false;+ if (!proposal || typeof proposal !== 'object') return false;+ return proposal.complexity === HANDOFF_COMPLEXITY && proposal.safe === true;+}++/**+ * Build the CoS task payload that hands a filed proposal to an Engine-A coding+ * agent. Deterministic (no I/O) so it's unit-tested; the handler passes the+ * result to `addTask(..., 'internal')`. The task is APPROVAL-GATED — an agent+ * writing code straight from the loop shouldn't run unattended (mirrors+ * autoFixer's every code-editing task). The description leads with a stable+ * `LI hand-off:` prefix so addTask's per-app dedup suppresses a re-enqueue while+ * the same proposal's task is still pending/in-flight.+ */+export function buildHandoffTask({ app, proposal, issueRef } = {}) {+ const ref = typeof issueRef === 'number' ? `#${issueRef}` : String(issueRef ?? '').trim();+ const context = [+ '# Layered Intelligence hand-off',+ '',+ `The Layered Intelligence loop identified a TRIVIAL, SAFE improvement for **${app?.name || app?.id || 'this app'}** and filed it as ${ref}.`,+ '',+ '## Task',+ `Implement the change described in ${ref} end-to-end: read the issue, make the fix, run the app's tests, and open a PR that closes ${ref}.`,+ 'If — once you dig in — the change turns out to be non-trivial or carries any regression/data-loss risk, STOP and leave a comment on the issue explaining why instead of forcing it. Filing was the safe fallback; a half-done risky change is worse than none.',+ '',+ '## Proposal',+ `- **Title:** ${proposal?.title || ''}`,+ `- **Value:** ${proposal?.value || '(not provided)'}`,+ '',+ proposal?.body || ''+ ].join('\n');+ return {+ description: `LI hand-off: ${proposal?.title || ref}`,+ priority: 'MEDIUM',+ context,+ app: app?.id,+ approvalRequired: true+ };+}+/*** Which filing path a resolved work tracker uses. Branches the handler up front* so a `plan` app never hits the forge-only label/issue paths.@@ -378,8 +454,12 @@ export function buildPrompt({ app, config, sources = {}, openIssues = [], isPort? openIssues.map(i => `- #${i.number ?? '?'} [${i.slug || extractSlugFromBody(i.body) || 'no-slug'}] ${i.title || ''}`).join('\n'): '(none)';- return `You are the Layered Intelligence reasoner for the app "${app.name}". Analyze the app's goals and telemetry and decide the SINGLE highest-value improvement to propose this run — signal, not noise. You never write code; you return structured JSON that a deterministic system files as ONE tracker issue.+ const handoffNote = config.handoff?.enabled+ ? '\nHand-off: a proposal you mark BOTH "complexity":"trivial" AND "safe":true may be handed directly to a coding agent to implement now (not just filed). Only mark a proposal trivial+safe when it is small, self-contained, and carries no regression or data-loss risk — when in doubt, use a higher complexity or "safe":false so a human triages it first.\n'+ : '';+ return `You are the Layered Intelligence reasoner for the app "${app.name}". Analyze the app's goals and telemetry and decide the SINGLE highest-value improvement to propose this run — signal, not noise. You never write code; you return structured JSON that a deterministic system files as ONE tracker issue.+${handoffNote}Rules & guidance from the operator:${config.rules?.trim() || '(none)'}@@ -400,7 +480,9 @@ Respond with JSON only (no markdown fences):"slug": "kebab-stable-id","title": "short imperative title","body": "markdown detail for the coding agent",- "value": "why this is the single highest-value item now"+ "value": "why this is the single highest-value item now",+ "complexity": "trivial | moderate | complex", // honest effort/risk estimate+ "safe": false // true ONLY if a coding agent could implement it end-to-end with no regression/data-loss risk},"pause": { // null if not pausing"blockOnIssue": "this" or <existing issue number>,diff --git a/server/services/layeredIntelligence.test.js b/server/services/layeredIntelligence.test.jsindex b71db0b8a4..cdc2d9b337 100644--- a/server/services/layeredIntelligence.test.js+++ b/server/services/layeredIntelligence.test.js@@ -21,6 +21,9 @@ import {SEMANTIC_DEDUP_MAX_CANDIDATES,isAppParked,validateReasonerResponse,+ isHandoffEligible,+ buildHandoffTask,+ HANDOFF_COMPLEXITY,resolveBlockOnIssue,filerForTracker,trackerSupportsPause,@@ -72,6 +75,11 @@ describe('defaultLayeredIntelligenceConfig', () => {expect(c.allowedScopes).toContain('loop-meta');expect(c.allowedScopes).toContain('portos-self');});++ it('ships the Engine-A hand-off off by default', () => {+ expect(defaultLayeredIntelligenceConfig(false).handoff).toEqual({ enabled: false });+ expect(defaultLayeredIntelligenceConfig(true).handoff).toEqual({ enabled: false });+ });});describe('getEffectiveConfig', () => {@@ -101,6 +109,13 @@ describe('getEffectiveConfig', () => {expect(c.sources.custom).toEqual([]);expect(Array.isArray(c.allowedScopes)).toBe(true);});++ it('merges handoff one level deep (partial does not wipe default enabled)', () => {+ expect(getEffectiveConfig({ layeredIntelligence: { handoff: {} } }).handoff).toEqual({ enabled: false });+ expect(getEffectiveConfig({ layeredIntelligence: { handoff: { enabled: true } } }).handoff).toEqual({ enabled: true });+ // A junk (non-object) handoff falls back to the default.+ expect(getEffectiveConfig({ layeredIntelligence: { handoff: 'nope' } }).handoff).toEqual({ enabled: false });+ });});describe('summarizeLoopStatus (overview page shape)', () => {@@ -147,6 +162,16 @@ describe('summarizeLoopStatus (overview page shape)', () => {expect(JSON.stringify(s)).not.toContain('never add deps');});+ it('surfaces the hand-off enabled flag', () => {+ const off = summarizeLoopStatus({ app: { id: 'h0', name: 'Off' }, now: NOW });+ expect(off.handoffEnabled).toBe(false);+ const on = summarizeLoopStatus({+ app: { id: 'h1', name: 'On', layeredIntelligence: { enabled: true, handoff: { enabled: true } } },+ now: NOW+ });+ expect(on.handoffEnabled).toBe(true);+ });+it('surfaces PortOS scopes + custom source count', () => {const s = summarizeLoopStatus({app: { id: 'portos-default', name: 'PortOS', layeredIntelligence: { enabled: true, sources: { custom: [{ type: 'file', ref: 'x.md' }] } } },@@ -334,6 +359,68 @@ describe('validateReasonerResponse', () => {expect(validateReasonerResponse('nope')).toEqual({ analysis: '', proposal: null, pause: null });expect(validateReasonerResponse({ proposal: [], pause: [] })).toEqual({ analysis: '', proposal: null, pause: null });});++ it('normalizes proposal complexity + safe (defaults: null / false)', () => {+ const bare = validateReasonerResponse({ proposal: { scope: 'app-improvement', slug: 'x', title: 'X' } });+ expect(bare.proposal.complexity).toBe(null);+ expect(bare.proposal.safe).toBe(false);++ const trivial = validateReasonerResponse({ proposal: { scope: 'app-improvement', slug: 'x', title: 'X', complexity: 'trivial', safe: true } });+ expect(trivial.proposal.complexity).toBe('trivial');+ expect(trivial.proposal.safe).toBe(true);++ // Unknown complexity → null; a non-strict-true safe → false.+ const junk = validateReasonerResponse({ proposal: { scope: 'app-improvement', slug: 'x', title: 'X', complexity: 'epic', safe: 'yes' } });+ expect(junk.proposal.complexity).toBe(null);+ expect(junk.proposal.safe).toBe(false);+ });+});++describe('isHandoffEligible', () => {+ const trivialSafe = { complexity: HANDOFF_COMPLEXITY, safe: true };+ const on = { handoff: { enabled: true } };++ it('is eligible only when enabled + filed ref + trivial + safe', () => {+ expect(isHandoffEligible({ proposal: trivialSafe, config: on, filed: 42 })).toBe(true);+ expect(isHandoffEligible({ proposal: trivialSafe, config: on, filed: 'PROJ-7' })).toBe(true);+ });++ it('is NOT eligible when hand-off is disabled', () => {+ expect(isHandoffEligible({ proposal: trivialSafe, config: { handoff: { enabled: false } }, filed: 42 })).toBe(false);+ expect(isHandoffEligible({ proposal: trivialSafe, config: {}, filed: 42 })).toBe(false);+ });++ it('is NOT eligible without a concrete filed ref (plan-tracked apps)', () => {+ expect(isHandoffEligible({ proposal: trivialSafe, config: on, filed: null })).toBe(false);+ expect(isHandoffEligible({ proposal: trivialSafe, config: on, filed: '' })).toBe(false);+ expect(isHandoffEligible({ proposal: trivialSafe, config: on, filed: false })).toBe(false);+ });++ it('is NOT eligible unless BOTH trivial AND safe', () => {+ expect(isHandoffEligible({ proposal: { complexity: 'moderate', safe: true }, config: on, filed: 1 })).toBe(false);+ expect(isHandoffEligible({ proposal: { complexity: 'trivial', safe: false }, config: on, filed: 1 })).toBe(false);+ expect(isHandoffEligible({ proposal: null, config: on, filed: 1 })).toBe(false);+ });+});++describe('buildHandoffTask', () => {+ const app = { id: 'app-1', name: 'App One' };+ const proposal = { title: 'Fix the typo', body: 'change X to Y', value: 'clarity', slug: 'fix-typo' };++ it('builds an approval-gated internal task scoped to the app', () => {+ const t = buildHandoffTask({ app, proposal, issueRef: 42 });+ expect(t.approvalRequired).toBe(true);+ expect(t.app).toBe('app-1');+ expect(t.priority).toBe('MEDIUM');+ expect(t.description).toBe('LI hand-off: Fix the typo');+ });++ it('references the filed issue in the context (# for forge number, raw key for jira)', () => {+ expect(buildHandoffTask({ app, proposal, issueRef: 42 }).context).toContain('#42');+ const jira = buildHandoffTask({ app, proposal, issueRef: 'PROJ-7' }).context;+ expect(jira).toContain('PROJ-7');+ expect(jira).toContain('change X to Y'); // carries the proposal body+ });});describe('resolveBlockOnIssue', () => {@@ -408,6 +495,14 @@ describe('buildPrompt', () => {expect(out).toContain('ship faster');expect(out).toContain('JSON only');});++ it('mentions the hand-off only when it is enabled', () => {+ const off = buildPrompt({ app, isPortos: false, config: { allowedScopes: ['app-improvement'], rules: '' } });+ expect(off).not.toContain('Hand-off:');+ const on = buildPrompt({ app, isPortos: false, config: { allowedScopes: ['app-improvement'], rules: '', handoff: { enabled: true } } });+ expect(on).toContain('Hand-off:');+ expect(on).toContain('"complexity":"trivial"');+ });});describe('extractPlanSlugs', () => {