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
support GitLab repos in Brain links and add on-demand update-and-restudy
[._.]/ Adam Eivy5a0033b84c76
diff --git a/client/src/components/QuickBrainCapture.jsx b/client/src/components/QuickBrainCapture.jsxindex dccd932f68..811ff42d53 100644--- a/client/src/components/QuickBrainCapture.jsx+++ b/client/src/components/QuickBrainCapture.jsx@@ -26,7 +26,7 @@ export default function QuickBrainCapture() {// A single-video YouTube URL takes a different path entirely (ingest, not// capture) and unlocks the advanced panel below.const isYoutube = useMemo(() => isYoutubeVideoUrl(input), [input]);- // A bare GitHub repo URL is cloned on capture, which unlocks the two post-clone+ // A bare repo URL is cloned on capture, which unlocks the two post-clone// agent opt-ins (malware scan / repo study).const repoIntake = useRepoIntake(input);@@ -279,18 +279,7 @@ export default function QuickBrainCapture() {<RepoIntakeOptionsidPrefix="quick-brain-repo"- repo={repoIntake.repo}- options={repoIntake.options}- managedApps={repoIntake.managedApps}- targetAppId={repoIntake.targetAppId}- onTargetAppChange={repoIntake.setTargetAppId}- studyContext={repoIntake.studyContext}- onStudyContextChange={repoIntake.setStudyContext}- providerOverride={repoIntake.providerOverride}- providers={repoIntake.providers}- activeProviderId={repoIntake.activeProviderId}- onProviderOverrideChange={repoIntake.setProviderOverride}- onToggle={repoIntake.toggle}+ {...repoIntake}/>{ingest.active && (diff --git a/client/src/components/apps/tabs/SubmodulesTab.jsx b/client/src/components/apps/tabs/SubmodulesTab.jsxindex b24c95449c..93f0b34fe1 100644--- a/client/src/components/apps/tabs/SubmodulesTab.jsx+++ b/client/src/components/apps/tabs/SubmodulesTab.jsx@@ -5,7 +5,7 @@ import Pill from '../../ui/Pill';import ToggleSwitch from '../../ToggleSwitch';import BrailleSpinner from '../../BrailleSpinner';import * as api from '../../../services/api';-import { parseGitHubUrl } from '../../../lib/githubRepoUrl';+import { parseGitHubUrl } from '../../../lib/repoUrl';/** Whether a submodule's pointer differs from what its remote default branch has. */const needsUpdate = (sub) => sub.behind > 0 || sub.outOfSync || !sub.initialized || sub.conflicted;diff --git a/client/src/components/brain/RepoIntakeOptions.jsx b/client/src/components/brain/RepoIntakeOptions.jsxindex 193c657892..c99b450e04 100644--- a/client/src/components/brain/RepoIntakeOptions.jsx+++ b/client/src/components/brain/RepoIntakeOptions.jsx@@ -1,9 +1,9 @@import { GitBranch, ShieldCheck, Lightbulb } from 'lucide-react';import ToggleChip from '../ui/ToggleChip';-import AgentJobProviderFields from '../cos/AgentJobProviderFields';+import RepoStudyFields from './RepoStudyFields';/**- * The "this URL is a GitHub repo" affordance shared by both Brain capture boxes+ * The "this URL is a repository" affordance shared by both Brain capture boxes* (the Quick Capture dashboard widget and the Inbox capture form).** Presentational only — the sticky checkbox state and the repo-URL rule live in@@ -30,18 +30,15 @@ export const REPO_INTAKE_OPTIONS = [* @param {object} props* @param {string} props.idPrefix unique per host form — the checkbox ids/labels* must not collide when both capture boxes are mounted on the same page.- * @param {{owner: string, repo: string}|null} props.repo parsed repo, or null to- * render nothing (the capture isn't a bare repo URL)+ * @param {{host: string, owner: string, repo: string}|null} props.repo parsed+ * repo, or null to render nothing (the capture isn't a bare repo URL)* @param {{malwareScan: boolean, learn: boolean}} props.options- * @param {string} props.studyContext- * @param {(context: string) => void} props.onStudyContextChange- * @param {{providerId: string, model: string, effort: string}} props.providerOverride- * @param {Array} props.providers- * @param {string} props.activeProviderId- * @param {(patch: object) => void} props.onProviderOverrideChange- * @param {(key: string) => void} props.onToggle+ * @param {(key: string) => void} props.toggle+ * Remaining props are the `useRepoStudyConfig` shape, forwarded to+ * `RepoStudyFields` when the study option is ticked — so a host can spread+ * the whole `useRepoIntake` return onto this component.*/-export default function RepoIntakeOptions({ idPrefix, repo, options, managedApps = [], targetAppId, onTargetAppChange, studyContext = '', onStudyContextChange, providerOverride = { providerId: '', model: '', effort: '' }, providers = [], activeProviderId = '', onProviderOverrideChange, onToggle }) {+export default function RepoIntakeOptions({ idPrefix, repo, options, toggle, ...studyFields }) {if (!repo) return null;return (@@ -49,7 +46,7 @@ export default function RepoIntakeOptions({ idPrefix, repo, options, managedApps<p className="flex items-center gap-1.5 text-xs text-gray-400"><GitBranch size={12} className="text-port-accent shrink-0" /><span>- <span className="text-gray-200">{repo.owner}/{repo.repo}</span> will be cloned locally.+ <span className="text-gray-200">{repo.owner}/{repo.repo}</span> on {repo.host} will be cloned locally.</span></p><div className="flex flex-wrap gap-2">@@ -61,54 +58,11 @@ export default function RepoIntakeOptions({ idPrefix, repo, options, managedAppshint={hint}Icon={Icon}checked={options[key]}- onToggle={() => onToggle(key)}+ onToggle={() => toggle(key)}/>))}</div>- {options.learn && managedApps.length > 0 && (- <label htmlFor={`${idPrefix}-target-app`} className="block text-xs text-gray-400">- File study issues against- <select- id={`${idPrefix}-target-app`}- value={targetAppId}- onChange={e => onTargetAppChange?.(e.target.value)}- className="ml-2 px-2 py-1 bg-port-bg border border-port-border rounded text-gray-200 text-xs"- >- {managedApps.map(app => <option key={app.id} value={app.id}>{app.name}</option>)}- </select>- </label>- )}- {options.learn && (- <div>- <label htmlFor={`${idPrefix}-study-context`} className="block text-xs text-gray-400 mb-1">- Study context <span className="text-gray-600">(optional)</span>- </label>- <textarea- id={`${idPrefix}-study-context`}- rows={3}- maxLength={5000}- value={studyContext}- onChange={e => onStudyContextChange?.(e.target.value)}- placeholder="What should the agent look for, and where might an implementation fit?"- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"- />- </div>- )}- {options.learn && (- <div className="pt-1">- <AgentJobProviderFields- data={providerOverride}- providers={providers}- activeProviderId={activeProviderId}- onChange={onProviderOverrideChange}- />- {providers.length > 0 && (- <p className="mt-1 text-xs text-gray-500">- Optional override for this study only. Leave it on the default to use the configured CoS provider.- </p>- )}- </div>- )}+ {options.learn && <RepoStudyFields idPrefix={idPrefix} {...studyFields} />}{REPO_INTAKE_OPTIONS.some(({ key }) => options[key]) && (<p className="text-xs text-gray-500">A CoS agent starts once the clone finishes — track it in Chief of Staff.diff --git a/client/src/components/brain/RepoRestudyPanel.jsx b/client/src/components/brain/RepoRestudyPanel.jsxnew file mode 100644index 0000000000..afb23ec092--- /dev/null+++ b/client/src/components/brain/RepoRestudyPanel.jsx@@ -0,0 +1,96 @@+import { useState } from 'react';+import { Lightbulb, RefreshCw, X } from 'lucide-react';+import * as api from '../../services/api';+import toast from '../ui/Toast';+import BrailleSpinner from '../BrailleSpinner';+import RepoStudyFields from './RepoStudyFields';+import { useRepoStudyConfig } from '../../hooks';++/**+ * The Links tab's on-demand "Update & study" form for an already-cloned repo:+ * refresh the checkout, then queue a fresh `repo-study` run with a brief the+ * user writes right now ("look at how it does X", "compare its onboarding to+ * ours") instead of the one they may have written weeks ago at capture time.+ *+ * The knobs and their payload come from the SAME `useRepoStudyConfig` /+ * `RepoStudyFields` pair the capture boxes use, so the two dispatch paths can't+ * drift apart. The brief the last run was given seeds the field.+ *+ * @param {object} props+ * @param {object} props.link the cloned repo link+ * @param {() => void} props.onClose+ * @param {(link: object) => void} props.onQueued receives the updated link record+ */+export default function RepoRestudyPanel({ link, onClose, onQueued }) {+ const study = useRepoStudyConfig({+ resetKey: link.id,+ initialStudyContext: link.repoStudy?.studyContext || '',+ });+ const [pull, setPull] = useState(true);+ const [submitting, setSubmitting] = useState(false);++ const handleSubmit = async () => {+ setSubmitting(true);+ const result = await api+ .studyBrainLink(link.id, { pull, ...study.studyPayload() }, { silent: true })+ .catch(err => {+ toast.error(err.message || 'Failed to queue study');+ return null;+ });+ setSubmitting(false);+ if (!result) return;++ // A pull failure does not stop the study — say so, or the user has no way to+ // know the agent is reading a checkout that never got refreshed.+ toast[result.pulled && !result.pulled.ok ? 'warning' : 'success'](+ result.pulled && !result.pulled.ok+ ? 'Study queued — the pull failed, so it reads the existing checkout'+ : 'Study queued — track it in Chief of Staff'+ );+ onQueued?.(result.link);+ onClose?.();+ };++ return (+ <div className="mt-2 w-full rounded-lg border border-port-border bg-port-bg/60 p-3 space-y-2">+ <div className="flex items-center gap-2">+ <Lightbulb size={14} className="text-port-accent shrink-0" />+ <h4 className="text-sm font-medium text-gray-200">Update & study this repo</h4>+ <button+ onClick={onClose}+ className="ml-auto p-1 text-gray-400 hover:text-white transition-colors"+ title="Close" aria-label="Close study form"+ >+ <X size={14} />+ </button>+ </div>++ <label htmlFor={`restudy-pull-${link.id}`} className="flex items-center gap-2 text-xs text-gray-400">+ <input+ id={`restudy-pull-${link.id}`}+ type="checkbox"+ checked={pull}+ onChange={e => setPull(e.target.checked)}+ className="accent-port-accent"+ />+ Pull the latest commits before studying+ </label>++ <RepoStudyFields+ idPrefix={`restudy-${link.id}`}+ {...study}+ contextLabel="What should this study look for?"+ contextPlaceholder="e.g. how it handles offline sync, and whether our Brain could adopt the same conflict model"+ />++ <button+ onClick={handleSubmit}+ disabled={submitting}+ className="flex items-center gap-1.5 px-3 py-1.5 text-xs rounded bg-port-accent/20 text-port-accent border border-port-accent/30 hover:bg-port-accent/30 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"+ >+ {submitting ? <BrailleSpinner /> : <RefreshCw size={12} />}+ {pull ? 'Update & study' : 'Study now'}+ </button>+ </div>+ );+}diff --git a/client/src/components/brain/RepoStudyFields.jsx b/client/src/components/brain/RepoStudyFields.jsxnew file mode 100644index 0000000000..fee35a5193--- /dev/null+++ b/client/src/components/brain/RepoStudyFields.jsx@@ -0,0 +1,78 @@+import AgentJobProviderFields from '../cos/AgentJobProviderFields';++/**+ * The `repo-study` configuration form: which managed app's tracker receives the+ * issues, the free-form brief telling the agent what to look for, and an+ * optional provider/model/effort pin for that one run.+ *+ * Presentational only — state lives in `hooks/useRepoStudyConfig.js`, whose+ * return value spreads straight onto these props (the prop names ARE that+ * hook's, so a call site never has to re-map them). Shared by the Brain capture+ * boxes' post-clone opt-in (`RepoIntakeOptions`) and the Links tab's on-demand+ * re-study panel, so the two can't drift.+ *+ * @param {object} props+ * @param {string} props.idPrefix unique per host form — the field ids/labels+ * must not collide when several of these are mounted on the same page.+ * @param {string} [props.contextLabel] heading for the brief textarea.+ * @param {string} [props.contextPlaceholder]+ * @param {string} [props.providerHint] note under the provider controls.+ */+export default function RepoStudyFields({+ idPrefix,+ managedApps = [],+ targetAppId,+ setTargetAppId,+ studyContext = '',+ setStudyContext,+ providerOverride = { providerId: '', model: '', effort: '' },+ providers = [],+ activeProviderId = '',+ setProviderOverride,+ contextLabel = 'Study context',+ contextPlaceholder = 'What should the agent look for, and where might an implementation fit?',+ providerHint = 'Optional override for this study only. Leave it on the default to use the configured CoS provider.',+}) {+ return (+ <>+ {managedApps.length > 0 && (+ <label htmlFor={`${idPrefix}-target-app`} className="block text-xs text-gray-400">+ File study issues against+ <select+ id={`${idPrefix}-target-app`}+ value={targetAppId}+ onChange={e => setTargetAppId?.(e.target.value)}+ className="ml-2 px-2 py-1 bg-port-bg border border-port-border rounded text-gray-200 text-xs"+ >+ {managedApps.map(app => <option key={app.id} value={app.id}>{app.name}</option>)}+ </select>+ </label>+ )}+ <div>+ <label htmlFor={`${idPrefix}-study-context`} className="block text-xs text-gray-400 mb-1">+ {contextLabel} <span className="text-gray-600">(optional)</span>+ </label>+ <textarea+ id={`${idPrefix}-study-context`}+ rows={3}+ maxLength={5000}+ value={studyContext}+ onChange={e => setStudyContext?.(e.target.value)}+ placeholder={contextPlaceholder}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ />+ </div>+ <div className="pt-1">+ <AgentJobProviderFields+ data={providerOverride}+ providers={providers}+ activeProviderId={activeProviderId}+ onChange={setProviderOverride}+ />+ {providers.length > 0 && (+ <p className="mt-1 text-xs text-gray-500">{providerHint}</p>+ )}+ </div>+ </>+ );+}diff --git a/client/src/components/brain/tabs/InboxTab.jsx b/client/src/components/brain/tabs/InboxTab.jsxindex 87bf24dda6..f0fbdc4fcc 100644--- a/client/src/components/brain/tabs/InboxTab.jsx+++ b/client/src/components/brain/tabs/InboxTab.jsx@@ -57,7 +57,7 @@ export default function InboxTab({ onRefresh, settings }) {// when on, captured thoughts are flagged so they can later be batch-sent to the// creative catalog (vs todos/refs that stay out).const [creative, setCreative] = useLocalStorageBool('brain.captureCreative', false);- // A bare GitHub repo URL is cloned on capture, which unlocks the two post-clone+ // A bare repo URL is cloned on capture, which unlocks the two post-clone// agent opt-ins (malware scan / repo study) — shared with Quick Capture.const repoIntake = useRepoIntake(inputText);const [entries, setEntries] = useState([]);@@ -381,7 +381,7 @@ export default function InboxTab({ onRefresh, settings }) {<p className="mt-2 text-xs text-gray-500">Capture a thought — type or use the mic. AI will classify and route it automatically.{inputIsUrl && (repoIntake.repo- ? <span className="text-cyan-400"> That’s a GitHub repo — it will be saved to Links and cloned.</span>+ ? <span className="text-cyan-400"> That’s a repository — it will be saved to Links and cloned.</span>: <span className="text-cyan-400"> That’s a URL — it will be saved to Links.</span>)}{!inputIsUrl && creative && <span className="text-port-accent-2"> Creative mode on — captures are flagged for the Catalog.</span>}{settings?.confidenceThreshold && (@@ -390,18 +390,7 @@ export default function InboxTab({ onRefresh, settings }) {</p><RepoIntakeOptionsidPrefix="inbox-capture-repo"- repo={repoIntake.repo}- options={repoIntake.options}- managedApps={repoIntake.managedApps}- targetAppId={repoIntake.targetAppId}- onTargetAppChange={repoIntake.setTargetAppId}- studyContext={repoIntake.studyContext}- onStudyContextChange={repoIntake.setStudyContext}- providerOverride={repoIntake.providerOverride}- providers={repoIntake.providers}- activeProviderId={repoIntake.activeProviderId}- onProviderOverrideChange={repoIntake.setProviderOverride}- onToggle={repoIntake.toggle}+ {...repoIntake}/></form>diff --git a/client/src/components/brain/tabs/LinksTab.jsx b/client/src/components/brain/tabs/LinksTab.jsxindex 9a0d371043..ea3f42fa44 100644--- a/client/src/components/brain/tabs/LinksTab.jsx+++ b/client/src/components/brain/tabs/LinksTab.jsx@@ -32,6 +32,7 @@ import InlineConfirmRow from '../../ui/InlineConfirmRow';import { timeAgo } from '../../../utils/formatters';import { useAutoRefetch } from '../../../hooks/useAutoRefetch';import BucketBoard from '../links/BucketBoard';+import RepoRestudyPanel from '../RepoRestudyPanel';import { LINK_DND_TYPE } from '../links/bucketColors';import { reorderLinksInBucket } from '../links/bucketReorder';import { normalizeUrl as normalizeUrlShared } from '../../../utils/urlNormalize';@@ -56,6 +57,9 @@ function normalizeUrl(raw) {}const LINK_TYPE_COLORS = {+ repo: 'bg-purple-500/20 text-purple-400 border-purple-500/30',+ // Pre-multi-host records still carry `github`; migration 328 renames the+ // stored value but a peer on older code can still federate one in.github: 'bg-purple-500/20 text-purple-400 border-purple-500/30',article: 'bg-blue-500/20 text-blue-400 border-blue-500/30',documentation: 'bg-green-500/20 text-green-400 border-green-500/30',@@ -123,12 +127,14 @@ export default function LinksTab({ onRefresh }) {const [links, setLinks] = useState([]);const [buckets, setBuckets] = useState([]);const [loading, setLoading] = useState(true);- const [filter, setFilter] = useState('all'); // all, github, scanned, other, ungrouped+ const [filter, setFilter] = useState('all'); // all, repo, scanned, other, ungroupedconst [search, setSearch] = useState('');const [editingId, setEditingId] = useState(null);const [editForm, setEditForm] = useState({});const [confirmingDeleteId, setConfirmingDeleteId] = useState(null);const [scanningId, setScanningId] = useState(null);+ // The one repo whose "Update & study" form is open, if any.+ const [studyingId, setStudyingId] = useState(null);const inputRef = useRef(null);// Fetch the full link set; filtering, search, and bucket membership are all@@ -220,9 +226,9 @@ export default function LinksTab({ onRefresh }) {// Client-side filter (type / bucket membership) then keyword search.const matchesFilter = (link) => {- if (filter === 'github') return link.isGitHubRepo;+ if (filter === 'repo') return link.isRepo;if (filter === 'scanned') return hasScanReport(link);- if (filter === 'other') return !link.isGitHubRepo;+ if (filter === 'other') return !link.isRepo;if (filter === 'ungrouped') return !link.bucketId;return true;};@@ -272,8 +278,7 @@ export default function LinksTab({ onRefresh }) {setSending(false);if (result) {- const isGitHub = result.isGitHubRepo;- toast.success(isGitHub ? 'GitHub repo added - cloning in background' : 'Link saved');+ toast.success(result.isRepo ? 'Repo added - cloning in background' : 'Link saved');setInputUrl('');setInputTitle('');setInputNote('');@@ -482,7 +487,7 @@ export default function LinksTab({ onRefresh }) {type="text"value={inputUrl}onChange={(e) => setInputUrl(e.target.value)}- placeholder="Paste a URL (GitHub repos auto-clone)..."+ placeholder="Paste a URL (GitHub / GitLab repos auto-clone)..."aria-label="Link URL to save"className="flex-1 px-4 py-3 bg-port-card border border-port-border rounded-lg text-white placeholder-gray-500 focus:outline-hidden focus:border-port-accent"disabled={sending}@@ -554,7 +559,7 @@ export default function LinksTab({ onRefresh }) {)}<p className="mt-2 text-xs text-gray-500">- Paste any URL. GitHub repos will be automatically cloned for local reference.+ Paste any URL. GitHub and GitLab repos will be automatically cloned for local reference.</p></form>@@ -562,9 +567,9 @@ export default function LinksTab({ onRefresh }) {<div className="flex gap-2 mb-4 flex-wrap">{[{ id: 'all', label: 'All', count: links.length },- { id: 'github', label: 'GitHub Repos', icon: GitBranch, count: links.filter(l => l.isGitHubRepo).length },+ { id: 'repo', label: 'Repos', icon: GitBranch, count: links.filter(l => l.isRepo).length },{ id: 'scanned', label: 'Scan Reports', icon: FileText, count: links.filter(hasScanReport).length },- { id: 'other', label: 'Other Links', icon: Link2, count: links.filter(l => !l.isGitHubRepo).length },+ { id: 'other', label: 'Other Links', icon: Link2, count: links.filter(l => !l.isRepo).length },{ id: 'ungrouped', label: 'Ungrouped', icon: FolderClosed, count: links.filter(l => !l.bucketId).length }].map(tab => {const Icon = tab.icon;@@ -683,7 +688,7 @@ export default function LinksTab({ onRefresh }) {onChange={(e) => setEditForm({ ...editForm, linkType: e.target.value })}className="px-2 py-1 bg-port-bg border border-port-border rounded text-white text-sm">- <option value="github">GitHub</option>+ <option value="repo">Repository</option><option value="article">Article</option><option value="documentation">Documentation</option><option value="tool">Tool</option>@@ -720,7 +725,7 @@ export default function LinksTab({ onRefresh }) {<><div className="flex-1 min-w-0"><div className="flex items-center gap-2 mb-1">- {link.isGitHubRepo ? (+ {link.isRepo ? (link.malwareScan?.verdict === 'DANGEROUS'? <Skull size={16} className="text-port-error shrink-0" aria-label="Dangerous repository" />: <GitBranch size={16} className="text-purple-400 shrink-0" />@@ -827,8 +832,8 @@ export default function LinksTab({ onRefresh }) {</div>)}- {/* GitHub-specific controls */}- {link.isGitHubRepo && (+ {/* Repository-specific controls */}+ {link.isRepo && (<>{/* Clone status */}<span className={`flex items-center gap-1 text-xs ${CLONE_STATUS_STYLES[link.cloneStatus]}`}>@@ -942,6 +947,18 @@ export default function LinksTab({ onRefresh }) {<RefreshCw size={12} />Pull</button>+ <button+ onClick={() => setStudyingId(current => (current === link.id ? null : link.id))}+ className={`flex items-center gap-1 px-2 py-1 text-xs rounded border transition-colors ${+ studyingId === link.id+ ? 'border-port-accent/30 bg-port-accent/20 text-port-accent'+ : 'border-port-border text-gray-400 hover:text-white'+ }`}+ title="Pull the latest commits and queue a fresh repo study with your own brief"+ >+ <Lightbulb size={12} />+ Update & study+ </button><buttononClick={() => handleScan(link.id)}disabled={scanningId === link.id}@@ -957,6 +974,14 @@ export default function LinksTab({ onRefresh }) {</button></>)}++ {studyingId === link.id && (+ <RepoRestudyPanel+ link={link}+ onClose={() => setStudyingId(null)}+ onQueued={(updated) => updated && setLinks(prev => prev.map(l => (l.id === updated.id ? updated : l)))}+ />+ )}</>)}</div>diff --git a/client/src/components/brain/tabs/LinksTab.test.jsx b/client/src/components/brain/tabs/LinksTab.test.jsxindex bc62267982..2f763c840f 100644--- a/client/src/components/brain/tabs/LinksTab.test.jsx+++ b/client/src/components/brain/tabs/LinksTab.test.jsx@@ -15,9 +15,13 @@ vi.mock('../../../services/api', () => ({scanBrainLink: vi.fn(),openBrainLinkFolder: vi.fn(),brainScanReportPath: vi.fn(() => '/report'),+ studyBrainLink: vi.fn(),+ // Read by the shared repo-study form (useRepoStudyConfig).+ getApps: vi.fn(() => Promise.resolve([])),+ getProviders: vi.fn(() => Promise.resolve({ providers: [] })),}));-vi.mock('../../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));+vi.mock('../../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn(), warning: vi.fn() } }));// Counting stub: the board is the most expensive consumer of the `links`// array, so its render count is the direct measure of "the poll does not@@ -30,16 +34,17 @@ vi.mock('../links/BucketBoard', () => ({},}));-import { createBrainLink, getBrainLink, getBrainLinks, getBrainBuckets } from '../../../services/api';+import { createBrainLink, getBrainLink, getBrainLinks, getBrainBuckets, studyBrainLink } from '../../../services/api';+import toast from '../../ui/Toast';import LinksTab from './LinksTab';const link = (id, cloneStatus, overrides = {}) => ({id,url: `https://github.com/example/${id}`,title: `repo-${id}`,- linkType: 'github',+ linkType: 'repo',tags: [],- isGitHubRepo: true,+ isRepo: true,cloneStatus,bucketId: null,createdAt: '2026-01-01T00:00:00.000Z',@@ -275,7 +280,7 @@ describe('LinksTab link creation form', () => {const created = link('new', 'none', {url: 'https://example.com/article',title: 'example.com',- isGitHubRepo: false,+ isRepo: false,});createBrainLink.mockResolvedValue(created);await renderTab();@@ -299,3 +304,42 @@ describe('LinksTab link creation form', () => {});});});++describe('LinksTab on-demand repo re-study', () => {+ const cloned = () => link('a', 'cloned', { localPath: '/repos/example/a' });++ const openStudyForm = async () => {+ getBrainLinks.mockResolvedValue({ links: [cloned()] });+ const view = await renderTab();+ await act(async () => { screen.getByRole('button', { name: /update & study/i }).click(); });+ return view;+ };++ it('sends the brief, the target app, and the pull flag', async () => {+ studyBrainLink.mockResolvedValue({ taskId: 'task-1', pulled: { ok: true }, link: cloned() });+ const { container } = await openStudyForm();++ const brief = container.querySelector('#restudy-a-study-context');+ await act(async () => {+ fireEvent.change(brief, { target: { value: 'look at its offline sync' } });+ });+ // Two buttons carry the label — the row toggle and the form's submit.+ await act(async () => { screen.getAllByRole('button', { name: /update & study/i }).at(-1).click(); });++ expect(studyBrainLink).toHaveBeenCalledWith(+ 'a',+ expect.objectContaining({ pull: true, studyContext: 'look at its offline sync' }),+ { silent: true },+ );+ });++ it('warns rather than claiming success when the pull failed but the study queued', async () => {+ studyBrainLink.mockResolvedValue({ taskId: 'task-1', pulled: { ok: false, error: 'diverged' }, link: cloned() });+ await openStudyForm();++ await act(async () => { screen.getAllByRole('button', { name: /update & study/i }).at(-1).click(); });++ expect(toast.warning).toHaveBeenCalledWith(expect.stringMatching(/pull failed/i));+ expect(toast.success).not.toHaveBeenCalled();+ });+});diff --git a/client/src/components/settings/InstanceFeaturesTab.jsx b/client/src/components/settings/InstanceFeaturesTab.jsxindex 81971dcb83..c986621854 100644--- a/client/src/components/settings/InstanceFeaturesTab.jsx+++ b/client/src/components/settings/InstanceFeaturesTab.jsx@@ -4,7 +4,7 @@ import toast from '../ui/Toast';import BrailleSpinner from '../BrailleSpinner';import ToggleSwitch from '../ToggleSwitch';import { useInstanceFeatures, publishInstanceFeatures } from '../../hooks/useInstanceFeatures.js';-import { isGitHubRepoUrl, parseGitHubUrl } from '../../lib/githubRepoUrl.js';+import { isGitHubRepoUrl, parseGitHubUrl } from '../../lib/repoUrl.js';import { getPrimaryLaunchUrl } from '../../services/appUrls.js';import { installEidoverseFeature, updateEidoverseWorldsSource, updateInstanceFeature } from '../../services/api';diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 7dfa81dde6..9b45530d6a 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -191,7 +191,8 @@ grep -i "what you want to do" client/src/hooks/README.md| `useSystemResourceReport` | The system-resource disk scan plus its cleanup lifecycle: generation-guarded `runReport` (a late scan can never resurrect rows a newer one removed), one-delete-at-a-time removal keyed on the candidate's server-issued action, and report invalidation after a successful delete. Returns `{ report, setReport, loading, runReport, cleanup }` — `cleanup` is the prop bag `StoragePanel`/`ModelsPanel`/`CleanupControl` expect. | Dev Tools → System Resources → Storage, and Models → Status. Don't re-wire the scan/cleanup pair by hand. || `useImageTo3dTargets` | The image-to-3D target registry (`GET /api/image-to-3d/targets`), fetched once per mount. Returns `{ targets, loading, error, reload }` — `error` is first-class, because a failed registry read is NOT an empty registry and both call sites render that distinction. | The `/3d` render flow (target picker + readiness summary) and Models → 3D (install/repair). Don't re-roll the fetch in a third surface. || `useTwinEvaluationSuite` | Shared lifecycle for the three Digital Twin evaluation-suite panels (Values-Alignment, Adversarial-Boundary, Multi-Turn): loads suite + recent history (silenced), runs every selected provider/model in parallel, prepends fresh runs, and handles the stale-persona / partial-failure toast fan-out. `countField` names the suite's pass-count key so history stays generic. Returns `{ items, history, loading, running, results, expanded, setExpanded, run, reload }`. | The Digital Twin `TwinEvaluationSuitePanel` presentation shell — don't re-roll the load/run/history dance per suite. |-| `useRepoIntake` | The Brain capture boxes' GitHub-repo state: `repo` (the parsed `{owner,repo}` when the ENTIRE capture text is a repo URL — i.e. exactly when the server will clone it), the two sticky post-clone agent opt-ins (`options`/`toggle`, persisted to `localStorage`), per-capture repo-study context, and `intakeFor(submittedText)` which re-derives at submit time so a sticky tick can't ride along on a capture retyped into a plain thought. Also exports the pure `capturedGitHubRepo(text)`. | Any capture surface that should offer the malware-scan / repo-study runs. Render with `components/brain/RepoIntakeOptions`; don't re-parse the text in the component. |+| `useRepoIntake` | The Brain capture boxes' repository state: `repo` (the parsed `{host,owner,repo}` when the ENTIRE capture text is a github.com/gitlab.com repo URL — i.e. exactly when the server will clone it), the two sticky post-clone agent opt-ins (`options`/`toggle`, persisted to `localStorage`), the `useRepoStudyConfig` knobs it composes, and `intakeFor(submittedText)` which re-derives at submit time so a sticky tick can't ride along on a capture retyped into a plain thought. Also exports the pure `capturedRepo(text)`. | Any capture surface that should offer the malware-scan / repo-study runs. Render with `components/brain/RepoIntakeOptions`; don't re-parse the text in the component. |+| `useRepoStudyConfig` | The knobs a `repo-study` dispatch takes — target managed app, the free-form brief, and an optional provider/model/effort pin — plus `studyPayload()` for the request body. | Any surface that dispatches a repo study: the capture-time opt-in (via `useRepoIntake`) and the Links tab's on-demand "Update & study". Render with `components/brain/RepoStudyFields`. || `useRenderJobQueue` | Per-entry render-job queue for the Universe Builder — `pendingByEntryId` (entryId → jobId[]), `pendingHeadByEntryId` (first jobId per entry for single-subscription thumbs), `enqueueEntryJobs` (append variation/canon jobs), `clearPendingForEntry` (shift a jobId out, or drop the entry). | Universe Builder render orchestration. Don't re-roll the per-entry pending-jobs reducer. || `useUniverse` | Loads the universe record for a `universeId` with mount/cancel guards; returns `[universe, setUniverse, loading, error]` (setter exposed for optimistic post-mutation updates). | Any surface that loads a linked universe (pipeline stages, etc.) — use instead of re-rolling the getUniverse-on-mount effect. || `useUniverseAction` | LLM-driven universe mutation scaffolding. | Universe Builder action UIs. |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex aa9c977e7e..20b09c4d0d 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -201,6 +201,7 @@ export * from './usePostSession.js';export * from './useRecordMerge.js';export * from './useRenderJobQueue.js';export * from './useRepoIntake.js';+export * from './useRepoStudyConfig.js';export * from './useSyncIntegrity.js';export * from './useSystemResourceReport.js';export * from './useTwinEvaluationSuite.js';diff --git a/client/src/hooks/useRepoIntake.js b/client/src/hooks/useRepoIntake.jsindex 2b8654a382..6a01e66da3 100644--- a/client/src/hooks/useRepoIntake.js+++ b/client/src/hooks/useRepoIntake.js@@ -1,19 +1,19 @@-import { useEffect, useMemo, useState } from 'react';+import { useMemo } from 'react';import { useLocalStorageBool } from './useLocalStorageBool.js';-import useProviderModels from './useProviderModels.js';+import { useRepoStudyConfig } from './useRepoStudyConfig.js';import { parseBareUrl } from '../lib/bareUrl.js';-import { parseGitHubUrl } from '../lib/githubRepoUrl.js';-import * as api from '../services/api.js';-import { PORTOS_APP_ID } from '../lib/appIdentity.js';+import { parseRepoUrl } from '../lib/repoUrl.js';/**- * The Brain capture boxes' "this URL is a GitHub repo" state.+ * The Brain capture boxes' "this URL is a repository" state.*- * A bare GitHub repo URL is always cloned by the server, which unlocks two- * opt-in post-clone CoS agent runs (malware scan / repo study). Both preferences- * are sticky — same pattern as the Creative toggle — so a user who always wants- * a malware scan ticks it once.+ * A bare repo URL (github.com / gitlab.com) is always cloned by the server,+ * which unlocks two opt-in post-clone CoS agent runs (malware scan / repo+ * study). Both preferences are sticky — same pattern as the Creative toggle —+ * so a user who always wants a malware scan ticks it once.*+ * The study knobs come from the shared `useRepoStudyConfig`, so the capture+ * boxes and the Links tab's on-demand re-study send the same payload shape.* Rendering lives in `components/brain/RepoIntakeOptions.jsx`, which takes the* `repo` this returns rather than re-parsing the text.*/@@ -25,88 +25,46 @@ const STORAGE_KEYS = {};/**- * `{ owner, repo }` when a capture's ENTIRE text is a GitHub repo URL — i.e.- * exactly when the server will file it to Links and clone it. Composes the two- * mirrored rules in the same order `services/brain.js` does (`parseBareUrl` →- * `parseGitHubUrl`); checking only the second would light the panel up for+ * The parsed repo when a capture's ENTIRE text is a repo URL — i.e. exactly+ * when the server will file it to Links and clone it. Composes the two mirrored+ * rules in the same order `services/brain.js` does (`parseBareUrl` →+ * `parseRepoUrl`); checking only the second would light the panel up for* "check out github.com/owner/repo", which the server files as a thought.*/-export function capturedGitHubRepo(text) {+export function capturedRepo(text) {const url = parseBareUrl(text);- return url ? parseGitHubUrl(url) : null;+ return url ? parseRepoUrl(url) : null;}/*** @param {string} text the current capture text- * @returns {{ repo: object|null, options: object, studyContext: string,- * setStudyContext: (context: string) => void, providerOverride: object,- * setProviderOverride: (patch: object) => void, toggle: (key: string) => void,- * intakeFor: (text: string) => object|undefined }}- * `repo` is the parsed `{ owner, repo }` (null when the text isn't a bare repo- * URL) — both the panel and the host's hint read it, so the text is parsed- * once per keystroke rather than once per consumer. `intakeFor(text)` is the- * payload to send with a capture: the ticked options when `text` is a repo- * URL, else undefined. It re-derives from the SUBMITTED text so a sticky tick- * can't ride along on a capture the user retyped into a plain thought.+ * @returns {object} the `useRepoStudyConfig` shape plus `repo`, `options`,+ * `toggle`, and `intakeFor`. `repo` is the parsed `{ host, owner, repo }`+ * (null when the text isn't a bare repo URL) — both the panel and the host's+ * hint read it, so the text is parsed once per keystroke rather than once per+ * consumer. `intakeFor(text)` is the payload to send with a capture: the+ * ticked options when `text` is a repo URL, else undefined. It re-derives from+ * the SUBMITTED text so a sticky tick can't ride along on a capture the user+ * retyped into a plain thought.*/export function useRepoIntake(text) {const [malwareScan, setMalwareScan] = useLocalStorageBool(STORAGE_KEYS.malwareScan, false);const [learn, setLearn] = useLocalStorageBool(STORAGE_KEYS.learn, false);- const repo = useMemo(() => capturedGitHubRepo(text), [text]);- const { providers, activeProviderId } = useProviderModels({- allowDefault: true,- silent: true,- withEffort: true,- enabled: Boolean(repo && learn),- });- const [managedApps, setManagedApps] = useState([{ id: PORTOS_APP_ID, name: 'PortOS' }]);- const [targetAppId, setTargetAppId] = useState(PORTOS_APP_ID);- const [studyContext, setStudyContext] = useState('');- const [providerOverride, setProviderOverride] = useState({ providerId: '', model: '', effort: '' });+ const repo = useMemo(() => capturedRepo(text), [text]);++ const repoKey = repo ? `${repo.host}/${repo.owner}/${repo.repo}` : null;+ const study = useRepoStudyConfig({ enabled: Boolean(repo && learn), resetKey: repoKey });- const repoKey = repo ? `${repo.owner}/${repo.repo}` : null;const options = useMemo(() => ({ malwareScan, learn }), [malwareScan, learn]);const setters = { malwareScan: setMalwareScan, learn: setLearn };- useEffect(() => {- setStudyContext('');- setProviderOverride({ providerId: '', model: '', effort: '' });- }, [repoKey]);-- useEffect(() => {- if (!repo || !learn || typeof api.getApps !== 'function') return;- api.getApps({ silent: true }).then((apps) => {- const eligible = (Array.isArray(apps) ? apps : [])- .filter(app => app?.id && app.repoPath && !app.archived)- .sort((a, b) => (a.id === PORTOS_APP_ID ? -1 : b.id === PORTOS_APP_ID ? 1 : a.name.localeCompare(b.name)));- if (eligible.length) {- setManagedApps(eligible);- setTargetAppId(current => eligible.some(app => app.id === current) ? current : eligible[0].id);- }- }).catch(() => {});- }, [repo, learn]);-return {+ ...study,repo,options,- managedApps,- targetAppId,- setTargetAppId,- studyContext,- setStudyContext,- providers,- activeProviderId,- providerOverride,- setProviderOverride: (patch) => setProviderOverride(current => ({ ...current, ...patch })),toggle: (key) => setters[key](v => !v),- intakeFor: (submitted) => (capturedGitHubRepo(submitted)- ? { ...options, ...(learn ? {- targetAppId,- ...(studyContext.trim() ? { studyContext: studyContext.trim() } : {}),- ...(providerOverride.providerId ? { providerId: providerOverride.providerId } : {}),- ...(providerOverride.model ? { model: providerOverride.model } : {}),- ...(providerOverride.effort ? { effort: providerOverride.effort } : {}),- } : {}) }+ intakeFor: (submitted) => (capturedRepo(submitted)+ ? { ...options, ...(learn ? study.studyPayload() : {}) }: undefined),};}diff --git a/client/src/hooks/useRepoStudyConfig.js b/client/src/hooks/useRepoStudyConfig.jsnew file mode 100644index 0000000000..161a71b19b--- /dev/null+++ b/client/src/hooks/useRepoStudyConfig.js@@ -0,0 +1,82 @@+import { useEffect, useState } from 'react';+import useProviderModels from './useProviderModels.js';+import * as api from '../services/api.js';+import { PORTOS_APP_ID } from '../lib/appIdentity.js';++/**+ * The knobs a `repo-study` dispatch takes: which managed app's tracker receives+ * the issues, the free-form brief telling the agent what to look for, and an+ * optional provider/model/effort pin for that one run.+ *+ * Shared by both callers so the two forms can't drift: the capture boxes'+ * "study for app ideas" checkbox (through `useRepoIntake`) and the Links tab's+ * on-demand "Update & study" button. Rendering lives in+ * `components/brain/RepoStudyFields.jsx`, which takes what this returns.+ *+ * @param {object} [options]+ * @param {boolean} [options.enabled] false parks the hook — no provider or app+ * fetch — for a form that is currently collapsed or irrelevant.+ * @param {string|null} [options.resetKey] changing it clears the brief and the+ * provider pin, so a form re-aimed at a different repo doesn't inherit the+ * previous one's context.+ * @param {string} [options.initialStudyContext] pre-fills the brief (the Links+ * tab opens the form with the brief the last study was given).+ */+export function useRepoStudyConfig({ enabled = true, resetKey = null, initialStudyContext = '' } = {}) {+ const { providers, activeProviderId } = useProviderModels({+ allowDefault: true,+ silent: true,+ withEffort: true,+ enabled,+ });+ const [managedApps, setManagedApps] = useState([{ id: PORTOS_APP_ID, name: 'PortOS' }]);+ const [targetAppId, setTargetAppId] = useState(PORTOS_APP_ID);+ const [studyContext, setStudyContext] = useState(initialStudyContext);+ const [providerOverride, setProviderOverride] = useState({ providerId: '', model: '', effort: '' });++ useEffect(() => {+ setStudyContext(initialStudyContext);+ setProviderOverride({ providerId: '', model: '', effort: '' });+ // `initialStudyContext` is deliberately NOT a dependency: it seeds the field+ // once per target, and re-running on every render would fight the user's own+ // edits.+ }, [resetKey]);++ useEffect(() => {+ if (!enabled || typeof api.getApps !== 'function') return;+ api.getApps({ silent: true }).then((apps) => {+ const eligible = (Array.isArray(apps) ? apps : [])+ .filter(app => app?.id && app.repoPath && !app.archived)+ .sort((a, b) => (a.id === PORTOS_APP_ID ? -1 : b.id === PORTOS_APP_ID ? 1 : a.name.localeCompare(b.name)));+ if (eligible.length) {+ setManagedApps(eligible);+ setTargetAppId(current => eligible.some(app => app.id === current) ? current : eligible[0].id);+ }+ }).catch(() => {});+ }, [enabled]);++ return {+ managedApps,+ targetAppId,+ setTargetAppId,+ studyContext,+ setStudyContext,+ providers,+ activeProviderId,+ providerOverride,+ setProviderOverride: (patch) => setProviderOverride(current => ({ ...current, ...patch })),+ /**+ * The study fields to send. Empty selections are the "use the configured+ * default" sentinel and are omitted rather than sent as empty strings.+ */+ studyPayload: () => ({+ targetAppId,+ ...(studyContext.trim() ? { studyContext: studyContext.trim() } : {}),+ ...(providerOverride.providerId ? { providerId: providerOverride.providerId } : {}),+ ...(providerOverride.model ? { model: providerOverride.model } : {}),+ ...(providerOverride.effort ? { effort: providerOverride.effort } : {}),+ }),+ };+}++export default useRepoStudyConfig;diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex d7d3c3d50f..f105c3b016 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -123,7 +123,7 @@ grep -i "what you want to do" client/src/lib/README.md| `downloadBlob.js` | `downloadBlob(data, filename, type?)` — trigger a browser "Save as…" for a Blob / ArrayBuffer / typed array / string, with object-URL + temporary `<a>` cleanup. Use instead of inlining `URL.createObjectURL` + `<a download>`. || `extensionErrors.js` | `isExtensionError(payload)` — true when an error report came from a browser extension's injected content script rather than from PortOS, so `clientErrorReporter` can drop it instead of spending its 1/sec throttle slot on an error we can't fix. Client mirror of the authoritative `server/lib/extensionErrors.js` (parity enforced by `server/lib/extensionErrors.mirror.test.js`); the server re-checks, since a long-lived tab can still be running an old bundle. || `genUtils.js` | Shared bits between Image Gen and Video Gen pages. |-| `githubRepoUrl.js` | `parseGitHubUrl(url)` / `isGitHubRepoUrl(url)` — client mirror of the authoritative `server/lib/githubRepoUrl.js` (parity enforced by `server/lib/githubRepoUrl.mirror.test.js`). The Brain capture boxes use it to tell the user a bare repo URL will be cloned and to reveal the post-clone agent options (malware scan / learn-from-repo). |+| `repoUrl.js` | `parseRepoUrl(url)` / `isRepoUrl(url)` / `parseGitHubUrl(url)` / `isGitHubRepoUrl(url)` — client mirror of the authoritative `server/lib/repoUrl.js` (parity enforced by `server/lib/repoUrl.mirror.test.js`), covering github.com and gitlab.com. The Brain capture boxes use it to tell the user a bare repo URL will be cloned and to reveal the post-clone agent options (malware scan / learn-from-repo). || `healthProvenance.js` | `PROVENANCE_LEVELS` / `getProvenanceLevel(level)` — the `data-backed`/`inferred`/`experimental`/`speculative` trust taxonomy (label, tone, description, "what would change this?" copy) behind the `ProvenanceChip` source-style chips on MeatSpace / genome / death-clock / longevity views. Pure data; the chip component maps tone→color and id→icon. || `joinInfluenceList.js` | Mirror of `joinInfluenceList` in server universe builder. || `kanbanColumns.js` | `bucketTickets` / `ticketInColumn` / `columnConfig` / `FALLBACK_COLUMNS` — pure column logic for the Jira Kanban board (`components/KanbanBoard.jsx`). Buckets tickets into resolved workflow columns (by status name, or statusCategory for the fallback board), assigns each column a stable unique `id` (Jira `name` is not unique — same-named columns map to different statuses), appends an orphan column for any unmatched status, and precomputes per-column Tailwind color config (Blocked→red, Review/QA→purple, else by category). |diff --git a/client/src/lib/githubRepoUrl.js b/client/src/lib/githubRepoUrl.jsdeleted file mode 100644index e2e6c6989f..0000000000--- a/client/src/lib/githubRepoUrl.js+++ /dev/null@@ -1,72 +0,0 @@-/**- * GitHub repository URL parsing — MIRROR of `server/lib/githubRepoUrl.js`- * (authoritative there).- *- * The Brain capture boxes preview what the server will do with a bare URL: a- * GitHub repo gets cloned, which unlocks the post-clone agent options (malware- * scan / learn-from-repo). A looser client offers those options for a URL the- * server files as a plain bookmark; a tighter one hides them for a repo that- * will in fact be cloned.- *- * Port any change from the server copy verbatim; parity is enforced by- * `server/lib/githubRepoUrl.mirror.test.js`.- */--// The owner/repo pair is a PATH OPERAND, not just a label: githubCloner clones-// into `join(reposDir, owner, repo)` and the resulting `localPath` is later-// handed to an agent as the directory to scan/study. So both segments are-// matched against the character sets GitHub actually allows, NOT "anything but-// a slash" — the loose form parsed `https://github.com/../evil` as owner `..`,-// which resolves OUTSIDE the managed clone root.-// owner: a GitHub login — alphanumeric with internal hyphens, no dots-// repo: alphanumerics plus `_`, `.`, `-`-const OWNER = '[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?';-const REPO = '[A-Za-z0-9_.-]+';--// SSH remote: [email protected]:owner/repo(.git)-const SSH_REPO_RE = new RegExp(`^git@github\\.com:(${OWNER})/(${REPO})$`, 'i');--// Any scheme (or none), optional userinfo, optional www: github.com/owner/repo[.git][/...]-// Anchored at the host so `https://evil.com/github.com/o/r` is NOT read as a-// GitHub repo. `REPO` cannot cross `/`, `?`, or `#`, so a deep link like-// `github.com/o/r/tree/main` still resolves to `o/r`.-const HTTPS_REPO_RE = new RegExp(- `^(?:[A-Za-z][A-Za-z0-9+.-]*://)?(?:[^/@\\s]+@)?(?:www\\.)?github\\.com/(${OWNER})/(${REPO})`,- 'i',-);--// `REPO`'s character class admits the dot segments `.` and `..`, which would-// escape (or collapse to) the clone root the same way a bad owner does. The-// owner pattern already rejects them by requiring a leading alphanumeric.-const DOT_SEGMENTS = new Set(['.', '..']);--/**- * Parse a GitHub URL into `{ owner, repo, isGitHub }`, or null when the URL- * isn't a GitHub repository (or names a path-unsafe owner/repo).- *- * @param {string} url- * @returns {{ owner: string, repo: string, isGitHub: true } | null}- */-export function parseGitHubUrl(url) {- if (!url) return null;- const normalized = String(url).trim();-- const match = normalized.match(SSH_REPO_RE) || normalized.match(HTTPS_REPO_RE);- if (!match) return null;-- const owner = match[1];- const repo = match[2].replace(/\.git$/i, '');- if (!repo || DOT_SEGMENTS.has(repo)) return null;-- return { owner, repo, isGitHub: true };-}--/**- * True when the URL points at a GitHub repository.- *- * @param {string} url- * @returns {boolean}- */-export function isGitHubRepoUrl(url) {- return parseGitHubUrl(url) !== null;-}diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex e3b70235ca..5b174c7b4f 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -95,7 +95,7 @@ export * from './dndTransform.js';export * from './downloadBlob.js';export * from './extensionErrors.js';export * from './genUtils.js';-export * from './githubRepoUrl.js';+export * from './repoUrl.js';export * from './healthProvenance.js';export * from './joinInfluenceList.js';export * from './kanbanColumns.js';diff --git a/client/src/lib/repoUrl.js b/client/src/lib/repoUrl.jsnew file mode 100644index 0000000000..6ce71ff85d--- /dev/null+++ b/client/src/lib/repoUrl.js@@ -0,0 +1,144 @@+/**+ * Git repository URL parsing — MIRROR of `server/lib/repoUrl.js`+ * (authoritative there).+ *+ * The Brain capture boxes preview what the server will do with a bare URL: a+ * github.com / gitlab.com repo gets cloned, which unlocks the post-clone agent+ * options (malware scan / learn-from-repo). A looser client offers those options+ * for a URL the server files as a plain bookmark; a tighter one hides them for a+ * repo that will in fact be cloned.+ *+ * Port any change from the server copy verbatim; parity is enforced by+ * `server/lib/repoUrl.mirror.test.js`.+ */++// The host allowlist. `provider` is the stable id stored on a link record+// (`repoHost` holds the hostname itself), so adding a host here is the only+// change needed to clone from it — everything downstream is host-generic.+export const REPO_HOSTS = Object.freeze({+ 'github.com': 'github',+ 'gitlab.com': 'gitlab',+});++// The owner/repo pair is a PATH OPERAND, not just a label: the cloner clones+// into `join(reposDir, …owner, repo)` and the resulting `localPath` is later+// handed to an agent as the directory to scan/study. So every segment is+// matched against the character sets the hosts actually allow, NOT "anything+// but a slash" — the loose form parsed `https://github.com/../evil` as owner+// `..`, which resolves OUTSIDE the managed clone root.+// owner: a login (or a GitLab group/subgroup) — alphanumeric with internal+// hyphens, no dots, so no segment can ever be `.` or `..`+// repo: alphanumerics plus `_`, `.`, `-`+const OWNER_RE = /^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/;+const REPO_RE = /^[A-Za-z0-9_.-]+$/;++// `REPO_RE`'s character class admits the dot segments `.` and `..`, which would+// escape (or collapse to) the clone root the same way a bad owner does. The+// owner pattern already rejects them by requiring a leading alphanumeric.+const DOT_SEGMENTS = new Set(['.', '..']);++// SSH remote: git@host:path (optionally `ssh://git@host/path`).+const SSH_RE = /^(?:ssh:\/\/)?git@([^:/\s]+)[:/](\S+)$/i;++// Any scheme (or none), optional userinfo: host[:port][/path]. Anchored at the+// host so `https://evil.com/github.com/o/r` is NOT read as a GitHub repo, and+// whitespace-free end-to-end so `github.com/a b/c` is rejected outright.+const HTTP_RE = /^(?:[A-Za-z][A-Za-z0-9+.-]*:\/\/)?(?:[^/@\s]+@)?([^/?#\s]+)(\/\S*)?$/;++// Path words that begin a host's own UI route rather than another namespace+// segment. GitLab's modern deep links use the `/-/` separator (handled+// separately), but its legacy links — and every GitHub deep link — put the+// route word directly after the project, so the segment walk stops here.+const RESERVED_PATH_SEGMENTS = new Set([+ 'tree', 'blob', 'raw', 'commit', 'commits', 'compare', 'branches', 'tags',+ 'releases', 'issues', 'pull', 'pulls', 'merge_requests', 'wiki', 'wikis',+ 'actions', 'pipelines', 'settings', 'activity', 'network', 'graphs', 'blame',+]);++/**+ * Parse a repository URL into `{ host, provider, owner, repo, isGitHub }`, or+ * null when the URL isn't a repository on a supported host (or names a+ * path-unsafe owner/repo).+ *+ * `owner` is a single login on GitHub and may be a `group/subgroup` path on+ * GitLab; every one of its segments is validated, so it stays path-safe.+ *+ * @param {string} url+ * @returns {{ host: string, provider: string, owner: string, repo: string, isGitHub: boolean } | null}+ */+export function parseRepoUrl(url) {+ if (!url) return null;+ const normalized = String(url).trim();++ const match = normalized.match(SSH_RE) || normalized.match(HTTP_RE);+ if (!match) return null;++ const host = match[1].toLowerCase().replace(/^www\./, '').replace(/:\d+$/, '');+ const provider = REPO_HOSTS[host];+ if (!provider) return null;++ // Drop the query/hash, then GitLab's `/-/` deep-link separator, then walk the+ // remaining segments until a host UI route word.+ let path = (match[2] || '').split(/[?#]/)[0].replace(/^\//, '');+ const dashIndex = path.indexOf('/-/');+ if (dashIndex !== -1) path = path.slice(0, dashIndex);++ const segments = [];+ for (const segment of path.split('/')) {+ if (!segment) continue;+ if (RESERVED_PATH_SEGMENTS.has(segment.toLowerCase())) break;+ segments.push(segment);+ }+ if (segments.length < 2) return null;++ // GitHub has no subgroups: anything past owner/repo is a deep link. GitLab+ // nests groups arbitrarily, so everything before the last segment is the+ // namespace.+ const ownerSegments = provider === 'github' ? segments.slice(0, 1) : segments.slice(0, -1);+ const repo = (provider === 'github' ? segments[1] : segments[segments.length - 1])+ .replace(/\.git$/i, '');++ if (!ownerSegments.every(segment => OWNER_RE.test(segment))) return null;+ if (!repo || DOT_SEGMENTS.has(repo) || !REPO_RE.test(repo)) return null;++ return {+ host,+ provider,+ owner: ownerSegments.join('/'),+ repo,+ isGitHub: provider === 'github',+ };+}++/**+ * True when the URL points at a repository on a supported host.+ *+ * @param {string} url+ * @returns {boolean}+ */+export function isRepoUrl(url) {+ return parseRepoUrl(url) !== null;+}++/**+ * Parse a URL only when it is a GitHub repository. The GitHub-only callers are+ * the ones whose downstream really is GitHub-specific (the Eidoverse worlds+ * repo, which is pushed to with a GitHub token), NOT the Brain's repo capture.+ *+ * @param {string} url+ * @returns {{ owner: string, repo: string, isGitHub: true } | null}+ */+export function parseGitHubUrl(url) {+ const parsed = parseRepoUrl(url);+ return parsed?.isGitHub ? { owner: parsed.owner, repo: parsed.repo, isGitHub: true } : null;+}++/**+ * True when the URL points at a GitHub repository specifically.+ *+ * @param {string} url+ * @returns {boolean}+ */+export function isGitHubRepoUrl(url) {+ return parseGitHubUrl(url) !== null;+}diff --git a/client/src/services/apiBrain.js b/client/src/services/apiBrain.jsindex c1a044ada9..1fe9e02892 100644--- a/client/src/services/apiBrain.js+++ b/client/src/services/apiBrain.js@@ -222,7 +222,7 @@ export const runBrainReview = (providerOverride, modelOverride, options = {}) =>export const getBrainLinks = (options = {}) => {const params = new URLSearchParams();if (options.linkType) params.set('linkType', options.linkType);- if (options.isGitHubRepo !== undefined) params.set('isGitHubRepo', options.isGitHubRepo);+ if (options.isRepo !== undefined) params.set('isRepo', options.isRepo);if (options.limit) params.set('limit', options.limit);if (options.offset) params.set('offset', options.offset);return request(`/brain/links?${params}`);@@ -251,6 +251,14 @@ export const cloneBrainLink = (id, options = {}) => request(`/brain/links/${id}/export const pullBrainLink = (id, options = {}) => request(`/brain/links/${id}/pull`, { method: 'POST', ...options });export const openBrainLinkFolder = (id, options = {}) => request(`/brain/links/${id}/open-folder`, { method: 'POST', ...options });export const scanBrainLink = (id, options = {}) => request(`/brain/links/${id}/scan`, { method: 'POST', ...options });+// Refresh the clone (unless `pull: false`) and queue a fresh repo-study run with+// the brief in `studyContext` — the on-demand twin of the capture-time+// "study for app ideas" checkbox.+export const studyBrainLink = (id, data = {}, options = {}) => request(`/brain/links/${id}/study`, {+ method: 'POST',+ body: JSON.stringify(data),+ ...options+});export const brainScanReportPath = (id) => `/brain/links/${encodeURIComponent(id)}/scan-report`;export const getBrainScanReport = (id, options = {}) => request(`/brain/links/${encodeURIComponent(id)}/scan-report`, {responseType: 'text',diff --git a/docs/API.md b/docs/API.mdindex 707a250646..6b50c76deb 100644--- a/docs/API.md+++ b/docs/API.md@@ -397,9 +397,11 @@ backward-compatible historical snapshot/introspection endpoints.| POST | `/brain/links` | Save a new link || PUT | `/brain/links/:id` | Update link || DELETE | `/brain/links/:id` | Delete link |-| POST | `/brain/links/:id/clone` | Clone GitHub repo |+| POST | `/brain/links/:id/clone` | Clone repository (github.com / gitlab.com) || POST | `/brain/links/:id/pull` | Pull updates for cloned repo || POST | `/brain/links/:id/open-folder` | Open cloned repo in file manager |+| POST | `/brain/links/:id/scan` | Queue a read-only malware/risk scan of the clone |+| POST | `/brain/links/:id/study` | Refresh the clone and queue a repo study with a caller-supplied brief |### File Uploadsdiff --git a/docs/features/product-surfaces.md b/docs/features/product-surfaces.mdindex 045c4b4abc..a11540ff60 100644--- a/docs/features/product-surfaces.md+++ b/docs/features/product-surfaces.md@@ -4,7 +4,7 @@ PortOS is a local-first operating system for a developer's machines, work, and pThis document is the **canonical user-facing feature inventory** for PortOS. It serves three primary functions:1. **User & Contributor Orientation**: A comprehensive map of every major surface, route, and capability in PortOS.-2. **Autonomous Repo-Study Reference**: The canonical baseline consumed by the `repo-study` task (`server/services/repoIntake.js`) when studying external GitHub repositories to map new capabilities, enhancements, and UX patterns onto PortOS.+2. **Autonomous Repo-Study Reference**: The canonical baseline consumed by the `repo-study` task (`server/services/repoIntake.js`) when studying external repositories (github.com / gitlab.com) to map new capabilities, enhancements, and UX patterns onto PortOS.3. **Architecture & Guide Index**: Quick pointers to dedicated feature deep dives in `docs/features/` and root architectural guides in `docs/`.---diff --git a/scripts/migrations/328-brain-link-repo-fields.js b/scripts/migrations/328-brain-link-repo-fields.jsnew file mode 100644index 0000000000..0d7986f49d--- /dev/null+++ b/scripts/migrations/328-brain-link-repo-fields.js@@ -0,0 +1,76 @@+/**+ * Rename the Brain link repository fields from their GitHub-only shape to the+ * host-generic one, now that PortOS clones gitlab.com as well as github.com.+ *+ * isGitHubRepo → isRepo (the legacy key is KEPT, see below)+ * gitHubOwner → repoOwner+ * gitHubRepo → repoName+ * linkType 'github' → 'repo'+ * + repoHost: 'github.com'+ *+ * Every link this migration touches was captured before multi-host support+ * existed, so its host can only be github.com — the legacy fields had no way to+ * express anything else.+ *+ * The legacy keys are deliberately LEFT IN PLACE rather than deleted. PortOS is+ * distributed: brain links federate verbatim, and a peer still on older code+ * reads `isGitHubRepo` to decide a link is a clonable repo. Dropping the key+ * here would demote every shared repo to a plain bookmark on that peer. New+ * writes keep both shapes for the same reason (`lib/repoLinkFields.js`), and a+ * later migration can retire the legacy half once no supported peer reads it.+ *+ * Idempotent: a record that already carries `isRepo` is skipped, so a re-run+ * after a partial pass finishes the remainder without rewriting the rest.+ */++import { readdir, readFile } from 'fs/promises';+import { join } from 'path';+import { writeJsonAtomic } from './_lib.js';++const LABEL = 'migration 328';++/** The upgraded record, or null when nothing needs to change. */+export function upgradeLinkRecord(record) {+ if (!record || typeof record !== 'object') return null;+ // Tombstones carry no link fields, and a record already in the new shape is+ // done — including one written by a newer peer that reached this install+ // before the migration ran.+ if (record._deleted || record.isRepo !== undefined) return null;+ if (!record.isGitHubRepo) return null;++ return {+ ...record,+ isRepo: true,+ repoHost: 'github.com',+ repoOwner: record.gitHubOwner ?? null,+ repoName: record.gitHubRepo ?? null,+ ...(record.linkType === 'github' ? { linkType: 'repo' } : {}),+ };+}++export default {+ async up({ rootDir }) {+ const linksDir = join(rootDir, 'data', 'brain', 'links');+ const entries = await readdir(linksDir, { withFileTypes: true })+ .catch(err => (err.code === 'ENOENT' ? [] : Promise.reject(err)));++ let updated = 0;+ for (const entry of entries) {+ if (!entry.isDirectory()) continue;+ const path = join(linksDir, entry.name, 'index.json');+ // A record that is missing or unreadable is left exactly as it is — this+ // migration is a field rename, not a repair pass.+ const record = await readFile(path, 'utf8')+ .then(JSON.parse)+ .catch(() => null);+ const upgraded = upgradeLinkRecord(record);+ if (!upgraded) continue;+ await writeJsonAtomic(path, upgraded);+ updated += 1;+ }++ if (updated === 0) return { updated: 0, reason: 'already-applied' };+ console.log(`🔗 ${LABEL}: renamed repository fields on ${updated} brain link(s).`);+ return { updated };+ },+};diff --git a/scripts/migrations/328-brain-link-repo-fields.test.js b/scripts/migrations/328-brain-link-repo-fields.test.jsnew file mode 100644index 0000000000..9602b39a27--- /dev/null+++ b/scripts/migrations/328-brain-link-repo-fields.test.js@@ -0,0 +1,96 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import migration from './328-brain-link-repo-fields.js';++const writeJson = (path, value) => writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`);+const readJson = (path) => JSON.parse(readFileSync(path, 'utf8'));++describe('migration 328 — brain link repository fields', () => {+ let rootDir;+ let linksDir;++ const writeLink = (id, record) => {+ mkdirSync(join(linksDir, id), { recursive: true });+ writeJson(join(linksDir, id, 'index.json'), record);+ };+ const readLink = (id) => readJson(join(linksDir, id, 'index.json'));++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-328-'));+ linksDir = join(rootDir, 'data', 'brain', 'links');+ mkdirSync(linksDir, { recursive: true });+ });++ afterEach(() => rmSync(rootDir, { recursive: true, force: true }));++ it('does nothing on an install with no brain links directory', async () => {+ rmSync(join(rootDir, 'data'), { recursive: true, force: true });+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'already-applied' });+ });++ it('renames the GitHub-only fields and keeps the legacy mirror for older peers', async () => {+ writeLink('link-a', {+ id: 'link-a',+ url: 'https://github.com/example-owner/example-repo',+ linkType: 'github',+ isGitHubRepo: true,+ gitHubOwner: 'example-owner',+ gitHubRepo: 'example-repo',+ localPath: '/repos/example-owner/example-repo',+ });++ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 1 });++ expect(readLink('link-a')).toMatchObject({+ linkType: 'repo',+ isRepo: true,+ repoHost: 'github.com',+ repoOwner: 'example-owner',+ repoName: 'example-repo',+ // Federation compatibility: a peer on older code still reads these.+ isGitHubRepo: true,+ gitHubOwner: 'example-owner',+ gitHubRepo: 'example-repo',+ localPath: '/repos/example-owner/example-repo',+ });+ });++ it('leaves plain bookmarks, tombstones, and already-migrated records untouched', async () => {+ writeLink('bookmark', { id: 'bookmark', url: 'https://example.com', linkType: 'article', isGitHubRepo: false });+ writeLink('gone', { id: 'gone', _deleted: true, updatedAt: '2026-01-01T00:00:00.000Z' });+ writeLink('fresh', {+ id: 'fresh',+ url: 'https://gitlab.com/example-group/example-repo',+ linkType: 'repo',+ isRepo: true,+ repoHost: 'gitlab.com',+ repoOwner: 'example-group',+ repoName: 'example-repo',+ isGitHubRepo: false,+ });++ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'already-applied' });++ expect(readLink('bookmark')).not.toHaveProperty('isRepo');+ expect(readLink('gone')).toEqual({ id: 'gone', _deleted: true, updatedAt: '2026-01-01T00:00:00.000Z' });+ expect(readLink('fresh')).toMatchObject({ repoHost: 'gitlab.com', isRepo: true });+ });++ it('is idempotent across a re-run', async () => {+ writeLink('link-a', {+ id: 'link-a',+ url: 'https://github.com/example-owner/example-repo',+ linkType: 'github',+ isGitHubRepo: true,+ gitHubOwner: 'example-owner',+ gitHubRepo: 'example-repo',+ });++ await migration.up({ rootDir });+ const afterFirst = readLink('link-a');+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'already-applied' });+ expect(readLink('link-a')).toEqual(afterFirst);+ });+});diff --git a/server/lib/README.md b/server/lib/README.mdindex 1d310a8156..1b1bf9060f 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -275,7 +275,8 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `gitForge.js` | `parseGitRemote`, `parseGitHubOwnerFromRemote`, `pickGhAccountForOwner`, `detectForgeCli`, `parsePullRequestUrl` — pure GitHub/GitLab remote + PR/MR URL parsers and forge/account selectors used by `git.js`. || `gitOutputParsers.js` | `parseStatus`, `parseDiffStat`, `parseBranchVerboseLine`, `parseSubmoduleStatusLine`/`SUBMODULE_STATUS_RE`, `extractAgentSummary` — pure parsers turning git command output into structured data for `git.js`. `extractAgentSummary` anchors on `agentOutputMarkers`' completion marker so a TUI agent's PR body carries its sentinel summary, not the lifecycle telemetry above it. `isBenignConcurrentFetchRefRace(stderr)` reads a non-zero `git fetch` as a SUCCESS when its only failure is a lost compare-and-swap whose refs already hold the fetched commits — the routine outcome when the Git tab, `getRemoteBranches`, and CoS agent worktrees fetch one `.git` at once. || `gitRemote.js` | `getOriginInfo`, `classifyOriginRemote`, `parseGitRemoteUrl`, `readRemoteUrl`, `UPSTREAM_OWNER`/`UPSTREAM_REPO` — safely reads and classifies checkout remotes against PortOS or a caller-supplied canonical upstream. Used by self-update and managed integrations to detect forks. |-| `githubRepoUrl.js` | `parseGitHubUrl(url)` → `{ owner, repo }` / `isGitHubRepoUrl(url)` — authoritative "is this a clonable GitHub repo URL?" rule, re-exported by `services/githubCloner.js`. Mirrored to `client/src/lib/githubRepoUrl.js` (parity pinned by `githubRepoUrl.mirror.test.js`) so the Brain capture boxes reveal the post-clone agent options for exactly the URLs the server will clone. |+| `repoLinkFields.js` | `deriveRepoLinkFields(url)` / `normalizeRepoLinkFields(link)` / `linkIsRepo(link)` / `repoLinkLabel(link)` — the repository metadata a Brain link carries, plus the dual-write/tolerant-read shim that keeps the pre-multi-host `isGitHubRepo` field names readable across federated peers. |+| `repoUrl.js` | `parseRepoUrl(url)` → `{ host, provider, owner, repo, isGitHub }` / `isRepoUrl(url)` / `repoCloneUrl(parsed)` / `parseGitHubUrl(url)` / `isGitHubRepoUrl(url)` — authoritative "is this a clonable repo URL?" rule for github.com and gitlab.com, re-exported by `services/repoCloner.js`. Mirrored to `client/src/lib/repoUrl.js` (parity pinned by `repoUrl.mirror.test.js`) so the Brain capture boxes reveal the post-clone agent options for exactly the URLs the server will clone. || `glabArgs.js` | `GLAB_JSON_ARGS`, `withGlabJson(args)` — pure `glab` argv conventions. The JSON output flag is `--output json`, NOT `-F json`: on `glab issue list` (and only there) `-F` is `--output-format` (details/ids/urls), so `-F json` is accepted, ignored, and answers with the human table at exit 0. Shared by all three `glab` runners so the spelling has one definition; guarded tree-wide by `services/gitlab.glabFlags.test.js`. || `killWithEscalation.js` | `killWithEscalation(proc, {label, stillRunning, delayMs=8000})` — shared SIGTERM→grace→SIGKILL cancel-escalation for spawn-based media jobs. Sends SIGTERM, then escalates to SIGKILL after `delayMs` only when `stillRunning()` holds and the child hasn't exited (`exitCode===null && signalCode===null`). The timer is unref'd and the callback is try/catch-wrapped (runs outside the request lifecycle). Converges musicVideo/render, videoTimeline, imageGen local+codex, videoGen, loraTraining, and the yt-dlp track import cancel paths. || `processEnv.js` | `stripDebugMallocEnv(env)` / `safeChildProcessEnv(extra)` — drop macOS `Malloc*` debug env vars before spawning a child. `safeChildProcessOptions(options)` adds that sanitized environment plus `windowsHide: true`, preventing detached PM2 subprocesses from opening transient Windows console UI; `buildSafeCliBaseEnv(env, provider)` allowlists runtime/delivery essentials and only the selected CLI's ambient provider auth before an AI CLI inherits the server environment. Route Node→Python and other background CLI spawns through the process helpers. Also `whichFirst(name)` — first-hit `which`/`where` PATH probe (safe options, 5s timeout) returning the absolute binary path or `null`; `whichFirstSync(name)` provides the same contract without the await; `findCommandOnPath(name, { env, cwd })` resolves an executable from the exact child environment without needing `which` itself on that PATH. |diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.jsonindex 2493d0edca..c2a0554456 100644--- a/server/lib/apiRouteCatalog.generated.json+++ b/server/lib/apiRouteCatalog.generated.json@@ -2148,7 +2148,7 @@"sources": [{"source": "server/routes/brainLinks.js",- "line": 300+ "line": 340}]},@@ -2159,7 +2159,7 @@"sources": [{"source": "server/routes/brainLinks.js",- "line": 310+ "line": 350}]},@@ -2170,7 +2170,7 @@"sources": [{"source": "server/routes/brainLinks.js",- "line": 349+ "line": 389}]},@@ -2181,7 +2181,7 @@"sources": [{"source": "server/routes/brainLinks.js",- "line": 334+ "line": 374}]},@@ -2192,7 +2192,7 @@"sources": [{"source": "server/routes/brainLinks.js",- "line": 322+ "line": 362}]},@@ -2698,7 +2698,7 @@"sources": [{"source": "server/routes/brainLinks.js",- "line": 37+ "line": 39}]},@@ -2709,7 +2709,7 @@"sources": [{"source": "server/routes/brainLinks.js",- "line": 89+ "line": 91}]},@@ -2720,7 +2720,7 @@"sources": [{"source": "server/routes/brainLinks.js",- "line": 153+ "line": 152}]},@@ -2731,7 +2731,7 @@"sources": [{"source": "server/routes/brainLinks.js",- "line": 77+ "line": 79}]},@@ -2742,7 +2742,7 @@"sources": [{"source": "server/routes/brainLinks.js",- "line": 113+ "line": 115}]},@@ -2753,7 +2753,7 @@"sources": [{"source": "server/routes/brainLinks.js",- "line": 165+ "line": 164}]},@@ -2764,7 +2764,7 @@"sources": [{"source": "server/routes/brainLinks.js",- "line": 221+ "line": 220}]},@@ -2775,7 +2775,7 @@"sources": [{"source": "server/routes/brainLinks.js",- "line": 200+ "line": 199}]},@@ -2786,7 +2786,7 @@"sources": [{"source": "server/routes/brainLinks.js",- "line": 251+ "line": 250}]},@@ -2797,7 +2797,18 @@"sources": [{"source": "server/routes/brainLinks.js",- "line": 280+ "line": 320+ }+ ]+ },+ {+ "method": "POST",+ "path": "/api/brain/links/:id/study",+ "mountPath": "/api/brain",+ "sources": [+ {+ "source": "server/routes/brainLinks.js",+ "line": 286}]},@@ -2808,7 +2819,7 @@"sources": [{"source": "server/routes/brainLinks.js",- "line": 53+ "line": 55}]},@@ -23842,8 +23853,8 @@],"stats": {"mounts": 147,- "operations": 2151,- "declarations": 2154,+ "operations": 2152,+ "declarations": 2155,"sourceFiles": 229}}diff --git a/server/lib/brainValidation.js b/server/lib/brainValidation.jsindex 64d52c48b3..9a72bb3fbc 100644--- a/server/lib/brainValidation.js+++ b/server/lib/brainValidation.js@@ -207,6 +207,16 @@ export const repoIntakeSchema = z.object(optionalBooleanMap(REPO_INTAKE_KEYS)).e});const repoIntakeInputSchema = repoIntakeSchema.optional();+/**+ * Body of `POST /api/brain/links/:id/study` — an on-demand re-study of an+ * already-cloned repo. Same study knobs as the capture-time opt-in (that is the+ * point: the client renders one shared form for both), minus the action+ * booleans, plus `pull` so the user can refresh the clone in the same click.+ */+export const linkStudyInputSchema = repoIntakeSchema+ .omit(Object.fromEntries(REPO_INTAKE_KEYS.map(key => [key, true])))+ .extend({ pull: z.boolean().optional().default(true) });+// Capture input schemaexport const captureInputSchema = z.object({text: z.string().min(1).max(10000),@@ -428,8 +438,10 @@ export const reviewOutputSchema = z.object({// LINKS SCHEMAS// =============================================================================-// Link type enum-export const linkTypeEnum = z.enum(['github', 'article', 'documentation', 'tool', 'reference', 'other']);+// Link type enum. `github` predates multi-host repo support and is retained so+// links stored (or federated from a peer) before migration 328 still validate;+// `repo` is what new links are written with.+export const linkTypeEnum = z.enum(['repo', 'github', 'article', 'documentation', 'tool', 'reference', 'other']);// Link Record schemaexport const linkRecordSchema = z.object({@@ -440,10 +452,16 @@ export const linkRecordSchema = z.object({note: z.string().max(2000).optional().default(''),linkType: linkTypeEnum.default('other'),tags: z.array(z.string().max(50)).optional().default([]),- // GitHub-specific fields+ // Repository fields. `repoOwner` may be a GitLab `group/subgroup` path.+ isRepo: z.boolean().default(false),+ repoHost: z.string().max(253).nullable().optional(),+ repoOwner: z.string().max(200).nullable().optional(),+ repoName: z.string().max(100).nullable().optional(),+ // Legacy GitHub-only mirror, still written so a peer on older code keeps+ // recognising a captured GitHub repo — see lib/repoLinkFields.js.isGitHubRepo: z.boolean().default(false),- gitHubOwner: z.string().max(100).optional(),- gitHubRepo: z.string().max(100).optional(),+ gitHubOwner: z.string().max(100).nullable().optional(),+ gitHubRepo: z.string().max(100).nullable().optional(),localPath: z.string().max(500).optional(),cloneStatus: z.enum(['pending', 'cloning', 'cloned', 'failed', 'none']).default('none'),cloneError: z.string().max(500).optional(),@@ -467,7 +485,10 @@ export const linkRecordSchema = z.object({// The queued `repo-study` run, once dispatched.repoStudy: z.object({taskId: z.string().optional(),- queuedAt: z.string().datetime().optional()+ queuedAt: z.string().datetime().optional(),+ // The brief the last study was dispatched with, so the re-study form opens+ // pre-filled instead of blank.+ studyContext: z.string().max(5000).optional()}).optional(),// Bucket grouping (nullable = ungrouped)bucketId: z.string().guid().nullable().optional(),@@ -509,7 +530,7 @@ export const linksQuerySchema = z.object({linkType: linkTypeEnum.optional(),// Query params arrive as strings; z.coerce.boolean() treats any non-empty// string (including "false") as true, so parse the string value explicitly.- isGitHubRepo: z.preprocess(+ isRepo: z.preprocess(v => (typeof v === 'string' ? v === 'true' : v),z.boolean()).optional(),diff --git a/server/lib/brainValidation.test.js b/server/lib/brainValidation.test.jsindex baffcbc203..4fa8a614ab 100644--- a/server/lib/brainValidation.test.js+++ b/server/lib/brainValidation.test.js@@ -511,7 +511,7 @@ describe('brainValidation.js', () => {note: 'Review before sharing with the team',linkType: 'github',tags: ['reference'],- isGitHubRepo: true,+ isRepo: true,gitHubOwner: 'example',gitHubRepo: 'repo',cloneStatus: 'cloned',@@ -624,16 +624,16 @@ describe('brainValidation.js', () => {expect(result.data.offset).toBe(0);});- it('should coerce isGitHubRepo boolean', () => {- const result = linksQuerySchema.safeParse({ isGitHubRepo: 'true' });+ it('should coerce isRepo boolean', () => {+ const result = linksQuerySchema.safeParse({ isRepo: 'true' });expect(result.success).toBe(true);- expect(result.data.isGitHubRepo).toBe(true);+ expect(result.data.isRepo).toBe(true);});it('should coerce the string "false" to false (not true)', () => {- const result = linksQuerySchema.safeParse({ isGitHubRepo: 'false' });+ const result = linksQuerySchema.safeParse({ isRepo: 'false' });expect(result.success).toBe(true);- expect(result.data.isGitHubRepo).toBe(false);+ expect(result.data.isRepo).toBe(false);});it('should filter by linkType', () => {diff --git a/server/lib/githubRepoUrl.js b/server/lib/githubRepoUrl.jsdeleted file mode 100644index 1c5466a1e0..0000000000--- a/server/lib/githubRepoUrl.js+++ /dev/null@@ -1,72 +0,0 @@-/**- * GitHub repository URL parsing — AUTHORITATIVE copy.- *- * Answers "is this URL a GitHub repo we can clone, and which owner/repo is it?"- * Lives in `lib/` (not `services/githubCloner.js`, which re-exports it) because- * the Brain capture boxes have to preview the same answer BEFORE submitting: a- * capture that is a bare GitHub repo URL gets cloned, and the client only offers- * the post-clone agent options (malware scan / learn-from-repo) when it agrees- * with the server about what counts as a repo.- *- * The client mirror is `client/src/lib/githubRepoUrl.js`; parity is enforced by- * `server/lib/githubRepoUrl.mirror.test.js`. Port any change to both.- */--// The owner/repo pair is a PATH OPERAND, not just a label: githubCloner clones-// into `join(reposDir, owner, repo)` and the resulting `localPath` is later-// handed to an agent as the directory to scan/study. So both segments are-// matched against the character sets GitHub actually allows, NOT "anything but-// a slash" — the loose form parsed `https://github.com/../evil` as owner `..`,-// which resolves OUTSIDE the managed clone root.-// owner: a GitHub login — alphanumeric with internal hyphens, no dots-// repo: alphanumerics plus `_`, `.`, `-`-const OWNER = '[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?';-const REPO = '[A-Za-z0-9_.-]+';--// SSH remote: [email protected]:owner/repo(.git)-const SSH_REPO_RE = new RegExp(`^git@github\\.com:(${OWNER})/(${REPO})$`, 'i');--// Any scheme (or none), optional userinfo, optional www: github.com/owner/repo[.git][/...]-// Anchored at the host so `https://evil.com/github.com/o/r` is NOT read as a-// GitHub repo. `REPO` cannot cross `/`, `?`, or `#`, so a deep link like-// `github.com/o/r/tree/main` still resolves to `o/r`.-const HTTPS_REPO_RE = new RegExp(- `^(?:[A-Za-z][A-Za-z0-9+.-]*://)?(?:[^/@\\s]+@)?(?:www\\.)?github\\.com/(${OWNER})/(${REPO})`,- 'i',-);--// `REPO`'s character class admits the dot segments `.` and `..`, which would-// escape (or collapse to) the clone root the same way a bad owner does. The-// owner pattern already rejects them by requiring a leading alphanumeric.-const DOT_SEGMENTS = new Set(['.', '..']);--/**- * Parse a GitHub URL into `{ owner, repo, isGitHub }`, or null when the URL- * isn't a GitHub repository (or names a path-unsafe owner/repo).- *- * @param {string} url- * @returns {{ owner: string, repo: string, isGitHub: true } | null}- */-export function parseGitHubUrl(url) {- if (!url) return null;- const normalized = String(url).trim();-- const match = normalized.match(SSH_REPO_RE) || normalized.match(HTTPS_REPO_RE);- if (!match) return null;-- const owner = match[1];- const repo = match[2].replace(/\.git$/i, '');- if (!repo || DOT_SEGMENTS.has(repo)) return null;-- return { owner, repo, isGitHub: true };-}--/**- * True when the URL points at a GitHub repository.- *- * @param {string} url- * @returns {boolean}- */-export function isGitHubRepoUrl(url) {- return parseGitHubUrl(url) !== null;-}diff --git a/server/lib/index.js b/server/lib/index.jsindex b5128e27fd..69db5e0d63 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -258,7 +258,7 @@ export * from './gitCommitProbe.js';export * from './gitForge.js';export * from './gitOutputParsers.js';export * from './gitRemote.js';-export * from './githubRepoUrl.js';+export * from './repoUrl.js';export * from './glabArgs.js';export * from './goalFeatureMap.js';export * from './interactiveShellResolver.js';@@ -442,6 +442,7 @@ export * from './streamBackpressure.js';export * from './streamingSpawn.js';export * from './sseUtils.js';export * from './repoIntakeActions.js';+export * from './repoLinkFields.js';export * from './tombstones.js';export * from './uploadLimits.js';export * from './userActionTypes.js';diff --git a/server/lib/repoIntakeActions.mirror.test.js b/server/lib/repoIntakeActions.mirror.test.jsindex e5b6bafd83..9c69c6c855 100644--- a/server/lib/repoIntakeActions.mirror.test.js+++ b/server/lib/repoIntakeActions.mirror.test.js@@ -5,7 +5,7 @@* These are the wire contract. Drift is silent in both directions: a key added* server-side is simply never offered in either capture box, and a client-only* key is stripped by the Zod schema and ignored by `normalizeRepoIntake` with no- * error anywhere. Unlike the githubRepoUrl mirror this compares KEYS, not source+ * error anywhere. Unlike the repoUrl mirror this compares KEYS, not source* text — the client half legitimately carries labels, hints, and icons the* server has no business knowing about.*/diff --git a/server/lib/repoLinkFields.js b/server/lib/repoLinkFields.jsnew file mode 100644index 0000000000..2dc7355171--- /dev/null+++ b/server/lib/repoLinkFields.js@@ -0,0 +1,87 @@+/**+ * The repository metadata a Brain link carries, and the compatibility shim that+ * keeps it readable across PortOS versions.+ *+ * The fields used to be GitHub-only (`isGitHubRepo` / `gitHubOwner` /+ * `gitHubRepo`). They are now host-generic (`isRepo` / `repoHost` / `repoOwner`+ * / `repoName`) so gitlab.com repos are first-class, and migration 328 rewrites+ * every stored link.+ *+ * PortOS is DISTRIBUTED and brain links FEDERATE verbatim between peers, so a+ * rename alone would break a mixed-version tailnet in both directions. Hence:+ *+ * - `deriveRepoLinkFields` writes BOTH shapes, so a peer still on the old code+ * keeps recognising a captured GitHub repo. A gitlab.com repo is written+ * with `isGitHubRepo: false` on purpose — an old peer must file it as a+ * plain bookmark rather than hand a GitLab URL to a GitHub-only cloner.+ * - `normalizeRepoLinkFields` fills the new shape from the legacy one on READ,+ * so a record arriving from an old peer (or written before the migration+ * ran) still reads as a repo.+ */++import { parseRepoUrl } from './repoUrl.js';++/** Host assumed for a legacy record, whose fields could only ever be GitHub's. */+const LEGACY_REPO_HOST = 'github.com';++/**+ * The repo fields for a captured URL — new shape plus the legacy mirror.+ *+ * @param {string} url+ * @returns {{ isRepo: boolean, repoHost: string|null, repoOwner: string|null,+ * repoName: string|null, isGitHubRepo: boolean, gitHubOwner: string|null,+ * gitHubRepo: string|null }}+ */+export function deriveRepoLinkFields(url) {+ const parsed = parseRepoUrl(url);+ return {+ isRepo: Boolean(parsed),+ repoHost: parsed?.host ?? null,+ repoOwner: parsed?.owner ?? null,+ repoName: parsed?.repo ?? null,+ isGitHubRepo: Boolean(parsed?.isGitHub),+ gitHubOwner: parsed?.isGitHub ? parsed.owner : null,+ gitHubRepo: parsed?.isGitHub ? parsed.repo : null,+ };+}++/**+ * Read a link's repo fields, falling back to the legacy GitHub-only shape.+ * Returns the record unchanged when it already carries `isRepo`, so the common+ * (post-migration) path allocates nothing.+ *+ * @template {object|null|undefined} T+ * @param {T} link+ * @returns {T}+ */+export function normalizeRepoLinkFields(link) {+ if (!link || link.isRepo !== undefined) return link;+ if (!link.isGitHubRepo) return link;+ return {+ ...link,+ isRepo: true,+ repoHost: LEGACY_REPO_HOST,+ repoOwner: link.gitHubOwner ?? null,+ repoName: link.gitHubRepo ?? null,+ };+}++/**+ * True when a link record (either shape) names a cloneable repository.+ *+ * @param {object|null|undefined} link+ * @returns {boolean}+ */+export const linkIsRepo = (link) => Boolean(link?.isRepo ?? link?.isGitHubRepo);++/**+ * `owner/repo` for a link record (either shape), else its display title.+ *+ * @param {object|null|undefined} link+ * @returns {string}+ */+export function repoLinkLabel(link) {+ const owner = link?.repoOwner ?? link?.gitHubOwner;+ const repo = link?.repoName ?? link?.gitHubRepo;+ return owner && repo ? `${owner}/${repo}` : (link?.title || link?.url || 'unknown repo');+}diff --git a/server/lib/repoUrl.js b/server/lib/repoUrl.jsnew file mode 100644index 0000000000..3366f05bae--- /dev/null+++ b/server/lib/repoUrl.js@@ -0,0 +1,155 @@+/**+ * Git repository URL parsing — AUTHORITATIVE copy.+ *+ * Answers "is this URL a repository we can clone, and which host/owner/repo is+ * it?" for the hosts PortOS clones from: github.com and gitlab.com. Lives in+ * `lib/` (not `services/repoCloner.js`, which re-exports it) because the Brain+ * capture boxes have to preview the same answer BEFORE submitting: a capture+ * that is a bare repo URL gets cloned, and the client only offers the post-clone+ * agent options (malware scan / learn-from-repo) when it agrees with the server+ * about what counts as a repo.+ *+ * The client mirror is `client/src/lib/repoUrl.js`; parity is enforced by+ * `server/lib/repoUrl.mirror.test.js`. Port any change to both.+ */++// The host allowlist. `provider` is the stable id stored on a link record+// (`repoHost` holds the hostname itself), so adding a host here is the only+// change needed to clone from it — everything downstream is host-generic.+export const REPO_HOSTS = Object.freeze({+ 'github.com': 'github',+ 'gitlab.com': 'gitlab',+});++// The owner/repo pair is a PATH OPERAND, not just a label: the cloner clones+// into `join(reposDir, …owner, repo)` and the resulting `localPath` is later+// handed to an agent as the directory to scan/study. So every segment is+// matched against the character sets the hosts actually allow, NOT "anything+// but a slash" — the loose form parsed `https://github.com/../evil` as owner+// `..`, which resolves OUTSIDE the managed clone root.+// owner: a login (or a GitLab group/subgroup) — alphanumeric with internal+// hyphens, no dots, so no segment can ever be `.` or `..`+// repo: alphanumerics plus `_`, `.`, `-`+const OWNER_RE = /^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/;+const REPO_RE = /^[A-Za-z0-9_.-]+$/;++// `REPO_RE`'s character class admits the dot segments `.` and `..`, which would+// escape (or collapse to) the clone root the same way a bad owner does. The+// owner pattern already rejects them by requiring a leading alphanumeric.+const DOT_SEGMENTS = new Set(['.', '..']);++// SSH remote: git@host:path (optionally `ssh://git@host/path`).+const SSH_RE = /^(?:ssh:\/\/)?git@([^:/\s]+)[:/](\S+)$/i;++// Any scheme (or none), optional userinfo: host[:port][/path]. Anchored at the+// host so `https://evil.com/github.com/o/r` is NOT read as a GitHub repo, and+// whitespace-free end-to-end so `github.com/a b/c` is rejected outright.+const HTTP_RE = /^(?:[A-Za-z][A-Za-z0-9+.-]*:\/\/)?(?:[^/@\s]+@)?([^/?#\s]+)(\/\S*)?$/;++// Path words that begin a host's own UI route rather than another namespace+// segment. GitLab's modern deep links use the `/-/` separator (handled+// separately), but its legacy links — and every GitHub deep link — put the+// route word directly after the project, so the segment walk stops here.+const RESERVED_PATH_SEGMENTS = new Set([+ 'tree', 'blob', 'raw', 'commit', 'commits', 'compare', 'branches', 'tags',+ 'releases', 'issues', 'pull', 'pulls', 'merge_requests', 'wiki', 'wikis',+ 'actions', 'pipelines', 'settings', 'activity', 'network', 'graphs', 'blame',+]);++/**+ * Parse a repository URL into `{ host, provider, owner, repo, isGitHub }`, or+ * null when the URL isn't a repository on a supported host (or names a+ * path-unsafe owner/repo).+ *+ * `owner` is a single login on GitHub and may be a `group/subgroup` path on+ * GitLab; every one of its segments is validated, so it stays path-safe.+ *+ * @param {string} url+ * @returns {{ host: string, provider: string, owner: string, repo: string, isGitHub: boolean } | null}+ */+export function parseRepoUrl(url) {+ if (!url) return null;+ const normalized = String(url).trim();++ const match = normalized.match(SSH_RE) || normalized.match(HTTP_RE);+ if (!match) return null;++ const host = match[1].toLowerCase().replace(/^www\./, '').replace(/:\d+$/, '');+ const provider = REPO_HOSTS[host];+ if (!provider) return null;++ // Drop the query/hash, then GitLab's `/-/` deep-link separator, then walk the+ // remaining segments until a host UI route word.+ let path = (match[2] || '').split(/[?#]/)[0].replace(/^\//, '');+ const dashIndex = path.indexOf('/-/');+ if (dashIndex !== -1) path = path.slice(0, dashIndex);++ const segments = [];+ for (const segment of path.split('/')) {+ if (!segment) continue;+ if (RESERVED_PATH_SEGMENTS.has(segment.toLowerCase())) break;+ segments.push(segment);+ }+ if (segments.length < 2) return null;++ // GitHub has no subgroups: anything past owner/repo is a deep link. GitLab+ // nests groups arbitrarily, so everything before the last segment is the+ // namespace.+ const ownerSegments = provider === 'github' ? segments.slice(0, 1) : segments.slice(0, -1);+ const repo = (provider === 'github' ? segments[1] : segments[segments.length - 1])+ .replace(/\.git$/i, '');++ if (!ownerSegments.every(segment => OWNER_RE.test(segment))) return null;+ if (!repo || DOT_SEGMENTS.has(repo) || !REPO_RE.test(repo)) return null;++ return {+ host,+ provider,+ owner: ownerSegments.join('/'),+ repo,+ isGitHub: provider === 'github',+ };+}++/**+ * True when the URL points at a repository on a supported host.+ *+ * @param {string} url+ * @returns {boolean}+ */+export function isRepoUrl(url) {+ return parseRepoUrl(url) !== null;+}++/**+ * The `https` clone URL for a parsed repo.+ *+ * @param {{ host: string, owner: string, repo: string }} parsed+ * @returns {string}+ */+export function repoCloneUrl({ host, owner, repo }) {+ return `https://${host}/${owner}/${repo}.git`;+}++/**+ * Parse a URL only when it is a GitHub repository. The GitHub-only callers are+ * the ones whose downstream really is GitHub-specific (the Eidoverse worlds+ * repo, which is pushed to with a GitHub token), NOT the Brain's repo capture.+ *+ * @param {string} url+ * @returns {{ owner: string, repo: string, isGitHub: true } | null}+ */+export function parseGitHubUrl(url) {+ const parsed = parseRepoUrl(url);+ return parsed?.isGitHub ? { owner: parsed.owner, repo: parsed.repo, isGitHub: true } : null;+}++/**+ * True when the URL points at a GitHub repository specifically.+ *+ * @param {string} url+ * @returns {boolean}+ */+export function isGitHubRepoUrl(url) {+ return parseGitHubUrl(url) !== null;+}diff --git a/server/lib/githubRepoUrl.mirror.test.js b/server/lib/repoUrl.mirror.test.jssimilarity index 72%rename from server/lib/githubRepoUrl.mirror.test.jsrename to server/lib/repoUrl.mirror.test.jsindex 319f8541c2..ed45ab496a 100644--- a/server/lib/githubRepoUrl.mirror.test.js+++ b/server/lib/repoUrl.mirror.test.js@@ -1,5 +1,5 @@/**- * Mirror parity test for server/lib/githubRepoUrl.js ↔ client/src/lib/githubRepoUrl.js+ * Mirror parity test for server/lib/repoUrl.js ↔ client/src/lib/repoUrl.js** The server decides whether a captured URL gets cloned; the client previews* that decision by revealing the post-clone agent options (malware scan /@@ -18,20 +18,24 @@ import { compareDeclaration } from './mirrorParity.js';const __dirname = dirname(fileURLToPath(import.meta.url));-const SERVER_PATH = resolve(__dirname, 'githubRepoUrl.js');-const CLIENT_PATH = resolve(__dirname, '../../client/src/lib/githubRepoUrl.js');+const SERVER_PATH = resolve(__dirname, 'repoUrl.js');+const CLIENT_PATH = resolve(__dirname, '../../client/src/lib/repoUrl.js');const MIRRORED_NAMES = [- 'OWNER',- 'REPO',- 'SSH_REPO_RE',- 'HTTPS_REPO_RE',+ 'REPO_HOSTS',+ 'OWNER_RE',+ 'REPO_RE','DOT_SEGMENTS',+ 'SSH_RE',+ 'HTTP_RE',+ 'RESERVED_PATH_SEGMENTS',+ 'parseRepoUrl',+ 'isRepoUrl','parseGitHubUrl','isGitHubRepoUrl',];-describe('githubRepoUrl server↔client mirror parity', () => {+describe('repoUrl server↔client mirror parity', () => {const serverSrc = readFileSync(SERVER_PATH, 'utf8');const clientSrc = readFileSync(CLIENT_PATH, 'utf8');@@ -45,8 +49,8 @@ describe('githubRepoUrl server↔client mirror parity', () => {const { serverDecl, clientDecl, serverNorm, clientNorm } =compareDeclaration(serverSrc, clientSrc, name);- expect(serverDecl, `server/lib/githubRepoUrl.js is missing: ${name}`).not.toBeNull();- expect(clientDecl, `client/src/lib/githubRepoUrl.js is missing: ${name}`).not.toBeNull();+ expect(serverDecl, `server/lib/repoUrl.js is missing: ${name}`).not.toBeNull();+ expect(clientDecl, `client/src/lib/repoUrl.js is missing: ${name}`).not.toBeNull();expect(clientNorm,`"${name}" diverged — the server copy is authoritative; port the change verbatim`,diff --git a/server/lib/githubRepoUrl.test.js b/server/lib/repoUrl.test.jssimilarity index 57%rename from server/lib/githubRepoUrl.test.jsrename to server/lib/repoUrl.test.jsindex 9c1e1da5c3..644f3b0b0f 100644--- a/server/lib/githubRepoUrl.test.js+++ b/server/lib/repoUrl.test.js@@ -2,11 +2,11 @@ import { describe, it, expect } from 'vitest';import { posixPath } from './testHelper.js';import { join } from 'path';-import { parseGitHubUrl, isGitHubRepoUrl } from './githubRepoUrl.js';+import { parseRepoUrl, isRepoUrl, repoCloneUrl, parseGitHubUrl, isGitHubRepoUrl } from './repoUrl.js';const REPOS_ROOT = '/data/repos';const clonePath = (url) => {- const parsed = parseGitHubUrl(url);+ const parsed = parseRepoUrl(url);return parsed ? join(REPOS_ROOT, parsed.owner, parsed.repo) : null;};@@ -53,7 +53,7 @@ describe('parseGitHubUrl', () => {expect(parseGitHubUrl(null)).toBeNull();});- // The parsed pair is a PATH OPERAND — githubCloner clones into+ // The parsed pair is a PATH OPERAND — repoCloner clones into// join(reposDir, owner, repo), and that localPath is later handed to an agent// as the directory to scan/study. A dot segment escapes (or collapses to) the// managed clone root.@@ -102,3 +102,61 @@ describe('isGitHubRepoUrl', () => {expect(isGitHubRepoUrl('https://example.com')).toBe(false);});});++describe('parseRepoUrl across hosts', () => {+ it('parses a gitlab.com project the same shapes it parses a GitHub one', () => {+ for (const url of [+ 'https://gitlab.com/example-group/example-repo',+ 'https://gitlab.com/example-group/example-repo.git',+ 'gitlab.com/example-group/example-repo',+ '[email protected]:example-group/example-repo.git',+ ]) {+ expect(parseRepoUrl(url), url).toEqual({+ host: 'gitlab.com',+ provider: 'gitlab',+ owner: 'example-group',+ repo: 'example-repo',+ isGitHub: false,+ });+ }+ });++ it('keeps GitLab subgroups in the owner path', () => {+ expect(parseRepoUrl('https://gitlab.com/example-group/example-sub/example-repo'))+ .toMatchObject({ owner: 'example-group/example-sub', repo: 'example-repo' });+ });++ // GitLab's modern deep links insert /-/ before the UI route; the legacy shape+ // puts the route word straight after the project, which is why the segment+ // walk also stops at a reserved word.+ it('resolves a GitLab deep link back to the project', () => {+ expect(parseRepoUrl('https://gitlab.com/example-group/example-repo/-/tree/main/src'))+ .toMatchObject({ owner: 'example-group', repo: 'example-repo' });+ expect(parseRepoUrl('https://gitlab.com/example-group/example-repo/blob/main/README.md'))+ .toMatchObject({ owner: 'example-group', repo: 'example-repo' });+ expect(parseRepoUrl('https://github.com/example-owner/example-repo/tree/main'))+ .toMatchObject({ owner: 'example-owner', repo: 'example-repo' });+ });++ it('refuses an unsupported host and a path-unsafe GitLab namespace', () => {+ expect(parseRepoUrl('https://bitbucket.org/example-owner/example-repo')).toBeNull();+ expect(parseRepoUrl('https://gitlab.com/../example-group/example-repo')).toBeNull();+ expect(parseRepoUrl('https://gitlab.com/example-group')).toBeNull();+ expect(isRepoUrl('https://gitlab.com/example-group/example-repo')).toBe(true);+ expect(isRepoUrl('https://bitbucket.org/example-owner/example-repo')).toBe(false);+ });++ it('builds the https clone URL from the parsed host', () => {+ expect(repoCloneUrl(parseRepoUrl('[email protected]:example-group/example-repo')))+ .toBe('https://gitlab.com/example-group/example-repo.git');+ expect(repoCloneUrl(parseRepoUrl('https://github.com/example-owner/example-repo')))+ .toBe('https://github.com/example-owner/example-repo.git');+ });++ // The GitHub-only wrapper still exists for the callers whose downstream is+ // genuinely GitHub-specific (the Eidoverse worlds repo push).+ it('parseGitHubUrl rejects a valid GitLab repo', () => {+ expect(parseGitHubUrl('https://gitlab.com/example-group/example-repo')).toBeNull();+ expect(isGitHubRepoUrl('https://gitlab.com/example-group/example-repo')).toBe(false);+ });+});diff --git a/server/lib/spawnCwd.test.js b/server/lib/spawnCwd.test.jsindex 17a27c5166..aab01a5bb9 100644--- a/server/lib/spawnCwd.test.js+++ b/server/lib/spawnCwd.test.js@@ -272,7 +272,7 @@ describe('every cwd-passing spawn pins PWD', () => {['services/git.js', 'git/gh resolve from real cwd (and -C), never PWD'],['lib/execGit.js', 'git only'],['lib/planIds.js', 'git only'],- ['services/githubCloner.js', 'git clone/fetch only'],+ ['services/repoCloner.js', 'git clone/fetch only'],['services/gitlab.js', 'glab only'],['services/perpetualWork.js', 'git/gh/glab probes only'],['services/pm2Standardizer.js', 'git + pm2 only'],diff --git a/server/routes/brainLinks.js b/server/routes/brainLinks.jsindex 13bb270a57..89ac40e99a 100644--- a/server/routes/brainLinks.js+++ b/server/routes/brainLinks.js@@ -1,8 +1,8 @@/*** Brain Links & Buckets Routes*- * Bookmark links (with GitHub clone/pull/scan affordances) and the buckets- * that group them.+ * Bookmark links (with repository clone/pull/scan/study affordances for the+ * hosts in `lib/repoUrl.js`) and the buckets that group them.*/import { Router } from 'express';@@ -16,12 +16,14 @@ import {linkUpdateInputSchema,linkReorderSchema,linksQuerySchema,+ linkStudyInputSchema,bucketInputSchema,bucketUpdateInputSchema,bucketReorderSchema} from '../lib/brainValidation.js';-import * as githubCloner from '../services/githubCloner.js';-import { queueMalwareScan } from '../services/repoIntake.js';+import * as repoCloner from '../services/repoCloner.js';+import { deriveRepoLinkFields } from '../lib/repoLinkFields.js';+import { queueMalwareScan, restudyRepoLink } from '../services/repoIntake.js';import { getScanReport } from '../services/malwareScanReports.js';const router = Router();@@ -35,11 +37,11 @@ const router = Router();* Get all links with optional filters*/router.get('/links', asyncHandler(async (req, res) => {- const { linkType, isGitHubRepo, limit, offset } = validateRequest(linksQuerySchema, req.query);+ const { linkType, isRepo, limit, offset } = validateRequest(linksQuerySchema, req.query);// Filtering, newest-first ordering, and the total count are answered from// brainStorage's cached link-summary index, so only THIS page's records are// read and parsed from disk (issue #3509) — not the whole collection.- const { links, total } = await brainService.getLinksPage({ linkType, isGitHubRepo, limit, offset });+ const { links, total } = await brainService.getLinksPage({ linkType, isRepo, limit, offset });res.json({ links, total, limit, offset });}));@@ -99,7 +101,7 @@ router.post('/links', asyncHandler(async (req, res) => {});}- // Title derivation, GitHub metadata, and the background clone all live in the+ // Title derivation, repository metadata, and the background clone all live in the// service so a URL captured in the Brain inbox lands identically (see// captureUrlAsLink in services/brain.js).const link = await brainService.createLinkFromUrl(url, options);@@ -118,8 +120,8 @@ router.put('/links/:id', asyncHandler(async (req, res) => {throw new ServerError('Link not found', { status: 404, code: 'NOT_FOUND' });}- // When the URL changes, re-derive the GitHub-specific fields so the link- // type / repo metadata stay consistent with the new target.+ // When the URL changes, re-derive the repository fields so the link type /+ // repo metadata stay consistent with the new target.if (data.url && data.url !== existing.url) {const duplicate = await brainService.getLinkByUrl(data.url);if (duplicate && duplicate.id !== existing.id) {@@ -130,10 +132,7 @@ router.put('/links/:id', asyncHandler(async (req, res) => {});}- const parsed = githubCloner.parseGitHubUrl(data.url);- data.isGitHubRepo = !!parsed;- data.gitHubOwner = parsed?.owner || null;- data.gitHubRepo = parsed?.repo || null;+ Object.assign(data, deriveRepoLinkFields(data.url));// The previous clone (if any) belongs to the old URL — reset clone state so// it doesn't point at the wrong repo. The user can re-clone the new target.@@ -160,7 +159,7 @@ router.delete('/links/:id', asyncHandler(async (req, res) => {/*** POST /api/brain/links/:id/clone- * Manually trigger clone for a GitHub repo link+ * Manually trigger clone for a repository link*/router.post('/links/:id/clone', asyncHandler(async (req, res) => {const link = await brainService.getLinkById(req.params.id);@@ -168,10 +167,10 @@ router.post('/links/:id/clone', asyncHandler(async (req, res) => {throw new ServerError('Link not found', { status: 404, code: 'NOT_FOUND' });}- if (!link.isGitHubRepo) {- throw new ServerError('Link is not a GitHub repository', {+ if (!link.isRepo) {+ throw new ServerError('Link is not a repository', {status: 400,- code: 'NOT_GITHUB_REPO'+ code: 'NOT_A_REPO'});}@@ -203,14 +202,14 @@ router.post('/links/:id/pull', asyncHandler(async (req, res) => {throw new ServerError('Link not found', { status: 404, code: 'NOT_FOUND' });}- if (!link.isGitHubRepo || !link.localPath) {- throw new ServerError('Link is not a cloned GitHub repository', {+ if (!link.isRepo || !link.localPath) {+ throw new ServerError('Link is not a cloned repository', {status: 400,code: 'NOT_CLONED'});}- const result = await githubCloner.pullRepo(link.localPath);+ const result = await repoCloner.pullRepo(link.localPath);res.json({ message: 'Pull complete', ...result });}));@@ -253,8 +252,8 @@ router.post('/links/:id/scan', asyncHandler(async (req, res) => {if (!link) {throw new ServerError('Link not found', { status: 404, code: 'NOT_FOUND' });}- if (!link.isGitHubRepo || link.cloneStatus !== 'cloned' || !link.localPath) {- throw new ServerError('Link is not a cloned GitHub repository', {+ if (!link.isRepo || link.cloneStatus !== 'cloned' || !link.localPath) {+ throw new ServerError('Link is not a cloned repository', {status: 400,code: 'NOT_CLONED'});@@ -277,6 +276,47 @@ router.post('/links/:id/scan', asyncHandler(async (req, res) => {res.json({ message: 'Scan queued', taskId: result.taskId, linkId: link.id, scanPath: link.localPath });}));+/**+ * POST /api/brain/links/:id/study+ * Refresh the clone (unless `pull: false`) and queue a fresh `repo-study` run+ * against it, with the brief the user just wrote. The dispatch shape lives in+ * services/repoIntake.js so this button and the capture-time "study for app+ * ideas" checkbox queue exactly the same run.+ */+router.post('/links/:id/study', asyncHandler(async (req, res) => {+ const body = validateRequest(linkStudyInputSchema, req.body);+ const link = await brainService.getLinkById(req.params.id);+ if (!link) {+ throw new ServerError('Link not found', { status: 404, code: 'NOT_FOUND' });+ }+ if (!link.isRepo || link.cloneStatus !== 'cloned' || !link.localPath) {+ throw new ServerError('Link is not a cloned repository', {+ status: 400,+ code: 'NOT_CLONED'+ });+ }++ const result = await restudyRepoLink(link, body);+ if (!result.queued) {+ throw result.reason === 'duplicate'+ ? new ServerError('A study for this repo is already pending or in progress', { status: 409, code: 'DUPLICATE_TASK' })+ : result.reason === 'app-not-found'+ ? new ServerError('The app to file study issues against no longer exists', { status: 400, code: 'APP_NOT_FOUND' })+ : new ServerError('Local clone folder does not exist', { status: 400, code: 'PATH_NOT_FOUND' });+ }+ // Record the pending study the same way the capture-time path does, so a+ // reload shows the queued chip and the brief the run was given.+ const updated = await brainService.updateLink(link.id, result.linkPatch);++ res.json({+ message: 'Study queued',+ taskId: result.taskId,+ linkId: link.id,+ pulled: result.pulled,+ link: updated+ });+}));+router.get('/links/:id/scan-report', asyncHandler(async (req, res) => {const link = await brainService.getLinkById(req.params.id);if (!link?.malwareScan?.reportId) {diff --git a/server/routes/brainLinks.test.js b/server/routes/brainLinks.test.jsindex b8566ae32a..b38efb4574 100644--- a/server/routes/brainLinks.test.js+++ b/server/routes/brainLinks.test.js@@ -32,13 +32,17 @@ vi.mock('../services/brain.js', () => ({deleteBucketAndUnlinkChildren: vi.fn(),}));-vi.mock('../services/githubCloner.js', () => ({- parseGitHubUrl: vi.fn(() => null),+vi.mock('../services/repoCloner.js', () => ({pullRepo: vi.fn(),}));vi.mock('../services/cos.js', () => ({ addTask: vi.fn() }));+vi.mock('../services/repoIntake.js', () => ({+ queueMalwareScan: vi.fn(),+ restudyRepoLink: vi.fn(),+}));+vi.mock('../services/malwareScanReports.js', () => ({prepareScanReportDirectory: vi.fn(),reportPathForId: vi.fn(() => '/tmp/report.md'),@@ -48,6 +52,7 @@ vi.mock('../services/malwareScanReports.js', () => ({vi.mock('../lib/openFolder.js', () => ({ openFolderInSystemExplorer: vi.fn() }));import * as brainService from '../services/brain.js';+import { restudyRepoLink } from '../services/repoIntake.js';import linkRoutes from './brainLinks.js';const buildApp = () => {@@ -80,12 +85,12 @@ describe('GET /api/brain/links', () => {});it('delegates filtering, ordering, and pagination to getLinksPage', async () => {- await request(app).get('/api/brain/links?linkType=github&isGitHubRepo=true&limit=25&offset=50');+ await request(app).get('/api/brain/links?linkType=repo&isRepo=true&limit=25&offset=50');expect(brainService.getLinksPage).toHaveBeenCalledTimes(1);expect(brainService.getLinksPage).toHaveBeenCalledWith({- linkType: 'github',- isGitHubRepo: true,+ linkType: 'repo',+ isRepo: true,limit: 25,offset: 50,});@@ -107,17 +112,17 @@ describe('GET /api/brain/links', () => {expect(brainService.getLinksPage).toHaveBeenCalledWith({linkType: undefined,- isGitHubRepo: undefined,+ isRepo: undefined,limit: 50,offset: 0,});});- it('passes isGitHubRepo=false through as a boolean, not a truthy string', async () => {- await request(app).get('/api/brain/links?isGitHubRepo=false');+ it('passes isRepo=false through as a boolean, not a truthy string', async () => {+ await request(app).get('/api/brain/links?isRepo=false');expect(brainService.getLinksPage).toHaveBeenCalledWith(- expect.objectContaining({ isGitHubRepo: false }),+ expect.objectContaining({ isRepo: false }),);});@@ -165,7 +170,7 @@ describe('POST /api/brain/links/:id/clone', () => {const repoLink = (cloneStatus) => ({id: 'repo-link',url: 'https://github.com/acme/widgets',- isGitHubRepo: true,+ isRepo: true,cloneStatus,});@@ -197,3 +202,58 @@ describe('POST /api/brain/links/:id/clone', () => {logged.mockRestore();});});++describe('POST /api/brain/links/:id/study', () => {+ const cloned = () => ({+ id: 'repo-link',+ url: 'https://gitlab.com/example-group/example-repo',+ isRepo: true,+ cloneStatus: 'cloned',+ localPath: '/repos/gitlab.com/example-group/example-repo',+ });++ beforeEach(() => {+ brainService.getLinkById.mockResolvedValue(cloned());+ brainService.updateLink.mockImplementation(async (id, patch) => ({ ...cloned(), ...patch }));+ });++ it('queues the study with the brief and persists the pending run on the link', async () => {+ restudyRepoLink.mockResolvedValue({+ queued: true,+ taskId: 'task-1',+ pulled: { ok: true },+ linkPatch: { repoStudy: { taskId: 'task-1' } },+ });++ const res = await request(app)+ .post('/api/brain/links/repo-link/study')+ .send({ studyContext: 'look at its offline sync', targetAppId: 'portos-default' });++ expect(res.status).toBe(200);+ expect(restudyRepoLink).toHaveBeenCalledWith(+ expect.objectContaining({ id: 'repo-link' }),+ // `pull` defaults on, so the button refreshes the checkout unless told not to.+ expect.objectContaining({ pull: true, studyContext: 'look at its offline sync', targetAppId: 'portos-default' }),+ );+ expect(brainService.updateLink).toHaveBeenCalledWith('repo-link', { repoStudy: { taskId: 'task-1' } });+ expect(res.body).toMatchObject({ taskId: 'task-1', pulled: { ok: true } });+ });++ it('409s when a study for the repo is already in flight', async () => {+ restudyRepoLink.mockResolvedValue({ queued: false, reason: 'duplicate' });++ const res = await request(app).post('/api/brain/links/repo-link/study').send({});++ expect(res.status).toBe(409);+ expect(brainService.updateLink).not.toHaveBeenCalled();+ });++ it('rejects a link that has no clone to study', async () => {+ brainService.getLinkById.mockResolvedValue({ ...cloned(), cloneStatus: 'none', localPath: null });++ const res = await request(app).post('/api/brain/links/repo-link/study').send({});++ expect(res.status).toBe(400);+ expect(restudyRepoLink).not.toHaveBeenCalled();+ });+});diff --git a/server/routes/settings.js b/server/routes/settings.jsindex d0d163083b..cf2e96d19a 100644--- a/server/routes/settings.js+++ b/server/routes/settings.js@@ -13,7 +13,7 @@ import { assertMediaRoutingConfig } from '../services/federatedMedia/routingPoliimport { assertConfiguredEidoverseInstalled, getInstanceFeatures, updateEidoverseWorldsRepo, updateEidoverseWorldsSource, updateInstanceFeature } from '../services/instanceFeatures.js';import { installEidoverse } from '../services/eidoverse.js';import { ensureEidoverseHost } from '../services/eidoverseHost.js';-import { isGitHubRepoUrl } from '../lib/githubRepoUrl.js';+import { isGitHubRepoUrl } from '../lib/repoUrl.js';import { asyncHandler } from '../lib/errorHandler.js';import { isPlainObject } from '../lib/objects.js';import { agentContextSettingsSchema } from '../lib/agentContextValidation.js';diff --git a/server/services/brain.js b/server/services/brain.jsindex 07c2d58dad..cf6577e959 100644--- a/server/services/brain.js+++ b/server/services/brain.js@@ -19,7 +19,8 @@ import { runPromptThroughProvider } from './promptRunner.js';import { getDomainAutonomyMode } from './cosState.js';import { getDomainBudgetStatus, recordDomainUsage } from './domainUsage.js';import { deleteMemoryAssets } from './chatgptImport.js';-import * as githubCloner from './githubCloner.js';+import * as repoCloner from './repoCloner.js';+import { deriveRepoLinkFields } from '../lib/repoLinkFields.js';import { parseBareUrl } from '../lib/bareUrl.js';import { normalizeRepoIntake } from '../lib/repoIntakeActions.js';import {@@ -242,12 +243,12 @@ async function captureUrlAsLink(url, capturedText, { repoIntake = null, note } =link,message: existing? 'Already saved in Links.'- : (link.isGitHubRepo ? repoCaptureMessage(link.repoIntake) : 'Saved to Links!')+ : (link.isRepo ? repoCaptureMessage(link.repoIntake) : 'Saved to Links!')};}/**- * What a freshly-captured GitHub repo link tells the user will happen next. The+ * What a freshly-captured repo link tells the user will happen next. The* clone is always implied; the agent runs only when they ticked the boxes, and* they only start once the clone lands.*/@@ -257,8 +258,8 @@ function repoCaptureMessage(repoIntake) {repoIntake?.learn && 'repo study',].filter(Boolean);return queued.length- ? `GitHub repo saved — cloning, then queueing ${queued.join(' + ')}.`- : 'GitHub repo saved to Links — cloning now.';+ ? `Repo saved — cloning, then queueing ${queued.join(' + ')}.`+ : 'Repo saved to Links — cloning now.';}/**@@ -890,7 +891,7 @@ export async function recoverInterruptedRepoClones() {// Detached on purpose: boot AWAITS this function so the first links request// can't see an orphaned `cloning` badge, and a recursive scan plus `rm -rf` of// abandoned partial checkouts must not sit in front of `startListening()`.- githubCloner.reapStaleCloneStaging()+ repoCloner.reapStaleCloneStaging().catch(err => console.error(`❌ Clone staging recovery failed: ${err.message}`));}@@ -1005,7 +1006,7 @@ function hostnameFromUrl(url) {}/**- * Clone a GitHub repo in the background, tracking progress on the link record.+ * Clone a repo in the background, tracking progress on the link record.* Runs outside the request lifecycle, so every failure is caught and recorded* on the link rather than left to bubble.*@@ -1034,7 +1035,7 @@ export async function cloneRepoInBackground(linkId, url) {cloneInterrupted: false});- githubCloner.cloneRepo(url, { replaceIncomplete: previous?.cloneInterrupted === true })+ repoCloner.cloneRepo(url, { replaceIncomplete: previous?.cloneInterrupted === true }).then(async (result) => {const link = await storage.updateLink(linkId, {localPath: result.localPath,@@ -1072,7 +1073,7 @@ export async function cloneRepoInBackground(linkId, url) {}/**- * Create a link from a URL: derives the GitHub metadata + a readable default+ * Create a link from a URL: derives the repository metadata + a readable default* title and kicks off the background clone for a repo. Shared by the Links* route's quick-add and the bare-URL capture short-circuit so a URL pasted into* the Brain inbox lands exactly as it would from the Links tab.@@ -1083,18 +1084,18 @@ export async function cloneRepoInBackground(linkId, url) {export async function createLinkFromUrl(url, {title, description, note, linkType, tags, bucketId, bucketOrder, autoClone, repoIntake} = {}) {- const parsed = githubCloner.parseGitHubUrl(url);- const isGitHubRepo = !!parsed;- const shouldClone = isGitHubRepo && autoClone !== false;+ const repoFields = deriveRepoLinkFields(url);+ const shouldClone = repoFields.isRepo && autoClone !== false;// Opt-in post-clone agent actions. Only meaningful when a clone will actually// happen, and persisted on the link so the record says what was asked for even// if the clone is still running.const intake = shouldClone ? normalizeRepoIntake(repoIntake) : null;- // Derive a readable default title: repo slug for GitHub, hostname for plain- // URLs (so quick-added bucket chips read "example.com" instead of the full URL).- const defaultTitle = parsed- ? `${parsed.owner}/${parsed.repo}`+ // Derive a readable default title: repo slug for a repository, hostname for+ // plain URLs (so quick-added bucket chips read "example.com" instead of the+ // full URL).+ const defaultTitle = repoFields.isRepo+ ? `${repoFields.repoOwner}/${repoFields.repoName}`: (hostnameFromUrl(url) || url);const cleanNote = typeof note === 'string' ? note.trim() : '';@@ -1103,11 +1104,9 @@ export async function createLinkFromUrl(url, {title: title || defaultTitle,description: description || '',note: cleanNote,- linkType: linkType || (isGitHubRepo ? 'github' : 'other'),+ linkType: linkType || (repoFields.isRepo ? 'repo' : 'other'),tags: tags || [],- isGitHubRepo,- gitHubOwner: parsed?.owner,- gitHubRepo: parsed?.repo,+ ...repoFields,localPath: null,cloneStatus: shouldClone ? 'pending' : 'none',cloneError: null,@@ -1115,7 +1114,7 @@ export async function createLinkFromUrl(url, {...(bucketId !== undefined ? { bucketId } : {}),...(bucketOrder !== undefined ? { bucketOrder } : {})});- console.log(`🔗 Created link: ${link.id} (${isGitHubRepo ? 'GitHub repo' : 'regular URL'})`);+ console.log(`🔗 Created link: ${link.id} (${repoFields.isRepo ? `${repoFields.repoHost} repo` : 'regular URL'})`);if (shouldClone) {cloneRepoInBackground(link.id, url).catch(err => {diff --git a/server/services/brain.test.js b/server/services/brain.test.jsindex f2882ffd36..f3b550333e 100644--- a/server/services/brain.test.js+++ b/server/services/brain.test.js@@ -64,10 +64,11 @@ vi.mock('./brainStorage.js', () => {};});-// Mock githubCloner — the bare-URL capture path derives GitHub metadata and can-// kick off a background clone; stub it so no test ever shells out to git.-vi.mock('./githubCloner.js', () => ({- parseGitHubUrl: vi.fn(() => null),+// Mock repoCloner — the bare-URL capture path can kick off a background clone;+// stub it so no test ever shells out to git. The URL PARSE is deliberately not+// stubbed: it is a pure rule in lib/repoUrl.js, so the fixtures below exercise+// the real "is this a repo URL?" decision.+vi.mock('./repoCloner.js', () => ({cloneRepo: vi.fn(),reapStaleCloneStaging: vi.fn(() => Promise.resolve(0))}));@@ -133,7 +134,7 @@ assertProvider: (provider, { message, code, status = 503 } = {}) => {}));import { runPromptThroughProvider } from './promptRunner.js';-import * as githubCloner from './githubCloner.js';+import * as repoCloner from './repoCloner.js';import * as storage from './brainStorage.js';import { deleteMemoryAssets } from './chatgptImport.js';import { getProviderById } from './providers.js';@@ -244,8 +245,6 @@ describe('brain service', () => {describe('captureThought (bare URL)', () => {beforeEach(() => {- // mockReturnValue survives clearAllMocks — reset to "not a GitHub URL".- githubCloner.parseGitHubUrl.mockReturnValue(null);storage.getLinkByUrl.mockResolvedValue(null);storage.createLink.mockImplementation(async (data) => ({ id: 'link-001', ...data }));storage.createInboxLog.mockImplementation(async (entry) => ({ id: 'inbox-url-1', ...entry }));@@ -311,15 +310,17 @@ describe('brain service', () => {}));});- it('clones a captured GitHub repo the same way the Links tab does', async () => {- githubCloner.parseGitHubUrl.mockReturnValue({ owner: 'acme', repo: 'widgets', isGitHub: true });- githubCloner.cloneRepo.mockResolvedValue({ localPath: '/repos/acme/widgets' });+ it('clones a captured repo the same way the Links tab does', async () => {+ repoCloner.cloneRepo.mockResolvedValue({ localPath: '/repos/acme/widgets' });await captureThought('https://github.com/acme/widgets');expect(storage.createLink).toHaveBeenCalledWith(expect.objectContaining({title: 'acme/widgets',- linkType: 'github',+ linkType: 'repo',+ isRepo: true,+ repoHost: 'github.com',+ // The legacy GitHub-only mirror rides along for peers on older code.isGitHubRepo: true,cloneStatus: 'pending'}));@@ -360,13 +361,12 @@ describe('brain service', () => {// here is that a request only survives the capture path when a clone will// actually happen, since the agents read the clone.describe('repoIntake', () => {- const asGitHub = () => {- githubCloner.parseGitHubUrl.mockReturnValue({ owner: 'acme', repo: 'widgets', isGitHub: true });- githubCloner.cloneRepo.mockResolvedValue({ localPath: '/repos/acme/widgets' });+ const asRepo = () => {+ repoCloner.cloneRepo.mockResolvedValue({ localPath: '/repos/acme/widgets' });};it('records the requested actions on a newly captured repo link', async () => {- asGitHub();+ asRepo();const result = await captureThought('https://github.com/acme/widgets', undefined, undefined, {repoIntake: { malwareScan: true, learn: true },});@@ -378,7 +378,7 @@ describe('brain service', () => {});it('normalizes a partial request so an absent action is explicitly off', async () => {- asGitHub();+ asRepo();await captureThought('https://github.com/acme/widgets', undefined, undefined, {repoIntake: { learn: true },});@@ -389,7 +389,7 @@ describe('brain service', () => {});it('persists repo-study provider pins with the requested intake', async () => {- asGitHub();+ asRepo();await captureThought('https://github.com/acme/widgets', undefined, undefined, {repoIntake: { learn: true, providerId: 'codex', model: 'gpt-5', effort: 'high' },});@@ -406,7 +406,7 @@ describe('brain service', () => {});it('stores nothing when every box is unticked', async () => {- asGitHub();+ asRepo();await captureThought('https://github.com/acme/widgets', undefined, undefined, {repoIntake: { malwareScan: false, learn: false },});@@ -416,7 +416,7 @@ describe('brain service', () => {);});- it('drops the request for a non-GitHub URL, which is never cloned', async () => {+ it('drops the request for a URL that is not a repo, which is never cloned', async () => {await captureThought('https://example.com', undefined, undefined, {repoIntake: { malwareScan: true, learn: true },});@@ -430,7 +430,7 @@ describe('brain service', () => {// tab's Clone/Retry button (which calls cloneRepoInBackground with no// intake argument) honors a request whose first clone failed.it('is stored on the link, not only threaded through the first clone', async () => {- asGitHub();+ asRepo();await captureThought('https://github.com/acme/widgets', undefined, undefined, {repoIntake: { malwareScan: true, learn: false },});@@ -440,8 +440,8 @@ describe('brain service', () => {});it('does not re-run agents when a saved repo URL is pasted again', async () => {- asGitHub();- storage.getLinkByUrl.mockResolvedValue({ id: 'link-existing', isGitHubRepo: true });+ asRepo();+ storage.getLinkByUrl.mockResolvedValue({ id: 'link-existing', isRepo: true });const result = await captureThought('https://github.com/acme/widgets', undefined, undefined, {repoIntake: { malwareScan: true, learn: true },@@ -449,7 +449,7 @@ describe('brain service', () => {// No new link, so no new clone — and nothing for the agents to read.expect(storage.createLink).not.toHaveBeenCalled();- expect(githubCloner.cloneRepo).not.toHaveBeenCalled();+ expect(repoCloner.cloneRepo).not.toHaveBeenCalled();expect(result.message).toMatch(/already saved/i);});});@@ -461,8 +461,6 @@ describe('brain service', () => {describe('createLinkFromUrl', () => {beforeEach(() => {- // mockReturnValue survives clearAllMocks — reset to "not a GitHub URL".- githubCloner.parseGitHubUrl.mockReturnValue(null);storage.createLink.mockImplementation(async (data) => ({ id: 'link-002', ...data }));});@@ -470,14 +468,12 @@ describe('brain service', () => {await createLinkFromUrl('https://www.example.com/parks');expect(storage.createLink).toHaveBeenCalledWith(expect.objectContaining({title: 'example.com',- isGitHubRepo: false,+ isRepo: false,cloneStatus: 'none'}));});it('honors explicit overrides and skips the clone when autoClone is false', async () => {- githubCloner.parseGitHubUrl.mockReturnValue({ owner: 'acme', repo: 'widgets', isGitHub: true });-await createLinkFromUrl('https://github.com/acme/widgets', {title: 'My Widgets', note: 'Use this as a reference', bucketId: 'bucket-1', autoClone: false});@@ -1050,12 +1046,12 @@ describe('brain service', () => {// `Once`, so the never-settling promise can't leak into a later test —// mockReturnValue survives clearAllMocks.let released;- githubCloner.reapStaleCloneStaging.mockReturnValueOnce(new Promise(resolve => { released = resolve; }));+ repoCloner.reapStaleCloneStaging.mockReturnValueOnce(new Promise(resolve => { released = resolve; }));storage.getLinks.mockResolvedValue([]);await recoverInterruptedRepoClones();- expect(githubCloner.reapStaleCloneStaging).toHaveBeenCalled();+ expect(repoCloner.reapStaleCloneStaging).toHaveBeenCalled();released(0);});});diff --git a/server/services/brainStorage.js b/server/services/brainStorage.jsindex c21321a117..d316d85286 100644--- a/server/services/brainStorage.js+++ b/server/services/brainStorage.js@@ -41,6 +41,7 @@ import { atomicWrite, ensureDir, readJSONFile, safeJSONParse, safeDate, PATHS }import { getInstanceId } from './instances.js';import * as brainSyncLog from './brainSyncLog.js';import { createCollectionStore } from '../lib/collectionStore.js';+import { linkIsRepo, normalizeRepoLinkFields } from '../lib/repoLinkFields.js';const DATA_DIR = PATHS.brain;@@ -1029,13 +1030,20 @@ export const updateMemoryEntry = (id, data) => update('memories', id, data);export const deleteMemoryEntry = (id) => remove('memories', id);// Links-export const getLinks = (filters) => filters ? query('links', filters) : getAll('links');-export const getLinkById = (id) => getById('links', id);-export const createLink = (data) => create('links', data);-export const updateLink = (id, data) => update('links', id, data);+//+// Every read is passed through `normalizeRepoLinkFields` so a record written by+// an older PortOS (or arriving from a peer still on the GitHub-only field names)+// reads as a repo here — see lib/repoLinkFields.js. Writes are NOT normalized:+// the derivation belongs to `createLinkFromUrl`, which owns the URL.+const normalizeLinks = (links) => links.map(normalizeRepoLinkFields);+export const getLinks = async (filters) =>+ normalizeLinks(await (filters ? query('links', filters) : getAll('links')));+export const getLinkById = async (id) => normalizeRepoLinkFields(await getById('links', id));+export const createLink = async (data) => normalizeRepoLinkFields(await create('links', data));+export const updateLink = async (id, data) => normalizeRepoLinkFields(await update('links', id, data));// Batch reorder: per-id write queues so a multi-chip drag merges each link// against its freshest persisted record.-export const reorderLinks = (updates) => updateMany('links', updates);+export const reorderLinks = async (updates) => normalizeLinks(await updateMany('links', updates));export const deleteLink = (id) => remove('links', id);// ─── Link summary index (issue #3509) ───────────────────────────────────────@@ -1055,11 +1063,12 @@ const projectLinkSummary = (record) => (record && !isTombstone(record)// unparseable createdAt, so such a link sorts last deterministically// instead of poisoning the comparator with NaN.createdAtMs: safeDate(record.createdAt),- // Filter keys are stored RAW so the route's strict `===` comparison keeps- // its exact semantics (a link with no `isGitHubRepo` field must not match- // `?isGitHubRepo=false`, just as the old in-memory filter behaved).+ // `linkType` is stored RAW so the route's strict `===` comparison keeps its+ // exact semantics. `isRepo` is resolved through `linkIsRepo` instead, so a+ // legacy record still carrying only `isGitHubRepo` filters correctly without+ // the index having to be rebuilt behind the migration.linkType: record.linkType,- isGitHubRepo: record.isGitHubRepo,+ isRepo: linkIsRepo(record),url: record.url,}: null);@@ -1072,7 +1081,6 @@ const linkSummaryIndex = createRecordIndex(projectLinkSummary);const projectSummary = (record) => (record && !isTombstone(record)? {status: record.status,- isGitHubRepo: record.isGitHubRepo,capturedAtMs: safeDate(record.capturedAt),}: null);@@ -1085,18 +1093,18 @@ const resolveLinkSummaries = () => resolveRecordIndex(linkSummaryIndex, 'links',** Filtering, ordering, and the `total` count all come off the cached summary* index; only the page's own records are loaded from disk. `linkType` /- * `isGitHubRepo` are optional and compared strictly, matching the filters the- * route used to apply in memory.+ * `isRepo` are optional and compared strictly, matching the filters the route+ * used to apply in memory.*/-export async function getLinksPage({ linkType, isGitHubRepo, limit = 50, offset = 0 } = {}) {+export async function getLinksPage({ linkType, isRepo, limit = 50, offset = 0 } = {}) {const rows = await resolveLinkSummaries();// The two filters guard differently ON PURPOSE, mirroring the route code this// replaced: `linkType` was a truthiness check (no link type is the empty- // string, so `''` means "don't filter"), while `isGitHubRepo` must honour an+ // string, so `''` means "don't filter"), while `isRepo` must honour an// explicit `false` and so can only be skipped when it is genuinely absent.const matching = rows.filter(([, summary]) => summary&& (!linkType || summary.linkType === linkType)- && (isGitHubRepo === undefined || summary.isGitHubRepo === isGitHubRepo));+ && (isRepo === undefined || summary.isRepo === isRepo));// Newest-first, with the id as a deterministic tiebreak: a bulk import stamps// many links with the SAME createdAt, and an unstable order across two page@@ -1105,7 +1113,7 @@ export async function getLinksPage({ linkType, isGitHubRepo, limit = 50, offsetconst total = matching.length;const pageIds = matching.slice(offset, offset + limit).map(([id]) => id);- const page = await Promise.all(pageIds.map((id) => getById('links', id)));+ const page = normalizeLinks(await Promise.all(pageIds.map((id) => getById('links', id))));// A record deleted between the index read and the body read comes back null —// drop it rather than emitting a hole in the page.return { links: page.filter(Boolean), total };@@ -1127,7 +1135,7 @@ export async function listLinkIds() {export async function getLinkByUrl(url) {const rows = await resolveLinkSummaries();const hit = rows.find(([, summary]) => summary && summary.url === url);- return hit ? getById('links', hit[0]) : null;+ return hit ? normalizeRepoLinkFields(await getById('links', hit[0])) : null;}// Buckets (bookmark groups for links)@@ -1320,7 +1328,7 @@ export async function getSummary() {activeProjects: summaries.projects.filter(p => p.status === 'active').length,activeIdeas: summaries.ideas.filter(i => !i.status || i.status === 'active').length,openAdmin: summaries.admin.filter(a => a.status === 'open').length,- gitHubRepos: links.filter(l => l.isGitHubRepo).length,+ repos: links.filter(l => l.isRepo).length,needsReview: inboxCounts.needs_review,lastDailyDigest: meta.lastDailyDigest,lastWeeklyReview: meta.lastWeeklyReviewdiff --git a/server/services/brainStorage.test.js b/server/services/brainStorage.test.jsindex aa7b88a47f..705ef20e6f 100644--- a/server/services/brainStorage.test.js+++ b/server/services/brainStorage.test.js@@ -449,7 +449,7 @@ describe('Brain summary projection index (issue #5438)', () => {ideas: { title: 'Summary Idea' },admin: { title: 'Summary Admin', status: 'open' },memories: { title: 'Summary Memory' },- links: { url: 'https://example.com/summary-repo', isGitHubRepo: true },+ links: { url: 'https://example.com/summary-repo', isRepo: true },buckets: { name: 'Summary Bucket' },};@@ -479,7 +479,7 @@ describe('Brain summary projection index (issue #5438)', () => {expect(summary.activeProjects).toBe(before.activeProjects + 2);expect(summary.activeIdeas).toBe(before.activeIdeas + 2);expect(summary.openAdmin).toBe(before.openAdmin + 2);- expect(summary.gitHubRepos).toBe(before.gitHubRepos + 2);+ expect(summary.repos).toBe(before.repos + 2);expect(summary).toEqual(expect.objectContaining({needsReview: summary.counts.inbox.needs_review,lastDailyDigest: before.lastDailyDigest,@@ -588,26 +588,49 @@ describe('getLinksPage (paginated link reads, issue #3509)', () => {expect(mine(await brainStorage.getLinksPage({ linkType: 'tool', limit: 50 }), ids)).toHaveLength(0);});- it('filters strictly on linkType and isGitHubRepo, matching the old in-memory filter', async () => {- const repo = await brainStorage.create('links', { url: 'https://example.com/gh', linkType: 'github', isGitHubRepo: true });- const plain = await brainStorage.create('links', { url: 'https://example.com/plain', linkType: 'documentation', isGitHubRepo: false });- // No isGitHubRepo field at all — must NOT match `false`, exactly as the old- // `l.isGitHubRepo === isGitHubRepo` filter behaved.+ it('filters on linkType strictly and on isRepo by resolved repo-ness', async () => {+ const repo = await brainStorage.create('links', { url: 'https://example.com/gh', linkType: 'repo', isRepo: true });+ const plain = await brainStorage.create('links', { url: 'https://example.com/plain', linkType: 'documentation', isRepo: false });+ // No repo field at all — resolved as `false`, which is what it means.const untyped = await brainStorage.create('links', { url: 'https://example.com/untyped', linkType: 'documentation' });- const ids = [repo.id, plain.id, untyped.id];-- expect(mine(await brainStorage.getLinksPage({ isGitHubRepo: true, limit: 50 }), ids)).toEqual([repo.id]);- expect(mine(await brainStorage.getLinksPage({ isGitHubRepo: false, limit: 50 }), ids)).toEqual([plain.id]);+ // A record still in the pre-migration GitHub-only shape (or federated in+ // from a peer on older code) must filter as a repo, not as a bookmark.+ const legacy = await brainStorage.create('links', { url: 'https://example.com/legacy', linkType: 'github', isGitHubRepo: true });+ const ids = [repo.id, plain.id, untyped.id, legacy.id];++ expect(mine(await brainStorage.getLinksPage({ isRepo: true, limit: 50 }), ids).sort())+ .toEqual([repo.id, legacy.id].sort());+ expect(mine(await brainStorage.getLinksPage({ isRepo: false, limit: 50 }), ids).sort())+ .toEqual([plain.id, untyped.id].sort());expect(mine(await brainStorage.getLinksPage({ linkType: 'documentation', limit: 50 }), ids).sort()).toEqual([plain.id, untyped.id].sort());- expect(mine(await brainStorage.getLinksPage({ linkType: 'github', isGitHubRepo: true, limit: 50 }), ids))+ expect(mine(await brainStorage.getLinksPage({ linkType: 'repo', isRepo: true, limit: 50 }), ids)).toEqual([repo.id]);// An empty linkType means "no filter" (the route's old truthiness check), and- // is NOT the same as omitting isGitHubRepo — `false` there is a real filter.+ // is NOT the same as omitting isRepo — `false` there is a real filter.expect(mine(await brainStorage.getLinksPage({ linkType: '', limit: 50 }), ids).sort()).toEqual(ids.slice().sort());});+ it('reads a legacy GitHub-only link record in the host-generic shape', async () => {+ const legacy = await brainStorage.create('links', {+ url: 'https://github.com/example-owner/example-repo',+ linkType: 'github',+ isGitHubRepo: true,+ gitHubOwner: 'example-owner',+ gitHubRepo: 'example-repo',+ });++ expect(await brainStorage.getLinkById(legacy.id)).toMatchObject({+ isRepo: true,+ repoHost: 'github.com',+ repoOwner: 'example-owner',+ repoName: 'example-repo',+ });+ expect(await brainStorage.getLinkByUrl('https://github.com/example-owner/example-repo'))+ .toMatchObject({ isRepo: true, repoOwner: 'example-owner' });+ });+it('drops a link from the page as soon as it is deleted', async () => {const kept = await brainStorage.create('links', { url: 'https://example.com/kept', linkType: 'reference' });const gone = await brainStorage.create('links', { url: 'https://example.com/gone', linkType: 'reference' });diff --git a/server/services/eidoverse.js b/server/services/eidoverse.jsindex 1ca90ad50c..73cb47c8cf 100644--- a/server/services/eidoverse.js+++ b/server/services/eidoverse.js@@ -5,8 +5,8 @@ import { bufferedSpawnOrThrow } from '../lib/bufferedSpawn.js';import { commandExists } from '../lib/commandExists.js';import { execGit } from '../lib/execGit.js';import { atomicWrite, ensureDir, pathExists, PATHS } from '../lib/fileUtils.js';-import { parseGitHubUrl } from '../lib/githubRepoUrl.js';-import { cloneRepo } from './githubCloner.js';+import { parseGitHubUrl } from '../lib/repoUrl.js';+import { cloneRepo } from './repoCloner.js';import { createApp, getAllApps, notifyAppsChanged, updateApp } from './apps.js';import { getAppStatusStrict } from './pm2.js';diff --git a/server/services/eidoverse.test.js b/server/services/eidoverse.test.jsindex ef20c6b6b6..3ba18f3bcf 100644--- a/server/services/eidoverse.test.js+++ b/server/services/eidoverse.test.js@@ -38,7 +38,7 @@ vi.mock('../lib/bufferedSpawn.js', () => ({bufferedSpawnOrThrow: mock.spawn,}));-vi.mock('./githubCloner.js', () => ({+vi.mock('./repoCloner.js', () => ({cloneRepo: mock.cloneRepo,}));diff --git a/server/services/instanceFeatures.js b/server/services/instanceFeatures.jsindex 2f7d6cb24a..44b5e36a1f 100644--- a/server/services/instanceFeatures.js+++ b/server/services/instanceFeatures.js@@ -1,6 +1,6 @@import { ServerError } from '../lib/errorHandler.js';import { getOriginInfo } from '../lib/gitRemote.js';-import { parseGitHubUrl } from '../lib/githubRepoUrl.js';+import { parseGitHubUrl } from '../lib/repoUrl.js';import { INSTANCE_FEATURES, INSTANCE_FEATURE_IDS } from '../lib/instanceFeatureRegistry.js';import { isPlainObject } from '../lib/objects.js';import {diff --git a/server/services/githubCloner.js b/server/services/repoCloner.jssimilarity index 68%rename from server/services/githubCloner.jsrename to server/services/repoCloner.jsindex 0537f7ab5c..56f2bac96c 100644--- a/server/services/githubCloner.js+++ b/server/services/repoCloner.js@@ -1,16 +1,17 @@/**- * GitHub Repository Cloner Service+ * Repository Cloner Service*- * Handles cloning GitHub repositories to a local directory for reference.- * Supports shallow clones to save space and provides progress tracking.+ * Handles cloning repositories (github.com / gitlab.com — see `REPO_HOSTS` in+ * lib/repoUrl.js) to a local directory for reference. Supports shallow clones to+ * save space and provides progress tracking.*/import { spawn } from '../lib/childProcess.js';import { existsSync } from 'fs';import { mkdtemp, readdir, rename, rm } from 'fs/promises';-import { join } from 'path';+import { dirname, join } from 'path';import { ensureDir, PATHS } from '../lib/fileUtils.js';-import { parseGitHubUrl, isGitHubRepoUrl } from '../lib/githubRepoUrl.js';+import { parseRepoUrl, isRepoUrl, repoCloneUrl, parseGitHubUrl, isGitHubRepoUrl } from '../lib/repoUrl.js';// Default directory for cloned repos (can be configured in settings)const DEFAULT_CLONE_DIR = PATHS.repos;@@ -18,10 +19,24 @@ const CLONE_STAGING_PREFIX = '.portos-clone-';const CLONE_STAGING_MAX_AGE_MS = 10 * 60 * 1000;const CLONE_STAGING_RE = /^\.portos-clone-(\d{13})-[A-Za-z0-9]+$/;-// The owner/repo parse rule lives in lib/ so the client can mirror it — the+// The host/owner/repo parse rule lives in lib/ so the client can mirror it — the// Brain capture boxes have to predict "this URL will be cloned" before submit.-// Re-exported here so existing `githubCloner.parseGitHubUrl` callers keep working.-export { parseGitHubUrl, isGitHubRepoUrl };+// Re-exported here so callers reach the rule through the service they already use.+export { parseRepoUrl, isRepoUrl, parseGitHubUrl, isGitHubRepoUrl };++/**+ * The clone directory for a parsed repo, relative to the repos root.+ *+ * GitHub keeps the historical flat `<owner>/<repo>` layout so every clone made+ * before PortOS supported a second host stays exactly where its link record says+ * it is. Every other host is namespaced under its hostname, which is also what+ * keeps `gitlab.com/acme/widgets` from colliding with `github.com/acme/widgets`.+ * A GitLab `owner` may itself be a `group/subgroup` path; every segment is+ * validated by parseRepoUrl, so the join stays inside the root.+ */+export function repoSubPath({ host, owner, repo }) {+ return host === 'github.com' ? join(owner, repo) : join(host, owner, repo);+}/*** Get clone directory path@@ -43,18 +58,18 @@ export async function ensureCloneDir(cloneDir) {}/**- * Clone a GitHub repository- * Returns the local path where the repo was cloned+ * Clone a repository from a supported host.+ * Returns the local path where the repo was cloned.*/export async function cloneRepo(url, options = {}) {- const parsed = parseGitHubUrl(url);+ const parsed = parseRepoUrl(url);if (!parsed) {- throw new Error('Invalid GitHub URL');+ throw new Error('Invalid repository URL');}const { owner, repo } = parsed;const cloneDir = await ensureCloneDir(options.cloneDir);- const localPath = join(cloneDir, owner, repo);+ const localPath = join(cloneDir, repoSubPath(parsed));// Boot recovery marks only a known interrupted attempt. Old PortOS versions// cloned straight into localPath, so their partial checkout must be replaced@@ -74,8 +89,9 @@ export async function cloneRepo(url, options = {}) {};}- // Ensure owner directory exists- const ownerDir = join(cloneDir, owner);+ // Ensure the owner directory exists (for a namespaced host, and for a GitLab+ // subgroup path, that is several levels below the repos root).+ const ownerDir = dirname(localPath);if (!existsSync(ownerDir)) {await ensureDir(ownerDir);}@@ -87,7 +103,7 @@ export async function cloneRepo(url, options = {}) {const stagingPath = join(stagingRoot, repo);// Build clone command with shallow clone for space efficiency- const httpsUrl = `https://github.com/${owner}/${repo}.git`;+ const httpsUrl = repoCloneUrl(parsed);const args = ['clone','--depth', '1',@@ -156,29 +172,42 @@ export async function cloneRepo(url, options = {}) {* Remove only PortOS-owned clone staging directories older than twice the git* timeout. A freshly orphaned child may still be writing; the age gate leaves* it alone while bounding disk retained across repeated interrupted attempts.+ *+ * The sweep RECURSES because staging sits beside the checkout it will become,+ * and that is no longer always one level down: a namespaced host adds a+ * hostname level and a GitLab subgroup adds another. `MAX_STAGING_DEPTH` bounds+ * it to the deepest layout `repoSubPath` can produce, so the sweep never walks+ * into the clones themselves.*/+const MAX_STAGING_DEPTH = 4;+export async function reapStaleCloneStaging({ cloneDir = DEFAULT_CLONE_DIR, now = Date.now() } = {}) {- const owners = await readdir(cloneDir, { withFileTypes: true })- .catch(err => err.code === 'ENOENT' ? [] : Promise.reject(err));- let reaped = 0;- for (const owner of owners) {- if (!owner.isDirectory()) continue;- const ownerDir = join(cloneDir, owner.name);- // One unreadable owner directory (removed mid-sweep, or not ours to read)- // must not abort the sweep and leave every later owner's staging behind.- const entries = await readdir(ownerDir, { withFileTypes: true })+ // One unreadable directory (removed mid-sweep, or not ours to read) must not+ // abort the sweep and leave every later branch's staging behind.+ const sweep = async (dir, depth) => {+ const entries = await readdir(dir, { withFileTypes: true }).catch(err => {- console.error(`⚠️ Skipped clone staging sweep for ${owner.name}: ${err.message}`);+ if (err.code !== 'ENOENT') console.error(`⚠️ Skipped clone staging sweep for ${dir}: ${err.message}`);return [];});+ let reaped = 0;for (const entry of entries) {if (!entry.isDirectory()) continue;const match = entry.name.match(CLONE_STAGING_RE);- if (!match || now - Number(match[1]) < CLONE_STAGING_MAX_AGE_MS) continue;- await rm(join(ownerDir, entry.name), { recursive: true, force: true });- reaped++;+ if (match) {+ if (now - Number(match[1]) < CLONE_STAGING_MAX_AGE_MS) continue;+ await rm(join(dir, entry.name), { recursive: true, force: true });+ reaped++;+ } else if (depth < MAX_STAGING_DEPTH && !existsSync(join(dir, entry.name, '.git'))) {+ // A directory holding `.git` is a finished clone, not a namespace level —+ // descending into it would walk the studied repo's whole source tree.+ reaped += await sweep(join(dir, entry.name), depth + 1);+ }}- }+ return reaped;+ };++ const reaped = await sweep(cloneDir, 1);if (reaped > 0) console.log(`🧹 Reaped ${reaped} stale repository clone staging director${reaped === 1 ? 'y' : 'ies'}`);return reaped;}diff --git a/server/services/githubCloner.test.js b/server/services/repoCloner.test.jssimilarity index 62%rename from server/services/githubCloner.test.jsrename to server/services/repoCloner.test.jsindex 5e95b4561d..26a3538001 100644--- a/server/services/githubCloner.test.js+++ b/server/services/repoCloner.test.js@@ -18,7 +18,7 @@ vi.mock('../lib/fileUtils.js', () => ({import { existsSync } from 'fs';import { mkdtemp, readdir, rename, rm } from 'fs/promises';import { spawn } from '../lib/childProcess.js';-import { cloneRepo, reapStaleCloneStaging } from './githubCloner.js';+import { cloneRepo, reapStaleCloneStaging } from './repoCloner.js';const REPOS_DIR = '/repos';const OWNER_DIR = join(REPOS_DIR, 'acme');@@ -139,20 +139,37 @@ describe('cloneRepo', () => {describe('reapStaleCloneStaging', () => {const directory = name => ({ name, isDirectory: () => true });+ // The sweep walks a TREE now (a namespaced host and a GitLab subgroup each add+ // a level), so the fixtures are a path → entries map rather than a call+ // sequence — a sequence would silently encode one particular walk order.+ const mockTree = (tree, { clones = [] } = {}) => {+ readdir.mockImplementation(async (dir) => {+ const entries = tree[String(dir)];+ if (!entries) throw Object.assign(new Error('nope'), { code: 'ENOENT' });+ if (entries instanceof Error) throw entries;+ return entries;+ });+ // A directory holding `.git` is a finished clone; the sweep must not walk in.+ existsSync.mockImplementation(path => clones.includes(String(path).replace(/[/\\]\.git$/, '')));+ };+beforeEach(() => {vi.clearAllMocks();+ readdir.mockReset();+ existsSync.mockReset();rm.mockResolvedValue();vi.spyOn(console, 'error').mockImplementation(() => {});});it('reaps only expired PortOS clone staging directories', async () => {- readdir- .mockResolvedValueOnce([directory('acme')])- .mockResolvedValueOnce([+ mockTree({+ [REPOS_DIR]: [directory('acme')],+ [OWNER_DIR]: [directory('.portos-clone-1000000000000-old123'),directory('.portos-clone-1999999999999-new123'),- directory('.unrelated'),- ]);+ directory('widgets'),+ ],+ }, { clones: [LOCAL_PATH] });await expect(reapStaleCloneStaging({cloneDir: REPOS_DIR,@@ -164,20 +181,44 @@ describe('reapStaleCloneStaging', () => {join(OWNER_DIR, '.portos-clone-1000000000000-old123'),{ recursive: true, force: true });+ // The finished clone is a leaf, not another namespace level.+ expect(readdir).not.toHaveBeenCalledWith(LOCAL_PATH, expect.anything());+ });++ it('reaps staging nested under a namespaced host and a GitLab subgroup', async () => {+ const hostDir = join(REPOS_DIR, 'gitlab.com');+ const groupDir = join(hostDir, 'example-group');+ const subgroupDir = join(groupDir, 'example-sub');+ mockTree({+ [REPOS_DIR]: [directory('gitlab.com')],+ [hostDir]: [directory('example-group')],+ [groupDir]: [directory('example-sub')],+ [subgroupDir]: [directory('.portos-clone-1000000000000-old123')],+ });++ await expect(reapStaleCloneStaging({+ cloneDir: REPOS_DIR,+ now: 2000000000000+ })).resolves.toBe(1);+ expect(rm).toHaveBeenCalledWith(+ join(subgroupDir, '.portos-clone-1000000000000-old123'),+ { recursive: true, force: true }+ );});it('reports an empty repos directory rather than throwing', async () => {- readdir.mockRejectedValueOnce(Object.assign(new Error('nope'), { code: 'ENOENT' }));+ mockTree({});await expect(reapStaleCloneStaging({ cloneDir: REPOS_DIR })).resolves.toBe(0);expect(rm).not.toHaveBeenCalled();});it('keeps sweeping after an unreadable owner directory', async () => {- readdir- .mockResolvedValueOnce([directory('locked'), directory('acme')])- .mockRejectedValueOnce(Object.assign(new Error('permission denied'), { code: 'EACCES' }))- .mockResolvedValueOnce([directory('.portos-clone-1000000000000-old123')]);+ mockTree({+ [REPOS_DIR]: [directory('locked'), directory('acme')],+ [join(REPOS_DIR, 'locked')]: Object.assign(new Error('permission denied'), { code: 'EACCES' }),+ [OWNER_DIR]: [directory('.portos-clone-1000000000000-old123')],+ });await expect(reapStaleCloneStaging({cloneDir: REPOS_DIR,@@ -190,3 +231,39 @@ describe('reapStaleCloneStaging', () => {);});});++describe('cloneRepo across hosts', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ readdir.mockReset();+ existsSync.mockReset();+ existsSync.mockImplementation(path => !String(path).endsWith('.git'));+ mkdtemp.mockImplementation(async (prefix) => `${prefix}staging`);+ readdir.mockResolvedValue([]);+ rename.mockResolvedValue();+ rm.mockResolvedValue();+ });++ it('clones a gitlab.com project from its own host, under a hostname-namespaced path', async () => {+ const child = createChild();+ spawn.mockReturnValue(child);++ const resultPromise = cloneRepo('https://gitlab.com/example-group/example-sub/example-repo');+ await vi.waitFor(() => expect(spawn).toHaveBeenCalled());+ child.emit('close', 0);++ const [, args] = spawn.mock.calls[0];+ expect(args).toContain('https://gitlab.com/example-group/example-sub/example-repo.git');+ await expect(resultPromise).resolves.toMatchObject({+ localPath: join(REPOS_DIR, 'gitlab.com', 'example-group', 'example-sub', 'example-repo'),+ owner: 'example-group/example-sub',+ repo: 'example-repo',+ });+ });++ it('rejects a URL on an unsupported host', async () => {+ await expect(cloneRepo('https://bitbucket.org/acme/widgets'))+ .rejects.toThrow('Invalid repository URL');+ expect(spawn).not.toHaveBeenCalled();+ });+});diff --git a/server/services/repoIntake.js b/server/services/repoIntake.jsindex 8f7962f3a2..84a2a09930 100644--- a/server/services/repoIntake.js+++ b/server/services/repoIntake.js@@ -1,7 +1,7 @@/**- * Post-clone intake for a GitHub repo captured into the Brain.+ * Post-clone intake for a repository captured into the Brain.*- * When a bare GitHub repo URL is captured (Quick Capture / the Inbox capture+ * When a bare repo URL is captured (Quick Capture / the Inbox capture* box), the link is cloned in the background. The user can tick two opt-in boxes* at capture time to have a CoS agent pick the clone up once it lands:*@@ -29,13 +29,8 @@ import { prepareScanReportDirectory, reportPathForId } from './malwareScanReportimport { resolveTrackerFilingBlock } from '../lib/workTracker.js';import { GENERIC_REPO_STUDY_LABEL_CONTRACT } from '../lib/dispatchLabels.js';import { normalizeRepoIntake } from '../lib/repoIntakeActions.js';--/** `owner/repo` when the link carries GitHub metadata, else its display title. */-const repoLabel = (link) => (- link?.gitHubOwner && link?.gitHubRepo- ? `${link.gitHubOwner}/${link.gitHubRepo}`- : (link?.title || link?.url || 'unknown repo')-);+import { pullRepo } from './repoCloner.js';+import { repoLinkLabel as repoLabel } from '../lib/repoLinkFields.js';/*** True when the link's recorded clone is readable on disk. Both actions read the@@ -130,7 +125,7 @@ export function buildRepoStudyContext(link, { appName, repoPath, trackerInstructconst featureMapInstruction = featureMapPath? `Read \`${featureMapPath}\` — ${appName}'s user-facing feature inventory — in full before you judge anything.`: `${appName} keeps no single feature inventory; build one from its README, \`docs/\`, and navigation/route definitions under \`${repoPath}\` before you judge anything.`;- return `A GitHub repository was captured into the Brain and cloned locally. Study it as a PRODUCT — what it lets its users do, how it is designed, and what it does well — and record the feature ideas and enhancements ${appName} should adopt in the work tracker.${requesterContext}+ return `A repository was captured into the Brain and cloned locally. Study it as a PRODUCT — what it lets its users do, how it is designed, and what it does well — and record the feature ideas and enhancements ${appName} should adopt in the work tracker.${requesterContext}## The repository under study@@ -237,10 +232,49 @@ export async function queueRepoStudy(link, targetAppId = PORTOS_APP_ID, studyConreturn {queued: true,taskId: result.id,- linkPatch: { repoStudy: { taskId: result.id, queuedAt: new Date().toISOString() } },+ linkPatch: {+ repoStudy: {+ taskId: result.id,+ queuedAt: new Date().toISOString(),+ // Kept on the record so the Links tab can pre-fill the re-study form+ // with the brief the last run was given instead of a blank box.+ ...(studyContext?.trim() ? { studyContext: studyContext.trim() } : {}),+ },+ },};}+/**+ * Re-study an already-cloned repo on demand, optionally refreshing the clone+ * first. This is the Links tab's "Update & study" button: same `repo-study`+ * dispatch as the capture-time opt-in, with a study brief the user writes at the+ * moment they ask for it.+ *+ * A failed pull does NOT abort the study — the clone on disk is still readable,+ * and a repo that has been force-pushed or re-tagged upstream would otherwise be+ * permanently un-studyable. The pull outcome is reported so the caller can say+ * the study ran against a stale checkout.+ *+ * @returns {Promise<{ queued: boolean, reason?: string, taskId?: string,+ * linkPatch?: object, pulled?: { ok: boolean, error?: string } }>}+ */+export async function restudyRepoLink(link, { pull = true, targetAppId, studyContext, providerId, model, effort } = {}) {+ if (!isCloneReadable(link)) return { queued: false, reason: 'not-cloned' };++ const pulled = pull+ ? await pullRepo(link.localPath).then(+ () => ({ ok: true }),+ (err) => {+ console.error(`⚠️ Pull before repo study failed for link ${link.id}: ${err.message}`);+ return { ok: false, error: err.message };+ },+ )+ : undefined;++ const result = await queueRepoStudy(link, targetAppId, studyContext, { providerId, model, effort });+ return pulled ? { ...result, pulled } : result;+}+const INTAKE_QUEUERS = { malwareScan: queueMalwareScan, learn: queueRepoStudy };/**diff --git a/server/services/repoIntake.test.js b/server/services/repoIntake.test.jsindex 7c68604cb5..ede3bc7c32 100644--- a/server/services/repoIntake.test.js+++ b/server/services/repoIntake.test.js@@ -4,6 +4,7 @@ const addTask = vi.fn();const getAppById = vi.fn();const readOriginRemoteUrl = vi.fn();const existsSync = vi.fn();+const pullRepo = vi.fn();vi.mock('./cos.js', () => ({ addTask: (...args) => addTask(...args) }));vi.mock('./apps.js', () => ({@@ -15,6 +16,7 @@ vi.mock('./malwareScanReports.js', () => ({reportPathForId: (id) => `/scans/${id}.md`,}));vi.mock('fs', () => ({ existsSync: (...args) => existsSync(...args) }));+vi.mock('./repoCloner.js', () => ({ pullRepo: (...args) => pullRepo(...args) }));// The REAL workTracker resolution runs — the tracker instructions in the prompt// are what these tests assert. Only its one shell-out is stubbed; the tracker is// steered through the app's own `workTracker` setting, as a user would.@@ -22,14 +24,14 @@ vi.mock('../lib/gitRemote.js', () => ({readOriginRemoteUrl: (...args) => readOriginRemoteUrl(...args),}));-const { queueMalwareScan, queueRepoStudy, runRepoIntake, buildRepoStudyContext } = await import('./repoIntake.js');+const { queueMalwareScan, queueRepoStudy, restudyRepoLink, runRepoIntake, buildRepoStudyContext } = await import('./repoIntake.js');const LINK = {id: 'link-1',url: 'https://github.com/example-owner/example-repo',title: 'example-owner/example-repo',- gitHubOwner: 'example-owner',- gitHubRepo: 'example-repo',+ repoOwner: 'example-owner',+ repoName: 'example-repo',localPath: '/repos/example-owner/example-repo',};@@ -41,6 +43,7 @@ beforeEach(() => {getAppById.mockResolvedValue(APP);readOriginRemoteUrl.mockResolvedValue(null);addTask.mockImplementation(async () => ({ id: 'task-abc' }));+ pullRepo.mockResolvedValue({ success: true });});describe('queueMalwareScan', () => {@@ -300,3 +303,42 @@ describe('runRepoIntake', () => {expect(patch.repoStudy).toEqual({ taskId: 'task-study', queuedAt: expect.any(String) });});});++describe('restudyRepoLink', () => {+ it('refreshes the clone, then queues the study with the caller\'s brief', async () => {+ const result = await restudyRepoLink(LINK, { pull: true, studyContext: 'look at its offline sync' });++ expect(pullRepo).toHaveBeenCalledWith(LINK.localPath);+ expect(result).toMatchObject({ queued: true, taskId: 'task-abc', pulled: { ok: true } });+ expect(addTask.mock.calls[0][0].context).toContain('look at its offline sync');+ // The brief is stamped on the link so the form reopens pre-filled.+ expect(result.linkPatch.repoStudy.studyContext).toBe('look at its offline sync');+ });++ it('skips the pull when the caller opted out', async () => {+ const result = await restudyRepoLink(LINK, { pull: false });++ expect(pullRepo).not.toHaveBeenCalled();+ expect(result.queued).toBe(true);+ expect(result).not.toHaveProperty('pulled');+ });++ // A force-pushed or re-tagged upstream must not make a repo permanently+ // un-studyable — the clone on disk is still readable.+ it('still queues the study when the pull fails, and reports the failure', async () => {+ pullRepo.mockRejectedValue(new Error('diverged'));++ const result = await restudyRepoLink(LINK, {});++ expect(result).toMatchObject({ queued: true, pulled: { ok: false, error: 'diverged' } });+ expect(addTask).toHaveBeenCalled();+ });++ it('refuses to pull or queue against a clone that is gone from disk', async () => {+ existsSync.mockReturnValue(false);++ await expect(restudyRepoLink(LINK, {})).resolves.toEqual({ queued: false, reason: 'not-cloned' });+ expect(pullRepo).not.toHaveBeenCalled();+ expect(addTask).not.toHaveBeenCalled();+ });+});