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: run managed apps under a second GitHub account
Adam Eivyce874d90c816
diff --git a/client/src/components/apps/EditAppDrawer.jsx b/client/src/components/apps/EditAppDrawer.jsxindex 4c764381eb..4203aabdcb 100644--- a/client/src/components/apps/EditAppDrawer.jsx+++ b/client/src/components/apps/EditAppDrawer.jsx@@ -65,6 +65,7 @@ export default function EditAppDrawer({ app, onClose, onSave }) {nativeLaunchProcessName: app.nativeLaunch?.processName || '',editorCommand: app.editorCommand || 'code .',workTracker: app.workTracker || 'auto',+ forgeAccount: app.forgeAccount || '',defaultOpenPR: app.defaultOpenPR || false,defaultPrCompletion: app.defaultPrCompletion || DEFAULT_PR_COMPLETION,defaultUseWorktree: app.defaultUseWorktree || app.defaultOpenPR || false,@@ -270,6 +271,7 @@ export default function EditAppDrawer({ app, onClose, onSave }) {} : null,editorCommand: formData.editorCommand || undefined,workTracker: formData.workTracker || 'auto',+ forgeAccount: formData.forgeAccount.trim(),defaultUseWorktree: formData.defaultUseWorktree || formData.defaultOpenPR,defaultOpenPR: formData.defaultOpenPR,defaultPrCompletion: formData.defaultPrCompletion,@@ -652,6 +654,23 @@ export default function EditAppDrawer({ app, onClose, onSave }) {)}</div>+ <div>+ <label htmlFor="edit-app-forge-account" className="block text-sm text-gray-400 mb-1">GitHub Account</label>+ <input+ id="edit-app-forge-account"+ type="text"+ value={formData.forgeAccount}+ onChange={e => setFormData(prev => ({ ...prev, forgeAccount: e.target.value }))}+ placeholder="Detect from repo owner"+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"+ />+ <p className="text-xs text-gray-500 mt-1">+ A logged-in <code>gh</code> login to run this app under. Agents authenticate and commit as+ that account, so a repo belonging to a different GitHub identity gets the right token and the+ right commit authorship. Leave blank to match the repo owner against your logged-in accounts.+ </p>+ </div>+<label className="flex items-center gap-2 cursor-pointer"><inputtype="checkbox"diff --git a/client/src/components/apps/EditAppDrawer.test.jsx b/client/src/components/apps/EditAppDrawer.test.jsxindex a74758e58b..2402be2beb 100644--- a/client/src/components/apps/EditAppDrawer.test.jsx+++ b/client/src/components/apps/EditAppDrawer.test.jsx@@ -169,6 +169,21 @@ describe('EditAppDrawer work tracker selector', () => {expect(payload.workTracker).toBe('gitlab');});+ it('saves a trimmed GitHub account pin and defaults it to blank', async () => {+ renderDrawer();+ await openTab('Workflow');++ const input = await screen.findByLabelText('GitHub Account');+ // Blank is the documented "infer from the repo owner" default, so an app+ // that never set one must not send a value that looks deliberate.+ expect(input).toHaveValue('');+ fireEvent.change(input, { target: { value: ' acme-bot ' } });++ fireEvent.click(screen.getByRole('button', { name: 'Save Changes' }));+ await waitFor(() => expect(api.updateApp).toHaveBeenCalled());+ expect(api.updateApp.mock.calls[0][1].forgeAccount).toBe('acme-bot');+ });+it('omits `jira` from the save payload so a drawer save cannot clobber the JIRA tab config', async () => {// The server shallow-merges the PUT, so an ABSENT `jira` key preserves the// stored config. Sending `{ enabled: false }` (what the removed drawer tabdiff --git a/docs/MANAGED_APP_FORGE_ACCOUNTS.md b/docs/MANAGED_APP_FORGE_ACCOUNTS.mdnew file mode 100644index 0000000000..e6e6df1c30--- /dev/null+++ b/docs/MANAGED_APP_FORGE_ACCOUNTS.md@@ -0,0 +1,90 @@+# Managed apps under a second GitHub account++One PortOS install commonly manages repositories belonging to more than one+GitHub identity — a personal account, a bot account, a client's organization.+CoS agents have to push, open pull requests, and author commits as whichever+account owns the repo they are working in, not as whoever owns the machine.++Two independent things make that work, and they fail in different ways.++## 1. The remote's host must resolve to GitHub++The usual way to key a checkout to a non-default SSH identity is a `Host` alias:++```sshconfig+# ~/.ssh/config+Host github-acme+ HostName github.com+ IdentityFile ~/.ssh/id_acme+```++```bash+git clone git@github-acme:acme/widget.git+```++Git and `ssh` resolve `github-acme` transparently, so the checkout works — but a+program reading the remote sees the literal string `github-acme`. PortOS now+resolves these aliases through `~/.ssh/config` wherever it parses a remote host+(`server/lib/sshHostAlias.js`), the same thing `gh` does before it picks an API+host. Without it, an aliased repo hits three separate failures at once:++- **CoS holds every change-request task.** The forge spawn gate probes the repo's+ host for reachability; an alias is not a resolvable API host, so it reports+ `unreachable` and holds the task — for an hour — before letting it fail.+ The symptom is `⏸️ Holding task … — github-acme is unreachable`.+- **The work tracker falls back to PLAN.md.** `auto` classifies a repo from its+ origin host, and an unrecognized host is not GitHub, so the app's issues are+ invisible to `claim-issue` and to the task data inputs.+- **Agents get no account-pinned token.** The `GH_TOKEN` overlay is gated on a+ real `github.com` host, so an aliased repo's agent falls back to `gh`'s mutable+ active user — the "must be a collaborator" failure.++Only literal `Host` → `HostName` pairs are honored. `Match` blocks, `Include`+directives, wildcard patterns, and `%h`-style `HostName` tokens are left alone:+each can make resolution depend on the user, the network, or another file, and a+repo's forge identity must not change with the network the machine is on. An+unresolved host passes through untouched.++## 2. The app must name the account to run as++Set **GitHub Account** on the app (Apps → edit → Workflow), or `forgeAccount` in+the app record. It takes a `gh` login you are already authenticated as:++```bash+gh auth login # once per account; `gh auth status` should list them all+```++When set, PortOS pins **both halves** of that identity for every agent it+launches against the app's repo (and every worktree of it):++| | |+|---|---|+| `GH_TOKEN` | minted for that account, so `gh pr create` and `git push` act as it |+| `GIT_AUTHOR_*` / `GIT_COMMITTER_*` | `<id>+<login>@users.noreply.github.com`, the address GitHub attributes back to the account |++The credential and the authorship move together on purpose: authenticating as+another account while committing under the machine owner's name and email writes+the wrong person into someone else's repository history.++The identity arrives as environment variables on the agent process rather than as+`git config`, so PortOS never mutates a repository it does not own, and the+override lives exactly as long as the run.++### When it is left blank++The account is inferred by matching the repo owner against your logged-in `gh`+logins, which is what PortOS has always done, and **no commit identity is+overridden**. That inference is correct whenever the owner's login *is* the+account that should push — so most personal repos need no configuration at all.+Set the field when it is not: an organization repo, a bot account, or any repo+whose owner login differs from the account you push with.++A pinned account is never second-guessed. If `gh` has no token for it, the run+gets no forge credential rather than silently falling back to a different+account's token.++## Related++- [SELF_UPDATE.md](./SELF_UPDATE.md) — PortOS's own fork-aware update path+- `server/services/forgeAuth.js` — account/token/identity resolution+- `server/lib/sshHostAlias.js` — the ssh-alias resolver and what it declines to interpretdiff --git a/docs/README.md b/docs/README.mdindex 44d9e1d2c0..f8151aef05 100644--- a/docs/README.md+++ b/docs/README.md@@ -28,6 +28,7 @@ Index of everything under `docs/`. Start with the [root README](../README.md) fo| [VERSIONING.md](./VERSIONING.md) | SemVer + release process (`/do:release`) || [SELF_UPDATE.md](./SELF_UPDATE.md) | Fork-aware self-update flow — release polling, `FORK_SYNC_REQUIRED`, fork sync, running a customized fork || [MANAGED_APP_UPDATES.md](./MANAGED_APP_UPDATES.md) | Safe managed-app update default and the opt-in app lifecycle contract |+| [MANAGED_APP_FORGE_ACCOUNTS.md](./MANAGED_APP_FORGE_ACCOUNTS.md) | Running managed apps under a second GitHub account — ssh `Host` aliases and the per-app `forgeAccount` pin || [DEPS.md](./DEPS.md) | Dependency audit — every third-party package and its verdict || [TROUBLESHOOTING.md](./TROUBLESHOOTING.md) | Common runtime issues, known issues || [WINDOWS_CONSOLE.md](./WINDOWS_CONSOLE.md) | Why console windows flash and steal focus on Windows, and the two fixes |diff --git a/server/lib/README.md b/server/lib/README.mdindex 854fef35aa..3a72f2a3a3 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -359,7 +359,8 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `ffmpegRenderGuard.js` | `attachFfmpegRenderGuard(proc, {label, onSpawnError, onProcessError, onClose})` — shared spawn-state tracking + exactly-once `terminal` guard + pre-vs-post-spawn dispatch for the SSE ffmpeg render runners (musicVideo/render + videoTimeline/local). Owns the 'spawn'/'error'/'close' wiring (only the pre-spawn 'error' or 'close' finalizes; a post-spawn 'error' records only) and takes the service-specific finalize bodies as callbacks so each renderer keeps its own project-status/history behavior. || `gitArgs.js` | `PROTECTED_BRANCHES`, `validateFilePaths(files)`, `isGitStageableFilePath(file)` — pure command-arg builders/validators for `git.js` (reject injection/traversal in staged paths). `isGitStageableFilePath` is `validateFilePaths`' non-throwing twin, for callers that must refuse an unstageable path BEFORE writing the file rather than 500 on the commit. || `gitCommitProbe.js` | `commitsSince(workspacePath, sinceMs)` / `committedDuringRun(workspacePath, sinceMs)` / `runWindowDiff(workspacePath, sinceMs, {maxChars})` — the run-window git probes: how many commits landed with a COMMITTER date inside a run's window (so a rebase/commit by the agent counts, a merely-pulled remote commit does not). The single machine-checkable "did this run commit anything?" primitive shared by finalize's success-criteria evaluation, run completion, runner completion, and orphan recovery — it replaced the unsatisfiable task-id commit-marker grep (#3637). Non-throwing: a non-repo, empty repo, or git timeout is 0. `runWindowDiff` is the diff half — the accumulated `<base>..HEAD` text for everything the run committed, base resolved with the same committer-date window so the two probes can't disagree about which commits are the run's. Every failure is a `reason` string with a `null` diff, never `''`: a git that could not answer must not read as a run that changed nothing. |-| `gitForge.js` | `parseGitRemote`, `parseGitHubOwnerFromRemote`, `pickGhAccountForOwner`, `detectForgeCli`, `parsePullRequestUrl` — pure GitHub/GitLab remote + PR/MR URL parsers and forge/account selectors used by `git.js`. |+| `gitForge.js` | `parseGitRemote`, `parseGitHubOwnerFromRemote`, `pickGhAccountForOwner`, `detectForgeCli`, `parsePullRequestUrl` — GitHub/GitLab remote + PR/MR URL parsers and forge/account selectors used by `git.js`. Pure except that `parseGitRemote` canonicalizes an ssh `Host` alias through `sshHostAlias.js`. |+| `sshHostAlias.js` | `resolveSshHostAlias`, `parseSshHostAliases` — resolves a personal SSH `Host` alias (`git@github-acme:…`, backed by `HostName github.com` in `~/.ssh/config`) to the host a remote actually connects to. Every remote-URL host parser (`gitForge.parseGitRemote`, `gitRemote.parseGitRemoteUrl`, `workTracker.hostFromOriginUrl`) canonicalizes through it, so multi-account checkouts classify as GitHub instead of an unreachable unknown host. || `gitOutputParsers.js` | `parseStatus`, `parseDiffStat`, `parseBranchVerboseLine`, `parseSubmoduleStatusLine`/`SUBMODULE_STATUS_RE`, `extractAgentSummary` — pure parsers turning git command output into structured data for `git.js`. `extractAgentSummary` anchors on `agentOutputMarkers`' completion marker so a TUI agent's PR body carries its sentinel summary, not the lifecycle telemetry above it. `isBenignConcurrentFetchRefRace(stderr)` reads a non-zero `git fetch` as a SUCCESS when its only failure is a lost compare-and-swap whose refs already hold the fetched commits — the routine outcome when the Git tab, `getRemoteBranches`, and CoS agent worktrees fetch one `.git` at once. || `gitRemote.js` | `getOriginInfo`, `classifyOriginRemote`, `parseGitRemoteUrl`, `readRemoteUrl`, `UPSTREAM_OWNER`/`UPSTREAM_REPO` — safely reads and classifies checkout remotes against PortOS or a caller-supplied canonical upstream. Used by self-update and managed integrations to detect forks. || `repoLinkFields.js` | `deriveRepoLinkFields(url)` / `normalizeRepoLinkFields(link)` / `linkIsRepo(link)` / `repoLinkLabel(link)` — the repository metadata a Brain link carries, plus the dual-write/tolerant-read shim that keeps the pre-multi-host `isGitHubRepo` field names readable across federated peers. |@@ -611,7 +612,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and| `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 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`. |+| `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`. || `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. |diff --git a/server/lib/gitForge.js b/server/lib/gitForge.jsindex 8b4fbe3102..16e5029f5d 100644--- a/server/lib/gitForge.js+++ b/server/lib/gitForge.js@@ -1,25 +1,35 @@-// Pure helpers for resolving forge (GitHub/GitLab) identity from git remote-// and PR/MR URLs. No child-process or network access — these are string-// parsers and selectors. The orchestration that shells out to `gh`/`glab`-// lives in server/services/forgeAuth.js (account/token resolution) and+// Helpers for resolving forge (GitHub/GitLab) identity from git remote and+// PR/MR URLs. No child-process or network access — these are string parsers and+// selectors. The one non-pure edge is `parseGitRemote`, which canonicalizes a+// personal SSH `Host` alias through the user's `~/.ssh/config` (a cached,+// guarded, synchronous read — see lib/sshHostAlias.js for why that has to happen+// at parse time). The orchestration that shells out to `gh`/`glab` lives in+// server/services/forgeAuth.js (account/token resolution) and// server/services/git.js (PR operations); both compose these helpers.+import { resolveSshHostAlias } from './sshHostAlias.js';+/*** Parse a git remote URL into `{ host, owner }`. Returns null for unparseable input.* Examples:* [email protected]:atomantic/PortOS.git → { host: 'github.com', owner: 'atomantic' }* https://gitlab.com/group/sub/proj.git → { host: 'gitlab.com', owner: 'group' }* [email protected]:foo/bar.git → { host: 'gitlab.example.com', owner: 'foo' }+ *+ * `host` is the host the remote actually connects to: a personal SSH alias+ * (`git@github-acme:acme/widget.git` with `HostName github.com` in the user's ssh+ * config) resolves to `github.com`, so every downstream forge/CLI/API decision+ * keyed on this value matches what `git` and `gh` do with the same remote.*/export function parseGitRemote(url) {if (!url) return null;// SSH: git@HOST:OWNER/REPO[.git] (REPO can contain '/' for GitLab subgroups,// but we only need the top-level owner here)const ssh = url.match(/^git@([^:]+):([^/]+)\/.+?(?:\.git)?$/);- if (ssh) return { host: ssh[1], owner: ssh[2] };+ if (ssh) return { host: resolveSshHostAlias(ssh[1]), owner: ssh[2] };// HTTPS: https://HOST/OWNER/REPO[.git]const https = url.match(/^https?:\/\/([^/]+)\/([^/]+)\/.+?(?:\.git)?$/);- if (https) return { host: https[1], owner: https[2] };+ if (https) return { host: resolveSshHostAlias(https[1]), owner: https[2] };return null;}diff --git a/server/lib/gitRemote.js b/server/lib/gitRemote.jsindex 6466561fa8..7c8c461025 100644--- a/server/lib/gitRemote.js+++ b/server/lib/gitRemote.js@@ -1,5 +1,6 @@import { execGit } from './execGit.js';import { PATHS } from './fileUtils.js';+import { resolveSshHostAlias } from './sshHostAlias.js';export const UPSTREAM_OWNER = 'atomantic';export const UPSTREAM_REPO = 'PortOS';@@ -31,8 +32,12 @@ export function redactRemoteUrlCredentials(url) {* https://github.com/owner/repo* [email protected]:org/repo.git*- * The returned `host` is always normalized (no trailing `:port`) so callers- * comparing against e.g. `github.com` don't have to special-case ports.+ * The returned `host` is always normalized: no trailing `:port`, and a personal+ * SSH `Host` alias (`git@github-acme:acme/widget.git`, backed by a+ * `HostName github.com` block in `~/.ssh/config`) is resolved to the host it+ * actually connects to. Both normalizations exist for the same reason — callers+ * compare against e.g. `github.com` to decide which forge a repo lives on, and+ * neither a port nor an alias changes that answer. See lib/sshHostAlias.js.* Rejects URLs with extra path segments (e.g. `git@host:owner/repo/extra`)* since those would produce a `fullName` like `owner/repo/extra` that breaks* `gh repo sync` and fork classification.@@ -48,6 +53,9 @@ export function parseGitRemoteUrl(url) {// Normalize host — strip an optional `:port` suffix so `github.com:443`// and `github.com` compare equal.const stripPort = (h) => h.replace(/:\d+$/, '');+ // Port first, then alias: an alias is written bare in ssh config, so+ // `github-acme:22` must have its port removed before the lookup.+ const normalizeHost = (h) => resolveSshHostAlias(stripPort(h));// SCP-style SSH: git@host:[port/]owner/repo(.git). repo segment cannot// contain '/'. The optional `(?:\d+\/)?` matches the GitHub-specific variant@@ -55,14 +63,14 @@ export function parseGitRemoteUrl(url) {// hop port.const scpMatch = trimmed.match(/^[a-zA-Z0-9._-]+@([^:]+):(?:\d+\/)?([^/]+)\/([^/]+)$/);if (scpMatch) {- return { host: stripPort(scpMatch[1]), owner: scpMatch[2], repo: stripGit(scpMatch[3]) };+ return { host: normalizeHost(scpMatch[1]), owner: scpMatch[2], repo: stripGit(scpMatch[3]) };}// URL-style: scheme://[user@]host(:port)/owner/repo(.git) — repo segment// cannot contain '/'.const urlMatch = trimmed.match(/^[a-zA-Z]+:\/\/(?:[^@/]+@)?([^/]+)\/([^/]+)\/([^/]+)$/);if (urlMatch) {- return { host: stripPort(urlMatch[1]), owner: urlMatch[2], repo: stripGit(urlMatch[3]) };+ return { host: normalizeHost(urlMatch[1]), owner: urlMatch[2], repo: stripGit(urlMatch[3]) };}return null;diff --git a/server/lib/index.js b/server/lib/index.jsindex 15846dac3e..7ed00a9f5b 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -285,6 +285,7 @@ export * from './pathSafety.js';export * from './uploads.js';export * from './icloudFile.js';export * from './spawnCwd.js';+export * from './sshHostAlias.js';export * from './schemaVersions.js';export * from './secretText.js';export * from './imageClean.js';diff --git a/server/lib/sshHostAlias.js b/server/lib/sshHostAlias.jsnew file mode 100644index 0000000000..04228385ad--- /dev/null+++ b/server/lib/sshHostAlias.js@@ -0,0 +1,166 @@+/**+ * Resolve SSH `Host` aliases from `~/.ssh/config` to the real `HostName`.+ *+ * ## Why PortOS needs this+ *+ * The standard way to drive several GitHub accounts from one machine is a+ * per-account SSH alias:+ *+ * # ~/.ssh/config+ * Host github-acme+ * HostName github.com+ * IdentityFile ~/.ssh/id_acme+ *+ * …with the repo's origin set to `git@github-acme:acme/widget.git`. Git and ssh+ * resolve that alias transparently, so the checkout works — but every PortOS+ * code path that classifies a repo by its remote HOST sees the literal string+ * `github-acme` and gets the answer wrong:+ *+ * - `hostToWorkTracker()` doesn't match `github.com` or `github.*`, so the app's+ * work tracker silently degrades to PLAN.md and its GitHub issues are invisible.+ * - `checkGhHealth({ hostname: 'github-acme' })` can't reach an API host by that+ * name, so the CoS forge spawn gate reports the forge unreachable and HOLDS+ * every change-request task for an hour before letting it fail — the symptom+ * that prompted this module ("Holding task … — github-acme is unreachable").+ * - `resolveForgeTokenEnv()` gates its token overlay on `host === 'github.com'`,+ * so an aliased repo's agent never receives the account-pinned `GH_TOKEN` and+ * falls back to gh's mutable active user — the "must be a collaborator" trap.+ *+ * `gh` itself resolves these aliases through the user's ssh config before it+ * picks an API host, so canonicalizing here keeps PortOS's view of a remote and+ * the CLI's view of the same remote in agreement.+ *+ * ## Scope+ *+ * Only literal `Host` → `HostName` pairs are honored. Deliberately NOT handled:+ *+ * - Pattern aliases (`Host *.internal`, `Host !foo`) — a wildcard alias never+ * appears verbatim in a remote URL, so matching one would require re-+ * implementing ssh's matcher for no gain here.+ * - `Match` blocks and `Include` directives — both can make resolution depend on+ * the connecting user, the local network, or another file entirely. A remote's+ * forge identity must not change under PortOS with the network it is on, so an+ * alias we cannot resolve unconditionally is left alone.+ * - `HostName` values containing ssh's `%` tokens (`%h`, `%n`) — those expand at+ * connect time, not parse time.+ *+ * Anything unresolved passes through unchanged, so a plain `github.com` remote,+ * an enterprise host, and an alias we decline to interpret all behave exactly as+ * they did before this module existed.+ */++import { readFileSync, statSync } from 'fs';+import { homedir } from 'os';+import { join } from 'path';++// Re-stat the config at most this often. The map is read from remote-URL parsers+// that run on ordinary request paths, and an ssh config changes about as often as+// a new machine is set up — a stat per parse would be pure overhead.+const STAT_TTL_MS = 5000;++const WILDCARD = /[*?!]/;++let cache = null; // { key, aliases: Map }+let lastStatAt = 0;++/**+ * Parse ssh-config text into a `Map` of lowercased alias → canonical `HostName`.+ *+ * Exported for tests and for callers that already hold the config text; the+ * cached filesystem read lives in `resolveSshHostAlias`.+ *+ * @param {string} text - contents of an ssh config file+ * @returns {Map<string, string>}+ */+export function parseSshHostAliases(text) {+ const aliases = new Map();+ if (!text || typeof text !== 'string') return aliases;++ // ssh config is line-oriented; a keyword and its value may be separated by+ // whitespace or `=`. Host patterns accumulate until the next `Host`/`Match`+ // block starts, and `Match` ends the current block WITHOUT opening one we+ // honor — otherwise a `HostName` under `Match` would be attributed to the+ // Host block above it.+ let current = [];+ for (const rawLine of text.split('\n')) {+ const line = rawLine.replace(/#.*$/, '').trim();+ if (!line) continue;+ const match = line.match(/^(\w+)(?:\s*=\s*|\s+)(.+)$/);+ if (!match) continue;+ const keyword = match[1].toLowerCase();+ const value = match[2].trim();++ if (keyword === 'match') { current = []; continue; }+ if (keyword === 'host') {+ current = value.split(/\s+/).filter(name => name && !WILDCARD.test(name));+ continue;+ }+ if (keyword !== 'hostname' || !current.length) continue;+ // `%h` and friends expand at connect time against the alias itself; there is+ // no stable canonical host to record for them.+ if (value.includes('%')) continue;+ // A `user@host` HostName is legal in some configs; only the host half is the+ // forge identity.+ const hostName = value.includes('@') ? value.slice(value.lastIndexOf('@') + 1) : value;+ if (!hostName) continue;+ for (const alias of current) {+ // First declaration wins, matching ssh's own "first obtained value" rule.+ if (!aliases.has(alias.toLowerCase())) aliases.set(alias.toLowerCase(), hostName);+ }+ }+ return aliases;+}++/**+ * The alias map from `~/.ssh/config`, memoized on the file's size+mtime and+ * re-validated at most once per `STAT_TTL_MS`.+ *+ * A missing or unreadable config is an empty map, not an error: the overwhelming+ * majority of installs have no aliases and must not pay a throw for it.+ */+function loadAliases() {+ const now = Date.now();+ if (cache && now - lastStatAt < STAT_TTL_MS) return cache.aliases;++ const path = join(homedir(), '.ssh', 'config');+ // Sync + guarded: this sits inside synchronous remote-URL parsers, and every+ // failure mode (no file, no permission, a directory) means the same thing —+ // "this install has no aliases to honor".+ let key = null;+ try {+ const stats = statSync(path);+ key = `${stats.size}:${stats.mtimeMs}`;+ } catch {+ key = null;+ }+ lastStatAt = now;+ if (cache && cache.key === key) return cache.aliases;++ let aliases = new Map();+ if (key !== null) {+ try {+ aliases = parseSshHostAliases(readFileSync(path, 'utf8'));+ } catch {+ aliases = new Map();+ }+ }+ cache = { key, aliases };+ return aliases;+}++/**+ * Canonicalize a git-remote host through the user's ssh `Host` aliases.+ *+ * @param {string|null|undefined} host - host as it appears in the remote URL+ * @returns {string|null|undefined} the aliased `HostName`, or `host` unchanged+ */+export function resolveSshHostAlias(host) {+ if (!host || typeof host !== 'string') return host;+ return loadAliases().get(host.toLowerCase()) || host;+}++/** Test seam — drops the memoized ssh-config read. */+export function __resetSshHostAliasCache() {+ cache = null;+ lastStatAt = 0;+}diff --git a/server/lib/sshHostAlias.test.js b/server/lib/sshHostAlias.test.jsnew file mode 100644index 0000000000..f33cecfc23--- /dev/null+++ b/server/lib/sshHostAlias.test.js@@ -0,0 +1,146 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++import { parseSshHostAliases, resolveSshHostAlias, __resetSshHostAliasCache } from './sshHostAlias.js';+import { parseGitRemote, detectForgeCli } from './gitForge.js';+import { parseGitRemoteUrl } from './gitRemote.js';+import { hostFromOriginUrl, hostToWorkTracker } from './workTracker.js';++describe('parseSshHostAliases', () => {+ it('maps every literal alias in a block to its HostName', () => {+ const aliases = parseSshHostAliases([+ '# a comment',+ 'Host github-acme gh-acme',+ ' HostName github.com',+ ' IdentityFile ~/.ssh/id_acme',+ '',+ 'Host gl-internal',+ ' HostName=gitlab.example.com',+ ' Port 2222',+ ].join('\n'));+ expect(Object.fromEntries(aliases)).toEqual({+ 'github-acme': 'github.com',+ 'gh-acme': 'github.com',+ 'gl-internal': 'gitlab.example.com',+ });+ });++ it('declines the patterns ssh resolves at connect time rather than guessing', () => {+ // A wildcard alias never appears verbatim in a remote URL; a Match block's+ // HostName depends on the local network; and `%h` expands per connection.+ // Each must leave NO entry rather than a plausible-looking wrong one.+ const aliases = parseSshHostAliases([+ 'Host *',+ ' HostName fallback.example.com',+ 'Host bastion-?',+ ' HostName bastion.example.com',+ 'Host tunneled',+ ' HostName %h.internal.example.com',+ 'Host after-match',+ 'Match host github.com',+ ' HostName wrong.example.com',+ ].join('\n'));+ expect(aliases.size).toBe(0);+ });++ it('keeps the first HostName for a repeated alias and drops a user@ prefix', () => {+ const aliases = parseSshHostAliases([+ 'Host dup',+ ' HostName [email protected]',+ 'Host dup',+ ' HostName second.example.com',+ ].join('\n'));+ expect(aliases.get('dup')).toBe('first.example.com');+ });++ it('returns an empty map for missing or non-string input', () => {+ expect(parseSshHostAliases('').size).toBe(0);+ expect(parseSshHostAliases(null).size).toBe(0);+ });+});++describe('resolveSshHostAlias', () => {+ let home;++ beforeEach(() => {+ home = mkdtempSync(join(tmpdir(), 'portos-ssh-'));+ mkdirSync(join(home, '.ssh'));+ // `os.homedir()` reads $HOME on POSIX, which is how the module under test+ // finds the config — no module mock needed.+ vi.stubEnv('HOME', home);+ vi.stubEnv('USERPROFILE', home);+ __resetSshHostAliasCache();+ });++ afterEach(() => {+ vi.unstubAllEnvs();+ __resetSshHostAliasCache();+ rmSync(home, { recursive: true, force: true });+ });++ const writeConfig = (text) => writeFileSync(join(home, '.ssh', 'config'), text);++ it('resolves a per-account alias to the host the remote really connects to', () => {+ writeConfig('Host github-acme\n HostName github.com\n');+ expect(resolveSshHostAlias('github-acme')).toBe('github.com');+ // Aliases are case-insensitive to ssh, and a remote may be written either way.+ expect(resolveSshHostAlias('GitHub-Acme')).toBe('github.com');+ });++ it('passes through a host that is not an alias, and non-string input', () => {+ writeConfig('Host github-acme\n HostName github.com\n');+ expect(resolveSshHostAlias('github.com')).toBe('github.com');+ expect(resolveSshHostAlias('gitlab.example.com')).toBe('gitlab.example.com');+ expect(resolveSshHostAlias(null)).toBe(null);+ expect(resolveSshHostAlias('')).toBe('');+ });++ it('treats an absent ssh config as "no aliases" rather than an error', () => {+ expect(() => resolveSshHostAlias('github-acme')).not.toThrow();+ expect(resolveSshHostAlias('github-acme')).toBe('github-acme');+ });+});++describe('remote-host parsers under a multi-account ssh alias', () => {+ // The regression this module exists for: a repo cloned through a per-account+ // alias classified as an unknown host, so CoS reported the forge unreachable+ // and held every change-request task, the work tracker silently fell back to+ // PLAN.md, and agents never received an account-pinned GH_TOKEN. Asserted at+ // all three parsers because each one feeds a different one of those paths.+ let home;++ beforeEach(() => {+ home = mkdtempSync(join(tmpdir(), 'portos-ssh-'));+ mkdirSync(join(home, '.ssh'));+ writeFileSync(join(home, '.ssh', 'config'), 'Host github-acme\n HostName github.com\n IdentityFile ~/.ssh/id_acme\n');+ vi.stubEnv('HOME', home);+ vi.stubEnv('USERPROFILE', home);+ __resetSshHostAliasCache();+ });++ afterEach(() => {+ vi.unstubAllEnvs();+ __resetSshHostAliasCache();+ rmSync(home, { recursive: true, force: true });+ });++ const REMOTE = 'git@github-acme:acme/widget.git';++ it('reports the real forge host, so the repo is a GitHub repo everywhere', () => {+ expect(parseGitRemote(REMOTE)).toEqual({ host: 'github.com', owner: 'acme' });+ expect(parseGitRemoteUrl(REMOTE)).toEqual({ host: 'github.com', owner: 'acme', repo: 'widget' });+ expect(hostFromOriginUrl(REMOTE)).toBe('github.com');+ expect(detectForgeCli(parseGitRemote(REMOTE).host)).toBe('gh');+ expect(hostToWorkTracker(hostFromOriginUrl(REMOTE))).toBe('github');+ });++ it('strips a port before the alias lookup', () => {+ expect(parseGitRemoteUrl('ssh://git@github-acme:22/acme/widget.git').host).toBe('github.com');+ });++ it('leaves an alias the ssh config does not declare alone', () => {+ expect(parseGitRemote('git@github-other:acme/widget.git')).toEqual({ host: 'github-other', owner: 'acme' });+ });+});diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 84f4ca19d1..2927071865 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -299,6 +299,13 @@ export const appSchema = z.object({// cosTaskGenerator.js. WORK_TRACKERS is the single source of truth for the// value set.workTracker: z.enum(WORK_TRACKERS).optional(),+ // The `gh` account login PortOS authenticates AND commits as for this app's+ // repo — how one install drives repos belonging to several GitHub accounts.+ // Unset (the default) keeps the owner-match inference in services/forgeAuth.js+ // and leaves commit authorship to the machine's ambient git config; setting it+ // pins both the token and the GIT_AUTHOR/GIT_COMMITTER identity to that+ // account. Empty string clears the pin.+ forgeAccount: z.string().trim().max(120).optional(),// Layered Intelligence per-app config (the self-improvement loop). Full config// accepted on create/update; the dedicated updateAppLayeredIntelligence merge// (server/services/apps.js) preserves untouched fields on partial PATCHes.diff --git a/server/lib/workTracker.js b/server/lib/workTracker.jsindex 014ffb6975..2a8cfd9fea 100644--- a/server/lib/workTracker.js+++ b/server/lib/workTracker.js@@ -23,6 +23,7 @@ import {formatOptionalIssueLabelFlags,} from './dispatchLabels.js';import { getOriginInfo, readOriginRemoteUrl } from './gitRemote.js';+import { resolveSshHostAlias } from './sshHostAlias.js';import { getAuditFilingPreset, isAuditTaskType, metricLabelFromSlugPrefix } from './auditCatalog.js';// Every selectable value (UI + Zod enum). `'auto'` is the default; the rest are@@ -481,6 +482,10 @@ export function resolveWorkTracker({ configured, host } = {}) {* Embedded credentials are dropped inherently — the `user[:token]@` segment is* matched and discarded, never returned — so a PAT in an https remote can't* leak through `GET /api/apps/:id/work-tracker`. Ports are stripped too.+ *+ * A personal SSH `Host` alias is resolved to the host it connects to, so a repo+ * cloned as `git@github-acme:acme/widget.git` classifies as GitHub rather than+ * silently falling back to PLAN.md. See lib/sshHostAlias.js.*/export function hostFromOriginUrl(url) {if (typeof url !== 'string') return null;@@ -488,10 +493,10 @@ export function hostFromOriginUrl(url) {if (!trimmed) return null;// scheme://[userinfo@]host[:port]/... — host is the run up to the next / : @const scheme = trimmed.match(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\/(?:[^/@]+@)?([^/:]+)/);- if (scheme) return scheme[1] || null;+ if (scheme) return resolveSshHostAlias(scheme[1]) || null;// scp-style [user@]host:pathconst scp = trimmed.match(/^(?:[^@/]+@)?([^/:]+):/);- if (scp) return scp[1] || null;+ if (scp) return resolveSshHostAlias(scp[1]) || null;return null;}diff --git a/server/services/agentAppWorkspace.js b/server/services/agentAppWorkspace.jsindex db4c88ccf7..10e690ab17 100644--- a/server/services/agentAppWorkspace.js+++ b/server/services/agentAppWorkspace.js@@ -71,3 +71,28 @@ export async function getAppDataForTask(task) {return apps[appName] || Object.values(apps).find(a => a.name === appName) || null;}++/**+ * Every managed app that pins an explicit `forgeAccount`, as+ * `[{ repoPath, forgeAccount }]` — empty on the overwhelmingly common install+ * where no app pins one.+ *+ * Forge auth resolves credentials from whatever cwd it was handed (an agent+ * worktree included) and has no app name in scope, so it needs the inverse of+ * `getAppWorkspace`: a path-keyed lookup. Returning only the PINNED apps is what+ * lets that lookup stay free by default — an empty list means forge auth can+ * skip the `git rev-parse` that maps a worktree back to its checkout, so an+ * install that never uses the feature pays one registry read and no subprocess.+ *+ * @returns {Promise<Array<{repoPath: string, forgeAccount: string}>>}+ */+export async function listForgePinnedApps() {+ const data = await readJSONFile(join(ROOT_DIR, 'data/apps.json'), null);+ if (!data) return [];+ const apps = data.apps || data;+ // `Object.values` covers both registry shapes — the array format's values are+ // its elements — so this needs no Array.isArray branch of its own.+ return Object.values(apps)+ .filter(app => app?.repoPath && typeof app.forgeAccount === 'string' && app.forgeAccount.trim())+ .map(app => ({ repoPath: expandHome(app.repoPath), forgeAccount: app.forgeAccount.trim() }));+}diff --git a/server/services/apps.js b/server/services/apps.jsindex ebf3419894..153dcce95d 100644--- a/server/services/apps.js+++ b/server/services/apps.js@@ -444,6 +444,9 @@ export async function createApp(appData) {// concrete tracker (PLAN.md / GitHub / GitLab / JIRA) from the git origin// host at dispatch time — see server/lib/workTracker.js.workTracker: appData.workTracker || 'auto',+ // The gh account this app's repo is driven under. Absent (the default) means+ // "infer from the repo owner" — see services/forgeAuth.js.+ ...(appData.forgeAccount?.trim() ? { forgeAccount: appData.forgeAccount.trim() } : {}),// Only persisted when explicitly sent. Absent means ON (see// repoStateVerificationEnabled), so writing a default here would freeze the// app against a future change of that default — but an explicit `false` ondiff --git a/server/services/forgeAuth.js b/server/services/forgeAuth.jsindex f89e0b8096..20e62ae35c 100644--- a/server/services/forgeAuth.js+++ b/server/services/forgeAuth.js@@ -3,18 +3,21 @@* Keep account probing and token overlays here; repository mutations stay in git.js* and pure remote/account parsing stays in lib/gitForge.js.*/+// Aliased: `spawnCli`'s promise executor already binds `resolve` in its own scope.+import { dirname, isAbsolute, resolve as resolvePath } from 'path';import { spawn } from '../lib/childProcess.js';import { execGitSafe } from '../lib/execGit.js';import { parseGitRemote, detectForgeCli, pickGhAccountForOwner } from '../lib/gitForge.js';+import { listForgePinnedApps } from './agentAppWorkspace.js';const DEFAULT_SPAWN_CLI_TIMEOUT_MS = 10000;-function spawnCli(cmd, args, timeoutMs = DEFAULT_SPAWN_CLI_TIMEOUT_MS, signal) {+function spawnCli(cmd, args, timeoutMs = DEFAULT_SPAWN_CLI_TIMEOUT_MS, signal, env = null) {const timedOut = { code: -1, stdout: '', stderr: 'timed out' };if (signal?.aborted) return Promise.resolve(timedOut);return new Promise((resolve) => {- const child = spawn(cmd, args, { shell: false });+ const child = spawn(cmd, args, { shell: false, ...(env ? { env } : {}) });let stdout = '', stderr = '';let settled = false;let timer;@@ -56,63 +59,164 @@ async function getGhTokenForAccount(login, timeoutMs, signal) {return code === 0 ? stdout.trim() : null;}+/**+ * The MAIN checkout behind `dir`, which may be a worktree.+ *+ * CoS worktrees live under PortOS's own `data/cos/worktrees/<agentId>`, nowhere+ * near the app's `repoPath`, so a registry lookup keyed on the agent's cwd would+ * never match the app the agent is working on. `--git-common-dir` is the shared+ * `.git` both the worktree and its checkout point at, so its parent is the+ * checkout — and for an ordinary (non-worktree) repo it is that repo's own+ * `.git`, making this an identity for the common case.+ *+ * Returns `null` when `dir` is not a repository at all.+ */+async function resolveMainRepoRoot(dir) {+ const { exitCode, stdout } = await execGitSafe(['rev-parse', '--git-common-dir'], dir);+ const gitDir = exitCode === 0 ? (stdout || '').trim() : '';+ if (!gitDir) return null;+ // Older git answers with a path relative to `dir` (`--path-format=absolute`+ // only landed in 2.31), so resolve it before taking the parent.+ const absolute = isAbsolute(gitDir) ? gitDir : resolvePath(dir, gitDir);+ return dirname(absolute);+}++/**+ * The gh account a managed app is explicitly pinned to (`app.forgeAccount`), or+ * `null` to fall back to matching the repo owner against the logged-in accounts.+ *+ * This is what lets one install drive repos belonging to SEVERAL GitHub accounts:+ * owner-matching only works when the repo owner's login happens to be one of the+ * logged-in `gh` accounts, which it is not for an organization repo or any repo+ * whose owner differs from the account that should push to it.+ *+ * Best-effort by construction — a missing registry, an unreadable one, or a repo+ * that belongs to no managed app all mean "no pin", never an error.+ */+async function resolveConfiguredAccount(dir) {+ // The registry read comes first so an install where no app pins an account —+ // every install until someone uses the feature — costs one small JSON read and+ // no extra subprocess on a path that already runs three.+ const pinned = await listForgePinnedApps().catch(() => []);+ if (!pinned.length) return null;+ const root = await resolveMainRepoRoot(dir).catch(() => null);+ if (!root) return null;+ const target = resolvePath(root);+ return pinned.find(app => resolvePath(app.repoPath) === target)?.forgeAccount || null;+}++/**+ * The git commit identity for a gh account, as GitHub itself attributes it.+ *+ * `<id>+<login>@users.noreply.github.com` is the address GitHub links back to an+ * account, so a commit authored with it shows up under that account — which is+ * the point of pinning an app to a non-default account in the first place. The+ * numeric id is REQUIRED for the link: the legacy `<login>@users.noreply` form+ * predates account renames and no longer attributes reliably, so a probe that+ * cannot read the id returns null rather than a plausible-looking address that+ * silently attributes to nobody.+ *+ * @returns {Promise<{name: string, email: string}|null>}+ */+async function getGhCommitIdentity(token, timeoutMs, signal) {+ // Run the probe AS the pinned account. `gh api` otherwise answers for gh's+ // mutable active user, which is exactly the ambient identity this override+ // exists to escape — and the mismatch would be invisible, since the wrong+ // answer is still a well-formed identity.+ const { code, stdout } = await spawnCli(+ 'gh', ['api', 'user', '--hostname', 'github.com', '--jq', '[.id, .login, .name] | @tsv'],+ timeoutMs, signal, { ...process.env, GH_TOKEN: token, GITHUB_TOKEN: token }+ );+ if (code !== 0) return null;+ const [id, login, name] = (stdout || '').trim().split('\t');+ if (!id || !login) return null;+ return { name: name || login, email: `${id}+${login}@users.noreply.github.com` };+}+/*** Resolve the forge CLI + auth env for a given repo directory.- * - For GitHub repos: auto-pins `GH_TOKEN` to the logged-in gh account whose login- * matches the repo owner, so PR creation doesn't depend on `hosts.yml`'s mutable- * `user:` field (avoids the multi-account "must be a collaborator" failure mode).+ * - For GitHub repos: pins `GH_TOKEN` to a specific logged-in gh account, so PR+ * creation doesn't depend on `hosts.yml`'s mutable `user:` field (avoids the+ * multi-account "must be a collaborator" failure mode). The account is the+ * managed app's explicit `forgeAccount` when it has one, and otherwise the+ * logged-in account whose login matches the repo owner.* - For GitLab repos: uses glab as-is. glab is single-user-per-host, so its keyring* already disambiguates by host without the mutable-active-user pitfall.* Falls back to ambient env when no match is possible.- * @param {string} dir - Repository root+ *+ * `identity` is populated ONLY for an explicitly pinned `forgeAccount` — an+ * owner-match is an inference about which credential to use, not a statement+ * about who the commits belong to, so it must not quietly rewrite the authorship+ * of every repo whose owner happens to share a login with a local gh account.+ *+ * @param {string} dir - Repository root (a worktree of one is fine)* @param {object} [opts]* @param {number} [opts.timeoutMs=10000] - Per-process bound for gh auth probes* @param {AbortSignal} [opts.signal] - Cancels active and follow-on gh auth probes+ * @returns {Promise<{cli: string, env: object, host: string|null, owner: string|null,+ * account: string|null, identity: {name: string, email: string}|null}>}*/export async function resolveForgeForRepo(dir, { timeoutMs = DEFAULT_SPAWN_CLI_TIMEOUT_MS, signal } = {}) {const remote = await execGitSafe(['remote', 'get-url', 'origin'], dir);const parsed = parseGitRemote(remote.stdout?.trim());if (!parsed) {- return { cli: 'gh', env: process.env, host: null, owner: null, account: null };+ return { cli: 'gh', env: process.env, host: null, owner: null, account: null, identity: null };}const cli = detectForgeCli(parsed.host);- const ambient = { cli, env: process.env, host: parsed.host, owner: parsed.owner, account: null };+ const base = { cli, env: process.env, host: parsed.host, owner: parsed.owner, identity: null };+ const ambient = { ...base, account: null };if (cli !== 'gh' || signal?.aborted) return ambient;- const accounts = await listGhAccounts(timeoutMs, signal);+ const pinned = await resolveConfiguredAccount(dir);+ if (signal?.aborted) return ambient;++ // A pinned account skips the `gh auth status` listing entirely: the user named+ // the account, so the only question left is whether a token can be minted for+ // it — and a pin that gh is not logged into must fail as "no token", not be+ // silently replaced by an owner-match against a different account.+ const account = pinned || pickGhAccountForOwner(parsed.owner, await listGhAccounts(timeoutMs, signal));if (signal?.aborted) return ambient;- const account = pickGhAccountForOwner(parsed.owner, accounts);- if (!account) return { cli, env: process.env, host: parsed.host, owner: parsed.owner, account: null };+ if (!account) return ambient;const token = await getGhTokenForAccount(account, timeoutMs, signal);- if (signal?.aborted || !token) {- return { cli, env: process.env, host: parsed.host, owner: parsed.owner, account };- }+ if (signal?.aborted || !token) return { ...base, account };++ const identity = pinned ? await getGhCommitIdentity(token, timeoutMs, signal) : null;+ if (signal?.aborted) return { ...base, account };- return { cli, env: { ...process.env, GH_TOKEN: token }, host: parsed.host, owner: parsed.owner, account };+ return { ...base, env: { ...process.env, GH_TOKEN: token }, account, identity };}/*** Resolve just the GitHub-token env overlay for a repo directory, so a spawned* child that runs its own `gh pr create` — a CoS agent, most notably codex,* which is otherwise blind to PortOS's account-pinning — authenticates as the- * gh account whose login matches the repo owner (the same pinning- * `resolveForgeForRepo` gives PortOS's own `createPR`). Two reasons a plain- * env inherit isn't enough: (1) TUI agents run under `buildSafeEnv`, which- * strips `GH_TOKEN` entirely, so the child would fall back to gh's mutable- * `hosts.yml` active user; (2) even when inherited, the ambient token can be- * the wrong account in a multi-login setup ("must be a collaborator").+ * right gh account (the same pinning `resolveForgeForRepo` gives PortOS's own+ * `createPR`). Two reasons a plain env inherit isn't enough: (1) TUI agents run+ * under `buildSafeEnv`, which strips `GH_TOKEN` entirely, so the child would+ * fall back to gh's mutable `hosts.yml` active user; (2) even when inherited,+ * the ambient token can be the wrong account in a multi-login setup ("must be a+ * collaborator").+ *+ * When the app pinned an explicit `forgeAccount`, the overlay also carries that+ * account's `GIT_AUTHOR_` / `GIT_COMMITTER_` identity. Authenticating as another+ * account without it produces commits that carry the machine owner's name and+ * email into someone else's repository — the credential and the authorship have+ * to move together, or "run this app under another GitHub account" is only half+ * true. Env vars rather than `git config`: the override lives and dies with the+ * agent process instead of mutating a repository PortOS does not own, and git+ * gives them precedence over every config level.*- * Returns `{ GH_TOKEN }` only when a github.com repo-owner-matched account and- * token were found; otherwise `{}` so the child keeps whatever gh auth it would- * have used. Best-effort and bounded: never throws, and a stalled `gh` probe- * times out to `{}` so a spawn is never blocked.+ * Returns `{}` when no github.com account and token were resolved, so the child+ * keeps whatever gh auth it would have used. Best-effort and bounded: never+ * throws, and a stalled `gh` probe times out to `{}` so a spawn is never blocked.* @param {string} dir - Repo (or worktree) root* @param {object} [opts]* @param {number} [opts.timeoutMs=10000] - Cap on the git+gh probe before giving up- * @returns {Promise<{ GH_TOKEN?: string }>}+ * @returns {Promise<{ GH_TOKEN?: string, GIT_AUTHOR_NAME?: string, GIT_AUTHOR_EMAIL?: string,+ * GIT_COMMITTER_NAME?: string, GIT_COMMITTER_EMAIL?: string }>}*/export async function resolveForgeTokenEnv(dir, { timeoutMs = 10000 } = {}) {// Keep the whole lookup inside the agent-spawn budget. The shared abort signal@@ -145,5 +249,18 @@ export async function resolveForgeTokenEnv(dir, { timeoutMs = 10000 } = {}) {// the account matched but the token fetch failed.const minted = resolved && resolved.host === 'github.com' && resolved.env !== process.env;const token = minted ? resolved.env.GH_TOKEN : null;- return token ? { GH_TOKEN: token } : {};+ if (!token) return {};+ // Identity rides the SAME gates as the token — it is only ever populated for a+ // minted github.com credential on an explicitly pinned account, so an identity+ // can never be overlaid onto a repo whose token was not.+ const identity = resolved.identity;+ return {+ GH_TOKEN: token,+ ...(identity ? {+ GIT_AUTHOR_NAME: identity.name,+ GIT_AUTHOR_EMAIL: identity.email,+ GIT_COMMITTER_NAME: identity.name,+ GIT_COMMITTER_EMAIL: identity.email,+ } : {}),+ };}diff --git a/server/services/forgeAuth.test.js b/server/services/forgeAuth.test.jsindex 86237b0364..bcadd2e931 100644--- a/server/services/forgeAuth.test.js+++ b/server/services/forgeAuth.test.js@@ -2,8 +2,13 @@ import { EventEmitter } from 'node:events';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';vi.mock('../lib/childProcess.js', () => ({ spawn: vi.fn() }));+// The managed-app registry read is the only thing forge auth needs from the app+// layer; doubling it keeps this suite off the filesystem and makes the pinned+// vs. inferred account split explicit per test.+vi.mock('./agentAppWorkspace.js', () => ({ listForgePinnedApps: vi.fn(async () => []) }));import { spawn } from '../lib/childProcess.js';+import { listForgePinnedApps } from './agentAppWorkspace.js';import { resolveForgeForRepo, resolveForgeTokenEnv } from './forgeAuth.js';// Exercise remote discovery and authentication without a real credential store.@@ -30,6 +35,7 @@ function githubAccount({ host = 'github.com', tokenCode = 0 } = {}) {beforeEach(() => {vi.resetAllMocks();+ listForgePinnedApps.mockResolvedValue([]);vi.stubEnv('GH_TOKEN', 'test-ambient-token');});afterEach(() => {@@ -43,7 +49,7 @@ describe('forge credential resolution', () => {const forge = await resolveForgeForRepo('/example/repo');expect(forge).toEqual({cli: 'gh', host: 'github.com', owner: 'example-owner', account: 'example-owner',- env: { ...process.env, GH_TOKEN: 'test-owner-token' }+ env: { ...process.env, GH_TOKEN: 'test-owner-token' }, identity: null});expect(spawn).toHaveBeenNthCalledWith(3, 'gh', ['auth', 'token', '-u', 'example-owner', '-h', 'github.com'], { shell: false });expect(process.env.GH_TOKEN).toBe('test-ambient-token');@@ -65,7 +71,7 @@ describe('forge credential resolution', () => {it('keeps GitLab host auth ambient and never probes GitHub accounts', async () => {respond({ stdout: '[email protected]:group/project.git\n' });const forge = await resolveForgeForRepo('/example/repo');- expect(forge).toEqual({ cli: 'glab', host: 'gitlab.example.com', owner: 'group', account: null, env: process.env });+ expect(forge).toEqual({ cli: 'glab', host: 'gitlab.example.com', owner: 'group', account: null, env: process.env, identity: null });expect(forge.env).toBe(process.env);expect(spawn).toHaveBeenCalledTimes(1);});@@ -147,3 +153,82 @@ describe('forge credential resolution', () => {expect(spawn).toHaveBeenCalledTimes(1);});});++describe('per-app forge account pinning', () => {+ // `git remote get-url origin` → `git rev-parse --git-common-dir` (only when an+ // app pins an account) → `gh auth token` → `gh api user`. `gh auth status` is+ // deliberately absent: a named account is not something to second-guess+ // against the owner.+ function pinnedAccount({ tokenCode = 0, identity = '4242\tacme-bot\tAcme Bot\n', identityCode = 0 } = {}) {+ listForgePinnedApps.mockResolvedValue([{ repoPath: '/example/repo', forgeAccount: 'acme-bot' }]);+ respond({ stdout: '[email protected]:acme/widget.git\n' });+ respond({ stdout: '/example/repo/.git\n' });+ respond({ stdout: tokenCode === 0 ? 'acme-bot-token\n' : '', code: tokenCode });+ respond({ stdout: identity, code: identityCode });+ }++ it('authenticates and commits as the pinned account, not the repo owner', async () => {+ pinnedAccount();+ await expect(resolveForgeTokenEnv('/example/repo')).resolves.toEqual({+ GH_TOKEN: 'acme-bot-token',+ GIT_AUTHOR_NAME: 'Acme Bot',+ GIT_AUTHOR_EMAIL: '[email protected]',+ GIT_COMMITTER_NAME: 'Acme Bot',+ GIT_COMMITTER_EMAIL: '[email protected]',+ });+ // The owner (`acme`) never matched a logged-in login, so the pre-pin code+ // would have resolved no account at all — and `gh auth status` is not run.+ expect(spawn).toHaveBeenCalledTimes(4);+ expect(spawn).toHaveBeenNthCalledWith(3, 'gh', ['auth', 'token', '-u', 'acme-bot', '-h', 'github.com'], { shell: false });+ });++ it('runs the identity probe as the pinned account rather than gh\u2019s active user', async () => {+ pinnedAccount();+ await resolveForgeTokenEnv('/example/repo');+ const [, args, options] = spawn.mock.calls[3];+ expect(args).toContain('user');+ expect(options.env.GH_TOKEN).toBe('acme-bot-token');+ });++ it('still pins the token when the identity probe fails', async () => {+ // A commit authored as nobody is worse than one authored ambiently, so an+ // unreadable identity must drop the override without dropping the credential.+ pinnedAccount({ identityCode: 1 });+ await expect(resolveForgeTokenEnv('/example/repo')).resolves.toEqual({ GH_TOKEN: 'acme-bot-token' });+ });++ it('does not fall back to an owner match when the pinned account has no token', async () => {+ pinnedAccount({ tokenCode: 1 });+ await expect(resolveForgeTokenEnv('/example/repo')).resolves.toEqual({});+ });++ it('maps an agent worktree back to the checkout the pin is registered against', async () => {+ listForgePinnedApps.mockResolvedValue([{ repoPath: '/example/repo', forgeAccount: 'acme-bot' }]);+ respond({ stdout: '[email protected]:acme/widget.git\n' });+ // A CoS worktree lives under PortOS's own data dir and never matches an+ // app repoPath; --git-common-dir is what points back at the checkout.+ respond({ stdout: '/example/repo/.git\n' });+ respond({ stdout: 'acme-bot-token\n' });+ respond({ stdout: '4242\tacme-bot\t\n' });+ const env = await resolveForgeTokenEnv('/portos/data/cos/worktrees/agent-1');+ // A null `.name` falls back to the login rather than committing as "".+ expect(env.GIT_AUTHOR_NAME).toBe('acme-bot');+ expect(env.GH_TOKEN).toBe('acme-bot-token');+ });++ it('leaves an unpinned app on the inferred account with ambient commit identity', async () => {+ githubAccount();+ await expect(resolveForgeTokenEnv('/example/repo')).resolves.toEqual({ GH_TOKEN: 'test-owner-token' });+ // No rev-parse: nothing pins an account, so the worktree lookup is skipped.+ expect(spawn).toHaveBeenCalledTimes(3);+ });++ it('ignores a pin registered against a different repository', async () => {+ listForgePinnedApps.mockResolvedValue([{ repoPath: '/other/repo', forgeAccount: 'acme-bot' }]);+ respond({ stdout: '[email protected]:example-owner/project.git\n' });+ respond({ stdout: '/example/repo/.git\n' });+ respond({ stderr: 'Logged in to github.com account example-owner\n' });+ respond({ stdout: 'test-owner-token\n' });+ await expect(resolveForgeTokenEnv('/example/repo')).resolves.toEqual({ GH_TOKEN: 'test-owner-token' });+ });+});