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
fix: name the real cause when scheduled-task issue/PR preloads fail
Adam Eivyb118f4270922
diff --git a/server/services/github.js b/server/services/github.jsindex 39f0004b63..6df2a4d2d4 100644--- a/server/services/github.js+++ b/server/services/github.js@@ -644,12 +644,16 @@ export function classifyGhProbe({ code = null, stderr = '', spawnError = null }* 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) {+export function ghRemedy(status, { hostname = null } = {}) {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.';+ // gh keeps one credential per host, and SSH access to a repo's git remote+ // grants no API access — so an enterprise host needs its own login.+ return hostname+ ? `Run \`gh auth login --hostname ${hostname}\` — gh has no usable credential for ${hostname} (SSH git access does not grant API access).`+ : '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':diff --git a/server/services/perpetualWork.js b/server/services/perpetualWork.jsindex 46e3ea0c37..04d8352c40 100644--- a/server/services/perpetualWork.js+++ b/server/services/perpetualWork.js@@ -763,7 +763,13 @@ export async function listConfiguredForgeIssues(cli, app, options, env) {const result = await detectForgeIssues(cli === 'glab' ? 'claim-issue-gitlab' : 'claim-issue', app, options, true, env);- return { ok: !result.transient && result.reason !== 'no-repo-path', issues: result.issues || [], truncated: result.truncated === true };+ const ok = !result.transient && result.reason !== 'no-repo-path';+ return {+ ok,+ issues: result.issues || [],+ truncated: result.truncated === true,+ ...(ok ? {} : { error: result.detail || result.reason || '' }),+ };}// Forge-specific detector entry points (thin wrappers over the shared factory).diff --git a/server/services/taskDataInputs.js b/server/services/taskDataInputs.jsindex f57f21c7fc..5f7ca48185 100644--- a/server/services/taskDataInputs.js+++ b/server/services/taskDataInputs.js@@ -9,11 +9,13 @@import { readdir } from 'fs/promises';import { join, relative } from 'path';import { safeJSONParse, tryReadFile } from '../lib/fileUtils.js';+import { redactPii } from '../lib/piiRedactionPatterns.js';+import { scrubSecretTokens } from '../lib/secretText.js';import { DISPATCH_HINT_READING_GUIDANCE } from '../lib/dispatchLabels.js';import { TASK_DATA_INPUT_DEFINITIONS } from '../lib/taskDataInputCatalog.js';import { githubApiHost, resolveAppWorkTracker } from '../lib/workTracker.js';import { resolveForgeTokenEnv } from './forgeAuth.js';-import { execGh } from './github.js';+import { classifyGhProbe, execGh, ghRemedy } from './github.js';import { execGlabJson } from './gitlab.js';const MAX_DOCUMENT_FILES = 3;@@ -126,25 +128,50 @@ export function renderForgeItems(items, { emptyMessage }) {async function runForgeCli(cli, args, { cwd, env } = {}) {if (cli === 'gh') {- const stdout = await execGh(args, FORGE_TIMEOUT_MS, { cwd, env }).catch(() => null);- return stdout === null ? { code: -1, stdout: '' } : { code: 0, stdout };+ let stderr = '';+ const stdout = await execGh(args, FORGE_TIMEOUT_MS, { cwd, env }).catch((err) => {+ stderr = err?.ghStderr || err?.message || '';+ return null;+ });+ return stdout === null ? { code: -1, stdout: '', stderr } : { code: 0, stdout };}if (cli === 'glab') {- const { rows } = await execGlabJson(args, cwd, FORGE_TIMEOUT_MS);- return rows === null ? { code: -1, stdout: '' } : { code: 0, stdout: JSON.stringify(rows) };+ const { rows, reason } = await execGlabJson(args, cwd, FORGE_TIMEOUT_MS);+ return rows === null ? { code: -1, stdout: '', stderr: `glab ${reason}` } : { code: 0, stdout: JSON.stringify(rows) };}return { code: -1, stdout: '' };}+/**+ * Name WHY a forge read failed so the agent (and the operator reading its+ * prompt) sees the remedy instead of a generic "source read failed" — most+ * often a GitHub Enterprise host missing from `gh auth status`.+ */+export function describeForgeReadFailure({ cli, stderr = '', host = null } = {}) {+ const text = String(stderr || '').trim();+ if (cli === 'gh') {+ const { status } = classifyGhProbe({ code: 1, stderr: text });+ if (status === 'not-authenticated' || status === 'unreachable') {+ return ghRemedy(status, { hostname: host || 'github.com' });+ }+ }+ const firstLine = text.split('\n').find((line) => line.trim())?.trim();+ return firstLine ? `${cli} failed: ${redactPii(scrubSecretTokens(firstLine)).slice(0, 200)}` : 'source read failed';+}++function failedRead(cli, result) {+ return result.code !== 0 ? (result.stderr || '') : `${cli} returned no parseable list`;+}+export async function listForgeOpenIssues({ cli, cwd, env, exec = runForgeCli } = {}) {if (!cwd || (cli !== 'gh' && cli !== 'glab')) return { ok: false, issues: [] };const args = cli === 'glab'? ['issue', 'list', '-P', '100']: ['issue', 'list', '--state', 'open', '--limit', '100', '--json', 'number,title,state,url,labels'];const result = await exec(cli, args, { cwd, env });- if (result.code !== 0 || !result.stdout.trim()) return { ok: false, issues: [] };+ if (result.code !== 0 || !result.stdout.trim()) return { ok: false, issues: [], error: failedRead(cli, result) };const parsed = safeJSONParse(result.stdout, null, { logError: false });- if (!Array.isArray(parsed)) return { ok: false, issues: [] };+ if (!Array.isArray(parsed)) return { ok: false, issues: [], error: failedRead(cli, result) };return {ok: true,issues: parsed@@ -171,9 +198,9 @@ export async function listForgePullRequests({ cli, cwd, env, state = 'open', exe'--json', 'number,title,author,url,isDraft,headRefName,baseRefName,labels,closedAt'];const result = await exec(cli, args, { cwd, env });- if (result.code !== 0 || !result.stdout.trim()) return { ok: false, items: [] };+ if (result.code !== 0 || !result.stdout.trim()) return { ok: false, items: [], error: failedRead(cli, result) };const parsed = safeJSONParse(result.stdout, null, { logError: false });- if (!Array.isArray(parsed)) return { ok: false, items: [] };+ if (!Array.isArray(parsed)) return { ok: false, items: [], error: failedRead(cli, result) };// GitLab's --closed excludes merged MRs on current glab versions. Keep the// explicit filter as a compatibility guard if a version returns both.const items = closed@@ -186,6 +213,14 @@ function unavailableMessage(label, reason = 'source read failed') {return `${label} could not be preloaded (${reason}). Do not interpret this as an empty source.`;}+function forgeUnavailable(label, forge, result) {+ const reason = result?.error != null+ ? describeForgeReadFailure({ cli: forge.cli, stderr: result.error, host: forge.host })+ : undefined;+ if (reason) console.warn(`⚠️ Task data input "${label}" not preloaded: ${reason}`);+ return unavailableMessage(label, reason);+}+async function resolveForgeContext(app, deps) {if (!app?.repoPath) return null;const tracker = await deps.resolveTracker(app);@@ -238,21 +273,21 @@ const INPUT_LOADERS = {{ emptyMessage: 'No open issues match this task’s configured filters (help wanted is excluded).' })+ (result.truncated ? TRUNCATION_NOTICE : '')- : unavailableMessage('Open issues');+ : forgeUnavailable('Open issues', forge, result);},'open-pull-requests': async ({ app, deps, forge }) => {if (!forge) return unavailableMessage('Open pull requests', 'repository forge is unavailable');const result = await deps.listPullRequests({ cli: forge.cli, cwd: app.repoPath, env: forge.env, state: 'open' });return result.ok? renderForgeItems(result.items, { emptyMessage: 'No open pull requests.' })- : unavailableMessage('Open pull requests');+ : forgeUnavailable('Open pull requests', forge, result);},'closed-unmerged-pull-requests': async ({ app, deps, forge }) => {if (!forge) return unavailableMessage('Closed unmerged pull requests', 'repository forge is unavailable');const result = await deps.listPullRequests({ cli: forge.cli, cwd: app.repoPath, env: forge.env, state: 'closed-unmerged' });return result.ok? renderForgeItems(result.items, { emptyMessage: 'No recently closed unmerged pull requests.' })- : unavailableMessage('Closed unmerged pull requests');+ : forgeUnavailable('Closed unmerged pull requests', forge, result);},};diff --git a/server/services/taskDataInputs.test.js b/server/services/taskDataInputs.test.jsindex f9a5313fab..703a8296ee 100644--- a/server/services/taskDataInputs.test.js+++ b/server/services/taskDataInputs.test.js@@ -68,6 +68,44 @@ describe('taskDataInputs', () => {expect(empty[0].content).toContain('No open issues match');});+ it('names the gh login remedy when the forge host has no gh credential', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const exec = vi.fn().mockResolvedValue({+ code: -1, stdout: '',+ stderr: 'none of the git remotes configured for this repository point to a known GitHub host. To tell gh about a new GitHub host, please use `gh auth login`',+ });+ const [section] = await resolveTaskDataInputs(['open-issues'], {+ app: APP,+ dependencies: {+ resolveTracker: vi.fn().mockResolvedValue({ forge: 'gh', host: 'ghes.example.com' }),+ listIssues: (options) => listForgeOpenIssues({ ...options, exec }),+ },+ });+ expect(section.content).toContain('gh auth login --hostname ghes.example.com');+ expect(section.content).toContain('Do not interpret this as an empty source');+ expect(section.content).not.toContain('source read failed');+ expect(warn).toHaveBeenCalledTimes(1);+ warn.mockRestore();+ });++ it('adds no forge sections and makes no forge calls when none are selected', async () => {+ const resolveTracker = vi.fn();+ const listIssues = vi.fn();+ const listPullRequests = vi.fn();+ const sections = await resolveTaskDataInputs([], {+ app: APP, dependencies: { resolveTracker, listIssues, listPullRequests },+ });+ expect(sections).toEqual([]);+ expect(appendTaskDataInputs('Do the task.', sections)).toBe('Do the task.');+ await resolveTaskDataInputs(['project-goals'], {+ app: APP,+ dependencies: { resolveTracker, listIssues, listPullRequests, findFiles: vi.fn().mockResolvedValue([]) },+ });+ expect(resolveTracker).not.toHaveBeenCalled();+ expect(listIssues).not.toHaveBeenCalled();+ expect(listPullRequests).not.toHaveBeenCalled();+ });+it('uses task policy for issue context and fails closed when policy resolution fails', async () => {const listConfiguredIssues = vi.fn().mockResolvedValue({ ok: true, issues: [{ number: 7, title: 'Eligible' }] });const listIssues = vi.fn();@@ -266,8 +304,8 @@ describe('taskDataInputs', () => {it('does not treat blank forge output as a legitimately empty list', async () => {const exec = vi.fn().mockResolvedValue({ code: 0, stdout: ' ', stderr: '' });await expect(listForgeOpenIssues({ cli: 'gh', cwd: '/repo', exec }))- .resolves.toEqual({ ok: false, issues: [] });+ .resolves.toMatchObject({ ok: false, issues: [] });await expect(listForgePullRequests({ cli: 'gh', cwd: '/repo', exec }))- .resolves.toEqual({ ok: false, items: [] });+ .resolves.toMatchObject({ ok: false, items: [] });});});