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: report whether gh can reach the forge, so a blocked CLI stops looking like a quiet repo
[._.]/ Adam Eivyf0384b0348db
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 220bb59596..766822621a 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -44,6 +44,7 @@## Internal+- **System Health now reports whether the GitHub CLI can actually reach GitHub, instead of leaving a blocked `gh` invisible.** Around thirty places in PortOS shell out to `gh` and turn any failure into an empty result, so a CLI that cannot open a connection is indistinguishable from a repo with nothing open: the PR watcher sees no pull requests, branch and issue reconciliation see nothing to reconcile, and an agent told to open a PR finishes reporting success having opened none. That is exactly how a recent agent run ended — it committed and pushed its branch over SSH, which was unaffected, and then silently could not create the pull request. `/system-health` now carries a `forge` block that distinguishes the four states that were previously one: working, not installed, installed but not logged in, and installed and authenticated but unable to connect. Only the last two raise a warning — an install that never had `gh` has opted out of those features rather than broken them. The unreachable case names the cause that is easiest to misread as a local bug: an outbound firewall such as Little Snitch denies the connection rather than refusing it, which surfaces as "bad file descriptor" and looks nothing like a network problem. The probe uses the one GitHub endpoint that does not consume API quota, and its result is cached for a minute so a polled health page does not spawn a process per request.- **Route handlers now share one pagination parser.** Twenty-two places across fifteen route files hand-rolled `parseInt(req.query.limit, 10) || N` instead of calling the pagination helper that already existed. That spelling has two real consequences: `?limit=0` and negative values are falsy, so they silently fell back to the default rather than being clamped, and several endpoints had no upper bound at all — `?limit=999999` was passed straight through to the datastore. Every migrated endpoint keeps its previous default, and the ones that were unbounded gained a generous ceiling. Three sites were deliberately left alone because their behaviour genuinely differs: two treat a missing or zero limit as meaningful, and one uses an absent limit to mean "no limit". The helper's boundary behaviour now has direct test coverage.- **Slashdo command loading moved out of the general file utilities.** Two hundred lines of slashdo-specific command loading and template rendering lived in `fileUtils.js` alongside generic JSON, path and upload helpers, while a separate module already owned other slashdo concerns — so working on one feature meant reaching into two unrelated modules. The loading code now has its own module, registered in the library barrel and catalog. Behaviour is unchanged: the moved code is byte-identical to what was removed.- **[issue-3264] Fixed a development-mode freeze that left panels loading and buttons stuck after one click.** Under `npm run dev`, a mount guard used across fourteen components and hooks was never re-armed after React StrictMode double-mounts a component, so anything gated on it silently stopped updating — the music generator panel sat on "Loading generators…" forever, and every button backed by the shared async-action hook stayed disabled after its first click. All fourteen now use the shared hook that re-arms correctly, and a test fails if the broken shape is reintroduced anywhere in the client.diff --git a/server/routes/health.test.js b/server/routes/health.test.jsindex bd1b4be852..e25f9af8c7 100644--- a/server/routes/health.test.js+++ b/server/routes/health.test.js@@ -6,6 +6,7 @@ import systemHealthRoutes from './systemHealth.js';import { listProcesses } from '../services/pm2.js';import { getSelf } from '../services/instances.js';import { isAuthEnabled } from '../services/auth.js';+import { checkGhHealth } from '../services/github.js';vi.mock('../services/pm2.js', () => ({listProcesses: vi.fn().mockResolvedValue([])@@ -50,6 +51,14 @@ vi.mock('../lib/db.js', () => ({checkHealth: vi.fn().mockResolvedValue({ connected: false, hasSchema: false })}));+// The real probe spawns `gh` and hits the network — mock it, and default to a+// healthy forge so the existing cases keep their warning counts.+vi.mock('../services/github.js', () => ({+ checkGhHealth: vi.fn().mockResolvedValue({+ status: 'ok', ok: true, detail: null, remedy: null, checkedAt: '2026-01-01T00:00:00.000Z'+ })+}));+vi.mock('../services/settings.js', () => ({getSettings: vi.fn().mockResolvedValue({}),updateSettings: vi.fn().mockResolvedValue({}),@@ -148,6 +157,73 @@ describe('System Health Routes', () => {expect(response.body.topProcesses.map(p => p.name)).toEqual(['big', 'mid', 'small']);});+ describe('GET /health/details — forge (gh CLI) reachability', () => {+ it('reports a healthy forge without raising a warning', async () => {+ const response = await request(app).get('/api/system/health/details');+ expect(response.body.forge).toMatchObject({ status: 'ok', ok: true });+ expect((response.body.warnings || []).filter(w => w.type === 'forge')).toHaveLength(0);+ });++ it('warns, with the remedy, when gh is installed but cannot reach the forge', async () => {+ // The failure this exists for: every `gh` call site swallows the error+ // into an empty list, so a blocked CLI looks like a repo with nothing+ // open. Without this warning the only symptom is agents silently not+ // filing PRs.+ checkGhHealth.mockResolvedValueOnce({+ status: 'unreachable',+ ok: false,+ detail: 'dial tcp 140.82.116.6:443: connect: bad file descriptor',+ remedy: 'allow the gh binary to reach api.github.com',+ checkedAt: '2026-01-01T00:00:00.000Z'+ });+ const response = await request(app).get('/api/system/health/details');++ expect(response.body.forge).toMatchObject({ status: 'unreachable', ok: false });+ const forgeWarnings = (response.body.warnings || []).filter(w => w.type === 'forge');+ expect(forgeWarnings).toHaveLength(1);+ expect(forgeWarnings[0].message).toContain('unreachable');+ expect(forgeWarnings[0].message).toContain('allow the gh binary');+ expect(response.body.overallHealth).toBe('warning');+ });++ it('warns when gh is present but unauthenticated', async () => {+ checkGhHealth.mockResolvedValueOnce({+ status: 'not-authenticated', ok: false, detail: 'gh auth login', remedy: 'Run `gh auth login`', checkedAt: null+ });+ const response = await request(app).get('/api/system/health/details');+ expect((response.body.warnings || []).filter(w => w.type === 'forge')).toHaveLength(1);+ });++ it('stays quiet when gh was never installed — that is opting out, not a fault', async () => {+ checkGhHealth.mockResolvedValueOnce({+ status: 'not-installed', ok: false, detail: 'spawn gh ENOENT', remedy: 'Install the GitHub CLI', checkedAt: null+ });+ const response = await request(app).get('/api/system/health/details');++ expect(response.body.forge).toMatchObject({ status: 'not-installed' });+ expect((response.body.warnings || []).filter(w => w.type === 'forge')).toHaveLength(0);+ });++ it('does not downgrade an already-critical verdict to warning', async () => {+ listProcesses.mockResolvedValueOnce([+ { name: 'broken', status: 'errored', restarts: 1, unstableRestarts: 0, cpu: 0, memory: 0 }+ ]);+ checkGhHealth.mockResolvedValueOnce({+ status: 'unreachable', ok: false, detail: null, remedy: null, checkedAt: null+ });+ const response = await request(app).get('/api/system/health/details');+ expect(response.body.overallHealth).toBe('critical');+ });++ it('degrades to an error verdict rather than 500ing when the probe itself throws', async () => {+ checkGhHealth.mockRejectedValueOnce(new Error('probe blew up'));+ const response = await request(app).get('/api/system/health/details');++ expect(response.status).toBe(200);+ expect(response.body.forge).toMatchObject({ status: 'error', ok: false });+ });+ });+describe('PUT /health/thresholds', () => {it('rejects invalid numbers', async () => {const response = await request(app)diff --git a/server/routes/systemHealth.js b/server/routes/systemHealth.jsindex 60a51a13a1..fcc8f00f3a 100644--- a/server/routes/systemHealth.js+++ b/server/routes/systemHealth.js@@ -11,6 +11,7 @@ import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { getMemoryStats } from '../lib/memoryStats.js';import { formatBytes } from '../lib/fileUtils.js';import { getSettings, updateSettingsWith } from '../services/settings.js';+import { checkGhHealth } from '../services/github.js';import { isAuthEnabled } from '../services/auth.js';import { getHttpsEnabledAtBoot } from '../lib/httpsState.js';@@ -76,7 +77,7 @@ router.get('/health/details', asyncHandler(async (req, res) => {const startTime = Date.now();// Gather data in parallel- const [pm2Processes, appStatusSummary, cosStatus, self, dbHealth, version, diskStats, memStats, thresholds] = await Promise.all([+ const [pm2Processes, appStatusSummary, cosStatus, self, dbHealth, version, diskStats, memStats, thresholds, forgeHealth] = await Promise.all([listProcesses().catch(() => []),apps.getAppStatusSummary().catch(() => ({ total: 0, online: 0, stopped: 0, notStarted: 0, unknown: 0, degraded: false, unmanaged: 0 })),cos.getStatus().catch(() => null),@@ -85,7 +86,8 @@ router.get('/health/details', asyncHandler(async (req, res) => {getCurrentVersion().catch(() => null),statfs('/').catch(() => null),getMemoryStats(),- loadThresholds()+ loadThresholds(),+ checkGhHealth().catch(() => ({ status: 'error', ok: false, detail: 'Health check failed', remedy: null, checkedAt: null }))]);const memUsagePercent = Math.round((memStats.used / memStats.total) * 100);@@ -204,6 +206,20 @@ router.get('/health/details', asyncHandler(async (req, res) => {warnings.push({ type: 'database', message: 'PostgreSQL connected but schema missing' });}+ // A `gh` that cannot reach the forge does not fail loudly anywhere else: the+ // call sites that read pull requests and issues swallow the error into an+ // empty list, so a blocked or unauthenticated CLI looks exactly like a repo+ // with nothing open — and an agent asked to file a PR reports success having+ // filed none. Warn only when gh is present but unusable; an install that+ // never had gh has opted out of those features rather than broken them.+ if (!forgeHealth.ok && forgeHealth.status !== 'not-installed') {+ if (overallHealth !== 'critical') overallHealth = 'warning';+ warnings.push({+ type: 'forge',+ message: `GitHub CLI unusable (${forgeHealth.status})${forgeHealth.remedy ? ` — ${forgeHealth.remedy}` : ''}`+ });+ }+// CoS statusconst cosInfo = cosStatus ? {running: cosStatus.running,@@ -266,6 +282,7 @@ router.get('/health/details', asyncHandler(async (req, res) => {apps: appStats,cos: cosInfo,database: dbHealth,+ forge: forgeHealth,thresholds,topProcesses: [...pm2Processes].sort((a, b) => (b.memory || 0) - (a.memory || 0))diff --git a/server/services/github.ghHealth.test.js b/server/services/github.ghHealth.test.jsnew file mode 100644index 0000000000..fbaf205151--- /dev/null+++ b/server/services/github.ghHealth.test.js@@ -0,0 +1,182 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { EventEmitter } from 'events';++// `github.js` reaches for the data dir at module load; keep it off the real one.+vi.mock('../lib/fileUtils.js', () => ({+ PATHS: { root: '/mock', data: '/mock/data' },+ readJSONFile: vi.fn().mockResolvedValue({ repos: {}, secrets: {} }),+ atomicWrite: vi.fn().mockResolvedValue(undefined),+ ensureDir: vi.fn().mockResolvedValue(undefined)+}));++vi.mock('./settings.js', () => ({+ getSettings: vi.fn().mockResolvedValue({}),+ updateSettings: vi.fn().mockResolvedValue(undefined)+}));++const spawnMock = vi.fn();+vi.mock('child_process', () => ({ spawn: (...args) => spawnMock(...args) }));++const { classifyGhProbe, ghRemedy, checkGhHealth, __resetGhHealthCache } = await import('./github.js');++/** A fake `gh` child that emits the given outcome on the next tick. */+function fakeChild({ code = 0, stderr = '', spawnError = null } = {}) {+ const child = new EventEmitter();+ child.stdout = new EventEmitter();+ child.stderr = new EventEmitter();+ child.kill = vi.fn();+ setImmediate(() => {+ if (stderr) child.stderr.emit('data', Buffer.from(stderr));+ if (spawnError) child.emit('error', spawnError);+ else child.emit('close', code);+ });+ return child;+}++describe('classifyGhProbe', () => {+ it('reports ok on a clean exit', () => {+ expect(classifyGhProbe({ code: 0 })).toEqual({ status: 'ok', detail: null });+ });++ it('reports not-installed only for ENOENT, and error for other spawn faults', () => {+ const enoent = Object.assign(new Error('spawn gh ENOENT'), { code: 'ENOENT' });+ expect(classifyGhProbe({ spawnError: enoent }).status).toBe('not-installed');++ const eacces = Object.assign(new Error('spawn gh EACCES'), { code: 'EACCES' });+ expect(classifyGhProbe({ spawnError: eacces }).status).toBe('error');+ });++ it('classifies an outbound firewall denial as unreachable, not a local error', () => {+ // Little Snitch (and any NetworkExtension content filter) denies the+ // connect() rather than refusing it, and Go reports EBADF. Reading that as+ // a local bug is exactly the misdiagnosis this mapping exists to prevent.+ const probe = classifyGhProbe({+ code: 1,+ stderr: 'Get "https://api.github.com/rate_limit": dial tcp 140.82.116.6:443: connect: bad file descriptor'+ });+ expect(probe.status).toBe('unreachable');+ expect(probe.detail).toContain('bad file descriptor');+ });++ it.each([+ ['dial tcp 140.82.116.6:443: i/o timeout', 'unreachable'],+ ['dial tcp: lookup api.github.com: no such host', 'unreachable'],+ ['connection refused', 'unreachable'],+ ['net/http: TLS handshake timeout', 'unreachable'],+ ['gh api rate_limit timed out after 10000ms', 'unreachable']+ ])('treats %j as %s', (stderr, expected) => {+ expect(classifyGhProbe({ code: 1, stderr }).status).toBe(expected);+ });++ it.each([+ 'You are not logged in to any GitHub hosts. To log in, run: gh auth login',+ 'HTTP 401: Bad credentials (https://api.github.com/rate_limit)',+ 'error: authentication required'+ ])('treats %j as not-authenticated', (stderr) => {+ expect(classifyGhProbe({ code: 1, stderr }).status).toBe('not-authenticated');+ });++ it('prefers the auth verdict when a message carries both auth and network wording', () => {+ // `gh auth status` on a blocked network prints an auth-shaped line; the+ // credential problem is the actionable one, so auth must win the tie.+ const probe = classifyGhProbe({+ code: 1,+ stderr: 'The token in GH_TOKEN is invalid. To log in, run: gh auth login (dial tcp failed)'+ });+ expect(probe.status).toBe('not-authenticated');+ });++ it('falls back to error with the exit code when stderr says nothing recognisable', () => {+ expect(classifyGhProbe({ code: 3, stderr: '' })).toEqual({+ status: 'error',+ detail: 'gh exited with code 3'+ });+ });++ it('does not collapse an unrecognised failure into ok', () => {+ expect(classifyGhProbe({ code: 1, stderr: 'something new' }).status).toBe('error');+ });+});++describe('ghRemedy', () => {+ it('names the outbound-firewall case for unreachable', () => {+ expect(ghRemedy('unreachable')).toMatch(/firewall/i);+ });++ it('gives a remedy for every non-ok status and none for ok', () => {+ for (const s of ['not-installed', 'not-authenticated', 'unreachable', 'error']) {+ expect(ghRemedy(s), s).toBeTruthy();+ }+ expect(ghRemedy('ok')).toBeNull();+ });+});++describe('checkGhHealth', () => {+ beforeEach(() => {+ __resetGhHealthCache();+ spawnMock.mockReset();+ });++ afterEach(() => {+ __resetGhHealthCache();+ });++ it('probes the quota-free rate_limit endpoint', async () => {+ spawnMock.mockImplementation(() => fakeChild({ code: 0 }));+ const health = await checkGhHealth();+ expect(spawnMock).toHaveBeenCalledWith('gh', ['api', 'rate_limit'], expect.any(Object));+ expect(health.ok).toBe(true);+ expect(health.status).toBe('ok');+ expect(health.remedy).toBeNull();+ });++ it('surfaces a blocked connection as unreachable with a remedy', async () => {+ spawnMock.mockImplementation(() => fakeChild({+ code: 1,+ stderr: 'dial tcp 140.82.116.6:443: connect: bad file descriptor'+ }));+ const health = await checkGhHealth();+ expect(health.ok).toBe(false);+ expect(health.status).toBe('unreachable');+ expect(health.remedy).toMatch(/firewall/i);+ expect(health.checkedAt).toBeTruthy();+ });++ it('memoizes so a polled health endpoint does not spawn gh every request', async () => {+ spawnMock.mockImplementation(() => fakeChild({ code: 0 }));+ await checkGhHealth();+ await checkGhHealth();+ expect(spawnMock).toHaveBeenCalledTimes(1);+ });++ it('re-probes when forced', async () => {+ spawnMock.mockImplementation(() => fakeChild({ code: 0 }));+ await checkGhHealth();+ await checkGhHealth({ force: true });+ expect(spawnMock).toHaveBeenCalledTimes(2);+ });++ it('resolves rather than rejecting when gh is missing, so callers need no catch', async () => {+ spawnMock.mockImplementation(() => fakeChild({+ spawnError: Object.assign(new Error('spawn gh ENOENT'), { code: 'ENOENT' })+ }));+ await expect(checkGhHealth()).resolves.toMatchObject({ status: 'not-installed', ok: false });+ });++ it('kills and reports a probe that never returns', async () => {+ vi.useFakeTimers();+ const hung = new EventEmitter();+ hung.stdout = new EventEmitter();+ hung.stderr = new EventEmitter();+ hung.kill = vi.fn();+ spawnMock.mockImplementation(() => hung);++ const pending = checkGhHealth({ timeoutMs: 5000 });+ await vi.advanceTimersByTimeAsync(5000);+ const health = await pending;++ expect(hung.kill).toHaveBeenCalledWith('SIGKILL');+ expect(health.status).toBe('unreachable');+ vi.useRealTimers();+ });+});diff --git a/server/services/github.js b/server/services/github.jsindex f792c018bd..a18fd275df 100644--- a/server/services/github.js+++ b/server/services/github.js@@ -315,3 +315,145 @@ export async function getStatus() {secretCount: Object.keys(data.secrets).length};}++// --- Forge (gh CLI) reachability -------------------------------------------+//+// Roughly thirty call sites across PortOS run `gh` and swallow the failure into+// an empty result (`.catch(() => [])`). That collapses "the forge said there is+// nothing" into "we could not ask the forge" — the exact conflation the root+// CLAUDE.md's sentinel-and-validate rule exists to prevent. In practice it means+// a `gh` that cannot reach api.github.com is indistinguishable from a quiet+// repo: prWatcher sees no PRs, branchReconcile sees no branches, and an agent+// told to open a PR reports success having opened nothing.+//+// This probe answers the question those call sites cannot: is `gh` actually+// usable right now, and if not, which of the three failure modes is it? Callers+// stay unchanged — the value is that the state is *reportable* (see the `forge`+// block on GET /api/system/health/details) instead of silently absent.++const GH_PROBE_TIMEOUT_MS = 10000;+const GH_HEALTH_TTL_MS = 60000;++// Matched against `gh`'s stderr. Auth is checked first: an unauthenticated `gh`+// can still reach the network, and its message is the more actionable one.+const GH_AUTH_MARKERS = [+ 'not logged in',+ 'authentication required',+ 'requires authentication',+ 'bad credentials',+ 'gh auth login',+ 'no such host: authentication'+];++// A blocked or broken transport. `bad file descriptor` belongs here because an+// outbound-filtering firewall (Little Snitch and friends) denies the connect()+// rather than refusing it, and Go surfaces that as EBADF — which reads like a+// local bug unless it is named as a network failure.+const GH_NETWORK_MARKERS = [+ 'dial tcp',+ 'bad file descriptor',+ 'no such host',+ 'connection refused',+ 'connection reset',+ 'network is unreachable',+ 'i/o timeout',+ 'timed out',+ 'tls handshake',+ 'certificate'+];++const includesAny = (haystack, needles) => needles.some(n => haystack.includes(n));++/**+ * Classify a `gh` probe result. Split out from the spawn so the mapping from+ * failure text to status is testable without a network or a `gh` binary.+ *+ * @param {{ code?: number|null, stderr?: string, spawnError?: Error|null }} probe+ * @returns {{ status: 'ok'|'not-installed'|'not-authenticated'|'unreachable'|'error', detail: string|null }}+ */+export function classifyGhProbe({ code = null, stderr = '', spawnError = null } = {}) {+ if (spawnError) {+ // ENOENT is the only spawn error that reliably means "no binary on PATH";+ // anything else (EACCES, EPERM) is a real local fault worth reporting as-is.+ const status = spawnError.code === 'ENOENT' ? 'not-installed' : 'error';+ return { status, detail: spawnError.message || String(spawnError) };+ }+ if (code === 0) return { status: 'ok', detail: null };++ const text = String(stderr || '').trim();+ const lower = text.toLowerCase();+ if (includesAny(lower, GH_AUTH_MARKERS)) return { status: 'not-authenticated', detail: text || null };+ if (includesAny(lower, GH_NETWORK_MARKERS)) return { status: 'unreachable', detail: text || null };+ return { status: 'error', detail: text || `gh exited with code ${code}` };+}++/**+ * Human-readable remedy for a given probe status. Kept beside the classifier so+ * the message and the state it describes cannot drift apart.+ */+export function ghRemedy(status) {+ switch (status) {+ case 'not-installed':+ return 'Install the GitHub CLI (brew install gh) to let PortOS read pull requests and issues.';+ case 'not-authenticated':+ return 'Run `gh auth login` — PortOS can reach GitHub but has no usable credential.';+ case 'unreachable':+ return 'gh cannot open an outbound connection. If an outbound firewall (e.g. Little Snitch) is installed, allow the gh binary to reach api.github.com — a denied connect surfaces as "bad file descriptor".';+ case 'error':+ return 'gh failed for an unrecognised reason — run `gh api rate_limit` in a terminal to see the full output.';+ default:+ return null;+ }+}++let ghHealthCache = null;+let ghHealthCheckedAt = 0;++function probeGh(timeoutMs) {+ return new Promise((resolve) => {+ // `rate_limit` is authenticated, cheap, and — unlike every other endpoint —+ // does not itself consume quota, so polling this probe is free.+ const child = spawn('gh', ['api', 'rate_limit'], { shell: false, windowsHide: true });+ let stderr = '';+ let settled = false;+ const done = (result) => { if (!settled) { settled = true; clearTimeout(timer); resolve(result); } };+ const timer = setTimeout(() => {+ // setTimeout callback boundary — a kill() throw here would be uncaught.+ try { child.kill('SIGKILL'); } catch (err) { console.error(`❌ gh health probe: failed to kill child: ${err.message}`); }+ done({ code: null, stderr: `gh api rate_limit timed out after ${timeoutMs}ms`, spawnError: null });+ }, timeoutMs);+ child.stderr.on('data', (d) => { stderr += d.toString(); });+ child.on('error', (err) => done({ code: null, stderr, spawnError: err }));+ child.on('close', (code) => done({ code, stderr, spawnError: null }));+ });+}++/**+ * Probe whether `gh` can actually talk to the forge right now.+ *+ * Result is cached for a minute — /api/system/health/details is polled, and the+ * probe spawns a process. Pass `{ force: true }` to bypass the cache.+ *+ * @returns {Promise<{ status: string, ok: boolean, detail: string|null, remedy: string|null, checkedAt: string }>}+ */+export async function checkGhHealth({ force = false, timeoutMs = GH_PROBE_TIMEOUT_MS } = {}) {+ const now = Date.now();+ if (!force && ghHealthCache && (now - ghHealthCheckedAt) < GH_HEALTH_TTL_MS) return ghHealthCache;++ const { status, detail } = classifyGhProbe(await probeGh(timeoutMs));+ ghHealthCache = {+ status,+ ok: status === 'ok',+ detail,+ remedy: ghRemedy(status),+ checkedAt: new Date(now).toISOString()+ };+ ghHealthCheckedAt = now;+ return ghHealthCache;+}++/** Test seam — drops the memoized probe result. */+export function __resetGhHealthCache() {+ ghHealthCache = null;+ ghHealthCheckedAt = 0;+}