Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
ingest a YouTube video's transcript into the brain and queue an agent on it
[._.]/ Adam Eivy83e75d47af73
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 1de7239c0d..5ea7e414bd 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -164,3 +164,6 @@- **[issue-3563] "Continue Today's Routine" in POST no longer hands you the same drill over and over.** The routine always took the #1 recommendation, but the two signals that produce most recommendations — your weakest drill by recent accuracy, and a ladder you are partway up but not advancing — are windowed averages that a single rep barely moves. So the drill sitting at #1 before a run was still at #1 after it, and clicking Continue re-served the test just finished, indefinitely (Digit Span, in the report). Recommendations now know what you have already practiced today, from both scored sessions and the training log — Morse, Wordplay and Memory practice never post a scored session, so counting only sessions would have missed three of the surfaces that offer the Continue button. Anything already practiced today sinks below everything that has not been, which is enough for the routine to advance to the next thing on its own. Already-practiced items are demoted rather than dropped, so a day where you have done everything still shows what is up next instead of an empty panel, and each row in "Up next" now carries a Done today badge so the reordering reads as deliberate; they are still clickable, since practicing the same drill twice in a day is allowed — just not what the routine hands you. When nothing new is left, Continue ends the routine at the launcher and says so, rather than looping. A due memory item is matched by its item id and a ladder by its drill type, so switching off one practice mode cannot mark an unrelated one done, and the fallback "run a full self-test" is discharged only by an actual scored session.- **The Shell page gives the terminal roughly 300px more of a phone screen.** Everything above the terminal was laid out to wrap, so on a phone each strip claimed several rows: the title line pushed its Fullscreen/Restart/Stop/New buttons onto a second row, each session tab took a full row of its own (a live agent run's label is long enough to guarantee it) with the "+" button stranded on a third, and the quick-commands toolbar spread its hot keys, launchers and the "cd to app" dropdown across three rows. Together with the standing green banner explaining that a live TUI run is interactive, the chrome ate more vertical space than the terminal it was wrapped around. The banner is gone — the run's tab already marks itself with a bot icon, an accent tint and a pulsing dot, and what the banner actually said now lives in a tap-and-keyboard-reachable info tooltip beside the "N live" counter in the header, costing no vertical space at all (a plain `title` attribute would have hidden it from exactly the touch users this change is for). The header is one row that does not wrap: under `sm` the Connected pill collapses to its status dot — with the word kept for screen readers — and the session counter drops out, since the tabs below say the same thing. The tab strip and the quick-commands toolbar each scroll sideways instead of wrapping, so both cost one fixed row no matter how many sessions or commands there are, and tab labels truncate with the full name kept in the tooltip. Both scrollers hide their scrollbar and pin the swipe to the horizontal axis, the same recipe the shared tab bar uses — a platform scrollbar gutter would have eaten back the row each one is reclaiming. The "cd to app" dropdown sits outside the scrolling region — an absolutely-positioned menu inside one would be clipped — and shows just its folder icon on a phone. Desktop layout is unchanged apart from the tighter page padding under `md`.+- **YouTube videos can be ingested into the Brain — transcript to your Obsidian vault, with an agent queued to act on it.** Paste a single-video YouTube link into Quick Capture on the dashboard and a sliders button appears next to the input; it expands into the ingest options. Three independent checkboxes decide what is pulled in: the **transcript** (on by default), the full **video** into the media library, and the **audio** as an mp3 kept next to the transcript — at least one is required. Below them, a free-text box asks what an agent should do with the content, and a tags field. Whatever the switches say, the ingest always records that you consumed and kept the video: a Brain link record, which federates to your other machines, and a `media.watch` event so the video shows on the Timeline next to the watch history that syncs passively. Transcripts land as a note in your Obsidian vault with frontmatter carrying the title, source, channel, duration, publish date and tags. YouTube's auto-generated captions are a rolling two-line display where each cue repeats most of the one before it, so a naive strip-the-timings pass yields a transcript with every sentence in it two or three times; the captions are de-duplicated and their inline markup removed before they are written, which took a 14-minute talk from 128KB of caption file down to 14KB of readable prose. Whether the captions were human-written or machine-generated is read from the video's metadata rather than guessed from the file yt-dlp produced — it writes both kinds under the same name — and recorded alongside the transcript, because auto-captions get proper nouns wrong often enough to be worth knowing about later. A video with no captions at all is not treated as a failure: the ingest finishes, says so, and still stores everything else you asked for. Filling in the agent prompt queues a Chief of Staff task pointed at the freshly-stored transcript with your prompt as its brief; leaving it blank queues nothing, so an ingest never starts AI work you did not ask for. Which vault and folder transcripts go to, and what the checkboxes default to, are configurable under Brain → Config; an unset vault inherits the Daily Log's, so anyone who has already pointed the journal at Obsidian needs no setup at all. Playlists and channel URLs are deliberately not accepted — they fall through to ordinary link capture rather than quietly starting a 300-video download. `yt-dlp` is required for any ingest and `ffmpeg` additionally for the video/audio options, so a transcript-only ingest still works on a machine that has only the first.++- **The Daily Log's first note into a new Obsidian folder no longer silently fails to write.** Mirroring a record into a vault tried to update the note first and only created it if the update reported the note missing — but a note whose *folder* does not exist yet cannot be containment-checked at all: the path can't be resolved, so it falls back to the raw path, which fails the check against the realpath'd vault root whenever the vault is reached through a symlink. On macOS that is any vault under a `/var`-rooted path, and more generally any vault behind a symlinked home or mount. The update therefore reported "invalid path" rather than "not found", the create fallback never ran, and the day was never mirrored. Creating first and updating only on "already exists" sidesteps it entirely — the folder is ensured before the path is resolved. The two vault mirrors (Daily Log and the new YouTube transcript) now share one `upsertNote` in the Obsidian adapter instead of each carrying its own copy of that ordering rule, and it is tested against a real vault on disk rather than against stubbed calls, which is how the failure surfaced in the first place.diff --git a/client/src/components/QuickBrainCapture.jsx b/client/src/components/QuickBrainCapture.jsxindex 5089c5c6ff..fa31fbce5c 100644--- a/client/src/components/QuickBrainCapture.jsx+++ b/client/src/components/QuickBrainCapture.jsx@@ -1,10 +1,11 @@-import { useState, useMemo, useRef } from 'react';+import { useState, useMemo, useRef, useEffect } from 'react';import { Link } from 'react-router';-import { Send, Sparkles } from 'lucide-react';+import { ChevronDown, Film, Send, Sliders, Sparkles, X } from 'lucide-react';import toast from './ui/Toast';import * as api from '../services/api';-import { useLocalStorageBool } from '../hooks';+import { useLocalStorageBool, useYoutubeIngest } from '../hooks';import { parseBareUrl } from '../lib/bareUrl';+import { INGEST_OPTIONS, defaultIngestOptions, ingestOptionsFromSettings, isYoutubeVideoUrl } from '../lib/youtubeUrl';export default function QuickBrainCapture() {const [input, setInput] = useState('');@@ -17,12 +18,58 @@ export default function QuickBrainCapture() {// 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]);+ // A single-video YouTube URL takes a different path entirely (ingest, not+ // capture) and unlocks the advanced panel below.+ const isYoutube = useMemo(() => isYoutubeVideoUrl(input), [input]);++ const [showAdvanced, setShowAdvanced] = useState(false);+ const [ingestOpts, setIngestOpts] = useState(defaultIngestOptions);+ const [agentPrompt, setAgentPrompt] = useState('');+ const [tagsInput, setTagsInput] = useState('');++ // Server-side defaults for the checkboxes, so a user who always wants audio+ // sets it once in settings instead of every capture. Fetched lazily — the+ // first time the panel is opened — so the dashboard doesn't pay for it.+ const seededRef = useRef(false);+ useEffect(() => {+ if (!showAdvanced || seededRef.current) return;+ seededRef.current = true;+ api.getYoutubeIngestSettings({ silent: true })+ .then((settings) => setIngestOpts(ingestOptionsFromSettings(settings)))+ .catch(() => {}); // defaultIngestOptions() is already sensible+ }, [showAdvanced]);++ const ingest = useYoutubeIngest({+ onComplete: () => {+ setAgentPrompt('');+ setTagsInput('');+ },+ });++ const nothingSelected = !INGEST_OPTIONS.some((o) => ingestOpts[o.key]);const handleSubmit = async (e) => {e?.preventDefault();const text = input.trim();if (!text || submittingRef.current) return;+ if (isYoutube) {+ if (nothingSelected) {+ toast.error('Pick at least one of transcript, video, or audio');+ return;+ }+ // The ingest job is long-running and streams its own progress/toasts, so+ // the input clears immediately and the widget stays usable.+ setInput('');+ ingest.start({+ url: text,+ ...ingestOpts,+ agentPrompt: agentPrompt.trim(),+ tags: tagsInput.split(',').map((t) => t.trim()).filter(Boolean),+ });+ return;+ }+// Synchronous ref lock prevents duplicate requests from rapid clicks/EntersubmittingRef.current = true;setIsSubmitting(true);@@ -46,6 +93,8 @@ export default function QuickBrainCapture() {setIsSubmitting(false);};+ const toggleOption = (key) => setIngestOpts((prev) => ({ ...prev, [key]: !prev[key] }));+return (<div className="bg-port-card border border-port-border rounded-xl p-4"><div className="flex items-center justify-between mb-3">@@ -59,36 +108,134 @@ export default function QuickBrainCapture() {<inputid="quick-brain-input"type="text"- placeholder="Thought, URL, or link..."+ placeholder="Thought, URL, or YouTube link..."value={input}onChange={e => setInput(e.target.value)}- className="flex-1 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ className="flex-1 min-w-0 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"/>- <button- type="button"- onClick={() => setCreative(v => !v)}- aria-pressed={creative}- aria-label="Toggle creative capture mode"- disabled={isUrl}- className={`flex items-center px-2.5 py-2 rounded-lg border text-sm transition-colors min-h-[40px] disabled:opacity-40 disabled:cursor-not-allowed ${creative- ? 'bg-purple-500/20 text-purple-300 border-purple-500/40'- : 'bg-port-bg text-gray-400 border-port-border hover:text-gray-200'}`}- title={isUrl ? 'URLs are saved as links, not creative ideas' : 'Creative mode: flag this thought for the Catalog'}- >- <Sparkles size={14} />- </button>+ {isYoutube ? (+ <button+ type="button"+ onClick={() => setShowAdvanced(v => !v)}+ aria-expanded={showAdvanced}+ aria-controls="quick-brain-advanced"+ aria-label="Toggle ingest options"+ className={`flex items-center px-2.5 py-2 rounded-lg border text-sm transition-colors min-h-[40px] ${showAdvanced+ ? 'bg-red-500/20 text-red-300 border-red-500/40'+ : 'bg-port-bg text-gray-400 border-port-border hover:text-gray-200'}`}+ title="YouTube ingest options"+ >+ <Sliders size={14} />+ </button>+ ) : (+ <button+ type="button"+ onClick={() => setCreative(v => !v)}+ aria-pressed={creative}+ aria-label="Toggle creative capture mode"+ disabled={isUrl}+ className={`flex items-center px-2.5 py-2 rounded-lg border text-sm transition-colors min-h-[40px] disabled:opacity-40 disabled:cursor-not-allowed ${creative+ ? 'bg-purple-500/20 text-purple-300 border-purple-500/40'+ : 'bg-port-bg text-gray-400 border-port-border hover:text-gray-200'}`}+ title={isUrl ? 'URLs are saved as links, not creative ideas' : 'Creative mode: flag this thought for the Catalog'}+ >+ <Sparkles size={14} />+ </button>+ )}<buttontype="submit"- disabled={!input.trim() || isSubmitting}+ disabled={!input.trim() || isSubmitting || ingest.active}aria-label="Capture"className="flex items-center gap-1 px-3 py-2 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded-lg text-sm transition-colors disabled:opacity-50 min-h-[40px]"><Send size={14} /></button></form>- {input.trim() && (++ {isYoutube && showAdvanced && (+ <div id="quick-brain-advanced" className="mt-3 pt-3 border-t border-port-border space-y-3">+ <div className="flex flex-wrap gap-2">+ {INGEST_OPTIONS.map(({ key, label, hint }) => (+ <label+ key={key}+ htmlFor={`quick-brain-${key}`}+ title={hint}+ className={`flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg border text-xs cursor-pointer transition-colors ${ingestOpts[key]+ ? 'bg-port-accent/20 text-port-accent border-port-accent/40'+ : 'bg-port-bg text-gray-400 border-port-border hover:text-gray-200'}`}+ >+ <input+ id={`quick-brain-${key}`}+ type="checkbox"+ checked={ingestOpts[key]}+ onChange={() => toggleOption(key)}+ className="accent-port-accent"+ />+ {label}+ </label>+ ))}+ </div>++ <div>+ <label htmlFor="quick-brain-prompt" className="block text-xs text-gray-400 mb-1">+ What should an agent do with this? <span className="text-gray-600">(optional — queues a CoS task)</span>+ </label>+ <textarea+ id="quick-brain-prompt"+ rows={3}+ value={agentPrompt}+ onChange={e => setAgentPrompt(e.target.value)}+ placeholder="e.g. Review for features and improvements to our writing tools; file issues for anything actionable."+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ />+ </div>++ <div>+ <label htmlFor="quick-brain-tags" className="block text-xs text-gray-400 mb-1">+ Tags <span className="text-gray-600">(comma separated)</span>+ </label>+ <input+ id="quick-brain-tags"+ type="text"+ value={tagsInput}+ onChange={e => setTagsInput(e.target.value)}+ placeholder="writing-tools, research"+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ />+ </div>+ </div>+ )}++ {ingest.active && (+ <div className="mt-3 flex items-center gap-2 text-xs text-gray-400">+ <Film size={14} className="text-red-400 shrink-0" />+ <span className="capitalize">{ingest.stage || 'starting'}…</span>+ <div className="flex-1 h-1.5 bg-port-bg rounded-full overflow-hidden">+ <div className="h-full bg-port-accent transition-all" style={{ width: `${ingest.percent}%` }} />+ </div>+ <button+ type="button"+ onClick={ingest.cancel}+ aria-label="Cancel ingest"+ className="text-gray-500 hover:text-red-400 transition-colors"+ >+ <X size={14} />+ </button>+ </div>+ )}++ {input.trim() && !ingest.active && (<p className="mt-2 text-xs text-gray-500">- {isUrl ? 'Will save as link' : creative ? 'Will capture as a creative thought' : 'Will capture as thought'}+ {isYoutube ? (+ <button+ type="button"+ onClick={() => setShowAdvanced(v => !v)}+ className="inline-flex items-center gap-1 hover:text-gray-300 transition-colors"+ >+ Will ingest {INGEST_OPTIONS.filter(o => ingestOpts[o.key]).map(o => o.label.toLowerCase()).join(' + ') || 'nothing — pick an option'}+ <ChevronDown size={12} className={showAdvanced ? 'rotate-180 transition-transform' : 'transition-transform'} />+ </button>+ ) : isUrl ? 'Will save as link' : creative ? 'Will capture as a creative thought' : 'Will capture as thought'}</p>)}</div>diff --git a/client/src/components/QuickBrainCapture.test.jsx b/client/src/components/QuickBrainCapture.test.jsxindex e416801fab..770a8ae42f 100644--- a/client/src/components/QuickBrainCapture.test.jsx+++ b/client/src/components/QuickBrainCapture.test.jsx@@ -4,27 +4,65 @@ import { MemoryRouter } from 'react-router';vi.mock('../services/api', () => ({captureBrainThought: vi.fn(),+ getYoutubeIngestSettings: vi.fn(),+}));+// The ingest hook reaches for apiBrain directly (not through the `api` barrel),+// so mock it separately — that keeps the REAL useYoutubeIngest/useSseJobSlot+// wiring under test while never opening an EventSource.+vi.mock('../services/apiBrain.js', () => ({+ startYoutubeIngest: vi.fn(),+ cancelYoutubeIngest: vi.fn(),+ youtubeIngestEventsUrl: (jobId) => `/api/brain/youtube/ingest/${jobId}/events`,}));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';+// jsdom has no EventSource, and once a kickoff resolves the real+// useSseProgress subscribes to one. A do-nothing stub keeps the hook wiring+// under test without inventing a fake transport — no test here drives frames.+class StubEventSource {+ static CLOSED = 2;+ constructor(url) { this.url = url; this.readyState = 0; }+ close() { this.readyState = StubEventSource.CLOSED; }+}+globalThis.EventSource = StubEventSource;++import { captureBrainThought, getYoutubeIngestSettings } from '../services/api';+import { startYoutubeIngest } from '../services/apiBrain.js';import toast from './ui/Toast';import QuickBrainCapture from './QuickBrainCapture';+const PLACEHOLDER = 'Thought, URL, or YouTube link...';+const YT = 'https://youtu.be/oCnxnaVg0bY';+const renderWidget = () => render(<MemoryRouter><QuickBrainCapture /></MemoryRouter>);+const type = (text) =>+ fireEvent.change(screen.getByPlaceholderText(PLACEHOLDER), { target: { value: text } });+const submit = (text) => {- fireEvent.change(screen.getByPlaceholderText('Thought, URL, or link...'), { target: { value: text } });+ type(text);fireEvent.click(screen.getByLabelText('Capture'));};+// Open the advanced panel and wait for the settings-seeded checkbox state.+const openAdvanced = async () => {+ fireEvent.click(screen.getByLabelText('Toggle ingest options'));+ await waitFor(() => expect(getYoutubeIngestSettings).toHaveBeenCalled());+};+describe('QuickBrainCapture', () => {beforeEach(() => {vi.clearAllMocks();localStorage.clear();captureBrainThought.mockResolvedValue({ message: 'Saved to Links!' });+ getYoutubeIngestSettings.mockResolvedValue({+ defaultCaptureTranscript: true,+ defaultDownloadVideo: false,+ defaultIngestAudio: false,+ });+ startYoutubeIngest.mockResolvedValue({ jobId: 'job-1' });});it('captures both thoughts and URLs through the same endpoint', async () => {@@ -58,10 +96,92 @@ describe('QuickBrainCapture', () => {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' } });+ type('https://example.com');expect(screen.getByText('Will save as link')).toBeInTheDocument();- fireEvent.change(input, { target: { value: 'call mom' } });+ type('call mom');expect(screen.getByText('Will capture as thought')).toBeInTheDocument();});++ describe('YouTube ingest path', () => {+ it('offers ingest options only for a single-video YouTube URL', () => {+ renderWidget();+ type('https://example.com/article');+ expect(screen.queryByLabelText('Toggle ingest options')).toBeNull();+ expect(screen.getByLabelText('Toggle creative capture mode')).toBeInTheDocument();++ type(YT);+ expect(screen.getByLabelText('Toggle ingest options')).toBeInTheDocument();+ // The creative flag is meaningless for an ingest — don't offer it.+ expect(screen.queryByLabelText('Toggle creative capture mode')).toBeNull();+ });++ it('treats a playlist URL as an ordinary link, not an ingest', () => {+ renderWidget();+ type('https://www.youtube.com/playlist?list=PLabcdefghij');+ expect(screen.queryByLabelText('Toggle ingest options')).toBeNull();+ expect(screen.getByText('Will save as link')).toBeInTheDocument();+ });++ it('seeds the option checkboxes from saved settings', async () => {+ getYoutubeIngestSettings.mockResolvedValue({+ defaultCaptureTranscript: true,+ defaultDownloadVideo: false,+ defaultIngestAudio: true,+ });+ renderWidget();+ type(YT);+ await openAdvanced();+ await waitFor(() => expect(screen.getByLabelText('Audio').checked).toBe(true));+ expect(screen.getByLabelText('Transcript').checked).toBe(true);+ expect(screen.getByLabelText('Video').checked).toBe(false);+ });++ it('submits the full ingest payload — options, prompt, and parsed tags', async () => {+ renderWidget();+ type(YT);+ await openAdvanced();++ fireEvent.change(screen.getByLabelText(/what should an agent do/i), {+ target: { value: 'Review for writing-tool improvements.' },+ });+ fireEvent.change(screen.getByLabelText(/^tags/i), { target: { value: ' writing-tools , research ,, ' } });+ fireEvent.click(screen.getByLabelText('Capture'));++ expect(captureBrainThought).not.toHaveBeenCalled();+ await waitFor(() => expect(startYoutubeIngest).toHaveBeenCalled());+ expect(startYoutubeIngest.mock.calls[0][0]).toEqual({+ url: YT,+ captureTranscript: true,+ downloadVideo: false,+ ingestAudio: false,+ agentPrompt: 'Review for writing-tool improvements.',+ // Blank entries dropped, surrounding whitespace trimmed.+ tags: ['writing-tools', 'research'],+ });+ });++ it('ingests with no prompt or tags when the panel was never opened', async () => {+ renderWidget();+ submit(YT);+ await waitFor(() => expect(startYoutubeIngest).toHaveBeenCalled());+ expect(startYoutubeIngest.mock.calls[0][0]).toEqual({+ url: YT,+ captureTranscript: true,+ downloadVideo: false,+ ingestAudio: false,+ agentPrompt: '',+ tags: [],+ });+ });++ it('refuses to start an ingest with every artifact unchecked', async () => {+ renderWidget();+ type(YT);+ await openAdvanced();+ fireEvent.click(screen.getByLabelText('Transcript'));+ fireEvent.click(screen.getByLabelText('Capture'));+ expect(startYoutubeIngest).not.toHaveBeenCalled();+ expect(toast.error).toHaveBeenCalledWith('Pick at least one of transcript, video, or audio');+ });+ });});diff --git a/client/src/components/brain/YoutubeIngestSettings.jsx b/client/src/components/brain/YoutubeIngestSettings.jsxnew file mode 100644index 0000000000..69955ea712--- /dev/null+++ b/client/src/components/brain/YoutubeIngestSettings.jsx@@ -0,0 +1,238 @@+import { useState, useEffect } from 'react';+import { Film, Save, Trash2 } from 'lucide-react';+import * as api from '../../services/api';+import { INGEST_OPTIONS } from '../../lib/youtubeUrl';+import { formatDurationMs, timeAgo } from '../../utils/formatters';+import BrailleSpinner from '../BrailleSpinner';+import toast from '../ui/Toast';++const PRIORITIES = ['CRITICAL', 'HIGH', 'MEDIUM', 'LOW'];++/**+ * Settings for the YouTube → Brain ingest, plus the list of what has been+ * ingested so far: which Obsidian vault/folder transcripts are mirrored into,+ * what the Quick Capture panel defaults to, and a way to forget an ingest.+ *+ * The vault select's empty option is meaningful, not a placeholder: an unset+ * vault means "inherit the Daily Log's vault", which is what makes the feature+ * work with zero configuration for anyone who already pointed the journal at+ * Obsidian.+ */+export default function YoutubeIngestSettings() {+ const [loading, setLoading] = useState(true);+ const [saving, setSaving] = useState(false);+ const [vaults, setVaults] = useState([]);+ const [settings, setSettings] = useState(null);+ const [ingests, setIngests] = useState([]);+ // Two-click arm rather than a confirm dialog, per the client UI conventions.+ const [armedDelete, setArmedDelete] = useState(null);++ useEffect(() => {+ Promise.all([+ api.getYoutubeIngestSettings({ silent: true }).catch(() => null),+ api.getNotesVaults().catch(() => ({ vaults: [] })),+ api.getYoutubeIngests({ silent: true }).catch(() => ({ ingests: [] })),+ ]).then(([loaded, vaultData, ingestData]) => {+ setSettings(loaded);+ setVaults(vaultData?.vaults || []);+ setIngests(ingestData?.ingests || []);+ setLoading(false);+ });+ }, []);++ const handleForget = async (videoId) => {+ if (armedDelete !== videoId) {+ setArmedDelete(videoId);+ return;+ }+ setArmedDelete(null);+ const ok = await api.deleteYoutubeIngest(videoId, { silent: true }).catch((err) => {+ toast.error(err.message || 'Failed to remove the ingest');+ return null;+ });+ if (!ok) return;+ setIngests((prev) => prev.filter((i) => i.videoId !== videoId));+ toast.success('Ingest removed — the link, video and timeline entry were kept');+ };++ const patch = (updates) => setSettings((prev) => ({ ...prev, ...updates }));++ const handleSave = async () => {+ setSaving(true);+ const saved = await api.updateYoutubeIngestSettings({+ obsidianVaultId: settings.obsidianVaultId || null,+ obsidianFolder: settings.obsidianFolder || '',+ autoSync: !!settings.autoSync,+ // Same table Quick Capture's checkboxes come from, so a new artifact+ // becomes settable here without a second edit.+ ...Object.fromEntries(INGEST_OPTIONS.map((o) => [o.settingKey, !!settings[o.settingKey]])),+ taskPriority: settings.taskPriority,+ }).catch((err) => {+ toast.error(err.message || 'Failed to save YouTube ingest settings');+ return null;+ });+ if (saved) {+ setSettings(saved);+ toast.success('YouTube ingest settings saved');+ }+ setSaving(false);+ };++ if (loading) {+ return (+ <section className="p-4 bg-port-card border border-port-border rounded-lg">+ <BrailleSpinner />+ </section>+ );+ }+ if (!settings) return null;++ return (+ <section className="p-4 bg-port-card border border-port-border rounded-lg space-y-4">+ <div className="flex items-center gap-2">+ <Film className="w-5 h-5 text-red-400" />+ <h3 className="text-md font-semibold text-white">YouTube Ingest</h3>+ </div>+ <p className="text-xs text-gray-500">+ Paste a YouTube link into Quick Capture to pull in its transcript, video, or audio.+ Transcripts are mirrored into your Obsidian vault as a note.+ </p>++ <div className="grid gap-4 md:grid-cols-2">+ <div>+ <label htmlFor="ytVault" className="block text-sm font-medium text-gray-300 mb-2">+ Obsidian Vault+ </label>+ <select+ id="ytVault"+ value={settings.obsidianVaultId || ''}+ onChange={(e) => patch({ obsidianVaultId: e.target.value || null })}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:outline-hidden focus:ring-2 focus:ring-port-accent"+ >+ <option value="">Same as Daily Log</option>+ {vaults.map((v) => (+ <option key={v.id} value={v.id}>{v.name}</option>+ ))}+ </select>+ <p className="mt-1 text-xs text-gray-500">+ {vaults.length === 0+ ? 'No vaults configured yet — add one under Brain → Notes.'+ : 'Leave as "Same as Daily Log" to reuse the journal\'s vault.'}+ </p>+ </div>++ <div>+ <label htmlFor="ytFolder" className="block text-sm font-medium text-gray-300 mb-2">+ Vault Folder+ </label>+ <input+ id="ytFolder"+ type="text"+ value={settings.obsidianFolder ?? ''}+ onChange={(e) => patch({ obsidianFolder: e.target.value })}+ placeholder="Consumed/YouTube"+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:outline-hidden focus:ring-2 focus:ring-port-accent"+ />+ <p className="mt-1 text-xs text-gray-500">Where transcript notes are written. Blank = vault root.</p>+ </div>+ </div>++ <div className="flex flex-wrap items-center gap-4">+ <label htmlFor="ytAutoSync" className="flex items-center gap-2 text-sm text-gray-300">+ <input+ id="ytAutoSync"+ type="checkbox"+ checked={!!settings.autoSync}+ onChange={(e) => patch({ autoSync: e.target.checked })}+ className="accent-port-accent"+ />+ Mirror transcripts to Obsidian+ </label>++ <div className="flex items-center gap-2">+ <label htmlFor="ytPriority" className="text-sm text-gray-300">Review task priority</label>+ <select+ id="ytPriority"+ value={settings.taskPriority || 'MEDIUM'}+ onChange={(e) => patch({ taskPriority: e.target.value })}+ className="px-2 py-1 bg-port-bg border border-port-border rounded-lg text-white text-sm focus:outline-hidden focus:ring-2 focus:ring-port-accent"+ >+ {PRIORITIES.map((p) => <option key={p} value={p}>{p}</option>)}+ </select>+ </div>+ </div>++ <div>+ <span className="block text-sm font-medium text-gray-300 mb-2">Capture by default</span>+ <div className="flex flex-wrap gap-4">+ {INGEST_OPTIONS.map(({ settingKey, label, hint }) => (+ <label key={settingKey} htmlFor={`yt-${settingKey}`} title={hint} className="flex items-center gap-2 text-sm text-gray-300">+ <input+ id={`yt-${settingKey}`}+ type="checkbox"+ checked={!!settings[settingKey]}+ onChange={(e) => patch({ [settingKey]: e.target.checked })}+ className="accent-port-accent"+ />+ {label}+ </label>+ ))}+ </div>+ </div>++ <button+ type="button"+ onClick={handleSave}+ disabled={saving}+ className="flex items-center gap-2 px-4 py-2 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded-lg text-sm transition-colors disabled:opacity-50"+ >+ <Save size={14} />+ {saving ? 'Saving…' : 'Save YouTube Settings'}+ </button>++ {ingests.length > 0 && (+ <div className="pt-4 border-t border-port-border">+ <h4 className="text-sm font-medium text-gray-400 mb-2">Ingested ({ingests.length})</h4>+ <ul className="space-y-1 max-h-64 overflow-y-auto">+ {ingests.map((ingest) => (+ <li key={ingest.videoId} className="flex items-center gap-2 py-1.5 text-sm">+ <div className="min-w-0 flex-1">+ <a+ href={ingest.url}+ target="_blank"+ rel="noreferrer"+ className="block truncate text-gray-200 hover:text-port-accent transition-colors"+ >+ {ingest.title || ingest.videoId}+ </a>+ <p className="text-xs text-gray-500 truncate">+ {[+ ingest.channel,+ ingest.durationSec ? formatDurationMs(ingest.durationSec * 1000) : null,+ ingest.transcript ? `${Math.round(ingest.transcript.chars / 1000)}k transcript` : 'no transcript',+ ingest.audio ? 'audio' : null,+ ingest.video ? 'video' : null,+ ingest.ingestedAt ? timeAgo(ingest.ingestedAt) : null,+ ].filter(Boolean).join(' · ')}+ </p>+ </div>+ <button+ type="button"+ onClick={() => handleForget(ingest.videoId)}+ onBlur={() => setArmedDelete((v) => (v === ingest.videoId ? null : v))}+ aria-label={`Forget ingest: ${ingest.title || ingest.videoId}`}+ title="Removes the stored transcript, audio and Obsidian note. The link, downloaded video and timeline entry are kept."+ className={`flex items-center justify-center min-w-[44px] min-h-[44px] rounded-lg transition-colors ${armedDelete === ingest.videoId+ ? 'text-red-300 bg-red-500/20'+ : 'text-gray-500 hover:text-red-400'}`}+ >+ {armedDelete === ingest.videoId ? <span className="text-xs px-1">Sure?</span> : <Trash2 size={14} />}+ </button>+ </li>+ ))}+ </ul>+ </div>+ )}+ </section>+ );+}diff --git a/client/src/components/brain/tabs/ConfigTab.jsx b/client/src/components/brain/tabs/ConfigTab.jsxindex 02853f1f6a..89e0b13f13 100644--- a/client/src/components/brain/tabs/ConfigTab.jsx+++ b/client/src/components/brain/tabs/ConfigTab.jsx@@ -14,6 +14,7 @@ import {Settings,RefreshCw} from 'lucide-react';import BrailleSpinner from '../../BrailleSpinner';import toast from '../../ui/Toast';+import YoutubeIngestSettings from '../YoutubeIngestSettings';const DAYS_OF_WEEK = ['monday',@@ -433,6 +434,10 @@ export default function ConfigTab({ onRefresh }) {</div></section>+ {/* YouTube ingest — owns its own load/save (like the embeddings block+ above, its settings live in a separate store from brain settings). */}+ <YoutubeIngestSettings />+{/* Schedule Settings */}<section className="p-4 bg-port-card border border-port-border rounded-lg space-y-4"><div className="flex items-center gap-2 mb-4">diff --git a/client/src/components/dashboard/widgetRegistry.jsx b/client/src/components/dashboard/widgetRegistry.jsxindex 12f6705edc..5f061734fe 100644--- a/client/src/components/dashboard/widgetRegistry.jsx+++ b/client/src/components/dashboard/widgetRegistry.jsx@@ -48,7 +48,7 @@ export const WIDGETS = [// Daily Driver self-hides once the day is handled — gated on the per-day// first-visit/handled state so a handled day reserves no grid cell (#2666).{ id: 'daily-driver', label: 'Daily Driver', Component: DailyDriverWidget, width: 'third', defaultH: 6, gate: (s) => !!s.dailyDriver && !s.dailyDriver.handledToday },- { id: 'quick-brain', label: 'Quick Brain Capture', Component: QuickBrainCapture, width: 'half', defaultH: 3 },+ { id: 'quick-brain', label: 'Quick Brain Capture', Component: QuickBrainCapture, width: 'half', defaultH: 4 },{ id: 'quick-idea', label: 'Quick Idea (Catalog)', Component: QuickIdeaCapture, width: 'half', defaultH: 4 },{ id: 'quick-image', label: 'Quick Image Prompt', Component: QuickImagePrompt, width: 'half', defaultH: 6 },{ id: 'quick-task', label: 'Quick Task', Component: QuickTaskWidget, width: 'half', defaultH: 5 },diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex bd0335cf45..9e16d2e1a0 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -185,6 +185,7 @@ grep -i "what you want to do" client/src/hooks/README.md| `useVideoFileSrc` | `useVideoFileSrc(jobId, { enabled })` → `{ src, resolving }`. Resolves a video-history **id** to the file it really points at (`/data/videos/<filename>`) via the history lookup. | Any surface rendering a video by history id where the id is NOT the filename stem — notably a CD `finalVideoId` (the timeline renderer mints `timeline-*.mp4` beside a `randomUUID()` id, so `/data/videos/<id>.mp4` 404s while `<id>.jpg` poster loads). Pass the result to `<ScenePreview src=…>`. Gate autoplay on `resolving`. || `useVoiceUiSync` | Keeps voice server's UI index in sync with current page. | Wire once at root for voice agent support. || `useMoltworldWs` | Moltworld WebSocket feed. | Moltworld surfaces only. |+| `useYoutubeIngest` | One YouTube brain-ingest job slot: start/cancel + SSE progress + terminal-frame handling via `POST /api/brain/youtube/ingest`. Returns `{ active, percent, stage, start(body), cancel }` — `start` takes the whole payload (`{ url, captureTranscript, downloadVideo, ingestAudio, agentPrompt, tags }`), not a bare URL. `onComplete(ingest)` fires with the stored ingest record; non-fatal `warnings[]` on the terminal frame are toasted automatically. | Quick Capture's YouTube path, and any other surface that ingests a video into the brain. || `useYoutubeTrackImport` | One YouTube-audio-import job slot (#1945): start/cancel + SSE progress + terminal-frame handling via `POST /api/tracks/import/youtube`. Returns `{ active, percent, start(url, context), cancel }`; `onComplete(track, context)` fires with the finished Track. Call once per UI surface that can independently kick off an import — a shared slot would let one surface's kickoff orphan another's in-flight job. | Any picker that lets a user paste a YouTube URL to create a Track (Music Video's create form and track-change row). || `useVideoGenForm` | `useVideoGenForm({ models, status, availableLoras, grokEnabled })` → every VideoGen form field + setter, the URL-param prefill paths (ImageGen handoff, Continue, Remix, `?lora=`), the mode/backend transitions that clear stale inputs, the derived model/keyframe/IC gates (`extendModeBlocked`, `a2vModeBlocked`, `icLoraModeBlocked`, `keyframesError`), `applyRemix` / `applyResumedParams`, and `buildGeneratePayload()`. | The /media/video form — the single client-side source of truth for the payload `server/routes/videoGen.js` validates. Reuse it for any second entry point that generates video. || `useVideoGenQueue` | `useVideoGenQueue({ generating, runGeneration })` → `{ queue, runningQueueId, enqueue, removeFromQueue, clearFinishedQueue, cancelRunning }`. Client-side serial batch queue for VideoGen: owns the queue array + running marker + the worker effect that pumps the head whenever nothing is generating (with BUSY-backoff retry + unmount/staleness guards). | The VideoGen "Add to queue" batch flow. |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex 32259d12bb..2de2325c91 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -76,6 +76,7 @@ export { default as useUniverseRender } from './useUniverseRender.js';export { default as useUniverseTabs } from './useUniverseTabs.js';export { default as useVideoDownload } from './useVideoDownload.js';export { default as useWakeLock } from './useWakeLock.js';+export { default as useYoutubeIngest } from './useYoutubeIngest.js';export { default as useYoutubeTrackImport } from './useYoutubeTrackImport.js';export { default as useReferenceAudioImport } from './useReferenceAudioImport.js';export { default as useMidiTranscription } from './useMidiTranscription.js';diff --git a/client/src/hooks/useYoutubeIngest.js b/client/src/hooks/useYoutubeIngest.jsnew file mode 100644index 0000000000..ae998af5f6--- /dev/null+++ b/client/src/hooks/useYoutubeIngest.js@@ -0,0 +1,38 @@+import toast from '../components/ui/Toast';+import { startYoutubeIngest, cancelYoutubeIngest, youtubeIngestEventsUrl } from '../services/apiBrain.js';+import useSseJobSlot from './useSseJobSlot.js';++/**+ * One YouTube brain-ingest job slot — start/cancel + SSE progress + terminal+ * frames via `POST /api/brain/youtube/ingest`. A thin wrapper over the generic+ * `useSseJobSlot`, like the video-download and track-import hooks.+ *+ * `start(body)` takes the whole ingest payload (`{ url, captureTranscript,+ * downloadVideo, ingestAudio, agentPrompt, tags }`) rather than a bare URL, so+ * `trimStartArg` stays false and the payload passes through untouched.+ *+ * Non-fatal outcomes (no captions, a duplicate review task) ride along on the+ * terminal `complete` frame as `warnings[]` — the hook only ever sees the+ * terminal payload, so a live-only warning frame would be lost.+ */+export default function useYoutubeIngest({ onComplete } = {}) {+ const { active, percent, stage, start, cancel } = useSseJobSlot({+ startRequest: (body) => startYoutubeIngest(body, { silent: true }),+ eventsUrl: youtubeIngestEventsUrl,+ cancelRequest: cancelYoutubeIngest,+ onComplete: (frame) => {+ for (const message of frame.warnings || []) toast.info(message);+ onComplete?.(frame.ingest);+ },+ successToast: (frame) => (+ frame.ingest?.taskId+ ? `Ingested "${frame.ingest.title}" — review task queued`+ : `Ingested "${frame.ingest?.title || 'video'}"`+ ),+ errorFallback: 'YouTube ingest failed',+ canceledMessage: 'YouTube ingest cancelled',+ lostConnectionMessage: 'Lost connection to the ingest — check Brain → Links',+ startErrorFallback: 'Failed to start the ingest',+ });+ return { active, percent, stage, start, cancel };+}diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex f0f9aaa912..b6ed5e9529 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -81,6 +81,7 @@ grep -i "what you want to do" client/src/lib/README.md| `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. |+| `youtubeUrl.js` | `isYoutubeVideoUrl(text)` / `youtubeVideoId(url)` — single-video YouTube URL detection. Client mirror of `YOUTUBE_INGEST_URL_RE` in `server/services/youtubeIngest.js` (behavioral parity pinned by `server/lib/youtubeUrl.mirror.test.js`); deliberately excludes playlists and channels. Quick Capture uses it to swap to the ingest submit path and reveal the ingest options panel. Also `INGEST_OPTIONS` — the single table of the three ingest artifacts (`key` / `settingKey` / `fallback` / `label` / `hint`) — plus `defaultIngestOptions()` and `ingestOptionsFromSettings(settings)`. Everything that enumerates the switches derives from that table; add an artifact there, not at each call site. || `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/index.js b/client/src/lib/index.jsindex 72286043e4..5b59cf7354 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -88,6 +88,7 @@ export * from './sketchCanvas.js';export * from './unsorted.js';export * from './upsertByIdPrepend.js';export * from './voiceLabel.js';+export * from './youtubeUrl.js';// === Page-scoped pure helpers ===export * from './audioContext.js';diff --git a/client/src/lib/youtubeUrl.js b/client/src/lib/youtubeUrl.jsnew file mode 100644index 0000000000..2323ef0202--- /dev/null+++ b/client/src/lib/youtubeUrl.js@@ -0,0 +1,78 @@+/**+ * Single-video YouTube URL detection — MIRROR of `YOUTUBE_INGEST_URL_RE` in+ * `server/services/youtubeIngest.js` (authoritative there).+ *+ * The Quick Capture box swaps its whole submit path (brain capture → YouTube+ * ingest) based on this predicate, and reveals the ingest options panel from it,+ * so a looser client answer would offer options for a URL the server refuses.+ * Port any change from the server copy verbatim.+ *+ * Deliberately narrow: playlists, channels, and `/@handle` pages are NOT+ * matched — a paste that would have yt-dlp pull 300 videos should fall through+ * to normal link capture, not silently start a batch download.+ */++const SINGLE_VIDEO_RE =+ /^https?:\/\/(www\.|m\.|music\.)?(youtube\.com\/(watch\?[^\s#]*\bv=[\w-]{6,}|shorts\/[\w-]{6,}|live\/[\w-]{6,}|embed\/[\w-]{6,})|youtu\.be\/[\w-]{6,})/i;++/** The video id in a YouTube URL, or null. Mirrors `youtubeVideoIdFromUrl` server-side. */+export function youtubeVideoId(url) {+ if (!url) return null;+ const s = String(url).trim();+ const vParam = /[?&]v=([A-Za-z0-9_-]{6,20})/.exec(s);+ if (vParam) return vParam[1];+ const pathId = /(?:youtu\.be\/|\/shorts\/|\/embed\/|\/live\/|\/v\/)([A-Za-z0-9_-]{6,20})/.exec(s);+ return pathId ? pathId[1] : null;+}++/** True when `text` is a single-video YouTube URL the ingest endpoint accepts. */+export function isYoutubeVideoUrl(text) {+ const trimmed = (text ?? '').trim();+ return SINGLE_VIDEO_RE.test(trimmed) && !!youtubeVideoId(trimmed);+}++/**+ * The three artifacts an ingest can produce, as ONE table.+ *+ * `key` is the request field the server reads, `settingKey` the+ * `youtube-ingest-settings.json` field holding its default, and `fallback` what+ * to use before those settings load. Everything that enumerates the switches —+ * the checkbox row, the initial state, the settings-seed mapping, the+ * "pick at least one" guard, the summary line, and the settings form — derives+ * from this, so adding a fourth artifact is one row plus the server field rather+ * than seven edit sites that silently half-work if one is missed.+ */+export const INGEST_OPTIONS = [+ {+ key: 'captureTranscript',+ settingKey: 'defaultCaptureTranscript',+ fallback: true,+ label: 'Transcript',+ hint: 'Captions → note in your Obsidian vault',+ },+ {+ key: 'downloadVideo',+ settingKey: 'defaultDownloadVideo',+ fallback: false,+ label: 'Video',+ hint: 'Full video into the media library',+ },+ {+ key: 'ingestAudio',+ settingKey: 'defaultIngestAudio',+ fallback: false,+ label: 'Audio',+ hint: 'mp3 kept next to the transcript',+ },+];++/** The `{ captureTranscript, downloadVideo, ingestAudio }` bag before settings load. */+export const defaultIngestOptions = () =>+ Object.fromEntries(INGEST_OPTIONS.map((o) => [o.key, o.fallback]));++/** Map a saved settings object onto the same bag, falling back per option. */+export const ingestOptionsFromSettings = (settings) =>+ Object.fromEntries(INGEST_OPTIONS.map((o) => [+ o.key,+ typeof settings?.[o.settingKey] === 'boolean' ? settings[o.settingKey] : o.fallback,+ ]));diff --git a/client/src/services/apiBrain.js b/client/src/services/apiBrain.jsindex 39d625dbc9..3b5555e80d 100644--- a/client/src/services/apiBrain.js+++ b/client/src/services/apiBrain.js@@ -322,3 +322,31 @@ export const draftActivityDigest = (date = 'today', options = {}) => request(`/brain/daily-log/${encodeURIComponent(date)}/draft`,{ method: 'POST', ...options });++// Brain - YouTube ingest (transcript / video / audio → brain + Obsidian)+export const startYoutubeIngest = (body, options = {}) => request('/brain/youtube/ingest', {+ method: 'POST',+ body: JSON.stringify(body),+ ...options+});+export const cancelYoutubeIngest = (jobId, options = {}) => request(+ `/brain/youtube/ingest/${encodeURIComponent(jobId)}/cancel`,+ { method: 'POST', ...options }+);+export const getYoutubeIngests = (options = {}) => request('/brain/youtube/ingests', options);+export const getYoutubeIngest = (videoId, options = {}) => request(+ `/brain/youtube/ingests/${encodeURIComponent(videoId)}`,+ options+);+export const deleteYoutubeIngest = (videoId, options = {}) => request(+ `/brain/youtube/ingests/${encodeURIComponent(videoId)}`,+ { method: 'DELETE', ...options }+);+export const getYoutubeIngestSettings = (options = {}) => request('/brain/youtube/settings', options);+export const updateYoutubeIngestSettings = (settings, options = {}) => request('/brain/youtube/settings', {+ method: 'PUT',+ body: JSON.stringify(settings),+ ...options+});+export const youtubeIngestEventsUrl = (jobId) =>+ `/api/brain/youtube/ingest/${encodeURIComponent(jobId)}/events`;diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex e24f6ec4bb..068355d1fb 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -57,6 +57,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](- App scaffolds / cloned repos / browser profiles — `data/repos`, `data/browser-profile` — inherently filesystem-oriented.- Sprite animation-track definitions — `data/sprites/animation-tracks.json` (#3152). A small hand-editable authoring config: which animation types exist beyond the compiled-in `walk` (label, directionality, frame/fps bounds, prompt template, and the on-disk `setKind` strings). `file-primary` rather than `db-primary` because it is **machine-local and inseparable from the on-disk sprite tree it describes** — a row names the `setKind` an approved set under `data/sprites/{id}/` already carries, so the two travel together or neither means anything — and because it has no cross-record queries, no relationships beyond `kinds` strings, and no sync cursor. Read synchronously and cached per process (`server/services/sprites/animationTrackStore.js`): `server/lib/validation.js` builds sprite Zod ranges from it at module load, so it must resolve without `await`. Seeded from `data.reference/sprites/animation-tracks.json` (migration 211), which is also the fallback read when no user copy exists yet. Backed up in full by the rsync snapshot.- Quota-burn plan — `data/cos/quota-burn.json` (#3390). The install's burn plan: master switch, poll interval, and per-provider-family windows + ordered job list. `file-primary` and **intentionally machine-local — never federated**: quota belongs to a particular machine and provider account, so a synced plan would have each peer spending against the other's window budget, and the plan's `agent-prompt` jobs name managed apps that only exist on this machine. No sync cursor, no tombstone. Its four companions are `ephemeral-file` — regenerable telemetry, all safe to delete: `data/cos/quota-burn-dispatches.json` (per-window dispatch counts, self-pruning at 30 days), `data/cos/quota-burn-runs.json` (capped run log), `data/cos/quota-burn-inflight.json` (entries a burn job has enqueued but whose renders have not completed, self-pruning at 6 hours — deleting it only risks re-queueing a render already in flight), and `data/cos/quota-burn-denials.json` (per-family blocks from an observed provider refusal, cleared by the next successful burn or a 5-hour TTL — deleting it only risks one dispatch into a still-exhausted window). Backed up with the rest of `data/cos/`; a restored plan simply re-applies on this machine. See [Quota Burn](./QUOTA-BURN.md).+- YouTube brain ingests — `data/brain/youtube/{videoId}.md` (transcript), `{videoId}.mp3` (optional audio), plus `data/brain/youtube/index.json` (the ingest index) and `data/brain/youtube-ingest-settings.json`. The transcript IS an external file: it is mirrored into the user's Obsidian vault, edited there, and syncs through iCloud — the same boundary that keeps the Daily Log file-backed. The index is **intentionally machine-local — never federated**: every field in it is a local filesystem path, an Obsidian vault id, or a local video-history id, so a peer's copy would be meaningless and would poison brain reconcile exactly the way the daily log's `journal-obsidian-locations.json` sidecar would. The durable, federated record of "I consumed and kept this" is the brain `links` entry (`db-primary` via the brain store) plus a `media.watch` row in `human_activity_events`. No sync cursor, no tombstone. Adapter: `server/services/youtubeIngest.js`.- LoRA training datasets — `data/lora-datasets/{id}/index.json` + `images/*.png` (collectionStore). The record is inseparable from the image bytes it organizes, has no cross-record queries beyond a small characterId scan, and is **machine-local** like `data/loras/` itself (training artifacts tied to this machine's GPU output — never federates, no sync cursor/tombstone). Backed up in full: uploads and hand-edited captions are not re-creatable. Training RUN records are `db-primary` (`lora_training_runs`); run artifacts (checkpoints/samples) live under `data/training-runs/{runId}/` with checkpoints/cache excluded from backup.---diff --git a/docs/features/brain-system.md b/docs/features/brain-system.mdindex 15d88bdb83..a003cc8707 100644--- a/docs/features/brain-system.md+++ b/docs/features/brain-system.md@@ -21,6 +21,7 @@ Brain provides a capture-classify-store-surface workflow:6. **Daily Digest**: AI-generated summary of actions and status7. **Weekly Review**: GTD-style open loops and accomplishments8. **Trust Panel**: Full audit trail of classifications+9. **YouTube Ingest**: Pull a video's transcript (and optionally the video/audio) into the brain, mirror the transcript to Obsidian, and queue an agent to act on it## Databases@@ -117,6 +118,53 @@ Generated weekly (GTD-style):- Ideas to explore- Admin items to address+## YouTube Ingest++Paste a single-video YouTube URL into **Quick Capture** (dashboard widget) and the+submit path switches from `/api/brain/capture` to `/api/brain/youtube/ingest`. A+sliders button next to the input expands the advanced panel: which artifacts to+capture, a free-text prompt for a follow-up agent, and tags.++**Three independent switches** — at least one is required:++| Switch | Produces |+|--------|----------|+| `captureTranscript` (default) | `data/brain/youtube/<videoId>.md`, mirrored into the Obsidian vault |+| `downloadVideo` | A `source: 'download'` entry in the shared media library (same shape the Dev Tools downloader writes) |+| `ingestAudio` | `data/brain/youtube/<videoId>.mp3`, kept next to the transcript |++**Always recorded, regardless of switches:**++- a brain `links` record (federated — the durable "saved for future reference" artifact), and+- a `media.watch` row in `human_activity_events` (machine-local), so the video appears on the Timeline next to passively-synced watch history.++**The agent prompt.** Supplying `agentPrompt` queues a CoS task pointed at the+stored transcript with that prompt as its brief — "here is what I want done with+this content." Leaving it blank queues nothing: PortOS never starts AI work the+user did not ask for (see the AI Provider Usage Policy in the root `CLAUDE.md`).++**Transcripts.** yt-dlp is asked for English captions; the metadata dump's+`subtitles` key (not the produced filename, which is identical for both kinds)+distinguishes human-authored captions from auto-generated ones, and that lands on+the record as `transcript.source`. YouTube's auto-captions are a rolling two-line+display where each cue repeats the previous one, so `server/lib/vttTranscript.js`+collapses the repetition and strips inline markup — a 14-minute talk goes from+128 KB of VTT to ~14 KB of prose. A video with no captions is **not** a failure:+the ingest completes with a warning and everything else is still stored.++**Obsidian.** The transcript note is written to the vault configured under+**Brain → Config → YouTube Ingest**. An unset vault inherits the Daily Log's, so+anyone who already pointed the journal at Obsidian needs no setup. The note+carries YAML frontmatter (title, source, channel, duration, published, captured,+tags) so vault queries and Dataview can find it.++**Storage.** `data/brain/youtube/index.json` is machine-local and never+federated — every field in it is a local path, an Obsidian vault id, or a local+video-history id. See [STORAGE.md](../STORAGE.md).++**Requirements.** `yt-dlp` on PATH for any ingest; `ffmpeg` additionally for the+video/audio switches (a transcript-only ingest works without it).+## API Endpoints| Route | Description |@@ -134,6 +182,13 @@ Generated weekly (GTD-style):| POST /api/brain/digest/run | Trigger daily digest || POST /api/brain/review/run | Trigger weekly review || GET/PUT /api/brain/settings | Get/update settings |+| POST /api/brain/youtube/ingest | Start a YouTube ingest → `{ jobId, videoId }` |+| GET /api/brain/youtube/ingest/:jobId/events | SSE progress for an ingest |+| POST /api/brain/youtube/ingest/:jobId/cancel | Cancel an in-flight ingest |+| GET /api/brain/youtube/ingests | List ingests, newest first |+| GET/DELETE /api/brain/youtube/ingests/:videoId | One ingest / forget it |+| GET /api/brain/youtube/ingests/:videoId/transcript | Stored transcript markdown |+| GET/PUT /api/brain/youtube/settings | Ingest vault/folder + option defaults |## Prompt Templates@@ -158,7 +213,9 @@ Generated weekly (GTD-style):| `server/services/brain.js` | Core business logic || `server/services/brainStorage.js` | JSONL/JSON file operations || `server/services/brainScheduler.js` | Daily/weekly job scheduler |-| `server/routes/brain.js` | Aggregator router mounting brainCapture, brainCrud, brainDigest, brainSettings, brainLinks, brainGraph, brainSync, and brainDailyLog |+| `server/services/youtubeIngest.js` | YouTube ingest orchestration (transcript / video / audio → brain + Obsidian + CoS task) |+| `server/lib/vttTranscript.js` | WebVTT/SRT → readable prose (collapses auto-caption repetition) |+| `server/routes/brain.js` | Aggregator router mounting brainCapture, brainCrud, brainDigest, brainSettings, brainLinks, brainGraph, brainSync, brainDailyLog, brainSongbook, and brainYoutube || `client/src/pages/Brain.jsx` | Main page with tabs || `client/src/components/brain/tabs/*.jsx` | Tab components || `data/prompts/stages/brain-*.md` | Prompt templates |diff --git a/server/lib/README.md b/server/lib/README.mdindex b9c406c537..f14dfe4c63 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -182,6 +182,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `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. Pinokio-launched PortOS exports `MallocStackLogging`/`MallocScribble`/etc. that flood Python subprocess stderr with `can't turn off malloc stack logging` lines; route every Node→Python spawn through this. No-op on Linux/Windows. Also `whichFirst(name)` — first-hit `which`/`where` PATH probe (Malloc-stripped env, 5s timeout) returning the absolute binary path or `null`; the shared discovery probe behind `findYtDlp`/`findFfmpeg`/`detectPython`/voice `which`. || `pythonSetup.js` | Python venv / runner setup helpers. |+| `vttTranscript.js` | WebVTT/SRT → readable prose. `vttToPlainText(vtt)` (paragraph-joined transcript), `vttToLines(vtt)` (cleaned caption lines), `cleanCaptionLine(line)`. Collapses YouTube auto-captions' rolling repetition and strips inline `<c>`/timestamp markup. Used by the brain YouTube ingest. || `ytdlp.js` | `findYtDlp()` — cached discovery of the `yt-dlp` binary on PATH, mirrors `findFfmpeg()` in `ffmpeg.js`. Used by the track YouTube-import job. |## Networkingdiff --git a/server/lib/brainValidation.js b/server/lib/brainValidation.jsindex 91ccf6c597..35e9b661fa 100644--- a/server/lib/brainValidation.js+++ b/server/lib/brainValidation.js@@ -650,3 +650,37 @@ export const songAttachmentUploadSchema = z.object({data: z.string().min(1),label: z.string().max(300).optional().default('')});++// =============================================================================+// YOUTUBE INGEST SCHEMAS (POST /api/brain/youtube/*)+// =============================================================================++// POST /api/brain/youtube/ingest. The URL host/shape allowlist lives in the+// service (assertYoutubeIngestUrl) so the error names the supported URL forms;+// the schema guards the payload shape and the bounds.+//+// The three capture switches are independently optional — the service rejects+// an all-false request with NOTHING_TO_INGEST rather than silently doing work+// the user didn't ask for. `agentPrompt` is what turns an ingest into a queued+// CoS task; absent/empty means "just store it".+export const youtubeIngestSchema = z.object({+ url: z.string().url().max(2048),+ captureTranscript: z.boolean().optional(),+ downloadVideo: z.boolean().optional(),+ ingestAudio: z.boolean().optional(),+ agentPrompt: z.string().max(10000).optional(),+ tags: z.array(z.string().min(1).max(60)).max(20).optional(),+ priority: z.enum(['CRITICAL', 'HIGH', 'MEDIUM', 'LOW']).optional()+});++// PUT /api/brain/youtube/settings. strict() rejects unknown keys so a typo+// can't quietly accumulate in the settings file.+export const youtubeIngestSettingsSchema = z.object({+ obsidianVaultId: z.string().nullable().optional(),+ obsidianFolder: z.string().max(300).optional(),+ autoSync: z.boolean().optional(),+ defaultCaptureTranscript: z.boolean().optional(),+ defaultDownloadVideo: z.boolean().optional(),+ defaultIngestAudio: z.boolean().optional(),+ taskPriority: z.enum(['CRITICAL', 'HIGH', 'MEDIUM', 'LOW']).optional()+}).strict();diff --git a/server/lib/index.js b/server/lib/index.jsindex 79b80e2c56..795c46f842 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -172,6 +172,7 @@ export * from './killWithEscalation.js';export * from './openFolder.js';export * from './processEnv.js';export * from './pythonSetup.js';+export * from './vttTranscript.js';export * from './ytdlp.js';// === Networking ===diff --git a/server/lib/vttTranscript.js b/server/lib/vttTranscript.jsnew file mode 100644index 0000000000..1f13bb7692--- /dev/null+++ b/server/lib/vttTranscript.js@@ -0,0 +1,120 @@+/**+ * WebVTT / SRT subtitle → readable plain-text transcript.+ *+ * yt-dlp hands us caption files, not prose. YouTube's AUTO-generated captions in+ * particular are a rolling two-line display: every cue repeats the tail of the+ * previous cue and appends a few new words, so a naive "strip the timings and+ * join" produces a transcript where most of the text appears two or three+ * times. This module owns the de-duplication and inline-tag stripping so the+ * ingest service can stay about orchestration.+ *+ * Pure and side-effect free — no fs, no network — so the messy parsing rules are+ * pinned by unit tests rather than only exercised behind a yt-dlp spawn.+ */++// A cue-timing line is the only line that must contain `-->`. VTT allows both+// `HH:MM:SS.mmm` and `MM:SS.mmm`; SRT uses a comma for the decimal separator.+// Matching on the arrow alone covers every variant (plus VTT's trailing cue+// settings, e.g. `align:start position:0%`) without a brittle time regex.+const CUE_TIMING_RE = /-->/;++// WebVTT header + block-level metadata that carries no spoken content.+const HEADER_RE = /^(WEBVTT|Kind:|Language:|NOTE\b|STYLE\b|REGION\b|X-TIMESTAMP-MAP)/;++// SRT cue indices are a bare integer on their own line. VTT cue *identifiers*+// can be arbitrary text, but yt-dlp emits numeric ones, so this covers both.+const CUE_INDEX_RE = /^\d+$/;++// Inline karaoke/positioning markup: `<00:00:01.234>`, `<c.colorE5E5E5>`,+// `</c>`, `<v Speaker>`, `<b>`… Captions carry these; prose shouldn't.+const INLINE_TAG_RE = /<[^>]*>/g;++// The handful of entities YouTube actually emits in caption text.+const ENTITIES = {+ '&': '&',+ '<': '<',+ '>': '>',+ '"': '"',+ ''': "'",+ ''': "'",+ ' ': ' ',+};++const decodeEntities = (text) =>+ text.replace(/&(?:amp|lt|gt|quot|#39|apos|nbsp);/g, (m) => ENTITIES[m] ?? m);++/** Strip inline markup + entities from one caption line and normalize whitespace. */+export function cleanCaptionLine(line) {+ return decodeEntities(String(line).replace(INLINE_TAG_RE, ''))+ .replace(/\s+/g, ' ')+ .trim();+}++/**+ * Extract the spoken lines from a VTT/SRT document, in order, with the rolling+ * auto-caption repetition collapsed.+ *+ * De-duplication is deliberately conservative — it only drops a line that is+ * EXACTLY a line we already kept in the recent window, or that the previous kept+ * line already ends with (the "previous cue's tail is repeated verbatim at the+ * top of this cue" shape). A real repeated phrase further apart than the window+ * survives, because dropping genuinely-spoken repetition would silently rewrite+ * what the speaker said.+ *+ * @param {string} vtt Raw subtitle file contents.+ * @param {object} [opts]+ * @param {number} [opts.dedupeWindow=4] How many recent lines an exact repeat is checked against.+ * @returns {string[]} Cleaned caption lines.+ */+export function vttToLines(vtt, { dedupeWindow = 4 } = {}) {+ if (typeof vtt !== 'string' || !vtt.trim()) return [];++ const kept = [];+ for (const raw of vtt.split(/\r?\n/)) {+ const line = raw.trim();+ if (!line) continue;+ if (CUE_TIMING_RE.test(line)) continue;+ if (HEADER_RE.test(line)) continue;+ if (CUE_INDEX_RE.test(line)) continue;++ const text = cleanCaptionLine(line);+ if (!text) continue;++ const recent = kept.slice(-dedupeWindow);+ if (recent.includes(text)) continue;+ // Rolling auto-captions also emit the previous line *plus* new words as one+ // cue; when the new cue merely extends the previous one, replace rather than+ // append so the transcript keeps the longer, complete phrasing exactly once.+ const prev = kept[kept.length - 1];+ if (prev && text.startsWith(prev)) {+ kept[kept.length - 1] = text;+ continue;+ }+ kept.push(text);+ }+ return kept;+}++/**+ * Render a VTT/SRT document as readable prose.+ *+ * Caption lines are ~5 words each, so joining them one-per-line produces a+ * ragged wall. Lines are joined with spaces and broken into paragraphs every+ * `paragraphEvery` lines — arbitrary but stable, and the result reads far better+ * in Obsidian than either extreme.+ *+ * @param {string} vtt+ * @param {object} [opts]+ * @param {number} [opts.paragraphEvery=24]+ * @returns {string} Plain-text transcript ('' when there was nothing to extract).+ */+export function vttToPlainText(vtt, { paragraphEvery = 24, dedupeWindow = 4 } = {}) {+ const lines = vttToLines(vtt, { dedupeWindow });+ if (lines.length === 0) return '';++ const paragraphs = [];+ for (let i = 0; i < lines.length; i += paragraphEvery) {+ paragraphs.push(lines.slice(i, i + paragraphEvery).join(' '));+ }+ return paragraphs.join('\n\n');+}diff --git a/server/lib/vttTranscript.test.js b/server/lib/vttTranscript.test.jsnew file mode 100644index 0000000000..ec0287cc6d--- /dev/null+++ b/server/lib/vttTranscript.test.js@@ -0,0 +1,115 @@+import { describe, it, expect } from 'vitest';+import { cleanCaptionLine, vttToLines, vttToPlainText } from './vttTranscript.js';++describe('cleanCaptionLine', () => {+ it('strips inline karaoke timestamps and <c> spans', () => {+ expect(cleanCaptionLine('hello<00:00:00.500><c> there</c> world')).toBe('hello there world');+ });++ it('decodes the entities YouTube emits', () => {+ expect(cleanCaptionLine('R&D <tags> "quoted" it's')).toBe('R&D <tags> "quoted" it\'s');+ });++ it('collapses runs of whitespace', () => {+ expect(cleanCaptionLine(' too many spaces ')).toBe('too many spaces');+ });+});++describe('vttToLines', () => {+ it('drops the header, cue timings, and blank lines', () => {+ const vtt = [+ 'WEBVTT',+ 'Kind: captions',+ 'Language: en',+ '',+ '00:00:00.000 --> 00:00:02.000 align:start position:0%',+ 'first line',+ '',+ '00:00:02.000 --> 00:00:04.000',+ 'second line',+ '',+ ].join('\n');+ expect(vttToLines(vtt)).toEqual(['first line', 'second line']);+ });++ it('handles SRT (numeric cue indices, comma decimals)', () => {+ const srt = [+ '1',+ '00:00:00,000 --> 00:00:02,000',+ 'alpha',+ '',+ '2',+ '00:00:02,000 --> 00:00:04,000',+ 'beta',+ '',+ ].join('\n');+ expect(vttToLines(srt)).toEqual(['alpha', 'beta']);+ });++ it('collapses the rolling repetition of auto-generated captions', () => {+ // The shape YouTube actually emits: each cue repeats the previous line and+ // appends the next fragment.+ const vtt = [+ 'WEBVTT',+ '',+ '00:00:00.000 --> 00:00:02.000',+ 'the quick brown',+ '',+ '00:00:02.000 --> 00:00:04.000',+ 'the quick brown',+ 'fox jumps over',+ '',+ '00:00:04.000 --> 00:00:06.000',+ 'fox jumps over',+ 'the lazy dog',+ '',+ ].join('\n');+ expect(vttToLines(vtt)).toEqual(['the quick brown', 'fox jumps over', 'the lazy dog']);+ });++ it('replaces a line that a later cue extends, keeping the longer phrasing once', () => {+ const vtt = [+ 'WEBVTT',+ '',+ '00:00:00.000 --> 00:00:01.000',+ 'we should',+ '',+ '00:00:01.000 --> 00:00:02.000',+ 'we should build a thing',+ '',+ ].join('\n');+ expect(vttToLines(vtt)).toEqual(['we should build a thing']);+ });++ it('keeps a genuine repeat that falls outside the dedupe window', () => {+ const vtt = [+ 'WEBVTT',+ '',+ ...['no', 'a', 'b', 'c', 'd', 'e', 'no'].flatMap((text, i) => [+ `00:00:0${i}.000 --> 00:00:0${i + 1}.000`,+ text,+ '',+ ]),+ ].join('\n');+ const lines = vttToLines(vtt, { dedupeWindow: 4 });+ expect(lines.filter((l) => l === 'no')).toHaveLength(2);+ });++ it('returns an empty array for empty or non-string input', () => {+ expect(vttToLines('')).toEqual([]);+ expect(vttToLines(null)).toEqual([]);+ expect(vttToLines('WEBVTT\n\n')).toEqual([]);+ });+});++describe('vttToPlainText', () => {+ it('joins lines into paragraphs of paragraphEvery lines', () => {+ const cues = ['one', 'two', 'three', 'four'];+ const vtt = ['WEBVTT', '', ...cues.flatMap((t, i) => [`00:00:0${i}.000 --> 00:00:0${i + 1}.000`, t, ''])].join('\n');+ expect(vttToPlainText(vtt, { paragraphEvery: 2 })).toBe('one two\n\nthree four');+ });++ it('returns an empty string when nothing was extracted', () => {+ expect(vttToPlainText('WEBVTT\n')).toBe('');+ });+});diff --git a/server/lib/youtubeUrl.mirror.test.js b/server/lib/youtubeUrl.mirror.test.jsnew file mode 100644index 0000000000..e184505a78--- /dev/null+++ b/server/lib/youtubeUrl.mirror.test.js@@ -0,0 +1,60 @@+/**+ * Mirror parity test for the YouTube single-video URL rule.+ *+ * Authoritative: `YOUTUBE_INGEST_URL_RE` + `youtubeVideoIdFromUrl` (server).+ * Mirror: `isYoutubeVideoUrl` + `youtubeVideoId` (client).+ *+ * Quick Capture swaps its ENTIRE submit path on the client predicate — a looser+ * client offers ingest options for a URL the server will reject with a 400, and+ * a tighter one silently files a real video as a plain link. Unlike the+ * bareUrl mirror (which compares declaration source text), this compares+ * BEHAVIOR: the two live in differently-shaped modules — the server's id parser+ * is shared with the Takeout importer — so a text diff would fail on structure+ * rather than on drift.+ */++import { describe, it, expect } from 'vitest';+import { YOUTUBE_INGEST_URL_RE } from '../services/youtubeIngest.js';+import { youtubeVideoIdFromUrl } from '../services/youtubeImport.js';+import { isYoutubeVideoUrl, youtubeVideoId } from '../../client/src/lib/youtubeUrl.js';++const CASES = [+ 'https://youtu.be/oCnxnaVg0bY',+ 'http://youtu.be/oCnxnaVg0bY',+ 'https://www.youtube.com/watch?v=oCnxnaVg0bY',+ 'https://www.youtube.com/watch?v=oCnxnaVg0bY&list=PLabc&index=2',+ 'https://m.youtube.com/watch?v=oCnxnaVg0bY&t=42s',+ 'https://music.youtube.com/watch?v=oCnxnaVg0bY',+ 'https://youtube.com/shorts/oCnxnaVg0bY',+ 'https://www.youtube.com/live/oCnxnaVg0bY',+ 'https://www.youtube.com/embed/oCnxnaVg0bY',+ // Not single videos — must be rejected by both.+ 'https://www.youtube.com/playlist?list=PLabcdefghij',+ 'https://www.youtube.com/@somechannel',+ 'https://www.youtube.com/c/somechannel',+ 'https://www.youtube.com/feed/history',+ 'https://vimeo.com/123456789',+ 'https://example.com/watch?v=oCnxnaVg0bY',+ 'not a url',+ '',+];++// The server's own answer, assembled from its two halves exactly the way+// assertYoutubeIngestUrl does.+const serverAccepts = (url) =>+ typeof url === 'string' && YOUTUBE_INGEST_URL_RE.test(url) && !!youtubeVideoIdFromUrl(url);++describe('youtubeUrl server↔client mirror parity', () => {+ it.each(CASES)('agrees on whether %j is a single-video YouTube URL', (url) => {+ expect(isYoutubeVideoUrl(url)).toBe(serverAccepts(url));+ });++ it.each(CASES.filter(serverAccepts))('extracts the same video id from %j', (url) => {+ expect(youtubeVideoId(url)).toBe(youtubeVideoIdFromUrl(url));+ });++ it('covers both outcomes, so a rule that always returns one value cannot pass', () => {+ expect(CASES.some(serverAccepts)).toBe(true);+ expect(CASES.some((u) => !serverAccepts(u))).toBe(true);+ });+});diff --git a/server/routes/brain.js b/server/routes/brain.jsindex d6b364e87b..48f3e450a9 100644--- a/server/routes/brain.js+++ b/server/routes/brain.js@@ -16,6 +16,7 @@ import graphRoutes from './brainGraph.js';import syncRoutes from './brainSync.js';import dailyLogRoutes from './brainDailyLog.js';import songbookRoutes from './brainSongbook.js';+import youtubeRoutes from './brainYoutube.js';const router = Router();@@ -28,5 +29,6 @@ router.use(graphRoutes);router.use(syncRoutes);router.use(dailyLogRoutes);router.use('/songbook', songbookRoutes);+router.use('/youtube', youtubeRoutes);export default router;diff --git a/server/routes/brainYoutube.js b/server/routes/brainYoutube.jsnew file mode 100644index 0000000000..a92735a3ba--- /dev/null+++ b/server/routes/brainYoutube.js@@ -0,0 +1,80 @@+/**+ * Brain YouTube Ingest Routes+ *+ * Mounted at /api/brain/youtube. Kickoff returns a jobId immediately and the+ * work streams over SSE (same job/SSE shape as the track import and the Dev+ * Tools video downloader), so a 40-minute talk doesn't hold an HTTP request+ * open.+ */++import { Router } from 'express';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { validateRequest } from '../lib/validation.js';+import { youtubeIngestSchema, youtubeIngestSettingsSchema } from '../lib/brainValidation.js';+import * as ingest from '../services/youtubeIngest.js';++const router = Router();++/**+ * POST /api/brain/youtube/ingest+ * Start an ingest. Body: { url, captureTranscript?, downloadVideo?, ingestAudio?,+ * agentPrompt?, tags?, priority? } → { jobId, videoId }+ */+router.post('/ingest', asyncHandler(async (req, res) => {+ const data = validateRequest(youtubeIngestSchema, req.body || {});+ const result = await ingest.startYoutubeIngest(data);+ res.json(result);+}));++/** GET /api/brain/youtube/ingest/:jobId/events — SSE progress stream. */+router.get('/ingest/:jobId/events', (req, res) => {+ if (!ingest.attachIngestSseClient(req.params.jobId, res)) {+ res.status(404).json({ error: 'Ingest job not found' });+ }+});++/** POST /api/brain/youtube/ingest/:jobId/cancel */+router.post('/ingest/:jobId/cancel', asyncHandler(async (req, res) => {+ const canceled = ingest.cancelYoutubeIngest(req.params.jobId);+ if (!canceled) throw new ServerError('Ingest job not found or already finished', { status: 404, code: 'NOT_FOUND' });+ res.json({ message: 'Cancellation requested' });+}));++/** GET /api/brain/youtube/ingests — every ingest, newest first. */+router.get('/ingests', asyncHandler(async (req, res) => {+ res.json({ ingests: await ingest.listIngests() });+}));++/** GET /api/brain/youtube/ingests/:videoId */+router.get('/ingests/:videoId', asyncHandler(async (req, res) => {+ const record = await ingest.getIngest(req.params.videoId);+ if (!record) throw new ServerError('Ingest not found', { status: 404, code: 'NOT_FOUND' });+ res.json(record);+}));++/** GET /api/brain/youtube/ingests/:videoId/transcript — the stored markdown. */+router.get('/ingests/:videoId/transcript', asyncHandler(async (req, res) => {+ const markdown = await ingest.getTranscript(req.params.videoId);+ if (markdown === null) {+ throw new ServerError('No transcript is stored for this video', { status: 404, code: 'TRANSCRIPT_NOT_FOUND' });+ }+ res.type('text/markdown').send(markdown);+}));++/** DELETE /api/brain/youtube/ingests/:videoId — drops local files + the note. */+router.delete('/ingests/:videoId', asyncHandler(async (req, res) => {+ const removed = await ingest.deleteIngest(req.params.videoId);+ if (!removed) throw new ServerError('Ingest not found', { status: 404, code: 'NOT_FOUND' });+ res.json({ message: 'Ingest removed' });+}));++router.get('/settings', asyncHandler(async (req, res) => {+ res.json(await ingest.getSettings());+}));++router.put('/settings', asyncHandler(async (req, res) => {+ const data = validateRequest(youtubeIngestSettingsSchema, req.body || {});+ res.json(await ingest.updateSettings(data));+}));++export default router;diff --git a/server/services/brainJournal.js b/server/services/brainJournal.jsindex 5ccb94bff5..efc2fafd45 100644--- a/server/services/brainJournal.js+++ b/server/services/brainJournal.js@@ -22,7 +22,6 @@* — that would bypass the sync log and silently diverge peers again.*/-import { existsSync } from 'fs';import { join } from 'path';import { atomicWrite, ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';import { createMutex } from '../lib/asyncMutex.js';@@ -402,22 +401,15 @@ export async function syncToObsidian(entry, { force = false } = {}) {if (!settings.obsidianVaultId) return null;if (!force && !settings.autoSync) return null;- const vault = await obsidian.getVaultById(settings.obsidianVaultId);- if (!vault || !existsSync(vault.path)) return null;-const vaultId = settings.obsidianVaultId;const notePath = buildObsidianNotePath(settings, entry.date);- const markdown = buildMarkdown(entry);- // createNote errors when the file exists; try update first then create.- const update = await obsidian.updateNote(vaultId, notePath, markdown);- if (update?.error === 'NOTE_NOT_FOUND') {- const created = await obsidian.createNote(vaultId, notePath, markdown);- if (created?.error) return null;- await persistObsidianLocation(entry.date, notePath, vaultId);- return notePath;- }- if (update?.error) return null;+ // upsertNote owns the update-then-create ordering (createNote errors when the+ // file exists) and the missing-vault-folder no-op — both properties of the+ // Obsidian adapter, not of this caller.+ const written = await obsidian.upsertNote(vaultId, notePath, buildMarkdown(entry));+ if (!written) return null;+// Persist whenever the path OR the vault changes — a folder rename or// a vault swap in Settings both need to update the store so a later// deleteJournal() unlinks the right file in the right vault.diff --git a/server/services/brainJournal.test.js b/server/services/brainJournal.test.jsindex c70cfcbe31..065c36bf5f 100644--- a/server/services/brainJournal.test.js+++ b/server/services/brainJournal.test.js@@ -27,8 +27,10 @@ tryReadFile: vi.fn().mockResolvedValue(null),vi.mock('./obsidian.js', () => ({getVaultById: vi.fn(),- updateNote: vi.fn(),- createNote: vi.fn(),+ // The update-then-create ordering lives inside the real upsertNote and is+ // tested against a real vault in obsidian.test.js — from the journal's side+ // the contract is just 'mirror this markdown to this vault path'.+ upsertNote: vi.fn(),deleteNote: vi.fn(),}));@@ -233,57 +235,54 @@ describe('brainJournal', () => {it('skips sync when autoSync is false', async () => {await journal.updateSettings({ obsidianVaultId: 'v1', autoSync: false });await journal.appendJournal('2026-04-17', 'hi');- expect(obsidian.updateNote).not.toHaveBeenCalled();- expect(obsidian.createNote).not.toHaveBeenCalled();+ expect(obsidian.upsertNote).not.toHaveBeenCalled();});it('honors force:true even when autoSync is false (manual resync path)', async () => {obsidian.getVaultById.mockResolvedValue({ id: 'v1', path: '/' });- obsidian.updateNote.mockResolvedValueOnce({ path: 'Daily Log/2026-04-17.md' });+ obsidian.upsertNote.mockResolvedValue('Daily Log/2026-04-17.md');await journal.updateSettings({ obsidianVaultId: 'v1', autoSync: false, obsidianFolder: 'Daily Log' });// Regular syncToObsidian() still no-ops without force.await journal.syncToObsidian({ id: 'j1', date: '2026-04-17', content: 'hi', segments: [] });- expect(obsidian.updateNote).not.toHaveBeenCalled();+ expect(obsidian.upsertNote).not.toHaveBeenCalled();// force bypasses autoSync so the manual "Re-sync all" action works.await journal.syncToObsidian({ id: 'j1', date: '2026-04-17', content: 'hi', segments: [] },{ force: true },);- expect(obsidian.updateNote).toHaveBeenCalled();+ expect(obsidian.upsertNote).toHaveBeenCalled();});// Test syncToObsidian() directly rather than going through// appendJournal()'s fire-and-forget scheduleObsidianSync() — the// background promise isn't awaited, so assertions against mocked// obsidian calls would otherwise race with the test runner.- it('creates an obsidian note on first sync and updates on later syncs', async () => {+ it('mirrors the day as markdown to the configured vault and folder', async () => {obsidian.getVaultById.mockResolvedValue({ id: 'v1', path: '/' });- obsidian.updateNote.mockResolvedValueOnce({ error: 'NOTE_NOT_FOUND' });- obsidian.createNote.mockResolvedValueOnce({ path: 'Daily Log/2026-04-17.md' });- obsidian.updateNote.mockResolvedValueOnce({ path: 'Daily Log/2026-04-17.md' });+ obsidian.upsertNote.mockResolvedValue('Daily Log/2026-04-17.md');await journal.updateSettings({ obsidianVaultId: 'v1', autoSync: true, obsidianFolder: 'Daily Log' });const entry = { id: 'j1', date: '2026-04-17', content: 'first', segments: [] };await journal.syncToObsidian(entry);await journal.syncToObsidian({ ...entry, content: 'first\n\nsecond' });- expect(obsidian.createNote).toHaveBeenCalledTimes(1);- const [vaultIdArg, pathArg, markdownArg] = obsidian.createNote.mock.calls[0];+ // Both syncs go through the SAME call — whether the note already existed+ // is upsertNote's problem (covered against a real vault in obsidian.test.js),+ // not something the journal branches on.+ expect(obsidian.upsertNote).toHaveBeenCalledTimes(2);+ const [vaultIdArg, pathArg, markdownArg] = obsidian.upsertNote.mock.calls[0];expect(vaultIdArg).toBe('v1');expect(pathArg).toBe('Daily Log/2026-04-17.md');expect(markdownArg).toContain('# Daily Log — 2026-04-17');expect(markdownArg).toContain('first');-- // Second sync updates, not creates- expect(obsidian.updateNote).toHaveBeenCalled();+ expect(obsidian.upsertNote.mock.calls[1][2]).toContain('second');});it('refuses to delete notes from a different vault than the one the entry was mirrored to', async () => {obsidian.getVaultById.mockResolvedValue({ id: 'v1', path: '/' });- obsidian.updateNote.mockResolvedValueOnce({ error: 'NOTE_NOT_FOUND' });- obsidian.createNote.mockResolvedValueOnce({ path: 'Daily Log/2026-04-17.md' });+ obsidian.upsertNote.mockResolvedValue('Daily Log/2026-04-17.md');// Mirror a note to vault v1.await journal.updateSettings({ obsidianVaultId: 'v1', autoSync: true, obsidianFolder: 'Daily Log' });@@ -305,7 +304,7 @@ describe('brainJournal', () => {it('does not resurrect an Obsidian-location sidecar entry for a day deleted before a deferred sync lands', async () => {obsidian.getVaultById.mockResolvedValue({ id: 'v1', path: '/' });- obsidian.updateNote.mockResolvedValue({ path: 'Daily Log/2026-04-17.md' });+ obsidian.upsertNote.mockResolvedValue('Daily Log/2026-04-17.md');await journal.updateSettings({ obsidianVaultId: 'v1', autoSync: true, obsidianFolder: 'Daily Log' });// Create the day, then delete it (tombstone + clear sidecar).diff --git a/server/services/obsidian.js b/server/services/obsidian.jsindex eb810d8ce6..05fb7f9028 100644--- a/server/services/obsidian.js+++ b/server/services/obsidian.js@@ -266,6 +266,47 @@ export async function createNote(vaultId, notePath, content = '') {return await getNote(vaultId, notePath, { includeBacklinks: false });}+/**+ * Write a note whether or not it already exists.+ *+ * `createNote` refuses an existing file and `updateNote` refuses a missing one,+ * so every mirror-a-record-into-the-vault caller has to try one and fall back to+ * the other. That ordering rule is a property of THIS adapter, not of any+ * caller, so it lives here — the Daily Log mirror and the YouTube-ingest+ * transcript mirror both go through this.+ *+ * CREATE first, then update on `NOTE_EXISTS` — not the other way round. Only+ * `createNote` ensures the note's parent folder, and `resolveVaultPath` cannot+ * containment-check a path whose parent does not exist yet: it falls back to the+ * un-realpath'd path, which fails the check against the realpath'd vault root+ * whenever the vault is reached through a symlink (`/var` → `/private/var` on+ * macOS, and any vault the user reaches via a symlinked home or mount). Trying+ * `updateNote` first therefore reports `INVALID_PATH` — not `NOTE_NOT_FOUND` —+ * for the very first note written into a new subfolder, and a caller keyed on+ * `NOTE_NOT_FOUND` silently mirrors nothing. Creating first sidesteps it: the+ * folder is ensured before the path is resolved, and by the time `updateNote`+ * runs the parent provably exists.+ *+ * Also swallows the "vault configured but its folder is gone" case (an unplugged+ * external drive, an iCloud container not yet materialized) as a no-op rather+ * than an error: a mirror is best-effort by nature, and the record it mirrors is+ * already stored in PortOS.+ *+ * @returns {Promise<string|null>} the note path on success, null when the write+ * was skipped or the adapter reported an error.+ */+export async function upsertNote(vaultId, notePath, content) {+ const vault = await getVaultById(vaultId);+ if (!vault || !existsSync(vault.path)) return null;++ const created = await createNote(vaultId, notePath, content);+ if (!created?.error) return notePath;+ if (created.error !== 'NOTE_EXISTS') return null;++ const updated = await updateNote(vaultId, notePath, content);+ return updated?.error ? null : notePath;+}+export async function deleteNote(vaultId, notePath) {const vault = await getVaultById(vaultId);if (!vault) return { error: 'VAULT_NOT_FOUND' };diff --git a/server/services/obsidian.test.js b/server/services/obsidian.test.jsnew file mode 100644index 0000000000..4b3ad9453d--- /dev/null+++ b/server/services/obsidian.test.js@@ -0,0 +1,81 @@+/**+ * `upsertNote` — the "write a note whether or not it already exists" adapter+ * primitive both vault mirrors (Daily Log, YouTube ingest) go through.+ *+ * Exercised against a REAL temp vault rather than mocked `createNote`/+ * `updateNote`: the whole point of the helper is the ordering rule between+ * those two (createNote refuses an existing file, updateNote refuses a missing+ * one), and a test that stubs both would only re-assert the order it was handed.+ */++import { describe, it, expect, beforeEach, afterAll } from 'vitest';+import { mkdirSync, rmSync, writeFileSync, readFileSync, existsSync } from 'fs';+import { join } from 'path';+import { createTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';++// obsidian.js captures PATHS.brain at module load for its vaults file, so the+// root is fixed for the whole file and per-test isolation comes from wiping the+// dir in beforeEach. PATHS.brain is derived from INSTALL_ROOT rather than+// PATHS.data, so it needs its own override.+const tempRoot = createTempDataRoot('portos-obsidian-');++vi.mock('../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../lib/fileUtils.js');+ return makePathsProxy(actual, {+ dataRoot: tempRoot,+ extraOverrides: (root) => ({ brain: join(root, 'brain') }),+ });+});++const { addVault, upsertNote, getNote } = await import('./obsidian.js');++const VAULT_DIR = join(tempRoot, 'vault');+let vaultId;++beforeEach(async () => {+ rmSync(tempRoot, { recursive: true, force: true });+ mkdirSync(join(VAULT_DIR, '.obsidian'), { recursive: true });+ const vault = await addVault({ name: 'Test Vault', path: VAULT_DIR });+ vaultId = vault.id;+});++afterAll(() => rmSync(tempRoot, { recursive: true, force: true }));++describe('obsidian.upsertNote', () => {+ it('creates the note when it does not exist yet, including missing folders', async () => {+ const path = 'Consumed/YouTube/note.md';+ expect(await upsertNote(vaultId, path, '# hello')).toBe(path);+ expect(readFileSync(join(VAULT_DIR, path), 'utf-8')).toBe('# hello');+ });++ it('overwrites the note when it already exists', async () => {+ const path = 'Daily Log/2026-04-17.md';+ await upsertNote(vaultId, path, 'first');+ expect(await upsertNote(vaultId, path, 'second')).toBe(path);+ expect(readFileSync(join(VAULT_DIR, path), 'utf-8')).toBe('second');+ // One note, not two — the create fallback must not have forked a duplicate.+ expect(await getNote(vaultId, path)).toMatchObject({ content: 'second' });+ });++ it('no-ops (rather than erroring) when the vault folder is gone', async () => {+ rmSync(VAULT_DIR, { recursive: true, force: true });+ expect(await upsertNote(vaultId, 'note.md', 'x')).toBeNull();+ });++ it('no-ops for an unknown vault id', async () => {+ expect(await upsertNote('does-not-exist', 'note.md', 'x')).toBeNull();+ });++ it('refuses a path that escapes the vault', async () => {+ expect(await upsertNote(vaultId, '../escaped.md', 'x')).toBeNull();+ expect(existsSync(join(tempRoot, 'escaped.md'))).toBe(false);+ });++ it('leaves an existing note untouched when the write is refused', async () => {+ // A path that resolves inside the vault stays writable; the guard above must+ // not be so broad that ordinary nested paths start failing.+ writeFileSync(join(VAULT_DIR, 'keep.md'), 'original');+ await upsertNote(vaultId, '../escaped.md', 'x');+ expect(readFileSync(join(VAULT_DIR, 'keep.md'), 'utf-8')).toBe('original');+ });+});diff --git a/server/services/videoDownload.js b/server/services/videoDownload.jsindex 1a48556ddd..6bd13a27c9 100644--- a/server/services/videoDownload.js+++ b/server/services/videoDownload.js@@ -14,19 +14,22 @@* immediately, the download runs detached, progress streams over the shared SSE* helpers, and the client attaches with useSseProgress. A single yt-dlp* invocation does the whole job (best mp4 video+audio merged via ffmpeg).+ *+ * The yt-dlp invocation itself lives in ytdlpVideoImport.js — extracted so the+ * YouTube brain ingest can run the same download as one step of a bigger job+ * (the same split ytdlpAudioImport.js already made for the audio path). This+ * module keeps the download-specific concerns: the host allowlist, the SSE job+ * map, and the `source: 'download'` video-history entry.*/-import { spawn } from 'child_process';-import { readdir, unlink } from 'fs/promises';-import { join, dirname } from 'path';+import { join } from 'path';import { randomUUID } from 'crypto';import { ServerError } from '../lib/errorHandler.js';-import { shortId, PATHS, ensureDir } from '../lib/fileUtils.js';+import { shortId, PATHS } from '../lib/fileUtils.js';import { findFfmpeg, generateThumbnail, probeVideoDuration } from '../lib/ffmpeg.js';import { findYtDlp } from '../lib/ytdlp.js';import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../lib/sseUtils.js';-import { safeChildProcessEnv } from '../lib/processEnv.js';-import { createLineReader } from '../lib/streamLines.js';+import { downloadVideoToDir, cleanupProducedFiles } from './ytdlpVideoImport.js';import { loadHistory, mutateVideoHistory } from './videoGen/history.js';import { deleteHistoryItem } from './videoGen/local.js';import { videoGenEvents } from './videoGen/events.js';@@ -66,13 +69,7 @@ export function cancelVideoDownload(jobId) {const job = downloadJobs.get(jobId);if (!job || !job.process) return false;const proc = job.process;- proc.kill('SIGTERM');- setTimeout(() => {- if (job.process === proc && proc.exitCode === null && proc.signalCode === null) {- console.log(`⚠️ yt-dlp download didn't exit on SIGTERM — escalating to SIGKILL`);- proc.kill('SIGKILL');- }- }, 8000);+ killWithEscalation(proc, { label: 'yt-dlp download', stillRunning: () => job.process === proc });return true;}@@ -97,42 +94,10 @@ export async function deleteDownload(id) {return deleteHistoryItem(id);}-const TITLE_PREFIX = 'PORTOS_TITLE:';-// Machine-readable progress markers via yt-dlp's --progress-template rather than-// scraping human-readable console lines — mirrors trackYoutubeImport.-const PROGRESS_PREFIX = 'PORTOS_PROGRESS:';-const STAGE_PREFIX = 'PORTOS_STAGE:';-// A cancelled/failed run can leave yt-dlp's pre-merge fragment files behind// (`downloaded-<uuid>.f137.mp4`, `.part`, etc.), so cleanup globs every file// this job's prefix touched in PATHS.videos rather than unlinking one path.-async function cleanupDownloadFiles(jobId) {- const prefix = `${FILENAME_PREFIX}${jobId}`;- const entries = await readdir(PATHS.videos).catch(() => []);- await Promise.all(- entries.filter((name) => name.startsWith(prefix)).map((name) => unlink(join(PATHS.videos, name)).catch(() => {})),- );-}--// Locate the final produced file for a job. yt-dlp writes intermediate streams-// as `downloaded-<id>.f<code>.<ext>` and a `.part`/`.ytdl` in progress, then-// merges/remuxes to a single `downloaded-<id>.<ext>` and deletes the rest. We do-// NOT hardcode `.mp4`: the format fallback chain can land a single-file webm/mkv-// (VP9/AV1) that `--merge-output-format`/`--remux-video mp4` only converts on a-// best-effort basis, so assuming `.mp4` would miss a perfectly-good download and-// then delete it as a "failure". Prefer an exact `.mp4`, else the lone remaining-// non-intermediate file. Returns the basename or null when nothing was produced.-export async function findDownloadedFile(jobId, dir = PATHS.videos) {- const prefix = `${FILENAME_PREFIX}${jobId}.`;- const entries = await readdir(dir).catch(() => []);- const candidates = entries.filter((n) =>- n.startsWith(prefix)- && !n.endsWith('.part')- && !n.endsWith('.ytdl')- && !/\.f\d+\.[^.]+$/.test(n), // format-fragment intermediates (.f137.mp4)- );- return candidates.find((n) => n === `${prefix}mp4`) || candidates[0] || null;-}+const cleanupDownloadFiles = (jobId) => cleanupProducedFiles(`${FILENAME_PREFIX}${jobId}`, PATHS.videos);// Build the `source: 'download'` video-history entry. Pure + exported so the// load-bearing shape (the fields normalizeVideo, mediaAssetIndex videoToRow, and@@ -153,6 +118,74 @@ export function buildDownloadHistoryEntry({ jobId, filename, thumbnail, duration};}+/**+ * Download a video and land it in the shared media library.+ *+ * This — not the bare yt-dlp spawn — is the unit a second caller wants: it owns+ * the `downloaded-<id>` filename prefix, the thumbnail + duration probe, the+ * `source: 'download'` video-history entry, the media-index `completed` event,+ * and cleanup of partial files when any of that fails. Extracted so the YouTube+ * brain ingest lands a video EXACTLY the way the Dev Tools downloader does;+ * duplicating the tail is how the two silently drift.+ *+ * `outcome: 'canceled' | 'failed'` are returned rather than thrown (matching+ * `downloadVideoToDir`) so the caller decides how to surface them; anything that+ * fails AFTER a successful download throws, with the partial files already+ * cleaned up.+ *+ * `id` is the library id: the filename prefix, the thumbnail name and the+ * history-entry id all derive from it, so a caller that already has a job id+ * passes it to keep the two aligned (the SSE downloader does — its terminal+ * frame's `id` has always been the video's id).+ *+ * @returns {Promise<{ outcome:'complete'|'canceled'|'failed', entry?:object, reason?:string }>}+ */+export async function downloadVideoIntoLibrary({+ url, ytDlp, ffmpeg, id, maxBytes = VIDEO_DOWNLOAD_MAX_BYTES,+ maxDurationSec = VIDEO_DOWNLOAD_MAX_DURATION_SEC, onProgress, registerProcess,+}) {+ const jobId = id || randomUUID();+ try {+ const result = await downloadVideoToDir({+ url,+ ytDlp,+ ffmpeg,+ outDir: PATHS.videos,+ filePrefix: `${FILENAME_PREFIX}${jobId}`,+ maxBytes,+ maxDurationSec,+ onProgress,+ registerProcess,+ });+ if (result.outcome !== 'complete') return result;++ const { filename, title } = result;+ const outPath = join(PATHS.videos, filename);+ onProgress?.({ percent: 100, stage: 'finalizing' });+ const [thumbnail, durationSec] = await Promise.all([+ generateThumbnail(outPath, jobId),+ probeVideoDuration(outPath).catch(() => null),+ ]);++ // Derived, not a generation: a `source: 'download'` video-history entry so+ // the existing videoToRow / onVideoCompleted media-index path and the+ // gallery pick it up unmodified. Serialized read-modify-write so two+ // near-simultaneous downloads can't clobber each other's entry.+ const entry = buildDownloadHistoryEntry({ jobId, filename, thumbnail, durationSec, title, sourceUrl: url });+ await mutateVideoHistory((history) => { history.unshift(entry); return history; });++ // Let the live media-asset index hook index this immediately (it loads+ // history by generationId and upserts one row). Reconcile is the backstop.+ videoGenEvents.emit('completed', { generationId: jobId, filename, path: `/data/videos/${filename}`, thumbnail });+ return { outcome: 'complete', entry };+ } catch (err) {+ // A throw between the download and the history write would otherwise orphan+ // a multi-GB file in data/videos with nothing pointing at it.+ await cleanupDownloadFiles(jobId);+ throw err;+ }+}+/*** Kick off a full-video download. Returns `{ jobId }` immediately; the download* runs detached and streams progress over SSE. Terminal frames:@@ -167,134 +200,34 @@ export async function startVideoDownload(url) {if (!ffmpeg) throw new ServerError('ffmpeg not found on PATH', { status: 500, code: 'FFMPEG_MISSING' });const jobId = randomUUID();- // The final filename/extension isn't known until the download resolves (the- // format fallback can produce a non-mp4 single file), so it's detected from- // disk on success via findDownloadedFile rather than assumed here.- const outTemplate = join(PATHS.videos, `${FILENAME_PREFIX}${jobId}.%(ext)s`);-const job = { id: jobId, status: 'running', clients: [], process: null };downloadJobs.set(jobId, job);console.log(`📥 Video download ${shortId(jobId)} — ${url}`);(async () => {- let title = '';try {- // On a fresh install data/videos may not exist yet (setup-data.js doesn't- // create it, and no prior render/import may have). Every other video- // writer ensures it first; without this the first download points yt-dlp- // at a missing directory and fails before producing a file.- await ensureDir(PATHS.videos);- const args = [- // Prefer an mp4 (h264/aac) video+audio pair that merges cleanly for- // broad browser playback; fall back to best single-file mp4, then best.- '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best',- '--merge-output-format', 'mp4',- // Best-effort remux a single-file/non-mp4 result into an mp4 container so- // browser playback is broad; when the codec can't be remuxed losslessly- // yt-dlp leaves the native container, which findDownloadedFile handles.- '--remux-video', 'mp4',- '--no-playlist',- '--ffmpeg-location', dirname(ffmpeg),- '--newline',- '--print', `${TITLE_PREFIX}%(title)s`,- '--progress-template', `download:${PROGRESS_PREFIX}%(progress._percent_str)s`,- '--progress-template', `postprocess:${STAGE_PREFIX}merging`,- // --print implies --simulate AND suppresses normal progress reporting;- // --no-simulate + --progress restore the real run + machine markers- // (same yt-dlp quirk documented in trackYoutubeImport).- '--no-simulate',- '--progress',- '--max-filesize', String(VIDEO_DOWNLOAD_MAX_BYTES),- // Two --match-filters are OR'd by yt-dlp: bound KNOWN-duration videos to- // the cap, but let a post whose duration can't be resolved pre-download- // (common on x.com/Twitter) through rather than silently rejecting it —- // the byte cap above still bounds it. A known video longer than the cap- // matches neither filter and is skipped.- '--match-filters', `duration <= ${VIDEO_DOWNLOAD_MAX_DURATION_SEC}`,- '--match-filters', '!duration',- '-o', outTemplate,+ const result = await downloadVideoIntoLibrary({url,- ];- const proc = spawn(ytDlp, args, { env: safeChildProcessEnv(), stdio: ['ignore', 'pipe', 'pipe'] });- job.process = proc;-- const onLine = (line) => {- if (line.startsWith(TITLE_PREFIX)) {- title = line.slice(TITLE_PREFIX.length).trim();- return;- }- if (line.startsWith(PROGRESS_PREFIX)) {- const percent = parseFloat(line.slice(PROGRESS_PREFIX.length));- if (Number.isFinite(percent)) broadcastSse(job, { type: 'progress', percent });- return;- }- if (line.startsWith(STAGE_PREFIX)) {- broadcastSse(job, { type: 'progress', percent: 100, stage: line.slice(STAGE_PREFIX.length) });- }- };- // Separate readers per stream — a shared buffer can complete a partial- // line from one stream with a chunk from the other, corrupting a marker.- const stdoutReader = createLineReader(onLine);- const stderrReader = createLineReader(onLine);- proc.stdout.on('data', stdoutReader.push);- proc.stderr.on('data', stderrReader.push); // yt-dlp writes some progress/info lines to stderr too-- const exit = await new Promise((resolve) => {- proc.on('error', (err) => resolve({ code: null, reason: `spawn failed: ${err.message}` }));- proc.on('close', (code, signal) => resolve({ code, signal }));+ ytDlp,+ ffmpeg,+ id: jobId, // keep the library id == the SSE job id, as it has always been+ onProgress: ({ percent, stage }) => broadcastSse(job, { type: 'progress', percent, ...(stage ? { stage } : {}) }),+ registerProcess: (proc) => { job.process = proc; },});- job.process = null;- if (exit.signal === 'SIGTERM' || exit.signal === 'SIGKILL') {- // Don't flush on cancel — a SIGKILL'd child leaves only a partial- // marker line in the carry, and emitting it would broadcast a stray- // progress/stage SSE frame right before the cancellation frame.+ if (result.outcome === 'canceled') {console.log(`🛑 Video download ${shortId(jobId)} cancelled`);broadcastSse(job, { type: 'canceled' });- await cleanupDownloadFiles(jobId);return;}- // Flush any final line the child wrote without a trailing newline.- stdoutReader.flush();- stderrReader.flush();- const produced = await findDownloadedFile(jobId);- if (exit.code !== 0 || !produced) {- // A --match-filters/--max-filesize rejection exits 0 with no output- // file (yt-dlp treats a filtered-out video as "nothing to do") — and- // --print suppresses the specific reason, so name the known bounds.- // x.com/Twitter downloads also fail here on login-walled/rate-limited- // content; surface a clear message rather than a bare exit code.- const reason = exit.code === 0- ? `no video was produced — it may be longer than ${VIDEO_DOWNLOAD_MAX_DURATION_SEC / 60} minutes or larger than ${Math.round(VIDEO_DOWNLOAD_MAX_BYTES / 1024 / 1024 / 1024)}GB, or (for x.com) login-walled, rate-limited, or otherwise unavailable`- : (exit.reason || `yt-dlp exited ${exit.code}`);- throw new Error(reason);- }-- const filename = produced;- const outPath = join(PATHS.videos, filename);- broadcastSse(job, { type: 'progress', percent: 100, stage: 'finalizing' });- const [thumbnail, durationSec] = await Promise.all([- generateThumbnail(outPath, jobId),- probeVideoDuration(outPath).catch(() => null),- ]);-- // Derived, not a generation: a `source: 'download'` video-history entry so- // the existing videoToRow / onVideoCompleted media-index path and the- // gallery pick it up unmodified. Serialized read-modify-write so two- // near-simultaneous downloads can't clobber each other's entry.- const entry = buildDownloadHistoryEntry({ jobId, filename, thumbnail, durationSec, title, sourceUrl: url });- await mutateVideoHistory((history) => { history.unshift(entry); return history; });-- // Let the live media-asset index hook index this immediately (it loads- // history by generationId and upserts one row). Reconcile is the backstop.- videoGenEvents.emit('completed', { generationId: jobId, filename, path: `/data/videos/${filename}`, thumbnail });+ if (result.outcome === 'failed') throw new Error(result.reason);- console.log(`📥 Video download ${shortId(jobId)} complete — "${entry.title}" (${filename})`);+ const { entry } = result;+ console.log(`📥 Video download ${shortId(jobId)} complete — "${entry.title}" (${entry.filename})`);broadcastSse(job, { type: 'complete', id: jobId, video: entry });} catch (err) {console.error(`❌ Video download ${shortId(jobId)} failed: ${err?.message || err}`);broadcastSse(job, { type: 'error', error: err?.message || String(err) });- await cleanupDownloadFiles(jobId);} finally {closeJobAfterDelay(downloadJobs, jobId);}diff --git a/server/services/videoDownload.test.js b/server/services/videoDownload.test.jsindex ce38444346..198289696c 100644--- a/server/services/videoDownload.test.js+++ b/server/services/videoDownload.test.js@@ -1,4 +1,4 @@-import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { describe, it, expect, vi, beforeEach } from 'vitest';// Mock the history store so listDownloads/deleteDownload can be exercised// without touching disk, and mock deleteHistoryItem so deleteDownload's@@ -14,16 +14,12 @@ vi.mock('./videoGen/history.js', () => ({vi.mock('./videoGen/local.js', () => ({ deleteHistoryItem }));vi.mock('./videoGen/events.js', () => ({ videoGenEvents: { emit: vi.fn() } }));-import { mkdtemp, writeFile, rm } from 'fs/promises';-import { join } from 'path';-import { tmpdir } from 'os';import {SUPPORTED_VIDEO_URL_RE,assertSupportedVideoUrl,listDownloads,deleteDownload,buildDownloadHistoryEntry,- findDownloadedFile,} from './videoDownload.js';describe('videoDownload URL allowlist', () => {@@ -122,32 +118,3 @@ describe('buildDownloadHistoryEntry (contract shape)', () => {expect(entry).not.toHaveProperty('durationSec');});});--describe('findDownloadedFile (robust output detection)', () => {- let dir;- beforeEach(async () => { dir = await mkdtemp(join(tmpdir(), 'viddl-')); });- afterEach(async () => { await rm(dir, { recursive: true, force: true }); });-- it('prefers an exact .mp4 over other candidates', async () => {- await writeFile(join(dir, 'downloaded-x.mp4'), 'v');- await writeFile(join(dir, 'downloaded-x.webm'), 'v');- expect(await findDownloadedFile('x', dir)).toBe('downloaded-x.mp4');- });-- it('finds a non-mp4 single-file result (the .mp4-assumption bug)', async () => {- await writeFile(join(dir, 'downloaded-y.webm'), 'v');- expect(await findDownloadedFile('y', dir)).toBe('downloaded-y.webm');- });-- it('ignores in-progress and format-fragment intermediates', async () => {- await writeFile(join(dir, 'downloaded-z.f137.mp4'), 'v'); // fragment- await writeFile(join(dir, 'downloaded-z.mp4.part'), 'v'); // partial- await writeFile(join(dir, 'downloaded-z.webm.ytdl'), 'v'); // sidecar- expect(await findDownloadedFile('z', dir)).toBeNull();- });-- it('does not match a different job id', async () => {- await writeFile(join(dir, 'downloaded-other.mp4'), 'v');- expect(await findDownloadedFile('mine', dir)).toBeNull();- });-});diff --git a/server/services/youtubeImport.js b/server/services/youtubeImport.jsindex ac684e42ea..0426f2aade 100644--- a/server/services/youtubeImport.js+++ b/server/services/youtubeImport.js@@ -48,7 +48,10 @@ export function youtubeVideoIdFromUrl(url) {const s = String(url).trim();const vParam = /[?&]v=([A-Za-z0-9_-]{6,20})/.exec(s);if (vParam) return vParam[1];- const pathId = /(?:youtu\.be\/|\/shorts\/|\/embed\/|\/v\/)([A-Za-z0-9_-]{6,20})/.exec(s);+ // `/live/` is the permalink shape a finished livestream keeps — Takeout watch+ // records for streams carry it, and the brain ingest accepts it, so it must+ // resolve to an id here rather than being silently dropped as unrecognized.+ const pathId = /(?:youtu\.be\/|\/shorts\/|\/embed\/|\/live\/|\/v\/)([A-Za-z0-9_-]{6,20})/.exec(s);if (pathId) return pathId[1];return null;}diff --git a/server/services/youtubeIngest.js b/server/services/youtubeIngest.jsnew file mode 100644index 0000000000..ae8976a95b--- /dev/null+++ b/server/services/youtubeIngest.js@@ -0,0 +1,765 @@+/**+ * YouTube → Brain ingest.+ *+ * "I watched (or want to work from) this video; pull it into PortOS as content+ * I've consumed and deliberately kept." One job, three independent switches:+ *+ * - `captureTranscript` — pull the captions and turn them into readable prose,+ * stored locally AND mirrored into the Obsidian vault as a note (so the+ * transcript is greppable/linkable next to everything else the user keeps).+ * - `downloadVideo` — the full video, into the shared media library via+ * the same `source: 'download'` history entry the Dev Tools downloader writes.+ * - `ingestAudio` — an mp3 kept alongside the transcript.+ *+ * Regardless of which are on, an ingest ALWAYS records the consumption itself:+ * - a brain `links` record (federated — this is the "saved for future+ * reference" artifact that peers should see), and+ * - a `media.watch` human-activity event (machine-local, so the video shows up+ * on the Timeline alongside passively-synced watch history).+ *+ * Finally, when the user supplies an `agentPrompt` at ingest time, a CoS task is+ * queued that points an agent at the freshly-stored transcript with that prompt+ * — "here is what I want done with this content." No prompt, no task: PortOS+ * must never queue AI work the user didn't ask for (root CLAUDE.md, AI Provider+ * Usage Policy).+ *+ * Storage:+ * data/brain/youtube/index.json — machine-local ingest index (paths!)+ * data/brain/youtube/<videoId>.md — canonical transcript copy+ * data/brain/youtube/<videoId>.mp3 — audio, when ingestAudio was on+ * data/brain/youtube-ingest-settings.json — vault/folder + option defaults+ *+ * The index is deliberately NOT a synced brain store: every field in it is a+ * local filesystem path, an Obsidian vault id, or a local video-history id —+ * all machine-local, and federating them would poison peer reconcile the same+ * way the daily log's obsidian-locations sidecar would (see brainJournal.js).+ * The durable, federated record of "I kept this" is the links entry.+ */++import { spawn } from 'child_process';+import { readdir, readFile, rename, rm, stat, unlink } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';+import { randomUUID } from 'crypto';+import { ServerError } from '../lib/errorHandler.js';+import { atomicWrite, ensureDir, PATHS, readJSONFile, shortId } from '../lib/fileUtils.js';+import { findFfmpeg } from '../lib/ffmpeg.js';+import { findYtDlp } from '../lib/ytdlp.js';+import { killWithEscalation } from '../lib/killWithEscalation.js';+import { safeChildProcessEnv } from '../lib/processEnv.js';+import { attachSseClient as attachSse, broadcastSse, closeJobAfterDelay } from '../lib/sseUtils.js';+import { vttToPlainText } from '../lib/vttTranscript.js';+import { createMutex } from '../lib/asyncMutex.js';+import { downloadAudioToTempMp3 } from './ytdlpAudioImport.js';+import { downloadVideoIntoLibrary } from './videoDownload.js';+import { youtubeVideoIdFromUrl } from './youtubeImport.js';+import * as obsidian from './obsidian.js';+import * as brainStorage from './brainStorage.js';+import { createLinkFromUrl } from './brain.js';+import * as brainJournal from './brainJournal.js';+import { recordEvents } from './humanActivity.js';+// Straight from the task store rather than the cos.js facade — same reason+// referenceRepos.js does: it avoids pulling the whole Chief-of-Staff graph in+// behind a brain-side service. The `tasks:changed` event addTask emits is what+// cos.js listens on to spawn, so queueing behaves identically either way.+import { addTask } from './cosTaskStore.js';++// Accepts the URL shapes that carry a single video id. Playlists, channels, and+// `/@handle` pages are rejected up front so a paste that would have yt-dlp pull+// 300 videos fails with a clear message instead of running for an hour.+export const YOUTUBE_INGEST_URL_RE =+ /^https?:\/\/(www\.|m\.|music\.)?(youtube\.com\/(watch\?[^\s#]*\bv=[\w-]{6,}|shorts\/[\w-]{6,}|live\/[\w-]{6,}|embed\/[\w-]{6,})|youtu\.be\/[\w-]{6,})/i;++/**+ * Validate an ingest URL and hand back the video id it carries — the id has to+ * be parsed to validate at all, so returning it keeps the caller from parsing+ * the same URL a second time (and from disagreeing about the answer).+ */+export function assertYoutubeIngestUrl(url) {+ const videoId = typeof url === 'string' && YOUTUBE_INGEST_URL_RE.test(url) ? youtubeVideoIdFromUrl(url) : null;+ if (!videoId) {+ throw new ServerError(+ 'Expected a single-video YouTube URL (watch, shorts, live, or youtu.be) — playlists and channels are not supported',+ { status: 400, code: 'YOUTUBE_URL_INVALID' },+ );+ }+ return videoId;+}++// Bound resource use, same reasoning as the audio/video importers: a livestream+// archive or a 12-hour upload would otherwise download unbounded. Generous —+// conference talks and long-form podcasts are exactly what this feature is for.+export const INGEST_MAX_DURATION_SEC = 6 * 60 * 60; // 6 hours+export const INGEST_VIDEO_MAX_BYTES = 4 * 1024 * 1024 * 1024; // 4 GB+export const INGEST_AUDIO_MAX_BYTES = 512 * 1024 * 1024; // 512 MB++// `--dump-single-json` on a long video can be slow (yt-dlp negotiates formats);+// bound it so a wedged extractor can't hold a job open forever.+const METADATA_TIMEOUT_MS = 90_000;+const SUBTITLE_TIMEOUT_MS = 120_000;++const INGEST_DIR = join(PATHS.brain, 'youtube');+const INDEX_FILE = join(INGEST_DIR, 'index.json');+const SETTINGS_FILE = join(PATHS.brain, 'youtube-ingest-settings.json');++const DEFAULT_SETTINGS = {+ // null → inherit the Daily Log's vault, so a user who already pointed the+ // journal at Obsidian gets transcripts in the same vault with zero setup.+ obsidianVaultId: null,+ obsidianFolder: 'Consumed/YouTube',+ autoSync: true,+ // Quick-capture's advanced panel seeds its checkboxes from these.+ defaultCaptureTranscript: true,+ defaultDownloadVideo: false,+ defaultIngestAudio: false,+ taskPriority: 'MEDIUM',+};++// ─── Settings ──────────────────────────────────────────────────────────────++export async function getSettings() {+ await ensureDir(PATHS.brain);+ const loaded = await readJSONFile(SETTINGS_FILE, null);+ return loaded ? { ...DEFAULT_SETTINGS, ...loaded } : { ...DEFAULT_SETTINGS };+}++export async function updateSettings(partial) {+ const next = { ...(await getSettings()), ...partial };+ await atomicWrite(SETTINGS_FILE, next);+ return next;+}++/**+ * Which Obsidian vault transcripts go to: the explicit setting when present,+ * otherwise the Daily Log's vault. Returns null when neither is configured (the+ * ingest still succeeds — the local transcript copy is the canonical one).+ */+async function resolveVaultId(settings) {+ if (settings.obsidianVaultId) return settings.obsidianVaultId;+ const journalSettings = await brainJournal.getSettings().catch(() => null);+ return journalSettings?.obsidianVaultId || null;+}++// ─── Local ingest index ────────────────────────────────────────────────────++// Serialize read→modify→write of the index so two ingests finishing at once+// can't clobber each other's entry (single-user, but a "transcript only" job+// and a slow video job legitimately overlap).+const indexMutex = createMutex();++async function loadIndex() {+ await ensureDir(INGEST_DIR);+ const loaded = await readJSONFile(INDEX_FILE, {});+ return loaded && typeof loaded === 'object' && !Array.isArray(loaded) ? loaded : {};+}++// A first ingest only patches in the artifacts its switches produced, so seed+// the rest as explicit nulls — readers (and the client) get one record shape+// whether a video was ingested once for its transcript or three times for+// everything.+const NEW_INGEST = { transcript: null, obsidian: null, video: null, audio: null, taskId: null, agentPrompt: null };++async function putIngest(videoId, patch) {+ return indexMutex(async () => {+ const index = await loadIndex();+ const existing = index[videoId] || null;+ const record = {+ ...(existing || NEW_INGEST),+ ...patch,+ videoId,+ ingestedAt: existing?.ingestedAt || new Date().toISOString(),+ updatedAt: new Date().toISOString(),+ };+ index[videoId] = record;+ await atomicWrite(INDEX_FILE, index);+ return record;+ });+}++/** Every ingest, newest first. */+export async function listIngests() {+ const index = await loadIndex();+ return Object.values(index).sort((a, b) => String(b.ingestedAt || '').localeCompare(String(a.ingestedAt || '')));+}++export async function getIngest(videoId) {+ const index = await loadIndex();+ return index[videoId] || null;+}++/** The stored transcript markdown, or null when this video has none. */+export async function getTranscript(videoId) {+ const record = await getIngest(videoId);+ if (!record?.transcript?.path) return null;+ return readFile(record.transcript.path, 'utf-8').catch(() => null);+}++/**+ * Forget an ingest: removes the local transcript/audio files and the Obsidian+ * note, then drops the index entry. Deliberately leaves the links record, the+ * downloaded video, and the activity event alone — each has its own lifecycle+ * and its own UI to delete from, and silently nuking a user's media library+ * entry from a "remove this transcript" action would be a nasty surprise.+ */+export async function deleteIngest(videoId) {+ // Read the record and drop it inside ONE lock, then clean up its files:+ // reading outside the lock would unlink paths from a record a concurrent+ // re-ingest had already replaced, and would parse the whole index twice.+ const record = await indexMutex(async () => {+ const index = await loadIndex();+ const found = index[videoId] || null;+ if (!found) return null;+ delete index[videoId];+ await atomicWrite(INDEX_FILE, index);+ return found;+ });+ if (!record) return false;++ if (record.transcript?.path) await unlink(record.transcript.path).catch(() => {});+ if (record.audio?.path) await unlink(record.audio.path).catch(() => {});+ if (record.obsidian?.path && record.obsidian?.vaultId) {+ await obsidian.deleteNote(record.obsidian.vaultId, record.obsidian.path).catch(() => {});+ }+ console.log(`🧹 Removed YouTube ingest ${videoId}`);+ return true;+}++// ─── yt-dlp helpers ────────────────────────────────────────────────────────++// Run yt-dlp to completion, collecting stdout. Used for the two invocations that+// produce no progress stream (metadata dump, subtitle fetch); the long-running+// media downloads go through the shared audio/video cores instead.+function runYtDlp(ytDlp, args, { timeoutMs, registerProcess }) {+ return new Promise((resolve) => {+ const proc = spawn(ytDlp, args, { env: safeChildProcessEnv(), stdio: ['ignore', 'pipe', 'pipe'] });+ registerProcess?.(proc);+ let stdout = '';+ let stderr = '';+ proc.stdout.on('data', (d) => { stdout += d.toString(); });+ proc.stderr.on('data', (d) => { stderr += d.toString(); });+ const timer = setTimeout(() => proc.kill('SIGKILL'), timeoutMs);+ proc.on('error', (err) => {+ clearTimeout(timer);+ registerProcess?.(null);+ resolve({ code: null, stdout, stderr, reason: `spawn failed: ${err.message}` });+ });+ proc.on('close', (code, signal) => {+ clearTimeout(timer);+ registerProcess?.(null);+ resolve({ code, signal, stdout, stderr });+ });+ });+}++/**+ * Read the video's metadata and, when `subsDir` is given, write its English+ * caption files there — in ONE yt-dlp invocation.+ *+ * Doing them separately cost two full YouTube extractions (player-response ++ * format negotiation, several seconds each) of the same URL on the DEFAULT+ * ingest path. `--dump-single-json` normally implies `--simulate`, which would+ * skip writing the subtitle files, so `--no-simulate` is required alongside it+ * — the same yt-dlp quirk `--print` has, documented at length in+ * ytdlpAudioImport.js. Verified against a real video: the JSON lands on stdout+ * and the `.vtt` files land in `subsDir`.+ *+ * Returns the parsed metadata; the caller reads the caption files itself.+ */+async function fetchVideoInfo(ytDlp, url, registerProcess, { subsDir = null } = {}) {+ const result = await runYtDlp(+ ytDlp,+ [+ '--dump-single-json', '--no-playlist', '--no-warnings',+ ...(subsDir+ ? [+ '--no-simulate', '--skip-download',+ '--write-subs', '--write-auto-subs',+ // Prefer real English tracks; `en.*` also catches en-US/en-GB/en-orig.+ '--sub-langs', 'en.*,en',+ // yt-dlp can only *convert* subtitles with ffmpeg, but `--sub-format`+ // negotiates the download format directly — vtt is what YouTube serves+ // natively, so no conversion (and no ffmpeg dependency) is needed.+ '--sub-format', 'vtt/srt/best',+ '-o', join(subsDir, 'subs'),+ ]+ : ['--skip-download']),+ url,+ ],+ { timeoutMs: subsDir ? SUBTITLE_TIMEOUT_MS : METADATA_TIMEOUT_MS, registerProcess },+ );+ if (result.signal) throw new Error('canceled');+ if (result.code !== 0) {+ // yt-dlp's own stderr is the most actionable thing we have here (private+ // video, age gate, region block, extractor breakage all land differently).+ const detail = (result.stderr || result.reason || '').trim().split('\n').filter(Boolean).pop();+ throw new Error(detail || `yt-dlp exited ${result.code} while reading video metadata`);+ }+ return parseVideoMetadata(result.stdout);+}++/**+ * Normalize yt-dlp's `--dump-single-json` payload down to the handful of fields+ * the ingest actually stores. Pure + exported so the shape is unit-testable+ * without a yt-dlp spawn.+ */+export function parseVideoMetadata(json) {+ const raw = typeof json === 'string' ? JSON.parse(json) : json;+ // `upload_date` is YYYYMMDD with no separators.+ const upload = typeof raw?.upload_date === 'string' && /^\d{8}$/.test(raw.upload_date)+ ? `${raw.upload_date.slice(0, 4)}-${raw.upload_date.slice(4, 6)}-${raw.upload_date.slice(6, 8)}`+ : null;+ const duration = Number(raw?.duration);+ return {+ videoId: raw?.id || null,+ title: (raw?.title || '').trim() || 'Untitled video',+ channel: (raw?.channel || raw?.uploader || '').trim() || null,+ channelUrl: raw?.channel_url || raw?.uploader_url || null,+ durationSec: Number.isFinite(duration) && duration > 0 ? Math.round(duration) : null,+ publishedAt: upload,+ description: (raw?.description || '').trim(),+ thumbnailUrl: raw?.thumbnail || null,+ // `subtitles` holds human-authored tracks, `automatic_captions` the ASR+ // ones. This is the ONLY reliable manual-vs-auto signal: yt-dlp writes both+ // kinds to the same `<base>.<lang>.vtt` filename shape, so the produced+ // filename can't be used to tell them apart. Auto captions have no+ // punctuation-grade accuracy on proper nouns, which is worth recording+ // alongside the stored transcript.+ hasManualCaptions: Object.keys(raw?.subtitles || {}).length > 0,+ };+}++/**+ * Read the caption files `fetchVideoInfo` wrote into `subsDir` and render them+ * as prose. Returns `{ text, language, source }` or null when the video had no+ * captions.+ *+ * yt-dlp names subtitle files `subs.<lang>.<ext>` and the language tag varies+ * (`en`, `en-US`, `en-orig`), so the produced file is discovered from disk+ * rather than assumed — the same "don't guess the filename" rule the video core+ * follows. `--sub-langs en.*,en` routinely writes MORE than one file (a real+ * upload yields both `subs.en-orig.vtt` and `subs.en.vtt`), so a plain `en`+ * track is preferred and the rest ignored, making the choice deterministic.+ *+ * `hasManualCaptions` comes from the same metadata dump — see parseVideoMetadata.+ */+async function readTranscriptFrom(subsDir, { hasManualCaptions } = {}) {+ const produced = (await readdir(subsDir).catch(() => [])).filter((n) => /\.(vtt|srt)$/i.test(n));+ const chosen = produced.find((n) => /\.en\.(vtt|srt)$/i.test(n)) || produced[0] || null;+ if (!chosen) return null;++ const raw = await readFile(join(subsDir, chosen), 'utf-8').catch(() => '');+ const text = vttToPlainText(raw);+ if (!text) return null;+ const langMatch = /\.([\w-]+)\.(vtt|srt)$/i.exec(chosen);+ return {+ text,+ language: langMatch ? langMatch[1] : 'en',+ source: hasManualCaptions ? 'captions' : 'auto-captions',+ };+}++// ─── Obsidian note ─────────────────────────────────────────────────────────++// Characters that are illegal or hostile in a filename on macOS/Windows, plus+// leading dots (hidden files) and trailing dots/spaces (Windows strips them).+const sanitizeFilename = (name) =>+ String(name)+ .replace(/[/\\:*?"<>|#^[\]]/g, ' ')+ .replace(/\s+/g, ' ')+ .replace(/^[.\s]+|[.\s]+$/g, '')+ .slice(0, 80)+ .trim() || 'video';++const formatDuration = (sec) => {+ if (!Number.isFinite(sec) || sec <= 0) return null;+ const h = Math.floor(sec / 3600);+ const m = Math.floor((sec % 3600) / 60);+ const s = sec % 60;+ return h > 0+ ? `${h}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`+ : `${m}:${String(s).padStart(2, '0')}`;+};++// YAML scalars we interpolate can contain quotes/colons; wrap in double quotes+// and escape the two characters that would break out of them.+const yamlString = (value) => `"${String(value ?? '').replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;++/**+ * Render the Obsidian note for an ingest. Pure + exported so the frontmatter+ * shape (which the user's own vault queries/dataview will key on) is pinned by+ * a test rather than only produced behind a yt-dlp spawn.+ */+export function buildIngestNote({ meta, url, transcript, tags, agentPrompt, capturedAt }) {+ const duration = formatDuration(meta.durationSec);+ const frontmatter = [+ '---',+ `title: ${yamlString(meta.title)}`,+ `source: ${url}`,+ ...(meta.channel ? [`channel: ${yamlString(meta.channel)}`] : []),+ ...(duration ? [`duration: ${yamlString(duration)}`] : []),+ ...(meta.publishedAt ? [`published: ${meta.publishedAt}`] : []),+ `captured: ${capturedAt.slice(0, 10)}`,+ `tags: [${['youtube', 'consumed', 'portos', ...tags].join(', ')}]`,+ '---',+ ];++ const facts = [+ `**Source:** [${url}](${url})`,+ ...(meta.channel ? [`**Channel:** ${meta.channel}`] : []),+ ...(duration ? [`**Duration:** ${duration}`] : []),+ ...(meta.publishedAt ? [`**Published:** ${meta.publishedAt}`] : []),+ ].join(' · ');++ const body = [+ '',+ `# ${meta.title}`,+ '',+ facts,+ '',+ ...(agentPrompt ? ['> [!note] Why I kept this', ...agentPrompt.split('\n').map((l) => `> ${l}`), ''] : []),+ ...(meta.description ? ['## Description', '', meta.description, ''] : []),+ '## Transcript',+ '',+ transcript?.text+ ? transcript.text+ : '_No captions were available for this video._',+ '',+ ];++ return [...frontmatter, ...body].join('\n');+}++const buildNotePath = (settings, meta, capturedAt) => {+ const folder = (settings.obsidianFolder || '').replace(/^\/+|\/+$/g, '');+ const filename = `${capturedAt.slice(0, 10)} ${sanitizeFilename(meta.title)} (${meta.videoId}).md`;+ return folder ? `${folder}/${filename}` : filename;+};++// ─── CoS follow-up task ────────────────────────────────────────────────────++/**+ * The prompt body handed to the CoS agent. Pure + exported so the contract+ * ("here is the content, here is what the user wants done with it") is testable+ * without queueing a real task.+ */+export function buildAgentTaskContext({ meta, url, agentPrompt, transcriptPath, notePath, tags, hasTranscript }) {+ return [+ `The user ingested a YouTube video into the PortOS brain and asked for this to be done with it:`,+ '',+ agentPrompt,+ '',+ '---',+ '',+ '## Content',+ '',+ `- **Title:** ${meta.title}`,+ ...(meta.channel ? [`- **Channel:** ${meta.channel}`] : []),+ `- **URL:** ${url}`,+ ...(meta.durationSec ? [`- **Duration:** ${formatDuration(meta.durationSec)}`] : []),+ ...(tags.length ? [`- **Tags:** ${tags.join(', ')}`] : []),+ ...(hasTranscript+ ? [`- **Transcript (read this first):** \`${transcriptPath}\``]+ : ['- **Transcript:** not available — this video had no captions.']),+ ...(notePath ? [`- **Obsidian note:** \`${notePath}\``] : []),+ '',+ '## How to work this',+ '',+ 'Read the transcript before doing anything else — the user\'s request above is about THIS content, not about the video in the abstract.',+ 'Produce a concrete plan, not a summary. Where the request implies changes to PortOS, file GitHub issues for each actionable item (follow the `portos-file-issue` conventions: decide-don\'t-defer, ready-to-work bodies) and list the issue numbers in your final response.',+ 'If the content does not actually support the request, say so plainly rather than inventing findings.',+ ].join('\n');+}++// ─── Job orchestration ─────────────────────────────────────────────────────++// jobId -> { id, clients, lastPayload, process, canceled }+const ingestJobs = new Map();++export const attachIngestSseClient = (jobId, res) => attachSse(ingestJobs, jobId, res);++/**+ * Cancel an in-flight ingest. Returns false if the job is unknown or finished.+ *+ * The `canceled` flag matters independently of the child kill: an ingest is a+ * chain of steps, so cancelling between two of them (or during the non-spawn+ * persist phase) has no process to signal and is caught by the flag instead.+ */+export function cancelYoutubeIngest(jobId) {+ const job = ingestJobs.get(jobId);+ if (!job) return false;+ job.canceled = true;+ const proc = job.process;+ if (proc) {+ killWithEscalation(proc, { label: 'yt-dlp ingest', stillRunning: () => job.process === proc });+ }+ return true;+}++/**+ * Kick off an ingest. Returns `{ jobId, videoId }` immediately; the work runs+ * detached and streams progress over SSE. Terminal frames:+ * `{ type: 'complete', ingest }`, `{ type: 'error', error }`, `{ type: 'canceled' }`.+ *+ * @param {object} opts+ * @param {string} opts.url+ * @param {boolean} [opts.captureTranscript=true]+ * @param {boolean} [opts.downloadVideo=false]+ * @param {boolean} [opts.ingestAudio=false]+ * @param {string} [opts.agentPrompt] Non-empty → queue a CoS task pointed at the transcript.+ * @param {string[]} [opts.tags]+ * @param {string} [opts.priority] CoS task priority (defaults to the setting).+ */+export async function startYoutubeIngest({+ url,+ captureTranscript = true,+ downloadVideo = false,+ ingestAudio = false,+ agentPrompt = '',+ tags = [],+ priority,+} = {}) {+ const videoId = assertYoutubeIngestUrl(url);+ if (!captureTranscript && !downloadVideo && !ingestAudio) {+ throw new ServerError('Pick at least one of: transcript, video, audio', {+ status: 400,+ code: 'NOTHING_TO_INGEST',+ });+ }++ const ytDlp = await findYtDlp();+ if (!ytDlp) throw new ServerError('yt-dlp not found on PATH', { status: 500, code: 'YTDLP_MISSING' });+ // ffmpeg is only needed to merge video / transcode audio — a transcript-only+ // ingest must not fail on a machine that has yt-dlp but no ffmpeg.+ const ffmpeg = (downloadVideo || ingestAudio) ? await findFfmpeg() : null;+ if ((downloadVideo || ingestAudio) && !ffmpeg) {+ throw new ServerError('ffmpeg not found on PATH', { status: 500, code: 'FFMPEG_MISSING' });+ }++ const jobId = randomUUID();+ const job = { id: jobId, clients: [], process: null, canceled: false };+ ingestJobs.set(jobId, job);+ const cleanTags = tags.map((t) => String(t).trim()).filter(Boolean);+ const prompt = String(agentPrompt || '').trim();+ console.log(`📺 YouTube ingest ${shortId(jobId)} — ${videoId} (transcript=${captureTranscript} video=${downloadVideo} audio=${ingestAudio})`);++ (async () => {+ const registerProcess = (proc) => { job.process = proc; };+ const stage = (name, percent) => broadcastSse(job, { type: 'progress', stage: name, ...(percent != null ? { percent } : {}) });+ // Non-fatal outcomes the user still needs told about (no captions, duplicate+ // task). Broadcast live AND replayed on the terminal frame — a client using+ // the generic single-slot SSE hook only reads the terminal payload, so a+ // warning-only frame would otherwise vanish.+ const warnings = [];+ const warn = (message) => {+ warnings.push(message);+ broadcastSse(job, { type: 'warning', message });+ };+ // One timestamp for the whole ingest. Taken up front so the note's+ // `captured:` frontmatter, the note's filename date, and the activity+ // event's `happenedAt` can't disagree — an ingest that downloads a 3-hour+ // video legitimately crosses midnight.+ const capturedAt = new Date().toISOString();+ // Read once: the vault/folder decision and the CoS task priority both come+ // from here, and an ingest should use one settings snapshot throughout.+ const settings = await getSettings();+ // A dedicated per-job temp dir rather than a shared-prefix scan of+ // os.tmpdir() (which routinely holds thousands of entries on macOS): the+ // captions are found with a 2-entry readdir and removed with one rm.+ const subsDir = captureTranscript ? join(tmpdir(), `portos-yt-subs-${jobId}`) : null;++ try {+ await ensureDir(INGEST_DIR);+ if (subsDir) await ensureDir(subsDir);++ // Metadata AND captions come back from a single yt-dlp extraction.+ stage(captureTranscript ? 'transcript' : 'metadata');+ const meta = await fetchVideoInfo(ytDlp, url, registerProcess, { subsDir });+ // yt-dlp's own id is authoritative; ours is a URL-shape guess.+ meta.videoId = meta.videoId || videoId;+ broadcastSse(job, { type: 'metadata', title: meta.title, channel: meta.channel, durationSec: meta.durationSec });+ if (job.canceled) throw new Error('canceled');++ // ── Transcript ──+ // Written AND mirrored before the media downloads: the note doesn't depend+ // on them, and doing it here lets the caption text (up to a few hundred KB)+ // be collected before a multi-GB video download rather than being pinned in+ // this closure across it.+ let transcriptMeta = null;+ let transcriptPath = null;+ let obsidianLocation = null;+ if (captureTranscript) {+ const transcript = await readTranscriptFrom(subsDir, { hasManualCaptions: meta.hasManualCaptions });+ if (transcript) {+ const markdown = buildIngestNote({ meta, url, transcript, tags: cleanTags, agentPrompt: prompt, capturedAt });+ transcriptPath = join(INGEST_DIR, `${meta.videoId}.md`);+ await atomicWrite(transcriptPath, markdown);+ transcriptMeta = {+ path: transcriptPath,+ language: transcript.language,+ source: transcript.source,+ chars: transcript.text.length,+ };++ if (settings.autoSync) {+ const vaultId = await resolveVaultId(settings);+ const notePath = vaultId ? buildNotePath(settings, meta, capturedAt) : null;+ // Best-effort: the transcript is already stored locally, so a vault+ // on an unplugged drive must not fail the ingest.+ const written = notePath+ ? await obsidian.upsertNote(vaultId, notePath, markdown)+ .catch((err) => { console.error(`📓 Obsidian sync failed for ${meta.videoId}: ${err.message}`); return null; })+ : null;+ if (written) obsidianLocation = { path: written, vaultId };+ }+ } else {+ // Not fatal — the user still gets the link record, the activity event,+ // and whatever media they asked for. Say so explicitly rather than+ // completing with a silently empty transcript.+ warn('No captions were available for this video');+ }+ }++ // ── Video ──+ let video = null;+ if (downloadVideo) {+ stage('video', 0);+ // Same call the Dev Tools downloader makes, so the video lands in the+ // media library identically — history entry, thumbnail, index event and+ // partial-file cleanup all included.+ const result = await downloadVideoIntoLibrary({+ url,+ ytDlp,+ ffmpeg,+ maxBytes: INGEST_VIDEO_MAX_BYTES,+ maxDurationSec: INGEST_MAX_DURATION_SEC,+ onProgress: ({ percent, stage: s }) => broadcastSse(job, { type: 'progress', stage: s || 'video', percent }),+ registerProcess,+ });+ if (result.outcome === 'canceled' || job.canceled) throw new Error('canceled');+ if (result.outcome === 'failed') throw new Error(`video download failed — ${result.reason}`);+ video = { historyId: result.entry.id, filename: result.entry.filename };+ }++ // ── Audio ──+ let audio = null;+ if (ingestAudio) {+ stage('audio', 0);+ const tempPrefix = `portos-yt-ingest-${jobId}`;+ const result = await downloadAudioToTempMp3({+ url,+ ytDlp,+ ffmpeg,+ tempPrefix,+ maxBytes: INGEST_AUDIO_MAX_BYTES,+ maxDurationSec: INGEST_MAX_DURATION_SEC,+ onProgress: ({ percent, stage: s }) => broadcastSse(job, { type: 'progress', stage: s || 'audio', percent }),+ registerProcess,+ });+ if (result.outcome === 'canceled' || job.canceled) throw new Error('canceled');+ if (result.outcome === 'failed') throw new Error(`audio download failed — ${result.reason}`);+ // Kept next to the transcript rather than pushed into the music library:+ // a two-hour talk is reference material, not a track.+ const audioPath = join(INGEST_DIR, `${meta.videoId}.mp3`);+ await rename(result.outPath, audioPath);+ const bytes = await stat(audioPath).then((s) => s.size).catch(() => null);+ audio = { path: audioPath, bytes };+ }++ // ── Persist the "I consumed and kept this" artifacts ──+ stage('saving');++ // The federated record of "saved for future reference". Re-ingesting a+ // video reuses the existing link instead of forking a duplicate.+ const existingLink = await brainStorage.getLinkByUrl(url).catch(() => null);+ const link = existingLink || await createLinkFromUrl(url, {+ title: meta.title,+ description: [meta.channel, formatDuration(meta.durationSec)].filter(Boolean).join(' · '),+ linkType: 'reference',+ tags: ['youtube', ...cleanTags],+ autoClone: false,+ });++ // Machine-local consumption log, so the video shows on the Timeline next+ // to passively-synced watch history. Best-effort: a DB hiccup must not+ // fail an ingest whose files are already on disk. The `ingest:` dedupe+ // prefix keeps this distinct from youtubeSync's watch-history rows.+ await recordEvents([{+ source: 'youtube',+ kind: 'media.watch',+ happenedAt: capturedAt,+ durationS: meta.durationSec,+ title: meta.title,+ summary: meta.channel,+ url,+ dedupeKey: `ingest:${meta.videoId}`,+ metadata: { videoId: meta.videoId, channel: meta.channel, ingest: true, tags: cleanTags },+ }]).catch((err) => console.error(`🗓️ Activity event failed for ${meta.videoId}: ${err.message}`));++ // ── Follow-up agent task ──+ let taskId = null;+ if (prompt) {+ stage('queueing');+ const task = await addTask({+ description: `Review ingested YouTube content: ${meta.title}`,+ context: buildAgentTaskContext({+ meta, url, agentPrompt: prompt, transcriptPath, notePath: obsidianLocation?.path, tags: cleanTags,+ hasTranscript: !!transcriptPath,+ }),+ priority: priority || settings.taskPriority,+ // Analysis + issue-filing, not a code change: no worktree, no PR.+ useWorktree: false,+ openPR: false,+ simplify: false,+ reviewLoop: false,+ }, 'user').catch((err) => {+ console.error(`❌ CoS task for ingest ${meta.videoId} failed: ${err.message}`);+ return null;+ });+ if (task?.duplicate) {+ warn('A review task for this video is already queued');+ }+ taskId = task?.id || null;+ }++ // Artifact keys are written only for the switches this run actually ran.+ // putIngest merges over any prior record, so re-ingesting a video for its+ // audio alone must not null out the transcript entry whose file is still+ // sitting on disk — absent means "this run didn't touch it", not "gone".+ // Within a switch that DID run, an explicit null is meaningful (transcript+ // requested but the video had no captions), so it is written.+ const record = await putIngest(meta.videoId, {+ url,+ title: meta.title,+ channel: meta.channel,+ channelUrl: meta.channelUrl,+ durationSec: meta.durationSec,+ publishedAt: meta.publishedAt,+ ...(captureTranscript ? { transcript: transcriptMeta, obsidian: obsidianLocation } : {}),+ ...(downloadVideo ? { video } : {}),+ ...(ingestAudio ? { audio } : {}),+ ...(prompt ? { taskId, agentPrompt: prompt } : {}),+ linkId: link?.id || null,+ tags: cleanTags,+ });++ console.log(`📺 YouTube ingest ${shortId(jobId)} complete — "${meta.title}"${taskId ? ` → task ${taskId}` : ''}`);+ broadcastSse(job, { type: 'complete', ingest: record, warnings });+ } catch (err) {+ const message = err?.message || String(err);+ if (message === 'canceled' || job.canceled) {+ console.log(`🛑 YouTube ingest ${shortId(jobId)} cancelled`);+ broadcastSse(job, { type: 'canceled' });+ } else {+ console.error(`❌ YouTube ingest ${shortId(jobId)} failed: ${message}`);+ broadcastSse(job, { type: 'error', error: message });+ }+ } finally {+ // One rm regardless of outcome — the caption files are scratch, and on+ // cancel/failure yt-dlp may have written some of them.+ if (subsDir) await rm(subsDir, { recursive: true, force: true }).catch(() => {});+ closeJobAfterDelay(ingestJobs, jobId);+ }+ })();++ return { jobId, videoId };+}diff --git a/server/services/youtubeIngest.test.js b/server/services/youtubeIngest.test.jsnew file mode 100644index 0000000000..af8226bc99--- /dev/null+++ b/server/services/youtubeIngest.test.js@@ -0,0 +1,181 @@+import { describe, it, expect, vi } from 'vitest';++// The ingest module pulls in the brain/cos/media graphs at import time for its+// spawn path; the pure helpers under test need none of it. Stub the heavy edges+// so this suite exercises the parsing/rendering contracts without a live store.+vi.mock('./brain.js', () => ({ createLinkFromUrl: vi.fn() }));+vi.mock('./brainStorage.js', () => ({ getLinkByUrl: vi.fn() }));+vi.mock('./brainJournal.js', () => ({ getSettings: vi.fn(async () => ({ obsidianVaultId: null })) }));+vi.mock('./cosTaskStore.js', () => ({ addTask: vi.fn() }));+vi.mock('./humanActivity.js', () => ({ recordEvents: vi.fn() }));+vi.mock('./videoGen/history.js', () => ({ mutateVideoHistory: vi.fn() }));+vi.mock('./videoGen/events.js', () => ({ videoGenEvents: { emit: vi.fn() } }));+vi.mock('./videoDownload.js', () => ({ buildDownloadHistoryEntry: vi.fn() }));++import {+ YOUTUBE_INGEST_URL_RE,+ assertYoutubeIngestUrl,+ parseVideoMetadata,+ buildIngestNote,+ buildAgentTaskContext,+} from './youtubeIngest.js';++const META = {+ videoId: 'oCnxnaVg0bY',+ title: 'A talk about "writing tools"',+ channel: 'Example Channel',+ durationSec: 3723,+ publishedAt: '2026-01-15',+ description: 'Some description.',+};++describe('YouTube ingest URL allowlist', () => {+ it('accepts every single-video URL shape', () => {+ for (const url of [+ 'https://youtu.be/oCnxnaVg0bY',+ 'https://www.youtube.com/watch?v=oCnxnaVg0bY',+ 'https://m.youtube.com/watch?v=oCnxnaVg0bY&t=42s',+ 'https://music.youtube.com/watch?v=oCnxnaVg0bY',+ 'https://youtube.com/shorts/oCnxnaVg0bY',+ 'https://www.youtube.com/live/oCnxnaVg0bY',+ 'https://www.youtube.com/embed/oCnxnaVg0bY',+ ]) {+ expect(YOUTUBE_INGEST_URL_RE.test(url)).toBe(true);+ expect(() => assertYoutubeIngestUrl(url)).not.toThrow();+ }+ });++ it('rejects playlists, channels, handles, and non-YouTube URLs', () => {+ for (const url of [+ 'https://www.youtube.com/playlist?list=PLabcdefghij',+ 'https://www.youtube.com/@somechannel',+ 'https://www.youtube.com/c/somechannel',+ 'https://vimeo.com/123456789',+ 'https://x.com/someone/status/123',+ 'not a url',+ ]) {+ expect(() => assertYoutubeIngestUrl(url)).toThrow(/single-video YouTube URL/);+ }+ });+});++describe('parseVideoMetadata', () => {+ it('normalizes the fields the ingest stores', () => {+ const meta = parseVideoMetadata(JSON.stringify({+ id: 'oCnxnaVg0bY',+ title: ' Some Talk ',+ channel: 'Example Channel',+ channel_url: 'https://youtube.com/@example',+ duration: 3723.4,+ upload_date: '20260115',+ description: ' body ',+ thumbnail: 'https://i.ytimg.com/x.jpg',+ subtitles: { en: [{ ext: 'vtt' }] },+ }));+ expect(meta).toEqual({+ videoId: 'oCnxnaVg0bY',+ title: 'Some Talk',+ channel: 'Example Channel',+ channelUrl: 'https://youtube.com/@example',+ durationSec: 3723,+ publishedAt: '2026-01-15',+ description: 'body',+ thumbnailUrl: 'https://i.ytimg.com/x.jpg',+ hasManualCaptions: true,+ });+ });++ it('reads manual-vs-auto captions from `subtitles`, not `automatic_captions`', () => {+ // The real shape for an auto-captioned upload (verified against+ // youtu.be/oCnxnaVg0bY): `subtitles` empty, `automatic_captions` populated.+ // Filenames can't distinguish the two — yt-dlp writes both as `<base>.en.vtt`.+ expect(parseVideoMetadata({ subtitles: {}, automatic_captions: { en: [{}], fr: [{}] } }).hasManualCaptions).toBe(false);+ expect(parseVideoMetadata({}).hasManualCaptions).toBe(false);+ });++ it('falls back to uploader fields and tolerates missing/odd values', () => {+ const meta = parseVideoMetadata({ uploader: 'Someone', uploader_url: 'u', duration: 0, upload_date: 'nope' });+ expect(meta.channel).toBe('Someone');+ expect(meta.channelUrl).toBe('u');+ // A zero/absent duration must be null, not 0 — `0` would render a bogus+ // "0:00" duration in the note frontmatter.+ expect(meta.durationSec).toBeNull();+ expect(meta.publishedAt).toBeNull();+ expect(meta.title).toBe('Untitled video');+ });+});++describe('buildIngestNote', () => {+ const note = buildIngestNote({+ meta: META,+ url: 'https://youtu.be/oCnxnaVg0bY',+ transcript: { text: 'Hello world.', language: 'en', source: 'captions' },+ tags: ['writing-tools'],+ agentPrompt: 'Review for feature ideas.',+ capturedAt: '2026-08-05T12:00:00.000Z',+ });++ it('emits parseable frontmatter with the source, duration, and tags', () => {+ expect(note.startsWith('---\n')).toBe(true);+ // Quotes inside a title must be escaped or the YAML block breaks.+ expect(note).toContain('title: "A talk about \\"writing tools\\""');+ expect(note).toContain('source: https://youtu.be/oCnxnaVg0bY');+ expect(note).toContain('duration: "1:02:03"');+ expect(note).toContain('published: 2026-01-15');+ expect(note).toContain('captured: 2026-08-05');+ expect(note).toContain('tags: [youtube, consumed, portos, writing-tools]');+ });++ it('carries the transcript, description, and the "why I kept this" callout', () => {+ expect(note).toContain('## Transcript\n\nHello world.');+ expect(note).toContain('## Description');+ expect(note).toContain('> Review for feature ideas.');+ });++ it('says so explicitly when there were no captions', () => {+ const bare = buildIngestNote({+ meta: { ...META, description: '' },+ url: 'https://youtu.be/oCnxnaVg0bY',+ transcript: null,+ tags: [],+ agentPrompt: '',+ capturedAt: '2026-08-05T12:00:00.000Z',+ });+ expect(bare).toContain('_No captions were available for this video._');+ expect(bare).not.toContain('## Description');+ expect(bare).not.toContain('Why I kept this');+ });+});++describe('buildAgentTaskContext', () => {+ it('leads with the user request and points the agent at the transcript', () => {+ const context = buildAgentTaskContext({+ meta: META,+ url: 'https://youtu.be/oCnxnaVg0bY',+ agentPrompt: 'Review for writing-tool improvements.',+ transcriptPath: '/data/brain/youtube/oCnxnaVg0bY.md',+ notePath: 'Consumed/YouTube/note.md',+ tags: ['writing-tools'],+ hasTranscript: true,+ });+ expect(context).toContain('Review for writing-tool improvements.');+ expect(context).toContain('/data/brain/youtube/oCnxnaVg0bY.md');+ expect(context).toContain('Consumed/YouTube/note.md');+ expect(context).toContain('portos-file-issue');+ expect(context).toContain('**Duration:** 1:02:03');+ });++ it('tells the agent when no transcript exists rather than pointing at a missing file', () => {+ const context = buildAgentTaskContext({+ meta: META,+ url: 'https://youtu.be/oCnxnaVg0bY',+ agentPrompt: 'Do a thing.',+ transcriptPath: null,+ notePath: null,+ tags: [],+ hasTranscript: false,+ });+ expect(context).toContain('not available');+ expect(context).not.toContain('read this first');+ });+});diff --git a/server/services/ytdlpVideoImport.js b/server/services/ytdlpVideoImport.jsnew file mode 100644index 0000000000..498350bc04--- /dev/null+++ b/server/services/ytdlpVideoImport.js@@ -0,0 +1,184 @@+/**+ * Shared yt-dlp FULL-VIDEO download core.+ *+ * The mirror image of ytdlpAudioImport.js, extracted for the same reason: the+ * YouTube brain ingest (#3565) wants the exact video-download behavior the Dev+ * Tools downloader (#1946) already had — the format fallback chain, the merge/+ * remux flags, the `--progress-template` machine-readable markers, the+ * two-`--match-filters` duration bound, and the "find the produced file, because+ * the extension isn't knowable up front" logic — but as ONE step inside a larger+ * job rather than as its own SSE-owning service.+ *+ * Like the audio core, this is deliberately SSE-agnostic: it takes `onProgress`+ * and `registerProcess` callbacks and RETURNS an outcome. The caller owns the+ * job map, SSE broadcasting, terminal frames, and what happens to the produced+ * file. URL validation is the caller's job too, so the core never sees an+ * unvetted URL.+ */++import { spawn } from 'child_process';+import { readdir, unlink } from 'fs/promises';+import { join, dirname } from 'path';+import { ensureDir } from '../lib/fileUtils.js';+import { safeChildProcessEnv } from '../lib/processEnv.js';+import { createLineReader } from '../lib/streamLines.js';++const TITLE_PREFIX = 'PORTOS_TITLE:';+// Machine-readable progress markers via yt-dlp's --progress-template rather than+// scraping human-readable console lines — same rationale as ytdlpAudioImport.+const PROGRESS_PREFIX = 'PORTOS_PROGRESS:';+const STAGE_PREFIX = 'PORTOS_STAGE:';++/**+ * Locate the final produced file for a download prefix. yt-dlp writes+ * intermediate streams as `<prefix>.f<code>.<ext>` and a `.part`/`.ytdl` in+ * progress, then merges/remuxes to a single `<prefix>.<ext>` and deletes the+ * rest. We do NOT hardcode `.mp4`: the format fallback chain can land a+ * single-file webm/mkv (VP9/AV1) that `--merge-output-format`/`--remux-video+ * mp4` only converts on a best-effort basis, so assuming `.mp4` would miss a+ * perfectly-good download and then delete it as a "failure". Prefer an exact+ * `.mp4`, else the lone remaining non-intermediate file.+ *+ * @returns {Promise<string|null>} basename, or null when nothing was produced.+ */+export async function findProducedFile(filePrefix, dir) {+ const prefix = `${filePrefix}.`;+ const entries = await readdir(dir).catch(() => []);+ const candidates = entries.filter((n) =>+ n.startsWith(prefix)+ && !n.endsWith('.part')+ && !n.endsWith('.ytdl')+ && !/\.f\d+\.[^.]+$/.test(n), // format-fragment intermediates (.f137.mp4)+ );+ return candidates.find((n) => n === `${prefix}mp4`) || candidates[0] || null;+}++/**+ * A cancelled/failed run can leave yt-dlp's pre-merge fragment files behind+ * (`<prefix>.f137.mp4`, `.part`, etc.), so cleanup globs every file this+ * prefix touched rather than unlinking one assumed path.+ */+export async function cleanupProducedFiles(filePrefix, dir) {+ const entries = await readdir(dir).catch(() => []);+ await Promise.all(+ entries.filter((name) => name.startsWith(filePrefix)).map((name) => unlink(join(dir, name)).catch(() => {})),+ );+}++/**+ * Download a full video (best mp4 video+audio, merged) into `outDir`.+ *+ * @param {object} opts+ * @param {string} opts.url Already-validated source URL.+ * @param {string} opts.ytDlp yt-dlp binary path.+ * @param {string} opts.ffmpeg ffmpeg binary path (for merge/remux).+ * @param {string} opts.outDir Destination directory (created if missing).+ * @param {string} opts.filePrefix Unique per-job basename prefix (no extension).+ * @param {number} opts.maxBytes `--max-filesize` cap.+ * @param {number} opts.maxDurationSec `--match-filters duration<=` cap.+ * @param {function} opts.onProgress ({ percent, stage }) => void — SSE-agnostic.+ * @param {function} opts.registerProcess (proc|null) => void — lets the caller wire cancel.+ * @returns {Promise<{ outcome:'complete'|'canceled'|'failed', filename?:string, title?:string, reason?:string }>}+ *+ * Never throws for a yt-dlp runtime failure (returns `failed` + `reason`); the+ * caller decides how to surface it. Cleans partial files on `canceled`/`failed`;+ * on `complete` the caller owns the produced file.+ */+export async function downloadVideoToDir({+ url, ytDlp, ffmpeg, outDir, filePrefix, maxBytes, maxDurationSec, onProgress, registerProcess,+}) {+ // On a fresh install the destination may not exist yet (setup-data.js doesn't+ // create data/videos, and no prior render/import may have); without this+ // yt-dlp points at a missing directory and fails before producing a file.+ await ensureDir(outDir);++ let title = '';+ const args = [+ // Prefer an mp4 (h264/aac) video+audio pair that merges cleanly for broad+ // browser playback; fall back to best single-file mp4, then best.+ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best',+ '--merge-output-format', 'mp4',+ // Best-effort remux a single-file/non-mp4 result into an mp4 container so+ // browser playback is broad; when the codec can't be remuxed losslessly+ // yt-dlp leaves the native container, which findProducedFile handles.+ '--remux-video', 'mp4',+ '--no-playlist',+ '--ffmpeg-location', dirname(ffmpeg),+ '--newline',+ '--print', `${TITLE_PREFIX}%(title)s`,+ '--progress-template', `download:${PROGRESS_PREFIX}%(progress._percent_str)s`,+ '--progress-template', `postprocess:${STAGE_PREFIX}merging`,+ // --print implies --simulate AND suppresses normal progress reporting;+ // --no-simulate + --progress restore the real run + machine markers+ // (the yt-dlp quirk documented at length in ytdlpAudioImport).+ '--no-simulate',+ '--progress',+ '--max-filesize', String(maxBytes),+ // Two --match-filters are OR'd by yt-dlp: bound KNOWN-duration videos to the+ // cap, but let a post whose duration can't be resolved pre-download (common+ // on x.com/Twitter) through rather than silently rejecting it — the byte cap+ // above still bounds it. A known video longer than the cap matches neither+ // filter and is skipped.+ '--match-filters', `duration <= ${maxDurationSec}`,+ '--match-filters', '!duration',+ '-o', join(outDir, `${filePrefix}.%(ext)s`),+ url,+ ];++ const proc = spawn(ytDlp, args, { env: safeChildProcessEnv(), stdio: ['ignore', 'pipe', 'pipe'] });+ registerProcess(proc);++ const onLine = (line) => {+ if (line.startsWith(TITLE_PREFIX)) {+ title = line.slice(TITLE_PREFIX.length).trim();+ return;+ }+ if (line.startsWith(PROGRESS_PREFIX)) {+ const percent = parseFloat(line.slice(PROGRESS_PREFIX.length));+ if (Number.isFinite(percent)) onProgress({ percent });+ return;+ }+ if (line.startsWith(STAGE_PREFIX)) {+ onProgress({ percent: 100, stage: line.slice(STAGE_PREFIX.length) });+ }+ };+ // Separate readers per stream — stdout and stderr chunks arrive independently,+ // so a shared buffer can complete a partial line from one stream with a chunk+ // from the other, corrupting a marker line.+ const stdoutReader = createLineReader(onLine);+ const stderrReader = createLineReader(onLine);+ proc.stdout.on('data', stdoutReader.push);+ proc.stderr.on('data', stderrReader.push); // yt-dlp writes some progress/info lines to stderr too++ const exit = await new Promise((resolve) => {+ proc.on('error', (err) => resolve({ code: null, reason: `spawn failed: ${err.message}` }));+ proc.on('close', (code, signal) => resolve({ code, signal }));+ });+ registerProcess(null);++ if (exit.signal === 'SIGTERM' || exit.signal === 'SIGKILL') {+ // Don't flush on cancel — a SIGKILL'd child leaves only a partial marker+ // line in the carry, and emitting it would fire a stray progress/stage+ // callback right before the caller reports the cancellation.+ await cleanupProducedFiles(filePrefix, outDir);+ return { outcome: 'canceled' };+ }+ // Flush any final line the child wrote without a trailing newline before exit.+ stdoutReader.flush();+ stderrReader.flush();++ const filename = await findProducedFile(filePrefix, outDir);+ if (exit.code !== 0 || !filename) {+ // A --match-filters/--max-filesize rejection exits 0 with no output file+ // (yt-dlp treats a filtered-out video as "nothing to do") — and --print+ // suppresses the specific reason, so name the known bounds. x.com/Twitter+ // downloads also fail here on login-walled/rate-limited content.+ const reason = exit.code === 0+ ? `no video was produced — it may be longer than ${Math.round(maxDurationSec / 60)} minutes or larger than ${Math.round(maxBytes / 1024 / 1024 / 1024)}GB, or (for x.com) login-walled, rate-limited, or otherwise unavailable`+ : (exit.reason || `yt-dlp exited ${exit.code}`);+ await cleanupProducedFiles(filePrefix, outDir);+ return { outcome: 'failed', reason };+ }++ return { outcome: 'complete', filename, title };+}diff --git a/server/services/ytdlpVideoImport.test.js b/server/services/ytdlpVideoImport.test.jsnew file mode 100644index 0000000000..293611c7f0--- /dev/null+++ b/server/services/ytdlpVideoImport.test.js@@ -0,0 +1,64 @@+/**+ * The shared yt-dlp video core's output detection.+ *+ * These cases moved here from videoDownload.test.js when the yt-dlp spawn was+ * extracted for the YouTube brain ingest: the "don't assume .mp4, don't pick up+ * an intermediate" rule is a property of the core both callers use, not of the+ * Dev Tools downloader that used to own it.+ */++import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtemp, writeFile, rm } from 'fs/promises';+import { join } from 'path';+import { tmpdir } from 'os';+import { findProducedFile, cleanupProducedFiles } from './ytdlpVideoImport.js';++describe('findProducedFile (robust output detection)', () => {+ let dir;+ beforeEach(async () => { dir = await mkdtemp(join(tmpdir(), 'viddl-')); });+ afterEach(async () => { await rm(dir, { recursive: true, force: true }); });++ it('prefers an exact .mp4 over other candidates', async () => {+ await writeFile(join(dir, 'downloaded-x.mp4'), 'v');+ await writeFile(join(dir, 'downloaded-x.webm'), 'v');+ expect(await findProducedFile('downloaded-x', dir)).toBe('downloaded-x.mp4');+ });++ it('finds a non-mp4 single-file result (the .mp4-assumption bug)', async () => {+ await writeFile(join(dir, 'downloaded-y.webm'), 'v');+ expect(await findProducedFile('downloaded-y', dir)).toBe('downloaded-y.webm');+ });++ it('ignores in-progress and format-fragment intermediates', async () => {+ await writeFile(join(dir, 'downloaded-z.f137.mp4'), 'v'); // fragment+ await writeFile(join(dir, 'downloaded-z.mp4.part'), 'v'); // partial+ await writeFile(join(dir, 'downloaded-z.webm.ytdl'), 'v'); // sidecar+ expect(await findProducedFile('downloaded-z', dir)).toBeNull();+ });++ it('does not match a different job id', async () => {+ await writeFile(join(dir, 'downloaded-other.mp4'), 'v');+ expect(await findProducedFile('downloaded-mine', dir)).toBeNull();+ });++ it('returns null for a directory that does not exist', async () => {+ expect(await findProducedFile('downloaded-x', join(dir, 'nope'))).toBeNull();+ });+});++describe('cleanupProducedFiles', () => {+ let dir;+ beforeEach(async () => { dir = await mkdtemp(join(tmpdir(), 'viddl-clean-')); });+ afterEach(async () => { await rm(dir, { recursive: true, force: true }); });++ it('removes every file the prefix touched, including intermediates, and spares others', async () => {+ for (const name of ['downloaded-a.mp4', 'downloaded-a.f137.mp4', 'downloaded-a.mp4.part', 'downloaded-b.mp4']) {+ await writeFile(join(dir, name), 'v');+ }+ await cleanupProducedFiles('downloaded-a', dir);+ // The whole point of globbing the prefix: a cancelled run leaves fragments+ // whose exact names aren't knowable up front.+ expect(await findProducedFile('downloaded-a', dir)).toBeNull();+ expect(await findProducedFile('downloaded-b', dir)).toBe('downloaded-b.mp4');+ });+});