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: track upstream code per-app + multi-keyframe video gen (LTX-2) (#205)
[._.]/ Adam Eivy2f1993223dc9
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex c7df99e939..002c00d5be 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -11,6 +11,18 @@ Scene cards now use a stronger visual treatment when active (accent ring + tintA new third extraction kind, **Objects**, extracts recurring symbolic items (the letter, the fedora) alongside Characters and Settings. Editable in a new Objects tab in the storyboard sidebar, with the same AI-fills-blanks merge rule as the other bibles.+### Reference Repos — track upstream code we borrow from++Each app in `data/apps.json` (including PortOS itself) can now declare a `referenceRepos` array of upstream repos it watches for adoptable changes. Each entry stores the repo URL (or local path), branch, free-text notes describing what features rely on it, and a `lastReviewedSha` checkpoint. A new `reference-watch` self-improvement task type runs weekly (off by default), fetches each ref into `data/cos/reference-repos/<refId>/`, computes commits since `lastReviewedSha`, and dispatches a CoS sub-agent that writes a propose-only `REFERENCE_REVIEW.md` (Adopt / Maybe / Skip) to the app's repo. Read-only — no auto-implementation.++REST surface is mounted at `/api/apps/:appId/reference-repos` with full CRUD plus `POST /:refId/check` (run a check now) and `POST /:refId/reviewed` (manually pin the reviewed SHA). 26 new tests covering the service + route layers.++### Multi-keyframe video interpolation (LTX-2)++The video gen route now accepts an arbitrary `keyframes` array (`[{ file, index }, ...]`, length 2-8) on `mode='fflf'` for ltx2-runtime models, replacing the implicit two-frame cap of the existing `sourceImageFile` + `lastImageFile` pair. The underlying `KeyframeInterpolationPipeline` already supported N anchors at arbitrary pixel-frame indices — PortOS just exposes it now.++This is the compositional primitive Writers Room storyboards need: anchor every shot's keyframe-0 to the same character still for cross-shot continuity, pin pose/framing at specific timecodes, or set N storyboard panels as keyframes inside one render. Validation rejects non-ascending or out-of-range indices before the spawn so a typo doesn't burn a 30-second model load. Multi-keyframe is incompatible with `chunks > 1` (chains anchor a single clip).+### Live render dockA page-level run dock now slides up from the bottom of the Writers Room while image-gen jobs are queued or rendering. Each row shows the scene label, status, progress bar, ETA, and a per-job stop button; "Stop all" cancels every queued and in-flight render. The dock auto-hides one second after the last job completes.diff --git a/client/src/App.jsx b/client/src/App.jsxindex 72954497ce..885cf08cda 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -32,6 +32,7 @@ const DataDog = lazyWithReload(() => import('./pages/DataDog'));const GitHub = lazyWithReload(() => import('./pages/GitHub'));const CyberCity = lazyWithReload(() => import('./pages/CyberCity'));const AppDetail = lazyWithReload(() => import('./pages/AppDetail'));+const ReferenceRepos = lazyWithReload(() => import('./pages/ReferenceRepos'));const FeatureAgents = lazyWithReload(() => import('./pages/FeatureAgents'));const FeatureAgentDetail = lazyWithReload(() => import('./pages/FeatureAgentDetail'));const CalendarPage = lazyWithReload(() => import('./pages/Calendar'));@@ -124,6 +125,7 @@ export default function App() {<Route path="/" element={<Layout />}><Route index element={<Dashboard />} /><Route path="apps" element={<Apps />} />+ <Route path="reference-repos" element={<ReferenceRepos />} /><Route path="devtools" element={<Navigate to="/devtools/runs" replace />} /><Route path="devtools/datadog" element={<DataDog />} /><Route path="devtools/github" element={<GitHub />} />diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex 6e6040eb3a..728abc2673 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -264,6 +264,7 @@ const navItems = [{ to: '/post/wordplay', label: 'Wordplay', icon: MessageCircle },]},+ { to: '/reference-repos', label: 'Reference Repos', icon: GitBranch, single: true },{label: 'Settings',icon: Settings,diff --git a/client/src/components/apps/AppDetailView.jsx b/client/src/components/apps/AppDetailView.jsxindex c5fae3bcac..b56d3c0bee 100644--- a/client/src/components/apps/AppDetailView.jsx+++ b/client/src/components/apps/AppDetailView.jsx@@ -16,6 +16,7 @@ import DocumentsTab from './tabs/DocumentsTab';import GitTab from './tabs/GitTab';import GsdTab from './tabs/GsdTab';import ProcessesTab from './tabs/ProcessesTab';+import ReferencesTab from './tabs/ReferencesTab';import DatadogTab from './tabs/DatadogTab';import UpdateTab from './tabs/UpdateTab';@@ -137,6 +138,8 @@ export default function AppDetailView() {return <GsdTab appId={appId} repoPath={app.repoPath} />;case 'processes':return <ProcessesTab pm2ProcessNames={app.pm2ProcessNames} />;+ case 'references':+ return <ReferencesTab appId={appId} appName={app.name} />;case 'update':if (app.id !== api.PORTOS_APP_ID) {return (diff --git a/client/src/components/apps/ReferenceReposPanel.jsx b/client/src/components/apps/ReferenceReposPanel.jsxnew file mode 100644index 0000000000..ff0a1a0eff--- /dev/null+++ b/client/src/components/apps/ReferenceReposPanel.jsx@@ -0,0 +1,402 @@+import { useEffect, useState, useCallback, useRef } from 'react';+import { GitBranch, Plus, RefreshCw, Trash2, CheckCircle, AlertCircle, Edit3, X } from 'lucide-react';+import toast from '../ui/Toast';+import * as api from '../../services/api';++/**+ * Per-app reference-repos manager. Embedded inside the app detail page+ * (Tasks tab) and reused on the global /reference-repos page in+ * read-only-ish mode (`compact={true}` hides the "Add" form so the+ * global summary stays a summary).+ */+export default function ReferenceReposPanel({ appId, appName, compact = false, initialRefs = null }) {+ const [refs, setRefs] = useState(initialRefs || []);+ // Two distinct loading states:+ // - `initialLoading` is true only on the very first fetch (mount); the+ // panel renders a placeholder while it's true. Stays false after+ // that, even on subsequent refreshes.+ // - `refreshing` is true during post-mutation re-fetches. The panel+ // keeps the list visible during refresh so per-row state (an+ // unsaved notes draft, an expanded commit list <details>) doesn't+ // get unmounted and lost every time the user clicks Check or+ // Mark-reviewed.+ const [initialLoading, setInitialLoading] = useState(initialRefs == null);+ const [refreshing, setRefreshing] = useState(false);+ const [showAdd, setShowAdd] = useState(false);+ // Per-ref UI state — keyed by ref id. Holds the in-progress check snapshot+ // (commit list) so the user can see what's queued before marking-as-reviewed.+ const [snapshots, setSnapshots] = useState({});+ // Track concurrent in-flight checks per-ref. Using a Set so two adjacent+ // rows can both spin without one row's completion clearing the other's+ // spinner. RefRow reads checking via `checkingIds.has(ref.id)`.+ const [checkingIds, setCheckingIds] = useState(() => new Set());+ const [editingNotesId, setEditingNotesId] = useState(null);++ // Track an explicit fetch error separately from `refs` so a transient+ // failure doesn't blank the list — stale-but-valid is far better UX+ // than "no refs configured" appearing when the server hiccups.+ const [fetchError, setFetchError] = useState(null);+ const fetch = useCallback(async () => {+ setRefreshing(true);+ const res = await api.listReferenceRepos(appId).catch((e) => ({ __error: e?.message || 'Failed to load references' }));+ if (res && res.__error) {+ setFetchError(res.__error);+ } else {+ setFetchError(null);+ setRefs(res?.referenceRepos || []);+ }+ setRefreshing(false);+ setInitialLoading(false);+ }, [appId]);++ // Fetch on mount unless the parent seeded us with initialRefs. After+ // any local mutation we re-fetch unconditionally to pick up server-side+ // status updates (lastCheckedAt, lastError).+ const initialRefsProvided = initialRefs != null;+ useEffect(() => {+ if (!initialRefsProvided) fetch();+ }, [fetch, initialRefsProvided]);++ const handleAdd = async (form) => {+ const created = await api.addReferenceRepo(appId, form).catch((e) => { toast.error(e.message || 'Add failed'); return null; });+ if (!created) return;+ toast.success(`Added "${created.name}"`);+ setShowAdd(false);+ fetch();+ };++ // Two-click delete per CLAUDE.md "no window.confirm". First click arms the+ // row, second click within 4s actually deletes.+ const pendingDeleteRef = useRef({ id: null, expiresAt: 0 });+ const handleDelete = async (ref) => {+ const pending = pendingDeleteRef.current;+ if (pending.id !== ref.id || Date.now() > pending.expiresAt) {+ pendingDeleteRef.current = { id: ref.id, expiresAt: Date.now() + 4000 };+ toast(`Click delete again to remove "${ref.name}"`, { icon: '⚠️' });+ return;+ }+ pendingDeleteRef.current = { id: null, expiresAt: 0 };+ // Only mutate local state on success — otherwise the row vanishes from+ // the UI while the server still has the ref, leaving the user confused+ // about why "delete failed" appeared next to a now-empty list.+ const ok = await api.deleteReferenceRepo(appId, ref.id)+ .then(() => true)+ .catch((e) => { toast.error(e.message || 'Delete failed'); return false; });+ if (!ok) return;+ setRefs((prev) => prev.filter((r) => r.id !== ref.id));+ setSnapshots((prev) => { const n = { ...prev }; delete n[ref.id]; return n; });+ };++ const handleCheck = async (ref) => {+ // Add this ref's id to the in-flight set so its spinner stays on+ // while it runs, even if a different ref's check completes first.+ setCheckingIds((prev) => { const n = new Set(prev); n.add(ref.id); return n; });+ const snap = await api.checkReferenceRepo(appId, ref.id).catch((e) => {+ toast.error(e.message || 'Check failed');+ return null;+ });+ setCheckingIds((prev) => { const n = new Set(prev); n.delete(ref.id); return n; });+ if (!snap) {+ // Clear any stale snapshot — the user just saw a check failure, so+ // leaving a previous commit list expandable would mislead them into+ // thinking the listed commits are still the most recent unreviewed+ // ones (they may not be; the failed check might've been triggered+ // by upstream HEAD moving).+ setSnapshots((prev) => { const n = { ...prev }; delete n[ref.id]; return n; });+ fetch();+ return;+ }+ setSnapshots((prev) => ({ ...prev, [ref.id]: snap }));+ toast.success(`${ref.name}: ${snap.commitCount} new commit${snap.commitCount === 1 ? '' : 's'}`);+ fetch();+ };++ const handleMarkReviewed = async (ref) => {+ const snap = snapshots[ref.id];+ const sha = snap?.head;+ if (!sha) {+ toast.error('Run "Check now" first to fetch the latest head SHA.');+ return;+ }+ // Only show the success toast / clear the snapshot on a successful+ // PATCH. Otherwise the UI claims the ref was reviewed while the server+ // still has the old lastReviewedSha — which gets confusing fast since+ // the next "Check" rediscovers the same commits.+ const ok = await api.markReferenceRepoReviewed(appId, ref.id, sha)+ .then(() => true)+ .catch((e) => { toast.error(e.message || 'Mark reviewed failed'); return false; });+ if (!ok) return;+ toast.success(`Marked ${ref.name} reviewed up to ${sha.slice(0, 8)}`);+ setSnapshots((prev) => { const n = { ...prev }; delete n[ref.id]; return n; });+ fetch();+ };++ const handleSaveNotes = async (ref, nextNotes) => {+ // Keep the editor open on a failed PATCH — losing the user's draft on+ // a transient network blip is the worst possible outcome here. They+ // can re-click Save, or click Cancel to discard.+ const ok = await api.updateReferenceRepo(appId, ref.id, { notes: nextNotes })+ .then(() => true)+ .catch((e) => { toast.error(e.message || 'Update failed'); return false; });+ if (!ok) return;+ setEditingNotesId(null);+ fetch();+ };++ if (initialLoading) {+ return <div className="text-gray-400 text-sm">Loading references…</div>;+ }++ return (+ <div className="space-y-3">+ {!compact && (+ <div className="flex items-center justify-between">+ <div>+ <h3 className="text-sm font-semibold text-white flex items-center gap-2">+ <GitBranch size={14} /> Reference Repos+ {refreshing && <RefreshCw size={11} className="animate-spin text-gray-500" />}+ </h3>+ <p className="text-xs text-gray-500 mt-0.5">+ Upstream repos {appName} watches for clean-room reimplementation. The <code className="text-port-accent">reference-watch</code> task fetches each weekly and proposes features/fixes worth re-building in our own code via <code>REFERENCE_REVIEW.md</code>.+ </p>+ </div>+ <button+ onClick={() => setShowAdd(true)}+ className="px-3 py-1.5 bg-port-accent/20 text-port-accent hover:bg-port-accent/30 rounded text-xs inline-flex items-center gap-1 shrink-0"+ >+ <Plus size={14} /> Add reference+ </button>+ </div>+ )}++ {showAdd && !compact && (+ <AddRefForm onSubmit={handleAdd} onCancel={() => setShowAdd(false)} />+ )}++ {fetchError && (+ <div className="bg-port-error/10 border border-port-error/40 text-port-error text-xs rounded p-2 inline-flex items-center gap-2">+ <AlertCircle size={12} /> Failed to refresh references: {fetchError}. Showing last known data.+ </div>+ )}++ {refs.length === 0 ? (+ <div className="bg-port-card border border-port-border rounded-lg p-4 text-center text-gray-500 text-sm">+ No reference repos configured.+ </div>+ ) : (+ <div className="space-y-2">+ {refs.map((ref) => (+ <RefRow+ key={ref.id}+ reference={ref}+ snapshot={snapshots[ref.id]}+ checking={checkingIds.has(ref.id)}+ editingNotes={editingNotesId === ref.id}+ onCheck={() => handleCheck(ref)}+ onMarkReviewed={() => handleMarkReviewed(ref)}+ onDelete={() => handleDelete(ref)}+ onEditNotes={() => setEditingNotesId(ref.id)}+ onCancelNotes={() => setEditingNotesId(null)}+ onSaveNotes={(notes) => handleSaveNotes(ref, notes)}+ compact={compact}+ />+ ))}+ </div>+ )}+ </div>+ );+}++function StatusBadge({ status, lastError }) {+ 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'}>+ <AlertCircle size={10} /> error+ </span>+ );+ }+ if (status === 'needs-clone') {+ return <span className="px-1.5 py-0.5 bg-gray-500/20 text-gray-400 text-[10px] rounded">unscanned</span>;+ }+ return (+ <span className="px-1.5 py-0.5 bg-port-success/20 text-port-success text-[10px] rounded inline-flex items-center gap-1">+ <CheckCircle size={10} /> ok+ </span>+ );+}++function RefRow({ reference, snapshot, checking, editingNotes, onCheck, onMarkReviewed, onDelete, onEditNotes, onCancelNotes, onSaveNotes, compact }) {+ // Seed the draft when the user enters edit mode. Don't depend on+ // `reference.notes` — a parent re-fetch produces a new ref object every+ // poll and would clobber whatever the user is mid-typing.+ const [notesDraft, setNotesDraft] = useState(reference.notes || '');+ useEffect(() => {+ if (editingNotes) setNotesDraft(reference.notes || '');+ }, [editingNotes]); // eslint-disable-line react-hooks/exhaustive-deps++ const lastReviewedShort = reference.lastReviewedSha ? reference.lastReviewedSha.slice(0, 8) : null;+ const lastCheckedAgo = reference.lastCheckedAt ? new Date(reference.lastCheckedAt).toLocaleString() : 'never';+ const commitCount = snapshot?.commitCount;++ return (+ <div className="bg-port-card border border-port-border rounded-lg p-3 space-y-2">+ <div className="flex items-start justify-between gap-2">+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-2 flex-wrap">+ <span className="font-medium text-white truncate">{reference.name}</span>+ <StatusBadge status={reference.status} lastError={reference.lastError} />+ {commitCount > 0 && (+ <span className="px-1.5 py-0.5 bg-port-warning/20 text-port-warning text-[10px] rounded">+ {commitCount} new+ </span>+ )}+ </div>+ <div className="text-xs text-gray-500 truncate mt-0.5" title={reference.repoUrl}>+ {reference.repoUrl} <span className="text-gray-600">·</span> {reference.branch || 'main'}+ </div>+ <div className="text-[10px] text-gray-600 mt-0.5">+ Last reviewed: <span className="font-mono">{lastReviewedShort || '—'}</span>+ <span className="mx-1">·</span>+ Last checked: {lastCheckedAgo}+ </div>+ </div>+ <div className="flex items-center gap-1 shrink-0">+ <button+ onClick={onCheck}+ disabled={checking}+ className="px-2 py-1 bg-port-accent/20 text-port-accent hover:bg-port-accent/30 rounded text-xs inline-flex items-center gap-1 disabled:opacity-50"+ title="Fetch upstream and list new commits"+ >+ <RefreshCw size={12} className={checking ? 'animate-spin' : ''} /> Check+ </button>+ {snapshot?.head && snapshot.head !== reference.lastReviewedSha && (+ <button+ onClick={onMarkReviewed}+ className="px-2 py-1 bg-port-success/20 text-port-success hover:bg-port-success/30 rounded text-xs"+ title={`Pin lastReviewedSha = ${snapshot.head.slice(0, 8)}`}+ >+ Mark reviewed+ </button>+ )}+ {!compact && (+ <>+ <button+ onClick={onEditNotes}+ className="px-2 py-1 text-gray-400 hover:text-white rounded"+ title="Edit notes"+ >+ <Edit3 size={12} />+ </button>+ <button+ onClick={onDelete}+ className="px-2 py-1 text-gray-400 hover:text-port-error rounded"+ title="Remove this reference"+ >+ <Trash2 size={12} />+ </button>+ </>+ )}+ </div>+ </div>++ {editingNotes ? (+ <div className="space-y-1">+ <textarea+ value={notesDraft}+ onChange={(e) => setNotesDraft(e.target.value)}+ rows={4}+ placeholder="What features rely on this repo? The watch agent reads this to know which commits matter."+ className="w-full px-2 py-1 bg-port-bg border border-port-border rounded text-xs text-white focus:border-port-accent focus:outline-hidden"+ />+ <div className="flex gap-1">+ <button+ onClick={() => onSaveNotes(notesDraft.trim())}+ className="px-2 py-1 bg-port-accent/20 text-port-accent hover:bg-port-accent/30 rounded text-xs"+ >+ Save+ </button>+ <button+ onClick={onCancelNotes}+ className="px-2 py-1 text-gray-400 hover:text-white rounded text-xs inline-flex items-center gap-1"+ >+ <X size={12} /> Cancel+ </button>+ </div>+ </div>+ ) : reference.notes ? (+ <div className="text-xs text-gray-400 whitespace-pre-wrap border-l-2 border-port-border pl-2">+ {reference.notes}+ </div>+ ) : null}++ {snapshot?.commits?.length > 0 && (+ <details className="text-xs text-gray-300">+ <summary className="cursor-pointer text-gray-400 hover:text-white">+ View {snapshot.commits.length} new commit{snapshot.commits.length === 1 ? '' : 's'}+ </summary>+ <ul className="mt-1 ml-2 space-y-0.5 font-mono text-[11px]">+ {snapshot.commits.map((c) => (+ <li key={c.sha} className="truncate">+ <span className="text-port-accent">{c.sha.slice(0, 8)}</span>+ <span className="mx-1 text-gray-500">·</span>+ <span className="text-gray-200">{c.subject}</span>+ <span className="mx-1 text-gray-600">—</span>+ <span className="text-gray-500">{c.author}, {c.date.slice(0, 10)}</span>+ </li>+ ))}+ </ul>+ </details>+ )}+ </div>+ );+}++function AddRefForm({ onSubmit, onCancel }) {+ const [form, setForm] = useState({ name: '', repoUrl: '', branch: 'main', notes: '' });+ const submit = (e) => {+ e.preventDefault();+ if (!form.name.trim() || !form.repoUrl.trim()) return;+ onSubmit({+ name: form.name.trim(),+ repoUrl: form.repoUrl.trim(),+ branch: form.branch.trim() || undefined,+ notes: form.notes.trim() || undefined,+ });+ };+ return (+ <form onSubmit={submit} className="bg-port-card border border-port-accent/40 rounded-lg p-3 space-y-2">+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">+ <input+ autoFocus+ value={form.name}+ onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}+ placeholder="Display name (e.g. phosphene)"+ className="px-2 py-1 bg-port-bg border border-port-border rounded text-sm text-white focus:border-port-accent focus:outline-hidden"+ />+ <input+ value={form.branch}+ onChange={(e) => setForm((f) => ({ ...f, branch: e.target.value }))}+ placeholder="Branch (default: main)"+ className="px-2 py-1 bg-port-bg border border-port-border rounded text-sm text-white focus:border-port-accent focus:outline-hidden"+ />+ </div>+ <input+ value={form.repoUrl}+ onChange={(e) => setForm((f) => ({ ...f, repoUrl: e.target.value }))}+ placeholder="Repo URL (https://github.com/owner/repo.git) or local path"+ className="w-full px-2 py-1 bg-port-bg border border-port-border rounded text-sm text-white focus:border-port-accent focus:outline-hidden"+ />+ <textarea+ value={form.notes}+ onChange={(e) => setForm((f) => ({ ...f, notes: e.target.value }))}+ rows={3}+ placeholder="Notes — what features in our app use this repo? (Helps the watch agent prioritize.)"+ className="w-full px-2 py-1 bg-port-bg border border-port-border rounded text-sm text-white focus:border-port-accent focus:outline-hidden"+ />+ <div className="flex gap-2">+ <button type="submit" className="px-3 py-1.5 bg-port-accent text-white rounded text-xs">Add</button>+ <button type="button" onClick={onCancel} className="px-3 py-1.5 text-gray-400 hover:text-white text-xs">Cancel</button>+ </div>+ </form>+ );+}diff --git a/client/src/components/apps/constants.js b/client/src/components/apps/constants.jsindex 802633ef61..9c3ac3a18b 100644--- a/client/src/components/apps/constants.js+++ b/client/src/components/apps/constants.js@@ -13,6 +13,7 @@ export const APP_DETAIL_TABS = [{ id: 'git', label: 'Git' },{ id: 'gsd', label: 'GSD' },{ id: 'processes', label: 'Processes' },+ { id: 'references', label: 'References' },{ id: 'tasks', label: 'Tasks' },{ id: 'update', label: 'Update' },];diff --git a/client/src/components/apps/tabs/ReferencesTab.jsx b/client/src/components/apps/tabs/ReferencesTab.jsxnew file mode 100644index 0000000000..27a6d255a1--- /dev/null+++ b/client/src/components/apps/tabs/ReferencesTab.jsx@@ -0,0 +1,15 @@+import ReferenceReposPanel from '../ReferenceReposPanel';++/**+ * App-detail "References" tab — full CRUD over the app's reference repos.+ * The global summary at /reference-repos uses the same panel in `compact`+ * mode (read-and-check, no add/delete). Add/edit/remove always happens+ * here so the per-app context is unambiguous.+ */+export default function ReferencesTab({ appId, appName }) {+ return (+ <div className="p-4 sm:p-6 max-w-4xl">+ <ReferenceReposPanel appId={appId} appName={appName} />+ </div>+ );+}diff --git a/client/src/pages/ReferenceRepos.jsx b/client/src/pages/ReferenceRepos.jsxnew file mode 100644index 0000000000..bc8eea6509--- /dev/null+++ b/client/src/pages/ReferenceRepos.jsx@@ -0,0 +1,97 @@+import { useEffect, useState } from 'react';+import { Link } from 'react-router-dom';+import { GitBranch, ExternalLink } from 'lucide-react';+import * as api from '../services/api';+import { PORTOS_APP_ID } from '../services/apiCore';+import ReferenceReposPanel from '../components/apps/ReferenceReposPanel';++/**+ * Global summary of every reference repo configured across every app.+ *+ * This page is intentionally a *summary* — to add, edit, or delete a ref+ * the user clicks through to the per-app References tab. That keeps the+ * "which app does this ref belong to" decision visible at edit time.+ *+ * What you CAN do here: see status across all refs at a glance, run a+ * "Check now" per ref, mark-as-reviewed, and click into the app for+ * full management.+ */+export default function ReferenceRepos() {+ const [apps, setApps] = useState([]);+ const [loading, setLoading] = useState(true);+ // Distinguish "fetch failed" from "no apps configured" — without this+ // the empty-state message ("No apps have reference repos configured")+ // shows up on every transient server hiccup, which is misleading and+ // sends users hunting for a configuration mistake that doesn't exist.+ const [fetchError, setFetchError] = useState(null);++ useEffect(() => {+ let cancelled = false;+ (async () => {+ const all = await api.getApps().catch((e) => ({ __error: e?.message || 'Failed to load apps' }));+ if (cancelled) return;+ if (all && all.__error) {+ setFetchError(all.__error);+ setLoading(false);+ return;+ }+ const withRefs = (all || []).filter((a) => Array.isArray(a.referenceRepos) && a.referenceRepos.length > 0);+ withRefs.sort((a, b) => {+ if (a.id === PORTOS_APP_ID) return -1;+ if (b.id === PORTOS_APP_ID) return 1;+ return (a.name || '').localeCompare(b.name || '');+ });+ setApps(withRefs);+ setLoading(false);+ })();+ return () => { cancelled = true; };+ }, []);++ if (loading) {+ return <div className="p-6 text-gray-400">Loading reference repos…</div>;+ }++ return (+ <div className="p-4 sm:p-6 max-w-5xl space-y-4">+ <div>+ <h1 className="text-2xl font-bold text-white flex items-center gap-2">+ <GitBranch size={22} /> Reference Repos+ </h1>+ <p className="text-sm text-gray-400 mt-1">+ Upstream repos each app watches for clean-room reimplementation. The <code className="text-port-accent">reference-watch</code> task in CoS scans them on a schedule and writes <code>REFERENCE_REVIEW.md</code> proposals describing features and fixes worth re-building in our own code. We track upstream commits — we don't copy upstream code. Add/remove from each app's References tab.+ </p>+ </div>++ {fetchError ? (+ <div className="bg-port-error/10 border border-port-error/40 rounded-lg p-4 text-port-error text-sm">+ Failed to load apps: {fetchError}. Refresh to retry.+ </div>+ ) : apps.length === 0 ? (+ <div className="bg-port-card border border-port-border rounded-lg p-8 text-center text-gray-400">+ <p className="mb-2">No apps have reference repos configured yet.</p>+ <p className="text-sm text-gray-500">+ Open any app from <Link to="/apps" className="text-port-accent hover:underline">Apps</Link> and use its <span className="text-white">References</span> tab to add one.+ </p>+ </div>+ ) : (+ apps.map((app) => (+ <div key={app.id} className="bg-port-bg border border-port-border rounded-lg p-4 space-y-3">+ <div className="flex items-center justify-between">+ <div className="flex items-baseline gap-2">+ <h2 className="text-lg font-semibold text-white">{app.name}</h2>+ <span className="text-xs text-gray-500">{app.referenceRepos.length} ref{app.referenceRepos.length === 1 ? '' : 's'}</span>+ </div>+ <Link+ to={`/apps/${app.id}/references`}+ className="text-xs text-port-accent hover:underline inline-flex items-center gap-1"+ >+ Manage <ExternalLink size={12} />+ </Link>+ </div>+ <ReferenceReposPanel appId={app.id} appName={app.name} compact initialRefs={app.referenceRepos} />+ </div>+ ))+ )}+ </div>+ );+}diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 1e6d82cc03..ca98b00812 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -5,6 +5,7 @@ export * from './apiCore.js';export * from './apiHealth.js';export * from './apiSystem.js';export * from './apiApps.js';+export * from './apiReferenceRepos.js';export * from './apiPorts.js';export * from './apiScaffold.js';export * from './apiProviders.js';diff --git a/client/src/services/apiReferenceRepos.js b/client/src/services/apiReferenceRepos.jsnew file mode 100644index 0000000000..3e8f058211--- /dev/null+++ b/client/src/services/apiReferenceRepos.js@@ -0,0 +1,39 @@+import { request } from './apiCore.js';++// Reference repos — upstream code we borrow from. Each entry is per-app.+// The `reference-watch` self-improvement task type uses `checkReferenceRepo`+// to pull each ref and decide whether to dispatch a CoS sub-agent.++export const listReferenceRepos = (appId) =>+ request(`/apps/${appId}/reference-repos`);++export const addReferenceRepo = (appId, body) =>+ request(`/apps/${appId}/reference-repos`, {+ method: 'POST',+ body: JSON.stringify(body),+ });++export const updateReferenceRepo = (appId, refId, body) =>+ request(`/apps/${appId}/reference-repos/${refId}`, {+ method: 'PATCH',+ body: JSON.stringify(body),+ });++export const deleteReferenceRepo = (appId, refId) =>+ request(`/apps/${appId}/reference-repos/${refId}`, {+ method: 'DELETE',+ });++// Run a check now — returns { head, headShort, commitCount, commits, ... }.+// Does NOT advance lastReviewedSha.+export const checkReferenceRepo = (appId, refId) =>+ request(`/apps/${appId}/reference-repos/${refId}/check`, {+ method: 'POST',+ });++// Pin lastReviewedSha after the user / agent has processed the changes.+export const markReferenceRepoReviewed = (appId, refId, sha) =>+ request(`/apps/${appId}/reference-repos/${refId}/reviewed`, {+ method: 'POST',+ body: JSON.stringify({ sha }),+ });diff --git a/scripts/generate_ltx2.py b/scripts/generate_ltx2.pyindex e5c5f94762..468159542f 100644--- a/scripts/generate_ltx2.py+++ b/scripts/generate_ltx2.py@@ -102,6 +102,11 @@ def parse_args() -> argparse.Namespace:help="Distilled-LoRA fusion strength (default 1.0, matches dgrauet's CLI).")p.add_argument("--image", default=None, help="Source/start frame (image, fflf modes)")p.add_argument("--last-image", default=None, help="End frame (fflf mode)")+ p.add_argument("--keyframes-json", default=None,+ help="Multi-keyframe interpolation: JSON-encoded list of {path,index} dicts "+ "(length >= 2, indices strictly ascending in [0, num_frames-1]). When "+ "set, fflf mode uses these instead of --image/--last-image — unlocks "+ "N>2 keyframes for cross-shot continuity, character anchoring, etc.")p.add_argument("--extend-from-video", default=None, help="Source video path (extend mode)")p.add_argument("--extend-frames", type=int, default=2,help="Number of latent frames to add (extend mode); 1 latent ≈ 8 pixel frames")@@ -225,16 +230,65 @@ def run_image(args: argparse.Namespace) -> str:)+def _resolve_keyframes(args: argparse.Namespace) -> tuple[list[str], list[int]]:+ """Decide between multi-keyframe (--keyframes-json) and legacy 2-keyframe.++ Multi-keyframe wins when --keyframes-json is non-empty. Validation is+ strict so agent bugs surface here before any GPU work.+ """+ last_pixel_frame = args.num_frames - 1+ if args.keyframes_json:+ try:+ raw = json.loads(args.keyframes_json)+ except json.JSONDecodeError as e:+ raise SystemExit(f"--keyframes-json is not valid JSON: {e}")+ if not isinstance(raw, list) or len(raw) < 2:+ raise SystemExit("--keyframes-json must be a list of length >= 2")+ images: list[str] = []+ indices: list[int] = []+ for i, kf in enumerate(raw):+ if not isinstance(kf, dict) or "path" not in kf or "index" not in kf:+ raise SystemExit(f"keyframe[{i}] must be an object with 'path' and 'index'")+ path = kf["path"]+ idx = kf["index"]+ if not isinstance(path, str) or not path:+ raise SystemExit(f"keyframe[{i}].path must be a non-empty string")+ if not isinstance(idx, int) or isinstance(idx, bool):+ raise SystemExit(f"keyframe[{i}].index must be an int")+ if not Path(path).exists():+ raise SystemExit(f"keyframe[{i}].path does not exist: {path}")+ if idx < 0 or idx > last_pixel_frame:+ raise SystemExit(+ f"keyframe[{i}].index {idx} out of range [0, {last_pixel_frame}]"+ )+ if indices and idx <= indices[-1]:+ raise SystemExit(+ f"keyframe indices must be strictly ascending; got {indices[-1]} then {idx}"+ )+ images.append(path)+ indices.append(idx)+ return images, indices+ if not args.image or not args.last_image:+ raise SystemExit(+ "fflf mode requires either --keyframes-json or both --image and --last-image"+ )+ return [args.image, args.last_image], [0, last_pixel_frame]++def run_fflf(args: argparse.Namespace) -> str:- """Keyframe interpolation — true FFLF (start + end frame conditioning).+ """Keyframe interpolation — N keyframes at arbitrary frame indices.++ Pixel frame indices map to LTX's latent grid; num_frames must be 8k+1+ (LTX latent boundary) — the panel UI enforces this via FRAME_OPTIONS.- Pixel frame indices: keyframe 0 anchors at frame 0, keyframe 1 at the- LAST pixel frame (num_frames - 1). num_frames must be 8k+1 (LTX latent- boundary) — the panel UI already enforces this via FRAME_OPTIONS.+ Two callers:+ - Legacy FFLF (--image start, --last-image end at [0, num_frames-1])+ - Multi-keyframe (--keyframes-json with N>=2 anchor points). Agent SDK+ uses this for character continuity, cross-shot anchoring, and+ compositional control."""from ltx_pipelines_mlx import KeyframeInterpolationPipeline- if not args.image or not args.last_image:- raise SystemExit("--image and --last-image are required for fflf mode")+ keyframe_images, keyframe_indices = _resolve_keyframes(args)# Keyframe interpolation needs the dev (non-distilled) transformer +# the distilled LoRA fused on top for stage 2. Defaults match the file# names in dgrauet/ltx-2.3-mlx-q4 and dgrauet/ltx-2.3-mlx-q8 — caller@@ -252,13 +306,12 @@ def run_fflf(args: argparse.Namespace) -> str:distilled_lora_strength=args.lora_strength,)emit_stage(1, 1, 1, "Loaded")- emit_status("Interpolating between keyframes…")- last_pixel_frame = args.num_frames - 1+ emit_status(f"Interpolating between {len(keyframe_images)} keyframes at indices {keyframe_indices}…")return pipe.generate_and_save(prompt=args.prompt,output_path=args.output,- keyframe_images=[args.image, args.last_image],- keyframe_indices=[0, last_pixel_frame],+ keyframe_images=keyframe_images,+ keyframe_indices=keyframe_indices,height=args.height,width=args.width,num_frames=args.num_frames,diff --git a/server/index.js b/server/index.jsindex 5c65ed268d..b83a29c2ee 100644--- a/server/index.js+++ b/server/index.js@@ -14,6 +14,7 @@ import appleHealthRoutes from './routes/appleHealth.js';import avatarRoutes from './routes/avatar.js';import systemHealthRoutes from './routes/systemHealth.js';import appsRoutes from './routes/apps.js';+import referenceReposRoutes from './routes/referenceRepos.js';import portsRoutes from './routes/ports.js';import logsRoutes from './routes/logs.js';import detectRoutes from './routes/detect.js';@@ -246,6 +247,7 @@ app.use('/api/alerts', alertsRoutes);app.use('/api/avatar', avatarRoutes);app.use('/api/system', systemHealthRoutes);app.use('/api/apps', appsRoutes);+app.use('/api/apps/:appId/reference-repos', referenceReposRoutes);app.use('/api/ports', portsRoutes);app.use('/api/logs', logsRoutes);app.use('/api/detect', detectRoutes);diff --git a/server/lib/errorHandler.js b/server/lib/errorHandler.jsindex b57155f229..5c749297ab 100644--- a/server/lib/errorHandler.js+++ b/server/lib/errorHandler.js@@ -28,6 +28,18 @@ export class ServerError extends Error {* Wrap async route handlers to catch errors and emit Socket.IO events* Also sends error response to client*/+/**+ * Translate a Zod safeParse() failure into the standard `Validation failed:`+ * ServerError shape that the rest of PortOS speaks. Pass the result of+ * `schema.safeParse(...)` after confirming `.success === false`.+ */+export function failValidation(parsed) {+ throw new ServerError(+ `Validation failed: ${parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join(', ')}`,+ { status: 400, code: 'VALIDATION_ERROR' },+ );+}+export function asyncHandler(fn) {return (req, res, next) => {Promise.resolve(fn(req, res, next)).catch((err) => {diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex 5128c54877..78c5a8c4fd 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -8,6 +8,7 @@ export const NAV_COMMANDS = [{ id: 'nav.review-hub', path: '/review', label: 'Review Hub', section: 'Main', aliases: ['review', 'review-hub'] },{ id: 'nav.cybercity', path: '/city', label: 'CyberCity', section: 'Main', aliases: ['city', 'cybercity'], keywords: ['3d', 'visualization'] },{ id: 'nav.apps', path: '/apps', label: 'Apps', section: 'Main', aliases: ['apps'] },+ { id: 'nav.reference-repos', path: '/reference-repos', label: 'Reference Repos', section: 'Main', aliases: ['reference-repos', 'references', 'reference', 'upstream', 'watch'], keywords: ['upstream', 'reference code', 'borrowed code', 'fork', 'git watch', 'commit watch', 'phosphene'] },{ id: 'nav.media', path: '/media/image', label: 'Media Gen', section: 'Create', aliases: ['media', 'media-gen', 'mediagen', 'generate'], keywords: ['image', 'video', 'render', 'art', 'movie'] },{ id: 'nav.media.image', path: '/media/image', label: 'Image', section: 'Create', aliases: ['image-gen', 'imagegen', 'generate-image', 'sd', 'stable-diffusion'], keywords: ['stable diffusion', 'render', 'art', 'picture', 'photo', 'draw', 'flux', 'mflux'] },diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 5119b6d136..2912c46cf1 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -178,6 +178,37 @@ export const datadogConfigSchema = z.object({environment: z.string().optional()});+// Reference-repo entry. Each app can list upstream repos it watches for+// clean-room reimplementation;+// the `reference-watch` scheduled task fetches each one, finds commits since+// `lastReviewedSha`, and produces a REFERENCE_REVIEW.md proposal in the app's+// repo. `notes` is the free-text "what we use from this repo" field — fed+// into the review prompt so the agent knows which features in our app are+// load-bearing for the watch.+export const referenceRepoSchema = z.object({+ id: z.string().min(1).max(64),+ name: z.string().min(1).max(120),+ // Either a clonable URL (https://github.com/owner/repo or scp-style+ // user@host:owner/repo.git) or a local filesystem path. The service+ // detects remote URLs by matching `scheme://` or scp-style+ // `user@host:path` (see isLocalPath in services/referenceRepos.js);+ // anything else is treated as a local path.+ repoUrl: z.string().min(1).max(500),+ branch: z.string().max(120).optional().default('main'),+ // 40-char hex SHA (case-insensitive), or null (no review yet). Validating+ // hex here rather than just length means a bogus PATCH like 'g'.repeat(40)+ // fails fast at the API instead of producing confusing git failures later.+ lastReviewedSha: z.string().regex(/^[0-9a-f]{40}$/i, 'must be a 40-char hex SHA').nullable().optional(),+ lastCheckedAt: z.string().datetime().nullable().optional(),+ notes: z.string().max(4000).optional().default(''),+ // Last action's outcome — used by the UI to highlight refs needing+ // attention. 'needs-clone' means the managed clone hasn't been+ // initialized yet (first run will populate it).+ status: z.enum(['ok', 'checking', 'error', 'needs-clone']).optional().default('needs-clone'),+ lastError: z.string().max(2000).nullable().optional(),+ createdAt: z.string().datetime().optional()+});+// App schema for registration/updateexport const appSchema = z.object({name: z.string().min(1).max(100),@@ -211,9 +242,43 @@ export const appSchema = z.object({defaultOpenPR: z.boolean().optional(),jira: jiraConfigSchema.optional().nullable(),datadog: datadogConfigSchema.optional().nullable()-});--// Partial schema for updates+ // referenceRepos is INTENTIONALLY not part of the create/update API+ // surface. createApp() doesn't persist it and updateApp() (via the+ // omit() in appUpdateSchema) ignores it — the dedicated+ // /api/apps/:appId/reference-repos endpoints own the lifecycle so+ // server-managed fields (status, lastError, createdAt) can't be+ // clobbered through the generic apps API.+});++// Used by routes that POST a NEW reference repo (id/createdAt are server-+// assigned, lastReviewedSha/lastCheckedAt populate after the first check).+// `.trim()` runs before `min(1)` so a name/repoUrl that's just whitespace+// fails validation rather than slipping through and producing confusing+// git failures downstream — matches the project convention used elsewhere+// in this file.+export const referenceRepoCreateSchema = z.object({+ name: z.string().trim().min(1).max(120),+ repoUrl: z.string().trim().min(1).max(500),+ branch: z.string().trim().max(120).optional(),+ notes: z.string().max(4000).optional()+});++// Patch schema — every field optional. `lastReviewedSha` is also accepted+// here so the UI's "mark as reviewed" button (and the post-check service+// path) can pin a SHA. Same trim-before-min-length convention as the+// create schema. lastReviewedSha is hex-validated so a bad PATCH can't+// persist a non-SHA into apps.json.+export const referenceRepoUpdateSchema = z.object({+ name: z.string().trim().min(1).max(120).optional(),+ repoUrl: z.string().trim().min(1).max(500).optional(),+ branch: z.string().trim().max(120).optional(),+ notes: z.string().max(4000).optional(),+ lastReviewedSha: z.string().regex(/^[0-9a-f]{40}$/i, 'must be a 40-char hex SHA').nullable().optional()+});++// Partial schema for updates. referenceRepos is intentionally absent+// from appSchema (see comment there) so it can't sneak in via PUT+// either — all ref CRUD goes through /api/apps/:appId/reference-repos.export const appUpdateSchema = appSchema.partial();// Provider schemadiff --git a/server/routes/referenceRepos.js b/server/routes/referenceRepos.jsnew file mode 100644index 0000000000..dabb5d87ba--- /dev/null+++ b/server/routes/referenceRepos.js@@ -0,0 +1,66 @@+/**+ * Reference Repos routes.+ *+ * Per-app management of upstream repos we borrow code from. The+ * `reference-watch` scheduled task uses `checkReferenceRepo` to find+ * commits since each ref's `lastReviewedSha`, then dispatches a CoS+ * sub-agent to write REFERENCE_REVIEW.md to the app's repo.+ *+ * Mounted at /api/apps/:appId/reference-repos so it sits next to the+ * existing apps API surface.+ */++import { Router } from 'express';+import { asyncHandler, failValidation } from '../lib/errorHandler.js';+import { referenceRepoCreateSchema, referenceRepoUpdateSchema } from '../lib/validation.js';+import {+ listReferenceRepos,+ addReferenceRepo,+ updateReferenceRepo,+ deleteReferenceRepo,+ checkReferenceRepo,+ markReferenceRepoReviewed,+} from '../services/referenceRepos.js';++const router = Router({ mergeParams: true });++router.get('/', asyncHandler(async (req, res) => {+ const refs = await listReferenceRepos(req.params.appId);+ res.json({ referenceRepos: refs });+}));++router.post('/', asyncHandler(async (req, res) => {+ const parsed = referenceRepoCreateSchema.safeParse(req.body || {});+ if (!parsed.success) failValidation(parsed);+ const ref = await addReferenceRepo(req.params.appId, parsed.data);+ res.status(201).json(ref);+}));++router.patch('/:refId', asyncHandler(async (req, res) => {+ const parsed = referenceRepoUpdateSchema.safeParse(req.body || {});+ if (!parsed.success) failValidation(parsed);+ const ref = await updateReferenceRepo(req.params.appId, req.params.refId, parsed.data);+ res.json(ref);+}));++router.delete('/:refId', asyncHandler(async (req, res) => {+ await deleteReferenceRepo(req.params.appId, req.params.refId);+ res.json({ ok: true });+}));++// Run a check now — fetches the upstream repo and returns the commit list+// since lastReviewedSha. Does NOT advance lastReviewedSha; that happens+// via the explicit /reviewed endpoint after the user / agent has actually+// processed the changes.+router.post('/:refId/check', asyncHandler(async (req, res) => {+ const snapshot = await checkReferenceRepo(req.params.appId, req.params.refId);+ res.json(snapshot);+}));++router.post('/:refId/reviewed', asyncHandler(async (req, res) => {+ const sha = (req.body?.sha || '').trim();+ const ref = await markReferenceRepoReviewed(req.params.appId, req.params.refId, sha);+ res.json(ref);+}));++export default router;diff --git a/server/routes/referenceRepos.test.js b/server/routes/referenceRepos.test.jsnew file mode 100644index 0000000000..cd6a2fb83c--- /dev/null+++ b/server/routes/referenceRepos.test.js@@ -0,0 +1,129 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';++// Stub the service surface — route tests assert wiring (status codes,+// validation, body forwarding), not the service layer (which has its own+// dedicated tests).+vi.mock('../services/referenceRepos.js', () => ({+ listReferenceRepos: vi.fn(async () => [{ id: 'r1', name: 'phosphene' }]),+ addReferenceRepo: vi.fn(async (_appId, body) => ({ id: 'r-new', ...body })),+ updateReferenceRepo: vi.fn(async (_appId, refId, patch) => ({ id: refId, ...patch })),+ deleteReferenceRepo: vi.fn(async () => ({ ok: true })),+ checkReferenceRepo: vi.fn(async () => ({ head: 'a'.repeat(40), commitCount: 2, commits: [] })),+ markReferenceRepoReviewed: vi.fn(async (_appId, refId, sha) => ({ id: refId, lastReviewedSha: sha })),+}));++import * as svc from '../services/referenceRepos.js';+import referenceReposRoutes from './referenceRepos.js';+import { errorMiddleware } from '../lib/errorHandler.js';++const buildApp = () => {+ const app = express();+ app.use(express.json());+ // Same nested mount the production server uses — :appId is the parent param.+ app.use('/api/apps/:appId/reference-repos', referenceReposRoutes);+ app.use(errorMiddleware);+ return app;+};++describe('reference repos routes', () => {+ let app;+ beforeEach(() => {+ vi.clearAllMocks();+ app = buildApp();+ });++ describe('GET /', () => {+ it('returns the list under {referenceRepos}', async () => {+ const r = await request(app).get('/api/apps/app-1/reference-repos');+ expect(r.status).toBe(200);+ expect(r.body).toEqual({ referenceRepos: [{ id: 'r1', name: 'phosphene' }] });+ expect(svc.listReferenceRepos).toHaveBeenCalledWith('app-1');+ });+ });++ describe('POST /', () => {+ it('creates a ref from a valid body', async () => {+ const r = await request(app).post('/api/apps/app-1/reference-repos').send({+ name: 'phosphene',+ repoUrl: 'https://github.com/x/y.git',+ notes: 'video gen',+ });+ expect(r.status).toBe(201);+ expect(r.body).toMatchObject({ id: 'r-new', name: 'phosphene' });+ expect(svc.addReferenceRepo).toHaveBeenCalledWith('app-1', expect.objectContaining({ name: 'phosphene' }));+ });++ it('rejects missing name with 400', async () => {+ const r = await request(app).post('/api/apps/app-1/reference-repos').send({+ repoUrl: 'https://github.com/x/y.git',+ });+ expect(r.status).toBe(400);+ expect(r.body.error).toMatch(/Validation failed/);+ });++ it('rejects oversized notes', async () => {+ const r = await request(app).post('/api/apps/app-1/reference-repos').send({+ name: 'x',+ repoUrl: 'y',+ notes: 'a'.repeat(5000),+ });+ expect(r.status).toBe(400);+ });+ });++ describe('PATCH /:refId', () => {+ it('forwards the patch to the service', async () => {+ const r = await request(app).patch('/api/apps/app-1/reference-repos/r1').send({+ name: 'renamed',+ });+ expect(r.status).toBe(200);+ expect(r.body).toMatchObject({ id: 'r1', name: 'renamed' });+ expect(svc.updateReferenceRepo).toHaveBeenCalledWith('app-1', 'r1', { name: 'renamed' });+ });++ it('rejects malformed lastReviewedSha (must be 40 chars)', async () => {+ const r = await request(app).patch('/api/apps/app-1/reference-repos/r1').send({+ lastReviewedSha: 'short',+ });+ expect(r.status).toBe(400);+ });++ it('rejects 40-char non-hex lastReviewedSha (validation regex)', async () => {+ // Length-only validation would accept 'g'.repeat(40) and persist it,+ // then `git log <bad>..HEAD` would fail later in a confusing way.+ const r = await request(app).patch('/api/apps/app-1/reference-repos/r1').send({+ lastReviewedSha: 'g'.repeat(40),+ });+ expect(r.status).toBe(400);+ });+ });++ describe('DELETE /:refId', () => {+ it('returns ok=true', async () => {+ const r = await request(app).delete('/api/apps/app-1/reference-repos/r1');+ expect(r.status).toBe(200);+ expect(r.body).toEqual({ ok: true });+ expect(svc.deleteReferenceRepo).toHaveBeenCalledWith('app-1', 'r1');+ });+ });++ describe('POST /:refId/check', () => {+ it('returns the snapshot the service produces', async () => {+ const r = await request(app).post('/api/apps/app-1/reference-repos/r1/check');+ expect(r.status).toBe(200);+ expect(r.body).toMatchObject({ commitCount: 2 });+ expect(svc.checkReferenceRepo).toHaveBeenCalledWith('app-1', 'r1');+ });+ });++ describe('POST /:refId/reviewed', () => {+ it('forwards the SHA to the service', async () => {+ const sha = 'a'.repeat(40);+ const r = await request(app).post('/api/apps/app-1/reference-repos/r1/reviewed').send({ sha });+ expect(r.status).toBe(200);+ expect(svc.markReferenceRepoReviewed).toHaveBeenCalledWith('app-1', 'r1', sha);+ });+ });+});diff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsindex 2bfb3050c7..588bfa6aa2 100644--- a/server/routes/videoGen.js+++ b/server/routes/videoGen.js@@ -12,7 +12,7 @@ import { copyFile, unlink } from 'fs/promises';import { randomUUID } from 'crypto';import { join, basename, resolve as resolvePath, sep as PATH_SEP, extname } from 'path';import { z } from 'zod';-import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { asyncHandler, ServerError, failValidation } from '../lib/errorHandler.js';import { uploadFields } from '../lib/multipart.js';import { PATHS, ensureDir } from '../lib/fileUtils.js';import { safeUnder } from '../lib/ffmpeg.js';@@ -26,6 +26,7 @@ import {extractLastFrame,stitchVideos,upscaleHistoryItem,+ DEFAULT_NUM_FRAMES,} from '../services/videoGen/local.js';import { enqueueJob, attachSseClient, cancelJob, listJobs } from '../services/mediaJobQueue/index.js';@@ -79,13 +80,21 @@ const optionalNum = (min, max, label) => z.preprocess((v) => v == null || v === '' ? undefined : Number(v),z.number().refine((n) => n >= min && n <= max, `${label} ${min}..${max}`).optional(),);+// numFrames and chunks must be integers. Multipart bodies send `'121'` as+// a string and `'121.5'` would silently coerce to 121.5 — feed that into+// keyframe-index range checks and the maximum becomes a fractional bound,+// not an integer one. Reject up front.+const optionalInt = (min, max, label) => z.preprocess(+ (v) => v == null || v === '' ? undefined : Number(v),+ z.number().int().refine((n) => n >= min && n <= max, `${label} ${min}..${max}`).optional(),+);const generateBodySchema = z.object({prompt: z.string().min(1).max(2000),negativePrompt: z.string().max(2000).optional(),modelId: z.string().max(64).optional(),width: optionalNum(64, 2048, 'width'),height: optionalNum(64, 2048, 'height'),- numFrames: optionalNum(1, 1024, 'numFrames'),+ numFrames: optionalInt(1, 1024, 'numFrames'),fps: optionalNum(1, 60, 'fps'),steps: optionalNum(1, 200, 'steps'),guidanceScale: optionalNum(0, 30, 'guidanceScale'),@@ -105,12 +114,30 @@ const generateBodySchema = z.object({// Chain N renders end-to-end: each chunk's last frame becomes the next// chunk's start frame, then ffmpeg concats them into one clip. 1..8 to// keep the worst-case wall time bounded (8 × ~5min ≈ 40min on M3 Max).- chunks: optionalNum(1, 8, 'chunks'),+ chunks: optionalInt(1, 8, 'chunks'),// History id of a prior render to extend natively (ltx2 runtime only —// routes through ExtendPipeline.extend_from_video which conditions on// the entire source video's latent rather than a single last frame).// The legacy chained-i2v path keeps using sourceImageFile.extendFromVideoId: z.string().uuid().optional(),+ // Multi-keyframe interpolation (ltx2 + mode='fflf'). Each entry pins one+ // gallery image at a specific pixel-frame index. Indices must be strictly+ // ascending and within [0, numFrames-1]. When set, overrides the legacy+ // sourceImageFile/lastImageFile pair. Multipart bodies arrive as a string,+ // so the preprocess parses JSON before zod sees it.+ keyframes: z.preprocess(+ (v) => {+ if (v == null || v === '') return undefined;+ if (typeof v === 'string') {+ try { return JSON.parse(v); } catch { return v; }+ }+ return v;+ },+ z.array(z.object({+ file: z.string().min(1).max(512),+ index: z.number().int().min(0).max(1023),+ })).min(2).max(8).optional(),+ ),});router.get('/status', asyncHandler(async (_req, res) => {@@ -166,7 +193,7 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {const parsed = generateBodySchema.safeParse(req.body);if (!parsed.success) {await cleanupTempUploads();- throw new ServerError(`Validation failed: ${parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join(', ')}`, { status: 400, code: 'VALIDATION_ERROR' });+ failValidation(parsed);}const body = parsed.data;const s = await getSettings();@@ -316,6 +343,96 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {extraUploadedTempPaths.push(audioFilePath);}+ // Multi-keyframe interpolation: resolve each gallery filename to an+ // absolute path under PATHS.images via the same path-traversal guard as+ // sourceImageFile. Reject up-front when any reference can't be resolved+ // so the queue doesn't accept a doomed job. Only valid for fflf mode ++ // single-chunk renders (the chain orchestrator pins keyframes only on+ // chunk 0; chaining ≥2 chunks with N keyframes has no defined semantic).+ let resolvedKeyframes = null;+ if (body.keyframes && body.keyframes.length >= 2) {+ if (body.mode && body.mode !== 'fflf') {+ await cleanupAllStaged();+ throw new ServerError(+ `keyframes is only valid with mode='fflf' (got mode='${body.mode}').`,+ { status: 400, code: 'KEYFRAMES_MODE_MISMATCH' },+ );+ }+ // Reject mixing keyframes with the legacy 2-keyframe inputs — the+ // worker would silently ignore sourceImage/lastImage when keyframes is+ // present, but staging/resizing them anyway is wasted work and the+ // ambiguity (which one wins?) bites callers later. Force the user to+ // pick one shape per request. Covers both upload paths and the+ // gallery-resolved file fields.+ if (sourceImagePath || lastImagePath || body.sourceImageFile || body.lastImageFile) {+ await cleanupAllStaged();+ throw new ServerError(+ 'keyframes cannot be combined with sourceImage / lastImage inputs — pass each anchor frame as a keyframes[] entry instead.',+ { status: 400, code: 'KEYFRAMES_LEGACY_INPUTS_CONFLICT' },+ );+ }+ // Multi-keyframe FFLF is an LTX-2 primitive — the legacy mlx_video+ // pipeline has no equivalent. Mirror the a2v guard above so a bad+ // modelId can't enqueue a doomed job that will only fail in the+ // worker (with KEYFRAMES_REQUIRE_LTX2).+ if (effectiveModel && effectiveModel.runtime !== 'ltx2') {+ await cleanupAllStaged();+ throw new ServerError(+ `keyframes mode requires an ltx2-runtime model. Model "${effectiveModelId}" runs on "${effectiveModel.runtime || 'mlx_video'}".`,+ { status: 400, code: 'KEYFRAMES_REQUIRE_LTX2' },+ );+ }+ // Default mode to 'fflf' when keyframes is set without an explicit mode —+ // otherwise local.js#buildLtx2Args resolves helperMode to 'text' and the+ // keyframes silently disappear.+ if (!body.mode) body.mode = 'fflf';+ if (body.chunks != null && Number(body.chunks) > 1) {+ await cleanupAllStaged();+ throw new ServerError(+ 'keyframes cannot be combined with chunks > 1 — keyframes anchor a single clip.',+ { status: 400, code: 'KEYFRAMES_CHUNKS_CONFLICT' },+ );+ }+ // Validate keyframe indices against the *effective* numFrames so a+ // request with no explicit `numFrames` (which falls back to the+ // generateVideo default of 121) still rejects out-of-range indices+ // up-front instead of failing late inside the worker / Python helper.+ // Keep this in sync with the default in services/videoGen/local.js.+ const effectiveNumFrames = body.numFrames != null ? Number(body.numFrames) : DEFAULT_NUM_FRAMES;+ resolvedKeyframes = [];+ let prevIndex = -1;+ for (let i = 0; i < body.keyframes.length; i++) {+ const kf = body.keyframes[i];+ const path = resolveGalleryImage(kf.file);+ if (!path) {+ await cleanupAllStaged();+ throw new ServerError(+ `keyframes[${i}].file not found in gallery: ${kf.file}`,+ { status: 400, code: 'KEYFRAME_GALLERY_MISS' },+ );+ }+ if (kf.index <= prevIndex) {+ await cleanupAllStaged();+ throw new ServerError(+ `keyframes indices must be strictly ascending; got ${prevIndex} then ${kf.index}`,+ { status: 400, code: 'KEYFRAME_INDICES_NOT_ASCENDING' },+ );+ }+ if (kf.index > effectiveNumFrames - 1) {+ await cleanupAllStaged();+ const numFramesLabel = body.numFrames != null+ ? `numFrames ${body.numFrames}`+ : `default numFrames ${DEFAULT_NUM_FRAMES}`;+ throw new ServerError(+ `keyframes[${i}].index ${kf.index} >= ${numFramesLabel}`,+ { status: 400, code: 'KEYFRAME_INDEX_OUT_OF_RANGE' },+ );+ }+ resolvedKeyframes.push({ path, index: kf.index });+ prevIndex = kf.index;+ }+ }+// Native extend (ltx2 runtime): resolve the history id to a video file// path under data/videos/ and forward it as extendFromVideoPath. Reject// a missing/tampered id rather than silently falling back to t2v —@@ -371,6 +488,7 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {uploadedTempPath,uploadedTempPaths: extraUploadedTempPaths,lastImagePath,+ keyframes: resolvedKeyframes,extendFromVideoPath,mode: body.mode,imageStrength: body.imageStrength,@@ -439,10 +557,6 @@ router.post('/last-frame/:id', asyncHandler(async (req, res) => {// other route schemas.const historyIdSchema = z.string().uuid('invalid history id');-const failValidation = (parsed) => {- throw new ServerError(`Validation failed: ${parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join(', ')}`, { status: 400, code: 'VALIDATION_ERROR' });-};-router.post('/upscale/:id', asyncHandler(async (req, res) => {const parsed = historyIdSchema.safeParse(req.params.id);if (!parsed.success) failValidation(parsed);diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.jsindex c1a4fdb2fd..36a69bd55b 100644--- a/server/routes/videoGen.test.js+++ b/server/routes/videoGen.test.js@@ -21,6 +21,9 @@ vi.mock('../services/videoGen/local.js', () => ({extractLastFrame: vi.fn(),stitchVideos: vi.fn(),upscaleHistoryItem: vi.fn(),+ // Mirrors the real export — keeps the route's keyframe-range check in+ // sync with whatever the service actually defaults to.+ DEFAULT_NUM_FRAMES: 121,}));// Render submissions go through the mediaJobQueue. Mock its surface so the@@ -235,6 +238,190 @@ describe('videoGen routes', () => {}));});+ it('forwards multi-keyframe array (resolved to gallery paths) under params.keyframes', async () => {+ const r = await request(app).post('/api/video-gen/').send({+ prompt: 'four-pose shot',+ mode: 'fflf',+ numFrames: 121,+ keyframes: [+ { file: 'pose-a.png', index: 0 },+ { file: 'pose-b.png', index: 40 },+ { file: 'pose-c.png', index: 80 },+ { file: 'pose-d.png', index: 120 },+ ],+ });+ expect(r.status).toBe(200);+ expect(mediaJobQueue.enqueueJob).toHaveBeenCalledWith(expect.objectContaining({+ kind: 'video',+ params: expect.objectContaining({+ mode: 'fflf',+ keyframes: [+ { path: '/mock/images/pose-a.png', index: 0 },+ { path: '/mock/images/pose-b.png', index: 40 },+ { path: '/mock/images/pose-c.png', index: 80 },+ { path: '/mock/images/pose-d.png', index: 120 },+ ],+ }),+ }));+ });++ it('parses keyframes when sent as a JSON-encoded string (multipart bodies)', async () => {+ const r = await request(app).post('/api/video-gen/').send({+ prompt: 'multipart-style submission',+ mode: 'fflf',+ numFrames: 49,+ keyframes: JSON.stringify([+ { file: 'a.png', index: 0 },+ { file: 'b.png', index: 48 },+ ]),+ });+ expect(r.status).toBe(200);+ expect(mediaJobQueue.enqueueJob).toHaveBeenCalledWith(expect.objectContaining({+ params: expect.objectContaining({+ keyframes: [+ { path: '/mock/images/a.png', index: 0 },+ { path: '/mock/images/b.png', index: 48 },+ ],+ }),+ }));+ });++ it("defaults mode to 'fflf' when keyframes is set without an explicit mode", async () => {+ const r = await request(app).post('/api/video-gen/').send({+ prompt: 'mode-default coercion',+ numFrames: 49,+ keyframes: [+ { file: 'a.png', index: 0 },+ { file: 'b.png', index: 48 },+ ],+ });+ expect(r.status).toBe(200);+ expect(mediaJobQueue.enqueueJob).toHaveBeenCalledWith(expect.objectContaining({+ params: expect.objectContaining({ mode: 'fflf' }),+ }));+ });++ it('rejects keyframes when paired with mode != fflf', async () => {+ const r = await request(app).post('/api/video-gen/').send({+ prompt: 'wrong mode',+ mode: 'image',+ keyframes: [+ { file: 'a.png', index: 0 },+ { file: 'b.png', index: 24 },+ ],+ });+ expect(r.status).toBe(400);+ expect(r.body.error).toMatch(/keyframes is only valid with mode='fflf'/);+ });++ it('rejects keyframes when chunks > 1 (no defined chained semantic)', async () => {+ const r = await request(app).post('/api/video-gen/').send({+ prompt: 'chained keyframes',+ mode: 'fflf',+ chunks: 3,+ keyframes: [+ { file: 'a.png', index: 0 },+ { file: 'b.png', index: 24 },+ ],+ });+ expect(r.status).toBe(400);+ expect(r.body.error).toMatch(/keyframes cannot be combined with chunks/);+ });++ it('rejects keyframes when an index is outside [0, numFrames-1]', async () => {+ const r = await request(app).post('/api/video-gen/').send({+ prompt: 'out of range index',+ mode: 'fflf',+ numFrames: 25,+ keyframes: [+ { file: 'a.png', index: 0 },+ { file: 'b.png', index: 25 }, // == numFrames, must be < numFrames+ ],+ });+ expect(r.status).toBe(400);+ expect(r.body.error).toMatch(/>= numFrames/);+ });++ it('rejects keyframes paired with a non-ltx2 modelId (KEYFRAMES_REQUIRE_LTX2)', async () => {+ // Multi-keyframe FFLF is an LTX-2 primitive — the route must reject+ // up-front rather than enqueue and let the worker fail asynchronously.+ videoGenService.listVideoModels.mockReturnValueOnce([+ { id: 'ltx_legacy', name: 'LTX legacy', runtime: 'mlx_video' },+ ]);+ const r = await request(app).post('/api/video-gen/').send({+ prompt: 'multi-keyframe on the wrong runtime',+ modelId: 'ltx_legacy',+ keyframes: [+ { file: 'a.png', index: 0 },+ { file: 'b.png', index: 24 },+ ],+ });+ expect(r.status).toBe(400);+ expect(r.body.code).toBe('KEYFRAMES_REQUIRE_LTX2');+ expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();+ });++ it('rejects keyframes paired with sourceImageFile (KEYFRAMES_LEGACY_INPUTS_CONFLICT)', async () => {+ // Mixing keyframes with the legacy 2-keyframe inputs has ambiguous+ // precedence — force callers to pick one shape per request so the+ // worker doesn't silently drop one.+ const r = await request(app).post('/api/video-gen/').send({+ prompt: 'ambiguous inputs',+ sourceImageFile: 'first.png',+ keyframes: [+ { file: 'a.png', index: 0 },+ { file: 'b.png', index: 24 },+ ],+ });+ expect(r.status).toBe(400);+ expect(r.body.code).toBe('KEYFRAMES_LEGACY_INPUTS_CONFLICT');+ expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();+ });++ it('rejects keyframes paired with lastImageFile (KEYFRAMES_LEGACY_INPUTS_CONFLICT)', async () => {+ const r = await request(app).post('/api/video-gen/').send({+ prompt: 'ambiguous inputs 2',+ lastImageFile: 'last.png',+ keyframes: [+ { file: 'a.png', index: 0 },+ { file: 'b.png', index: 24 },+ ],+ });+ expect(r.status).toBe(400);+ expect(r.body.code).toBe('KEYFRAMES_LEGACY_INPUTS_CONFLICT');+ expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();+ });++ it('rejects keyframes with index > default numFrames when numFrames is omitted', async () => {+ // generateVideo() defaults numFrames to 121 — the route must reject+ // out-of-range indices up-front instead of letting them queue and+ // fail late inside the worker / Python helper.+ const r = await request(app).post('/api/video-gen/').send({+ prompt: 'no numframes specified',+ mode: 'fflf',+ keyframes: [+ { file: 'a.png', index: 0 },+ { file: 'b.png', index: 500 }, // way past default of 121+ ],+ });+ expect(r.status).toBe(400);+ expect(r.body.error).toMatch(/default numFrames 121/);+ });++ it('rejects keyframes with non-ascending indices', async () => {+ const r = await request(app).post('/api/video-gen/').send({+ prompt: 'bad order',+ mode: 'fflf',+ numFrames: 121,+ keyframes: [+ { file: 'a.png', index: 50 },+ { file: 'b.png', index: 30 }, // < previous+ ],+ });+ expect(r.status).toBe(400);+ expect(r.body.error).toMatch(/strictly ascending/);+ });+it('forwards chunks > 1 so the queue dispatches the chain orchestrator', async () => {const r = await request(app).post('/api/video-gen/').send({prompt: 'a long shot',diff --git a/server/services/cos.js b/server/services/cos.jsindex e594407efa..15a5d3e59d 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -1914,10 +1914,54 @@ async function generateManagedAppImprovementTaskForType(taskType, app, state, {const promptTemplate = metadata.pipeline?.stages? await taskSchedule.getStagePrompt(taskType, 0): await taskSchedule.getTaskPrompt(taskType);++ // reference-watch: dynamically inject {referenceData} — a Markdown chunk+ // describing each ref configured on the app + commits since lastReviewedSha.+ // The check itself fetches each upstream and persists status/lastError, so+ // a bad URL surfaces in the UI even if the agent dispatch is skipped below.+ let referenceDataBlock = '';+ if (taskType === 'reference-watch') {+ const refs = Array.isArray(app.referenceRepos) ? app.referenceRepos : [];+ if (refs.length === 0) {+ emitLog('info', `Skipping reference-watch for ${app.name}: no reference repos configured`, { appId: app.id });+ return null;+ }+ const referenceRepos = await import('./referenceRepos.js');+ const blocks = [];+ let anySuccessWithCommits = false;+ for (const ref of refs) {+ try {+ // eslint-disable-next-line no-await-in-loop+ const snapshot = await referenceRepos.checkReferenceRepo(app.id, ref.id);+ if (snapshot.commitCount > 0) {+ blocks.push(referenceRepos.formatReferenceForPrompt(ref, snapshot));+ anySuccessWithCommits = true;+ }+ } catch (err) {+ emitLog('warn', `Reference check failed for ${ref.name}: ${err.message}`, { appId: app.id, refId: ref.id });+ blocks.push(`## Reference: ${ref.name}\n\n_Check failed: ${err.message}_`);+ }+ }+ // Don't burn an agent dispatch when there's nothing actionable —+ // either every ref is up-to-date OR every ref errored. Errored refs+ // already surfaced their lastError in the UI via checkReferenceRepo,+ // so the user can fix configs without an agent involved.+ if (!anySuccessWithCommits) {+ emitLog('info', `Skipping reference-watch for ${app.name}: no refs produced reviewable commits`, { appId: app.id });+ return null;+ }+ referenceDataBlock = blocks.join('\n\n---\n\n');+ }+const description = promptTemplate.replace(/\{appName\}/g, app.name).replace(/\{repoPath\}/g, app.repoPath)- .replace(/\{appId\}/g, app.id);+ .replace(/\{appId\}/g, app.id)+ // Use a replacer function — String.replace with a replacement STRING+ // interprets `$&`, `$1`, etc. as backreferences. Commit subjects/authors+ // legitimately contain `$` (env-var docs, prices, awk snippets) and+ // would get mangled. The function form passes the value verbatim.+ .replace(/\{referenceData\}/g, () => referenceDataBlock);applyAppWorktreeDefault(metadata, app);diff --git a/server/services/referenceRepos.js b/server/services/referenceRepos.jsnew file mode 100644index 0000000000..62352c915b--- /dev/null+++ b/server/services/referenceRepos.js@@ -0,0 +1,589 @@+/**+ * Reference Repos service.+ *+ * Each PortOS-managed app can list upstream repos it watches for clean-room+ * reimplementation — the agent reads upstream commits and proposes which+ * features/fixes are worth re-building in the app's OWN code, never+ * copying upstream verbatim.+ * (e.g., PortOS itself watches `phosphene` for video-gen ideas). The+ * `reference-watch` scheduled task asks this service to fetch each ref+ * and find commits since `lastReviewedSha`. The CoS sub-agent then+ * produces a REFERENCE_REVIEW.md proposal in the target app's repo.+ *+ * Storage: refs live inline on each app in data/apps.json under the+ * `referenceRepos` array — fits the existing per-app config model and+ * keeps the schedule task's per-app dispatch simple.+ *+ * Clones: managed under data/cos/reference-repos/<refId>/. The user+ * never has to clone manually; first `check` initializes the clone.+ */++import { existsSync, statSync } from 'fs';+import { homedir } from 'os';+import { join } from 'path';+import { v4 as uuidv4 } from '../lib/uuid.js';+import { ensureDir, PATHS } from '../lib/fileUtils.js';+import { ServerError } from '../lib/errorHandler.js';+import { execGit } from '../lib/execGit.js';+import {+ getAppById,+ updateApp,+} from './apps.js';++// `path.join(homedir(), '/.foo')` discards the homedir because of the leading+// slash, so we strip the `~/` prefix (or `~`) before joining. Same shape as+// the helper in lib/mediaModels.js — kept inline here to avoid pulling in the+// rest of that module just for one helper.+const expandHome = (p) => {+ if (!p || typeof p !== 'string' || !p.startsWith('~')) return p;+ if (p === '~') return homedir();+ if (p.startsWith('~/')) return join(homedir(), p.slice(2));+ return p;+};++const REFERENCE_REPOS_ROOT = join(PATHS.data, 'cos', 'reference-repos');++// 40-char hex SHA the same way git outputs it. Used by every callsite that+// reads a SHA back from `git rev-parse` — git is supposed to give us 40 hex+// chars, but if the working tree is corrupt we should fail loud rather than+// quietly write garbage to apps.json.+const SHA_RE = /^[0-9a-f]{40}$/i;++const SHORT_SHA = (sha) => (sha && SHA_RE.test(sha) ? sha.slice(0, 8) : null);++// addReferenceRepo always assigns refIds via uuidv4(), but apps.json is a+// hand-editable JSON file — a corrupted or maliciously-edited entry could+// set `id` to "../.." and have cloneDir escape REFERENCE_REPOS_ROOT,+// letting git operations read/write arbitrary paths under PATHS.data.+// Enforce a strict id format here so the assumption "refId is a safe+// path segment" holds at every callsite.+const REF_ID_RE = /^[A-Za-z0-9_-]+$/;+const cloneDir = (refId) => {+ if (typeof refId !== 'string' || !REF_ID_RE.test(refId)) {+ throw new ServerError(+ `Reference repo id has an invalid format (must match ${REF_ID_RE.source}): ${refId}`,+ { status: 500, code: 'REFERENCE_REPO_BAD_ID' },+ );+ }+ return join(REFERENCE_REPOS_ROOT, refId);+};++// scp-style remotes — git accepts both `user@host:path` and the bare+// `host:path` form. Disambiguating from a Windows drive path (`C:\foo`,+// `C:/foo`) requires the segment before `:` to be longer than one char+// (excluding Windows drive letters). The segment after `:` must NOT start+// with `\` or `/` (excluding `C:\path` / `C:/path` style local paths).+// This matches how git itself parses scp-syntax in `connect.c`. Examples:+// [email protected]:owner/repo.git → remote (scp with user, dotted host)+// github.com:owner/repo.git → remote (scp without user, dotted host)+// gitserver:owner/repo.git → remote (scp without user, intranet host+// with no dot — common on internal forges)+// user@gitserver:owner/repo.git → remote (scp with user, host has no dot)+// C:\Users\me\repo → local (host-segment single char)+// C:/Users/me/repo → local (same; segment after `:` is `/`)+const SCP_REMOTE_RE = /^([^/@:]+@)?[^/@:]{2,}:[^\\/].*$/;++const isLocalPath = (urlOrPath) => {+ if (!urlOrPath) return false;+ // scheme:// and scp-style remotes (`user@host:path` and bare `host:path`)+ // are remote; everything else (including ~ and absolute paths) is local.+ // The user can pass `/Users/.../phosphene` or `~/phosphene` to skip the+ // clone and reuse an existing working tree.+ if (urlOrPath.includes('://')) return false;+ if (SCP_REMOTE_RE.test(urlOrPath)) return false;+ return true;+};++// Strip userinfo (`user:token@`) from URL-shaped args so a bad HTTPS remote+// doesn't surface its embedded PAT in the persisted `lastError` field (which+// the UI renders verbatim). Also catches scp-style `user@host:path` — but+// keeps the host so the user can still see what failed.+const redactUrlCreds = (s) => {+ if (typeof s !== 'string') return s;+ // scheme://user:token@host/... → scheme://host/...+ let out = s.replace(/(\w+:\/\/)[^\s/@]+@/g, '$1');+ // user@host:path → host:path (scp-style only, no scheme)+ if (!out.includes('://')) {+ out = out.replace(/(^|\s)[^\s/@:]+@([^\s/@:]+:[^\s]+)/g, '$1$2');+ }+ return out;+};+const redactArgsForError = (args) => args.map(redactUrlCreds);++// Reject any HTTPS URL with credentials in userinfo (e.g.+// `https://token@host/repo` or `https://user:token@host/repo`). Throws a+// 400 ServerError on rejection so route handlers don't need to repeat the+// check. scp-style `git@host:repo` is NOT credentials (SSH key auth) and+// is allowed through. Used by both addReferenceRepo (ingest) and+// updateReferenceRepo (PATCH) so a tokened URL can't sneak in either way.+const rejectCredentialedUrl = (url) => {+ if (typeof url !== 'string') return;+ if (/^\w+:\/\/[^\s/@]+@/.test(url)) {+ throw new ServerError(+ 'repoUrl must not embed credentials in the URL (e.g. https://token@host/repo). Configure git credentials separately (credential helper, SSH keys).',+ { status: 400, code: 'REFERENCE_REPO_URL_HAS_CREDS' },+ );+ }+};++// Patterns that indicate the user's config is wrong (so the right HTTP+// status is 4xx, not 5xx). Order matters — first match wins. Codes here+// surface to the UI via `lastError`, so the strings are user-facing.+const GIT_USER_ERROR_PATTERNS = [+ { pattern: /authentication failed|could not read username|terminal prompts disabled/i, code: 'REFERENCE_REPO_AUTH_FAILED', status: 400 },+ { pattern: /could not resolve host|repository not found|not found\.\s*$/i, code: 'REFERENCE_REPO_NOT_FOUND_REMOTE', status: 400 },+ { pattern: /unknown revision|bad revision|unknown ref/i, code: 'REFERENCE_REPO_BAD_REF', status: 400 },+ { pattern: /not a git repository/i, code: 'REFERENCE_REPO_NOT_A_REPO', status: 400 },+];++// Wrap the shared execGit helper so the rest of this module gets the same+// `(cwd, args) => stdout` shape it had before — and so any git failure here+// surfaces as a typed ServerError instead of a bare Error.+const runGit = async (cwd, args, { timeoutMs = 60_000 } = {}) => {+ const result = await execGit(args, cwd, { timeout: timeoutMs }).catch((err) => ({ error: err }));+ if (result.error) {+ // Redact `user:token@host` userinfo and scp-style `user@host` from BOTH+ // the persisted/thrown message AND the server log line — credentials+ // embedded in repoUrl must not land anywhere they could later be read+ // (logs, persisted lastError, or API responses).+ const safeArgs = redactArgsForError(args);+ const safeMessage = redactUrlCreds(String(result.error.message || ''));+ console.error(`❌ git ${safeArgs.join(' ')} (cwd=${cwd}) failed: ${safeMessage}`);+ // Map well-known stderr patterns to 4xx so the UI/route layer can+ // distinguish "fix your config" from "server problem". checkReferenceRepo+ // preserves these codes when re-throwing.+ const userError = GIT_USER_ERROR_PATTERNS.find((p) => p.pattern.test(safeMessage));+ const status = userError ? userError.status : 500;+ const code = userError ? userError.code : 'REFERENCE_REPO_GIT_FAILED';+ throw new ServerError(`git ${safeArgs.join(' ')}: ${safeMessage}`, { status, code });+ }+ return String(result.stdout || '').trim();+};++/**+ * Resolve the working directory for a ref. For URL-based refs we use the+ * managed clone path under data/cos/reference-repos/<refId>/; for local+ * refs (user-supplied path), we shell directly into that path so the user+ * can keep using their normal working tree. `~` in a local path is+ * expanded so cwd ends up on the actual filesystem path.+ */+const workingDirectory = (ref) => (+ isLocalPath(ref.repoUrl) ? expandHome(ref.repoUrl) : cloneDir(ref.id)+);++/**+ * Make sure the managed clone exists for a URL-based ref. No-op for local+ * refs (the user maintains those themselves).+ */+const ensureClone = async (ref) => {+ if (isLocalPath(ref.repoUrl)) {+ const localPath = expandHome(ref.repoUrl);+ if (!existsSync(localPath)) {+ throw new ServerError(`Local reference path not found: ${ref.repoUrl}`, { status: 400, code: 'REFERENCE_REPO_LOCAL_MISSING' });+ }+ // A regular file (or symlink to one) at the path will surface later as+ // an opaque "not a git repository" error from `git rev-parse`. Catch it+ // here with a clear message so the user knows to fix the URL.+ let stat;+ try { stat = statSync(localPath); } catch {+ throw new ServerError(`Local reference path not accessible: ${ref.repoUrl}`, { status: 400, code: 'REFERENCE_REPO_LOCAL_INACCESSIBLE' });+ }+ if (!stat.isDirectory()) {+ throw new ServerError(`Local reference path is not a directory: ${ref.repoUrl}`, { status: 400, code: 'REFERENCE_REPO_LOCAL_NOT_DIR' });+ }+ if (!existsSync(join(localPath, '.git'))) {+ throw new ServerError(`Local reference path is not a git working tree (no .git): ${ref.repoUrl}`, { status: 400, code: 'REFERENCE_REPO_LOCAL_NOT_GIT' });+ }+ return localPath;+ }+ await ensureDir(REFERENCE_REPOS_ROOT);+ const dest = cloneDir(ref.id);+ if (existsSync(join(dest, '.git'))) return dest;+ // No clone yet → bring one down. --depth 1 would lose the diff window we+ // need for `git log lastReviewedSha..HEAD`, so do a full clone.+ console.log(`📦 Cloning reference repo "${ref.name}" → ${dest}`);+ await runGit(REFERENCE_REPOS_ROOT, ['clone', ref.repoUrl, ref.id], { timeoutMs: 600_000 });+ return dest;+};++/**+ * Fetch the latest commits for a ref's branch (or its remote-tracking+ * default if no branch was set). Returns the head SHA after fetch.+ */+const fetchHead = async (ref) => {+ const cwd = await ensureClone(ref);+ const branch = ref.branch || 'main';+ // For URL-based refs, fetch the latest from origin so rev-parse picks+ // up new commits. Local-path refs are the user's own working tree —+ // skip fetch (the user manages their tree directly) and read the+ // branch tip in place.+ if (!isLocalPath(ref.repoUrl)) {+ await runGit(cwd, ['fetch', '--prune', 'origin', branch]);+ }+ const headRef = isLocalPath(ref.repoUrl) ? branch : `origin/${branch}`;+ const head = await runGit(cwd, ['rev-parse', headRef]);+ if (!SHA_RE.test(head)) {+ throw new ServerError(`git rev-parse returned non-SHA for ${headRef}: "${head}"`, { status: 500, code: 'REFERENCE_REPO_GIT_FAILED' });+ }+ return { cwd, head, headRef };+};++/**+ * Build a structured commit list since `sinceSha` (exclusive) up to the+ * ref tip. Returned shape is JSON-friendly so the UI / agent prompt can+ * render it directly.+ */+// Hard cap on commits returned per check. Without this, a ref left+// unreviewed for a long time (a year of upstream activity, e.g. ~3000+// commits) generates an oversized agent prompt, a huge UI payload, and+// a slow git log. 200 is plenty for the agent to prioritize commits+// against the user's notes; the user can pin lastReviewedSha forward+// to drop older items if needed.+const COMMIT_LIST_CAP = 200;++// Returns { commits, truncated, totalCommitCount } where:+// - commits.length <= COMMIT_LIST_CAP+// - truncated is true when totalCommitCount > COMMIT_LIST_CAP+// - totalCommitCount is null when truncation isn't possible (no sinceSha)+const listCommits = async (cwd, sinceSha, headRef) => {+ if (!sinceSha) {+ // No prior review — surface only the most recent 25 commits to keep+ // the first-scan prompt bounded. The UI tells the user they can pin+ // a SHA manually if they want to start from a specific point.+ const out = await runGit(cwd, ['log', '-n', '25', '--pretty=format:%H%x09%an%x09%ae%x09%aI%x09%s', headRef]);+ return { commits: parseCommitLog(out), truncated: false, totalCommitCount: null };+ }+ // For incremental scans we DO know the total — check it cheaply with+ // `rev-list --count` so the UI can show "showing 200 of N" honestly,+ // then fetch only the most recent COMMIT_LIST_CAP entries.+ const range = `${sinceSha}..${headRef}`;+ const totalRaw = await runGit(cwd, ['rev-list', '--count', range]);+ const totalCommitCount = Number(totalRaw) || 0;+ const out = await runGit(cwd, ['log', '-n', String(COMMIT_LIST_CAP), '--pretty=format:%H%x09%an%x09%ae%x09%aI%x09%s', range]);+ const commits = parseCommitLog(out);+ return { commits, truncated: totalCommitCount > COMMIT_LIST_CAP, totalCommitCount };+};++const parseCommitLog = (raw) => {+ if (!raw) return [];+ return raw.split('\n').filter(Boolean).map((line) => {+ const [sha, author, email, date, ...rest] = line.split('\t');+ return { sha, author, email, date, subject: rest.join('\t') };+ });+};++/**+ * Public API ─────────────────────────────────────────────────────────────+ */++export async function listReferenceRepos(appId) {+ const app = await getAppById(appId);+ if (!app) throw new ServerError(`App not found: ${appId}`, { status: 404, code: 'APP_NOT_FOUND' });+ return Array.isArray(app.referenceRepos) ? app.referenceRepos : [];+}++export async function addReferenceRepo(appId, { name, repoUrl, branch, notes }) {+ const app = await getAppById(appId);+ if (!app) throw new ServerError(`App not found: ${appId}`, { status: 404, code: 'APP_NOT_FOUND' });+ const trimmedUrl = repoUrl.trim();+ rejectCredentialedUrl(trimmedUrl);+ const existing = Array.isArray(app.referenceRepos) ? app.referenceRepos : [];+ const ref = {+ id: uuidv4(),+ name: name.trim(),+ repoUrl: trimmedUrl,+ branch: (branch || 'main').trim(),+ notes: (notes || '').trim(),+ lastReviewedSha: null,+ lastCheckedAt: null,+ status: 'needs-clone',+ lastError: null,+ createdAt: new Date().toISOString(),+ };+ await updateApp(appId, { referenceRepos: [...existing, ref] });+ return ref;+}++export async function updateReferenceRepo(appId, refId, patch) {+ const app = await getAppById(appId);+ if (!app) throw new ServerError(`App not found: ${appId}`, { status: 404, code: 'APP_NOT_FOUND' });+ const refs = Array.isArray(app.referenceRepos) ? app.referenceRepos : [];+ const idx = refs.findIndex((r) => r.id === refId);+ if (idx < 0) throw new ServerError(`Reference repo not found: ${refId}`, { status: 404, code: 'REFERENCE_REPO_NOT_FOUND' });+ // Allow only known fields through — guards against a bad client payload+ // resetting status/lastError/etc. Trim the same string fields that+ // addReferenceRepo() trims so we don't end up with mismatched shapes+ // (e.g. " main " as a branch name causing confusing git failures).+ //+ // Defensive SHA validation: the route's Zod schema already hex-validates+ // lastReviewedSha, but a non-route caller (CoS task runner, future+ // internal API) could bypass that and persist garbage. Re-check here so+ // the service contract is self-enforcing. null clears the SHA cleanly+ // and is allowed.+ if (patch.lastReviewedSha !== undefined && patch.lastReviewedSha !== null && !SHA_RE.test(patch.lastReviewedSha)) {+ throw new ServerError(`lastReviewedSha must be a 40-char hex SHA: ${patch.lastReviewedSha}`, { status: 400, code: 'REFERENCE_REPO_BAD_SHA' });+ }+ // PATCH must enforce the same credential-in-URL rejection as POST —+ // otherwise a user could sidestep the ingest check by editing the URL+ // afterwards and persisting `https://token@host/repo` into apps.json.+ if (typeof patch.repoUrl === 'string') {+ rejectCredentialedUrl(patch.repoUrl.trim());+ }+ // When a SHA is being pinned, verify it actually resolves to a commit+ // in the clone. Without this, a PATCH could persist a syntactically valid+ // but nonexistent SHA, and the next `checkReferenceRepo` would die in+ // `git log <bad>..HEAD` with a confusing "unknown revision" error.+ // Skipped when:+ // - clearing (null) — that always succeeds+ // - the ref has never been cloned yet (fresh add + manual SHA pin)+ // - the same PATCH is also changing repoUrl: the clone hasn't been+ // re-fetched against the new origin yet, so its commits reflect+ // the OLD repo. Verifying against stale state would produce+ // misleading results (false positives where the SHA happens to+ // exist in the old repo, or false negatives where it doesn't).+ // Let the next checkReferenceRepo surface any real mismatch.+ const repoUrlChanging = typeof patch.repoUrl === 'string' && patch.repoUrl.trim() !== refs[idx].repoUrl;+ if (+ typeof patch.lastReviewedSha === 'string'+ && SHA_RE.test(patch.lastReviewedSha)+ && !repoUrlChanging+ ) {+ const ref = refs[idx];+ const dest = isLocalPath(ref.repoUrl) ? expandHome(ref.repoUrl) : cloneDir(ref.id);+ // Same .git-existence check applies to both URL-based managed clones+ // and user-supplied local paths (ensureClone validates `.git` for local+ // refs too), so no per-branch logic needed.+ const cloneExists = existsSync(join(dest, '.git'));+ if (cloneExists) {+ const verify = await execGit(['cat-file', '-e', `${patch.lastReviewedSha}^{commit}`], dest, { timeout: 10_000 })+ .catch((err) => ({ error: err }));+ if (verify && verify.error) {+ // `cat-file -e` exits non-zero for two distinct reasons: (a) the+ // object isn't there, and (b) the repo is corrupt / unreadable /+ // permissions / timeout. The user-facing fix is different in each+ // case — distinguish via stderr text so the UI can show actionable+ // detail.+ const msg = String(verify.error.message || '').toLowerCase();+ const looksLikeMissing = /not a valid object|missing|does not exist|bad object|unable to read tree/.test(msg);+ if (looksLikeMissing) {+ throw new ServerError(+ `lastReviewedSha ${patch.lastReviewedSha.slice(0, 8)} not found in reference repo "${ref.name}"`,+ { status: 400, code: 'REFERENCE_REPO_SHA_NOT_FOUND' },+ );+ }+ // Anything else (permission denied, corrupt index, timeout) — surface+ // the underlying message so the user can act on it. Redact in case+ // the error includes the URL with credentials.+ throw new ServerError(+ `Failed to verify lastReviewedSha against reference repo "${ref.name}": ${redactUrlCreds(verify.error.message || 'unknown git error')}`,+ { status: 500, code: 'REFERENCE_REPO_SHA_VERIFY_FAILED' },+ );+ }+ }+ }+ // If repoUrl is changing on a URL-based ref with an existing managed+ // clone, point the clone's origin remote at the new URL — otherwise+ // subsequent fetches keep pulling from the old URL and the ref appears+ // stuck. Skipped when: same URL, ref is local-path (no managed clone),+ // or no clone exists yet (next check will clone fresh).+ const oldRef = refs[idx];+ if (typeof patch.repoUrl === 'string' && patch.repoUrl.trim() !== oldRef.repoUrl && !isLocalPath(patch.repoUrl)) {+ const dest = cloneDir(oldRef.id);+ if (existsSync(join(dest, '.git'))) {+ const result = await execGit(['remote', 'set-url', 'origin', patch.repoUrl.trim()], dest, { timeout: 10_000 })+ .catch((err) => ({ error: err }));+ if (result && result.error) {+ // Don't fail the patch outright — the user can manually delete+ // and re-add the ref to recover. But surface a warning so the+ // next check doesn't silently fetch from the old URL.+ console.warn(`⚠️ Failed to update origin remote for ref "${oldRef.name}": ${redactUrlCreds(result.error.message || '')}. Next check may use the previous URL — delete and re-add the ref to recover.`);+ }+ }+ }+ const TRIMMED_KEYS = new Set(['name', 'repoUrl', 'branch', 'notes']);+ const updated = { ...refs[idx] };+ for (const key of ['name', 'repoUrl', 'branch', 'notes', 'lastReviewedSha']) {+ if (patch[key] !== undefined) {+ updated[key] = (TRIMMED_KEYS.has(key) && typeof patch[key] === 'string')+ ? patch[key].trim()+ : patch[key];+ }+ }+ // Manual SHA pin counts as a review — record the time so "last reviewed"+ // doesn't silently lie. Skip the bump when the SHA is being CLEARED+ // (lastReviewedSha=null), otherwise "last checked" would look fresh+ // immediately after a reset.+ if (typeof patch.lastReviewedSha === 'string' && SHA_RE.test(patch.lastReviewedSha)) {+ updated.lastCheckedAt = new Date().toISOString();+ }+ const next = [...refs];+ next[idx] = updated;+ await updateApp(appId, { referenceRepos: next });+ return updated;+}++export async function deleteReferenceRepo(appId, refId) {+ const app = await getAppById(appId);+ if (!app) throw new ServerError(`App not found: ${appId}`, { status: 404, code: 'APP_NOT_FOUND' });+ const refs = Array.isArray(app.referenceRepos) ? app.referenceRepos : [];+ const next = refs.filter((r) => r.id !== refId);+ if (next.length === refs.length) {+ throw new ServerError(`Reference repo not found: ${refId}`, { status: 404, code: 'REFERENCE_REPO_NOT_FOUND' });+ }+ await updateApp(appId, { referenceRepos: next });+ // Clone is best-effort to leave on disk — user might re-add the ref by+ // URL and we'd save them the re-clone. UI offers a "purge clones" action+ // separately if disk pressure becomes a thing.+ return { ok: true };+}++/**+ * Fetch the ref, compute commits since lastReviewedSha, and return a+ * structured snapshot. Does NOT update lastReviewedSha — that happens+ * after the user / scheduled task has reviewed the proposal.+ */+export async function checkReferenceRepo(appId, refId) {+ const app = await getAppById(appId);+ if (!app) throw new ServerError(`App not found: ${appId}`, { status: 404, code: 'APP_NOT_FOUND' });+ const refs = Array.isArray(app.referenceRepos) ? app.referenceRepos : [];+ const ref = refs.find((r) => r.id === refId);+ if (!ref) throw new ServerError(`Reference repo not found: ${refId}`, { status: 404, code: 'REFERENCE_REPO_NOT_FOUND' });++ const checkedAt = new Date().toISOString();+ let snapshot;+ let nextStatus = 'ok';+ let nextError = null;+ let originalError = null;+ try {+ const { cwd, head, headRef } = await fetchHead(ref);+ const { commits, truncated, totalCommitCount } = await listCommits(cwd, ref.lastReviewedSha, headRef);+ snapshot = {+ head,+ headShort: SHORT_SHA(head),+ sinceSha: ref.lastReviewedSha,+ sinceShort: SHORT_SHA(ref.lastReviewedSha),+ // Visible-on-this-page count, capped by COMMIT_LIST_CAP.+ commitCount: commits.length,+ // True when more commits exist upstream than we returned. UI shows+ // "X of Y new" when this is set.+ truncated,+ // The full count (only available for incremental scans). null on+ // first scan since we don't pay for an extra rev-list there.+ totalCommitCount,+ commits,+ cwd,+ branch: ref.branch || 'main',+ };+ } catch (err) {+ nextStatus = 'error';+ nextError = err instanceof ServerError ? err.message : String(err.message || err);+ originalError = err;+ }+ // Persist status + lastCheckedAt regardless of success — UI surfaces the+ // error inline so the user can fix bad URL / branch.+ const next = refs.map((r) => (r.id === refId+ ? { ...r, status: nextStatus, lastError: nextError, lastCheckedAt: checkedAt }+ : r));+ await updateApp(appId, { referenceRepos: next });+ if (nextStatus === 'error') {+ // 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+ // unexpected errors.+ if (originalError instanceof ServerError) {+ throw new ServerError(originalError.message, {+ status: originalError.status,+ code: originalError.code || 'REFERENCE_REPO_CHECK_FAILED',+ });+ }+ throw new ServerError(nextError, { status: 500, code: 'REFERENCE_REPO_CHECK_FAILED' });+ }+ return snapshot;+}++/**+ * Mark a ref as reviewed up to the given SHA — called after a CoS+ * sub-agent finishes producing REFERENCE_REVIEW.md, or by the UI's+ * "mark as reviewed" button. SHA must match a real commit visible from+ * the ref's working tree (verified via `git cat-file -e <sha>^{commit}`+ * against the managed clone or the user-supplied local path).+ */+export async function markReferenceRepoReviewed(appId, refId, sha) {+ if (!SHA_RE.test(sha || '')) {+ throw new ServerError(`Invalid SHA: ${sha}`, { status: 400, code: 'REFERENCE_REPO_BAD_SHA' });+ }+ const app = await getAppById(appId);+ if (!app) throw new ServerError(`App not found: ${appId}`, { status: 404, code: 'APP_NOT_FOUND' });+ const refs = Array.isArray(app.referenceRepos) ? app.referenceRepos : [];+ const ref = refs.find((r) => r.id === refId);+ if (!ref) throw new ServerError(`Reference repo not found: ${refId}`, { status: 404, code: 'REFERENCE_REPO_NOT_FOUND' });+ // Make sure the clone exists, then verify the SHA resolves to a real+ // commit object. `cat-file -e <sha>^{commit}` exits non-zero (and our+ // execGit wrapper rejects) if the object is missing or not a commit.+ const cwd = await ensureClone(ref);+ const verify = await execGit(['cat-file', '-e', `${sha}^{commit}`], cwd, { timeout: 10_000 })+ .catch((err) => ({ error: err }));+ if (verify && verify.error) {+ throw new ServerError(+ `SHA ${sha.slice(0, 8)} not found in reference repo "${ref.name}"`,+ { status: 400, code: 'REFERENCE_REPO_SHA_NOT_FOUND' },+ );+ }+ return updateReferenceRepo(appId, refId, { lastReviewedSha: sha });+}++/**+ * Render a reference's commit list + notes into a Markdown chunk that+ * the reference-watch task injects into its agent prompt. Kept here+ * (not in the prompt template) so we can iterate the format without+ * touching cos.js.+ */+export function formatReferenceForPrompt(ref, snapshot) {+ const lines = [];+ lines.push(`## Reference: ${ref.name}`);+ // Redact userinfo before emitting into the prompt — even though we strip+ // credentials at ingest now, older entries persisted before that fix may+ // still carry tokens in apps.json.+ lines.push(`- Repo: ${redactUrlCreds(ref.repoUrl)}`);+ lines.push(`- Branch: ${ref.branch || 'main'}`);+ lines.push(`- Last reviewed: ${SHORT_SHA(ref.lastReviewedSha) || '(none — first scan)'}`);+ // When truncated, surface "showing X of Y" so the agent knows it's+ // looking at a head-end slice (most recent COMMIT_LIST_CAP commits).+ // Older commits are still in the upstream; user can pin a SHA forward+ // to drop them or run another check after reviewing this batch.+ const countLabel = snapshot.truncated+ ? `${snapshot.commitCount} of ${snapshot.totalCommitCount} new commits — older ones omitted; review these first then pin SHA forward`+ : `${snapshot.commitCount} new commits`;+ lines.push(`- Current head: ${snapshot.headShort} (${countLabel})`);+ if (ref.notes) {+ lines.push('');+ // User-provided context: how the app relates to this upstream — what+ // features the app maintains in its own code, what bugs to watch for,+ // what areas of upstream are out of scope. The agent uses this to+ // prioritize commits and decide what's worth reimplementing.+ lines.push('### Context (user-supplied — how this app relates to the repo)');+ lines.push(ref.notes);+ }+ if (snapshot.commits.length === 0) {+ lines.push('');+ lines.push('_No new commits since last review._');+ return lines.join('\n');+ }+ lines.push('');+ lines.push('### Commits to review');+ for (const c of snapshot.commits) {+ lines.push(`- \`${c.sha.slice(0, 8)}\` ${c.subject} _(by ${c.author}, ${c.date.slice(0, 10)})_`);+ }+ lines.push('');+ lines.push(`Source clone is at: \`${snapshot.cwd}\` — use \`git -C ${snapshot.cwd} show <sha>\` to read each commit's diff.`);+ return lines.join('\n');+}++// Exported for tests + reference-watch task type lookup.+export const __test = {+ REFERENCE_REPOS_ROOT,+ cloneDir,+ isLocalPath,+ workingDirectory,+ parseCommitLog,+};diff --git a/server/services/referenceRepos.test.js b/server/services/referenceRepos.test.jsnew file mode 100644index 0000000000..3ccd9c3473--- /dev/null+++ b/server/services/referenceRepos.test.js@@ -0,0 +1,337 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// ─── mocks (must precede the import under test) ──────────────────────────────++vi.mock('../lib/fileUtils.js', () => ({+ ensureDir: vi.fn(async () => {}),+ PATHS: { data: '/mock/data', root: '/mock/root' },+ readJSONFile: vi.fn(async () => ({ apps: {} })),+}));++vi.mock('../lib/uuid.js', () => ({+ v4: vi.fn(() => 'mock-uuid-1234'),+}));++// Stub apps.js so we can drive the per-app reference list without going+// through the full apps registry / file I/O.+const mockApps = new Map();+vi.mock('./apps.js', () => ({+ getAppById: vi.fn(async (id) => mockApps.get(id) || null),+ updateApp: vi.fn(async (id, patch) => {+ const cur = mockApps.get(id) || { id };+ const next = { ...cur, ...patch };+ mockApps.set(id, next);+ return next;+ }),+}));++// execGit is the one syscall every git operation funnels through. The mock+// returns canned stdout per call so each describe block can assert+// behavior without spawning real git. Tests pull `execGitMock` off the+// module to queue per-call results.+const execGitMock = vi.fn();+vi.mock('../lib/execGit.js', () => ({+ execGit: (args, cwd, opts) => {+ const result = execGitMock(args, cwd, opts);+ if (result?.error) return Promise.reject(result.error);+ return Promise.resolve({ stdout: result?.stdout ?? '', stderr: '', exitCode: 0 });+ },+}));++// existsSync is hit when the service decides whether the managed clone+// already exists. Default to false so first-touch goes through clone path;+// individual tests override.+const existsMock = vi.fn(() => false);+const statMock = vi.fn(() => ({ isDirectory: () => true }));+vi.mock('fs', () => ({+ existsSync: (p) => existsMock(p),+ statSync: (p) => statMock(p),+}));++// ─── module under test (after mocks) ─────────────────────────────────────────++let svc;+beforeEach(async () => {+ vi.resetModules();+ mockApps.clear();+ execGitMock.mockReset();+ existsMock.mockReset();+ existsMock.mockReturnValue(false);+ svc = await import('./referenceRepos.js');+});++const seedApp = (id, refs = []) => {+ mockApps.set(id, { id, name: 'TestApp', repoPath: '/mock/repo', referenceRepos: refs });+};++// ─── tests ───────────────────────────────────────────────────────────────────++describe('addReferenceRepo', () => {+ it('appends a ref with server-assigned id, default branch, and needs-clone status', async () => {+ seedApp('app-1');+ const ref = await svc.addReferenceRepo('app-1', {+ name: 'phosphene',+ repoUrl: 'https://github.com/mrbizarro/phosphene.git',+ notes: 'LTX-2 video gen pipeline',+ });+ expect(ref).toMatchObject({+ id: 'mock-uuid-1234',+ name: 'phosphene',+ repoUrl: 'https://github.com/mrbizarro/phosphene.git',+ branch: 'main',+ notes: 'LTX-2 video gen pipeline',+ lastReviewedSha: null,+ lastCheckedAt: null,+ status: 'needs-clone',+ });+ const stored = mockApps.get('app-1');+ expect(stored.referenceRepos).toHaveLength(1);+ });++ it('preserves existing refs when appending', async () => {+ seedApp('app-1', [{ id: 'r1', name: 'A', repoUrl: 'x', branch: 'main', status: 'ok' }]);+ await svc.addReferenceRepo('app-1', { name: 'B', repoUrl: 'y' });+ expect(mockApps.get('app-1').referenceRepos.map((r) => r.name)).toEqual(['A', 'B']);+ });++ it('throws 404 when the app does not exist', async () => {+ await expect(svc.addReferenceRepo('missing', { name: 'x', repoUrl: 'y' }))+ .rejects.toThrow(/App not found/);+ });+});++describe('updateReferenceRepo', () => {+ it('updates allowed fields only and bumps lastCheckedAt when SHA is pinned manually', async () => {+ seedApp('app-1', [{ id: 'r1', name: 'old', repoUrl: 'u', branch: 'main', notes: '', lastReviewedSha: null, status: 'ok' }]);+ const updated = await svc.updateReferenceRepo('app-1', 'r1', {+ name: 'new-name',+ lastReviewedSha: 'a'.repeat(40),+ });+ expect(updated.name).toBe('new-name');+ expect(updated.lastReviewedSha).toBe('a'.repeat(40));+ expect(updated.lastCheckedAt).toBeTruthy(); // bumped because SHA was pinned+ });++ it('silently drops unknown fields (allow-list of writable keys)', async () => {+ seedApp('app-1', [{ id: 'r1', name: 'a', repoUrl: 'u', status: 'ok' }]);+ const updated = await svc.updateReferenceRepo('app-1', 'r1', { name: 'b', status: 'error' });+ expect(updated.name).toBe('b');+ expect(updated.status).toBe('ok'); // status not in allowed-update list+ });++ it('throws 404 for unknown ref id', async () => {+ seedApp('app-1', [{ id: 'r1', name: 'a', repoUrl: 'u' }]);+ await expect(svc.updateReferenceRepo('app-1', 'r99', { name: 'b' }))+ .rejects.toThrow(/Reference repo not found/);+ });++ it('trims string fields (name/repoUrl/branch/notes) just like addReferenceRepo', async () => {+ // Without trimming, " main " as a branch causes confusing git failures+ // and " https://github.com/... " in repoUrl would mismatch addRef shape.+ seedApp('app-1', [{ id: 'r1', name: 'old', repoUrl: 'u', branch: 'main', notes: '', status: 'ok' }]);+ const updated = await svc.updateReferenceRepo('app-1', 'r1', {+ name: ' spaced ',+ branch: ' develop ',+ repoUrl: ' https://x/y.git ',+ notes: ' some notes ',+ });+ expect(updated.name).toBe('spaced');+ expect(updated.branch).toBe('develop');+ expect(updated.repoUrl).toBe('https://x/y.git');+ expect(updated.notes).toBe('some notes');+ });++ it('does not bump lastCheckedAt when lastReviewedSha is cleared to null', async () => {+ // Clearing the SHA pin (lastReviewedSha=null) is a "reset", not a "review" —+ // bumping lastCheckedAt would make the UI show a fresh-looking timestamp+ // immediately after a reset, which is misleading.+ seedApp('app-1', [{ id: 'r1', name: 'p', repoUrl: 'u', branch: 'main', lastReviewedSha: 'a'.repeat(40), lastCheckedAt: '2026-01-01T00:00:00Z', status: 'ok' }]);+ const updated = await svc.updateReferenceRepo('app-1', 'r1', { lastReviewedSha: null });+ expect(updated.lastReviewedSha).toBeNull();+ expect(updated.lastCheckedAt).toBe('2026-01-01T00:00:00Z'); // unchanged+ });+});++describe('deleteReferenceRepo', () => {+ it('removes the ref from the app and leaves siblings intact', async () => {+ seedApp('app-1', [+ { id: 'r1', name: 'a', repoUrl: 'u' },+ { id: 'r2', name: 'b', repoUrl: 'u' },+ ]);+ await svc.deleteReferenceRepo('app-1', 'r1');+ expect(mockApps.get('app-1').referenceRepos.map((r) => r.id)).toEqual(['r2']);+ });++ it('throws 404 when the ref id is unknown', async () => {+ seedApp('app-1', [{ id: 'r1', name: 'a', repoUrl: 'u' }]);+ await expect(svc.deleteReferenceRepo('app-1', 'missing'))+ .rejects.toThrow(/Reference repo not found/);+ });+});++describe('checkReferenceRepo', () => {+ // Wire execGitMock as a programmable sequence of git invocations.+ // For URL-based refs the order is: clone (when missing), fetch, rev-parse,+ // log. For local-path refs: rev-parse, log (no clone, no fetch).+ it('clones on first run, fetches, computes commits, persists status=ok', async () => {+ seedApp('app-1', [{ id: 'r1', name: 'phosphene', repoUrl: 'https://github.com/x/y.git', branch: 'main', lastReviewedSha: null, status: 'needs-clone' }]);+ existsMock.mockImplementation(() => false); // clone doesn't exist yet+ execGitMock+ .mockReturnValueOnce({ stdout: '' }) // git clone+ .mockReturnValueOnce({ stdout: '' }) // git fetch+ .mockReturnValueOnce({ stdout: 'a'.repeat(40) }) // git rev-parse+ .mockReturnValueOnce({ stdout: ['a'.repeat(40), 'Alice', 'a@x', '2026-05-01T00:00:00Z', 'first commit'].join('\t') }); // git log++ const snapshot = await svc.checkReferenceRepo('app-1', 'r1');+ expect(snapshot.head).toBe('a'.repeat(40));+ expect(snapshot.commitCount).toBe(1);+ expect(snapshot.commits[0].subject).toBe('first commit');++ // The first execGitMock call should have been `git clone <url> <id>`+ expect(execGitMock.mock.calls[0][0]).toEqual(['clone', 'https://github.com/x/y.git', 'r1']);+ // Persisted status must reflect the successful run.+ const persisted = mockApps.get('app-1').referenceRepos[0];+ expect(persisted.status).toBe('ok');+ expect(persisted.lastError).toBeNull();+ expect(persisted.lastCheckedAt).toBeTruthy();+ });++ it('skips clone when .git already exists', async () => {+ seedApp('app-1', [{ id: 'r1', name: 'p', repoUrl: 'https://github.com/x/y.git', branch: 'main', lastReviewedSha: null }]);+ existsMock.mockImplementation((p) => String(p).endsWith('/.git'));+ execGitMock+ .mockReturnValueOnce({ stdout: '' }) // git fetch+ .mockReturnValueOnce({ stdout: 'b'.repeat(40) }) // git rev-parse+ .mockReturnValueOnce({ stdout: '' }); // git log (empty)++ const snapshot = await svc.checkReferenceRepo('app-1', 'r1');+ expect(snapshot.commitCount).toBe(0);+ // First git call should be fetch, not clone.+ expect(execGitMock.mock.calls[0][0][0]).toBe('fetch');+ });++ 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'));+ execGitMock+ .mockReturnValueOnce({ stdout: '' }) // fetch+ .mockReturnValueOnce({ stdout: 'd'.repeat(40) }) // rev-parse+ .mockReturnValueOnce({ stdout: '' }); // log++ await svc.checkReferenceRepo('app-1', 'r1');+ // After rev-parse, listCommits runs `rev-list --count <range>` before+ // `log -n N <range>`. Both end with the same range arg, so checking+ // the last positional in either call confirms the SHA gets plumbed+ // through to git as a strict <sinceSha>..<headRef> bound.+ const rangeCall = execGitMock.mock.calls[2][0];+ const range = rangeCall[rangeCall.length - 1];+ expect(range).toBe(`${'c'.repeat(40)}..origin/main`);+ });++ it('persists status=error and re-throws on git failure', async () => {+ seedApp('app-1', [{ id: 'r1', name: 'p', repoUrl: 'https://github.com/x/y.git', branch: 'main', lastReviewedSha: null }]);+ existsMock.mockImplementation((p) => String(p).endsWith('/.git'));+ execGitMock.mockReturnValueOnce({ error: new Error('fatal: bad branch') });++ await expect(svc.checkReferenceRepo('app-1', 'r1')).rejects.toThrow(/fatal: bad branch/);+ const persisted = mockApps.get('app-1').referenceRepos[0];+ expect(persisted.status).toBe('error');+ expect(persisted.lastError).toMatch(/bad branch/);+ });++ 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+ execGitMock+ .mockReturnValueOnce({ stdout: 'e'.repeat(40) }) // rev-parse main+ .mockReturnValueOnce({ stdout: '' }); // log++ const snapshot = await svc.checkReferenceRepo('app-1', 'r1');+ expect(snapshot.head).toBe('e'.repeat(40));+ // No clone, no fetch — first call is rev-parse on the user path+ expect(execGitMock.mock.calls[0][0]).toEqual(['rev-parse', 'main']);+ expect(execGitMock.mock.calls[0][1]).toBe('/Users/me/phosphene');+ });+});++describe('isLocalPath', () => {+ it('classifies https / ssh-scheme / scp-style URLs as remote', () => {+ const { isLocalPath } = svc.__test;+ expect(isLocalPath('https://github.com/owner/repo.git')).toBe(false);+ expect(isLocalPath('ssh://[email protected]/owner/repo.git')).toBe(false);+ expect(isLocalPath('[email protected]:owner/repo.git')).toBe(false);+ // scp-style with non-github user@host shape — must still be remote+ expect(isLocalPath('[email protected]:owner/repo.git')).toBe(false);+ // scp-style with NO user (`host:path`) — git accepts these too+ expect(isLocalPath('github.com:owner/repo.git')).toBe(false);+ });++ it('classifies absolute paths and ~-paths as local', () => {+ const { isLocalPath } = svc.__test;+ expect(isLocalPath('/Users/me/phosphene')).toBe(true);+ expect(isLocalPath('~/phosphene')).toBe(true);+ expect(isLocalPath('./phosphene')).toBe(true);+ // Windows drive paths must NOT be treated as scp-style remotes —+ // single-char host segment + path starting with `\` or `/`.+ expect(isLocalPath('C:\\Users\\me\\phosphene')).toBe(true);+ expect(isLocalPath('C:/Users/me/phosphene')).toBe(true);+ });+});++describe('formatReferenceForPrompt', () => {+ it('renders a Markdown chunk with notes + commit list', () => {+ const ref = { id: 'r1', name: 'phosphene', repoUrl: 'https://github.com/x/y.git', branch: 'main', lastReviewedSha: null, notes: 'video gen' };+ const snapshot = {+ head: 'f'.repeat(40),+ headShort: 'ffffffff',+ commitCount: 1,+ commits: [{ sha: 'a'.repeat(40), subject: 'add new feature', author: 'Alice', date: '2026-05-01T00:00:00Z' }],+ cwd: '/mock/clone',+ branch: 'main',+ };+ const out = svc.formatReferenceForPrompt(ref, snapshot);+ expect(out).toContain('## Reference: phosphene');+ expect(out).toContain('Context (user-supplied');+ expect(out).toContain('video gen');+ expect(out).toContain('aaaaaaaa');+ expect(out).toContain('add new feature');+ });++ it('shows "no new commits" line when commitCount is 0', () => {+ const ref = { id: 'r1', name: 'phosphene', repoUrl: 'https://x', branch: 'main', notes: '' };+ const snapshot = { head: 'f'.repeat(40), headShort: 'ffffffff', commitCount: 0, commits: [], cwd: '/x', branch: 'main' };+ const out = svc.formatReferenceForPrompt(ref, snapshot);+ expect(out).toContain('No new commits since last review');+ });+});++describe('markReferenceRepoReviewed', () => {+ it('rejects malformed SHA before touching state', async () => {+ seedApp('app-1', [{ id: 'r1', name: 'p', repoUrl: 'u', branch: 'main' }]);+ await expect(svc.markReferenceRepoReviewed('app-1', 'r1', 'too-short')).rejects.toThrow(/Invalid SHA/);+ });++ it('persists lastReviewedSha + lastCheckedAt on a valid SHA verified in the clone', async () => {+ // Local-path ref so ensureClone() is a no-op other than the existsSync+ // check; cat-file -e succeeds → SHA is treated as verified.+ 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');+ execGitMock.mockReturnValueOnce({ stdout: '' }); // git cat-file -e <sha>^{commit}+ const out = await svc.markReferenceRepoReviewed('app-1', 'r1', 'a'.repeat(40));+ expect(out.lastReviewedSha).toBe('a'.repeat(40));+ expect(out.lastCheckedAt).toBeTruthy();+ // Verify the actual git call shape so a future refactor can't silently+ // drop SHA verification.+ expect(execGitMock.mock.calls[0][0]).toEqual(['cat-file', '-e', `${'a'.repeat(40)}^{commit}`]);+ });++ it('rejects when the SHA does not resolve to a commit in the clone', 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');+ execGitMock.mockReturnValueOnce({ error: new Error('fatal: Not a valid object name') });+ await expect(svc.markReferenceRepoReviewed('app-1', 'r1', 'a'.repeat(40)))+ .rejects.toThrow(/not found in reference repo/);+ // SHA must NOT have been persisted on a failed verification.+ expect(mockApps.get('app-1').referenceRepos[0].lastReviewedSha).toBeNull();+ });+});diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.jsindex a5242f6185..3ff8ebcca2 100644--- a/server/services/taskSchedule.js+++ b/server/services/taskSchedule.js@@ -897,7 +897,128 @@ Repository: {repoPath}## Review Checklist-{reviewChecklist}`+{reviewChecklist}`,++ 'reference-watch': `[Improvement: {appName}] Reference Repo Review++You are reviewing upstream commits from one or more reference repositories that+{appName} watches for clean-room reimplementation — meaning {appName} maintains+its OWN implementation of similar features and may benefit from re-building+the bug fixes or new capabilities those upstream commits introduce. Your job+is to PROPOSE which commits are worth re-implementing, NOT to copy upstream+code. Read-only mode — do NOT modify {appName}'s source. **Never paste+upstream code verbatim into recommendations**: describe what to change in our+own architecture, naming the files and functions in {appName} that need+edits. The user owns the actual implementation.++Repository: {repoPath}++## References++{referenceData}++## What to do++For each reference above:++1. For every commit in the "Commits to review" list, read its diff via+ \`git -C <source clone path> show <sha>\` (the path is in the reference's+ block above). For commits with many files, focus on diffs that match the+ user-supplied "Context" block — that's the load-bearing intersection+ between this app and upstream, and the user has flagged what matters.++2. **SECURITY SCREEN — do this BEFORE deciding whether the commit is worth+ adopting.** Reference repos are third-party code we don't control; an+ upstream maintainer's account compromise, a malicious PR merge, or a+ typo-squatting branch name could ship malware or new vulnerabilities+ into a commit that *looks* useful. For every commit, scan the diff for:++ - **Malware indicators**: obfuscated/minified strings in source files,+ base64/hex blobs being decoded then \`eval\`'d / \`exec\`'d / piped to+ a shell, network calls to non-obvious hosts (anything that isn't the+ upstream's own infra or a well-known package registry), exfil of+ env vars / \`~/.ssh/\` / \`~/.aws/\` / browser cookie stores, new+ post-install / pre-publish hooks, dynamic-import patterns that+ fetch-then-execute remote code, suspicious file writes outside the+ repo root.+ - **New vulnerabilities introduced**: SQL/NoSQL/command injection on+ newly-added user-input paths, path traversal in newly-added file+ I/O, prototype pollution via unvalidated object merges, unsafe+ deserialization (eval, vm, pickle, Marshal, YAML.load without+ SafeLoader), deactivated security headers / CSP relaxations,+ authentication or authorization checks removed or weakened, secrets+ committed (tokens, keys, .env contents).+ - **Suspicious dependency changes**: newly added deps from publishers+ with no track record, dep-version downgrades to known-vulnerable+ ranges, lockfile-only changes that pull a different version than+ the manifest claims.++ If a commit shows ANY of these, classify it as **Skip — security+ concern** in REFERENCE_REVIEW.md (see template below) with a one-line+ note describing exactly what tripped the screen. Do NOT recommend+ adoption even if the surface feature looks attractive.++3. Decide whether the change is worth REIMPLEMENTING in {appName}. Use these+ criteria, in priority order:+ - Does it fix a bug we'd hit too? (high priority — re-implement the fix+ in our equivalent code path)+ - Does it expose a capability we artificially restrict? (e.g. our wrapper+ around a shared library uses a constrained subset of an API the upstream+ just opened up — we can do the same in our wrapper)+ - Does it improve performance / correctness on a code path we share?+ - Is it a docs / install / packaging fix specific to upstream's distribution+ model? (skip — those rarely apply)++4. Write a single \`REFERENCE_REVIEW.md\` at the root of {repoPath} with this+ structure:++ \`\`\`markdown+ # Reference Review — <today's date>++ ## Summary++ <1-3 sentences: what's the gist across all refs? Mention if any+ commits were flagged as a security concern.>++ ## Skip — security concern++ <commits flagged by the security screen. List FIRST so the user sees+ these before any "adopt" recommendations. For each:>+ - **<short title>** — \`<sha>\` from <ref name>+ - What tripped the screen: <one sentence — malware indicator,+ new vuln, or suspicious dep change>+ - Detail: <specific file:line(s) + the pattern that concerned you>++ ## Adopt — high value++ For each commit you'd recommend pulling in (security-clean only):+ - **<short title>** — \`<sha>\` from <ref name>+ - Why it matters for {appName}: <1-2 sentences tied to our notes>+ - What to change: <specific files + functions in {appName}, e.g.+ server/services/foo.js buildArgs() — accept new arg, plumb to+ subprocess. Describe the BEHAVIOR to add, not upstream's exact+ code — clean-room reimplementation.>+ - Estimated scope: <small / medium / large>++ ## Maybe — needs human call++ <commits where the value is real but the fit is unclear; what to ask>++ ## Skip — not for us++ <commits we should explicitly NOT adopt + one-line reason each>++ ## Per-reference SHA pointers++ - <ref name>: latest reviewed in this report = \`<head sha>\`+ \`\`\`++5. Do NOT create branches, commits, PRs, or any code edits. The user reviews+ REFERENCE_REVIEW.md and decides what to implement.++6. Once REFERENCE_REVIEW.md is written, your final assistant message must be a+ 2-3 sentence summary of how many commits you reviewed, how many security+ flags you raised, and how many you marked Adopt vs. Maybe vs. Skip.`};// Prompt versions — bump when a default prompt changes so existing instances auto-upgrade.@@ -906,7 +1027,8 @@ const PROMPT_VERSIONS = {'feature-ideas': 6, // v6: remove hardcoded worktree language (worktree context injected by agentPromptBuilder)'pr-reviewer': 3, // v3: multi-stage pipeline (security scan → code review + merge)'code-reviewer-a': 1, // v1: 2-stage pipeline (codebase review → triage & implement)- 'code-reviewer-b': 1 // v1: 2-stage pipeline (codebase review → triage & implement)+ 'code-reviewer-b': 1, // v1: 2-stage pipeline (codebase review → triage & implement)+ 'reference-watch': 1 // v1: clean-room reimplementation framing + mandatory security screen (malware / new vuln / suspicious deps) before adoption decisions};// Known previous default prompts for legacy migration.@@ -1280,7 +1402,11 @@ export const SELF_IMPROVEMENT_TASK_TYPES = ['accessibility', 'branch-cleanup', 'console-errors', 'dependency-updates', 'documentation','ui-bugs', 'mobile-responsive', 'feature-ideas', 'error-handling','typing', 'release-check', 'pr-reviewer', 'code-reviewer-a', 'code-reviewer-b',- 'jira-sprint-manager', 'jira-status-report', 'do-replan'+ 'jira-sprint-manager', 'jira-status-report', 'do-replan',+ // Watches `referenceRepos` configured on the app — fetches each upstream+ // repo, finds commits since lastReviewedSha, and writes a propose-only+ // REFERENCE_REVIEW.md with adoption recommendations to the app's repo.+ 'reference-watch'];// Shared config for code-reviewer-a and code-reviewer-b (two instances for independent provider/model configuration)@@ -1307,7 +1433,11 @@ const DEFAULT_TASK_INTERVALS = {'code-reviewer-b': { ...CODE_REVIEWER_INTERVAL },'jira-sprint-manager': { type: INTERVAL_TYPES.DAILY, enabled: false, weekdaysOnly: true, providerId: null, model: null, prompt: null, taskMetadata: { useWorktree: true, openPR: true, simplify: true } },'jira-status-report': { type: INTERVAL_TYPES.WEEKLY, enabled: false, weekdaysOnly: true, providerId: null, model: null, prompt: null, taskMetadata: { readOnly: true } },- 'do-replan': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { useWorktree: true, openPR: true } }+ 'do-replan': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { useWorktree: true, openPR: true } },+ // Read-only by default — the agent's job is to propose, not implement.+ // Worktree off because the task body itself reads from data/cos/reference-repos+ // (managed clones the user can't accidentally clobber).+ 'reference-watch': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { readOnly: true } }};/**diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.jsindex e04ac3aac3..a52d76f2aa 100644--- a/server/services/videoGen/local.js+++ b/server/services/videoGen/local.js@@ -87,7 +87,7 @@ export const saveHistory = (h) => atomicWrite(HISTORY_FILE, h);// The helper lives in the ltx-2-mlx venv (so its `import ltx_pipelines_mlx`// resolves) but the script file lives in the PortOS repo so updates ship// with PortOS releases instead of the user's HF cache.-const buildLtx2Args = ({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, guidance, seed, sourceImagePath, lastImagePath, extendFromVideoPath, audioFilePath, mode, imageStrength, disableAudio, outputPath, textEncoderRepo }) => {+const buildLtx2Args = ({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, guidance, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, mode, imageStrength, disableAudio, outputPath, textEncoderRepo }) => {if (!existsSync(LTX2_VENV_PYTHON)) {throw new ServerError(`ltx-2-mlx venv not found at ${LTX2_VENV_PYTHON}. Run \`INSTALL_LTX2=1 bash scripts/setup-image-video.sh\` to install.`,@@ -102,15 +102,22 @@ const buildLtx2Args = ({ model, prompt, negativePrompt, width, height, numFrames// When mode is omitted, infer i2v from a present sourceImagePath — matches// the route schema's documented "absence falls back to inferring" behavior.const wantsNativeExtend = mode === 'extend' && !!extendFromVideoPath;+ const hasMultiKeyframes = Array.isArray(keyframes) && keyframes.length >= 2;+ // When `mode` is omitted but multi-keyframes are supplied, infer fflf so a+ // direct caller (test, script) doesn't get a silent text-only render with+ // their keyframes dropped on the floor. The route handler always sets+ // mode='fflf' when keyframes are present, but defense-in-depth here covers+ // callers that bypass the route (e.g. Writers Room batch dispatch).const helperMode = mode === 'fflf' ? 'fflf': mode === 'a2v' ? 'a2v': wantsNativeExtend ? 'extend': mode === 'image' || mode === 'extend' ? 'image'+ : (!mode && hasMultiKeyframes) ? 'fflf': (!mode && sourceImagePath) ? 'image': 'text';- if (helperMode === 'fflf' && (!sourceImagePath || !lastImagePath)) {+ if (helperMode === 'fflf' && !hasMultiKeyframes && (!sourceImagePath || !lastImagePath)) {throw new ServerError(- 'FFLF mode on the ltx2 runtime requires BOTH a start image (sourceImagePath) and an end image (lastImagePath).',+ 'FFLF mode on the ltx2 runtime requires either a keyframes array (length >= 2) or BOTH a start image and an end image.',{ status: 400, code: 'LTX2_FFLF_MISSING_KEYFRAMES' },);}@@ -151,6 +158,34 @@ const buildLtx2Args = ({ model, prompt, negativePrompt, width, height, numFramesconst safeRaw = Math.floor(pixelBudget / (Number(width) * Number(height)));const safeLatent = Math.max(1, Math.floor((safeRaw - 1) / 8));const safeFrames = safeLatent * 8 + 1;+ // Multi-keyframe renders pin specific pixel-frame indices — clamping+ // numFrames below `max(keyframe.index)` would either drop a keyframe+ // or hand the Python helper an out-of-range index that hard-fails+ // mid-render. Surface a 400 with a clear "raise FFLF_LTX2_PIXEL_BUDGET+ // or lower resolution" message instead of silently clamping.+ if (hasMultiKeyframes) {+ // Reject non-numeric indices upfront — Math.max(..., NaN) is NaN,+ // which would silently bypass the safeFrames guard below and let+ // the Python helper hard-fail with an opaque error mid-render.+ const indices = keyframes.map((kf, i) => {+ const n = Number(kf.index);+ if (!Number.isFinite(n)) {+ throw new ServerError(+ `keyframes[${i}].index is not a finite number: ${kf.index}`,+ { status: 400, code: 'LTX2_KEYFRAME_INVALID' },+ );+ }+ return n;+ });+ const maxKfIndex = Math.max(...indices);+ if (maxKfIndex > safeFrames - 1) {+ throw new ServerError(+ `Multi-keyframe render exceeds the FFLF/ltx2 pixel budget: ${width}×${height}×${numFrames} > ${pixelBudget} pixel-frames, but max keyframe index is ${maxKfIndex} (would clamp to ${safeFrames} frames). Lower resolution or raise FFLF_LTX2_PIXEL_BUDGET.`,+ { status: 400, code: 'LTX2_FFLF_PIXEL_BUDGET_EXCEEDED' },+ );+ }+ // Otherwise the keyframes still fit — clamp is safe.+ }console.log(`⚠️ FFLF/ltx2 numFrames clamped ${numFrames} → ${safeFrames} to fit pixel budget ${pixelBudget} (export FFLF_LTX2_PIXEL_BUDGET=<n> to raise)`);numFrames = safeFrames;}@@ -175,8 +210,17 @@ const buildLtx2Args = ({ model, prompt, negativePrompt, width, height, numFramesif (disableAudio) args.push('--no-audio');if (helperMode === 'image' && sourceImagePath) args.push('--image', sourceImagePath);if (helperMode === 'fflf') {- args.push('--image', sourceImagePath);- args.push('--last-image', lastImagePath);+ if (hasMultiKeyframes) {+ // Emit the helper's JSON contract — the path field is the resized image+ // on disk (already cropped to (width, height) by generateVideo). The+ // helper reads paths verbatim, so any mismatch here is unrecoverable.+ args.push('--keyframes-json', JSON.stringify(+ keyframes.map((kf) => ({ path: kf.path, index: kf.index })),+ ));+ } else {+ args.push('--image', sourceImagePath);+ args.push('--last-image', lastImagePath);+ }}if (helperMode === 'extend') {args.push('--extend-from-video', extendFromVideoPath);@@ -198,12 +242,18 @@ const buildLtx2Args = ({ model, prompt, negativePrompt, width, height, numFramesreturn { bin: LTX2_VENV_PYTHON, args };};-const buildArgs = ({ pythonPath, modelId, model, prompt, negativePrompt, width, height, numFrames, fps, steps, guidance, seed, tiling, disableAudio, sourceImagePath, lastImagePath, extendFromVideoPath, audioFilePath, mode, imageStrength, textEncoderRepo, outputPath }) => {+const buildArgs = ({ pythonPath, modelId, model, prompt, negativePrompt, width, height, numFrames, fps, steps, guidance, seed, tiling, disableAudio, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, mode, imageStrength, textEncoderRepo, outputPath }) => {// Route to the dgrauet/ltx-2-mlx helper when the model declares the new// runtime. Existing notapalindrome models default to runtime: 'mlx_video'// (or undefined in legacy registries — see backfillRuntime in mediaModels.js).if (model.runtime === 'ltx2') {- return buildLtx2Args({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, guidance, seed, sourceImagePath, lastImagePath, extendFromVideoPath, audioFilePath, mode, imageStrength, disableAudio, outputPath, textEncoderRepo });+ return buildLtx2Args({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, guidance, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, mode, imageStrength, disableAudio, outputPath, textEncoderRepo });+ }+ if (Array.isArray(keyframes) && keyframes.length >= 2) {+ throw new ServerError(+ 'Multi-keyframe mode (keyframes array) is only supported on the ltx2 runtime. Pick a model with runtime: "ltx2" in data/media-models.json.',+ { status: 400, code: 'KEYFRAMES_REQUIRE_LTX2' },+ );}if (mode === 'a2v') {throw new ServerError(@@ -263,7 +313,13 @@ const buildArgs = ({ pythonPath, modelId, model, prompt, negativePrompt, width,return { bin: pythonPath, args };};-export async function generateVideo({ pythonPath, prompt, negativePrompt = '', modelId = defaultVideoModelId(), width = 768, height = 512, numFrames = 121, fps = 24, steps, guidanceScale, seed, tiling = 'auto', disableAudio = false, sourceImagePath = null, uploadedTempPath = null, uploadedTempPaths = [], lastImagePath = null, extendFromVideoPath = null, audioFilePath = null, mode = null, imageStrength = null, hidden = false, jobId: providedJobId = null }) {+// Default frame count for LTX renders, matching the 8k+1 latent-boundary+// the model wants. Exported so the route layer can validate keyframe+// indices against the same effective number of frames the service will+// use (avoiding drift between two hardcoded constants).+export const DEFAULT_NUM_FRAMES = 121;++export async function generateVideo({ pythonPath, prompt, negativePrompt = '', modelId = defaultVideoModelId(), width = 768, height = 512, numFrames = DEFAULT_NUM_FRAMES, fps = 24, steps, guidanceScale, seed, tiling = 'auto', disableAudio = false, sourceImagePath = null, uploadedTempPath = null, uploadedTempPaths = [], lastImagePath = null, keyframes = null, extendFromVideoPath = null, audioFilePath = null, mode = null, imageStrength = null, hidden = false, jobId: providedJobId = null }) {uploadedTempPaths = Array.isArray(uploadedTempPaths) ? uploadedTempPaths : [];if (!pythonPath) throw new ServerError('Python path not configured — set it in Settings > Image Gen', { status: 400, code: 'VIDEO_GEN_NOT_CONFIGURED' });if (!prompt?.trim()) throw new ServerError('Prompt is required', { status: 400, code: 'VALIDATION_ERROR' });@@ -314,7 +370,19 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m// status, but the diffusers pipeline only reads --image — the script// never opens the last-frame file, so no resize is needed there either.const lastImageWillBeUsed = !!lastImagePath && !IS_WIN && mode === 'fflf' && !sourceImagePath;- const ffmpeg = (sourceImagePath || lastImageWillBeUsed) ? await findFfmpeg() : null;+ // A non-null `keyframes` that ISN'T a length-≥2 array is malformed —+ // fail fast instead of silently dropping it (which would produce an+ // unexpected text/i2v render with the user's anchors ignored). The+ // route guarantees the array shape, but non-route callers (tests,+ // persisted queue replays) could pass a stray scalar/empty array.+ if (keyframes != null && !(Array.isArray(keyframes) && keyframes.length >= 2)) {+ throw new ServerError(+ `keyframes must be null OR an array of length >= 2; got ${Array.isArray(keyframes) ? `array(length=${keyframes.length})` : typeof keyframes}`,+ { status: 400, code: 'KEYFRAME_INVALID_SHAPE' },+ );+ }+ const hasMultiKeyframes = Array.isArray(keyframes) && keyframes.length >= 2;+ const ffmpeg = (sourceImagePath || lastImageWillBeUsed || hasMultiKeyframes) ? await findFfmpeg() : null;const resizeImage = async (srcPath, tag) => {if (!srcPath || !ffmpeg) return { resolved: srcPath, tempPath: null };const resizedPath = join(tmpdir(), `resized-${tag}-${jobId}.png`);@@ -334,6 +402,42 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', mconst { resolved: resolvedLastImage, tempPath: resizedLastTempPath } = lastImageWillBeUsed? await resizeImage(lastImagePath, 'last'): { resolved: lastImagePath, tempPath: null };+ // Resize each multi-keyframe image to the target resolution (the helper+ // requires exact W×H, same as i2v). Indices pass through unchanged.+ // Each ffmpeg subprocess is independent — fan out so 8 keyframes don't+ // serialize behind 7 unrelated ffmpeg startups.+ const resizedKeyframeTempPaths = [];+ let resolvedKeyframes = null;+ if (hasMultiKeyframes) {+ // The route validates shape, but a non-route caller (test, persisted+ // queue replay, future internal API) could pass malformed entries.+ // Fail fast with a clear error instead of letting `undefined` paths+ // flow into ffmpeg or the Python helper, where the failure is opaque.+ keyframes.forEach((kf, i) => {+ if (!kf || typeof kf !== 'object') {+ throw new ServerError(`keyframes[${i}] must be an object: got ${typeof kf}`, { status: 400, code: 'KEYFRAME_INVALID_SHAPE' });+ }+ if (typeof kf.path !== 'string' || !kf.path) {+ throw new ServerError(`keyframes[${i}].path must be a non-empty string`, { status: 400, code: 'KEYFRAME_INVALID_SHAPE' });+ }+ // The Python helper enforces `index` is an int; a float or numeric+ // string here would crash mid-render. Coerce + verify integerness+ // up-front so non-route callers (tests, persisted queue replays)+ // get a clear 400 instead of a Python traceback.+ const n = Number(kf.index);+ if (!Number.isInteger(n)) {+ throw new ServerError(`keyframes[${i}].index must be an integer: got ${kf.index}`, { status: 400, code: 'KEYFRAME_INVALID_SHAPE' });+ }+ });+ const results = await Promise.all(keyframes.map((kf, i) => resizeImage(kf.path, `kf${i}`)));+ resolvedKeyframes = results.map((r, i) => {+ if (r.tempPath) resizedKeyframeTempPaths.push(r.tempPath);+ // Normalize index to a real Number so the JSON we hand to the+ // Python helper is unambiguous (no '5' string sneaking through+ // from a multipart form).+ return { path: r.resolved, index: Number(keyframes[i].index) };+ });+ }const meta = {id: jobId,@@ -347,13 +451,41 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', mfps: parsedFps,filename,createdAt: new Date().toISOString(),- mode: mode || (sourceImagePath ? 'image' : 'text'),+ // History mode reflects the EFFECTIVE mode — buildLtx2Args infers fflf+ // from `keyframes` even when caller omitted `mode`, so without this the+ // history entry would say 'text' for a multi-keyframe render.+ mode: mode || (hasMultiKeyframes ? 'fflf' : sourceImagePath ? 'image' : 'text'),...(hidden ? { hidden: true } : {}),};const job = { ...meta, clients: [], status: 'running' };jobs.set(jobId, job);- const { bin, args } = buildArgs({ pythonPath, modelId, model, prompt, negativePrompt, width: w, height: h, numFrames: parsedNumFrames, fps: parsedFps, steps: actualSteps, guidance: actualGuidance, seed: actualSeed, tiling, disableAudio, sourceImagePath: resolvedSourceImage, lastImagePath: resolvedLastImage, extendFromVideoPath, audioFilePath, mode, imageStrength: actualImageStrength, textEncoderRepo: actualTextEncoderRepo, outputPath });+ // buildArgs now throws synchronously on multi-keyframe pixel-budget+ // overflow and a few other validation paths — without this guard the+ // job would stay "running" forever in the jobs map and the resized+ // temp files would leak (the spawn close-handler that normally cleans+ // them up never runs because we never spawned). Mirror the cleanup+ // logic of the spawn-error handler so failure modes converge.+ let bin, args;+ try {+ ({ bin, args } = buildArgs({ pythonPath, modelId, model, prompt, negativePrompt, width: w, height: h, numFrames: parsedNumFrames, fps: parsedFps, steps: actualSteps, guidance: actualGuidance, seed: actualSeed, tiling, disableAudio, sourceImagePath: resolvedSourceImage, lastImagePath: resolvedLastImage, keyframes: resolvedKeyframes, extendFromVideoPath, audioFilePath, mode, imageStrength: actualImageStrength, textEncoderRepo: actualTextEncoderRepo, outputPath }));+ } catch (err) {+ job.status = 'error';+ const reason = err.message || 'Failed to build video gen args';+ console.log(`❌ Video generation buildArgs error [${jobId.slice(0, 8)}]: ${reason}`);+ broadcastSse(job, { type: 'error', error: reason });+ videoGenEvents.emit('failed', { generationId: jobId, error: reason });+ if (resizedSrcTempPath) unlink(resizedSrcTempPath).catch(() => {});+ if (resizedLastTempPath) unlink(resizedLastTempPath).catch(() => {});+ for (const p of resizedKeyframeTempPaths) unlink(p).catch(() => {});+ if (uploadedTempPath) unlink(uploadedTempPath).catch(() => {});+ for (const p of uploadedTempPaths) unlink(p).catch(() => {});+ if (audioFilePath && !uploadedTempPaths.includes(audioFilePath)) {+ unlink(audioFilePath).catch(() => {});+ }+ closeJobAfterDelay(jobs, jobId);+ throw err;+ }console.log(`🎬 Generating video [${jobId.slice(0, 8)}]: ${modelId} ${w}x${h} frames=${parsedNumFrames} steps=${actualSteps}`);videoGenEvents.emit('started', { generationId: jobId, totalSteps: actualSteps, ...meta });@@ -389,6 +521,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m// ENOENT/permission errors leak files in os.tmpdir().if (resizedSrcTempPath) unlink(resizedSrcTempPath).catch(() => {});if (resizedLastTempPath) unlink(resizedLastTempPath).catch(() => {});+ for (const p of resizedKeyframeTempPaths) unlink(p).catch(() => {});if (uploadedTempPath) unlink(uploadedTempPath).catch(() => {});for (const p of uploadedTempPaths) unlink(p).catch(() => {});// Defensive: a direct caller (bypassing the route) may pass audioFilePath@@ -466,6 +599,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m// (macOS /var → /private/var) so startsWith() can silently miss.if (resizedSrcTempPath) await unlink(resizedSrcTempPath).catch(() => {});if (resizedLastTempPath) await unlink(resizedLastTempPath).catch(() => {});+ for (const p of resizedKeyframeTempPaths) await unlink(p).catch(() => {});// Cleanup the original multipart upload temp file too — without this,// every i2v request leaves a file in os.tmpdir() forever.if (uploadedTempPath) await unlink(uploadedTempPath).catch(() => {});@@ -613,6 +747,11 @@ export async function generateChainedVideo({ chunks, jobId: outerJobId, ...rest// is single-conditioned on the previous chunk's tail frame (or full video// for extend mode).lastImagePath: i === 0 ? rest.lastImagePath : null,+ // Multi-keyframe interpolation only makes sense for the first chunk+ // (the user pinned specific frame indices in a single clip). Subsequent+ // chunks fall through to the image-chain path, conditioning on the+ // prior chunk's tail frame.+ keyframes: i === 0 ? rest.keyframes : null,}).catch((err) => {detach();reject(err);