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
review: sentinel failed-vs-empty tracker reads, normalize GitLab opened state, confine custom file refs, honor openIssues toggle, reuse safeJSONParse (#2262)
Adam Eivy61a08b69e863
diff --git a/server/lib/validation.js b/server/lib/validation.jsindex edc4eb61ae..a63c097f4f 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -128,7 +128,13 @@ export const layeredIntelligenceConfigSchema = z.object({openIssues: z.boolean().optional(),custom: z.array(z.object({type: z.enum(['file']),+ // A safe repo-relative path — reject absolute paths and `..` traversal so a+ // custom source can't read files outside the app repo into the LLM prompt.+ // gatherSources also enforces this at read time (defense in depth).ref: z.string().min(1).max(500)+ .refine(r => !r.startsWith('/') && !r.split(/[/\\]/).includes('..'), {+ message: 'ref must be a repo-relative path (no leading / and no ".." segments)'+ })})).optional()}).optional(),rules: z.string().max(8000).optional(),diff --git a/server/services/autonomousJobs/layeredIntelligenceHandler.js b/server/services/autonomousJobs/layeredIntelligenceHandler.jsindex ba67335985..49e8c97f54 100644--- a/server/services/autonomousJobs/layeredIntelligenceHandler.js+++ b/server/services/autonomousJobs/layeredIntelligenceHandler.js@@ -33,7 +33,8 @@ import {extractPlanSlugs} from '../layeredIntelligence.js'import { resolveAppWorkTracker } from '../../lib/workTracker.js'-import { tryReadFile } from '../../lib/fileUtils.js'+import { tryReadFile, safeJSONParse } from '../../lib/fileUtils.js'+import { stripCodeFences } from '../../lib/aiProvider.js'import { join } from 'path'/**@@ -83,13 +84,20 @@ export async function processApp(app, deps = {}) {return { app: app.id, action: 'skipped', reason: 'jira-filer-not-implemented' }}- // ---- Park check (forge/jira only; plan has no issue to block on) ----+ // ---- 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 })- if (isAppParked(blocking)) {- console.log(`⏸️ Layered Intelligence: ${app.name} parked on ${blocking.length} blocking issue(s) — skipping`)+ // 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) {+ console.warn(`⚠️ Layered Intelligence: ${app.name} blocking-issue read failed — skipping this run`)await recordRun(app, config, now)- return { app: app.id, action: 'parked', blocking: blocking.length }+ return { app: app.id, action: 'skipped', reason: 'blocking-read-failed' }+ }+ if (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 }}}@@ -97,9 +105,16 @@ export async function processApp(app, deps = {}) {const sources = await gatherSources(app, config)let openIssues = []let existingIssues = []+ let trackerReadFailed = falseif (filer === 'forge' && forgeCli) {- existingIssues = await listForgeIssues({ cli: forgeCli, cwd })- openIssues = existingIssues.filter(i => i.state === 'open')+ const listed = await listForgeIssues({ cli: forgeCli, cwd })+ trackerReadFailed = !listed.ok+ existingIssues = listed.issues+ // Only surface open issues to the reasoner when the openIssues source is on;+ // dedup still runs against ALL existing issues regardless of the toggle.+ if (config.sources?.openIssues !== false) {+ openIssues = existingIssues.filter(i => i.state === 'open')+ }} else if (filer === 'plan' && cwd) {const planContent = await tryReadFile(join(cwd, 'PLAN.md'))const planSlugs = extractPlanSlugs(planContent || '')@@ -129,6 +144,11 @@ export async function processApp(app, deps = {}) {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 (trackerReadFailed) {+ // Dedup would be blind against a failed tracker read — never file, or a+ // transient forge blip files a duplicate. Retry next run (CLAUDE.md sentinel).+ console.warn(`⚠️ Layered Intelligence: ${app.name} tracker read failed — suppressing proposal to avoid a blind duplicate`)+ filedAction = 'tracker-read-failed'} else if (isProposalDuplicate({ slug: proposal.slug, existingIssues, now })) {console.log(`♻️ Layered Intelligence: ${app.name} proposal "${proposal.slug}" is a duplicate — suppressed`)filedAction = 'duplicate'@@ -198,15 +218,14 @@ async function resolveLLM(config, injected) {}}-/** Parse LLM JSON, returning null on failure (a no-op for that app). */+/**+ * Parse LLM JSON, returning null on failure (a no-op for that app). Reuses the+ * shared `stripCodeFences` + `safeJSONParse` helpers rather than a local+ * try/catch (repo convention: no non-boundary try/catch).+ */function safeParse(text) {if (typeof text !== 'string') return null- const cleaned = text.trim().replace(/^```(?:json)?\n?/, '').replace(/\n?```$/, '').trim()- try {- return JSON.parse(cleaned)- } catch {- return null- }+ return safeJSONParse(stripCodeFences(text), null, { logError: false })}/**diff --git a/server/services/autonomousJobs/layeredIntelligenceHandler.test.js b/server/services/autonomousJobs/layeredIntelligenceHandler.test.jsindex 9be24d69cb..7a882f4238 100644--- a/server/services/autonomousJobs/layeredIntelligenceHandler.test.js+++ b/server/services/autonomousJobs/layeredIntelligenceHandler.test.js@@ -21,7 +21,9 @@ vi.mock('../../lib/workTracker.js', () => ({// orchestration (park → gather → reason → decide → act → pause) is isolated.const forgeState = {existing: [],+ existingOk: true,blocking: [],+ blockingOk: true,fileResult: { success: true, number: 100 },filed: [],blockingApplied: []@@ -31,8 +33,9 @@ vi.mock('../layeredIntelligence.js', async (importOriginal) => {return {...actual,gatherSources: vi.fn().mockResolvedValue({ goals: 'g' }),- listForgeIssues: vi.fn(async () => forgeState.existing),- listBlockingIssues: vi.fn(async () => forgeState.blocking),+ // Listers now return { ok, issues }; forgeState.existingOk toggles a failed read.+ listForgeIssues: vi.fn(async () => ({ ok: forgeState.existingOk, issues: forgeState.existing })),+ listBlockingIssues: vi.fn(async () => ({ ok: forgeState.blockingOk, issues: forgeState.blocking })),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 }))@@ -52,7 +55,9 @@ beforeEach(() => {vi.clearAllMocks();updateAppMock.mockResolvedValue({});forgeState.existing = [];+ forgeState.existingOk = true;forgeState.blocking = [];+ forgeState.blockingOk = true;forgeState.fileResult = { success: true, number: 100 };forgeState.filed = [];forgeState.blockingApplied = [];@@ -159,6 +164,33 @@ describe('processApp', () => {expect(out.reason).toContain('timeout');});+ it('does NOT file when the tracker issue-list read failed (avoids blind duplicate)', async () => {+ forgeState.existingOk = false;+ const callLLM = reasoner({ proposal: { scope: 'app-improvement', slug: 'add-x', title: 'Add X' } });+ const out = await processApp(enabledApp(), { callLLM });+ expect(out.action).toBe('tracker-read-failed');+ expect(forgeState.filed).toHaveLength(0);+ });++ it('skips (does not reason) when the blocking-issue read failed', async () => {+ forgeState.blockingOk = false;+ const callLLM = reasoner({ proposal: { scope: 'app-improvement', slug: 'add-x', title: 'Add X' } });+ const out = await processApp(enabledApp(), { callLLM });+ expect(out.action).toBe('skipped');+ expect(out.reason).toBe('blocking-read-failed');+ expect(callLLM).not.toHaveBeenCalled();+ });++ it('does NOT pass open issues to the prompt when the openIssues source is off (but still dedups)', async () => {+ forgeState.existing = [{ slug: 'add-x', state: 'open' }];+ const app = enabledApp();+ app.layeredIntelligence.sources = { openIssues: false };+ const callLLM = reasoner({ proposal: { scope: 'app-improvement', slug: 'add-x', title: 'Add X' } });+ const out = await processApp(app, { callLLM });+ // Dedup still fires against existing issues regardless of the prompt toggle.+ expect(out.action).toBe('duplicate');+ });+it('does NOT pause a plan-tracked app (no issue to block on)', async () => {resolveTrackerMock.mockResolvedValue({ resolved: 'plan', forge: null });const callLLM = reasoner({diff --git a/server/services/layeredIntelligence.js b/server/services/layeredIntelligence.jsindex d314e59cf8..c6f885eee6 100644--- a/server/services/layeredIntelligence.js+++ b/server/services/layeredIntelligence.js@@ -20,10 +20,10 @@*/import { spawn } from 'child_process';-import { join } from 'path';+import { join, resolve, relative, isAbsolute } from 'path';import { readFile, writeFile, appendFile } from 'fs/promises';import { existsSync } from 'fs';-import { DAY, tryReadFile, readJSONFile, PATHS } from '../lib/fileUtils.js';+import { DAY, tryReadFile, readJSONFile, safeJSONParse, 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@@ -335,56 +335,86 @@ export async function gatherSources(app, config, { cosPath = PATHS.cos } = {}) {}for (const custom of src.custom || []) {if (custom?.type === 'file' && typeof custom.ref === 'string' && repo) {- const content = await tryReadFile(join(repo, custom.ref));+ // Confine the ref to the app repo: an absolute path or a `../` escape must+ // not leak arbitrary readable files into the LLM prompt. resolve() ++ // relative() rejects anything that lands outside repoPath.+ const abs = resolve(repo, custom.ref);+ const rel = relative(repo, abs);+ if (rel.startsWith('..') || isAbsolute(rel)) {+ console.warn(`⚠️ Layered Intelligence: custom source "${custom.ref}" escapes repo — skipped`);+ continue;+ }+ const content = await tryReadFile(abs);if (content) out[`custom:${custom.ref}`] = content.slice(0, 8000);}}return out;}+/**+ * Normalize a forge issue state to `open` / `closed`. GitLab reports `opened`+ * (and `closed`/`locked`); GitHub reports `open`/`closed`. Anything that isn't a+ * recognized closed/locked state is treated as open so dedup + park don't miss a+ * GitLab-`opened` issue. (`merged` never applies to issues.)+ */+export function normalizeIssueState(state) {+ const s = (state || '').toLowerCase();+ if (s === 'closed' || s === 'locked') return 'closed';+ return 'open';+}+/*** 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.+ * so the handler can feed them to the reasoner and run the dedup guard.+ *+ * Returns `{ ok, issues }` — `ok:false` means the tracker read FAILED (CLI error+ * or unparseable output), which is NOT the same as "no existing issues" (`ok:true,+ * issues:[]`). The handler must NOT file when the read failed, or a transient+ * `gh` blip would defeat dedup and file a duplicate (CLAUDE.md sentinel rule).*/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 || '')- }));+ if (code !== 0) return { ok: false, issues: [] };+ if (!stdout.trim()) return { ok: true, issues: [] };+ const parsed = safeJSONParse(stdout, null, { logError: false });+ if (!Array.isArray(parsed)) return { ok: false, issues: [] };+ return {+ ok: true,+ issues: parsed.map(i => ({+ number: i.number ?? i.iid ?? null,+ title: i.title || '',+ body: i.body || i.description || '',+ state: normalizeIssueState(i.state),+ 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. */+/**+ * List OPEN blocking-labeled issues for the app (park check). Returns+ * `{ ok, issues }` with the same failed-vs-empty distinction as listForgeIssues.+ */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 [];- }+ if (code !== 0) return { ok: false, issues: [] };+ if (!stdout.trim()) return { ok: true, issues: [] };+ const parsed = safeJSONParse(stdout, null, { logError: false });+ if (!Array.isArray(parsed)) return { ok: false, issues: [] };+ return {+ ok: true,+ issues: parsed.map(i => ({+ number: i.number ?? i.iid ?? null,+ title: i.title || '',+ state: normalizeIssueState(i.state)+ }))+ };}/**diff --git a/server/services/layeredIntelligence.test.js b/server/services/layeredIntelligence.test.jsindex 1c57af8de2..b822116c63 100644--- a/server/services/layeredIntelligence.test.js+++ b/server/services/layeredIntelligence.test.js@@ -20,6 +20,8 @@ import {buildPrompt,extractPlanSlugs,appendProposalToPlan,+ gatherSources,+ normalizeIssueState,listForgeIssues,listBlockingIssues,fileProposalToForge,@@ -374,6 +376,57 @@ describe('appendProposalToPlan', () => {});});+describe('normalizeIssueState', () => {+ it('maps GitLab "opened" and GitHub "open" to open', () => {+ expect(normalizeIssueState('opened')).toBe('open');+ expect(normalizeIssueState('OPEN')).toBe('open');+ });+ it('maps closed/locked to closed', () => {+ expect(normalizeIssueState('closed')).toBe('closed');+ expect(normalizeIssueState('locked')).toBe('closed');+ });+ it('treats unknown/empty as open (fail-open so dedup does not miss)', () => {+ expect(normalizeIssueState('')).toBe('open');+ expect(normalizeIssueState(undefined)).toBe('open');+ });+});++describe('gatherSources custom file confinement', () => {+ let dir;+ beforeEach(async () => { dir = await mkdtemp(join(tmpdir(), 'lil-src-')); });+ afterEach(async () => { await rm(dir, { recursive: true, force: true }); });++ it('reads a safe relative custom file', async () => {+ await writeFile(join(dir, 'METRICS.md'), 'metric content');+ const out = await gatherSources(+ { repoPath: dir },+ { sources: { custom: [{ type: 'file', ref: 'METRICS.md' }] } }+ );+ expect(out['custom:METRICS.md']).toBe('metric content');+ });++ it('refuses a "../" traversal ref (no arbitrary file leak into the prompt)', async () => {+ // A file one level ABOVE the repo must never be read.+ await writeFile(join(dir, 'secret.txt'), 'SECRET');+ const sub = join(dir, 'repo');+ const { mkdir } = await import('fs/promises');+ await mkdir(sub, { recursive: true });+ const out = await gatherSources(+ { repoPath: sub },+ { sources: { custom: [{ type: 'file', ref: '../secret.txt' }] } }+ );+ expect(Object.keys(out)).not.toContain('custom:../secret.txt');+ });++ it('refuses an absolute-path ref', async () => {+ const out = await gatherSources(+ { repoPath: dir },+ { sources: { custom: [{ type: 'file', ref: '/etc/hosts' }] } }+ );+ expect(Object.keys(out).some(k => k.startsWith('custom:'))).toBe(false);+ });+});+describe('forge I/O (injected exec)', () => {it('listForgeIssues parses gh JSON and extracts slugs', async () => {const exec = vi.fn().mockResolvedValue({@@ -383,21 +436,44 @@ describe('forge I/O (injected exec)', () => {{ number: 2, title: 'B', body: 'no slug', state: 'CLOSED', closedAt: '2026-07-01T00:00:00Z' }])});- const issues = await listForgeIssues({ cli: 'gh', cwd: '/x', exec });+ const { ok, issues } = await listForgeIssues({ cli: 'gh', cwd: '/x', exec });+ expect(ok).toBe(true);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 () => {+ it('listForgeIssues normalizes GitLab "opened" state to open', async () => {+ const exec = vi.fn().mockResolvedValue({+ code: 0,+ stdout: JSON.stringify([{ iid: 7, title: 'G', description: `d ${slugMarker('g-slug')}`, state: 'opened' }])+ });+ const { ok, issues } = await listForgeIssues({ cli: 'glab', cwd: '/x', exec });+ expect(ok).toBe(true);+ expect(issues[0].number).toBe(7);+ expect(issues[0].state).toBe('open'); // 'opened' → 'open'+ expect(issues[0].slug).toBe('g-slug');+ });++ it('listForgeIssues signals ok:false on CLI failure (tracker unavailable ≠ empty)', async () => {const exec = vi.fn().mockResolvedValue({ code: 1, stdout: '' });- expect(await listForgeIssues({ cli: 'gh', cwd: '/x', exec })).toEqual([]);+ expect(await listForgeIssues({ cli: 'gh', cwd: '/x', exec })).toEqual({ ok: false, issues: [] });+ });++ it('listForgeIssues signals ok:true, [] on a successful empty read', async () => {+ const exec = vi.fn().mockResolvedValue({ code: 0, stdout: '' });+ expect(await listForgeIssues({ cli: 'gh', cwd: '/x', exec })).toEqual({ ok: true, issues: [] });+ });++ it('listForgeIssues signals ok:false on unparseable output', async () => {+ const exec = vi.fn().mockResolvedValue({ code: 0, stdout: 'not json' });+ expect(await listForgeIssues({ cli: 'gh', cwd: '/x', exec })).toEqual({ ok: false, issues: [] });});- it('listBlockingIssues uses the blocking label', async () => {+ it('listBlockingIssues uses the blocking label and normalizes state', 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(res).toEqual({ ok: true, issues: [{ number: 5, title: '', state: 'open' }] });expect(exec.mock.calls[0][1]).toContain(LI_BLOCKING_LABEL);});