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: file Layered Intelligence proposals to Jira (#2262)
[._.]/ Adam Eivya7d5b323ee32
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 468fcdef37..992f3234bb 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -168,4 +168,6 @@- **[issue-2262] Layered Intelligence Loop — per-app config UI (client slice).** The Edit App drawer gains an "Intelligence" tab that configures the self-improvement loop per managed app: enable/disable, a run-interval preset select (hourly → weekly, with a "Custom" readout for a hand-set cadence), an optional provider/model override (defaults to the active CoS provider), the Layer-1 telemetry source toggles (goals, CoS metrics, health report, PLAN.md, open issues), an add/remove list of repo-relative custom `file` sources, a free-text guidance-rules box, and the allowed-proposal-scope checkboxes — with the `loop-meta` / `portos-self` scopes shown only on the PortOS baseline app (mirroring the server's PORTOS-only gate). The tab reads the effective config from a new read-only `GET /api/apps/:id/layered-intelligence` endpoint (stored partial merged over the shipped defaults + `isPortos` flag) and, on save, PATCHes only the fields that changed against that baseline via a `buildLayeredIntelligenceUpdate` diff — so an unchanged config stays absent and the server's merge-over-stored contract keeps the install forward-compatible with future default changes (persisting the full effective config would freeze it). No migration or seed file is needed: the job ships via the `DEFAULT_JOBS` boot-merge and the per-app config comes from the accessor default (per the design doc in `docs/plans/2026-07-07-layered-intelligence-loop.md`). (`client/src/components/apps/LayeredIntelligenceTab.jsx`, `client/src/components/apps/EditAppDrawer.jsx`, `client/src/services/apiApps.js`, `server/routes/apps.js`)+- **[issue-2262] Layered Intelligence Loop now files to Jira (tracker abstraction completed).** A Jira-tracked managed app previously short-circuited BEFORE reasoning (`skipped: jira-filer-not-implemented`) — only GitHub/GitLab forges and PLAN.md apps could file. The loop's "act" step now files through the PortOS Jira REST service for any app whose resolved work tracker is `jira` with an enabled `jira.instanceId`/`projectKey` (Jira is never auto-detected from the git host, matching `resolveAppWorkTracker`). A Jira app with no usable config still skips before reasoning (`jira-not-configured`) so no LLM call is burned on a result that can't land. Dedup, park, and pause reuse the same tracker-derived model as the forges: the `<!-- lil-slug: … -->` marker is embedded in the ticket description and matched via a `labels = "layered-intelligence"` JQL scan (with the `ok`/`issues` failed-vs-empty sentinel so a transient Jira blip suppresses filing rather than duplicating), closed-issue suppression uses the ticket `resolutiondate` against the shared 30-day window, and pause applies a Jira-safe `layered-intelligence-blocking` label (colons/spaces stripped) filtered by `statusCategory != Done` so a resolved blocker un-parks the app automatically. Because Jira issues are keyed strings (`PROJ-123`), `pause.blockOnIssue: "this"` resolves to the just-filed ticket's key and an integer resolves to `<projectKey>-<n>`. Adds three generic Jira service helpers (`searchIssues`, `addLabels`, exported `escapeJql`) reused by the filer. (`server/services/jira.js`, `server/services/layeredIntelligence.js`, `server/services/autonomousJobs/layeredIntelligenceHandler.js`)+- **[issue-2277] Layered Intelligence custom sources gain `http` + `cmd` types (full-stack).** The Intelligence tab's custom-source list previously only offered `file` rows even though the design called for three source types — `http`/`cmd` sources could only be set through the API. Each row now has a type selector (File / URL / Command) that swaps in the type-appropriate value field (repo-relative `ref` / `url` / `cmd`) plus an optional `label`, and "Add source" seeds a new file row. The backend backbone the UI needs was also added in the same change (it didn't exist in `main` yet): the Zod schema is now a `type`-discriminated union (`file` keeps the repo-relative-path refine, `http` requires an http(s) URL, `cmd` is a bounded command string, all with an optional label), and `gatherSources` reads the new types via two injectable, degrade-to-omit helpers — `fetchHttpSource` (http(s)-scheme-guarded, 10s-timeout `fetch`, null on non-2xx/throw) and `runShellCommand` (shell-run in the app's repo dir, 15s timeout, null on non-zero exit). A `customSourceKey` helper namespaces the prompt map key by type so a `file` ref and an `http` url that share a string can't collide. Sanitize/diff on the client mirrors all three types + label so a blank/half-typed row still sanitizes away (no over-persist), and a type change clears the stale value field while keeping the label. (`server/lib/validation.js`, `server/services/layeredIntelligence.js`, `client/src/components/apps/LayeredIntelligenceTab.jsx`)diff --git a/server/services/autonomousJobs/layeredIntelligenceHandler.js b/server/services/autonomousJobs/layeredIntelligenceHandler.jsindex 49e8c97f54..4c2e2f510b 100644--- a/server/services/autonomousJobs/layeredIntelligenceHandler.js+++ b/server/services/autonomousJobs/layeredIntelligenceHandler.js@@ -30,7 +30,12 @@ import {fileProposalToForge,applyBlockingLabel,appendProposalToPlan,- extractPlanSlugs+ extractPlanSlugs,+ listJiraIssues,+ listJiraBlockingIssues,+ fileProposalToJira,+ resolveJiraBlockKey,+ applyJiraBlockingLabel} from '../layeredIntelligence.js'import { resolveAppWorkTracker } from '../../lib/workTracker.js'import { tryReadFile, safeJSONParse } from '../../lib/fileUtils.js'@@ -77,24 +82,31 @@ export async function processApp(app, deps = {}) {const forgeCli = tracker.forge // 'gh' | 'glab' | nullconst 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') {+ // Jira coordinates come from the app's explicit per-app config (never+ // auto-detected). A jira-tracked app with no usable instance/project can't file,+ // so skip it BEFORE reasoning rather than burn an LLM call on a result we can't+ // land. `projectKey` is also needed to resolve integer pause targets to keys.+ const jira = (filer === 'jira' && app.jira?.enabled && app.jira?.instanceId && app.jira?.projectKey)+ ? { instanceId: app.jira.instanceId, projectKey: app.jira.projectKey, issueType: app.jira.issueType || 'Task' }+ : null+ if (filer === 'jira' && !jira) {await recordRun(app, config, now)- return { app: app.id, action: 'skipped', reason: 'jira-filer-not-implemented' }+ return { app: app.id, action: 'skipped', reason: 'jira-not-configured' }}- // ---- Park check (forge only; plan has no issue to block on) ----- if (trackerSupportsPause(tracker.resolved) && filer === 'forge' && forgeCli) {- const blocking = await listBlockingIssues({ cli: forgeCli, cwd })+ // ---- Park check (forge + jira; plan has no issue to block on) ----+ if (trackerSupportsPause(tracker.resolved)) {+ const blocking = filer === 'jira'+ ? await listJiraBlockingIssues({ instanceId: jira.instanceId, projectKey: jira.projectKey })+ : (forgeCli ? await listBlockingIssues({ cli: forgeCli, cwd }) : null)// A FAILED read (ok:false) is not "no blocking issues" — skip this app rather// than risk resuming work the user parked, and try again next run.- if (!blocking.ok) {+ if (blocking && !blocking.ok) {console.warn(`⚠️ Layered Intelligence: ${app.name} blocking-issue read failed — skipping this run`)await recordRun(app, config, now)return { app: app.id, action: 'skipped', reason: 'blocking-read-failed' }}- if (isAppParked(blocking.issues)) {+ if (blocking && isAppParked(blocking.issues)) {console.log(`⏸️ Layered Intelligence: ${app.name} parked on ${blocking.issues.length} blocking issue(s) — skipping`)await recordRun(app, config, now)return { app: app.id, action: 'parked', blocking: blocking.issues.length }@@ -115,6 +127,13 @@ export async function processApp(app, deps = {}) {if (config.sources?.openIssues !== false) {openIssues = existingIssues.filter(i => i.state === 'open')}+ } else if (filer === 'jira') {+ const listed = await listJiraIssues({ instanceId: jira.instanceId, projectKey: jira.projectKey })+ trackerReadFailed = !listed.ok+ existingIssues = listed.issues+ if (config.sources?.openIssues !== false) {+ openIssues = existingIssues.filter(i => i.state === 'open')+ }} else if (filer === 'plan' && cwd) {const planContent = await tryReadFile(join(cwd, 'PLAN.md'))const planSlugs = extractPlanSlugs(planContent || '')@@ -138,7 +157,8 @@ export async function processApp(app, deps = {}) {const { proposal, pause } = validateReasonerResponse(parsed)// ---- Layer 3: DECIDE (scope-gate + dedup) ----- let filedNumber = null+ let filedNumber = null // forge: integer issue number+ let filedKey = null // jira: string ticket key (PROJ-123)let filedAction = 'no-op'if (proposal) {const scopeOk = isScopeAllowed({ scope: proposal.scope, allowedScopes: config.allowedScopes, isPortos })@@ -154,18 +174,20 @@ export async function processApp(app, deps = {}) {filedAction = 'duplicate'} else {// ---- Layer 4: ACT (file exactly one) ----- const filed = await fileProposal({ filer, forgeCli, cwd, app, proposal })+ const filed = await fileProposal({ filer, forgeCli, cwd, app, proposal, jira })if (filed.success) {filedNumber = filed.number ?? null+ filedKey = filed.key ?? nullfiledAction = 'filed'- console.log(`📌 Layered Intelligence: ${app.name} filed "${proposal.title}" [${proposal.slug}]${filedNumber ? ` (#${filedNumber})` : ''}`)+ const ref = filedKey || (filedNumber ? `#${filedNumber}` : '')+ console.log(`📌 Layered Intelligence: ${app.name} filed "${proposal.title}" [${proposal.slug}]${ref ? ` (${ref})` : ''}`)} else {console.error(`❌ Layered Intelligence: ${app.name} failed to file proposal: ${filed.error || 'unknown'}`)}}}- // ---- Pause (forge only; resolve blockOnIssue after filing) ----+ // ---- Pause (forge + jira; resolve blockOnIssue after filing) ----let paused = falseif (pause && filer === 'forge' && forgeCli) {const number = resolveBlockOnIssue(pause, filedNumber)@@ -174,22 +196,34 @@ export async function processApp(app, deps = {}) {paused = res.successif (paused) console.log(`⏸️ Layered Intelligence: ${app.name} paused on #${number} — ${pause.reason}`)}+ } else if (pause && filer === 'jira' && jira) {+ const key = resolveJiraBlockKey(pause, filedKey, jira.projectKey)+ if (key) {+ const res = await applyJiraBlockingLabel({ instanceId: jira.instanceId, key })+ paused = res.success+ if (paused) console.log(`⏸️ Layered Intelligence: ${app.name} paused on ${key} — ${pause.reason}`)+ }}await recordRun(app, config, now)- return { app: app.id, action: filedAction, filedNumber, paused }+ return { app: app.id, action: filedAction, filedNumber, filedKey, paused }}/** File the proposal via the resolved tracker's filer. */-async function fileProposal({ filer, forgeCli, cwd, app, proposal }) {+async function fileProposal({ filer, forgeCli, cwd, app, proposal, jira }) {if (filer === 'forge' && forgeCli) {return fileProposalToForge({ cli: forgeCli, cwd, title: proposal.title, body: proposal.body, slug: proposal.slug })}+ if (filer === 'jira' && jira) {+ return fileProposalToJira({+ instanceId: jira.instanceId, projectKey: jira.projectKey, issueType: jira.issueType,+ title: proposal.title, body: proposal.body, slug: proposal.slug+ })+ }if (filer === 'plan' && cwd) {const res = await appendProposalToPlan({ repoPath: cwd, appName: app.name, slug: proposal.slug, title: proposal.title, body: proposal.body })return { success: res.success, number: null }}- // Jira filing is deferred to a follow-up (see PR Remaining).return { success: false, error: `filer "${filer}" not implemented` }}diff --git a/server/services/autonomousJobs/layeredIntelligenceHandler.test.js b/server/services/autonomousJobs/layeredIntelligenceHandler.test.jsindex 7a882f4238..c9dae4f9fe 100644--- a/server/services/autonomousJobs/layeredIntelligenceHandler.test.js+++ b/server/services/autonomousJobs/layeredIntelligenceHandler.test.js@@ -26,7 +26,15 @@ const forgeState = {blockingOk: true,fileResult: { success: true, number: 100 },filed: [],- blockingApplied: []+ blockingApplied: [],+ // Jira mirrors: separate lister/filer/label spies so the dispatch is asserted per tracker.+ jiraExisting: [],+ jiraExistingOk: true,+ jiraBlocking: [],+ jiraBlockingOk: true,+ jiraFileResult: { success: true, key: 'PROJ-100' },+ jiraFiled: [],+ jiraBlockingApplied: []};vi.mock('../layeredIntelligence.js', async (importOriginal) => {const actual = await importOriginal();@@ -38,7 +46,11 @@ vi.mock('../layeredIntelligence.js', async (importOriginal) => {listBlockingIssues: vi.fn(async () => ({ ok: forgeState.blockingOk, issues: 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 }))+ appendProposalToPlan: vi.fn(async () => ({ success: true, duplicate: false })),+ listJiraIssues: vi.fn(async () => ({ ok: forgeState.jiraExistingOk, issues: forgeState.jiraExisting })),+ listJiraBlockingIssues: vi.fn(async () => ({ ok: forgeState.jiraBlockingOk, issues: forgeState.jiraBlocking })),+ fileProposalToJira: vi.fn(async (opts) => { forgeState.jiraFiled.push(opts); return forgeState.jiraFileResult; }),+ applyJiraBlockingLabel: vi.fn(async (opts) => { forgeState.jiraBlockingApplied.push(opts); return { success: true }; })};});@@ -61,6 +73,13 @@ beforeEach(() => {forgeState.fileResult = { success: true, number: 100 };forgeState.filed = [];forgeState.blockingApplied = [];+ forgeState.jiraExisting = [];+ forgeState.jiraExistingOk = true;+ forgeState.jiraBlocking = [];+ forgeState.jiraBlockingOk = true;+ forgeState.jiraFileResult = { success: true, key: 'PROJ-100' };+ forgeState.jiraFiled = [];+ forgeState.jiraBlockingApplied = [];resolveTrackerMock.mockResolvedValue({ resolved: 'github', forge: 'gh' });});@@ -204,6 +223,83 @@ describe('processApp', () => {});});+describe('processApp — jira tracker', () => {+ const jiraApp = (extra = {}) => ({+ id: 'app-j', name: 'Jira App', repoPath: '/repo',+ jira: { enabled: true, instanceId: 'inst', projectKey: 'PROJ', issueType: 'Task' },+ layeredIntelligence: { enabled: true, intervalMs: DAY, allowedScopes: ['app-improvement', 'app-data-gap'] },+ ...extra+ });++ beforeEach(() => {+ resolveTrackerMock.mockResolvedValue({ resolved: 'jira', forge: null });+ });++ it('skips a jira-tracked app that has no usable jira config (before reasoning)', async () => {+ const callLLM = reasoner({ proposal: { scope: 'app-improvement', slug: 's', title: 'T' } });+ const out = await processApp({+ id: 'app-j', name: 'Jira App', repoPath: '/repo',+ jira: { enabled: false },+ layeredIntelligence: { enabled: true, intervalMs: DAY, allowedScopes: ['app-improvement'] }+ }, { callLLM });+ expect(out.action).toBe('skipped');+ expect(out.reason).toBe('jira-not-configured');+ expect(callLLM).not.toHaveBeenCalled();+ });++ it('files ONE jira ticket for a valid proposal', async () => {+ const callLLM = reasoner({ proposal: { scope: 'app-improvement', slug: 'add-x', title: 'Add X', body: 'do it' } });+ const out = await processApp(jiraApp(), { callLLM });+ expect(out.action).toBe('filed');+ expect(out.filedKey).toBe('PROJ-100');+ expect(forgeState.jiraFiled).toHaveLength(1);+ expect(forgeState.jiraFiled[0]).toMatchObject({ instanceId: 'inst', projectKey: 'PROJ', slug: 'add-x' });+ expect(forgeState.filed).toHaveLength(0); // never touches the forge filer+ });++ it('parks a jira app when a blocking ticket is open (skips reasoning)', async () => {+ forgeState.jiraBlocking = [{ number: 'PROJ-5', state: 'open' }];+ const callLLM = reasoner({ proposal: { scope: 'app-improvement', slug: 's', title: 'T' } });+ const out = await processApp(jiraApp(), { callLLM });+ expect(out.action).toBe('parked');+ expect(callLLM).not.toHaveBeenCalled();+ });++ it('does NOT file when the jira issue-list read failed (avoids blind duplicate)', async () => {+ forgeState.jiraExistingOk = false;+ const callLLM = reasoner({ proposal: { scope: 'app-improvement', slug: 'add-x', title: 'Add X' } });+ const out = await processApp(jiraApp(), { callLLM });+ expect(out.action).toBe('tracker-read-failed');+ expect(forgeState.jiraFiled).toHaveLength(0);+ });++ it('dedups a jira proposal against existing tickets', async () => {+ forgeState.jiraExisting = [{ slug: 'add-x', state: 'open' }];+ const callLLM = reasoner({ proposal: { scope: 'app-improvement', slug: 'add-x', title: 'Add X' } });+ const out = await processApp(jiraApp(), { callLLM });+ expect(out.action).toBe('duplicate');+ expect(forgeState.jiraFiled).toHaveLength(0);+ });++ it('files AND pauses on the just-filed jira ticket key ("this")', async () => {+ const callLLM = reasoner({+ proposal: { scope: 'app-improvement', slug: 'add-x', title: 'Add X' },+ pause: { blockOnIssue: 'this', reason: 'need this first' }+ });+ const out = await processApp(jiraApp(), { callLLM });+ expect(out.action).toBe('filed');+ expect(out.paused).toBe(true);+ expect(forgeState.jiraBlockingApplied[0]).toMatchObject({ instanceId: 'inst', key: 'PROJ-100' });+ });++ it('resolves an integer pause target to <project>-<n> on an existing jira ticket', async () => {+ const callLLM = reasoner({ pause: { blockOnIssue: 7, reason: 'block on an existing ticket' } });+ const out = await processApp(jiraApp(), { callLLM });+ expect(out.paused).toBe(true);+ expect(forgeState.jiraBlockingApplied[0].key).toBe('PROJ-7');+ });+});+describe('runLayeredIntelligence sweep', () => {it('processes only enabled apps and continues past a per-app error', async () => {getActiveApps.mockResolvedValue([diff --git a/server/services/jira.js b/server/services/jira.jsindex db53ce7856..9c673c5551 100644--- a/server/services/jira.js+++ b/server/services/jira.js@@ -11,7 +11,7 @@ import { hostFromOriginUrl } from '../lib/workTracker.js';const JIRA_CONFIG_FILE = path.join(PATHS.data, 'jira.json');-const escapeJql = (s) => String(s).replace(/\\/g, '\\\\').replace(/"/g, '\\"');+export const escapeJql = (s) => String(s).replace(/\\/g, '\\\\').replace(/"/g, '\\"');/*** Get JIRA instances configuration@@ -269,6 +269,64 @@ export async function createTicket(instanceId, ticketData) {};}+/**+ * Search JIRA issues by an arbitrary JQL string. STRICT variant — lets fetch+ * errors bubble so a caller can distinguish a transient API failure from a+ * legitimately empty result set (the CLAUDE.md sentinel rule). `fields` selects+ * the returned issue fields; `maxResults` caps the page.+ *+ * Returns `[{ key, summary, description, status, statusCategory, labels, updated, url }]`.+ */+export async function searchIssues(instanceId, jql, { fields = 'summary,status,labels,updated,description,resolutiondate', maxResults = 100 } = {}) {+ const config = await getInstances();+ const instance = config.instances[instanceId];++ if (!instance) {+ throw new Error(`JIRA instance ${instanceId} not found`);+ }++ const client = createJiraClient(instance);+ const response = await client.get('/rest/api/2/search', {+ params: { jql, fields, maxResults }+ });++ return (response.data.issues || []).map(issue => ({+ key: issue.key,+ summary: issue.fields.summary || '',+ description: issue.fields.description || '',+ status: issue.fields.status?.name || null,+ statusCategory: issue.fields.status?.statusCategory?.name || null,+ labels: issue.fields.labels || [],+ updated: issue.fields.updated || null,+ resolutiondate: issue.fields.resolutiondate || null,+ url: `${instance.baseUrl}/browse/${issue.key}`+ }));+}++/**+ * Add labels to an existing JIRA ticket without disturbing its other labels.+ * Jira's field-update API takes an `update.labels` array of `{ add: <label> }`+ * ops, so this is additive (unlike PUT-ing `fields.labels`, which replaces).+ */+export async function addLabels(instanceId, ticketId, labels = []) {+ const config = await getInstances();+ const instance = config.instances[instanceId];++ if (!instance) {+ throw new Error(`JIRA instance ${instanceId} not found`);+ }++ const toAdd = (Array.isArray(labels) ? labels : []).filter(l => typeof l === 'string' && l.trim());+ if (toAdd.length === 0) return { success: true, ticketId };++ const client = createJiraClient(instance);+ await client.put(`/rest/api/2/issue/${encodeURIComponent(ticketId)}`, {+ update: { labels: toAdd.map(name => ({ add: name })) }+ });++ return { success: true, ticketId };+}+/*** Update JIRA ticket*/@@ -667,6 +725,8 @@ export default {getBoards,getIssue,createTicket,+ searchIssues,+ addLabels,updateTicket,addComment,getTransitions,diff --git a/server/services/layeredIntelligence.js b/server/services/layeredIntelligence.jsindex cbfaaedf1c..584303765a 100644--- a/server/services/layeredIntelligence.js+++ b/server/services/layeredIntelligence.js@@ -25,6 +25,7 @@ import { readFile, writeFile, appendFile, realpath } from 'fs/promises';import { existsSync } from 'fs';import { DAY, tryReadFile, readJSONFile, safeJSONParse, PATHS } from '../lib/fileUtils.js';import { bufferedSpawn } from '../lib/bufferedSpawn.js';+import { createTicket, searchIssues, addLabels, escapeJql } from './jira.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@@ -32,6 +33,11 @@ import { bufferedSpawn } from '../lib/bufferedSpawn.js';export const LI_LABEL = 'layered-intelligence';export const LI_BLOCKING_LABEL = 'layered-intelligence:blocking';+// Jira labels can't contain spaces, and a ':' is unsafe on some Jira versions,+// so the Jira pause label swaps the ':' for a '-'. The base LI_LABEL is already+// Jira-safe (kebab, no colon) and is reused verbatim across all trackers.+export const LI_JIRA_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;@@ -535,6 +541,104 @@ export async function applyBlockingLabel({ cli, cwd, env, number, exec = runClireturn code === 0 ? { success: true } : { success: false, error: stderr };}+// ---------------------------------------------------------------------------+// Jira filer. Jira has no forge CLI — it goes through the PortOS Jira REST+// service (server/services/jira.js). Dedup + pause are label-based (same as the+// forges) via JQL, with the slug marker embedded in the ticket description.+// The Jira deps (search/create/addLabel) are injectable so tests drive the+// dispatch without a live Jira instance.+// ---------------------------------------------------------------------------++/**+ * Normalize a Jira status CATEGORY to `open` / `closed`. Jira's three canonical+ * categories are "To Do" / "In Progress" / "Done"; only "Done" counts as closed+ * for dedup + park. Anything unrecognized is treated as open so a custom+ * in-flight status can't slip past dedup.+ */+export function normalizeJiraState(statusCategory) {+ return (statusCategory || '').toLowerCase() === 'done' ? 'closed' : 'open';+}++/**+ * List existing layered-intelligence tickets in a Jira project (open + recently+ * closed) for the reasoner + dedup guard. Mirrors listForgeIssues' `{ ok, issues }`+ * failed-vs-empty contract: a thrown search is `ok:false` (do NOT file — a blind+ * dedup would duplicate); an empty result is `ok:true, issues:[]`.+ */+export async function listJiraIssues({ instanceId, projectKey, search = searchIssues } = {}) {+ if (!instanceId || !projectKey) return { ok: false, issues: [] };+ const jql = `project = "${escapeJql(projectKey)}" AND labels = "${LI_LABEL}" ORDER BY updated DESC`;+ const rows = await search(instanceId, jql).then(r => r, () => null);+ if (!Array.isArray(rows)) return { ok: false, issues: [] };+ return {+ ok: true,+ issues: rows.map(i => ({+ number: i.key || null,+ title: i.summary || '',+ body: i.description || '',+ state: normalizeJiraState(i.statusCategory),+ closedAt: i.resolutiondate || null,+ slug: extractSlugFromBody(i.description || '') || extractSlugFromBody(i.summary || '')+ }))+ };+}++/**+ * List OPEN blocking-labeled Jira tickets for the app (park check). `{ ok, issues }`+ * with the same failed-vs-empty distinction. JQL filters out Done so a resolved+ * blocking ticket un-parks the app automatically (matching the forge pause model).+ */+export async function listJiraBlockingIssues({ instanceId, projectKey, search = searchIssues } = {}) {+ if (!instanceId || !projectKey) return { ok: false, issues: [] };+ const jql = `project = "${escapeJql(projectKey)}" AND labels = "${LI_JIRA_BLOCKING_LABEL}" AND statusCategory != Done ORDER BY updated DESC`;+ const rows = await search(instanceId, jql).then(r => r, () => null);+ if (!Array.isArray(rows)) return { ok: false, issues: [] };+ return {+ ok: true,+ issues: rows.map(i => ({ number: i.key || null, title: i.summary || '', state: normalizeJiraState(i.statusCategory) }))+ };+}++/**+ * File ONE proposal ticket in a Jira project. Embeds the slug marker in the+ * description (searchable for dedup) and tags it with the layered-intelligence+ * label. Returns `{ success, key, url }` — Jira issues are keyed strings+ * (`PROJ-123`), not integers, so the handler resolves pause targets by key.+ */+export async function fileProposalToJira({ instanceId, projectKey, issueType = 'Task', title, body, slug, create = createTicket } = {}) {+ if (!instanceId || !projectKey) return { success: false, error: 'jira instance/project not configured' };+ const description = `${body}\n\n${slugMarker(slug)}`;+ const res = await create(instanceId, {+ projectKey,+ summary: title,+ description,+ issueType,+ labels: [LI_LABEL]+ }).then(r => r, (err) => ({ success: false, error: err?.message || 'jira create failed' }));+ if (!res?.success) return { success: false, error: res?.error || 'jira create failed' };+ return { success: true, key: res.ticketId || null, url: res.url || null };+}++/**+ * Resolve a Jira pause target to a concrete issue KEY. `"this"` → the just-filed+ * ticket's key; an integer → `<projectKey>-<n>` (a pre-existing ticket in the+ * same project). Returns null when it can't resolve (e.g. `"this"` but nothing+ * was filed, or no project key for an integer target).+ */+export function resolveJiraBlockKey(pause, filedKey, projectKey) {+ if (!pause) return null;+ if (pause.blockOnIssue === 'this') return filedKey || null;+ if (Number.isInteger(pause.blockOnIssue) && projectKey) return `${projectKey}-${pause.blockOnIssue}`;+ return null;+}++/** Apply the Jira blocking label to an existing ticket (pause). Returns `{ success }`. */+export async function applyJiraBlockingLabel({ instanceId, key, addLabel = addLabels } = {}) {+ if (!instanceId || !key) return { success: false, error: 'no jira ticket key' };+ const res = await addLabel(instanceId, key, [LI_JIRA_BLOCKING_LABEL]).then(r => r, (err) => ({ success: false, error: err?.message }));+ return res?.success ? { success: true } : { success: false, error: res?.error || 'jira label failed' };+}+/*** 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 headingdiff --git a/server/services/layeredIntelligence.test.js b/server/services/layeredIntelligence.test.jsindex f657ff8d28..7c56f17b86 100644--- a/server/services/layeredIntelligence.test.js+++ b/server/services/layeredIntelligence.test.js@@ -30,9 +30,16 @@ import {fileProposalToForge,ensureForgeLabels,applyBlockingLabel,+ normalizeJiraState,+ listJiraIssues,+ listJiraBlockingIssues,+ fileProposalToJira,+ resolveJiraBlockKey,+ applyJiraBlockingLabel,CLOSED_SUPPRESSION_MS,LI_LABEL,- LI_BLOCKING_LABEL+ LI_BLOCKING_LABEL,+ LI_JIRA_BLOCKING_LABEL} from './layeredIntelligence.js';describe('defaultLayeredIntelligenceConfig', () => {@@ -612,3 +619,102 @@ describe('forge I/O (injected exec)', () => {expect(PROPOSAL_SCOPES).toEqual(['app-improvement', 'app-data-gap', 'loop-meta', 'portos-self']);});});++describe('Jira filer', () => {+ it('normalizeJiraState maps only the Done category to closed', () => {+ expect(normalizeJiraState('Done')).toBe('closed');+ expect(normalizeJiraState('done')).toBe('closed');+ expect(normalizeJiraState('In Progress')).toBe('open');+ expect(normalizeJiraState('To Do')).toBe('open');+ expect(normalizeJiraState('')).toBe('open');+ expect(normalizeJiraState(null)).toBe('open');+ });++ it('LI_JIRA_BLOCKING_LABEL is space-and-colon-free (Jira-safe)', () => {+ expect(LI_JIRA_BLOCKING_LABEL).toBe('layered-intelligence-blocking');+ expect(LI_JIRA_BLOCKING_LABEL).not.toMatch(/[\s:]/);+ // The base label is reused verbatim and is already Jira-safe.+ expect(LI_LABEL).not.toMatch(/[\s:]/);+ });++ it('listJiraIssues maps rows and reports ok:true on a successful search', async () => {+ const search = vi.fn().mockResolvedValue([+ { key: 'PROJ-1', summary: 'Do a thing', description: `body ${slugMarker('do-a-thing')}`, statusCategory: 'To Do', resolutiondate: null },+ { key: 'PROJ-2', summary: 'Done thing', description: 'no marker', statusCategory: 'Done', resolutiondate: '2026-07-01T00:00:00.000+0000' }+ ]);+ const res = await listJiraIssues({ instanceId: 'i', projectKey: 'PROJ', search });+ expect(res.ok).toBe(true);+ expect(res.issues[0]).toMatchObject({ number: 'PROJ-1', state: 'open', slug: 'do-a-thing' });+ expect(res.issues[1]).toMatchObject({ number: 'PROJ-2', state: 'closed', closedAt: '2026-07-01T00:00:00.000+0000' });+ // JQL scopes to the project and base LI label.+ expect(search.mock.calls[0][1]).toContain('project = "PROJ"');+ expect(search.mock.calls[0][1]).toContain(`labels = "${LI_LABEL}"`);+ });++ it('listJiraIssues reports ok:false on a thrown search (failed != empty)', async () => {+ const search = vi.fn().mockRejectedValue(new Error('boom'));+ const res = await listJiraIssues({ instanceId: 'i', projectKey: 'PROJ', search });+ expect(res.ok).toBe(false);+ expect(res.issues).toEqual([]);+ });++ it('listJiraIssues reports ok:false when instance/project missing', async () => {+ expect((await listJiraIssues({ instanceId: '', projectKey: 'PROJ' })).ok).toBe(false);+ expect((await listJiraIssues({ instanceId: 'i', projectKey: '' })).ok).toBe(false);+ });++ it('listJiraBlockingIssues filters to the blocking label and non-Done', async () => {+ const search = vi.fn().mockResolvedValue([{ key: 'PROJ-9', summary: 'blocker', statusCategory: 'In Progress' }]);+ const res = await listJiraBlockingIssues({ instanceId: 'i', projectKey: 'PROJ', search });+ expect(res.ok).toBe(true);+ expect(res.issues[0]).toMatchObject({ number: 'PROJ-9', state: 'open' });+ expect(search.mock.calls[0][1]).toContain(`labels = "${LI_JIRA_BLOCKING_LABEL}"`);+ expect(search.mock.calls[0][1]).toContain('statusCategory != Done');+ });++ it('fileProposalToJira embeds the slug marker + LI label and returns the key/url', async () => {+ const create = vi.fn().mockResolvedValue({ success: true, ticketId: 'PROJ-10', url: 'https://j/browse/PROJ-10' });+ const res = await fileProposalToJira({ instanceId: 'i', projectKey: 'PROJ', title: 'T', body: 'B', slug: 'add-x', create });+ expect(res).toEqual({ success: true, key: 'PROJ-10', url: 'https://j/browse/PROJ-10' });+ const payload = create.mock.calls[0][1];+ expect(payload).toMatchObject({ projectKey: 'PROJ', summary: 'T', issueType: 'Task', labels: [LI_LABEL] });+ expect(payload.description).toContain(slugMarker('add-x'));+ expect(payload.description).toContain('B');+ });++ it('fileProposalToJira surfaces a create failure rather than throwing', async () => {+ const create = vi.fn().mockRejectedValue(new Error('403'));+ const res = await fileProposalToJira({ instanceId: 'i', projectKey: 'PROJ', title: 'T', body: 'B', slug: 's', create });+ expect(res.success).toBe(false);+ expect(res.error).toContain('403');+ });++ it('fileProposalToJira refuses when instance/project missing', async () => {+ const res = await fileProposalToJira({ instanceId: '', projectKey: 'PROJ', title: 'T', body: 'B', slug: 's' });+ expect(res.success).toBe(false);+ });++ it('resolveJiraBlockKey resolves "this" to the filed key and an integer to <project>-<n>', () => {+ expect(resolveJiraBlockKey({ blockOnIssue: 'this' }, 'PROJ-10', 'PROJ')).toBe('PROJ-10');+ expect(resolveJiraBlockKey({ blockOnIssue: 42 }, null, 'PROJ')).toBe('PROJ-42');+ // "this" with nothing filed → null; integer with no project → null; no pause → null.+ expect(resolveJiraBlockKey({ blockOnIssue: 'this' }, null, 'PROJ')).toBe(null);+ expect(resolveJiraBlockKey({ blockOnIssue: 42 }, null, '')).toBe(null);+ expect(resolveJiraBlockKey(null, 'PROJ-1', 'PROJ')).toBe(null);+ });++ it('applyJiraBlockingLabel adds the Jira blocking label to the key', async () => {+ const addLabel = vi.fn().mockResolvedValue({ success: true });+ const res = await applyJiraBlockingLabel({ instanceId: 'i', key: 'PROJ-10', addLabel });+ expect(res.success).toBe(true);+ expect(addLabel).toHaveBeenCalledWith('i', 'PROJ-10', [LI_JIRA_BLOCKING_LABEL]);+ });++ it('applyJiraBlockingLabel refuses without a key and surfaces a thrown error', async () => {+ expect((await applyJiraBlockingLabel({ instanceId: 'i', key: null })).success).toBe(false);+ const addLabel = vi.fn().mockRejectedValue(new Error('nope'));+ const res = await applyJiraBlockingLabel({ instanceId: 'i', key: 'PROJ-1', addLabel });+ expect(res.success).toBe(false);+ expect(res.error).toContain('nope');+ });+});