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

file a brain capture that is only a URL straight to Links instead of classifying it

[._.]/ Adam Eivy8eb155ba0b33
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 0b2f44abe0..0a8a45e9f4 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -17,6 +17,10 @@
- **[issue-2952] On-device TRELLIS.2 renders now land correctly and show real progress** — validated the runner against the real TRELLIS.2 `generate.py` on Apple Silicon and fixed two things that showed up only on a live render: the finished `.glb` now saves to the exact spot PortOS serves it from (previously it could land one folder over and show as missing), and the progress bar now moves through the real stages of a render — loading the model, sampling, decoding the mesh, baking textures, exporting — instead of sitting at 0% for the whole multi-minute render and then jumping to done.
- **[issue-2952] Clear message when a 3D render needs Hugging Face access** — TRELLIS.2 pulls a gated model from Hugging Face the first time it runs, so a render on a machine that isn't signed in to Hugging Face used to fail with an unhelpful "generate exited 1". PortOS now recognizes that specific failure and tells you exactly what to do: accept the gated model's terms and sign in to Hugging Face (set an `HF_TOKEN` or run `huggingface-cli login`), then try again.
+## Brain
+
+- **Pasting a bare URL into the Brain inbox now saves it as a link** — capturing a thought that is nothing but a URL used to spend an AI classification call on it and then file it as an idea or an admin item, leaving the actual bookmark nowhere. A capture whose entire text is a URL now lands in **Brain → Links** exactly as if you'd added it there — hostname (or `owner/repo`) title, GitHub detection, and the same automatic clone for a repo — with no classifier call at all. The inbox still shows the capture, marked filed to Links with a **View** button that opens the Links tab, so a mis-detected one can be corrected with **Fix** (which moves it to the real destination and removes the bookmark it created). A URL wrapped in prose ("read this later https://example.com") is still an ordinary thought, as is a URL you capture with **Creative** on. Re-pasting a URL you already saved reuses the existing bookmark instead of failing. The dashboard's Quick Capture box, which handled this on its own, now uses the same path — so it, voice capture, and the inbox all behave identically.
+
## Internal
- **Agent guidance split into per-directory and on-demand files — the root `CLAUDE.md` drops from 51k to 32k characters** — the root memory file loads in full on every session, and it had grown past the size where Claude Code warns about a single memory file (~40k characters), so a third of what every session paid for was guidance that only applies in one directory or during one task. Content the codebase already answers on its own is gone: the `server/`/`client/src/` directory tour (`ls` shows it), the Tailwind design-token list (defined in `client/src/index.css`, and the copy had gone stale — it omitted `--port-accent-2`), the standard `npm start`/`npm run dev`/pm2 invocations (in `package.json` scripts), and the slashdo submodule mechanics (in `.gitmodules`). One stale claim was corrected rather than moved: the architecture intro still said data persists to JSON files in `data/`, contradicting the Storage backend policy further down the same file. The rest moved to where it loads on demand — `client/src/CLAUDE.md` (UI conventions, routing/deep-linking, the shared `Drawer` convention) and `server/CLAUDE.md` (schema parity, write serialization, peer fan-out in tests, prompt-template migrations) load only when working in those trees, while three new project skills (`portos-add-page`, `portos-socket-ui`, `portos-file-issue`) keep just a one-line description resident and load their bodies on invocation. The backup service's rsync-anchoring failure mode moved into `docs/BACKUP.md` beside the exclude-tier documentation it belongs with. Every safety-critical prohibition, the Security Model, the Storage backend policy, the AI Provider Usage Policy, and the Sensitive Data & Privacy rules stay in the always-loaded root file — a "never do X" rule must never move somewhere it might not be loaded when it matters. Each migrated block was moved verbatim, with a one-line pointer left behind at the source.
diff --git a/client/src/components/QuickBrainCapture.jsx b/client/src/components/QuickBrainCapture.jsx
index 1d4e43ae9c..cae5645a43 100644
--- a/client/src/components/QuickBrainCapture.jsx
+++ b/client/src/components/QuickBrainCapture.jsx
@@ -4,7 +4,7 @@ import { Send, Sparkles } from 'lucide-react';
import toast from './ui/Toast';
import * as api from '../services/api';
import { useLocalStorageBool } from '../hooks';
-import { isUrl as isUrlShared, normalizeUrl } from '../utils/urlNormalize';
+import { parseBareUrl } from '../lib/bareUrl';
export default function QuickBrainCapture() {
const [input, setInput] = useState('');
@@ -14,7 +14,9 @@ export default function QuickBrainCapture() {
// creative thought captured here is flagged for the catalog the same way.
const [creative, setCreative] = useLocalStorageBool('brain.captureCreative', false);
- const isUrl = useMemo(() => isUrlShared(input), [input]);
+ // Mirrors the server's filing rule (client/src/lib/bareUrl.js) so the hint and
+ // the Creative lockout match where the capture actually lands.
+ const isUrl = useMemo(() => !!parseBareUrl(input), [input]);
const handleSubmit = async (e) => {
e?.preventDefault();
@@ -27,29 +29,18 @@ export default function QuickBrainCapture() {
// Clear input immediately so user can keep typing
setInput('');
- if (isUrl) {
- const url = normalizeUrl(text, { allowGit: true });
- const result = await api.createBrainLink({ url }, { silent: true }).catch(err => {
- if (err.message?.includes('already exists')) {
- toast.error('This URL is already saved');
- } else {
- toast.error(err.message || 'Failed to save link');
- }
- setInput(prev => prev || text);
- return null;
- });
- if (result) {
- toast.success(result.isGitHubRepo ? 'GitHub repo added' : 'Link saved');
- }
- } else {
- const result = await api.captureBrainThought(text, undefined, undefined, { creative }, { silent: true }).catch(err => {
- toast.error(err.message || 'Failed to capture thought');
- setInput(prev => prev || text);
- return null;
- });
- if (result) {
- toast.success(result.message || 'Thought captured');
- }
+ // Everything goes through capture — the server files a text that is nothing
+ // but a URL straight to Links (re-pasting a saved URL reuses it instead of
+ // erroring), so this surface doesn't need its own link-vs-thought branch.
+ // It ignores the sticky Creative flag for a URL; dropping it here too keeps
+ // the request honest about what will be stored.
+ const result = await api.captureBrainThought(text, undefined, undefined, { creative: creative && !isUrl }, { silent: true }).catch(err => {
+ toast.error(err.message || 'Failed to capture');
+ setInput(prev => prev || text);
+ return null;
+ });
+ if (result) {
+ toast.success(result.message || 'Captured');
}
submittingRef.current = false;
setIsSubmitting(false);
diff --git a/client/src/components/QuickBrainCapture.test.jsx b/client/src/components/QuickBrainCapture.test.jsx
new file mode 100644
index 0000000000..eca189b8b7
--- /dev/null
+++ b/client/src/components/QuickBrainCapture.test.jsx
@@ -0,0 +1,67 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, fireEvent, waitFor } from '@testing-library/react';
+import { MemoryRouter } from 'react-router-dom';
+
+vi.mock('../services/api', () => ({
+ captureBrainThought: vi.fn(),
+}));
+vi.mock('./ui/Toast', () => ({
+ default: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() }),
+}));
+
+import { captureBrainThought } from '../services/api';
+import toast from './ui/Toast';
+import QuickBrainCapture from './QuickBrainCapture';
+
+const renderWidget = () => render(<MemoryRouter><QuickBrainCapture /></MemoryRouter>);
+
+const submit = (text) => {
+ fireEvent.change(screen.getByPlaceholderText('Thought, URL, or link...'), { target: { value: text } });
+ fireEvent.click(screen.getByLabelText('Capture'));
+};
+
+describe('QuickBrainCapture', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ localStorage.clear();
+ captureBrainThought.mockResolvedValue({ message: 'Saved to Links!' });
+ });
+
+ it('captures both thoughts and URLs through the same endpoint', async () => {
+ renderWidget();
+ submit('https://example.com');
+ await waitFor(() => expect(captureBrainThought).toHaveBeenCalled());
+ expect(captureBrainThought.mock.calls[0][0]).toBe('https://example.com');
+ });
+
+ it('surfaces the server message so a URL reads as saved to Links', async () => {
+ renderWidget();
+ submit('https://example.com');
+ await waitFor(() => expect(toast.success).toHaveBeenCalledWith('Saved to Links!'));
+ });
+
+ it('does not flag a URL as creative even when the sticky flag is on', async () => {
+ localStorage.setItem('brain.captureCreative', 'true');
+ renderWidget();
+ submit('https://example.com');
+ await waitFor(() => expect(captureBrainThought).toHaveBeenCalled());
+ expect(captureBrainThought.mock.calls[0][3]).toEqual({ creative: false });
+ });
+
+ it('still flags ordinary text as creative when the flag is on', async () => {
+ localStorage.setItem('brain.captureCreative', 'true');
+ renderWidget();
+ submit('a city that dreams');
+ await waitFor(() => expect(captureBrainThought).toHaveBeenCalled());
+ expect(captureBrainThought.mock.calls[0][3]).toEqual({ creative: true });
+ });
+
+ it('hints which way the capture will go', () => {
+ renderWidget();
+ const input = screen.getByPlaceholderText('Thought, URL, or link...');
+ fireEvent.change(input, { target: { value: 'https://example.com' } });
+ expect(screen.getByText('Will save as link')).toBeInTheDocument();
+ fireEvent.change(input, { target: { value: 'call mom' } });
+ expect(screen.getByText('Will capture as thought')).toBeInTheDocument();
+ });
+});
diff --git a/client/src/components/brain/ConfidenceBadge.jsx b/client/src/components/brain/ConfidenceBadge.jsx
new file mode 100644
index 0000000000..54d2b23169
--- /dev/null
+++ b/client/src/components/brain/ConfidenceBadge.jsx
@@ -0,0 +1,18 @@
+import { getConfidenceColor } from './constants';
+
+/**
+ * Classifier confidence as a colored percentage.
+ *
+ * Renders nothing when `confidence` is undefined — an entry no model classified
+ * (a URL filed to Links, or any capture taken with auto-classify off) has no
+ * score to show, and a hard-coded 0% would read as "the AI was certain it was
+ * wrong" rather than "no AI was involved".
+ */
+export default function ConfidenceBadge({ confidence }) {
+ if (confidence === undefined) return null;
+ return (
+ <span className={`text-xs ${getConfidenceColor(confidence)}`}>
+ {Math.round(confidence * 100)}%
+ </span>
+ );
+}
diff --git a/client/src/components/brain/constants.js b/client/src/components/brain/constants.js
index bbcc0d17f3..8b06ddd2e5 100644
--- a/client/src/components/brain/constants.js
+++ b/client/src/components/brain/constants.js
@@ -57,6 +57,11 @@ export const DESTINATIONS = {
icon: BookOpen,
color: 'bg-pink-500/20 text-pink-400 border-pink-500/30'
},
+ links: {
+ label: 'Links',
+ icon: Link2,
+ color: 'bg-cyan-500/20 text-cyan-400 border-cyan-500/30'
+ },
goals: {
label: 'Goals',
icon: Target,
@@ -74,6 +79,23 @@ export const DESTINATIONS = {
}
};
+// Destinations a user can file an inbox entry to by hand (Route / Fix pickers).
+// Mirrors the server's `manualDestinationEnum` — NOT `Object.keys(DESTINATIONS)`,
+// which also holds display-only entries (`links`, `goals`, `journals`) the
+// resolve/fix endpoints reject.
+export const MANUAL_DESTINATIONS = ['people', 'projects', 'ideas', 'admin', 'memories'];
+
+/**
+ * Display info for where an inbox entry ended up. `filed` wins over the
+ * classifier's guess — a URL capture is filed to Links with no classification at
+ * all, and a corrected entry lives in its new destination. An unmapped value
+ * (a peer on newer code can sync one) degrades to Unknown instead of crashing
+ * the list.
+ */
+export const destinationInfo = (entry) =>
+ DESTINATIONS[entry.filed?.destination || entry.classification?.destination || 'unknown']
+ || DESTINATIONS.unknown;
+
// Inbox status colors
export const STATUS_COLORS = {
classifying: 'bg-port-accent/20 text-port-accent border-port-accent/30',
diff --git a/client/src/components/brain/tabs/InboxTab.jsx b/client/src/components/brain/tabs/InboxTab.jsx
index b1b2e6bcd6..1ca4715ed9 100644
--- a/client/src/components/brain/tabs/InboxTab.jsx
+++ b/client/src/components/brain/tabs/InboxTab.jsx
@@ -26,14 +26,30 @@ import { useLocalStorageBool } from '../../../hooks';
import {
DESTINATIONS,
- getConfidenceColor
+ MANUAL_DESTINATIONS,
+ destinationInfo
} from '../constants';
+import ConfidenceBadge from '../ConfidenceBadge';
import { timeAgo } from '../../../utils/formatters';
+import { parseBareUrl } from '../../../lib/bareUrl';
import VoiceCapture from '../VoiceCapture';
+// Where a filed entry's "View" button points. A bare-URL capture is filed to the
+// links collection (see captureUrlAsLink) and lives in the Links tab; every
+// other destination is a Memory record.
+const filedRecordHref = (filed) => filed.destination === 'links'
+ ? '/brain/links'
+ : `/brain/memory?type=${filed.destination}&id=${filed.destinationId}`;
+
+const filedRecordTitle = (filed) => filed.destination === 'links' ? 'View in Links' : 'View in Memory';
+
export default function InboxTab({ onRefresh, settings }) {
const navigate = useNavigate();
const [inputText, setInputText] = useState('');
+ // Previews the server's filing decision with the mirrored predicate it uses
+ // (client/src/lib/bareUrl.js), so the hint and the Creative lockout can't
+ // promise a destination the server won't pick.
+ const inputIsUrl = !!parseBareUrl(inputText);
// Sticky "Creative" capture mode (shared localStorage key with Quick Capture):
// when on, captured thoughts are flagged so they can later be batch-sent to the
// creative catalog (vs todos/refs that stay out).
@@ -95,18 +111,21 @@ export default function InboxTab({ onRefresh, settings }) {
if (lastText === text) return;
if (inputRef.current) inputRef.current.dataset.lastSubmit = text;
+ // The server files a URL to Links regardless of the sticky Creative flag;
+ // dropping it here keeps the optimistic entry matching what gets stored.
+ const asCreative = creative && !inputIsUrl;
const tempId = `_pending_${++tempIdCounter.current}`;
const optimisticEntry = {
id: tempId,
capturedText: text,
status: 'classifying',
capturedAt: new Date().toISOString(),
- ...(creative ? { creative: true } : {})
+ ...(asCreative ? { creative: true } : {})
};
setInputText('');
setEntries(prev => [optimisticEntry, ...prev]);
- const result = await api.captureBrainThought(text, undefined, undefined, { creative }, { silent: true }).catch(err => {
+ const result = await api.captureBrainThought(text, undefined, undefined, { creative: asCreative }, { silent: true }).catch(err => {
toast.error(err.message || 'Failed to capture thought');
setEntries(prev => prev.filter(e => e.id !== tempId));
return null;
@@ -116,6 +135,9 @@ export default function InboxTab({ onRefresh, settings }) {
if (result) {
setEntries(prev => prev.map(e => e.id === tempId ? result.inboxLog : e));
+ // A capture that was just a URL is filed to Links synchronously — no
+ // brain:classified event follows, so announce the outcome here.
+ if (result.link) toast.success(result.message || 'Saved to Links');
onRefresh?.();
}
};
@@ -299,10 +321,13 @@ export default function InboxTab({ onRefresh, settings }) {
onClick={() => setCreative(v => !v)}
aria-pressed={creative}
aria-label="Toggle creative capture mode"
- className={`px-3 py-3 rounded-lg border transition-colors flex items-center gap-1.5 text-sm ${creative
+ disabled={inputIsUrl}
+ className={`px-3 py-3 rounded-lg border transition-colors flex items-center gap-1.5 text-sm disabled:opacity-40 disabled:cursor-not-allowed ${creative
? 'bg-port-accent-2/20 text-port-accent-2 border-port-accent-2/40'
: 'bg-port-card text-gray-400 border-port-border hover:text-gray-200'}`}
- title="Creative mode: flag captures as creative ideas you can send to the Catalog"
+ title={inputIsUrl
+ ? 'URLs are saved as links, not creative ideas'
+ : 'Creative mode: flag captures as creative ideas you can send to the Catalog'}
>
<Sparkles className="w-4 h-4" />
<span className="hidden sm:inline">Creative</span>
@@ -318,7 +343,8 @@ export default function InboxTab({ onRefresh, settings }) {
</div>
<p className="mt-2 text-xs text-gray-500">
Capture a thought — type or use the mic. AI will classify and route it automatically.
- {creative && <span className="text-port-accent-2"> Creative mode on — captures are flagged for the Catalog.</span>}
+ {inputIsUrl && <span className="text-cyan-400"> That&rsquo;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 && (
<span> Confidence threshold: {Math.round(settings.confidenceThreshold * 100)}%</span>
)}
@@ -473,7 +499,7 @@ export default function InboxTab({ onRefresh, settings }) {
) : editingId !== entry.id && (
<div className="flex items-center gap-2 flex-wrap">
<span className="text-xs text-gray-500">Route to:</span>
- {['people', 'projects', 'ideas', 'admin', 'memories'].map(dest => {
+ {MANUAL_DESTINATIONS.map(dest => {
const destInfo = DESTINATIONS[dest];
const Icon = destInfo.icon;
return (
@@ -653,9 +679,9 @@ export default function InboxTab({ onRefresh, settings }) {
{showFiled && (
<div className="space-y-2">
{filedEntries.map(entry => {
- const destInfo = DESTINATIONS[entry.classification?.destination || 'unknown'];
+ const destInfo = destinationInfo(entry);
const DestIcon = destInfo.icon;
- const confidence = entry.classification?.confidence || 0;
+ const confidence = entry.classification?.confidence;
const isCorrected = entry.status === 'corrected';
return (
@@ -720,9 +746,7 @@ export default function InboxTab({ onRefresh, settings }) {
{destInfo.label}
</span>
- <span className={`text-xs ${getConfidenceColor(confidence)}`}>
- {Math.round(confidence * 100)}%
- </span>
+ <ConfidenceBadge confidence={confidence} />
{isCorrected && (
<span className="text-xs text-blue-400">
@@ -732,12 +756,9 @@ export default function InboxTab({ onRefresh, settings }) {
{entry.filed?.destinationId && (
<button
- onClick={() => {
- // Navigate to the record in memory tab
- window.location.href = `/brain/memory?type=${entry.filed.destination}&id=${entry.filed.destinationId}`;
- }}
+ onClick={() => navigate(filedRecordHref(entry.filed))}
className="flex items-center gap-1 px-2 py-1 text-xs rounded border border-port-border text-gray-400 hover:text-white transition-colors"
- title="View in Memory"
+ title={filedRecordTitle(entry.filed)}
>
<ExternalLink size={12} />
View
@@ -764,7 +785,7 @@ export default function InboxTab({ onRefresh, settings }) {
title="Select new destination"
>
<option value="">Select...</option>
- {['people', 'projects', 'ideas', 'admin', 'memories']
+ {MANUAL_DESTINATIONS
.filter(d => d !== entry.filed?.destination)
.map(d => (
<option key={d} value={d}>{DESTINATIONS[d].label}</option>
@@ -822,7 +843,7 @@ export default function InboxTab({ onRefresh, settings }) {
{showDone && (
<div className="space-y-2">
{doneEntries.map(entry => {
- const destInfo = DESTINATIONS[entry.classification?.destination || 'unknown'];
+ const destInfo = destinationInfo(entry);
const DestIcon = destInfo.icon;
return (
@@ -871,11 +892,9 @@ export default function InboxTab({ onRefresh, settings }) {
</span>
{entry.filed?.destinationId && (
<button
- onClick={() => {
- window.location.href = `/brain/memory?type=${entry.filed.destination}&id=${entry.filed.destinationId}`;
- }}
+ onClick={() => navigate(filedRecordHref(entry.filed))}
className="flex items-center gap-1 px-2 py-1 text-xs rounded border border-port-border text-gray-500 hover:text-white transition-colors"
- title="View in Memory"
+ title={filedRecordTitle(entry.filed)}
>
<ExternalLink size={12} />
View
diff --git a/client/src/components/brain/tabs/TrustTab.jsx b/client/src/components/brain/tabs/TrustTab.jsx
index 240ff4b958..150044303d 100644
--- a/client/src/components/brain/tabs/TrustTab.jsx
+++ b/client/src/components/brain/tabs/TrustTab.jsx
@@ -12,10 +12,10 @@ import toast from '../../ui/Toast';
import { FormField } from '../../ui/FormField';
import {
- DESTINATIONS,
STATUS_COLORS,
- getConfidenceColor
+ destinationInfo
} from '../constants';
+import ConfidenceBadge from '../ConfidenceBadge';
import { timeAgo } from '../../../utils/formatters';
export default function TrustTab({ onRefresh }) {
@@ -237,9 +237,10 @@ export default function TrustTab({ onRefresh }) {
) : (
entries.map(entry => {
const isExpanded = expandedId === entry.id;
- const destInfo = DESTINATIONS[entry.classification?.destination || 'unknown'];
+ const destInfo = destinationInfo(entry);
const DestIcon = destInfo.icon;
- const confidence = entry.classification?.confidence || 0;
+ // Absent for an entry no model classified (a URL filed to Links).
+ const confidence = entry.classification?.confidence;
return (
<div
@@ -257,9 +258,7 @@ export default function TrustTab({ onRefresh }) {
<DestIcon size={10} />
{destInfo.label}
</span>
- <span className={`text-xs ${getConfidenceColor(confidence)}`}>
- {Math.round(confidence * 100)}%
- </span>
+ <ConfidenceBadge confidence={confidence} />
<span className="text-xs text-gray-500">
{timeAgo(entry.capturedAt)}
</span>
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index cc807e1b24..2ee4909968 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -77,6 +77,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `a11yKeyboard.js` | `clickableProps(handler, { role?, disabled? })` → `{ role, tabIndex, onKeyDown }` and `onActivateKeyDown(handler)` — make a non-`<button>` element with an `onClick` keyboard-accessible (Enter/Space activation, focusable, `role="button"`). Spread `clickableProps` next to the existing `onClick`. Use instead of hand-rolling `role`/`tabIndex`/`onKeyDown` on clickable `<div>`/`<span>`/`<li>`. |
| `applyManuscriptEdits.js` | `applyEditsToContent(content, edits, anchorQuote)` — PREVIEW-ONLY client mirror of the server's accept splice (`server/services/pipeline/manuscriptFix.js`): locate each `find` (nearest the anchor when recurring), drop overlaps, replace bottom-up. Powers the Manuscript editor's whole-manuscript impact preview. |
| `audioRecorder.js` | `startMemoRecording()` → `{ stream, stop, cancel }` handle whose `stop()` resolves to `{ audioBase64, mimeType, peak, durationMs }` (16 kHz mono WAV, base64); the live `stream` lets a tuner tap the same mic. `createStreamAnalyser(stream, { fftSize })` → `{ analyser, context, close }` taps an `AnalyserNode` off an existing stream (no second getUserMedia). Plus `blobToWav16k`, `encodePcmToWav`, `pickRecordingMimeType`, `arrayBufferToBase64`. Standalone one-shot memo capture for catalog voice ingest — NOT the live voice-agent recorder in `services/voiceClient.js`. |
+| `bareUrl.js` | `parseBareUrl(text)` — the normalized URL when a capture's entire text is a URL, else null. Client mirror of the authoritative `server/lib/bareUrl.js` (parity enforced by `server/lib/bareUrl.mirror.test.js`), so the brain capture boxes preview the exact filing decision the server will make. Use this — not the looser `utils/urlNormalize.js` `isUrl` — anywhere the answer must match the server. |
| `boundedMap.js` | `evictOldest(map, max, onEvict?)` — evict oldest-first (`map.keys().next().value`) until a Map is within `max`, with an optional per-evicted-key teardown callback for a companion timer map; `ORPHAN_BUFFER_MAX` (64), the shared cap for the orphan-event race-buffers. The one home for the "stash an unmatched event in a `jobId → …` Map, evict the oldest on overflow" idiom shared by `useSceneRenderLifecycle`, `useImageGenQueue`, and `clientErrorReporter`. |
| `clientErrorReporter.js` | `reportClientError({ type, error?, message?, ... })` — POSTs window.onerror + unhandledrejection events to `/api/client-errors` with throttle + dedup, dropping browser-extension errors (see `extensionErrors.js`) before either gate. Wired from `main.jsx`; never call directly from React components. |
| `clinicianReport.js` | Pure builders for the MeatSpace clinician-export view (`/meatspace/export`). `buildClinicianReport({ tests, config })` → structured report model (blood panels grouped by category with reference ranges + out-of-range flags, plus a lifestyle summary); `reportToMarkdown(report)` → copy-paste markdown. Reuses the Blood tab's `REFERENCE_RANGES` / `getBloodValueStatus` so printed flags match the UI. Also exports `buildBloodTestModel`, `buildLifestyleModel`, `getCategoryForKey`, `formatRange`. |
diff --git a/client/src/lib/bareUrl.js b/client/src/lib/bareUrl.js
new file mode 100644
index 0000000000..26043f28d1
--- /dev/null
+++ b/client/src/lib/bareUrl.js
@@ -0,0 +1,77 @@
+/**
+ * Bare-URL detection — MIRROR of `server/lib/bareUrl.js` (authoritative there).
+ *
+ * The server files a capture whose entire text is a URL straight to the links
+ * collection. The capture boxes preview that decision (the "will be saved to
+ * Links" hint, and the Creative toggle it disables), so they must answer the
+ * question exactly the way the server will — a looser client predicate promises
+ * a filing the server won't perform.
+ *
+ * Port any change from the server copy verbatim; parity is enforced by
+ * `server/lib/bareUrl.mirror.test.js`. (Distinct from `utils/urlNormalize.js`'s
+ * `isUrl`, which answers a deliberately looser question for the Links quick-add.)
+ */
+
+// Explicit http(s) scheme — the URL constructor does the real validation below.
+const HTTP_SCHEME_PATTERN = /^https?:\/\//i;
+
+// SSH remote: git@host:owner/repo(.git)
+const SSH_GIT_PATTERN = /^git@[a-z0-9.-]+:[\w.-]+\/[\w.-]+$/i;
+
+// Scheme-less host[:port][/path] with a plausible alphabetic TLD:
+// "example.com", "sub.example.co.uk/path?q=1", "example.com:8080/x".
+const DOMAIN_LIKE_PATTERN = /^(?:[a-z0-9-]+\.)+[a-z]{2,24}(?::\d{2,5})?(?:[/?#]\S*)?$/i;
+
+// Several ccTLDs double as common file extensions (`.md` Moldova, `.sh` St
+// Helena, `.py` Paraguay…), so a scheme-less bare token like `notes.md` or
+// `deploy.sh` is far more likely a filename in a note than a host. Only the
+// scheme-less, path-less form is filtered — `https://foo.md` and `foo.md/page`
+// still read as URLs. Digit-bearing extensions (`mp4`, `h264`) need no entry:
+// DOMAIN_LIKE_PATTERN's all-alphabetic TLD already rejects them. Not exhaustive
+// by construction — an extension that isn't also a plausible TLD can't reach here.
+const FILE_EXTENSION_TAIL = new Set([
+ 'md', 'txt', 'log', 'csv', 'json', 'xml', 'yml', 'yaml', 'toml', 'ini', 'env', 'lock',
+ 'js', 'jsx', 'ts', 'tsx', 'css', 'html', 'htm', 'py', 'rb', 'sh', 'zsh', 'go', 'rs',
+ 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'zip', 'tar', 'gz',
+ 'png', 'jpg', 'jpeg', 'gif', 'svg', 'webp', 'mov', 'wav'
+]);
+
+/**
+ * True for a scheme-less, path-less `name.ext` whose tail is a known file
+ * extension (`notes.md`) rather than a host.
+ */
+function looksLikeFilename(token) {
+ if (/[/?#:]/.test(token)) return false;
+ const tail = token.slice(token.lastIndexOf('.') + 1).toLowerCase();
+ return FILE_EXTENSION_TAIL.has(tail);
+}
+
+/**
+ * If `text` is nothing but a single URL, return it normalized (an `https://`
+ * scheme is prepended to a bare host). Returns null for free text, multi-token
+ * input, a URL with surrounding prose, or a non-http(s)/git scheme.
+ *
+ * @param {string} text
+ * @returns {string|null}
+ */
+export function parseBareUrl(text) {
+ const trimmed = (text ?? '').trim();
+ // "Just a URL" means the whole capture is one token — any whitespace (a label,
+ // a trailing note, a second URL) makes it a thought that mentions a link.
+ if (!trimmed || /\s/.test(trimmed)) return null;
+
+ if (SSH_GIT_PATTERN.test(trimmed)) return trimmed;
+
+ let candidate = null;
+ if (HTTP_SCHEME_PATTERN.test(trimmed)) {
+ candidate = trimmed;
+ } else if (DOMAIN_LIKE_PATTERN.test(trimmed) && !looksLikeFilename(trimmed)) {
+ candidate = `https://${trimmed}`;
+ }
+ if (!candidate) return null;
+
+ // Final gate: the parser rejects shapes the regexes let through (bad port,
+ // malformed IPv6 host). The scheme needs no re-check — a candidate only exists
+ // here because it matched `http(s)://` or had `https://` prepended.
+ return URL.canParse(candidate) ? candidate : null;
+}
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index badf4b992b..76de64bd18 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -51,6 +51,7 @@ export * from './goalFeatureMap.js';
export * from './a11yKeyboard.js';
export * from './applyManuscriptEdits.js';
export * from './audioRecorder.js';
+export * from './bareUrl.js';
export * from './boundedMap.js';
export * from './clientErrorReporter.js';
export * from './clinicianReport.js';
diff --git a/docs/API.md b/docs/API.md
index 1aff5473bc..68acecf56d 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -239,7 +239,7 @@ PortOS is designed for personal/developer use on trusted networks. It implements
| Method | Endpoint | Description |
|--------|----------|-------------|
-| POST | `/brain/capture` | Capture and classify thought |
+| POST | `/brain/capture` | Capture and classify thought (a text that is only a URL is filed straight to `/brain/links` — no classifier call — and returns the `link` alongside the inbox entry) |
| GET | `/brain/inbox` | List inbox log with filters |
| POST | `/brain/review/resolve` | Resolve needs_review item |
| POST | `/brain/fix` | Correct misclassified item |
diff --git a/server/lib/README.md b/server/lib/README.md
index e69c6212b7..d918f15663 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -186,6 +186,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `syncWire.js` | Single source of truth for what fields cross the federated-peer wire (snapshot loop + per-record push agree). |
| `tailscale.js` | Locate the Tailscale CLI binary, flag the sandboxed macOS App-bundle build (which can't write `tailscale cert` output outside its container), and read backend state (`getTailscaleStatus` / `isTailscaleUp`) to know whether we're actually connected to the tailnet. |
| `httpsState.js` | Captures whether PortOS booted with HTTPS active. |
+| `bareUrl.js` | `parseBareUrl(text)` — returns the normalized URL when a captured string is nothing *but* a URL (bare host gets `https://`), else null. Drives the brain-capture short-circuit that files a pasted URL straight to Links instead of running the classifier. Stricter than the client's `urlNormalize.js` `isUrl` (needs a plausible TLD; http/https/`git@` only) because it picks a storage destination rather than a hint. |
| `isSafeHref.js` | Pure http(s)-only scheme check (`isSafeHref`) for user-supplied URL fields that get rendered as a clickable `<a href>` — rejects `javascript:`/`data:`/etc. stored-XSS payloads. Mirrors client `urlNormalize.js`'s `isHttpUrl`. |
| `networkExposure.js` | Snapshot of scheme + bind + cert mode for the dashboard's Network Exposure widget. |
diff --git a/server/lib/bareUrl.js b/server/lib/bareUrl.js
new file mode 100644
index 0000000000..2f44d0db0e
--- /dev/null
+++ b/server/lib/bareUrl.js
@@ -0,0 +1,82 @@
+/**
+ * Bare-URL detection for capture surfaces.
+ *
+ * A brain capture whose ENTIRE text is a URL is a bookmark, not a thought — the
+ * capture path files it straight to the links collection instead of spending a
+ * classifier LLM call on it. This module owns that decision so every capture
+ * surface (Inbox tab, voice capture, the API) behaves identically.
+ *
+ * Deliberately stricter than `client/src/utils/urlNormalize.js`'s `isUrl` (which
+ * answers a looser question for the Links quick-add): here the answer picks a
+ * storage destination, so a token like `v1.2` or `notes.md` must NOT read as a
+ * URL. A bare host therefore needs a plausible TLD, and only http/https/git@ are
+ * accepted (no `javascript:`/`data:`/`file:`).
+ *
+ * AUTHORITATIVE COPY — mirrored to `client/src/lib/bareUrl.js` so the capture
+ * boxes can preview this exact decision. Parity is enforced by
+ * `bareUrl.mirror.test.js`; port any change to both.
+ */
+
+// Explicit http(s) scheme — the URL constructor does the real validation below.
+const HTTP_SCHEME_PATTERN = /^https?:\/\//i;
+
+// SSH remote: git@host:owner/repo(.git)
+const SSH_GIT_PATTERN = /^git@[a-z0-9.-]+:[\w.-]+\/[\w.-]+$/i;
+
+// Scheme-less host[:port][/path] with a plausible alphabetic TLD:
+// "example.com", "sub.example.co.uk/path?q=1", "example.com:8080/x".
+const DOMAIN_LIKE_PATTERN = /^(?:[a-z0-9-]+\.)+[a-z]{2,24}(?::\d{2,5})?(?:[/?#]\S*)?$/i;
+
+// Several ccTLDs double as common file extensions (`.md` Moldova, `.sh` St
+// Helena, `.py` Paraguay…), so a scheme-less bare token like `notes.md` or
+// `deploy.sh` is far more likely a filename in a note than a host. Only the
+// scheme-less, path-less form is filtered — `https://foo.md` and `foo.md/page`
+// still read as URLs. Digit-bearing extensions (`mp4`, `h264`) need no entry:
+// DOMAIN_LIKE_PATTERN's all-alphabetic TLD already rejects them. Not exhaustive
+// by construction — an extension that isn't also a plausible TLD can't reach here.
+const FILE_EXTENSION_TAIL = new Set([
+ 'md', 'txt', 'log', 'csv', 'json', 'xml', 'yml', 'yaml', 'toml', 'ini', 'env', 'lock',
+ 'js', 'jsx', 'ts', 'tsx', 'css', 'html', 'htm', 'py', 'rb', 'sh', 'zsh', 'go', 'rs',
+ 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'zip', 'tar', 'gz',
+ 'png', 'jpg', 'jpeg', 'gif', 'svg', 'webp', 'mov', 'wav'
+]);
+
+/**
+ * True for a scheme-less, path-less `name.ext` whose tail is a known file
+ * extension (`notes.md`) rather than a host.
+ */
+function looksLikeFilename(token) {
+ if (/[/?#:]/.test(token)) return false;
+ const tail = token.slice(token.lastIndexOf('.') + 1).toLowerCase();
+ return FILE_EXTENSION_TAIL.has(tail);
+}
+
+/**
+ * If `text` is nothing but a single URL, return it normalized (an `https://`
+ * scheme is prepended to a bare host). Returns null for free text, multi-token
+ * input, a URL with surrounding prose, or a non-http(s)/git scheme.
+ *
+ * @param {string} text
+ * @returns {string|null}
+ */
+export function parseBareUrl(text) {
+ const trimmed = (text ?? '').trim();
+ // "Just a URL" means the whole capture is one token — any whitespace (a label,
+ // a trailing note, a second URL) makes it a thought that mentions a link.
+ if (!trimmed || /\s/.test(trimmed)) return null;
+
+ if (SSH_GIT_PATTERN.test(trimmed)) return trimmed;
+
+ let candidate = null;
+ if (HTTP_SCHEME_PATTERN.test(trimmed)) {
+ candidate = trimmed;
+ } else if (DOMAIN_LIKE_PATTERN.test(trimmed) && !looksLikeFilename(trimmed)) {
+ candidate = `https://${trimmed}`;
+ }
+ if (!candidate) return null;
+
+ // Final gate: the parser rejects shapes the regexes let through (bad port,
+ // malformed IPv6 host). The scheme needs no re-check — a candidate only exists
+ // here because it matched `http(s)://` or had `https://` prepended.
+ return URL.canParse(candidate) ? candidate : null;
+}
diff --git a/server/lib/bareUrl.mirror.test.js b/server/lib/bareUrl.mirror.test.js
new file mode 100644
index 0000000000..67616f50d9
--- /dev/null
+++ b/server/lib/bareUrl.mirror.test.js
@@ -0,0 +1,55 @@
+/**
+ * Mirror parity test for server/lib/bareUrl.js ↔ client/src/lib/bareUrl.js
+ *
+ * The server decides where a capture is filed; the client only previews that
+ * decision ("that's a URL — it will be saved to Links", and the Creative toggle
+ * it disables). A drifted client promises a filing the server won't perform —
+ * exactly the lie this mirror exists to prevent.
+ *
+ * Comparison strips comments, so the intentionally divergent header commentary
+ * does not fail the test — only logic does.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { readFileSync } from 'fs';
+import { resolve, dirname } from 'path';
+import { fileURLToPath } from 'url';
+import { compareDeclaration } from './mirrorParity.js';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+
+const SERVER_PATH = resolve(__dirname, 'bareUrl.js');
+const CLIENT_PATH = resolve(__dirname, '../../client/src/lib/bareUrl.js');
+
+const MIRRORED_NAMES = [
+ 'HTTP_SCHEME_PATTERN',
+ 'SSH_GIT_PATTERN',
+ 'DOMAIN_LIKE_PATTERN',
+ 'FILE_EXTENSION_TAIL',
+ 'looksLikeFilename',
+ 'parseBareUrl',
+];
+
+describe('bareUrl server↔client mirror parity', () => {
+ const serverSrc = readFileSync(SERVER_PATH, 'utf8');
+ const clientSrc = readFileSync(CLIENT_PATH, 'utf8');
+
+ it('both files are non-empty', () => {
+ expect(serverSrc.length).toBeGreaterThan(100);
+ expect(clientSrc.length).toBeGreaterThan(100);
+ });
+
+ for (const name of MIRRORED_NAMES) {
+ it(`${name} is present and identical on both sides (code only)`, () => {
+ const { serverDecl, clientDecl, serverNorm, clientNorm } =
+ compareDeclaration(serverSrc, clientSrc, name);
+
+ expect(serverDecl, `server/lib/bareUrl.js is missing: ${name}`).not.toBeNull();
+ expect(clientDecl, `client/src/lib/bareUrl.js is missing: ${name}`).not.toBeNull();
+ expect(
+ clientNorm,
+ `"${name}" diverged — the server copy is authoritative; port the change verbatim`,
+ ).toBe(serverNorm);
+ });
+ }
+});
diff --git a/server/lib/bareUrl.test.js b/server/lib/bareUrl.test.js
new file mode 100644
index 0000000000..ee0b2cd54c
--- /dev/null
+++ b/server/lib/bareUrl.test.js
@@ -0,0 +1,65 @@
+import { describe, it, expect } from 'vitest';
+import { parseBareUrl } from './bareUrl.js';
+
+describe('parseBareUrl', () => {
+ it('returns an explicit http(s) URL unchanged', () => {
+ expect(parseBareUrl('https://example.com/parks')).toBe('https://example.com/parks');
+ expect(parseBareUrl('http://example.com')).toBe('http://example.com');
+ });
+
+ it('trims surrounding whitespace and newlines (pasted URLs carry them)', () => {
+ expect(parseBareUrl(' https://example.com ')).toBe('https://example.com');
+ expect(parseBareUrl('https://example.com\n')).toBe('https://example.com');
+ });
+
+ it('prepends https:// to a bare host', () => {
+ expect(parseBareUrl('example.com')).toBe('https://example.com');
+ expect(parseBareUrl('sub.example.co.uk/path?q=1')).toBe('https://sub.example.co.uk/path?q=1');
+ expect(parseBareUrl('example.com:8080/x')).toBe('https://example.com:8080/x');
+ });
+
+ it('accepts an ssh git remote as-is', () => {
+ expect(parseBareUrl('[email protected]:owner/repo.git')).toBe('[email protected]:owner/repo.git');
+ });
+
+ it('rejects free text', () => {
+ expect(parseBareUrl('call mom about the trip')).toBeNull();
+ expect(parseBareUrl('idea')).toBeNull();
+ });
+
+ it('rejects a URL wrapped in prose — that is a thought that mentions a link', () => {
+ expect(parseBareUrl('read this https://example.com')).toBeNull();
+ expect(parseBareUrl('https://example.com and https://example.org')).toBeNull();
+ expect(parseBareUrl('https://example.com — great post')).toBeNull();
+ });
+
+ it('rejects dotted tokens that are not hosts', () => {
+ expect(parseBareUrl('v1.2')).toBeNull();
+ expect(parseBareUrl('e.g')).toBeNull();
+ });
+
+ it('rejects a bare filename whose extension doubles as a ccTLD', () => {
+ expect(parseBareUrl('notes.md')).toBeNull();
+ expect(parseBareUrl('deploy.sh')).toBeNull();
+ expect(parseBareUrl('train.py')).toBeNull();
+ });
+
+ it('still accepts those TLDs with a scheme or a path', () => {
+ expect(parseBareUrl('https://example.md')).toBe('https://example.md');
+ expect(parseBareUrl('example.md/page')).toBe('https://example.md/page');
+ });
+
+ it('rejects non-http schemes so a capture cannot file a javascript:/file: payload', () => {
+ expect(parseBareUrl('javascript:alert(1)')).toBeNull();
+ expect(parseBareUrl('data:text/html,<script>')).toBeNull();
+ expect(parseBareUrl('file:///etc/passwd')).toBeNull();
+ expect(parseBareUrl('ftp://example.com/x')).toBeNull();
+ });
+
+ it('rejects empty and non-string input', () => {
+ expect(parseBareUrl('')).toBeNull();
+ expect(parseBareUrl(' ')).toBeNull();
+ expect(parseBareUrl(null)).toBeNull();
+ expect(parseBareUrl(undefined)).toBeNull();
+ });
+});
diff --git a/server/lib/brainValidation.js b/server/lib/brainValidation.js
index 5eaa1d163c..ae6065efd5 100644
--- a/server/lib/brainValidation.js
+++ b/server/lib/brainValidation.js
@@ -1,8 +1,19 @@
import { z } from 'zod';
import { partialWithoutDefaults } from './zodCompat.js';
-// Destination enum
-export const destinationEnum = z.enum(['people', 'projects', 'ideas', 'admin', 'memories', 'unknown']);
+// Destination enum. `links` is reachable only from the bare-URL capture
+// short-circuit (a pasted URL is filed straight to the links collection) — the
+// classifier never picks it and the manual resolve/fix paths exclude it, since
+// filing an arbitrary note as a bookmark needs a URL it doesn't have.
+export const destinationEnum = z.enum(['people', 'projects', 'ideas', 'admin', 'memories', 'links', 'unknown']);
+
+// Destinations the classifier may pick — everything but `links`, which needs a
+// URL no model extracted. A hallucinated one falls to needs_review instead of
+// reaching fileToDestination.
+export const classifierDestinationEnum = destinationEnum.exclude(['links']);
+
+// Destinations a user can file to by hand from the inbox (see fileToDestination).
+export const manualDestinationEnum = classifierDestinationEnum.exclude(['unknown']);
// Project status enum
export const projectStatusEnum = z.enum(['active', 'waiting', 'blocked', 'someday', 'done']);
@@ -46,7 +57,7 @@ export const filedSchema = z.object({
export const correctionSchema = z.object({
correctedAt: z.string().datetime(),
previousDestination: destinationEnum,
- newDestination: destinationEnum.exclude(['unknown']),
+ newDestination: manualDestinationEnum,
note: z.string().max(500).optional()
});
@@ -189,14 +200,14 @@ export const captureInputSchema = z.object({
// Resolve review input schema
export const resolveReviewInputSchema = z.object({
inboxLogId: z.string().guid(),
- destination: destinationEnum.exclude(['unknown']),
+ destination: manualDestinationEnum,
editedExtracted: z.record(z.unknown()).optional()
});
// Fix classification input schema
export const fixInputSchema = z.object({
inboxLogId: z.string().guid(),
- newDestination: destinationEnum.exclude(['unknown']),
+ newDestination: manualDestinationEnum,
updatedFields: z.record(z.unknown()).optional(),
note: z.string().max(500).optional()
});
@@ -327,7 +338,7 @@ export const extractedMemorySchema = z.object({
// AI Classifier output schema (what we expect from the AI)
export const classifierOutputSchema = z.object({
- destination: destinationEnum,
+ destination: classifierDestinationEnum,
confidence: z.number().min(0).max(1),
title: z.string().min(1).max(200),
cleanedUp: z.string().max(10000).optional().default(''),
diff --git a/server/lib/brainValidation.test.js b/server/lib/brainValidation.test.js
index 71d6722ef0..f021a5a875 100644
--- a/server/lib/brainValidation.test.js
+++ b/server/lib/brainValidation.test.js
@@ -1,6 +1,8 @@
import { describe, it, expect } from 'vitest';
import {
destinationEnum,
+ manualDestinationEnum,
+ classifierOutputSchema,
projectStatusEnum,
ideaStatusEnum,
adminStatusEnum,
@@ -51,6 +53,27 @@ describe('brainValidation.js', () => {
expect(destinationEnum.safeParse('invalid').success).toBe(false);
expect(destinationEnum.safeParse('').success).toBe(false);
});
+
+ it('accepts links as a filed destination (bare-URL captures)', () => {
+ expect(destinationEnum.safeParse('links').success).toBe(true);
+ expect(filedSchema.safeParse({
+ destination: 'links',
+ destinationId: '11111111-1111-4111-8111-111111111111'
+ }).success).toBe(true);
+ });
+
+ it('keeps links out of the hand-filed destinations and the classifier menu', () => {
+ expect(manualDestinationEnum.safeParse('links').success).toBe(false);
+ expect(classifierOutputSchema.safeParse({
+ destination: 'links', confidence: 1, title: 'x', extracted: {}
+ }).success).toBe(false);
+ expect(resolveReviewInputSchema.safeParse({
+ inboxLogId: '11111111-1111-4111-8111-111111111111', destination: 'links'
+ }).success).toBe(false);
+ expect(fixInputSchema.safeParse({
+ inboxLogId: '11111111-1111-4111-8111-111111111111', newDestination: 'links'
+ }).success).toBe(false);
+ });
});
describe('projectStatusEnum', () => {
diff --git a/server/lib/index.js b/server/lib/index.js
index 3896f89b07..baddda3291 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -139,6 +139,7 @@ export * from './zipWriter.js';
// === Process execution ===
export * from './agentGuard/index.js';
export * from './agentSentinel.js';
+export * from './bareUrl.js';
export * from './bashResolver.js';
export * from './bufferedSpawn.js';
export * from './commandSecurity.js';
diff --git a/server/routes/brain.test.js b/server/routes/brain.test.js
index 9e216f85a4..083d12a111 100644
--- a/server/routes/brain.test.js
+++ b/server/routes/brain.test.js
@@ -59,7 +59,8 @@ vi.mock('../services/brain.js', () => ({
getLinks: vi.fn(),
getLinkById: vi.fn(),
getLinkByUrl: vi.fn(),
- createLink: vi.fn(),
+ createLinkFromUrl: vi.fn(),
+ cloneRepoInBackground: vi.fn(),
updateLink: vi.fn(),
reorderLinks: vi.fn(),
deleteLink: vi.fn(),
@@ -1511,18 +1512,25 @@ describe('Brain Routes', () => {
});
});
- describe('POST /api/brain/links (bucket + title derivation)', () => {
- it('derives a hostname title for a plain URL and stores bucketId', async () => {
+ describe('POST /api/brain/links', () => {
+ it('delegates creation to the shared service with the validated options', async () => {
brainService.getLinkByUrl.mockResolvedValue(null);
- brainService.createLink.mockImplementation(async (data) => ({ id: 'l9', ...data }));
+ brainService.createLinkFromUrl.mockImplementation(async (url, opts) => ({ id: 'l9', url, ...opts }));
const res = await request(app)
.post('/api/brain/links')
.send({ url: 'https://www.example.com/parks', bucketId: '11111111-1111-4111-8111-111111111111' });
expect(res.status).toBe(201);
- expect(brainService.createLink).toHaveBeenCalledWith(expect.objectContaining({
- title: 'example.com',
- bucketId: '11111111-1111-4111-8111-111111111111'
- }));
+ expect(brainService.createLinkFromUrl).toHaveBeenCalledWith(
+ 'https://www.example.com/parks',
+ expect.objectContaining({ bucketId: '11111111-1111-4111-8111-111111111111' })
+ );
+ });
+
+ it('409s on a duplicate URL without creating anything', async () => {
+ brainService.getLinkByUrl.mockResolvedValue({ id: 'l1' });
+ const res = await request(app).post('/api/brain/links').send({ url: 'https://example.com' });
+ expect(res.status).toBe(409);
+ expect(brainService.createLinkFromUrl).not.toHaveBeenCalled();
});
});
});
diff --git a/server/routes/brainLinks.js b/server/routes/brainLinks.js
index 0c4567ca57..8bea2873b4 100644
--- a/server/routes/brainLinks.js
+++ b/server/routes/brainLinks.js
@@ -26,42 +26,6 @@ import * as cos from '../services/cos.js';
const router = Router();
-/**
- * Extract a clean hostname from a URL (strip a leading www.), or null if unparseable.
- */
-function hostnameFromUrl(url) {
- try {
- return new URL(url).hostname.replace(/^www\./, '');
- } catch {
- return null;
- }
-}
-
-/**
- * Clone repo in background and update link record
- */
-async function cloneRepoInBackground(linkId, url) {
- // Update status to cloning
- await brainService.updateLink(linkId, { cloneStatus: 'cloning' });
-
- githubCloner.cloneRepo(url)
- .then(async (result) => {
- await brainService.updateLink(linkId, {
- localPath: result.localPath,
- cloneStatus: 'cloned',
- cloneError: null
- });
- console.log(`✅ Background clone complete: ${linkId}`);
- })
- .catch(async (err) => {
- await brainService.updateLink(linkId, {
- cloneStatus: 'failed',
- cloneError: err.message
- });
- console.error(`❌ Background clone failed: ${linkId} - ${err.message}`);
- });
-}
-
// =============================================================================
// LINKS CRUD
// =============================================================================
@@ -134,7 +98,7 @@ router.get('/links/:id', asyncHandler(async (req, res) => {
* Create a new link (quick-add with URL)
*/
router.post('/links', asyncHandler(async (req, res) => {
- const { url, title, description, linkType, tags, bucketId, bucketOrder, autoClone } = validateRequest(linkInputSchema, req.body);
+ const { url, ...options } = validateRequest(linkInputSchema, req.body);
// Check if URL already exists
const existing = await brainService.getLinkByUrl(url);
@@ -146,43 +110,10 @@ router.post('/links', asyncHandler(async (req, res) => {
});
}
- // Parse GitHub URL if applicable
- const parsed = githubCloner.parseGitHubUrl(url);
- const isGitHubRepo = !!parsed;
-
- // 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}`
- : (hostnameFromUrl(url) || url);
-
- // Create initial link record
- const linkData = {
- url,
- title: title || defaultTitle,
- description: description || '',
- linkType: linkType || (isGitHubRepo ? 'github' : 'other'),
- tags: tags || [],
- isGitHubRepo,
- gitHubOwner: parsed?.owner,
- gitHubRepo: parsed?.repo,
- localPath: null,
- cloneStatus: isGitHubRepo && autoClone !== false ? 'pending' : 'none',
- cloneError: null,
- ...(bucketId !== undefined ? { bucketId } : {}),
- ...(bucketOrder !== undefined ? { bucketOrder } : {})
- };
-
- const link = await brainService.createLink(linkData);
- console.log(`🔗 Created link: ${link.id} (${isGitHubRepo ? 'GitHub repo' : 'regular URL'})`);
-
- // If GitHub repo and auto-clone enabled, start clone in background
- if (isGitHubRepo && autoClone !== false) {
- cloneRepoInBackground(link.id, url).catch(err => {
- console.error(`❌ Background clone setup failed for ${link.id}: ${err.message}`);
- });
- }
-
+ // Title derivation, GitHub 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);
res.status(201).json(link);
}));
@@ -263,7 +194,7 @@ router.post('/links/:id/clone', asyncHandler(async (req, res) => {
}
// Start clone in background
- cloneRepoInBackground(link.id, link.url);
+ brainService.cloneRepoInBackground(link.id, link.url);
res.json({ message: 'Clone started', linkId: link.id });
}));
diff --git a/server/services/brain.js b/server/services/brain.js
index 61b438a186..a853583a37 100644
--- a/server/services/brain.js
+++ b/server/services/brain.js
@@ -19,6 +19,8 @@ import { runPromptThroughProvider } from '../lib/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 { parseBareUrl } from '../lib/bareUrl.js';
import {
classifierOutputSchema,
digestOutputSchema,
@@ -134,6 +136,16 @@ function safeParseJsonResponse(content) {
* AI classification runs in the background and emits a socket event on completion.
*/
export async function captureThought(text, providerOverride, modelOverride, { creative = false } = {}) {
+ // A capture that is nothing but a URL is a bookmark, not a thought: file it
+ // straight to Links exactly as the Links tab would, and skip the classifier
+ // LLM call entirely. This outranks the creative flag — a bare URL carries no
+ // prose for the Catalog to work from — so both capture boxes disable the
+ // Creative toggle for a URL rather than the two rules disagreeing.
+ const bareUrl = parseBareUrl(text);
+ if (bareUrl) {
+ return captureUrlAsLink(bareUrl, text);
+ }
+
const meta = await storage.loadMeta();
const provider = providerOverride || meta.defaultProvider;
const model = modelOverride || meta.defaultModel;
@@ -194,6 +206,40 @@ export async function captureThought(text, providerOverride, modelOverride, { cr
};
}
+/**
+ * File a bare-URL capture to the links collection and log it as an already-filed
+ * inbox entry (so the capture is still auditable from the inbox, showing where
+ * it went). Re-pasting a URL that's already saved reuses that link instead of
+ * failing the capture — the inbox entry then points at the existing bookmark.
+ */
+async function captureUrlAsLink(url, capturedText) {
+ const existing = await storage.getLinkByUrl(url);
+ const link = existing || await createLinkFromUrl(url);
+
+ // No `classification` block: nothing classified this — the destination was
+ // decided by shape, not by a model, so there is no confidence or extraction to
+ // record. That also keeps the entry safe on a federated peer running older
+ // code (inbox records sync): its inbox renders `classification.destination`
+ // through a fixed destination map, so an absent classification degrades to the
+ // existing "Unknown" badge instead of an unmapped value it can't render.
+ const inboxEntry = await storage.createInboxLog({
+ capturedText,
+ source: 'brain_ui',
+ status: 'filed',
+ filed: { destination: 'links', destinationId: link.id }
+ });
+
+ console.log(`🔗 Captured URL filed to links: ${link.id}${existing ? ' (existing)' : ''} via ${inboxEntry.id}`);
+
+ return {
+ inboxLog: inboxEntry,
+ link,
+ message: existing
+ ? 'Already saved in Links.'
+ : (link.isGitHubRepo ? 'GitHub repo saved to Links!' : 'Saved to Links!')
+ };
+}
+
/**
* Background AI classification for a captured thought.
* Updates the inbox entry and emits a brain:classified event when done.
@@ -387,6 +433,18 @@ async function fileToDestination(destination, extracted, title) {
}
}
+/**
+ * Title to file an inbox entry under. Not every entry carries a classification —
+ * a URL filed to Links skipped the classifier, and so does every capture taken
+ * while auto-classify is off — so fall back to the captured text (bounded to the
+ * 200-char record-title limit) before the last-resort placeholder.
+ */
+function entryTitle(inboxLog) {
+ return inboxLog.classification?.title
+ || inboxLog.capturedText?.trim().slice(0, 200)
+ || 'Untitled';
+}
+
/**
* Resolve a needs_review inbox item
*/
@@ -402,7 +460,7 @@ export async function resolveReview(inboxLogId, destination, editedExtracted) {
// Merge extracted data with edits
const extracted = { ...inboxLog.classification?.extracted, ...editedExtracted };
- const title = inboxLog.classification?.title || 'Untitled';
+ const title = entryTitle(inboxLog);
// File to destination
const filedRecord = await fileToDestination(destination, extracted, title);
@@ -448,7 +506,7 @@ export async function fixClassification(inboxLogId, newDestination, updatedField
// Create new record in new destination
const extracted = { ...inboxLog.classification?.extracted, ...updatedFields };
- const title = inboxLog.classification?.title || 'Untitled';
+ const title = entryTitle(inboxLog);
const newRecord = await fileToDestination(newDestination, extracted, title);
// Mark old record as archived (soft delete by adding archived flag)
@@ -482,6 +540,14 @@ export async function fixClassification(inboxLogId, newDestination, updatedField
* Archive a record (soft delete)
*/
async function archiveRecord(destination, id) {
+ // A bookmark has no archived state — the Links tab renders every record — so
+ // correcting a bare-URL capture into a real destination removes the link it
+ // auto-created, rather than leaving it behind in Links.
+ if (destination === 'links') {
+ await storage.deleteLink(id);
+ return;
+ }
+
const updateFn = {
people: storage.updatePerson,
projects: storage.updateProject,
@@ -812,10 +878,10 @@ export async function deleteMemoryEntry(id) {
export const getLinks = storage.getLinks;
export const getLinkById = storage.getLinkById;
export const getLinkByUrl = storage.getLinkByUrl;
-export const createLink = storage.createLink;
export const updateLink = storage.updateLink;
export const reorderLinks = storage.reorderLinks;
export const deleteLink = storage.deleteLink;
+
export const getBuckets = storage.getBuckets;
export const getBucketById = storage.getBucketById;
export const createBucket = storage.createBucket;
@@ -848,3 +914,84 @@ export async function deleteBucketAndUnlinkChildren(id) {
await storage.deleteBucket(id);
return { deleted: true, unassigned };
}
+
+/**
+ * Extract a clean hostname from a URL (strip a leading www.), or null if unparseable.
+ */
+function hostnameFromUrl(url) {
+ return URL.parse(url)?.hostname.replace(/^www\./, '') ?? null;
+}
+
+/**
+ * Clone a GitHub 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.
+ */
+export async function cloneRepoInBackground(linkId, url) {
+ await storage.updateLink(linkId, { cloneStatus: 'cloning' });
+
+ githubCloner.cloneRepo(url)
+ .then(async (result) => {
+ await storage.updateLink(linkId, {
+ localPath: result.localPath,
+ cloneStatus: 'cloned',
+ cloneError: null
+ });
+ console.log(`✅ Background clone complete: ${linkId}`);
+ })
+ .catch(async (err) => {
+ await storage.updateLink(linkId, {
+ cloneStatus: 'failed',
+ cloneError: err.message
+ });
+ console.error(`❌ Background clone failed: ${linkId} - ${err.message}`);
+ });
+}
+
+/**
+ * Create a link from a URL: derives the GitHub 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.
+ *
+ * Callers own duplicate handling (the route 409s; capture reuses the existing
+ * link) — this always creates.
+ */
+export async function createLinkFromUrl(url, {
+ title, description, linkType, tags, bucketId, bucketOrder, autoClone
+} = {}) {
+ const parsed = githubCloner.parseGitHubUrl(url);
+ const isGitHubRepo = !!parsed;
+ const shouldClone = isGitHubRepo && autoClone !== false;
+
+ // 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}`
+ : (hostnameFromUrl(url) || url);
+
+ const link = await storage.createLink({
+ url,
+ title: title || defaultTitle,
+ description: description || '',
+ linkType: linkType || (isGitHubRepo ? 'github' : 'other'),
+ tags: tags || [],
+ isGitHubRepo,
+ gitHubOwner: parsed?.owner,
+ gitHubRepo: parsed?.repo,
+ localPath: null,
+ cloneStatus: shouldClone ? 'pending' : 'none',
+ cloneError: null,
+ ...(bucketId !== undefined ? { bucketId } : {}),
+ ...(bucketOrder !== undefined ? { bucketOrder } : {})
+ });
+ console.log(`🔗 Created link: ${link.id} (${isGitHubRepo ? 'GitHub repo' : 'regular URL'})`);
+
+ if (shouldClone) {
+ cloneRepoInBackground(link.id, url).catch(err => {
+ console.error(`❌ Background clone setup failed for ${link.id}: ${err.message}`);
+ });
+ }
+
+ return link;
+}
diff --git a/server/services/brain.test.js b/server/services/brain.test.js
index 904d163998..6bfce4ad0d 100644
--- a/server/services/brain.test.js
+++ b/server/services/brain.test.js
@@ -61,6 +61,13 @@ 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),
+ cloneRepo: vi.fn()
+}));
+
// Mock chatgptImport — brain.js's deleteMemoryEntry wrapper delegates the
// on-disk asset cleanup to deleteMemoryAssets; stub it so the wrapper test
// asserts the wiring (gating + survivor computation) without touching the FS.
@@ -120,6 +127,7 @@ assertProvider: (provider, { message, code, status = 503 } = {}) => {
}));
import { runPromptThroughProvider } from '../lib/promptRunner.js';
+import * as githubCloner from './githubCloner.js';
import * as storage from './brainStorage.js';
import { deleteMemoryAssets } from './chatgptImport.js';
import { getProviderById } from './providers.js';
@@ -135,7 +143,8 @@ import {
updateInboxEntry,
deleteInboxEntry,
deleteMemoryEntry,
- recoverStuckClassifications
+ recoverStuckClassifications,
+ createLinkFromUrl
} from './brain.js';
describe('brain service', () => {
@@ -222,6 +231,143 @@ describe('brain service', () => {
});
});
+ // ===========================================================================
+ // captureThought — bare-URL short-circuit (files to links, no classifier)
+ // ===========================================================================
+
+ 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 }));
+ });
+
+ it('saves a pasted URL to links and logs it as already filed', async () => {
+ const result = await captureThought('https://example.com/parks');
+
+ expect(storage.createLink).toHaveBeenCalledWith(expect.objectContaining({
+ url: 'https://example.com/parks',
+ title: 'example.com',
+ linkType: 'other'
+ }));
+ expect(storage.createInboxLog).toHaveBeenCalledWith(expect.objectContaining({
+ capturedText: 'https://example.com/parks',
+ status: 'filed',
+ filed: { destination: 'links', destinationId: 'link-001' }
+ }));
+ expect(result.link.id).toBe('link-001');
+ expect(result.inboxLog.filed.destination).toBe('links');
+ });
+
+ it('never calls the classifier for a URL capture, and records no classification', async () => {
+ await captureThought('https://example.com');
+ expect(runPromptThroughProvider).not.toHaveBeenCalled();
+ // No `ai`/`classification` block: an older federated peer renders the
+ // entry as Unknown instead of choking on a destination it can't map.
+ expect(storage.createInboxLog).toHaveBeenCalledWith(
+ expect.not.objectContaining({ ai: expect.anything() })
+ );
+ expect(storage.createInboxLog).toHaveBeenCalledWith(
+ expect.not.objectContaining({ classification: expect.anything() })
+ );
+ });
+
+ it('normalizes a scheme-less URL before saving', async () => {
+ await captureThought('example.com');
+ expect(storage.createLink).toHaveBeenCalledWith(
+ expect.objectContaining({ url: 'https://example.com' })
+ );
+ });
+
+ it('reuses an existing link instead of failing on a re-paste', async () => {
+ storage.getLinkByUrl.mockResolvedValue({ id: 'link-existing', title: 'example.com' });
+
+ const result = await captureThought('https://example.com');
+
+ expect(storage.createLink).not.toHaveBeenCalled();
+ expect(result.link.id).toBe('link-existing');
+ expect(result.message).toMatch(/already saved/i);
+ expect(storage.createInboxLog).toHaveBeenCalledWith(expect.objectContaining({
+ filed: { destination: 'links', destinationId: 'link-existing' }
+ }));
+ });
+
+ 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' });
+
+ await captureThought('https://github.com/acme/widgets');
+
+ expect(storage.createLink).toHaveBeenCalledWith(expect.objectContaining({
+ title: 'acme/widgets',
+ linkType: 'github',
+ isGitHubRepo: true,
+ cloneStatus: 'pending'
+ }));
+ expect(storage.updateLink).toHaveBeenCalledWith('link-001', { cloneStatus: 'cloning' });
+ });
+
+ it('files a URL to Links even when the creative flag is set', async () => {
+ await captureThought('https://example.com', undefined, undefined, { creative: true });
+
+ expect(storage.createLink).toHaveBeenCalled();
+ expect(storage.createInboxLog).toHaveBeenCalledWith(expect.objectContaining({
+ status: 'filed',
+ filed: { destination: 'links', destinationId: 'link-001' }
+ }));
+ expect(storage.createInboxLog).toHaveBeenCalledWith(
+ expect.not.objectContaining({ creative: expect.anything() })
+ );
+ });
+
+ it('treats a URL wrapped in prose as an ordinary thought', async () => {
+ await captureThought('read this later https://example.com');
+
+ expect(storage.createLink).not.toHaveBeenCalled();
+ expect(storage.createInboxLog).toHaveBeenCalledWith(
+ expect.objectContaining({ status: 'classifying' })
+ );
+ });
+ });
+
+ // ===========================================================================
+ // createLinkFromUrl (shared by the Links route and URL capture)
+ // ===========================================================================
+
+ 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 }));
+ });
+
+ it('derives a hostname title (www stripped) for a plain URL', async () => {
+ await createLinkFromUrl('https://www.example.com/parks');
+ expect(storage.createLink).toHaveBeenCalledWith(expect.objectContaining({
+ title: 'example.com',
+ isGitHubRepo: 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', bucketId: 'bucket-1', autoClone: false
+ });
+
+ expect(storage.createLink).toHaveBeenCalledWith(expect.objectContaining({
+ title: 'My Widgets',
+ bucketId: 'bucket-1',
+ cloneStatus: 'none'
+ }));
+ expect(storage.updateLink).not.toHaveBeenCalled();
+ });
+ });
+
// ===========================================================================
// resolveReview
// ===========================================================================
@@ -1121,6 +1267,25 @@ describe('brain service', () => {
expect(storage[updateFns[dest]]).toHaveBeenCalledWith('old-001', { archived: true });
});
}
+
+ it('deletes the bookmark when a URL capture is corrected to another destination', async () => {
+ storage.getInboxLogById.mockResolvedValue({
+ id: 'inbox-002',
+ status: 'filed',
+ capturedText: 'https://example.com',
+ filed: { destination: 'links', destinationId: 'link-001' }
+ });
+ storage.createIdea.mockResolvedValue({ id: 'idea-001' });
+ storage.updateInboxLog.mockResolvedValue({});
+
+ await fixClassification('inbox-002', 'ideas', undefined, 'not a bookmark');
+
+ expect(storage.deleteLink).toHaveBeenCalledWith('link-001');
+ // No classification to draw a title from — the captured text stands in.
+ expect(storage.createIdea).toHaveBeenCalledWith(
+ expect.objectContaining({ title: 'https://example.com' })
+ );
+ });
});
// ===========================================================================