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: detect enterprise forge hosts from CLI config (#8191)
[._.]/ Adam Eivyb5efc5e3505e
diff --git a/server/lib/README.md b/server/lib/README.mdindex a4bed02d16..31a6534f45 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -682,7 +682,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `userActionTypes.js` | Closed vocabulary for the operator-action ledger (`user_action_events`, #5594 / #5596): `USER_ACTION_TYPES` (CoS task/feedback/schedule + settings + instance-feature toggles + event-only creative/Brain pointers), `USER_ACTION_ACTORS` (`user` / `mind` / `schedule` / `system`), and the `isUserActionType` / `isUserActionActor` predicates. `recordUserAction` (`services/userActions.js`) throws on a type absent from the list, so a typo fails a test instead of writing a row nothing can filter on. || `uuid.js` | `v4()` thin wrapper over the global `crypto.randomUUID()`. Import-free, so a leaf the browser imports may reach it without a Node built-in — importable, not browser-callable: `randomUUID` needs a secure context there, so client code mints through `client/src/lib/uuid.js`. || `versionUtils.js` | `compareSemver(a, b)` — semver ordering (-1/0/1) with pre-release precedence and build-metadata stripping. Shared by the self-update checker (`updateChecker.js`) and the local-LLM Ollama update detector (`localLlm.js`). Inputs must be `v`-stripped. |-| `workTracker.js` | `WORK_TRACKERS`/`CONCRETE_WORK_TRACKERS`/`DEFAULT_WORK_TRACKER`, `workTrackerLabel`, `hostToWorkTracker`, `isGithubHost` (GitHub-family host test — github.com + enterprise github.*; enterprise-aware replacement for the github.com-only `isGithub` gate), `githubRepoSpec(origin)` (host-qualified `HOST/OWNER/REPO` selector for `gh --repo`, or null for a non-GitHub origin — pairs the isGithubHost gate with the selector so prWatcher/branchReconcile/issueReconcile share one "resolvable GitHub repo" definition), `forgeCliForTracker`, `isFileTracker` (true when the tracker records work as repo files — PLAN.md — so an agent's proposal necessarily dirties the worktree; false for github/gitlab/jira), `trackerToClaimTaskType`, `hostFromOriginUrl` (subgroup-tolerant, ssh-alias-aware host parse), pure `resolveWorkTracker({configured,host})`, async `resolveAppWorkTracker(app)` — resolves a managed app's autonomous work source (PLAN.md / GitHub / GitLab / JIRA), defaulting `'auto'` to the git origin host. Async `resolveRepoForgeTarget(repoPath)` — the ONE definition of "which forge can we query for this checkout", returning `{ forge, fullName, repoSpec, apiHost }` (enterprise-aware `gh --repo` selector for GitHub; `repoSpec: null` for GitLab, which `glab` resolves from its cwd) or null for a non-forge origin; shared by `issueReconcile.js` and `appIssues.js`. Async `resolveAppForgeTarget(app, {repoPath})` — the composed `resolveAppWorkTracker` + `resolveRepoForgeTarget` for callers holding the managed-app record, returning `{ tracker, target }` with the app's github/gitlab pin threaded in as `preferredForge` (so a self-hosted forge on a hostname matching neither pattern still resolves); use this instead of re-threading the pin by hand. Also owns the `{trackerInstructions}` prompt block shared by the TRACKER-FILING task types (types that read the app read-only and deliver findings as tracker items, not a commit): `TRACKER_FILING_PRESETS` (per-task-type slug prefix / label / body requirements — `reference-watch`, `ux`, `repo-study`), `TRACKER_FILING_TASK_TYPES` (derived from the presets, so a gated type always has wording), `extraIssueLabels` / `formatForgeCategoryLabelFlags` (category + metric-slug labels + `plan` as repeated `--label` flags), and `formatTrackerInstructions(tracker, options)` which renders the plan/github/gitlab/jira block (reference-watch is the default option set, so a bare call stays byte-identical for it). Consumed by the `claim-work` router in `cosTaskGenerator.js`, `referenceRepos.js`, and `routes/apps.js`. Also `repoIssueUrlBase(target)` — the browsable issue-tracker base URL for a resolved forge target (`/-/issues` on GitLab, `/issues` elsewhere), so a caller stamps a finished base onto its record and nothing downstream has to classify a host. |+| `workTracker.js` | `WORK_TRACKERS`/`CONCRETE_WORK_TRACKERS`/`DEFAULT_WORK_TRACKER`, `workTrackerLabel`, `hostToWorkTracker`, `isGithubHost` (GitHub-family host test — github.com + enterprise github.*; enterprise-aware replacement for the github.com-only `isGithub` gate), `githubRepoSpec(origin)` (host-qualified `HOST/OWNER/REPO` selector for `gh --repo`, or null for a non-GitHub origin — pairs the isGithubHost gate with the selector so prWatcher/branchReconcile/issueReconcile share one "resolvable GitHub repo" definition), `forgeCliForTracker`, `isFileTracker` (true when the tracker records work as repo files — PLAN.md — so an agent's proposal necessarily dirties the worktree; false for github/gitlab/jira), `trackerToClaimTaskType`, `hostFromOriginUrl` (subgroup-tolerant, ssh-alias-aware host parse), pure `resolveWorkTracker({configured,host})`, async `resolveAppWorkTracker(app)` — resolves a managed app's autonomous work source (PLAN.md / GitHub / GitLab / JIRA), defaulting `'auto'` to the git origin host and checking the `gh` and `glab` host configs for otherwise-unmatched hosts. Async `resolveRepoForgeTarget(repoPath)` — the ONE definition of "which forge can we query for this checkout", returning `{ forge, fullName, repoSpec, apiHost }` (enterprise-aware `gh --repo` selector for GitHub; `repoSpec: null` for GitLab, which `glab` resolves from its cwd) or null for a non-forge origin; shared by `issueReconcile.js` and `appIssues.js`. Async `resolveAppForgeTarget(app, {repoPath})` — the composed `resolveAppWorkTracker` + `resolveRepoForgeTarget` for callers holding the managed-app record, returning `{ tracker, target }` with the app's github/gitlab pin threaded in as `preferredForge` (so a self-hosted forge on a hostname matching neither pattern still resolves); use this instead of re-threading the pin by hand. Also owns the `{trackerInstructions}` prompt block shared by the TRACKER-FILING task types (types that read the app read-only and deliver findings as tracker items, not a commit): `TRACKER_FILING_PRESETS` (per-task-type slug prefix / label / body requirements — `reference-watch`, `ux`, `repo-study`), `TRACKER_FILING_TASK_TYPES` (derived from the presets, so a gated type always has wording), `extraIssueLabels` / `formatForgeCategoryLabelFlags` (category + metric-slug labels + `plan` as repeated `--label` flags), and `formatTrackerInstructions(tracker, options)` which renders the plan/github/gitlab/jira block (reference-watch is the default option set, so a bare call stays byte-identical for it). Consumed by the `claim-work` router in `cosTaskGenerator.js`, `referenceRepos.js`, and `routes/apps.js`. Also `repoIssueUrlBase(target)` — the browsable issue-tracker base URL for a resolved forge target (`/-/issues` on GitLab, `/issues` elsewhere), so a caller stamps a finished base onto its record and nothing downstream has to classify a host. || `eidoverseProxyRoutes.js` | Allowlist + path helpers for the same-origin Eidoverse reverse-proxy on `:5555` (`/eidoverse-host` prefix strip and root routes like `/ws` / `/version` while the host is active). Shared by `services/eidoverseProxy.js` so the main server and the optional `:5563` bridge stay in sync with eidoverse-worlds `server/routes.ts`. || `workspaceRoots.js` | Shared allow-list for routes that take a caller-supplied filesystem path. `isWithinAllowedRoots(realPath)` is the single complete test — on Windows it also allows any lettered non-system drive (`D:\code`), which appears in no root, so never render `ALLOWED_WORKSPACE_ROOTS` as "the directories you may use". `outsideAllowedRootsMessage(realPath, { field })` formats a redacted server-only diagnostic with the rejected realpath and every checked root. Also `ALLOWED_WORKSPACE_ROOTS` (defaults + `PORTOS_WORKSPACE_ROOTS`, split on the platform path delimiter — `;` on Windows — and symlink-resolved), `isWithinRoot(resolvedPath, root)` (separator-safe containment), and `WORKSPACE_ROOTS_CONFIGURED` (true when the operator set the env var — lets a permissive-by-default route like `routes/detect.js` opt into confinement). Defaults cover home plus wherever the platform mounts secondary volumes: `/tmp` + `/Users` + `/Volumes` + `/mnt` + `/media` + `/opt` on POSIX; home + the temp dir plus the non-system-drive rule on Windows, where those POSIX literals would resolve to whatever drive the process happens to be on. Used by `routes/commands.js`, `routes/scaffold.js`, and `routes/git.js` (always scoped) and `routes/detect.js` (scoped only when configured). || `zodCompat.js` | Zod 4 compatibility helpers. `partialWithoutDefaults(objectSchema)` — like `.partial()` but strips inner field defaults first, so a PATCH/update schema doesn't inject (and clobber) the stored values of fields the caller didn't send. Use for any update schema derived from a defaulted base. Also home to the provider-reference zod forms (#7564) — `providerRefSchema` / `providerRefFieldSchema` (a preset id OR a composite `harness.method@service[+bootstrap]`, per `providerRef.js`) and `presetProviderIdSchema` (preset-only) — because `cosValidation.js` needs them and must not import validation.js. |diff --git a/server/lib/workTracker.js b/server/lib/workTracker.jsindex d6a19b4657..ca5d4a124b 100644--- a/server/lib/workTracker.js+++ b/server/lib/workTracker.js@@ -3,18 +3,22 @@//// Each managed app carries a `workTracker` field (default `'auto'`). `'auto'`// resolves to a concrete tracker from the app's git `origin` host: a github.com-// remote → GitHub issues, a gitlab.* remote → GitLab issues, anything else (or-// no remote) → PLAN.md. JIRA is never auto-selected — it requires explicit+// remote → GitHub issues, a gitlab.* remote → GitLab issues, and a custom host+// known to the matching forge CLI → that forge's issues. Unknown hosts (or no+// remote) fall back to PLAN.md. JIRA is never auto-selected — it requires// per-app JIRA config (`app.jira`) — so a user picks it deliberately.//// The pure mappers (hostToWorkTracker / forgeCliForTracker / trackerToClaimTaskType// / resolveWorkTracker / hostFromOriginUrl) are side-effect-free and unit-tested.// resolveAppWorkTracker is the async wrapper that reads the app's origin URL via-// readOriginRemoteUrl and extracts the host with hostFromOriginUrl — it shells-// out to git, mirroring gitRemote.js (which also lives in lib/ despite running-// `git`). See server/services/cosTaskGenerator.js for the claim-work router-// that consumes trackerToClaimTaskType.-+// readOriginRemoteUrl, extracts the host with hostFromOriginUrl, and checks CLI host+// maps only when the host-pattern fast path cannot identify a forge. See+// server/services/cosTaskGenerator.js for the claim-work router that consumes+// trackerToClaimTaskType.++import { readFile } from 'node:fs/promises';+import { homedir } from 'node:os';+import path from 'node:path';import {DISPATCH_HINT_GUIDANCE,JIRA_DISPATCH_HINT_GUIDANCE,@@ -473,6 +477,91 @@ export function resolveWorkTracker({ configured, host } = {}) {return { configured: 'auto', resolved: 'plan', source: 'fallback' };}+/**+ * Read a CLI YAML config without exposing its contents or failing resolution+ * when the file is missing, malformed, or unreadable.+ * @param {string} configPath+ * @returns {Promise<{found:boolean, config:object|null}>}+ */+async function readForgeCliConfig(configPath) {+ let contents;+ try {+ contents = await readFile(configPath, 'utf8');+ } catch (error) {+ return { found: error?.code !== 'ENOENT', config: null };+ }++ try {+ const yaml = await import('js-yaml');+ const parseYaml = yaml.load || yaml.default?.load;+ const parsed = parseYaml(contents);+ return {+ found: true,+ config: parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null,+ };+ } catch {+ return { found: true, config: null };+ }+}++function configHasHost(config, host, hostMapKey = null) {+ const hosts = hostMapKey ? config?.[hostMapKey] : config?.hosts || config;+ if (!hosts || typeof hosts !== 'object' || Array.isArray(hosts)) return false;+ const normalizedHost = host.toLowerCase();+ return Object.entries(hosts).some(([configuredHost, settings]) => (+ configuredHost.toLowerCase() === normalizedHost+ && settings+ && typeof settings === 'object'+ && !Array.isArray(settings)+ ));+}++function glabConfigPaths() {+ if (process.env.GLAB_CONFIG_DIR) {+ return [path.join(process.env.GLAB_CONFIG_DIR, 'config.yml')];+ }++ const home = homedir();+ const directories = [path.join(home, '.config', 'glab-cli')];+ if (process.env.XDG_CONFIG_HOME) {+ directories.push(path.join(process.env.XDG_CONFIG_HOME, 'glab-cli'));+ } else if (process.platform === 'darwin') {+ directories.push(path.join(home, 'Library', 'Application Support', 'glab-cli'));+ } else if (process.platform === 'win32') {+ directories.push(path.join(process.env.LOCALAPPDATA || path.join(home, 'AppData', 'Local'), 'glab-cli'));+ }+ const systemConfigDirs = process.env.XDG_CONFIG_DIRS || '/etc/xdg';+ directories.push(...systemConfigDirs.split(path.delimiter).filter(Boolean).map((dir) => path.join(dir, 'glab-cli')));+ return [...new Set(directories.map((dir) => path.join(dir, 'config.yml')))];+}++/**+ * Detect a custom forge host from the CLI host maps without launching a CLI.+ * The config values can contain credentials; only host keys are inspected.+ * @param {string|null} host+ * @returns {Promise<'github'|'gitlab'|null>}+ */+async function hostKnownToForgeCli(host) {+ if (!host) return null;+ let defaultGhConfigDir = path.join(homedir(), '.config', 'gh');+ if (process.env.XDG_CONFIG_HOME) {+ defaultGhConfigDir = path.join(process.env.XDG_CONFIG_HOME, 'gh');+ } else if (process.platform === 'win32' && (process.env.AppData || process.env.APPDATA)) {+ defaultGhConfigDir = path.join(process.env.AppData || process.env.APPDATA, 'GitHub CLI');+ }+ const ghConfigDir = process.env.GH_CONFIG_DIR+ || defaultGhConfigDir;+ const ghConfig = await readForgeCliConfig(path.join(ghConfigDir, 'hosts.yml'));+ if (configHasHost(ghConfig.config, host)) return 'github';++ for (const configPath of glabConfigPaths()) {+ const glabConfig = await readForgeCliConfig(configPath);+ if (!glabConfig.found) continue;+ return configHasHost(glabConfig.config, host, 'hosts') ? 'gitlab' : null;+ }+ return null;+}+/*** Extract just the host from a git origin URL — only the host is needed to* classify the forge, so this handles EVERY remote form in one pass rather than@@ -511,8 +600,10 @@ export function hostFromOriginUrl(url) {/*** Resolve a managed app's effective work tracker, reading its git origin host* when needed. Returns `{ configured, resolved, host, forge, source }` where- * `forge` is the CLI ('gh' | 'glab' | null) for the resolved tracker. Never- * throws — a missing repo / origin degrades to host=null (→ PLAN.md fallback).+ * `forge` is the CLI ('gh' | 'glab' | null) for the resolved tracker.+ * `source` is `cli-config` when an existing CLI host entry identifies a custom host.+ * Never throws — missing repo/origin data, config errors, and unknown hosts+ * degrade to PLAN.md.*/export async function resolveAppWorkTracker(app) {const configured = app?.workTracker;@@ -522,6 +613,18 @@ export async function resolveAppWorkTracker(app) {host = hostFromOriginUrl(url);}const base = resolveWorkTracker({ configured, host });+ if (base.source === 'fallback' && host) {+ const fromForgeCli = await hostKnownToForgeCli(host);+ if (fromForgeCli) {+ return {+ ...base,+ resolved: fromForgeCli,+ source: 'cli-config',+ host,+ forge: forgeCliForTracker(fromForgeCli),+ };+ }+ }return { ...base, host, forge: forgeCliForTracker(base.resolved) };}@@ -563,12 +666,12 @@ function gitlabProjectPath(originUrl) {* `repoSpec` is therefore null for GitLab — the caller must run `glab` in* `repoPath`.*- * `preferredForge` ('github' | 'gitlab' | null) is the app's EXPLICITLY- * configured work tracker (never 'auto' — that already flows through the same- * `hostToWorkTracker` classification above, so it would already have matched- * here if it could). It's a fallback, tried only once both host-pattern checks- * above have failed: a self-hosted GitHub Enterprise Server or GitLab instance- * can run on ANY domain the operator picked (`git.mycompany.com`,+ * `preferredForge` ('github' | 'gitlab' | null) is the concrete tracker result+ * supplied by `resolveAppForgeTarget`: it comes from an explicit app setting or+ * from a CLI host config entry for an otherwise-unmatched host, never directly from 'auto'.+ * It's a fallback, tried only once both host-pattern checks above have failed:+ * a self-hosted GitHub Enterprise Server or GitLab instance can run on ANY+ * domain the operator picked (`git.mycompany.com`,* `scm.mycompany.com`, …) — there is no hostname heuristic that can tell such a* host apart from a non-forge remote, so the user's own pin is the only signal* left. A genuinely wrong pin (e.g. a bitbucket.org origin pinned to 'github')@@ -650,8 +753,9 @@ export function repoIssueUrlBase(target) {/*** Composed `resolveAppWorkTracker` + `resolveRepoForgeTarget` for callers that* hold the managed-app record (not just a bare `repoPath`): resolve the app's- * work tracker, then resolve its forge target with that tracker supplied as the- * `preferredForge` pin.+ * work tracker, then resolve its forge target with that concrete tracker supplied+ * as the `preferredForge`. The tracker may come from a hostname match or from+ * an existing CLI config entry for a custom host.** This composition exists so a feature can't accidentally drop the pin. Threading* it by hand is what left the issue-reconcile scan blind to a self-hosted forgediff --git a/server/lib/workTracker.test.js b/server/lib/workTracker.test.jsindex 93897df933..4796e3aa79 100644--- a/server/lib/workTracker.test.js+++ b/server/lib/workTracker.test.js@@ -1,4 +1,9 @@-import { describe, it, expect, vi, beforeEach } from 'vitest';+import { afterEach, describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('node:fs/promises', async (importOriginal) => ({+ ...(await importOriginal()),+ readFile: vi.fn(),+}));// gitRemote is the ONLY effectful dependency of the async resolvers below, so// mocking it lets `resolveAppForgeTarget` run its real composition (tracker@@ -9,7 +14,9 @@ vi.mock('./gitRemote.js', () => ({}));import { getOriginInfo, readOriginRemoteUrl } from './gitRemote.js';-import { repoIssueUrlBase, resolveAppForgeTarget } from './workTracker.js';+import { readFile } from 'node:fs/promises';+import path from 'node:path';+import { repoIssueUrlBase, resolveAppForgeTarget, resolveAppWorkTracker } from './workTracker.js';import {WORK_TRACKERS,CONCRETE_WORK_TRACKERS,@@ -229,6 +236,105 @@ describe('hostFromOriginUrl', () => {});});+describe('resolveAppWorkTracker — CLI auth fallback for enterprise hosts (#8191)', () => {+ const enterpriseOrigin = 'https://git.example-corp.com/acme/widget.git';+ const ghConfigDir = 'example-gh-config';+ const glabConfigDir = 'example-glab-config';+ const ghConfigPath = path.join(ghConfigDir, 'hosts.yml');+ const glabConfigPath = path.join(glabConfigDir, 'config.yml');++ function setConfigs({ gh = false, glab = false, errorCode = 'ENOENT' } = {}) {+ readFile.mockImplementation(async (configPath) => {+ if (configPath === ghConfigPath && gh) {+ return 'git.example-corp.com:\n user: example\n';+ }+ if (configPath === glabConfigPath && glab) {+ return 'hosts:\n git.example-corp.com:\n user: example\n';+ }+ const error = new Error('configuration unavailable');+ error.code = errorCode;+ throw error;+ });+ }++ beforeEach(() => {+ vi.clearAllMocks();+ vi.stubEnv('GH_CONFIG_DIR', ghConfigDir);+ vi.stubEnv('GLAB_CONFIG_DIR', glabConfigDir);+ readOriginRemoteUrl.mockResolvedValue(enterpriseOrigin);+ setConfigs();+ });++ afterEach(() => {+ vi.unstubAllEnvs();+ });++ it('resolves a custom host present in the gh hosts config as GitHub', async () => {+ setConfigs({ gh: true });++ await expect(resolveAppWorkTracker({ repoPath: '/repo', workTracker: 'auto' })).resolves.toMatchObject({+ configured: 'auto',+ resolved: 'github',+ source: 'cli-config',+ host: 'git.example-corp.com',+ forge: 'gh',+ });+ expect(readFile).toHaveBeenCalledWith(ghConfigPath, 'utf8');+ });++ it('resolves a custom host present in the glab config as GitLab', async () => {+ setConfigs({ glab: true });++ await expect(resolveAppWorkTracker({ repoPath: '/repo', workTracker: 'auto' })).resolves.toMatchObject({+ configured: 'auto',+ resolved: 'gitlab',+ source: 'cli-config',+ host: 'git.example-corp.com',+ forge: 'glab',+ });+ expect(readFile).toHaveBeenCalledWith(glabConfigPath, 'utf8');+ });++ it('threads the auto-detected forge into the app forge target', async () => {+ setConfigs({ gh: true });+ getOriginInfo.mockResolvedValue({+ host: 'git.example-corp.com',+ fullName: 'acme/widget',+ originUrl: enterpriseOrigin,+ });++ const { tracker, target } = await resolveAppForgeTarget({ repoPath: '/repo', workTracker: 'auto' });+ expect(tracker).toBe('github');+ expect(target).toMatchObject({+ forge: 'github',+ fullName: 'acme/widget',+ repoSpec: 'git.example-corp.com/acme/widget',+ });+ });++ it('keeps the PLAN.md fallback when neither CLI recognizes the host', async () => {+ await expect(resolveAppWorkTracker({ repoPath: '/repo', workTracker: 'auto' })).resolves.toMatchObject({+ configured: 'auto',+ resolved: 'plan',+ source: 'fallback',+ host: 'git.example-corp.com',+ forge: null,+ });+ expect(readFile).toHaveBeenCalledWith(ghConfigPath, 'utf8');+ expect(readFile).toHaveBeenCalledWith(glabConfigPath, 'utf8');+ });++ it('degrades to PLAN.md without throwing when CLI auth configuration cannot be read', async () => {+ setConfigs({ errorCode: 'EACCES' });++ await expect(resolveAppWorkTracker({ repoPath: '/repo', workTracker: 'auto' })).resolves.toMatchObject({+ resolved: 'plan',+ source: 'fallback',+ forge: null,+ });+ });+});+describe('workTrackerLabel', () => {it('returns a human label for every value, falling back to the raw value', () => {for (const t of WORK_TRACKERS) {