Skip to content

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

move per-host repo behavior into the REPO_HOSTS table and share the clone-link route guard

[._.]/ Adam Eivya60c1feabab4
diff --git a/client/src/components/apps/tabs/SubmodulesTab.jsx b/client/src/components/apps/tabs/SubmodulesTab.jsx
index 93f0b34fe1..0f3c12bac4 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/repoUrl';
+import { parseRepoUrl, repoBrowseUrl } 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;
@@ -13,11 +13,12 @@ const needsUpdate = (sub) => sub.behind > 0 || sub.outOfSync || !sub.initialized
/**
* Browsable URL for a submodule's remote. `.gitmodules` commonly declares the
* scp-style SSH form (`[email protected]:owner/repo`), which is not a link a
- * browser can follow — normalize it rather than href-ing it raw.
+ * browser can follow — normalize it rather than href-ing it raw. Host-generic:
+ * a gitlab.com submodule earns the same link.
*/
function repoHref(url) {
- const parsed = parseGitHubUrl(url || '');
- if (parsed) return `https://github.com/${parsed.owner}/${parsed.repo}`;
+ const parsed = parseRepoUrl(url || '');
+ if (parsed) return repoBrowseUrl(parsed);
return /^https?:\/\//i.test(url || '') ? url.replace(/\.git$/, '') : null;
}
diff --git a/client/src/components/brain/RepoRestudyPanel.jsx b/client/src/components/brain/RepoRestudyPanel.jsx
index afb23ec092..8c7a6b85f7 100644
--- a/client/src/components/brain/RepoRestudyPanel.jsx
+++ b/client/src/components/brain/RepoRestudyPanel.jsx
@@ -4,7 +4,7 @@ import * as api from '../../services/api';
import toast from '../ui/Toast';
import BrailleSpinner from '../BrailleSpinner';
import RepoStudyFields from './RepoStudyFields';
-import { useRepoStudyConfig } from '../../hooks';
+import { useAsyncAction, useRepoStudyConfig } from '../../hooks';
/**
* The Links tab's on-demand "Update & study" form for an already-cloned repo:
@@ -27,29 +27,19 @@ export default function RepoRestudyPanel({ link, onClose, onQueued }) {
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;
+ const [handleSubmit, submitting] = useAsyncAction(async () => {
+ const result = await api.studyBrainLink(link.id, { pull, ...study.studyPayload() }, { silent: true });
// 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'
- );
+ const pullFailed = result.pulled?.ok === false;
+ toast[pullFailed ? 'warning' : 'success'](pullFailed
+ ? 'Study queued — the pull failed, so it reads the existing checkout'
+ : 'Study queued — track it in Chief of Staff');
onQueued?.(result.link);
onClose?.();
- };
+ }, { errorMessage: 'Failed to queue study' });
return (
<div className="mt-2 w-full rounded-lg border border-port-border bg-port-bg/60 p-3 space-y-2">
@@ -58,7 +48,7 @@ export default function RepoRestudyPanel({ link, onClose, onQueued }) {
<h4 className="text-sm font-medium text-gray-200">Update &amp; study this repo</h4>
<button
onClick={onClose}
- className="ml-auto p-1 text-gray-400 hover:text-white transition-colors"
+ className="ml-auto flex min-h-[44px] min-w-[44px] items-center justify-center text-gray-400 hover:text-white transition-colors"
title="Close" aria-label="Close study form"
>
<X size={14} />
diff --git a/client/src/components/brain/RepoStudyFields.jsx b/client/src/components/brain/RepoStudyFields.jsx
index fee35a5193..54ba540060 100644
--- a/client/src/components/brain/RepoStudyFields.jsx
+++ b/client/src/components/brain/RepoStudyFields.jsx
@@ -20,14 +20,14 @@ import AgentJobProviderFields from '../cos/AgentJobProviderFields';
*/
export default function RepoStudyFields({
idPrefix,
- managedApps = [],
+ managedApps,
targetAppId,
setTargetAppId,
- studyContext = '',
+ studyContext,
setStudyContext,
- providerOverride = { providerId: '', model: '', effort: '' },
- providers = [],
- activeProviderId = '',
+ providerOverride,
+ providers,
+ activeProviderId,
setProviderOverride,
contextLabel = 'Study context',
contextPlaceholder = 'What should the agent look for, and where might an implementation fit?',
diff --git a/client/src/components/brain/tabs/LinksTab.jsx b/client/src/components/brain/tabs/LinksTab.jsx
index ea3f42fa44..5bafd12b04 100644
--- a/client/src/components/brain/tabs/LinksTab.jsx
+++ b/client/src/components/brain/tabs/LinksTab.jsx
@@ -56,11 +56,13 @@ function normalizeUrl(raw) {
return normalizeUrlShared(raw, { allowGit: true, requireDot: true });
}
+const REPO_TYPE_COLOR = 'bg-purple-500/20 text-purple-400 border-purple-500/30';
+
const LINK_TYPE_COLORS = {
- repo: 'bg-purple-500/20 text-purple-400 border-purple-500/30',
+ repo: REPO_TYPE_COLOR,
// 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',
+ github: REPO_TYPE_COLOR,
article: 'bg-blue-500/20 text-blue-400 border-blue-500/30',
documentation: 'bg-green-500/20 text-green-400 border-green-500/30',
tool: 'bg-yellow-500/20 text-yellow-400 border-yellow-500/30',
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index f105c3b016..471a99dbb1 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. |
-| `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). |
+| `repoUrl.js` | `parseRepoUrl(url)` / `isRepoUrl(url)` / `repoBrowseUrl(parsed)` / `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/repoUrl.js b/client/src/lib/repoUrl.js
index 6ce71ff85d..e608fe65e6 100644
--- a/client/src/lib/repoUrl.js
+++ b/client/src/lib/repoUrl.js
@@ -12,12 +12,25 @@
* `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.
+// The host allowlist, and the two behaviors that actually differ between hosts.
+// They live IN the table rather than as `host === 'github.com'` branches further
+// down, so adding a host is one entry here and nothing else — and so each flag
+// has to be decided deliberately for the new host rather than inherited from
+// whichever existing host the branch happened to compare against.
+//
+// provider stable id stored on a link record (`repoHost` holds the
+// hostname itself)
+// nestedNamespaces the host nests groups arbitrarily (GitLab subgroups), so
+// everything before the last path segment is the namespace.
+// GitHub has no subgroups: anything past owner/repo is a
+// deep link.
+// flatClonePath LEGACY CARVE-OUT — clone to `<owner>/<repo>` with no
+// hostname level, so clones made before PortOS supported a
+// second host stay exactly where their link record says they
+// are. Never set this for a newly added host.
export const REPO_HOSTS = Object.freeze({
- 'github.com': 'github',
- 'gitlab.com': 'gitlab',
+ 'github.com': { provider: 'github', nestedNamespaces: false, flatClonePath: true },
+ 'gitlab.com': { provider: 'gitlab', nestedNamespaces: true, flatClonePath: false },
});
// The owner/repo pair is a PATH OPERAND, not just a label: the cloner clones
@@ -56,15 +69,15 @@ const RESERVED_PATH_SEGMENTS = new Set([
]);
/**
- * 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).
+ * Parse a repository URL into `{ host, provider, owner, repo }`, 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}
+ * @returns {{ host: string, provider: string, owner: string, repo: string } | null}
*/
export function parseRepoUrl(url) {
if (!url) return null;
@@ -74,8 +87,8 @@ export function parseRepoUrl(url) {
if (!match) return null;
const host = match[1].toLowerCase().replace(/^www\./, '').replace(/:\d+$/, '');
- const provider = REPO_HOSTS[host];
- if (!provider) return null;
+ const hostConfig = REPO_HOSTS[host];
+ if (!hostConfig) return null;
// Drop the query/hash, then GitLab's `/-/` deep-link separator, then walk the
// remaining segments until a host UI route word.
@@ -91,11 +104,8 @@ export function parseRepoUrl(url) {
}
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])
+ const ownerSegments = hostConfig.nestedNamespaces ? segments.slice(0, -1) : segments.slice(0, 1);
+ const repo = (hostConfig.nestedNamespaces ? segments[segments.length - 1] : segments[1])
.replace(/\.git$/i, '');
if (!ownerSegments.every(segment => OWNER_RE.test(segment))) return null;
@@ -103,10 +113,9 @@ export function parseRepoUrl(url) {
return {
host,
- provider,
+ provider: hostConfig.provider,
owner: ownerSegments.join('/'),
repo,
- isGitHub: provider === 'github',
};
}
@@ -120,6 +129,17 @@ export function isRepoUrl(url) {
return parseRepoUrl(url) !== null;
}
+/**
+ * The browsable web URL for a parsed repo — what to `href` when a record stores
+ * the scp-style SSH remote a browser can't follow.
+ *
+ * @param {{ host: string, owner: string, repo: string }} parsed
+ * @returns {string}
+ */
+export function repoBrowseUrl({ host, owner, repo }) {
+ return `https://${host}/${owner}/${repo}`;
+}
+
/**
* 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
@@ -130,7 +150,7 @@ export function isRepoUrl(url) {
*/
export function parseGitHubUrl(url) {
const parsed = parseRepoUrl(url);
- return parsed?.isGitHub ? { owner: parsed.owner, repo: parsed.repo, isGitHub: true } : null;
+ return parsed?.provider === 'github' ? { owner: parsed.owner, repo: parsed.repo, isGitHub: true } : null;
}
/**
diff --git a/client/src/services/apiBrain.js b/client/src/services/apiBrain.js
index 1fe9e02892..d9cb188ea1 100644
--- a/client/src/services/apiBrain.js
+++ b/client/src/services/apiBrain.js
@@ -12,7 +12,7 @@ export const updateBrainSettings = (settings, options = {}) => request('/brain/s
// Brain - Capture & Inbox
// `repoIntake` ({ malwareScan, learn, targetAppId, studyContext, providerId,
// model, effort }) is the capture box's post-clone agent opt-in; the server
-// ignores it unless the text is a bare GitHub repo URL. Provider pins apply to
+// ignores it unless the text is a bare repository URL. Provider pins apply to
// the optional repo study only. `note` is saved on a bare-URL link.
export const captureBrainThought = (text, providerOverride, modelOverride, { creative, repoIntake, note } = {}, options = {}) => request('/brain/capture', {
method: 'POST',
diff --git a/scripts/migrations/328-brain-link-repo-fields.js b/scripts/migrations/328-brain-link-repo-fields.js
index 0d7986f49d..99f3d21f62 100644
--- a/scripts/migrations/328-brain-link-repo-fields.js
+++ b/scripts/migrations/328-brain-link-repo-fields.js
@@ -21,10 +21,15 @@
*
* Idempotent: a record that already carries `isRepo` is skipped, so a re-run
* after a partial pass finishes the remainder without rewriting the rest.
+ *
+ * The legacy → new mapping is deliberately duplicated from
+ * `server/lib/repoLinkFields.js` rather than imported: a migration is a
+ * point-in-time record and must not drift when that module changes.
*/
-import { readdir, readFile } from 'fs/promises';
+import { readdir } from 'fs/promises';
import { join } from 'path';
+import { readJSONFile } from '../../server/lib/fileUtils.js';
import { writeJsonAtomic } from './_lib.js';
const LABEL = 'migration 328';
@@ -60,9 +65,7 @@ export default {
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 record = await readJSONFile(path, null);
const upgraded = upgradeLinkRecord(record);
if (!upgraded) continue;
await writeJsonAtomic(path, upgraded);
diff --git a/server/lib/README.md b/server/lib/README.md
index 1b1bf9060f..42c37ad340 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -276,7 +276,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `gitOutputParsers.js` | `parseStatus`, `parseDiffStat`, `parseBranchVerboseLine`, `parseSubmoduleStatusLine`/`SUBMODULE_STATUS_RE`, `extractAgentSummary` — pure parsers turning git command output into structured data for `git.js`. `extractAgentSummary` anchors on `agentOutputMarkers`' completion marker so a TUI agent's PR body carries its sentinel summary, not the lifecycle telemetry above it. `isBenignConcurrentFetchRefRace(stderr)` reads a non-zero `git fetch` as a SUCCESS when its only failure is a lost compare-and-swap whose refs already hold the fetched commits — the routine outcome when the Git tab, `getRemoteBranches`, and CoS agent worktrees fetch one `.git` at once. |
| `gitRemote.js` | `getOriginInfo`, `classifyOriginRemote`, `parseGitRemoteUrl`, `readRemoteUrl`, `UPSTREAM_OWNER`/`UPSTREAM_REPO` — safely reads and classifies checkout remotes against PortOS or a caller-supplied canonical upstream. Used by self-update and managed integrations to detect forks. |
| `repoLinkFields.js` | `deriveRepoLinkFields(url)` / `normalizeRepoLinkFields(link)` / `linkIsRepo(link)` / `repoLinkLabel(link)` — the repository metadata a Brain link carries, plus the dual-write/tolerant-read shim that keeps the pre-multi-host `isGitHubRepo` field names readable across federated peers. |
-| `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. |
+| `repoUrl.js` | `parseRepoUrl(url)` → `{ host, provider, owner, repo }` / `isRepoUrl(url)` / `repoCloneUrl(parsed)` / `repoBrowseUrl(parsed)` / `parseGitHubUrl(url)` / `isGitHubRepoUrl(url)` — authoritative "is this a clonable repo URL?" rule, with per-host behavior (subgroup nesting, clone layout) in the `REPO_HOSTS` table. 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.json
index c2a0554456..69678d248b 100644
--- a/server/lib/apiRouteCatalog.generated.json
+++ b/server/lib/apiRouteCatalog.generated.json
@@ -2698,7 +2698,7 @@
"sources": [
{
"source": "server/routes/brainLinks.js",
- "line": 39
+ "line": 67
}
]
},
@@ -2709,7 +2709,7 @@
"sources": [
{
"source": "server/routes/brainLinks.js",
- "line": 91
+ "line": 119
}
]
},
@@ -2720,7 +2720,7 @@
"sources": [
{
"source": "server/routes/brainLinks.js",
- "line": 152
+ "line": 180
}
]
},
@@ -2731,7 +2731,7 @@
"sources": [
{
"source": "server/routes/brainLinks.js",
- "line": 79
+ "line": 107
}
]
},
@@ -2742,7 +2742,7 @@
"sources": [
{
"source": "server/routes/brainLinks.js",
- "line": 115
+ "line": 143
}
]
},
@@ -2753,7 +2753,7 @@
"sources": [
{
"source": "server/routes/brainLinks.js",
- "line": 164
+ "line": 192
}
]
},
@@ -2764,7 +2764,7 @@
"sources": [
{
"source": "server/routes/brainLinks.js",
- "line": 220
+ "line": 248
}
]
},
@@ -2775,7 +2775,7 @@
"sources": [
{
"source": "server/routes/brainLinks.js",
- "line": 199
+ "line": 227
}
]
},
@@ -2786,7 +2786,7 @@
"sources": [
{
"source": "server/routes/brainLinks.js",
- "line": 250
+ "line": 278
}
]
},
@@ -2808,7 +2808,7 @@
"sources": [
{
"source": "server/routes/brainLinks.js",
- "line": 286
+ "line": 301
}
]
},
@@ -2819,7 +2819,7 @@
"sources": [
{
"source": "server/routes/brainLinks.js",
- "line": 55
+ "line": 83
}
]
},
diff --git a/server/lib/brainValidation.js b/server/lib/brainValidation.js
index 9a72bb3fbc..ebb6ef2865 100644
--- a/server/lib/brainValidation.js
+++ b/server/lib/brainValidation.js
@@ -189,7 +189,7 @@ export const reviewRecordSchema = z.object({
// --- Input schemas for API endpoints ---
-// Opt-in post-clone agent actions for a captured GitHub repo URL. Keys derive
+// Opt-in post-clone agent actions for a captured repository URL. Keys derive
// from REPO_INTAKE_KEYS so the wire contract can't drift from the normalizer
// that reads it (server/lib/repoIntakeActions.js).
export const repoIntakeSchema = z.object(optionalBooleanMap(REPO_INTAKE_KEYS)).extend({
@@ -229,7 +229,7 @@ export const captureInputSchema = z.object({
// (vs a todo/reference). Creative notes are later batch-sendable into the
// creative catalog as ingredients (see catalog brain-bridge ingest).
creative: z.boolean().optional(),
- // Post-clone agent actions for a bare GitHub repo URL. `targetAppId` selects
+ // Post-clone agent actions for a bare repository URL. `targetAppId` selects
// the managed app whose tracker receives repo-study issues; omitted means
// PortOS for backward compatibility. Ignored for every other capture.
repoIntake: repoIntakeInputSchema
diff --git a/server/lib/repoIntakeActions.js b/server/lib/repoIntakeActions.js
index c4b4b7bc83..a5dfbfa813 100644
--- a/server/lib/repoIntakeActions.js
+++ b/server/lib/repoIntakeActions.js
@@ -1,5 +1,5 @@
/**
- * The opt-in post-clone agent actions a Brain capture can request for a GitHub
+ * The opt-in post-clone agent actions a Brain capture can request for a
* repo URL. Pure — the queueing itself lives in `services/repoIntake.js`, which
* pulls the whole CoS task graph; this half is safe to import from the link
* write path and from the Zod schemas.
diff --git a/server/lib/repoLinkFields.js b/server/lib/repoLinkFields.js
index 2dc7355171..b840fcbb69 100644
--- a/server/lib/repoLinkFields.js
+++ b/server/lib/repoLinkFields.js
@@ -21,8 +21,8 @@
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 one host the legacy GitHub-only mirror can describe. */
+const GITHUB_HOST = 'github.com';
/**
* The repo fields for a captured URL — new shape plus the legacy mirror.
@@ -34,14 +34,15 @@ const LEGACY_REPO_HOST = 'github.com';
*/
export function deriveRepoLinkFields(url) {
const parsed = parseRepoUrl(url);
+ const isGitHub = parsed?.host === GITHUB_HOST;
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,
+ isGitHubRepo: isGitHub,
+ gitHubOwner: isGitHub ? parsed.owner : null,
+ gitHubRepo: isGitHub ? parsed.repo : null,
};
}
@@ -60,7 +61,7 @@ export function normalizeRepoLinkFields(link) {
return {
...link,
isRepo: true,
- repoHost: LEGACY_REPO_HOST,
+ repoHost: GITHUB_HOST,
repoOwner: link.gitHubOwner ?? null,
repoName: link.gitHubRepo ?? null,
};
@@ -75,13 +76,15 @@ export function normalizeRepoLinkFields(link) {
export const linkIsRepo = (link) => Boolean(link?.isRepo ?? link?.isGitHubRepo);
/**
- * `owner/repo` for a link record (either shape), else its display title.
+ * `owner/repo` for a link record, else its display title. Reads only the new
+ * shape: every link reaches a caller through a `brainStorage` read, which has
+ * already run `normalizeRepoLinkFields`.
*
* @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');
+ return link?.repoOwner && link?.repoName
+ ? `${link.repoOwner}/${link.repoName}`
+ : (link?.title || link?.url || 'unknown repo');
}
diff --git a/server/lib/repoUrl.js b/server/lib/repoUrl.js
index 3366f05bae..7602a245e2 100644
--- a/server/lib/repoUrl.js
+++ b/server/lib/repoUrl.js
@@ -13,12 +13,25 @@
* `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.
+// The host allowlist, and the two behaviors that actually differ between hosts.
+// They live IN the table rather than as `host === 'github.com'` branches further
+// down, so adding a host is one entry here and nothing else — and so each flag
+// has to be decided deliberately for the new host rather than inherited from
+// whichever existing host the branch happened to compare against.
+//
+// provider stable id stored on a link record (`repoHost` holds the
+// hostname itself)
+// nestedNamespaces the host nests groups arbitrarily (GitLab subgroups), so
+// everything before the last path segment is the namespace.
+// GitHub has no subgroups: anything past owner/repo is a
+// deep link.
+// flatClonePath LEGACY CARVE-OUT — clone to `<owner>/<repo>` with no
+// hostname level, so clones made before PortOS supported a
+// second host stay exactly where their link record says they
+// are. Never set this for a newly added host.
export const REPO_HOSTS = Object.freeze({
- 'github.com': 'github',
- 'gitlab.com': 'gitlab',
+ 'github.com': { provider: 'github', nestedNamespaces: false, flatClonePath: true },
+ 'gitlab.com': { provider: 'gitlab', nestedNamespaces: true, flatClonePath: false },
});
// The owner/repo pair is a PATH OPERAND, not just a label: the cloner clones
@@ -57,15 +70,15 @@ const RESERVED_PATH_SEGMENTS = new Set([
]);
/**
- * 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).
+ * Parse a repository URL into `{ host, provider, owner, repo }`, 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}
+ * @returns {{ host: string, provider: string, owner: string, repo: string } | null}
*/
export function parseRepoUrl(url) {
if (!url) return null;
@@ -75,8 +88,8 @@ export function parseRepoUrl(url) {
if (!match) return null;
const host = match[1].toLowerCase().replace(/^www\./, '').replace(/:\d+$/, '');
- const provider = REPO_HOSTS[host];
- if (!provider) return null;
+ const hostConfig = REPO_HOSTS[host];
+ if (!hostConfig) return null;
// Drop the query/hash, then GitLab's `/-/` deep-link separator, then walk the
// remaining segments until a host UI route word.
@@ -92,11 +105,8 @@ export function parseRepoUrl(url) {
}
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])
+ const ownerSegments = hostConfig.nestedNamespaces ? segments.slice(0, -1) : segments.slice(0, 1);
+ const repo = (hostConfig.nestedNamespaces ? segments[segments.length - 1] : segments[1])
.replace(/\.git$/i, '');
if (!ownerSegments.every(segment => OWNER_RE.test(segment))) return null;
@@ -104,10 +114,9 @@ export function parseRepoUrl(url) {
return {
host,
- provider,
+ provider: hostConfig.provider,
owner: ownerSegments.join('/'),
repo,
- isGitHub: provider === 'github',
};
}
@@ -131,6 +140,17 @@ export function repoCloneUrl({ host, owner, repo }) {
return `https://${host}/${owner}/${repo}.git`;
}
+/**
+ * The browsable web URL for a parsed repo — what to `href` when a record stores
+ * the scp-style SSH remote a browser can't follow.
+ *
+ * @param {{ host: string, owner: string, repo: string }} parsed
+ * @returns {string}
+ */
+export function repoBrowseUrl({ host, owner, repo }) {
+ return `https://${host}/${owner}/${repo}`;
+}
+
/**
* 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
@@ -141,7 +161,7 @@ export function repoCloneUrl({ host, owner, repo }) {
*/
export function parseGitHubUrl(url) {
const parsed = parseRepoUrl(url);
- return parsed?.isGitHub ? { owner: parsed.owner, repo: parsed.repo, isGitHub: true } : null;
+ return parsed?.provider === 'github' ? { owner: parsed.owner, repo: parsed.repo, isGitHub: true } : null;
}
/**
diff --git a/server/lib/repoUrl.mirror.test.js b/server/lib/repoUrl.mirror.test.js
index ed45ab496a..50732dc7b6 100644
--- a/server/lib/repoUrl.mirror.test.js
+++ b/server/lib/repoUrl.mirror.test.js
@@ -31,6 +31,7 @@ const MIRRORED_NAMES = [
'RESERVED_PATH_SEGMENTS',
'parseRepoUrl',
'isRepoUrl',
+ 'repoBrowseUrl',
'parseGitHubUrl',
'isGitHubRepoUrl',
];
diff --git a/server/lib/repoUrl.test.js b/server/lib/repoUrl.test.js
index 644f3b0b0f..421f988c79 100644
--- a/server/lib/repoUrl.test.js
+++ b/server/lib/repoUrl.test.js
@@ -2,7 +2,7 @@ import { describe, it, expect } from 'vitest';
import { posixPath } from './testHelper.js';
import { join } from 'path';
-import { parseRepoUrl, isRepoUrl, repoCloneUrl, parseGitHubUrl, isGitHubRepoUrl } from './repoUrl.js';
+import { parseRepoUrl, isRepoUrl, repoCloneUrl, repoBrowseUrl, parseGitHubUrl, isGitHubRepoUrl } from './repoUrl.js';
const REPOS_ROOT = '/data/repos';
const clonePath = (url) => {
@@ -116,7 +116,6 @@ describe('parseRepoUrl across hosts', () => {
provider: 'gitlab',
owner: 'example-group',
repo: 'example-repo',
- isGitHub: false,
});
}
});
@@ -146,7 +145,10 @@ describe('parseRepoUrl across hosts', () => {
expect(isRepoUrl('https://bitbucket.org/example-owner/example-repo')).toBe(false);
});
- it('builds the https clone URL from the parsed host', () => {
+ it('builds the https clone and browse URLs from the parsed host', () => {
+ expect(repoBrowseUrl(parseRepoUrl('[email protected]:example-group/example-repo')))
+ .toBe('https://gitlab.com/example-group/example-repo');
+
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')))
diff --git a/server/routes/brainLinks.js b/server/routes/brainLinks.js
index 89ac40e99a..ef2e587c60 100644
--- a/server/routes/brainLinks.js
+++ b/server/routes/brainLinks.js
@@ -28,6 +28,34 @@ import { getScanReport } from '../services/malwareScanReports.js';
const router = Router();
+/**
+ * Resolve a link that has a readable clone, or throw the right 404/400. Every
+ * clone-reading action (open-folder aside, which only needs a path) shares these
+ * preconditions, so they are stated once rather than re-spelled per route.
+ */
+async function requireClonedRepoLink(id) {
+ const link = await brainService.getLinkById(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' });
+ }
+ return link;
+}
+
+/**
+ * How a `{ queued: false, reason }` from services/repoIntake.js is reported. A
+ * lookup rather than a ternary chain so a reason added there surfaces as itself
+ * instead of falling through to whichever branch happened to be last.
+ */
+const QUEUE_REASON_ERRORS = {
+ duplicate: (what) => new ServerError(`A ${what} for this repo is already pending or in progress`, { status: 409, code: 'DUPLICATE_TASK' }),
+ 'app-not-found': () => new ServerError('The app to file study issues against no longer exists', { status: 400, code: 'APP_NOT_FOUND' }),
+};
+const queueFailure = (reason, what) => (QUEUE_REASON_ERRORS[reason] ?? (() =>
+ new ServerError('Local clone folder does not exist', { status: 400, code: 'PATH_NOT_FOUND' })))(what);
+
// =============================================================================
// LINKS CRUD
// =============================================================================
@@ -248,26 +276,13 @@ router.post('/links/:id/open-folder', asyncHandler(async (req, res) => {
* capture-time "scan for malware" checkbox queue exactly the same run.
*/
router.post('/links/:id/scan', asyncHandler(async (req, res) => {
- 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 link = await requireClonedRepoLink(req.params.id);
// `not-cloned` here means the recorded localPath is gone from disk — the
// service re-checks existence so the background capture path can't queue a
// scan against a directory that was deleted after the clone.
const result = await queueMalwareScan(link);
- if (!result.queued) {
- throw result.reason === 'duplicate'
- ? new ServerError('A scan for this repo is already pending or in progress', { status: 409, code: 'DUPLICATE_TASK' })
- : new ServerError('Local clone folder does not exist', { status: 400, code: 'PATH_NOT_FOUND' });
- }
+ if (!result.queued) throw queueFailure(result.reason, 'scan');
// Record the pending scan the same way the capture-time path does, so a
// reload shows the "Scan queued" chip instead of re-arming the button (whose
// second click would 409 as a duplicate).
@@ -285,25 +300,10 @@ router.post('/links/:id/scan', asyncHandler(async (req, res) => {
*/
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 link = await requireClonedRepoLink(req.params.id);
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' });
- }
+ if (!result.queued) throw queueFailure(result.reason, 'study');
// 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);
diff --git a/server/services/brainStorage.js b/server/services/brainStorage.js
index d316d85286..f40d118b50 100644
--- a/server/services/brainStorage.js
+++ b/server/services/brainStorage.js
@@ -1031,19 +1031,21 @@ export const deleteMemoryEntry = (id) => remove('memories', id);
// Links
//
-// 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));
+// EVERY link leaves this module through `readLink`/`readLinks`, which apply
+// `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 — see
+// lib/repoLinkFields.js. Route through them when adding an accessor; the
+// persisted payload itself is never rewritten (the derivation belongs to
+// `createLinkFromUrl`, which owns the URL).
+const readLink = async (record) => normalizeRepoLinkFields(await record);
+const readLinks = async (records) => (await records).map(normalizeRepoLinkFields);
+export const getLinks = (filters) => readLinks(filters ? query('links', filters) : getAll('links'));
+export const getLinkById = (id) => readLink(getById('links', id));
+export const createLink = (data) => readLink(create('links', data));
+export const updateLink = (id, data) => readLink(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 = async (updates) => normalizeLinks(await updateMany('links', updates));
+export const reorderLinks = (updates) => readLinks(updateMany('links', updates));
export const deleteLink = (id) => remove('links', id);
// ─── Link summary index (issue #3509) ───────────────────────────────────────
@@ -1113,7 +1115,7 @@ export async function getLinksPage({ linkType, isRepo, limit = 50, offset = 0 }
const total = matching.length;
const pageIds = matching.slice(offset, offset + limit).map(([id]) => id);
- const page = normalizeLinks(await Promise.all(pageIds.map((id) => getById('links', id))));
+ const page = await readLinks(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 };
@@ -1135,7 +1137,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 ? normalizeRepoLinkFields(await getById('links', hit[0])) : null;
+ return hit ? readLink(getById('links', hit[0])) : null;
}
// Buckets (bookmark groups for links)
diff --git a/server/services/repoCloner.js b/server/services/repoCloner.js
index 56f2bac96c..b4de167d0c 100644
--- a/server/services/repoCloner.js
+++ b/server/services/repoCloner.js
@@ -8,10 +8,10 @@
import { spawn } from '../lib/childProcess.js';
import { existsSync } from 'fs';
-import { mkdtemp, readdir, rename, rm } from 'fs/promises';
+import { access, mkdtemp, readdir, rename, rm } from 'fs/promises';
import { dirname, join } from 'path';
import { ensureDir, PATHS } from '../lib/fileUtils.js';
-import { parseRepoUrl, isRepoUrl, repoCloneUrl, parseGitHubUrl, isGitHubRepoUrl } from '../lib/repoUrl.js';
+import { REPO_HOSTS, parseRepoUrl, repoCloneUrl } from '../lib/repoUrl.js';
// Default directory for cloned repos (can be configured in settings)
const DEFAULT_CLONE_DIR = PATHS.repos;
@@ -19,23 +19,19 @@ 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 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 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.
+ * A host flagged `flatClonePath` keeps the historical `<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);
+ return REPO_HOSTS[host]?.flatClonePath ? join(owner, repo) : join(host, owner, repo);
}
/**
@@ -181,6 +177,10 @@ export async function cloneRepo(url, options = {}) {
*/
const MAX_STAGING_DEPTH = 4;
+// A directory holding `.git` is a finished clone, not a namespace level —
+// descending into it would walk the studied repo's whole source tree.
+const isCheckout = (dir) => access(join(dir, '.git')).then(() => true, () => false);
+
export async function reapStaleCloneStaging({ cloneDir = DEFAULT_CLONE_DIR, now = Date.now() } = {}) {
// One unreadable directory (removed mid-sweep, or not ours to read) must not
// abort the sweep and leave every later branch's staging behind.
@@ -198,9 +198,7 @@ export async function reapStaleCloneStaging({ cloneDir = DEFAULT_CLONE_DIR, now
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.
+ } else if (depth < MAX_STAGING_DEPTH && !await isCheckout(join(dir, entry.name))) {
reaped += await sweep(join(dir, entry.name), depth + 1);
}
}
diff --git a/server/services/repoCloner.test.js b/server/services/repoCloner.test.js
index 26a3538001..89d64445c0 100644
--- a/server/services/repoCloner.test.js
+++ b/server/services/repoCloner.test.js
@@ -4,6 +4,7 @@ import { join } from 'node:path';
vi.mock('fs', () => ({ existsSync: vi.fn() }));
vi.mock('fs/promises', () => ({
+ access: vi.fn(),
mkdtemp: vi.fn(),
readdir: vi.fn(),
rename: vi.fn(),
@@ -16,7 +17,7 @@ vi.mock('../lib/fileUtils.js', () => ({
}));
import { existsSync } from 'fs';
-import { mkdtemp, readdir, rename, rm } from 'fs/promises';
+import { access, mkdtemp, readdir, rename, rm } from 'fs/promises';
import { spawn } from '../lib/childProcess.js';
import { cloneRepo, reapStaleCloneStaging } from './repoCloner.js';
@@ -150,13 +151,15 @@ describe('reapStaleCloneStaging', () => {
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$/, '')));
+ access.mockImplementation(async (path) => {
+ if (!clones.includes(String(path).replace(/[/\\]\.git$/, ''))) throw Object.assign(new Error('nope'), { code: 'ENOENT' });
+ });
};
beforeEach(() => {
vi.clearAllMocks();
readdir.mockReset();
- existsSync.mockReset();
+ access.mockReset();
rm.mockResolvedValue();
vi.spyOn(console, 'error').mockImplementation(() => {});
});
@@ -237,6 +240,7 @@ describe('cloneRepo across hosts', () => {
vi.clearAllMocks();
readdir.mockReset();
existsSync.mockReset();
+ access.mockReset();
existsSync.mockImplementation(path => !String(path).endsWith('.git'));
mkdtemp.mockImplementation(async (prefix) => `${prefix}staging`);
readdir.mockResolvedValue([]);
diff --git a/server/services/repoIntake.js b/server/services/repoIntake.js
index 84a2a09930..3b5a4e83e8 100644
--- a/server/services/repoIntake.js
+++ b/server/services/repoIntake.js
@@ -170,11 +170,16 @@ End with: the studied repo, its license, how many proposals you filed (with thei
}
/**
- * Queue the `repo-study` review of a cloned link against PortOS.
+ * Queue the `repo-study` review of a cloned link.
*
+ * @param {object} link
+ * @param {object} [study] the study knobs — `targetAppId` (the managed app whose
+ * tracker receives the issues; PortOS when absent), `studyContext` (the brief),
+ * and the optional `providerId`/`model`/`effort` pins for this one run. Same
+ * shape the capture-time intake stores, so both callers pass it straight through.
* @returns {Promise<{ queued: boolean, reason?: string, taskId?: string, linkPatch?: object }>}
*/
-export async function queueRepoStudy(link, targetAppId = PORTOS_APP_ID, studyContext, { providerId, model, effort } = {}) {
+export async function queueRepoStudy(link, { targetAppId, studyContext, providerId, model, effort } = {}) {
if (!isCloneReadable(link)) return { queued: false, reason: 'not-cloned' };
const app = await getAppById(targetAppId || PORTOS_APP_ID);
@@ -256,9 +261,10 @@ export async function queueRepoStudy(link, targetAppId = PORTOS_APP_ID, studyCon
* the study ran against a stale checkout.
*
* @returns {Promise<{ queued: boolean, reason?: string, taskId?: string,
- * linkPatch?: object, pulled?: { ok: boolean, error?: string } }>}
+ * linkPatch?: object, pulled: { ok: boolean, error?: string }|null }>}
+ * `pulled` is null when the caller opted out of the refresh.
*/
-export async function restudyRepoLink(link, { pull = true, targetAppId, studyContext, providerId, model, effort } = {}) {
+export async function restudyRepoLink(link, { pull = true, ...study } = {}) {
if (!isCloneReadable(link)) return { queued: false, reason: 'not-cloned' };
const pulled = pull
@@ -269,10 +275,9 @@ export async function restudyRepoLink(link, { pull = true, targetAppId, studyCon
return { ok: false, error: err.message };
},
)
- : undefined;
+ : null;
- const result = await queueRepoStudy(link, targetAppId, studyContext, { providerId, model, effort });
- return pulled ? { ...result, pulled } : result;
+ return { ...await queueRepoStudy(link, study), pulled };
}
const INTAKE_QUEUERS = { malwareScan: queueMalwareScan, learn: queueRepoStudy };
@@ -293,9 +298,7 @@ export async function runRepoIntake(link, intake) {
let patch = {};
for (const [key, queue] of Object.entries(INTAKE_QUEUERS)) {
if (!requested[key]) continue;
- const result = key === 'learn'
- ? await queue(link, requested.targetAppId, requested.studyContext, requested).catch(err => ({ queued: false, reason: err.message }))
- : await queue(link).catch(err => ({ queued: false, reason: err.message }));
+ const result = await queue(link, requested).catch(err => ({ queued: false, reason: err.message }));
if (result.queued) patch = { ...patch, ...result.linkPatch };
else console.error(`❌ Capture-time ${key} not queued for link ${link.id}: ${result.reason}`);
}
diff --git a/server/services/repoIntake.test.js b/server/services/repoIntake.test.js
index ede3bc7c32..8f34e0124b 100644
--- a/server/services/repoIntake.test.js
+++ b/server/services/repoIntake.test.js
@@ -109,7 +109,7 @@ describe('queueRepoStudy', () => {
it('files against the selected managed app', async () => {
const target = { id: 'app-2', name: 'Example App', repoPath: '/srv/example-app', workTracker: 'github' };
getAppById.mockImplementation(async id => id === target.id ? target : null);
- await queueRepoStudy(LINK, target.id);
+ await queueRepoStudy(LINK, { targetAppId: target.id });
expect(getAppById).toHaveBeenCalledWith(target.id);
expect(addTask.mock.calls[0][0].app).toBe(target.id);
expect(addTask.mock.calls[0][0].context).toContain('Example App');
@@ -118,11 +118,7 @@ describe('queueRepoStudy', () => {
});
it('passes the selected provider, model, and effort to the repo-study task', async () => {
- await queueRepoStudy(LINK, undefined, undefined, {
- providerId: 'codex',
- model: 'gpt-5',
- effort: 'high',
- });
+ await queueRepoStudy(LINK, { providerId: 'codex', model: 'gpt-5', effort: 'high' });
expect(addTask.mock.calls[0][0]).toEqual(expect.objectContaining({
provider: 'codex',
@@ -319,8 +315,7 @@ describe('restudyRepoLink', () => {
const result = await restudyRepoLink(LINK, { pull: false });
expect(pullRepo).not.toHaveBeenCalled();
- expect(result.queued).toBe(true);
- expect(result).not.toHaveProperty('pulled');
+ expect(result).toMatchObject({ queued: true, pulled: null });
});
// A force-pushed or re-tagged upstream must not make a repo permanently