Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: layered intelligence loop — deterministic backbone (#2262)

Adam Eivy4ad36c1ddf7c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 7dc84e8312..f0d3f3071c 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -153,3 +153,5 @@
- **[issue-2175] Generation-side character framework + structure doctrine (CWQE Phase 10 remainder).** Following the worldbuilding-doctrine slice (#2219), the character-generation and structure-planning prompts now teach the craft up front. The character bible gains the Ghost → Wound → Lie → Want → Need chain (with interlock checks: state the Lie in one sentence; the Need/Truth is its direct opposite; the Ghost causally explains the Lie), a declared arc type (positive/negative/flat), the Three Sliders (proactivity/likability/competence 1–10, rule: HIGH on ≥2 or one-with-growth; all-low = boring, all-high = Mary Sue), and a secrets list — all OPTIONAL so pre-#2175 records round-trip unchanged (`server/lib/storyBible.js` sanitizer + Zod-shape parity via the existing `canonArrayField` sanitize-on-write, client mirror in `client/src/lib/bibleLimits.js`, character-sheet UI in `CharacterDetailEditor.jsx` with `htmlFor`/`id` pairing, and no-clobber merge in `universeCharacterExpand.js` for the AI-expand path). The `character.consistency` / `arc.*` editorial checks now receive the authored Lie/Want/Need/arc-type when present (via `canonCharacterTraitsSummary`) so they reconcile plan-vs-delivery instead of inferring both. Structure prompts gain lean doctrine: `pipeline-season-episodes.md` a try-fail mandate (60%+ of middle episodes end "Yes, but"/"No, and"), beat rules (Catalyst external; Break Into Two a protagonist choice; All Is Lost includes a death — literal or of a hope/relationship/identity) and an active-climax rule; `pipeline-arc-overview.md` MICE-style thread nesting (threads close in reverse order of opening; name the opening/closing thread per season). Shipped-template edits ship to existing installs via hash-keyed migrations 171/172/173 (with the drift-cross-sync of prior owners 003/005/019/027/166). Remaining Phase 10 items (Le Guin style doctrine into the style-guide flow) stay tracked on #2175.
- **[issue-2160] Bulk-history importer for Spotify extended streaming history + shared import seam.** The `/timeline` page gains a collapsible "Import Spotify history" panel: upload the privacy-download ZIP (or a single `Streaming_History_Audio_*.json`) → preview parsed counts/date-range/top-artists → confirm, and every play lands as an idempotent `media.listen` event via the existing `recordEvents()` infra (dedupe on track-uri + played-at, so re-imports and overlapping exports never double-count). Both the modern extended-history shape (`ts`/`ms_played`/`master_metadata_*`) and the legacy `StreamingHistory*.json` shape (`endTime`/`artistName`/`trackName`/`msPlayed`) are parsed; legacy offset-less UTC timestamps are anchored to UTC so a server west of UTC can't shift the listen into the wrong day. The route reuses the streaming `multipart.js` parser + `zipStream.js` (no new deps; the JSON parser is hand-written), Zod-validates the `preview` flag, and always unlinks the temp upload. This is one slice of the larger backfill issue. (`server/services/spotifyImport.js`, `server/routes/timeline.js`, `client/src/services/apiTimeline.js`, `client/src/components/timeline/SpotifyImportPanel.jsx`, `client/src/pages/Timeline.jsx`)
+
+- **[issue-2262] Layered Intelligence Loop — deterministic backbone (server slice).** A perpetual, per-managed-app self-improvement loop that runs as an Engine-B autonomous script job (`job-layered-intelligence`, off by default). On its schedule the handler sweeps `getActiveApps()` and, for each app whose `layeredIntelligence.enabled === true` and whose per-app interval has elapsed, runs four layers: GATHER (reads enabled sources — GOALS.md, CoS `learning.json` metrics, HEALTH_REPORT.md, PLAN.md, open tracker issues, plus app-declared `file` custom sources), REASON (`callProviderAISimple` against the active/overridden provider with a JSON-only prompt), DECIDE (deterministic scope-gate + slug/label dedup against live tracker state), and ACT (files exactly ONE issue via the app's resolved work tracker, and optionally pauses the app on a blocking issue). The reasoning model never touches code — it returns structured JSON and every side effect is deterministic handler code, so the "model must not make direct code changes" contract holds by construction. Dedup and pause are fully tracker-derived (a `<!-- lil-slug: … -->` marker + `layered-intelligence` / `layered-intelligence:blocking` labels; closed-issue suppression pinned at 30 days) — the only local state is per-app `lastRunAt` bookkeeping. Meta/self proposal scopes (`loop-meta` / `portos-self`) are double-enforced to PortOS-only so a hallucinated or hand-edited scope can't file against the loop from someone else's app. GitHub (`gh`) and GitLab (`glab`) forge filing + `plan`-tracker PLAN.md append are implemented; ships via the `DEFAULT_JOBS` catalog (merged into existing installs on boot by `applyAdditiveFields`) and the per-app config accessor's default (all sources on; PortOS gets the meta/self scopes) — so no seed file or migration is needed. Off by default; only runs as a user-enabled scheduled automation (no cold-bootstrap LLM calls). (`server/services/layeredIntelligence.js`, `server/services/autonomousJobs/layeredIntelligenceHandler.js`, `server/services/autonomousJobs/scriptHandlers.js`, `server/services/autonomousJobs/defaults.js`, `server/services/apps.js`, `server/lib/validation.js`)
diff --git a/server/lib/validation.js b/server/lib/validation.js
index dced044095..edc4eb61ae 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -110,6 +110,32 @@ export const workspaceContextParamsSchema = z.object({
appId: z.string().min(1).max(128).regex(/^[A-Za-z0-9_-]+$/, 'invalid app id')
});
+// Layered Intelligence per-app config (the self-improvement loop). Off by
+// default; the loop is a user-enabled scheduled automation. `lastRunAt` is
+// server-managed run bookkeeping (cadence, not issue memory) but accepted here
+// so a round-tripped config doesn't 400. See server/services/layeredIntelligence.js.
+export const LAYERED_INTELLIGENCE_SCOPES = ['app-improvement', 'app-data-gap', 'loop-meta', 'portos-self'];
+export const layeredIntelligenceConfigSchema = z.object({
+ enabled: z.boolean().optional(),
+ intervalMs: z.number().int().min(60_000).optional(),
+ providerId: z.string().nullable().optional(),
+ model: z.string().nullable().optional(),
+ sources: z.object({
+ goals: z.boolean().optional(),
+ cosMetrics: z.boolean().optional(),
+ healthReport: z.boolean().optional(),
+ planMd: z.boolean().optional(),
+ openIssues: z.boolean().optional(),
+ custom: z.array(z.object({
+ type: z.enum(['file']),
+ ref: z.string().min(1).max(500)
+ })).optional()
+ }).optional(),
+ rules: z.string().max(8000).optional(),
+ allowedScopes: z.array(z.enum(LAYERED_INTELLIGENCE_SCOPES)).optional(),
+ lastRunAt: z.string().nullable().optional()
+});
+
export const appSchema = z.object({
name: z.string().min(1).max(100),
repoPath: z.string().min(1),
@@ -147,7 +173,11 @@ export const appSchema = z.object({
// — see server/lib/workTracker.js + the `claim-work` router in
// cosTaskGenerator.js. WORK_TRACKERS is the single source of truth for the
// value set.
- workTracker: z.enum(WORK_TRACKERS).optional()
+ workTracker: z.enum(WORK_TRACKERS).optional(),
+ // Layered Intelligence per-app config (the self-improvement loop). Full config
+ // accepted on create/update; the dedicated updateAppLayeredIntelligence merge
+ // (server/services/apps.js) preserves untouched fields on partial PATCHes.
+ layeredIntelligence: layeredIntelligenceConfigSchema.optional()
// referenceRepos is INTENTIONALLY not part of the create/update API
// surface. createApp() doesn't persist it and updateApp() (via the
// omit() in appUpdateSchema) ignores it — the dedicated
diff --git a/server/services/apps.js b/server/services/apps.js
index f9c7f3a486..d129b02331 100644
--- a/server/services/apps.js
+++ b/server/services/apps.js
@@ -421,6 +421,40 @@ export async function getAppWorkTracker(id) {
return resolveAppWorkTracker(app);
}
+/**
+ * Get an app's effective Layered Intelligence config (the loop's per-app
+ * settings). Merges the stored `layeredIntelligence` over the defaults so a
+ * partial/absent config still yields a complete, safe config. PortOS gets the
+ * meta/self scopes. Returns null when the app id is unknown.
+ *
+ * `isPortos` is passed to the merge so a missing config picks up the right
+ * default scopes without a per-app seed write — an install adopts the baseline
+ * the first time the loop reads it.
+ */
+export async function getAppLayeredIntelligenceConfig(id) {
+ const app = await getAppById(id);
+ if (!app) return null;
+ const { getEffectiveConfig } = await import('./layeredIntelligence.js');
+ return getEffectiveConfig({ ...app, isPortos: id === PORTOS_APP_ID });
+}
+
+/**
+ * Update an app's Layered Intelligence config. Shallow-merges `updates` over the
+ * stored config (with `sources` merged one level deep) so a partial PATCH
+ * doesn't wipe untouched fields. Returns the updated app, or null if unknown.
+ */
+export async function updateAppLayeredIntelligence(id, updates = {}) {
+ const app = await getAppById(id);
+ if (!app) return null;
+ const { getEffectiveConfig } = await import('./layeredIntelligence.js');
+ const current = getEffectiveConfig({ ...app, isPortos: id === PORTOS_APP_ID });
+ const merged = { ...current, ...updates };
+ if (updates.sources && typeof updates.sources === 'object') {
+ merged.sources = { ...current.sources, ...updates.sources };
+ }
+ return updateApp(id, { layeredIntelligence: merged });
+}
+
/**
* Get task type overrides for an app
*/
diff --git a/server/services/apps.layeredIntelligence.test.js b/server/services/apps.layeredIntelligence.test.js
new file mode 100644
index 0000000000..a6882e6cd0
--- /dev/null
+++ b/server/services/apps.layeredIntelligence.test.js
@@ -0,0 +1,76 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// Mock the file/PM2/port surface apps.js touches so the accessors run against an
+// in-memory apps store. Mirrors apps.test.js's mock shape.
+let store;
+vi.mock('fs/promises', () => ({ writeFile: vi.fn().mockResolvedValue(undefined) }));
+vi.mock('../lib/fileUtils.js', () => ({
+ tryReadFile: vi.fn().mockResolvedValue(null),
+ atomicWrite: vi.fn(async (_path, data) => { store = data; }),
+ ensureDir: vi.fn().mockResolvedValue(undefined),
+ readJSONFile: vi.fn(async () => store),
+ PATHS: { data: '/mock/data', root: '/mock/root', cos: '/mock/data/cos' },
+ DAY: 24 * 60 * 60 * 1000
+}));
+vi.mock('../../lib/tailscale-https.js', () => ({ hasTailscaleCert: () => false }));
+vi.mock('../../lib/certPaths.js', () => ({ certPaths: () => ({ dir: '/mock' }) }));
+vi.mock('../lib/ports.js', () => ({ PORTS: { API: 5555, API_LOCAL: 5553, UI: 5554, COS: 5556, AUTOFIXER: 5557, AUTOFIXER_UI: 5558, CDP: 5559, CDP_HEALTH: 5560 } }));
+vi.mock('./taskSchedule.js', () => ({ SELF_IMPROVEMENT_TASK_TYPES: [] }));
+vi.mock('./pm2.js', () => ({ listProcessesStrict: vi.fn().mockResolvedValue([]) }));
+
+import { getAppLayeredIntelligenceConfig, updateAppLayeredIntelligence, invalidateCache, PORTOS_APP_ID } from './apps.js';
+
+beforeEach(() => {
+ invalidateCache();
+ store = {
+ apps: {
+ 'app-1': { name: 'App One', repoPath: '/repo', type: 'express', createdAt: '2024-01-01T00:00:00.000Z' }
+ }
+ };
+});
+
+describe('getAppLayeredIntelligenceConfig', () => {
+ it('returns the default config for an app with no stored config', async () => {
+ const c = await getAppLayeredIntelligenceConfig('app-1');
+ expect(c.enabled).toBe(false);
+ expect(c.allowedScopes).toEqual(['app-improvement', 'app-data-gap']); // non-PortOS
+ expect(c.sources.goals).toBe(true);
+ });
+
+ it('gives the PortOS app the meta/self scopes even without a stored config', async () => {
+ invalidateCache();
+ const c = await getAppLayeredIntelligenceConfig(PORTOS_APP_ID);
+ expect(c.allowedScopes).toContain('loop-meta');
+ expect(c.allowedScopes).toContain('portos-self');
+ });
+
+ it('returns null for an unknown app', async () => {
+ expect(await getAppLayeredIntelligenceConfig('nope')).toBe(null);
+ });
+});
+
+describe('updateAppLayeredIntelligence', () => {
+ it('merges a partial update over the defaults without wiping sources', async () => {
+ await updateAppLayeredIntelligence('app-1', { enabled: true, sources: { goals: false } });
+ invalidateCache();
+ const c = await getAppLayeredIntelligenceConfig('app-1');
+ expect(c.enabled).toBe(true);
+ expect(c.sources.goals).toBe(false);
+ expect(c.sources.cosMetrics).toBe(true); // untouched default preserved
+ });
+
+ it('preserves lastRunAt bookkeeping across a config PATCH', async () => {
+ // First a run-bookkeeping write, then a user config PATCH.
+ await updateAppLayeredIntelligence('app-1', { lastRunAt: '2026-07-07T00:00:00Z' });
+ invalidateCache();
+ await updateAppLayeredIntelligence('app-1', { enabled: true });
+ invalidateCache();
+ const c = await getAppLayeredIntelligenceConfig('app-1');
+ expect(c.enabled).toBe(true);
+ expect(c.lastRunAt).toBe('2026-07-07T00:00:00Z');
+ });
+
+ it('returns null for an unknown app', async () => {
+ expect(await updateAppLayeredIntelligence('nope', { enabled: true })).toBe(null);
+ });
+});
diff --git a/server/services/autonomousJobs/defaults.js b/server/services/autonomousJobs/defaults.js
index 3d93f880ae..0850a0c9d4 100644
--- a/server/services/autonomousJobs/defaults.js
+++ b/server/services/autonomousJobs/defaults.js
@@ -255,6 +255,22 @@ Phase 4 — Report:
createdAt: null,
updatedAt: null
},
+ {
+ id: 'job-layered-intelligence',
+ name: 'Layered Intelligence Loop',
+ description: 'Per-managed-app self-improvement loop. Reads each enabled app\'s goals + telemetry, asks a reasoning model (default: local LLM) for the single most-valuable improvement, and files ONE deduplicated tracker issue (GitHub/GitLab/Jira/PLAN.md) for a coding agent. The model never writes code — every side effect is deterministic. Off by default; enable per app under its config.',
+ category: 'layered-intelligence',
+ interval: 'daily',
+ intervalMs: DAY,
+ enabled: false,
+ priority: 'MEDIUM',
+ type: 'script',
+ scriptHandler: 'layered-intelligence',
+ lastRun: null,
+ runCount: 0,
+ createdAt: null,
+ updatedAt: null
+ },
{
id: 'job-wiki-maintenance',
name: 'Wiki Maintenance',
diff --git a/server/services/autonomousJobs/layeredIntelligenceHandler.js b/server/services/autonomousJobs/layeredIntelligenceHandler.js
new file mode 100644
index 0000000000..d8c7b09985
--- /dev/null
+++ b/server/services/autonomousJobs/layeredIntelligenceHandler.js
@@ -0,0 +1,240 @@
+/**
+ * Layered Intelligence Loop — the Engine-B sweep handler.
+ *
+ * Registered in SCRIPT_HANDLERS as `layered-intelligence`. On each fire it sweeps
+ * getActiveApps() and processes every app whose `layeredIntelligence.enabled ===
+ * true`, honoring a per-app `intervalMs`. For each due 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.
+ *
+ * Runs OUTSIDE the request lifecycle, so — per the CLAUDE.md no-try/catch rule —
+ * a per-app failure is wrapped, logged emoji-style, and the sweep continues; one
+ * bad app never aborts the whole sweep. Off by default (AI-provider policy).
+ */
+
+import { PORTOS_APP_ID, getActiveApps, updateApp } from '../apps.js'
+import {
+ getEffectiveConfig,
+ buildPrompt,
+ gatherSources,
+ listForgeIssues,
+ listBlockingIssues,
+ isAppParked,
+ validateReasonerResponse,
+ isScopeAllowed,
+ isProposalDuplicate,
+ filerForTracker,
+ trackerSupportsPause,
+ resolveBlockOnIssue,
+ fileProposalToForge,
+ applyBlockingLabel,
+ appendProposalToPlan,
+ extractPlanSlugs
+} from '../layeredIntelligence.js'
+import { resolveAppWorkTracker } from '../../lib/workTracker.js'
+import { tryReadFile } from '../../lib/fileUtils.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)
+}
+
+/**
+ * Process ONE app end-to-end (the four layers). Returns a structured outcome for
+ * logging/telemetry: { app, action, ... }. Never throws — the caller's sweep
+ * wrap is the async boundary, but this stays defensive so a partial failure of
+ * one layer degrades to a no-op outcome rather than aborting.
+ *
+ * `deps` is injectable for tests (callLLM, forge listers/filers, plan append).
+ */
+export async function processApp(app, deps = {}) {
+ const {
+ callLLM,
+ now = Date.now()
+ } = deps
+
+ const isPortos = app.id === PORTOS_APP_ID
+ const config = getEffectiveConfig({ ...app, isPortos })
+
+ if (!config.enabled) return { app: app.id, action: 'skipped', reason: 'disabled' }
+ if (!isAppDue(config, app.layeredIntelligence?.lastRunAt, now)) {
+ return { app: app.id, action: 'skipped', reason: 'not-due' }
+ }
+
+ // 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 filing is deferred to a follow-up (see PR Remaining). Skip a jira-tracked
+ // app BEFORE reasoning so we never burn an LLM call that can't file the result.
+ if (filer === 'jira') {
+ await recordRun(app, config, now)
+ return { app: app.id, action: 'skipped', reason: 'jira-filer-not-implemented' }
+ }
+
+ // ---- Park check (forge/jira only; plan has no issue to block on) ----
+ if (trackerSupportsPause(tracker.resolved) && filer === 'forge' && forgeCli) {
+ const blocking = await listBlockingIssues({ cli: forgeCli, cwd })
+ if (isAppParked(blocking)) {
+ console.log(`⏸️ Layered Intelligence: ${app.name} parked on ${blocking.length} blocking issue(s) — skipping`)
+ await recordRun(app, config, now)
+ return { app: app.id, action: 'parked', blocking: blocking.length }
+ }
+ }
+
+ // ---- Layer 1: GATHER ----
+ const sources = await gatherSources(app, config)
+ let openIssues = []
+ let existingIssues = []
+ if (filer === 'forge' && forgeCli) {
+ existingIssues = await listForgeIssues({ cli: forgeCli, cwd })
+ 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)
+ if (!llm.ok) {
+ await recordRun(app, config, now)
+ return { app: app.id, action: 'no-op', reason: llm.reason }
+ }
+ const llmResult = await llm.call(prompt)
+ if (llmResult?.error) {
+ await recordRun(app, config, now)
+ return { app: app.id, 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
+ let filedAction = 'no-op'
+ 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`)
+ } else if (isProposalDuplicate({ slug: proposal.slug, existingIssues, now })) {
+ console.log(`♻️ Layered Intelligence: ${app.name} proposal "${proposal.slug}" is a duplicate — suppressed`)
+ filedAction = 'duplicate'
+ } else {
+ // ---- Layer 4: ACT (file exactly one) ----
+ const filed = await fileProposal({ filer, forgeCli, cwd, app, proposal })
+ if (filed.success) {
+ filedNumber = filed.number ?? null
+ filedAction = 'filed'
+ console.log(`📌 Layered Intelligence: ${app.name} filed "${proposal.title}" [${proposal.slug}]${filedNumber ? ` (#${filedNumber})` : ''}`)
+ } else {
+ console.error(`❌ Layered Intelligence: ${app.name} failed to file proposal: ${filed.error || 'unknown'}`)
+ }
+ }
+ }
+
+ // ---- Pause (forge only; 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}`)
+ }
+ }
+
+ await recordRun(app, config, now)
+ return { app: app.id, action: filedAction, filedNumber, paused }
+}
+
+/** File the proposal via the resolved tracker's filer. */
+async function fileProposal({ filer, forgeCli, cwd, app, proposal }) {
+ if (filer === 'forge' && forgeCli) {
+ return fileProposalToForge({ cli: forgeCli, cwd, 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 }
+ }
+ // Jira filing is deferred to a follow-up (see PR Remaining).
+ 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
+ * callProviderAISimple. Returns `{ ok: false, reason }` when no provider is
+ * available (a no-op for that app, never a throw).
+ */
+async function resolveLLM(config, injected) {
+ 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 { callProviderAISimple } = await import('../../lib/aiProvider.js')
+ return {
+ ok: true,
+ call: (prompt) => callProviderAISimple(provider, model, prompt, {
+ op: `layered-intelligence:${provider.id}`,
+ opLabel: 'Layered Intelligence reasoning…',
+ max_tokens: 1500
+ })
+ }
+}
+
+/** Parse LLM JSON, returning null on failure (a no-op for that app). */
+function safeParse(text) {
+ if (typeof text !== 'string') return null
+ const cleaned = text.trim().replace(/^```(?:json)?\n?/, '').replace(/\n?```$/, '').trim()
+ try {
+ return JSON.parse(cleaned)
+ } catch {
+ return null
+ }
+}
+
+/** Persist per-app run bookkeeping (lastRunAt) — run cadence, not issue memory. */
+async function recordRun(app, config, now) {
+ const li = { ...(app.layeredIntelligence || {}), lastRunAt: new Date(now).toISOString() }
+ await updateApp(app.id, { layeredIntelligence: li }).catch((err) => {
+ console.error(`❌ Layered Intelligence: failed to record run for ${app.id}: ${err.message}`)
+ })
+}
+
+/**
+ * The SCRIPT_HANDLERS entry. Sweeps active apps and processes each enabled+due
+ * one. Per-app failures are caught and logged so the sweep continues.
+ */
+export async function runLayeredIntelligence() {
+ const apps = await getActiveApps()
+ const results = []
+ let processed = 0
+ for (const app of apps) {
+ const config = getEffectiveConfig({ ...app, isPortos: app.id === PORTOS_APP_ID })
+ if (!config.enabled) continue
+ const outcome = await processApp(app).catch((err) => {
+ console.error(`❌ Layered Intelligence: ${app.name} sweep error: ${err.message}`)
+ return { app: app.id, action: 'error', error: err.message }
+ })
+ if (outcome.action !== 'skipped') processed++
+ results.push(outcome)
+ }
+ console.log(`🧠 Layered Intelligence sweep complete: ${processed} app(s) processed of ${apps.length} active`)
+ return { processed, total: apps.length, results }
+}
diff --git a/server/services/autonomousJobs/layeredIntelligenceHandler.test.js b/server/services/autonomousJobs/layeredIntelligenceHandler.test.js
new file mode 100644
index 0000000000..10c514a96b
--- /dev/null
+++ b/server/services/autonomousJobs/layeredIntelligenceHandler.test.js
@@ -0,0 +1,189 @@
+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([]),
+ updateApp: (...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: [],
+ blocking: [],
+ fileResult: { success: true, number: 100 },
+ filed: [],
+ blockingApplied: []
+};
+vi.mock('../layeredIntelligence.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ gatherSources: vi.fn().mockResolvedValue({ goals: 'g' }),
+ listForgeIssues: vi.fn(async () => forgeState.existing),
+ listBlockingIssues: vi.fn(async () => forgeState.blocking),
+ 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 }))
+ };
+});
+
+import { isAppDue, processApp, runLayeredIntelligence } from './layeredIntelligenceHandler.js';
+import { getActiveApps } from '../apps.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.blocking = [];
+ forgeState.fileResult = { success: true, number: 100 };
+ forgeState.filed = [];
+ forgeState.blockingApplied = [];
+ resolveTrackerMock.mockResolvedValue({ resolved: 'github', forge: 'gh' });
+});
+
+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
+ });
+
+ it('skips a disabled app', async () => {
+ const out = await processApp({ id: 'x', name: 'X', layeredIntelligence: { enabled: false } });
+ expect(out.action).toBe('skipped');
+ expect(out.reason).toBe('disabled');
+ });
+
+ it('skips an app that is not due', async () => {
+ const now = Date.parse('2026-07-07T00:00:00Z');
+ const app = enabledApp();
+ app.layeredIntelligence.lastRunAt = new Date(now - DAY / 2).toISOString();
+ const out = await processApp(app, { now });
+ expect(out.action).toBe('skipped');
+ expect(out.reason).toBe('not-due');
+ });
+
+ 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('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 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('runLayeredIntelligence sweep', () => {
+ it('processes only enabled apps and continues past a per-app error', async () => {
+ getActiveApps.mockResolvedValue([
+ { id: 'off', name: 'Off', layeredIntelligence: { enabled: false } },
+ { id: 'app-1', name: 'On', repoPath: '/r', layeredIntelligence: { enabled: true, intervalMs: DAY, allowedScopes: ['app-improvement'] } }
+ ]);
+ // No callLLM injected → resolveLLM will try to import providers; make the
+ // tracker resolve so processApp reaches the provider step and no-ops on no provider.
+ resolveTrackerMock.mockResolvedValue({ resolved: 'plan', forge: null });
+ const res = await runLayeredIntelligence();
+ expect(res.total).toBe(2);
+ // The enabled app is attempted (processed >= 0); the disabled one is skipped before processApp.
+ expect(res.results.some(r => r.app === 'off')).toBe(false);
+ expect(res.results.some(r => r.app === 'app-1')).toBe(true);
+ });
+});
diff --git a/server/services/autonomousJobs/scriptHandlers.js b/server/services/autonomousJobs/scriptHandlers.js
index 7ab0c0f862..c9340a65f5 100644
--- a/server/services/autonomousJobs/scriptHandlers.js
+++ b/server/services/autonomousJobs/scriptHandlers.js
@@ -16,6 +16,7 @@ import { checkAndPrompt as autobiographyCheckAndPrompt } from '../autobiography.
import { runGoalCheckIn } from '../goalCheckIn.js'
import { cleanupOrphanedWorktrees, reapMergedWorktrees } from '../worktreeManager.js'
import { getActiveAgentIds } from '../agentState.js'
+import { runLayeredIntelligence } from './layeredIntelligenceHandler.js'
/**
* Run the moltworld-explore.mjs script as a child process (no AI agent needed).
@@ -139,7 +140,8 @@ const SCRIPT_HANDLERS = {
'autobiography-prompt': autobiographyCheckAndPrompt,
'moltworld-exploration': runMoltworldExploration,
'agent-data-cleanup': agentDataCleanup,
- 'goal-check-in': runGoalCheckIn
+ 'goal-check-in': runGoalCheckIn,
+ 'layered-intelligence': runLayeredIntelligence
}
export { runMoltworldExploration, agentDataCleanup, SCRIPT_HANDLERS }
diff --git a/server/services/layeredIntelligence.js b/server/services/layeredIntelligence.js
new file mode 100644
index 0000000000..1ad4977c75
--- /dev/null
+++ b/server/services/layeredIntelligence.js
@@ -0,0 +1,475 @@
+/**
+ * Layered Intelligence Loop — deterministic backbone.
+ *
+ * A perpetual, per-managed-app self-improvement loop (Engine B autonomous script
+ * job). On a schedule the handler reads each enabled app's goals + telemetry,
+ * asks a reasoning model (default: local LLM) for the single most-valuable
+ * improvement, and this module's DETERMINISTIC helpers file that as a tracker
+ * issue (GitHub / GitLab / Jira / PLAN.md) for a coding agent to pick up later.
+ *
+ * The reasoning model never touches code — it returns structured JSON only; every
+ * side effect (dedup, scope-gating, pause, filing) is deterministic handler code
+ * so the "model must not make direct code changes" contract holds by construction.
+ *
+ * The pure helpers (config defaults, scope-gating, slug/dedup, pause resolution,
+ * reasoner-output validation, prompt building, filer dispatch) are side-effect-free
+ * and unit-tested. The I/O functions (gather, forge/jira/plan filers) take injectable
+ * deps so tests can drive them without a live LLM, `gh`, or filesystem.
+ *
+ * See docs/plans/2026-07-07-layered-intelligence-loop.md for the full design.
+ */
+
+import { spawn } from 'child_process';
+import { join } from 'path';
+import { readFile, writeFile, appendFile } from 'fs/promises';
+import { existsSync } from 'fs';
+import { DAY, tryReadFile, readJSONFile, PATHS } from '../lib/fileUtils.js';
+
+// Tracker labels + slug marker. The slug is the stable dedup key the reasoner
+// chooses; it is embedded in each filed issue body so a later run (or the
+// reasoner reading open issues) can self-avoid duplicates.
+export const LI_LABEL = 'layered-intelligence';
+export const LI_BLOCKING_LABEL = 'layered-intelligence:blocking';
+
+// Closed issues carrying a matching slug suppress a re-proposal for this long,
+// so the loop doesn't immediately re-file something the user just resolved.
+export const CLOSED_SUPPRESSION_MS = 30 * DAY;
+
+// Every proposal scope the reasoner may return. The handler enforces WHERE each
+// lands (see PROPOSAL_SCOPE_TARGETS) and gates meta/self scopes to PortOS only.
+export const PROPOSAL_SCOPES = ['app-improvement', 'app-data-gap', 'loop-meta', 'portos-self'];
+
+// Scopes that may only be filed when the sweeping app IS the PortOS install
+// itself (they extend / improve the loop, which lives in the PortOS repo).
+export const PORTOS_ONLY_SCOPES = ['loop-meta', 'portos-self'];
+
+/**
+ * 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
+ * improvement + data-gap scopes. Off by default — the loop is a user-enabled
+ * scheduled automation (AI-provider "no cold-bootstrap" policy).
+ */
+export function defaultLayeredIntelligenceConfig(isPortos = false) {
+ return {
+ enabled: false,
+ intervalMs: DAY,
+ providerId: null,
+ model: null,
+ sources: {
+ goals: true,
+ cosMetrics: true,
+ healthReport: true,
+ planMd: true,
+ openIssues: true,
+ custom: []
+ },
+ rules: '',
+ allowedScopes: isPortos
+ ? ['app-improvement', 'app-data-gap', 'loop-meta', 'portos-self']
+ : ['app-improvement', 'app-data-gap']
+ };
+}
+
+/**
+ * Merge an app record's stored `layeredIntelligence` over the defaults so a
+ * partial config (or none) still yields a complete, safe config. `sources` is
+ * merged one level deep so a stored `{ sources: { goals: false } }` doesn't wipe
+ * the other source toggles.
+ */
+export function getEffectiveConfig(app) {
+ const isPortos = !!app?.isPortos;
+ const base = defaultLayeredIntelligenceConfig(isPortos);
+ const stored = (app && typeof app.layeredIntelligence === 'object' && app.layeredIntelligence) || {};
+ const merged = { ...base, ...stored };
+ merged.sources = {
+ ...base.sources,
+ ...(stored.sources && typeof stored.sources === 'object' ? stored.sources : {})
+ };
+ if (!Array.isArray(merged.sources.custom)) merged.sources.custom = [];
+ if (!Array.isArray(merged.allowedScopes)) merged.allowedScopes = base.allowedScopes;
+ return merged;
+}
+
+/**
+ * Whether a proposal scope is allowed for this app. A hallucinated or
+ * hand-edited scope cannot escape this gate: it must be a recognized scope, be
+ * in the app's `allowedScopes`, and — for meta/self scopes — the app must BE the
+ * PortOS install. Double-enforced regardless of what the prompt told the model.
+ */
+export function isScopeAllowed({ scope, allowedScopes = [], isPortos = false }) {
+ if (!PROPOSAL_SCOPES.includes(scope)) return false;
+ if (PORTOS_ONLY_SCOPES.includes(scope) && !isPortos) return false;
+ return allowedScopes.includes(scope);
+}
+
+/** The HTML-comment slug marker embedded in a filed issue/ticket body. */
+export function slugMarker(slug) {
+ return `<!-- lil-slug: ${slug} -->`;
+}
+
+/** Extract a `lil-slug` marker's value from a body string (null if absent). */
+export function extractSlugFromBody(body) {
+ if (typeof body !== 'string') return null;
+ const m = body.match(/<!--\s*lil-slug:\s*([a-z0-9][a-z0-9-]*)\s*-->/i);
+ return m ? m[1].toLowerCase() : null;
+}
+
+/**
+ * Normalize a reasoner-chosen slug to a stable kebab id. Returns null for a
+ * non-string or an input that reduces to empty (so a bad slug is a no-op, never
+ * a mystery label).
+ */
+export function normalizeSlug(slug) {
+ if (typeof slug !== 'string') return null;
+ const norm = slug
+ .toLowerCase()
+ .trim()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '')
+ .slice(0, 80);
+ return norm || null;
+}
+
+/**
+ * Deterministic dedup guard. Given the slug of the proposed item and the live
+ * tracker's existing issues (each `{ slug, state, closedAt }`), suppress the
+ * proposal when a match is open, OR closed within CLOSED_SUPPRESSION_MS.
+ *
+ * `slug` matching is case-insensitive on the normalized slug. `existingIssues`
+ * may carry either a parsed `slug` or a raw `body`/`title` we extract from.
+ */
+export function isProposalDuplicate({ slug, existingIssues = [], now = Date.now() }) {
+ const target = normalizeSlug(slug);
+ if (!target) return false;
+ for (const issue of existingIssues) {
+ const issueSlug = issue.slug
+ ? normalizeSlug(issue.slug)
+ : extractSlugFromBody(issue.body) || extractSlugFromBody(issue.title);
+ if (issueSlug !== target) continue;
+ const state = (issue.state || '').toLowerCase();
+ if (state === 'open') return true;
+ // Closed within the suppression window still suppresses.
+ const closedAt = issue.closedAt ? Date.parse(issue.closedAt) : NaN;
+ if (Number.isFinite(closedAt) && now - closedAt <= CLOSED_SUPPRESSION_MS) return true;
+ // Closed long ago (or unknown close time treated as long ago) → allow re-file.
+ }
+ return false;
+}
+
+/**
+ * Whether the app is currently PARKED — i.e. has at least one OPEN blocking
+ * issue. When parked, the sweep skips the app entirely (no gather, no reason),
+ * resuming automatically once the blocking issue closes. Fully tracker-derived.
+ */
+export function isAppParked(blockingIssues = []) {
+ return blockingIssues.some(i => (i.state || '').toLowerCase() === 'open');
+}
+
+/**
+ * Validate + normalize the reasoner's JSON. Returns
+ * `{ analysis, proposal, pause }` with invalid pieces dropped (never throws):
+ * - `proposal` kept only when it has a recognized scope + a normalizable slug
+ * + a non-empty title. `slug` is normalized in place.
+ * - `pause` kept only when it has a reason AND a resolvable target: an integer
+ * issue number, or `"this"` WITH a surviving proposal to block on. A
+ * `pause.blockOnIssue: "this"` with a null proposal is invalid → dropped.
+ */
+export function validateReasonerResponse(parsed) {
+ const out = { analysis: '', proposal: null, pause: null };
+ if (!parsed || typeof parsed !== 'object') return out;
+ if (typeof parsed.analysis === 'string') out.analysis = parsed.analysis;
+
+ const p = parsed.proposal;
+ if (p && typeof p === 'object' && !Array.isArray(p)) {
+ const slug = normalizeSlug(p.slug);
+ const title = typeof p.title === 'string' ? p.title.trim() : '';
+ if (PROPOSAL_SCOPES.includes(p.scope) && slug && title) {
+ out.proposal = {
+ scope: p.scope,
+ slug,
+ title,
+ body: typeof p.body === 'string' ? p.body : '',
+ value: typeof p.value === 'string' ? p.value : ''
+ };
+ }
+ }
+
+ const pause = parsed.pause;
+ if (pause && typeof pause === 'object' && !Array.isArray(pause)) {
+ const reason = typeof pause.reason === 'string' ? pause.reason.trim() : '';
+ const target = pause.blockOnIssue;
+ const isThis = target === 'this';
+ const num = Number.isInteger(target) ? target : (typeof target === 'string' && /^\d+$/.test(target) ? Number(target) : null);
+ // "this" requires a surviving proposal to block on; else an explicit issue number.
+ if (reason && ((isThis && out.proposal) || num)) {
+ out.pause = { blockOnIssue: isThis ? 'this' : num, reason };
+ }
+ }
+ return out;
+}
+
+/**
+ * Resolve `pause.blockOnIssue` to a concrete issue number. `"this"` maps to the
+ * number of the issue just filed from the proposal; an integer passes through.
+ * Returns null when it can't resolve (e.g. `"this"` but nothing was filed).
+ */
+export function resolveBlockOnIssue(pause, filedIssueNumber) {
+ if (!pause) return null;
+ if (pause.blockOnIssue === 'this') return filedIssueNumber ?? null;
+ return Number.isInteger(pause.blockOnIssue) ? pause.blockOnIssue : null;
+}
+
+/**
+ * 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.
+ * github / gitlab → 'forge' (gh / glab issue create + labels)
+ * jira → 'jira' (createTicket + description slug marker)
+ * plan (fallback) → 'plan' (append slug-tagged PLAN.md checklist item)
+ */
+export function filerForTracker(resolved) {
+ if (resolved === 'github' || resolved === 'gitlab') return 'forge';
+ if (resolved === 'jira') return 'jira';
+ return 'plan';
+}
+
+/** Whether a resolved tracker supports pause (an issue to block on). `plan` doesn't. */
+export function trackerSupportsPause(resolved) {
+ return filerForTracker(resolved) !== 'plan';
+}
+
+/**
+ * Build the JSON-only reasoning prompt for one app. Deterministic: given the
+ * gathered sources, open issues, and config, produces the exact string sent to
+ * the model. Meta/self scopes are only offered when the app is PortOS.
+ */
+export function buildPrompt({ app, config, sources = {}, openIssues = [], isPortos = false }) {
+ const allowed = (config.allowedScopes || []).filter(s =>
+ isScopeAllowed({ scope: s, allowedScopes: config.allowedScopes, isPortos })
+ );
+ const scopeLines = allowed.map(s => ` - ${s}`).join('\n');
+ const sourceBlocks = Object.entries(sources)
+ .filter(([, v]) => typeof v === 'string' && v.trim())
+ .map(([k, v]) => `### ${k}\n${v.trim()}`)
+ .join('\n\n');
+ const openList = openIssues.length
+ ? 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.
+
+Rules & guidance from the operator:
+${config.rules?.trim() || '(none)'}
+
+Allowed proposal scopes (you MUST pick one of these for any proposal):
+${scopeLines || ' (none — return proposal: null)'}
+${isPortos ? '' : 'Note: meta/self scopes are unavailable on this app; frame any data need as an "app-data-gap" against this app.\n'}
+Already-open tracked issues (DO NOT duplicate these — reuse their slug only if genuinely the same work):
+${openList}
+
+Gathered sources:
+${sourceBlocks || '(no sources available — you may propose an app-data-gap to add telemetry)'}
+
+Respond with JSON only (no markdown fences):
+{
+ "analysis": "brief reasoning summary",
+ "proposal": { // null if nothing worth filing this run
+ "scope": "<one allowed scope>",
+ "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"
+ },
+ "pause": { // null if not pausing
+ "blockOnIssue": "this" or <existing issue number>,
+ "reason": "why the loop should pause on this app until resolved"
+ }
+}`;
+}
+
+// ---------------------------------------------------------------------------
+// I/O layer — gather + filers. Injectable deps keep these testable.
+// ---------------------------------------------------------------------------
+
+/** Run a CLI, resolving `{ code, stdout, stderr }` (never rejects). */
+function runCli(cmd, args, options = {}) {
+ return new Promise((resolve) => {
+ const child = spawn(cmd, args, { shell: false, windowsHide: true, ...options });
+ let stdout = '', stderr = '';
+ child.stdout?.on('data', d => { stdout += d.toString(); });
+ child.stderr?.on('data', d => { stderr += d.toString(); });
+ child.on('close', code => resolve({ code, stdout, stderr }));
+ child.on('error', err => resolve({ code: -1, stdout: '', stderr: err.message }));
+ });
+}
+
+/**
+ * Gather the enabled Layer-1 sources for one app into a `{ key: string }` map.
+ * Deterministic reads only (files + CoS metric JSON); NO LLM calls. Missing
+ * files degrade to omitted keys, never throws. `openIssues` is gathered
+ * separately by the handler (it shells out to the forge).
+ */
+export async function gatherSources(app, config, { cosPath = PATHS.cos } = {}) {
+ const out = {};
+ const src = config.sources || {};
+ const repo = app.repoPath;
+
+ if (src.goals && repo) {
+ const goals = await tryReadFile(join(repo, 'GOALS.md'));
+ if (goals) out.goals = goals.slice(0, 8000);
+ }
+ if (src.planMd && repo) {
+ const plan = await tryReadFile(join(repo, 'PLAN.md'));
+ if (plan) out.planMd = plan.slice(0, 8000);
+ }
+ if (src.healthReport && repo) {
+ const health = await tryReadFile(join(repo, 'HEALTH_REPORT.md'));
+ if (health) out.healthReport = health.slice(0, 8000);
+ }
+ if (src.cosMetrics) {
+ const learning = await readJSONFile(join(cosPath, 'learning.json'), null);
+ if (learning?.byTaskType) {
+ out.cosMetrics = JSON.stringify(learning.byTaskType).slice(0, 4000);
+ }
+ }
+ for (const custom of src.custom || []) {
+ if (custom?.type === 'file' && typeof custom.ref === 'string' && repo) {
+ const content = await tryReadFile(join(repo, custom.ref));
+ if (content) out[`custom:${custom.ref}`] = content.slice(0, 8000);
+ }
+ }
+ return out;
+}
+
+/**
+ * List existing layered-intelligence issues on a forge (open + recently closed)
+ * so the handler can feed them to the reasoner and run the dedup guard. Returns
+ * `[{ number, title, body, state, closedAt, slug }]`; `[]` on any failure.
+ */
+export async function listForgeIssues({ cli, cwd, env, exec = runCli } = {}) {
+ const args = cli === 'glab'
+ ? ['issue', 'list', '--label', LI_LABEL, '--all', '-P', '100', '-F', 'json']
+ : ['issue', 'list', '--label', LI_LABEL, '--state', 'all', '--limit', '100', '--json', 'number,title,body,state,closedAt'];
+ const { code, stdout } = await exec(cli, args, { cwd, env });
+ if (code !== 0 || !stdout.trim()) return [];
+ const parsed = safeJsonArray(stdout);
+ return parsed.map(i => ({
+ number: i.number ?? i.iid ?? null,
+ title: i.title || '',
+ body: i.body || i.description || '',
+ state: (i.state || '').toLowerCase(),
+ closedAt: i.closedAt || i.closed_at || null,
+ slug: extractSlugFromBody(i.body || i.description || '') || extractSlugFromBody(i.title || '')
+ }));
+}
+
+/** List OPEN blocking-labeled issues for the app (park check). `[]` on failure. */
+export async function listBlockingIssues({ cli, cwd, env, exec = runCli } = {}) {
+ const args = cli === 'glab'
+ ? ['issue', 'list', '--label', LI_BLOCKING_LABEL, '-P', '100', '-F', 'json']
+ : ['issue', 'list', '--label', LI_BLOCKING_LABEL, '--state', 'open', '--limit', '100', '--json', 'number,title,state'];
+ const { code, stdout } = await exec(cli, args, { cwd, env });
+ if (code !== 0 || !stdout.trim()) return [];
+ return safeJsonArray(stdout).map(i => ({
+ number: i.number ?? i.iid ?? null,
+ title: i.title || '',
+ state: (i.state || 'open').toLowerCase()
+ }));
+}
+
+function safeJsonArray(text) {
+ try {
+ const parsed = JSON.parse(text);
+ return Array.isArray(parsed) ? parsed : [];
+ } catch {
+ return [];
+ }
+}
+
+/**
+ * Ensure the layered-intelligence labels exist before the first `issue create`
+ * (gh/glab both fail creating an issue with a non-existent label). Idempotent —
+ * `--force` (gh) / re-create (glab) is a no-op when the label already exists.
+ */
+export async function ensureForgeLabels({ cli, cwd, env, exec = runCli } = {}) {
+ const labels = [
+ { name: LI_LABEL, color: '1d76db', desc: 'Filed by the Layered Intelligence loop' },
+ { name: LI_BLOCKING_LABEL, color: 'b60205', desc: 'Layered Intelligence loop is paused on this issue' }
+ ];
+ for (const l of labels) {
+ if (cli === 'glab') {
+ await exec(cli, ['label', 'create', '--name', l.name, '--color', `#${l.color}`, '--description', l.desc], { cwd, env });
+ } else {
+ await exec(cli, ['label', 'create', l.name, '--color', l.color, '--description', l.desc, '--force'], { cwd, env });
+ }
+ }
+}
+
+/**
+ * File ONE proposal issue on a forge (gh/glab). Ensures labels first, embeds the
+ * slug marker in the body, and returns `{ success, number, url }`. The issue
+ * number is parsed from the created URL's trailing digits.
+ */
+export async function fileProposalToForge({ cli, cwd, env, title, body, slug, exec = runCli } = {}) {
+ await ensureForgeLabels({ cli, cwd, env, exec });
+ const fullBody = `${body}\n\n${slugMarker(slug)}`;
+ const args = cli === 'glab'
+ ? ['issue', 'create', '--title', title, '--description', fullBody, '--label', LI_LABEL]
+ : ['issue', 'create', '--title', title, '--body', fullBody, '--label', LI_LABEL];
+ const { code, stdout, stderr } = await exec(cli, args, { cwd, env });
+ if (code !== 0) return { success: false, error: stderr || `${cli} exited with code ${code}` };
+ const urlMatch = stdout.trim().match(/(https?:\/\/\S+)/);
+ const url = urlMatch ? urlMatch[1] : stdout.trim();
+ const numMatch = url.match(/(\d+)\s*$/);
+ return { success: true, number: numMatch ? Number(numMatch[1]) : null, url };
+}
+
+/** Apply the blocking label to an existing issue (pause). Returns `{ success }`. */
+export async function applyBlockingLabel({ cli, cwd, env, number, exec = runCli } = {}) {
+ if (!Number.isInteger(number)) return { success: false, error: 'no issue number' };
+ const args = cli === 'glab'
+ ? ['issue', 'update', String(number), '--label', LI_BLOCKING_LABEL]
+ : ['issue', 'edit', String(number), '--add-label', LI_BLOCKING_LABEL];
+ const { code, stderr } = await exec(cli, args, { cwd, env });
+ return code === 0 ? { success: true } : { success: false, error: stderr };
+}
+
+/**
+ * Append a slug-tagged proposal to the app's PLAN.md (the `plan` tracker path).
+ * Dedups by scanning for the `[lil-<slug>]` tag. Creates PLAN.md with a heading
+ * + `## Next Up` section if absent. Returns `{ success, duplicate }`.
+ */
+export async function appendProposalToPlan({ repoPath, appName, slug, title, body } = {}) {
+ const planPath = join(repoPath, 'PLAN.md');
+ const tag = `[lil-${slug}]`;
+ const existing = existsSync(planPath) ? await readFile(planPath, 'utf-8').catch(() => '') : '';
+ if (existing.includes(tag)) return { success: true, duplicate: true };
+
+ const oneLine = (body || '').replace(/\s+/g, ' ').trim().slice(0, 500);
+ const item = `- [ ] ${tag} **${title}** ${oneLine}`.trim();
+
+ if (!existing) {
+ const content = `# ${appName} — Development Plan\n\n## Next Up\n\n${item}\n`;
+ await writeFile(planPath, content);
+ return { success: true, duplicate: false };
+ }
+ if (existing.includes('## Next Up')) {
+ // Insert right after the "## Next Up" heading line.
+ const updated = existing.replace(/(##\s+Next Up\s*\n)/, `$1${item}\n`);
+ await writeFile(planPath, updated.endsWith('\n') ? updated : `${updated}\n`);
+ return { success: true, duplicate: false };
+ }
+ // No Next Up section — append one.
+ const sep = existing.endsWith('\n') ? '' : '\n';
+ await appendFile(planPath, `${sep}\n## Next Up\n\n${item}\n`);
+ return { success: true, duplicate: false };
+}
+
+/** Scan a PLAN.md string for existing `[lil-<slug>]` tags → array of slugs. */
+export function extractPlanSlugs(planContent) {
+ if (typeof planContent !== 'string') return [];
+ const slugs = [];
+ const re = /\[lil-([a-z0-9][a-z0-9-]*)\]/gi;
+ let m;
+ while ((m = re.exec(planContent))) slugs.push(m[1].toLowerCase());
+ return slugs;
+}
diff --git a/server/services/layeredIntelligence.test.js b/server/services/layeredIntelligence.test.js
new file mode 100644
index 0000000000..a9d1ff2471
--- /dev/null
+++ b/server/services/layeredIntelligence.test.js
@@ -0,0 +1,412 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import {
+ defaultLayeredIntelligenceConfig,
+ getEffectiveConfig,
+ isScopeAllowed,
+ PROPOSAL_SCOPES,
+ PORTOS_ONLY_SCOPES,
+ slugMarker,
+ extractSlugFromBody,
+ normalizeSlug,
+ isProposalDuplicate,
+ isAppParked,
+ validateReasonerResponse,
+ resolveBlockOnIssue,
+ filerForTracker,
+ trackerSupportsPause,
+ buildPrompt,
+ extractPlanSlugs,
+ listForgeIssues,
+ listBlockingIssues,
+ fileProposalToForge,
+ ensureForgeLabels,
+ applyBlockingLabel,
+ CLOSED_SUPPRESSION_MS,
+ LI_LABEL,
+ LI_BLOCKING_LABEL
+} from './layeredIntelligence.js';
+
+describe('defaultLayeredIntelligenceConfig', () => {
+ it('is off by default with all sources on', () => {
+ const c = defaultLayeredIntelligenceConfig(false);
+ expect(c.enabled).toBe(false);
+ expect(c.sources.goals).toBe(true);
+ expect(c.sources.cosMetrics).toBe(true);
+ expect(c.sources.custom).toEqual([]);
+ });
+
+ it('caps non-PortOS apps at app scopes only', () => {
+ const c = defaultLayeredIntelligenceConfig(false);
+ expect(c.allowedScopes).toEqual(['app-improvement', 'app-data-gap']);
+ expect(c.allowedScopes).not.toContain('loop-meta');
+ expect(c.allowedScopes).not.toContain('portos-self');
+ });
+
+ it('grants PortOS the meta/self scopes', () => {
+ const c = defaultLayeredIntelligenceConfig(true);
+ expect(c.allowedScopes).toContain('loop-meta');
+ expect(c.allowedScopes).toContain('portos-self');
+ });
+});
+
+describe('getEffectiveConfig', () => {
+ it('returns defaults for an app with no stored config', () => {
+ expect(getEffectiveConfig({ name: 'X' })).toEqual(defaultLayeredIntelligenceConfig(false));
+ });
+
+ it('merges sources one level deep (partial toggle does not wipe others)', () => {
+ const c = getEffectiveConfig({ layeredIntelligence: { sources: { goals: false } } });
+ expect(c.sources.goals).toBe(false);
+ expect(c.sources.cosMetrics).toBe(true); // untouched default preserved
+ expect(c.sources.planMd).toBe(true);
+ });
+
+ it('uses PortOS scopes when isPortos is set and none stored', () => {
+ const c = getEffectiveConfig({ isPortos: true });
+ expect(c.allowedScopes).toContain('portos-self');
+ });
+
+ it('honors a stored allowedScopes override', () => {
+ const c = getEffectiveConfig({ layeredIntelligence: { allowedScopes: ['app-improvement'] } });
+ expect(c.allowedScopes).toEqual(['app-improvement']);
+ });
+
+ it('repairs a non-array custom / allowedScopes', () => {
+ const c = getEffectiveConfig({ layeredIntelligence: { sources: { custom: 'bad' }, allowedScopes: 'nope' } });
+ expect(c.sources.custom).toEqual([]);
+ expect(Array.isArray(c.allowedScopes)).toBe(true);
+ });
+});
+
+describe('isScopeAllowed (scope-gating)', () => {
+ const allowedPortos = ['app-improvement', 'app-data-gap', 'loop-meta', 'portos-self'];
+ const allowedApp = ['app-improvement', 'app-data-gap'];
+
+ it('allows an in-list app scope on a normal app', () => {
+ expect(isScopeAllowed({ scope: 'app-improvement', allowedScopes: allowedApp, isPortos: false })).toBe(true);
+ });
+
+ it('rejects an unrecognized scope', () => {
+ expect(isScopeAllowed({ scope: 'delete-everything', allowedScopes: allowedPortos, isPortos: true })).toBe(false);
+ });
+
+ it('rejects meta/self scopes on a non-PortOS app even if allowedScopes lists them', () => {
+ for (const scope of PORTOS_ONLY_SCOPES) {
+ // A hand-edited config that lists loop-meta on someone else's app must still be blocked.
+ expect(isScopeAllowed({ scope, allowedScopes: allowedPortos, isPortos: false })).toBe(false);
+ }
+ });
+
+ it('allows meta/self scopes only on PortOS', () => {
+ for (const scope of PORTOS_ONLY_SCOPES) {
+ expect(isScopeAllowed({ scope, allowedScopes: allowedPortos, isPortos: true })).toBe(true);
+ }
+ });
+
+ it('rejects a scope not in allowedScopes', () => {
+ expect(isScopeAllowed({ scope: 'app-data-gap', allowedScopes: ['app-improvement'], isPortos: false })).toBe(false);
+ });
+});
+
+describe('slug helpers', () => {
+ it('round-trips a slug marker', () => {
+ expect(extractSlugFromBody(`text ${slugMarker('my-slug')} more`)).toBe('my-slug');
+ });
+
+ it('extracts nothing from a body with no marker', () => {
+ expect(extractSlugFromBody('no marker here')).toBe(null);
+ });
+
+ it('normalizes messy slugs', () => {
+ expect(normalizeSlug(' My Cool Feature!! ')).toBe('my-cool-feature');
+ expect(normalizeSlug('already-good')).toBe('already-good');
+ });
+
+ it('returns null for empty/non-string slugs', () => {
+ expect(normalizeSlug('')).toBe(null);
+ expect(normalizeSlug(' ')).toBe(null);
+ expect(normalizeSlug(null)).toBe(null);
+ expect(normalizeSlug(42)).toBe(null);
+ });
+});
+
+describe('isProposalDuplicate (dedup)', () => {
+ const now = Date.parse('2026-07-07T00:00:00Z');
+
+ it('suppresses when an OPEN issue carries the same slug', () => {
+ const existing = [{ slug: 'add-metrics', state: 'open' }];
+ expect(isProposalDuplicate({ slug: 'add-metrics', existingIssues: existing, now })).toBe(true);
+ });
+
+ it('suppresses when a CLOSED issue is within the 30-day window', () => {
+ const closedAt = new Date(now - 10 * 24 * 60 * 60 * 1000).toISOString();
+ const existing = [{ slug: 'add-metrics', state: 'closed', closedAt }];
+ expect(isProposalDuplicate({ slug: 'add-metrics', existingIssues: existing, now })).toBe(true);
+ });
+
+ it('ALLOWS re-file when a closed issue is older than 30 days', () => {
+ const closedAt = new Date(now - (CLOSED_SUPPRESSION_MS + 24 * 60 * 60 * 1000)).toISOString();
+ const existing = [{ slug: 'add-metrics', state: 'closed', closedAt }];
+ expect(isProposalDuplicate({ slug: 'add-metrics', existingIssues: existing, now })).toBe(false);
+ });
+
+ it('matches slug embedded in a body marker (no parsed slug field)', () => {
+ const existing = [{ body: `stuff ${slugMarker('add-metrics')}`, state: 'open' }];
+ expect(isProposalDuplicate({ slug: 'add-metrics', existingIssues: existing, now })).toBe(true);
+ });
+
+ it('does not suppress a different slug', () => {
+ const existing = [{ slug: 'other-thing', state: 'open' }];
+ expect(isProposalDuplicate({ slug: 'add-metrics', existingIssues: existing, now })).toBe(false);
+ });
+
+ it('is a no-op for a bad slug', () => {
+ expect(isProposalDuplicate({ slug: '', existingIssues: [{ slug: 'x', state: 'open' }], now })).toBe(false);
+ });
+
+ it('normalizes both sides before comparing', () => {
+ const existing = [{ slug: 'Add Metrics!', state: 'open' }];
+ expect(isProposalDuplicate({ slug: 'add-metrics', existingIssues: existing, now })).toBe(true);
+ });
+});
+
+describe('isAppParked (pause)', () => {
+ it('is parked when at least one blocking issue is open', () => {
+ expect(isAppParked([{ state: 'open' }, { state: 'closed' }])).toBe(true);
+ });
+
+ it('is not parked when all blocking issues are closed', () => {
+ expect(isAppParked([{ state: 'closed' }])).toBe(false);
+ });
+
+ it('is not parked with no blocking issues', () => {
+ expect(isAppParked([])).toBe(false);
+ });
+});
+
+describe('validateReasonerResponse', () => {
+ it('keeps a valid proposal and normalizes the slug', () => {
+ const r = validateReasonerResponse({
+ analysis: 'a',
+ proposal: { scope: 'app-improvement', slug: 'Do The Thing', title: 'Do the thing', body: 'b', value: 'v' }
+ });
+ expect(r.proposal.slug).toBe('do-the-thing');
+ expect(r.proposal.scope).toBe('app-improvement');
+ expect(r.pause).toBe(null);
+ });
+
+ it('drops a proposal with an unrecognized scope', () => {
+ const r = validateReasonerResponse({ proposal: { scope: 'nuke', slug: 'x', title: 'X' } });
+ expect(r.proposal).toBe(null);
+ });
+
+ it('drops a proposal missing a title', () => {
+ const r = validateReasonerResponse({ proposal: { scope: 'app-improvement', slug: 'x', title: ' ' } });
+ expect(r.proposal).toBe(null);
+ });
+
+ it('drops a proposal with an empty slug', () => {
+ const r = validateReasonerResponse({ proposal: { scope: 'app-improvement', slug: '!!', title: 'X' } });
+ expect(r.proposal).toBe(null);
+ });
+
+ it('keeps a pause with an integer issue number', () => {
+ const r = validateReasonerResponse({ pause: { blockOnIssue: 42, reason: 'blocked' } });
+ expect(r.pause).toEqual({ blockOnIssue: 42, reason: 'blocked' });
+ });
+
+ it('keeps pause "this" ONLY when a proposal survives', () => {
+ const withProp = validateReasonerResponse({
+ proposal: { scope: 'app-improvement', slug: 'x', title: 'X' },
+ pause: { blockOnIssue: 'this', reason: 'block on the new one' }
+ });
+ expect(withProp.pause).toEqual({ blockOnIssue: 'this', reason: 'block on the new one' });
+ });
+
+ it('drops pause "this" when there is no proposal to block on', () => {
+ const r = validateReasonerResponse({ proposal: null, pause: { blockOnIssue: 'this', reason: 'x' } });
+ expect(r.pause).toBe(null);
+ });
+
+ it('drops a pause with no reason', () => {
+ const r = validateReasonerResponse({ pause: { blockOnIssue: 42, reason: '' } });
+ expect(r.pause).toBe(null);
+ });
+
+ it('coerces a numeric-string issue number', () => {
+ const r = validateReasonerResponse({ pause: { blockOnIssue: '17', reason: 'x' } });
+ expect(r.pause.blockOnIssue).toBe(17);
+ });
+
+ it('handles garbage input without throwing', () => {
+ expect(validateReasonerResponse(null)).toEqual({ analysis: '', proposal: null, pause: null });
+ expect(validateReasonerResponse('nope')).toEqual({ analysis: '', proposal: null, pause: null });
+ expect(validateReasonerResponse({ proposal: [], pause: [] })).toEqual({ analysis: '', proposal: null, pause: null });
+ });
+});
+
+describe('resolveBlockOnIssue', () => {
+ it('maps "this" to the just-filed issue number', () => {
+ expect(resolveBlockOnIssue({ blockOnIssue: 'this' }, 99)).toBe(99);
+ });
+
+ it('returns null for "this" with no filed issue', () => {
+ expect(resolveBlockOnIssue({ blockOnIssue: 'this' }, null)).toBe(null);
+ });
+
+ it('passes an integer through', () => {
+ expect(resolveBlockOnIssue({ blockOnIssue: 7 }, null)).toBe(7);
+ });
+
+ it('returns null for a null pause', () => {
+ expect(resolveBlockOnIssue(null, 5)).toBe(null);
+ });
+});
+
+describe('filerForTracker / trackerSupportsPause (dispatch)', () => {
+ it('routes forges to the forge filer', () => {
+ expect(filerForTracker('github')).toBe('forge');
+ expect(filerForTracker('gitlab')).toBe('forge');
+ });
+
+ it('routes jira to the jira filer', () => {
+ expect(filerForTracker('jira')).toBe('jira');
+ });
+
+ it('routes plan (and unknowns) to the plan filer', () => {
+ expect(filerForTracker('plan')).toBe('plan');
+ expect(filerForTracker(undefined)).toBe('plan');
+ expect(filerForTracker('weird')).toBe('plan');
+ });
+
+ it('plan does not support pause; forge/jira do', () => {
+ expect(trackerSupportsPause('plan')).toBe(false);
+ expect(trackerSupportsPause('github')).toBe(true);
+ expect(trackerSupportsPause('jira')).toBe(true);
+ });
+});
+
+describe('buildPrompt', () => {
+ const app = { name: 'TestApp' };
+
+ it('only offers meta/self scopes on PortOS', () => {
+ const nonPortos = buildPrompt({
+ app, isPortos: false,
+ config: { allowedScopes: ['app-improvement', 'app-data-gap', 'loop-meta'], rules: '' }
+ });
+ expect(nonPortos).not.toContain('loop-meta'); // gated out by isScopeAllowed
+ expect(nonPortos).toContain('meta/self scopes are unavailable');
+
+ const portos = buildPrompt({
+ app, isPortos: true,
+ config: { allowedScopes: ['app-improvement', 'loop-meta', 'portos-self'], rules: '' }
+ });
+ expect(portos).toContain('loop-meta');
+ expect(portos).toContain('portos-self');
+ });
+
+ it('injects operator rules and open-issue slugs', () => {
+ const out = buildPrompt({
+ app, isPortos: false,
+ config: { allowedScopes: ['app-improvement'], rules: 'prefer perf work' },
+ openIssues: [{ number: 3, slug: 'existing-thing', title: 'Existing' }],
+ sources: { goals: 'ship faster' }
+ });
+ expect(out).toContain('prefer perf work');
+ expect(out).toContain('existing-thing');
+ expect(out).toContain('ship faster');
+ expect(out).toContain('JSON only');
+ });
+});
+
+describe('extractPlanSlugs', () => {
+ it('collects lil-tagged slugs from PLAN.md content', () => {
+ const plan = `## Next Up\n- [ ] [lil-add-metrics] Add metrics\n- [ ] [lil-fix-thing] Fix\n- [ ] [ref-watch-other] not ours`;
+ expect(extractPlanSlugs(plan)).toEqual(['add-metrics', 'fix-thing']);
+ });
+
+ it('returns [] for non-string / empty', () => {
+ expect(extractPlanSlugs(null)).toEqual([]);
+ expect(extractPlanSlugs('')).toEqual([]);
+ });
+});
+
+describe('forge I/O (injected exec)', () => {
+ it('listForgeIssues parses gh JSON and extracts slugs', async () => {
+ const exec = vi.fn().mockResolvedValue({
+ code: 0,
+ stdout: JSON.stringify([
+ { number: 1, title: 'A', body: `x ${slugMarker('slug-a')}`, state: 'OPEN', closedAt: null },
+ { number: 2, title: 'B', body: 'no slug', state: 'CLOSED', closedAt: '2026-07-01T00:00:00Z' }
+ ])
+ });
+ const issues = await listForgeIssues({ cli: 'gh', cwd: '/x', exec });
+ expect(issues[0].slug).toBe('slug-a');
+ expect(issues[0].state).toBe('open');
+ expect(issues[1].closedAt).toBe('2026-07-01T00:00:00Z');
+ });
+
+ it('listForgeIssues returns [] on CLI failure', async () => {
+ const exec = vi.fn().mockResolvedValue({ code: 1, stdout: '' });
+ expect(await listForgeIssues({ cli: 'gh', cwd: '/x', exec })).toEqual([]);
+ });
+
+ it('listBlockingIssues uses the blocking label', async () => {
+ const exec = vi.fn().mockResolvedValue({ code: 0, stdout: JSON.stringify([{ number: 5, state: 'open' }]) });
+ const res = await listBlockingIssues({ cli: 'gh', cwd: '/x', exec });
+ expect(res).toEqual([{ number: 5, title: '', state: 'open' }]);
+ expect(exec.mock.calls[0][1]).toContain(LI_BLOCKING_LABEL);
+ });
+
+ it('ensureForgeLabels creates both labels for gh', async () => {
+ const exec = vi.fn().mockResolvedValue({ code: 0, stdout: '' });
+ await ensureForgeLabels({ cli: 'gh', cwd: '/x', exec });
+ const created = exec.mock.calls.map(c => c[1][2]); // gh: ['label','create',<name>,...]
+ expect(created).toContain(LI_LABEL);
+ expect(created).toContain(LI_BLOCKING_LABEL);
+ // gh uses --force for idempotency
+ expect(exec.mock.calls[0][1]).toContain('--force');
+ });
+
+ it('fileProposalToForge embeds slug marker and returns issue number from URL', async () => {
+ const exec = vi.fn()
+ .mockResolvedValueOnce({ code: 0, stdout: '' }) // label create
+ .mockResolvedValueOnce({ code: 0, stdout: '' }) // label create
+ .mockResolvedValueOnce({ code: 0, stdout: 'https://github.com/o/r/issues/123\n' });
+ const res = await fileProposalToForge({ cli: 'gh', cwd: '/x', title: 'T', body: 'B', slug: 'my-slug', exec });
+ expect(res.success).toBe(true);
+ expect(res.number).toBe(123);
+ // The create call body carries the slug marker.
+ const createCall = exec.mock.calls[2][1];
+ const bodyIdx = createCall.indexOf('--body') + 1;
+ expect(createCall[bodyIdx]).toContain(slugMarker('my-slug'));
+ });
+
+ it('fileProposalToForge reports failure on nonzero exit', async () => {
+ const exec = vi.fn()
+ .mockResolvedValueOnce({ code: 0, stdout: '' })
+ .mockResolvedValueOnce({ code: 0, stdout: '' })
+ .mockResolvedValueOnce({ code: 1, stdout: '', stderr: 'boom' });
+ const res = await fileProposalToForge({ cli: 'gh', cwd: '/x', title: 'T', body: 'B', slug: 's', exec });
+ expect(res.success).toBe(false);
+ expect(res.error).toContain('boom');
+ });
+
+ it('applyBlockingLabel adds the blocking label via gh edit', async () => {
+ const exec = vi.fn().mockResolvedValue({ code: 0, stdout: '' });
+ const res = await applyBlockingLabel({ cli: 'gh', cwd: '/x', number: 42, exec });
+ expect(res.success).toBe(true);
+ expect(exec.mock.calls[0][1]).toEqual(expect.arrayContaining(['edit', '42', '--add-label', LI_BLOCKING_LABEL]));
+ });
+
+ it('applyBlockingLabel rejects a non-integer number', async () => {
+ const exec = vi.fn();
+ const res = await applyBlockingLabel({ cli: 'gh', cwd: '/x', number: null, exec });
+ expect(res.success).toBe(false);
+ expect(exec).not.toHaveBeenCalled();
+ });
+
+ it('PROPOSAL_SCOPES is the full scope set', () => {
+ expect(PROPOSAL_SCOPES).toEqual(['app-improvement', 'app-data-gap', 'loop-meta', 'portos-self']);
+ });
+});