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: preserve reference study snapshots (#4412)
[._.]/ Adam Eivy84de3b48faba
diff --git a/.changelog/next/fixed-issue-4412.md b/.changelog/next/fixed-issue-4412.mdnew file mode 100644index 0000000000..b688e4db34--- /dev/null+++ b/.changelog/next/fixed-issue-4412.md@@ -0,0 +1 @@+- Keep the last successful reference-repository check visible when a refresh temporarily fails.diff --git a/client/src/components/apps/ReferenceReposPanel.jsx b/client/src/components/apps/ReferenceReposPanel.jsxindex 61ad0c3faa..2a251a7edd 100644--- a/client/src/components/apps/ReferenceReposPanel.jsx+++ b/client/src/components/apps/ReferenceReposPanel.jsx@@ -3,7 +3,7 @@ import { GitBranch, Plus, RefreshCw, Trash2, CheckCircle, AlertCircle, Edit3, Ximport toast from '../ui/Toast';import FormField from '../ui/FormField';import * as api from '../../services/api';-import { formatDateTime } from '../../utils/formatters';+import { formatDateTime, formatDurationMs } from '../../utils/formatters';// The add-reference form is dense, so its labels sit a step below FormField's// default size rather than the config-page default.@@ -138,6 +138,11 @@ export default function ReferenceReposPanel({ appId, appName }) {return;}setSnapshots((prev) => ({ ...prev, [ref.id]: snap }));+ if (snap.stale) {+ toast.error(`${ref.name}: latest check failed — showing the saved result from ${formatDateTime(snap.fetchedAt)}. Retry before relying on it.`);+ fetch();+ return;+ }const commitMsg = `${ref.name}: ${snap.commitCount} new commit${snap.commitCount === 1 ? '' : 's'}`;if (snap.analysis?.queued) {toast.success(`${commitMsg} — analysis task queued`);@@ -247,6 +252,13 @@ export default function ReferenceReposPanel({ appId, appName }) {}function StatusBadge({ status, lastError }) {+ if (status === 'stale') {+ return (+ <span className="px-1.5 py-0.5 bg-port-warning/20 text-port-warning text-[10px] rounded inline-flex items-center gap-1" title={lastError || 'Latest check failed; showing a saved result'}>+ <AlertCircle size={10} /> stale+ </span>+ );+ }if (status === 'error') {return (<span className="px-1.5 py-0.5 bg-port-error/20 text-port-error text-[10px] rounded inline-flex items-center gap-1" title={lastError || 'Last check failed'}>@@ -364,6 +376,12 @@ function RefRow({ reference, snapshot, checking, editingNotes, onCheck, onMarkRe</div>) : null}+ {snapshot?.stale && (+ <div role="status" className="bg-port-warning/10 border border-port-warning/40 text-port-warning text-xs rounded p-2 inline-flex items-center gap-2">+ <AlertCircle size={12} /> Latest check failed. Showing saved results from {formatDateTime(snapshot.fetchedAt)} ({formatDurationMs(snapshot.staleAgeMs)} old); retry before marking this reference reviewed. {snapshot.error?.message || reference.lastError}+ </div>+ )}+{snapshot?.commits?.length > 0 && (<details className="text-xs text-gray-300"><summary className="cursor-pointer text-gray-400 hover:text-white">diff --git a/client/src/components/apps/ReferenceReposPanel.test.jsx b/client/src/components/apps/ReferenceReposPanel.test.jsxnew file mode 100644index 0000000000..9cdabd4fa7--- /dev/null+++ b/client/src/components/apps/ReferenceReposPanel.test.jsx@@ -0,0 +1,58 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';++const api = vi.hoisted(() => ({+ listReferenceRepos: vi.fn(),+ getAppWorkTracker: vi.fn(),+ checkReferenceRepo: vi.fn(),+}));++vi.mock('../../services/api', () => api);+vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));++import ReferenceReposPanel from './ReferenceReposPanel';++const reference = {+ id: 'ref-1',+ name: 'Example upstream',+ repoUrl: 'https://example.com/upstream.git',+ branch: 'main',+ status: 'stale',+ lastError: 'git fetch failed',+ lastCheckedAt: '2026-08-16T00:00:00.000Z',+ lastReviewedSha: null,+};++beforeEach(() => {+ vi.clearAllMocks();+ api.listReferenceRepos.mockResolvedValue({ referenceRepos: [reference] });+ api.getAppWorkTracker.mockResolvedValue({ resolved: 'github' });+ api.checkReferenceRepo.mockResolvedValue({+ schemaVersion: 1,+ fetchedAt: '2026-08-15T00:00:00.000Z',+ head: 'a'.repeat(40),+ commitCount: 1,+ commits: [{ sha: 'a'.repeat(40), author: 'Alice', date: '2026-08-15T00:00:00.000Z', subject: 'saved commit' }],+ stale: true,+ staleAgeMs: 86_400_000,+ error: { code: 'REFERENCE_REPO_GIT_FAILED', message: 'temporary outage' },+ });+});++afterEach(cleanup);++describe('ReferenceReposPanel stale checks', () => {+ it('renders the stale state and keeps the saved snapshot visibly distinct after a failed check', async () => {+ render(<ReferenceReposPanel appId="app-1" appName="Example App" />);+ expect(await screen.findByText('stale')).toBeInTheDocument();++ fireEvent.click(screen.getByRole('button', { name: /check/i }));++ const notice = await screen.findByRole('status');+ expect(notice).toHaveTextContent(/latest check failed/i);+ expect(notice).toHaveTextContent(/temporary outage/i);+ expect(notice).toHaveTextContent(/1d 0h old/i);+ expect(notice).toHaveTextContent(/retry before marking this reference reviewed/i);+ await waitFor(() => expect(api.checkReferenceRepo).toHaveBeenCalledWith('app-1', 'ref-1', { silent: true }));+ });+});diff --git a/scripts/migrations/273-reference-repo-last-known-good-snapshot.js b/scripts/migrations/273-reference-repo-last-known-good-snapshot.jsnew file mode 100644index 0000000000..53b7bb8c66--- /dev/null+++ b/scripts/migrations/273-reference-repo-last-known-good-snapshot.js@@ -0,0 +1,48 @@+/**+ * Migration 273 — initialize reference-repo stale snapshot fields.+ *+ * Reference repos are stored inline in data/apps.json. Older entries lack the+ * explicit null used to distinguish “no successful snapshot yet” from a+ * malformed snapshot, so initialize only the missing field and preserve every+ * user-managed reference value byte-for-byte otherwise.+ */++import { readFile, rename, writeFile } from 'fs/promises';+import { join } from 'path';++const readJson = async (path) => {+ const raw = await readFile(path, 'utf8').catch((err) => {+ if (err.code === 'ENOENT') return null;+ throw err;+ });+ if (raw == null) return null;+ try { return JSON.parse(raw); } catch { return null; }+};++const writeJsonAtomic = async (path, value) => {+ const temporaryPath = `${path}.tmp-273`;+ await writeFile(temporaryPath, `${JSON.stringify(value, null, 2)}\n`);+ await rename(temporaryPath, path);+};++export default {+ async up({ rootDir }) {+ const appsPath = join(rootDir, 'data', 'apps.json');+ const data = await readJson(appsPath);+ if (!data?.apps || typeof data.apps !== 'object') {+ return { ok: true, reason: 'no-apps', updated: 0 };+ }++ let updated = 0;+ for (const app of Object.values(data.apps)) {+ if (!Array.isArray(app?.referenceRepos)) continue;+ app.referenceRepos = app.referenceRepos.map((ref) => {+ if (!ref || typeof ref !== 'object' || Object.hasOwn(ref, 'lastKnownGoodSnapshot')) return ref;+ updated += 1;+ return { ...ref, lastKnownGoodSnapshot: null };+ });+ }+ if (updated > 0) await writeJsonAtomic(appsPath, data);+ return { ok: true, reason: updated > 0 ? 'initialized' : 'already-current', updated };+ },+};diff --git a/scripts/migrations/273-reference-repo-last-known-good-snapshot.test.js b/scripts/migrations/273-reference-repo-last-known-good-snapshot.test.jsnew file mode 100644index 0000000000..c3482aa3ed--- /dev/null+++ b/scripts/migrations/273-reference-repo-last-known-good-snapshot.test.js@@ -0,0 +1,47 @@+import { afterEach, describe, expect, it } from 'vitest';+import { mkdtemp, mkdir, readFile, rm, writeFile } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';+import migration from './273-reference-repo-last-known-good-snapshot.js';++const roots = [];+const makeRoot = async () => {+ const rootDir = await mkdtemp(join(tmpdir(), 'migration-273-'));+ roots.push(rootDir);+ await mkdir(join(rootDir, 'data'));+ return rootDir;+};++afterEach(async () => {+ await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));+});++describe('migration 273', () => {+ it('initializes only legacy reference repos and preserves existing snapshots', async () => {+ const rootDir = await makeRoot();+ const appsPath = join(rootDir, 'data', 'apps.json');+ await writeFile(appsPath, JSON.stringify({+ apps: {+ app: {+ referenceRepos: [+ { id: 'legacy', name: 'Legacy' },+ { id: 'current', name: 'Current', lastKnownGoodSnapshot: { schemaVersion: 1 } },+ ],+ },+ },+ }));++ await expect(migration.up({ rootDir })).resolves.toEqual({ ok: true, reason: 'initialized', updated: 1 });+ const data = JSON.parse(await readFile(appsPath, 'utf8'));+ expect(data.apps.app.referenceRepos).toEqual([+ { id: 'legacy', name: 'Legacy', lastKnownGoodSnapshot: null },+ { id: 'current', name: 'Current', lastKnownGoodSnapshot: { schemaVersion: 1 } },+ ]);+ await expect(migration.up({ rootDir })).resolves.toEqual({ ok: true, reason: 'already-current', updated: 0 });+ });++ it('does not create an apps file when no registry exists', async () => {+ const rootDir = await makeRoot();+ await expect(migration.up({ rootDir })).resolves.toEqual({ ok: true, reason: 'no-apps', updated: 0 });+ });+});diff --git a/server/routes/referenceRepos.js b/server/routes/referenceRepos.jsindex bdf73b43d1..1a9244b646 100644--- a/server/routes/referenceRepos.js+++ b/server/routes/referenceRepos.js@@ -60,7 +60,9 @@ router.post('/:refId/check', asyncHandler(async (req, res) => {const { appId, refId } = req.params;const snapshot = await checkReferenceRepo(appId, refId);let analysis = { queued: false, reason: 'no-new-commits' };- if (snapshot.commitCount > 0) {+ if (snapshot.stale) {+ analysis = { queued: false, reason: 'stale-snapshot' };+ } else if (snapshot.commitCount > 0) {const app = await getAppById(appId);const ref = app?.referenceRepos?.find((r) => r.id === refId);if (!app) {diff --git a/server/routes/referenceRepos.test.js b/server/routes/referenceRepos.test.jsindex 7a7b47675c..549e4f573a 100644--- a/server/routes/referenceRepos.test.js+++ b/server/routes/referenceRepos.test.js@@ -152,6 +152,17 @@ describe('reference repos routes', () => {expect(r.body.analysis).toEqual({ queued: false, reason: 'no-new-commits' });expect(svc.triggerReferenceAnalysis).not.toHaveBeenCalled();});++ it('returns stale snapshots without queuing analysis', async () => {+ svc.checkReferenceRepo.mockResolvedValueOnce({+ head: 'a'.repeat(40), commitCount: 2, commits: [], stale: true,+ error: { code: 'REFERENCE_REPO_GIT_FAILED', message: 'temporary outage' },+ });+ const r = await request(app).post('/api/apps/app-1/reference-repos/r1/check');+ expect(r.status).toBe(200);+ expect(r.body).toMatchObject({ stale: true, analysis: { queued: false, reason: 'stale-snapshot' } });+ expect(svc.triggerReferenceAnalysis).not.toHaveBeenCalled();+ });});describe('POST /:refId/reviewed', () => {diff --git a/server/services/referenceRepos.js b/server/services/referenceRepos.jsindex 37123d313a..685ea28196 100644--- a/server/services/referenceRepos.js+++ b/server/services/referenceRepos.js@@ -237,6 +237,51 @@ const fetchHead = async (ref) => {// against the user's notes; the user can pin lastReviewedSha forward// to drop older items if needed.const COMMIT_LIST_CAP = 200;+const LAST_KNOWN_GOOD_SNAPSHOT_VERSION = 1;+const SNAPSHOT_AUTHOR_MAX_LENGTH = 200;+const SNAPSHOT_SUBJECT_MAX_LENGTH = 500;++const boundedText = (value, maxLength) => (+ typeof value === 'string' ? value.slice(0, maxLength) : ''+);++// The live snapshot contains a clone working directory because the internal+// reference-watch prompt needs it. The persisted fallback deliberately does+// not: clone paths are machine-local implementation details, and commit email+// addresses are not needed to explain a reference change to the user.+const persistableSnapshot = (snapshot, fetchedAt) => ({+ schemaVersion: LAST_KNOWN_GOOD_SNAPSHOT_VERSION,+ fetchedAt,+ head: snapshot.head,+ headShort: snapshot.headShort,+ sinceSha: snapshot.sinceSha,+ sinceShort: snapshot.sinceShort,+ branch: snapshot.branch,+ commitCount: snapshot.commitCount,+ truncated: snapshot.truncated === true,+ totalCommitCount: snapshot.totalCommitCount,+ commits: snapshot.commits.slice(0, COMMIT_LIST_CAP).map((commit) => ({+ sha: commit.sha,+ author: boundedText(commit.author, SNAPSHOT_AUTHOR_MAX_LENGTH),+ date: commit.date,+ subject: boundedText(commit.subject, SNAPSHOT_SUBJECT_MAX_LENGTH),+ })),+});++const lastKnownGoodSnapshot = (ref) => {+ const snapshot = ref?.lastKnownGoodSnapshot;+ if (+ !snapshot+ || snapshot.schemaVersion !== LAST_KNOWN_GOOD_SNAPSHOT_VERSION+ || !SHA_RE.test(snapshot.head || '')+ || typeof snapshot.fetchedAt !== 'string'+ || !Number.isFinite(Date.parse(snapshot.fetchedAt))+ || !Array.isArray(snapshot.commits)+ ) return null;+ return snapshot;+};++const staleAgeMs = (fetchedAt) => Math.max(0, Date.now() - Date.parse(fetchedAt));// Returns { commits, truncated, totalCommitCount } where:// - commits.length <= COMMIT_LIST_CAP@@ -295,6 +340,7 @@ export async function addReferenceRepo(appId, { name, repoUrl, branch, notes })lastCheckedAt: null,status: 'needs-clone',lastError: null,+ lastKnownGoodSnapshot: null,createdAt: new Date().toISOString(),};await updateApp(appId, { referenceRepos: [...existing, ref] });@@ -470,19 +516,41 @@ export async function checkReferenceRepo(appId, refId) {commits,cwd,branch: ref.branch || 'main',+ fetchedAt: checkedAt,+ stale: false,};} catch (err) {nextStatus = 'error';nextError = err instanceof ServerError ? err.message : String(err.message || err);originalError = err;}+ const storedSnapshot = snapshot ? persistableSnapshot(snapshot, checkedAt) : null;+ const fallbackSnapshot = lastKnownGoodSnapshot(ref);+ const errorCode = originalError instanceof ServerError+ ? originalError.code || 'REFERENCE_REPO_CHECK_FAILED'+ : 'REFERENCE_REPO_CHECK_FAILED';// Persist status + lastCheckedAt regardless of success — UI surfaces the- // error inline so the user can fix bad URL / branch.+ // error inline so the user can fix bad URL / branch. A failed refresh keeps+ // the last successful snapshot untouched so it remains a trustworthy fallback.const next = refs.map((r) => (r.id === refId- ? { ...r, status: nextStatus, lastError: nextError, lastCheckedAt: checkedAt }+ ? {+ ...r,+ status: nextStatus === 'error' && fallbackSnapshot ? 'stale' : nextStatus,+ lastError: nextError,+ lastCheckedAt: checkedAt,+ ...(storedSnapshot ? { lastKnownGoodSnapshot: storedSnapshot } : {}),+ }: r));await updateApp(appId, { referenceRepos: next });if (nextStatus === 'error') {+ if (fallbackSnapshot) {+ return {+ ...fallbackSnapshot,+ stale: true,+ staleAgeMs: staleAgeMs(fallbackSnapshot.fetchedAt),+ error: { code: errorCode, message: nextError },+ };+ }// Preserve the original ServerError's status/code (e.g. 400// REFERENCE_REPO_LOCAL_MISSING) so user-fixable config problems don't// become opaque 500s. Fall back to a generic 500 only for truly@@ -594,6 +662,9 @@ export { formatTrackerInstructions };* when the task can't be created (e.g. no commits, app not found).*/export async function triggerReferenceAnalysis(app, ref, snapshot) {+ if (snapshot?.stale) {+ return { queued: false, reason: 'stale-snapshot' };+ }if (!snapshot || snapshot.commitCount === 0) {return { queued: false, reason: 'no-new-commits' };}diff --git a/server/services/referenceRepos.test.js b/server/services/referenceRepos.test.jsindex d91461a467..7d4d40a011 100644--- a/server/services/referenceRepos.test.js+++ b/server/services/referenceRepos.test.js@@ -211,6 +211,15 @@ describe('checkReferenceRepo', () => {expect(persisted.status).toBe('ok');expect(persisted.lastError).toBeNull();expect(persisted.lastCheckedAt).toBeTruthy();+ expect(persisted.lastKnownGoodSnapshot).toMatchObject({+ schemaVersion: 1,+ head: 'a'.repeat(40),+ branch: 'main',+ commitCount: 1,+ fetchedAt: expect.any(String),+ });+ expect(persisted.lastKnownGoodSnapshot).not.toHaveProperty('cwd');+ expect(persisted.lastKnownGoodSnapshot.commits[0]).not.toHaveProperty('email');});it('skips clone when .git already exists', async () => {@@ -227,6 +236,30 @@ describe('checkReferenceRepo', () => {expect(execGitMock.mock.calls[0][0][0]).toBe('fetch');});+ it('replaces the prior snapshot with bounded, credential-free commit metadata', async () => {+ seedApp('app-1', [{+ id: 'r1', name: 'p', repoUrl: 'https://github.com/x/y.git', branch: 'main', lastReviewedSha: null,+ lastKnownGoodSnapshot: {+ schemaVersion: 1, fetchedAt: '2026-01-01T00:00:00.000Z', head: 'a'.repeat(40),+ commits: [], branch: 'main', commitCount: 0, truncated: false, totalCommitCount: null,+ },+ }]);+ existsMock.mockImplementation((p) => String(p).endsWith('/.git'));+ execGitMock+ .mockReturnValueOnce({ stdout: '' }) // fetch+ .mockReturnValueOnce({ stdout: 'b'.repeat(40) }) // rev-parse+ .mockReturnValueOnce({ stdout: ['b'.repeat(40), 'A'.repeat(250), '[email protected]', '2026-05-01T00:00:00Z', 'S'.repeat(550)].join('\t') }); // log++ await svc.checkReferenceRepo('app-1', 'r1');++ const persisted = mockApps.get('app-1').referenceRepos[0].lastKnownGoodSnapshot;+ expect(persisted.head).toBe('b'.repeat(40));+ expect(persisted.commits).toHaveLength(1);+ expect(persisted.commits[0]).toMatchObject({ author: 'A'.repeat(200), subject: 'S'.repeat(500) });+ expect(persisted.commits[0]).not.toHaveProperty('email');+ expect(persisted).not.toHaveProperty('cwd');+ });+it('uses lastReviewedSha as the lower bound when set', async () => {seedApp('app-1', [{ id: 'r1', name: 'p', repoUrl: 'https://github.com/x/y.git', branch: 'main', lastReviewedSha: 'c'.repeat(40) }]);existsMock.mockImplementation((p) => String(p).endsWith('/.git'));@@ -256,6 +289,41 @@ describe('checkReferenceRepo', () => {expect(persisted.lastError).toMatch(/bad branch/);});+ it('returns a stale last-known-good snapshot after a failed refresh', async () => {+ const savedSnapshot = {+ schemaVersion: 1,+ fetchedAt: '2026-01-01T00:00:00.000Z',+ head: 'a'.repeat(40),+ headShort: 'aaaaaaaa',+ sinceSha: null,+ sinceShort: null,+ branch: 'main',+ commitCount: 1,+ truncated: false,+ totalCommitCount: null,+ commits: [{ sha: 'a'.repeat(40), author: 'Alice', date: '2026-01-01T00:00:00.000Z', subject: 'saved commit' }],+ };+ seedApp('app-1', [{+ id: 'r1', name: 'p', repoUrl: 'https://github.com/x/y.git', branch: 'main',+ lastReviewedSha: null, lastKnownGoodSnapshot: savedSnapshot,+ }]);+ existsMock.mockImplementation((p) => String(p).endsWith('/.git'));+ execGitMock.mockReturnValueOnce({ error: new Error('fatal: temporary outage') });++ const snapshot = await svc.checkReferenceRepo('app-1', 'r1');++ expect(snapshot).toMatchObject({+ ...savedSnapshot,+ stale: true,+ staleAgeMs: expect.any(Number),+ error: { code: 'REFERENCE_REPO_GIT_FAILED', message: expect.stringContaining('temporary outage') },+ });+ const persisted = mockApps.get('app-1').referenceRepos[0];+ expect(persisted.status).toBe('stale');+ expect(persisted.lastKnownGoodSnapshot).toEqual(savedSnapshot);+ expect(persisted.lastError).toContain('temporary outage');+ });+it('skips clone+fetch for local-path refs and reads SHA via rev-parse on the user path', async () => {seedApp('app-1', [{ id: 'r1', name: 'p', repoUrl: '/Users/me/phosphene', branch: 'main', lastReviewedSha: null }]);existsMock.mockImplementation((p) => p === '/Users/me/phosphene' || p === '/Users/me/phosphene/.git'); // user path + git dir exist@@ -369,6 +437,12 @@ describe('triggerReferenceAnalysis', () => {expect(result).toEqual({ queued: false, reason: 'no-new-commits' });});+ it('never queues an analysis from a stale snapshot', async () => {+ const result = await svc.triggerReferenceAnalysis(app, ref, { ...snapshot, stale: true });+ expect(result).toEqual({ queued: false, reason: 'stale-snapshot' });+ expect(addTaskMock).not.toHaveBeenCalled();+ });+it('skips when app is null', async () => {const result = await svc.triggerReferenceAnalysis(null, ref, snapshot);expect(result).toEqual({ queued: false, reason: 'app-not-found' });