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
address review (self): pin updateRepoFlags, stop deleting private repos on scope loss
[._.]/ Adam Eivy85de2dd734e8
diff --git a/client/src/pages/GitHub.jsx b/client/src/pages/GitHub.jsxindex cd98daa89a..5e7f5a687e 100644--- a/client/src/pages/GitHub.jsx+++ b/client/src/pages/GitHub.jsx@@ -63,6 +63,7 @@ export default function GitHub() {setSecrets(secretsData || {});setAuthStatus(statusData);setLastSync(statusData?.lastRepoSync || null);+ setRepoListTruncated(statusData?.lastRepoSyncTruncated === true);setLoading(false);};@@ -75,14 +76,21 @@ export default function GitHub() {if (result) {setRepos(result.repos || {});setLastSync(result.lastRepoSync);- setAuthStatus(prev => prev ? { ...prev, githubUser: result.githubUser } : prev);setRepoListTruncated(result.truncated === true);if (result.truncated) {- toast.warning(`Loaded the first ${Object.keys(result.repos || {}).length} repositories. Narrower or paginated sync is not available yet.`);+ toast.warning('GitHub returned its repository listing limit. Some repositories may be missing; cached entries were preserved.');} else {toast.success(`Synced ${Object.keys(result.repos || {}).length} repos`);}}+ // Re-derive auth status from the server regardless of outcome — a sync+ // is the freshest signal about which account is actually authenticated.+ // Patching only `githubUser` in place left `login` stale (inverting the+ // account-mismatch banner after a legitimate account switch), and a+ // failed sync's 401/409 was otherwise dropped, leaving a stale+ // `authenticated: true` state that kept every mutating control enabled.+ const statusData = await getGitHubStatus({ silent: true }).catch(() => null);+ if (statusData) setAuthStatus(statusData);setSyncing(false);};diff --git a/scripts/migrations/341-github-repos-owner-reset.js b/scripts/migrations/341-github-repos-owner-reset.jsnew file mode 100644index 0000000000..aecea9f5f9--- /dev/null+++ b/scripts/migrations/341-github-repos-owner-reset.js@@ -0,0 +1,45 @@+/**+ * Clear the hardcoded maintainer default out of `data/github-repos.json`.+ *+ * Before this fix, `defaultData()` seeded `githubUser: 'atomantic'` and+ * `syncRepos()` never wrote a different value back — `const owner =+ * data.githubUser || 'atomantic'` read the field but nothing ever assigned to+ * it. So on every fork install that ever ran a sync, `gh repo list atomantic`+ * (the upstream maintainer's own login) executed regardless of which account+ * the local user actually authenticated as, and `githubUser` stayed+ * `'atomantic'` in the persisted file forever. `getRepos()` now filters by+ * that field (`reposForAccount`), so an install carrying the stale value would+ * otherwise see its cached list as "belonging to the current account" (if it+ * happens to also be `atomantic`) or get permanently 409'd on every mutation+ * with no obvious way out (if it is not).+ *+ * This resets `githubUser` to `null` wherever it is still exactly the shipped+ * default, forcing the same "sign in and sync" path a fresh install takes.+ * The underlying `repos` map is left untouched: per-repo `flags` /+ * `managedSecrets` are keyed by `fullName`, not by owner, so a real sync+ * afterward reattaches them to the correct entries automatically — including,+ * on the upstream maintainer's own machine, resolving right back to+ * `'atomantic'` with nothing lost.+ */++import { join } from 'path';+import { atomicWrite, readJSONFileStrict } from '../../server/lib/fileUtils.js';++const REPOS_PATH = join('data', 'github-repos.json');+const STALE_DEFAULT_OWNER = 'atomantic';++export default {+ async up({ rootDir }) {+ const path = join(rootDir, REPOS_PATH);+ const { ok, value: data } = await readJSONFileStrict(path, null);+ if (!ok || data === null) return { reset: false, reason: 'no readable github-repos.json' };+ if (data.githubUser !== STALE_DEFAULT_OWNER) {+ return { reset: false, reason: 'githubUser is not the shipped default' };+ }++ data.githubUser = null;+ await atomicWrite(path, JSON.stringify(data, null, 2) + '\n');+ console.log(`🔧 ${REPOS_PATH}: cleared the hardcoded '${STALE_DEFAULT_OWNER}' owner; next sync reattaches the authenticated account`);+ return { reset: true };+ },+};diff --git a/scripts/migrations/341-github-repos-owner-reset.test.js b/scripts/migrations/341-github-repos-owner-reset.test.jsnew file mode 100644index 0000000000..0cefc8ba08--- /dev/null+++ b/scripts/migrations/341-github-repos-owner-reset.test.js@@ -0,0 +1,78 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import migration from './341-github-repos-owner-reset.js';++describe('migration 341 — github-repos.json stale owner reset', () => {+ let rootDir;+ let reposPath;++ const writeRepos = (data) => {+ mkdirSync(join(rootDir, 'data'), { recursive: true });+ writeFileSync(reposPath, `${JSON.stringify(data, null, 2)}\n`);+ };+ const readRepos = () => JSON.parse(readFileSync(reposPath, 'utf8'));++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-341-'));+ reposPath = join(rootDir, 'data', 'github-repos.json');+ });++ afterEach(() => rmSync(rootDir, { recursive: true, force: true }));++ it('skips a fresh install with no github-repos.json', async () => {+ await expect(migration.up({ rootDir })).resolves.toEqual({+ reset: false,+ reason: 'no readable github-repos.json',+ });+ });++ it('resets a cache still carrying the shipped default owner', async () => {+ writeRepos({+ repos: {+ 'atomantic/portos': { fullName: 'atomantic/portos', flags: {}, managedSecrets: [] },+ },+ secrets: {},+ lastRepoSync: '2026-01-01T00:00:00.000Z',+ githubUser: 'atomantic',+ });++ await expect(migration.up({ rootDir })).resolves.toEqual({ reset: true });++ const data = readRepos();+ expect(data.githubUser).toBeNull();+ // The repo map is left alone — a real sync reattaches flags/managedSecrets+ // by fullName regardless of which account they were last tagged under.+ expect(data.repos['atomantic/portos']).toEqual({+ fullName: 'atomantic/portos',+ flags: {},+ managedSecrets: [],+ });+ });++ it('leaves an install alone once it has synced under a real, different account', async () => {+ writeRepos({+ repos: {},+ secrets: {},+ lastRepoSync: '2026-01-01T00:00:00.000Z',+ githubUser: 'example-user',+ });++ await expect(migration.up({ rootDir })).resolves.toEqual({+ reset: false,+ reason: 'githubUser is not the shipped default',+ });+ expect(readRepos().githubUser).toBe('example-user');+ });++ it('is idempotent — a second run on an already-reset cache is a no-op', async () => {+ writeRepos({ repos: {}, secrets: {}, lastRepoSync: null, githubUser: 'atomantic' });++ await migration.up({ rootDir });+ await expect(migration.up({ rootDir })).resolves.toEqual({+ reset: false,+ reason: 'githubUser is not the shipped default',+ });+ });+});diff --git a/server/services/github.js b/server/services/github.jsindex 1256c9cd6b..5553c565b1 100644--- a/server/services/github.js+++ b/server/services/github.js@@ -25,6 +25,7 @@ const defaultData = () => ({repos: {},secrets: {},lastRepoSync: null,+ lastRepoSyncTruncated: false,githubUser: null});@@ -165,11 +166,23 @@ export async function syncRepos() {}const owner = auth.login;const raw = await execGh([- 'repo', 'list', owner, '--limit', String(REPO_SYNC_LIMIT),+ // Ask for one more than REPO_SYNC_LIMIT so the boundary case (the+ // account owns exactly REPO_SYNC_LIMIT repos) is distinguishable from+ // an actually-truncated listing: the extra row, if present, IS the+ // truncation signal.+ 'repo', 'list', owner, '--limit', String(REPO_SYNC_LIMIT + 1),'--json', 'name,nameWithOwner,description,pushedAt,isArchived,isPrivate,isFork,parent,licenseInfo'], DEFAULT_EXEC_GH_TIMEOUT_MS, { env: auth.env });- const remoteRepos = JSON.parse(raw);- const { data, removed, listingMayBeTruncated } = await queueDataWrite(async () => {+ const parsedRepos = safeJSONParse(raw, null);+ if (!Array.isArray(parsedRepos)) {+ throw new ServerError('GitHub returned an unreadable repository listing. Try syncing again.', {+ status: 502,+ code: 'GITHUB_LISTING_UNPARSEABLE'+ });+ }+ const listingMayBeTruncated = parsedRepos.length > REPO_SYNC_LIMIT;+ const remoteRepos = listingMayBeTruncated ? parsedRepos.slice(0, REPO_SYNC_LIMIT) : parsedRepos;+ const { data, removed, missingFromRemote } = await queueDataWrite(async () => {const current = await load();const remoteNames = new Set();@@ -193,21 +206,39 @@ export async function syncRepos() {};}- const listingMayBeTruncated = remoteRepos.length >= REPO_SYNC_LIMIT;- const removed = listingMayBeTruncated+ // A zero-exit `gh repo list` is only authoritative for what THIS+ // credential can see — a token that lost `repo` scope still exits 0+ // with a valid (non-truncated) listing of public repos only. Deleting+ // on that answer would destroy a private repo's flags/managedSecrets+ // for no reason but a scope change. Only drop cached rows that carry+ // no user configuration; anything else is stamped, not deleted, so a+ // real deletion still eventually clears once nothing is left to lose.+ const candidates = listingMayBeTruncated? []: Object.entries(current.repos)- .filter(([, repo]) => repoBelongsToAccount(repo, owner) && !remoteNames.has(repo.fullName))- .map(([fullName]) => fullName);- for (const fullName of removed) delete current.repos[fullName];+ .filter(([, repo]) => repoBelongsToAccount(repo, owner) && !remoteNames.has(repo.fullName));+ const removed = [];+ const missingFromRemote = [];+ for (const [fullName, repo] of candidates) {+ const hasUserState = repo.managedSecrets?.length > 0 || Object.keys(repo.flags || {}).length > 0;+ if (hasUserState) {+ repo.missingFromRemote = new Date().toISOString();+ missingFromRemote.push(fullName);+ } else {+ delete current.repos[fullName];+ removed.push(fullName);+ }+ }current.lastRepoSync = new Date().toISOString();+ current.lastRepoSyncTruncated = listingMayBeTruncated;current.githubUser = owner;await save(current);- return { data: current, removed, listingMayBeTruncated };+ return { data: current, removed, missingFromRemote };});const removedMsg = removed.length ? `, removed ${removed.length} deleted` : '';- console.log(`🔄 Synced ${remoteRepos.length} repos from GitHub${removedMsg}`);+ const missingMsg = missingFromRemote.length ? `, flagged ${missingFromRemote.length} missing-with-config` : '';+ console.log(`🔄 Synced ${remoteRepos.length} repos from GitHub${removedMsg}${missingMsg}`);if (listingMayBeTruncated) {console.log(`⚠️ GitHub repo list reached ${REPO_SYNC_LIMIT}; unmatched cached repos were preserved`);}@@ -248,6 +279,7 @@ export async function getRepos() {* Update repo flags and managed secrets*/export async function updateRepoFlags(fullName, updates) {+ await requireActiveCachedAccount(await load());return queueDataWrite(async () => {const data = await load();const repo = data.repos[fullName];@@ -299,6 +331,10 @@ export async function setSecret(name, value) {await save(data);});+ // Call the unwrapped `*Now` form, not `syncSecretToRepos` — `setSecret` is+ // already inside `withGitHubMutation`, and the mutex is non-reentrant with+ // no timeout, so re-entering it here would deadlock every GitHub mutation+ // for the life of the process.return syncSecretToReposNow(name);});}@@ -388,7 +424,14 @@ export async function setRepoArchived(fullName, archived) {const updated = await queueDataWrite(async () => {const current = await load();if (!current.repos[fullName] || current.githubUser?.toLowerCase() !== auth.login.toLowerCase()) {- return { ...data.repos[fullName], isArchived: archived };+ // The archive/unarchive call above already ran against GitHub, but the+ // account changed underneath us before we could persist it — report+ // the mismatch rather than returning an unpersisted "success" that+ // would silently drift from the cache on the next load.+ throw new ServerError('The repository cache changed accounts during this action. Sync repositories to refresh.', {+ status: 409,+ code: 'GITHUB_ACCOUNT_MISMATCH'+ });}current.repos[fullName].isArchived = archived;await save(current);@@ -418,6 +461,7 @@ export async function getStatus() {...auth,githubUser: data.githubUser || null,lastRepoSync: data.lastRepoSync,+ lastRepoSyncTruncated: data.lastRepoSyncTruncated === true,totalRepos: repos.length,activeRepos: repos.filter(r => !r.isArchived).length,npmProjects: repos.filter(r => r.flags?.npmProject).length,@@ -597,10 +641,18 @@ export async function checkGhHealth({ force = false, timeoutMs = GH_PROBE_TIMEOU}/**- * Resolve the account the GitHub CLI will actually use. A successful `api user`- * is stronger than merely finding a token: it proves the credential works and- * gives repo sync the owner it must query. The login is returned only to the- * local UI; the credential inventory reduces this to presence/source.+ * Resolve the account the GitHub CLI will actually use ON GITHUB.COM. A+ * successful `api user` is stronger than merely finding a token: it proves+ * the credential works and gives repo sync the owner it must query. The login+ * is returned only to the local UI; the credential inventory reduces this to+ * presence/source.+ *+ * Unlike `checkGhHealth`/`probeGh` below (which accept a `hostname` for a+ * GitHub Enterprise forge), this repo-sync feature is intentionally+ * github.com-only — the UI it backs links directly to `https://github.com/…`+ * and lists the account's own personal/org repos, not a per-project managed+ * host. Do not thread an enterprise hostname through here without also+ * reworking that UI.*/export async function getGitHubAuthStatus({ env = process.env } = {}) {const credentialSource = githubCredentialSource(env);@@ -642,7 +694,17 @@ async function getPinnedGitHubAuth() {const token = environmentToken || await execGh(['auth', 'token', '--user', status.login, '--hostname', GITHUB_HOST,- ], GH_PROBE_TIMEOUT_MS, { env: githubDotComEnv(baseEnv) }).catch(() => null);+ ], GH_PROBE_TIMEOUT_MS, { env: githubDotComEnv(baseEnv) })+ // `--user` on `gh auth token` is a relatively recent flag. PortOS installs+ // upgrade independently, so an older local `gh` is a normal state, not an+ // edge case — fall back to the unqualified form, which still resolves to+ // the single active account `getGitHubAuthStatus` just verified.+ .catch(() => execGh(+ ['auth', 'token', '--hostname', GITHUB_HOST],+ GH_PROBE_TIMEOUT_MS,+ { env: githubDotComEnv(baseEnv) },+ ))+ .catch(() => null);if (!token) {throw new ServerError('Could not pin the active GitHub credential. Re-authenticate with gh and try again.', {status: 503,diff --git a/server/services/github.test.js b/server/services/github.test.jsindex 518c5348ae..3f449f1894 100644--- a/server/services/github.test.js+++ b/server/services/github.test.js@@ -394,6 +394,27 @@ describe('GitHub repository sync account selection', () => {expect(mock.spawn.mock.calls[2][2].env.GITHUB_TOKEN).toBeUndefined();});+ it('falls back to the unqualified token command on a gh build without --user', async () => {+ vi.stubEnv('GH_TOKEN', '');+ vi.stubEnv('GITHUB_TOKEN', '');+ mock.spawn.mockImplementation((_command, args) => {+ if (args[0] === 'api') return childReturning('example-user');+ // Older gh: `auth token --user <login>` fails, but the unqualified form+ // (single active account) still resolves.+ if (args.includes('--user')) return childFailing('unknown flag: --user');+ if (args[0] === 'auth') return childReturning('fake-pinned-token');+ return childReturning('[]');+ });++ await syncRepos();++ expect(mock.spawn.mock.calls[2][1]).toEqual(['auth', 'token', '--hostname', 'github.com']);+ expect(mock.spawn.mock.calls[3][2].env).toMatchObject({+ GH_HOST: 'github.com',+ GH_TOKEN: 'fake-pinned-token',+ });+ });+it('refuses to push secrets while cached repositories belong to another account', async () => {vi.stubEnv('GH_TOKEN', 'fake-example-token');mock.readJSONFile.mockResolvedValue({@@ -439,6 +460,25 @@ describe('GitHub repository sync account selection', () => {expect(mock.spawn).toHaveBeenCalledTimes(1);});+ it('refuses to update flags on a cached repository owned by another account', async () => {+ vi.stubEnv('GH_TOKEN', 'fake-example-token');+ mock.spawn.mockImplementation(() => childReturning('example-user'));++ await expect(updateRepoFlags('legacy-owner/old-repo', { flags: { npmProject: true } })).rejects.toMatchObject({+ status: 409,+ code: 'GITHUB_ACCOUNT_MISMATCH',+ });+ });++ it('refuses to update flags while gh is not authenticated', async () => {+ mock.spawn.mockImplementation(() => childFailing('You are not logged in. Run gh auth login.'));++ await expect(updateRepoFlags('legacy-owner/old-repo', { flags: { npmProject: true } })).rejects.toMatchObject({+ status: 401,+ code: 'GITHUB_NOT_AUTHENTICATED',+ });+ });+it('refuses to archive a repository that is not in the authenticated account cache', async () => {mock.readJSONFile.mockResolvedValue({repos: {},@@ -542,7 +582,19 @@ describe('GitHub repository sync account selection', () => {vi.useRealTimers();});- it('does not delete cached repositories when the GitHub listing reaches its limit', async () => {+ const listedRepos = (count) => Array.from({ length: count }, (_, index) => ({+ name: `repo-${index}`,+ nameWithOwner: `example-user/repo-${index}`,+ description: '',+ pushedAt: null,+ isArchived: false,+ isPrivate: false,+ isFork: false,+ parent: null,+ licenseInfo: null,+ }));++ it('does not delete cached repositories when the GitHub listing is actually truncated', async () => {vi.stubEnv('GH_TOKEN', 'fake-example-token');mock.readJSONFile.mockResolvedValue({repos: {@@ -557,24 +609,107 @@ describe('GitHub repository sync account selection', () => {lastRepoSync: null,githubUser: 'example-user',});- const listed = Array.from({ length: 200 }, (_, index) => ({- name: `repo-${index}`,- nameWithOwner: `example-user/repo-${index}`,- description: '',- pushedAt: null,- isArchived: false,- isPrivate: false,- isFork: false,- parent: null,- licenseInfo: null,- }));+ // The service now asks for REPO_SYNC_LIMIT + 1 so the extra row IS the+ // truncation signal — 201 here, not 200.+ const listed = listedRepos(201);mock.spawn.mockImplementation((_command, args) => (args[0] === 'api' ? childReturning('example-user') : childReturning(JSON.stringify(listed))));const result = await syncRepos();+ expect(result.truncated).toBe(true);expect(result.repos['example-user/keep-me']).toBeTruthy();+ expect(Object.keys(result.repos)).toHaveLength(201); // 200 listed + 1 preserved+ });++ it('does not treat exactly REPO_SYNC_LIMIT repos as truncated', async () => {+ vi.stubEnv('GH_TOKEN', 'fake-example-token');+ mock.readJSONFile.mockResolvedValue({+ repos: {+ 'example-user/deleted-on-github': {+ name: 'deleted-on-github',+ fullName: 'example-user/deleted-on-github',+ flags: {},+ managedSecrets: [],+ },+ },+ secrets: {},+ lastRepoSync: null,+ githubUser: 'example-user',+ });+ const listed = listedRepos(200);+ mock.spawn.mockImplementation((_command, args) => (+ args[0] === 'api' ? childReturning('example-user') : childReturning(JSON.stringify(listed))+ ));++ const result = await syncRepos();++ // Exactly 200 repos is a complete listing, not a truncated one — a repo+ // that genuinely no longer exists on GitHub is still pruned.+ expect(result.truncated).toBe(false);+ expect(result.repos['example-user/deleted-on-github']).toBeUndefined();+ expect(Object.keys(result.repos)).toHaveLength(200);+ });++ it('preserves a cached repo with configured flags or secrets when a scope-degraded credential omits it, but still prunes an unconfigured one', async () => {+ vi.stubEnv('GH_TOKEN', 'fake-example-token');+ mock.readJSONFile.mockResolvedValue({+ repos: {+ // Not returned by the (scope-limited) listing below, but carries user+ // configuration — must be preserved, not deleted, even though the+ // listing is NOT truncated.+ 'example-user/private-configured': {+ name: 'private-configured',+ fullName: 'example-user/private-configured',+ flags: { npmProject: true },+ managedSecrets: ['NPM_TOKEN'],+ },+ // Also missing from the listing, but carries no configuration — a+ // real deletion (or an unconfigured repo made private by the same+ // scope loss) is still pruned rather than accumulating forever.+ 'example-user/private-unconfigured': {+ name: 'private-unconfigured',+ fullName: 'example-user/private-unconfigured',+ flags: {},+ managedSecrets: [],+ },+ },+ secrets: {},+ lastRepoSync: null,+ githubUser: 'example-user',+ });+ // A credential that lost `repo` scope still exits 0 with a valid, public-+ // only, NON-truncated listing.+ mock.spawn.mockImplementation((_command, args) => (+ args[0] === 'api' ? childReturning('example-user') : childReturning('[]')+ ));++ const result = await syncRepos();++ expect(result.truncated).toBe(false);+ expect(result.repos['example-user/private-configured']).toMatchObject({+ flags: { npmProject: true },+ managedSecrets: ['NPM_TOKEN'],+ });+ expect(result.repos['example-user/private-unconfigured']).toBeUndefined();+ const persisted = JSON.parse(mock.atomicWrite.mock.calls.at(-1)[1]);+ expect(persisted.repos['example-user/private-configured'].missingFromRemote).toEqual(expect.any(String));+ });++ it('rejects an unparseable repository listing instead of throwing a bare SyntaxError', async () => {+ vi.stubEnv('GH_TOKEN', 'fake-example-token');+ mock.readJSONFile.mockResolvedValue({+ repos: {}, secrets: {}, lastRepoSync: null, githubUser: 'example-user',+ });+ mock.spawn.mockImplementation((_command, args) => (+ args[0] === 'api' ? childReturning('example-user') : childReturning('not json')+ ));++ await expect(syncRepos()).rejects.toMatchObject({+ status: 502,+ code: 'GITHUB_LISTING_UNPARSEABLE',+ });});it('preserves another account\'s repository configuration across account switches', async () => {@@ -610,6 +745,7 @@ describe('GitHub repository sync account selection', () => {it('serializes concurrent updates to the shared repository cache', async () => {let releaseFirstWrite;+ vi.stubEnv('GH_TOKEN', 'fake-example-token');mock.readJSONFile.mockResolvedValue({repos: {'example-user/example-repo': {@@ -623,6 +759,7 @@ describe('GitHub repository sync account selection', () => {lastRepoSync: null,githubUser: 'example-user',});+ mock.spawn.mockImplementation(() => childReturning('example-user'));mock.atomicWrite.mockImplementationOnce(() => new Promise((resolve) => { releaseFirstWrite = resolve; })).mockResolvedValue(undefined);