Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: add explicit IdeaLoom Obsidian exchange (#5338)
[._.]/ Adam Eivyab3427e6b601
diff --git a/client/src/components/brain/IdeaLoomLists.jsx b/client/src/components/brain/IdeaLoomLists.jsxindex 746e7443f4..5e6835e614 100644--- a/client/src/components/brain/IdeaLoomLists.jsx+++ b/client/src/components/brain/IdeaLoomLists.jsx@@ -1,5 +1,5 @@import { useCallback, useEffect, useMemo, useState } from 'react';-import { ArrowDown, ArrowUp, CheckCircle2, Plus, Save, Trash2, X } from 'lucide-react';+import { ArrowDown, ArrowUp, CheckCircle2, Download, Plus, Save, Trash2, Upload, X } from 'lucide-react';import * as api from '../../services/api';import toast from '../ui/Toast';import InlineConfirmRow from '../ui/InlineConfirmRow';@@ -49,6 +49,8 @@ export default function IdeaLoomLists() {const [loading, setLoading] = useState(true);const [draft, setDraft] = useState(null);const [ideaText, setIdeaText] = useState('');+ const [exchangeBusy, setExchangeBusy] = useState(false);+ const [exchangeResult, setExchangeResult] = useState(null);const { isConfirming, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();const select = useCallback((id) => updateParams({ list: id }), [updateParams]);@@ -126,6 +128,20 @@ export default function IdeaLoomLists() {setIdeaText('');};+ const runExchange = async (action, successMessage) => {+ setExchangeBusy(true);+ const result = await action().catch((error) => {+ toast.error(error.message || 'IdeaLoom exchange failed');+ return null;+ });+ setExchangeBusy(false);+ if (!result) return;+ const counts = result.counts || result;+ setExchangeResult(counts);+ toast.success(successMessage);+ await load();+ };+if (loading) return <p className="py-8 text-center text-gray-500">Loading IdeaLoom lists…</p>;return (@@ -136,6 +152,11 @@ export default function IdeaLoomLists() {<button type="button" onClick={() => { setDraft(emptyList()); select(null); }} className="min-h-[44px] rounded px-3 text-sm text-port-accent hover:bg-port-accent/10" aria-label="Create IdeaLoom list"><Plus size={16} /></button></div>{notice && <p role="status" className="mb-3 rounded bg-port-warning/10 p-2 text-xs text-port-warning">{notice}</p>}+ {!notice && <div className="mb-3 flex flex-wrap gap-2">+ <button type="button" disabled={exchangeBusy} onClick={() => runExchange(() => api.importIdeaLoomFromObsidian({ silent: true }), 'IdeaLoom import complete')} className="flex min-h-[44px] items-center gap-2 rounded border border-port-border px-3 text-xs text-gray-300 hover:bg-port-border/50 disabled:opacity-50"><Upload size={14} />Import from Obsidian</button>+ <button type="button" disabled={exchangeBusy} onClick={() => runExchange(() => api.syncIdeaLoomToObsidian(null, { silent: true }), 'IdeaLoom export complete')} className="flex min-h-[44px] items-center gap-2 rounded border border-port-border px-3 text-xs text-gray-300 hover:bg-port-border/50 disabled:opacity-50"><Download size={14} />Export to Obsidian</button>+ </div>}+ {exchangeResult && <p role="status" className="mb-3 text-xs text-gray-400">Last exchange: {exchangeResult.imported || 0} imported · {exchangeResult.exported || 0} exported · {exchangeResult.skipped || 0} skipped · {exchangeResult.malformed || 0} malformed · {exchangeResult.unavailable || 0} unavailable · {exchangeResult.failed || 0} failed</p>}<div className="space-y-1">{lists.map((list) => <button key={list.id} type="button" onClick={() => select(list.id)} className={`w-full rounded p-3 text-left ${selected?.id === list.id ? 'bg-port-accent/20 text-white' : 'text-gray-300 hover:bg-port-border/50'}`}><span className="block truncate text-sm font-medium">{list.title}</span><span className="text-xs text-gray-500">{list.status === 'completed' ? 'Completed' : 'Draft'} · {(list.ideas || []).length} ideas</span>diff --git a/client/src/components/brain/IdeaLoomLists.test.jsx b/client/src/components/brain/IdeaLoomLists.test.jsxindex e3294631d5..426eff0bc8 100644--- a/client/src/components/brain/IdeaLoomLists.test.jsx+++ b/client/src/components/brain/IdeaLoomLists.test.jsx@@ -5,6 +5,7 @@ import { MemoryRouter, useLocation } from 'react-router';vi.mock('../../services/api', () => ({getIdeaLoomLists: vi.fn(), getIdeaLoomSettings: vi.fn(),createIdeaLoomList: vi.fn(), updateIdeaLoomList: vi.fn(), deleteIdeaLoomList: vi.fn(),+ importIdeaLoomFromObsidian: vi.fn(), syncIdeaLoomToObsidian: vi.fn(),}));vi.mock('../ui/Toast', () => ({ default: { error: vi.fn(), success: vi.fn() } }));@@ -75,6 +76,17 @@ describe('IdeaLoomLists', () => {expect(await screen.findByLabelText('Idea 1')).toBeTruthy();});+ it('offers explicit exchange controls only for a configured vault', async () => {+ api.getIdeaLoomSettings.mockResolvedValue({ enabled: true, obsidianVaultId: 'vault-1', autoSync: false });+ api.getIdeaLoomLists.mockResolvedValue([storedList()]);+ api.syncIdeaLoomToObsidian.mockResolvedValue({ counts: { exported: 1, skipped: 0 } });+ renderPanel();++ fireEvent.click(await screen.findByRole('button', { name: 'Export to Obsidian' }));+ await waitFor(() => expect(api.syncIdeaLoomToObsidian).toHaveBeenCalledWith(null, { silent: true }));+ expect(await screen.findByText(/Last exchange: 0 imported · 1 exported/)).toBeTruthy();+ });+it('does not report an unread settings fetch as a disabled integration', async () => {api.getIdeaLoomSettings.mockRejectedValue(new Error('Server unreachable'));renderPanel();diff --git a/client/src/services/apiBrain.js b/client/src/services/apiBrain.jsindex 94597cc55e..6eb8301e17 100644--- a/client/src/services/apiBrain.js+++ b/client/src/services/apiBrain.js@@ -129,6 +129,12 @@ export const updateIdeaLoomList = (id, data, options = {}) => request(`/brain/idexport const deleteIdeaLoomList = (id, options = {}) => request(`/brain/ideas/idealoom/lists/${id}`, {method: 'DELETE', ...options});+export const importIdeaLoomFromObsidian = (options = {}) => request('/brain/ideas/idealoom/import', {+ method: 'POST', body: JSON.stringify({}), ...options+});+export const syncIdeaLoomToObsidian = (listId, options = {}) => request('/brain/ideas/idealoom/sync', {+ method: 'POST', body: JSON.stringify(listId ? { listId } : {}), ...options+});// Brain - Adminexport const getBrainAdmin = (filters) => {diff --git a/docs/API.md b/docs/API.mdindex b5041bc26a..34e5bf096b 100644--- a/docs/API.md+++ b/docs/API.md@@ -347,6 +347,8 @@ Context tools remain read-only. Semantic reads and writes are independent, defau| GET/PUT | `/brain/ideas/idealoom/settings` | Get or update local IdeaLoom integration settings (disabled by default) || GET/POST | `/brain/ideas/idealoom/lists` | List or create machine-local IdeaLoom lists || GET/PUT/DELETE | `/brain/ideas/idealoom/lists/:id` | Read, update, or delete a machine-local IdeaLoom list |+| POST | `/brain/ideas/idealoom/import` | Explicitly import valid IdeaLoom Markdown from the configured Obsidian vault |+| POST | `/brain/ideas/idealoom/sync` | Explicitly export all lists, or one list, to the configured Obsidian vault || GET | `/brain/admin` | List admin tasks || POST | `/brain/admin` | Create admin task || GET | `/brain/admin/:id` | Get admin task |diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 44c4f3412e..256d731559 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -61,7 +61,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](- 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`.-- IdeaLoom lists — `data/brain/idealoom-lists/{uuid}/index.json` with a schema-stamped collection index holding the disabled-by-default local integration settings. Lists retain their ordered idea strings, prompt/title/category/status/help, timestamps, and importer-owned local sync metadata. **Intentionally machine-local — never federated, reconciled, or memory-bridged**: a vault id, note path, and content hash are meaningful only on the install that configured them. Native Brain `ideas` remain a separate federated collection. Adapter: `server/services/idealoomLists.js`.+- IdeaLoom lists — `data/brain/idealoom-lists/{uuid}/index.json` with a schema-stamped collection index holding the disabled-by-default local integration settings. Lists retain their ordered idea strings, prompt/title/category/status/help, timestamps, and importer-owned local sync metadata. Explicit exchange reads/writes only the configured vault's `Idea Loom/` folder through the specialized `server/services/idealoomObsidian.js` parser/renderer; new notes use a date/title filename and imported note paths remain stable. **Intentionally machine-local — never federated, reconciled, or memory-bridged**: a vault id, note path, and content hash are meaningful only on the install that configured them. Native Brain `ideas` remain a separate federated collection. Adapter: `server/services/idealoomLists.js`.- Local-model assessments — `data/local-llm/assessments.json` (#4539). Measured evidence for one installed local model per (backend, model): the fit verdict (`fits`/`does-not-fit`/`incompatible`/`unknown`), per-context throughput/TTFT samples, resident footprint, and the coarse hardware environment the measurement was taken in. `file-primary` — a flat, capped, single-JSON projection with no cross-record queries and no relationships; the newest measurement replaces the old one per model rather than accumulating history. **Intentionally machine-local — never federated**: an assessment is a claim about THIS box, so a peer inheriting a 128 GB machine's its verdict for its 8 GB laptop would be actively wrong. No sync cursor, no tombstone, no `PORTOS_SCHEMA_VERSIONS` entry. Backed up (a run costs the user minutes of local compute), and the environment record deliberately carries no hostname/username/path. Adapter: `server/services/localModelAssessmentStore.js` (durable store + environment capture; no path to a provider, so read-only consumers like the catalog fit badge can import it); the run lives in `server/services/localModelAssessments.js` and the scoring in `server/lib/localModelAssessment.js`. Each record's environment is re-compared against the live machine on read, so a reading taken before a RAM upgrade or backend update is flagged stale rather than silently trusted.- 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 060e7036b5..c78f556f1c 100644--- a/docs/features/brain-system.md+++ b/docs/features/brain-system.md@@ -205,6 +205,29 @@ video/audio switches (a transcript-only ingest works without it).- **Digest**: Daily and weekly summaries with run buttons- **Trust**: Audit trail with classification confidence and reasoning+## IdeaLoom Obsidian exchange++The dedicated `/brain/ideas` page keeps native Brain ideas separate from+machine-local IdeaLoom lists. When the integration is enabled and an existing+Obsidian vault is selected, the page exposes explicit Import and Export actions.+Neither action runs during boot, and disabled or unconfigured integration does+not affect local list editing.++Import scans only the vault's `Idea Loom/` folder. A supported note has UUID,+title, category, draft/completed status, created/modified timestamps, an+IdeaLoom tag, a prompt heading, optional help text, and dense numbered idea+lines. Imports preserve the UUID, order, timestamps, and discovered note path;+malformed, duplicate, and iCloud-unavailable notes are reported in the result+instead of being silently accepted. Export writes the same frontmatter and+numbered Markdown shape, uses a date/title filename for new lists, and keeps an+imported filename stable.++The exchange result includes counts and per-note details for imported,+exported, skipped, malformed, unavailable, and failed work. List records and+vault identifiers remain under `data/brain/idealoom-lists/` and never enter+Brain federation or the memory bridge. Conflict-safe reconciliation and+automatic-sync behavior are intentionally handled by the follow-up sync slice.+## Implementation Files| File | Purpose |@@ -212,6 +235,8 @@ video/audio switches (a transcript-only ingest works without it).| `server/lib/brainValidation.js` | Zod schemas for all Brain entities || `server/services/brain.js` | Core business logic || `server/services/brainStorage.js` | JSONL/JSON file operations |+| `server/services/idealoomLists.js` | Machine-local ordered IdeaLoom list records and sync metadata |+| `server/services/idealoomObsidian.js` | Validated IdeaLoom Markdown import/export || `server/services/brainScheduler.js` | Daily/weekly job scheduler || `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) |diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.jsonindex 6482867cb9..a5d9a7251f 100644--- a/server/lib/apiRouteCatalog.generated.json+++ b/server/lib/apiRouteCatalog.generated.json@@ -2436,6 +2436,17 @@}]},+ {+ "method": "POST",+ "path": "/api/brain/ideas/idealoom/import",+ "mountPath": "/api/brain",+ "sources": [+ {+ "source": "server/routes/brainIdeaLoom.js",+ "line": 27+ }+ ]+ },{"method": "GET","path": "/api/brain/ideas/idealoom/lists",@@ -2443,7 +2454,7 @@"sources": [{"source": "server/routes/brainIdeaLoom.js",- "line": 21+ "line": 37}]},@@ -2454,7 +2465,7 @@"sources": [{"source": "server/routes/brainIdeaLoom.js",- "line": 25+ "line": 41}]},@@ -2465,7 +2476,7 @@"sources": [{"source": "server/routes/brainIdeaLoom.js",- "line": 43+ "line": 59}]},@@ -2476,7 +2487,7 @@"sources": [{"source": "server/routes/brainIdeaLoom.js",- "line": 30+ "line": 46}]},@@ -2487,7 +2498,7 @@"sources": [{"source": "server/routes/brainIdeaLoom.js",- "line": 36+ "line": 52}]},@@ -2498,7 +2509,7 @@"sources": [{"source": "server/routes/brainIdeaLoom.js",- "line": 12+ "line": 18}]},@@ -2509,7 +2520,18 @@"sources": [{"source": "server/routes/brainIdeaLoom.js",- "line": 16+ "line": 22+ }+ ]+ },+ {+ "method": "POST",+ "path": "/api/brain/ideas/idealoom/sync",+ "mountPath": "/api/brain",+ "sources": [+ {+ "source": "server/routes/brainIdeaLoom.js",+ "line": 32}]},@@ -23125,8 +23147,8 @@],"stats": {"mounts": 145,- "operations": 2086,- "declarations": 2089,+ "operations": 2088,+ "declarations": 2091,"sourceFiles": 225}}diff --git a/server/lib/brainValidation.js b/server/lib/brainValidation.jsindex 962f675af1..a4da407879 100644--- a/server/lib/brainValidation.js+++ b/server/lib/brainValidation.js@@ -298,6 +298,12 @@ export const ideaLoomSettingsInputSchema = z.object({autoSync: z.boolean().optional()}).strict();+export const ideaLoomImportInputSchema = z.preprocess((value) => value ?? {}, z.object({}).strict());++export const ideaLoomSyncInputSchema = z.preprocess((value) => value ?? {}, z.object({+ listId: z.string().uuid().optional()+}).strict());+// Create/Update Admin input schemaexport const adminInputSchema = z.object({title: z.string().min(1).max(200),diff --git a/server/routes/brain.test.js b/server/routes/brain.test.jsindex 86d26853f1..0c3aad9409 100644--- a/server/routes/brain.test.js+++ b/server/routes/brain.test.js@@ -88,6 +88,11 @@ vi.mock('../services/idealoomLists.js', () => ({deleteList: vi.fn()}));+vi.mock('../services/idealoomObsidian.js', () => ({+ importFromObsidian: vi.fn(),+ exportToObsidian: vi.fn(),+}));+// Mock the brain graph servicevi.mock('../services/brainGraph.js', () => ({getBrainGraphSearchIndex: vi.fn(),@@ -145,6 +150,7 @@ vi.mock('../services/brainJournal.js', () => ({// Import mocked modulesimport * as brainService from '../services/brain.js';import * as ideaLoomLists from '../services/idealoomLists.js';+import * as ideaLoomObsidian from '../services/idealoomObsidian.js';import { getBrainGraphSearchIndex, getBrainGraphOverview, getBrainGraphNeighborhood } from '../services/brainGraph.js';import { syncAllBrainData, getEmbeddingCoverage } from '../services/brainMemoryBridge.js';import { getChangesSince } from '../services/brainSyncLog.js';@@ -154,6 +160,7 @@ import * as journal from '../services/brainJournal.js';describe('Brain Routes', () => {let app;+ const LIST_ID = 'c17c0284-b7de-4db6-a09c-7f735f0fd501';beforeEach(() => {app = express();@@ -163,7 +170,6 @@ describe('Brain Routes', () => {});describe('IdeaLoom local lists', () => {- const LIST_ID = 'c17c0284-b7de-4db6-a09c-7f735f0fd501';const listInput = {prompt: 'Find practical improvements', title: 'Practical improvements',category: 'product', ideas: ['Improve empty states']@@ -233,6 +239,32 @@ describe('Brain Routes', () => {});});+ describe('IdeaLoom Obsidian exchange', () => {+ it('validates explicit import and export actions and returns their results', async () => {+ ideaLoomObsidian.importFromObsidian.mockResolvedValue({ counts: { imported: 1 } });+ ideaLoomObsidian.exportToObsidian.mockResolvedValue({ counts: { exported: 1 } });++ const imported = await request(app).post('/api/brain/ideas/idealoom/import').send({});+ expect(imported.status).toBe(200);+ expect(imported.body.counts.imported).toBe(1);+ expect(ideaLoomObsidian.importFromObsidian).toHaveBeenCalledOnce();++ const exported = await request(app)+ .post('/api/brain/ideas/idealoom/sync')+ .send({ listId: LIST_ID });+ expect(exported.status).toBe(200);+ expect(exported.body.counts.exported).toBe(1);+ expect(ideaLoomObsidian.exportToObsidian).toHaveBeenCalledWith({ listId: LIST_ID });+ });++ it('rejects unknown exchange request fields', async () => {+ expect((await request(app).post('/api/brain/ideas/idealoom/import').send({ force: true })).status).toBe(400);+ expect((await request(app).post('/api/brain/ideas/idealoom/sync').send({ direction: 'both' })).status).toBe(400);+ expect(ideaLoomObsidian.importFromObsidian).not.toHaveBeenCalled();+ expect(ideaLoomObsidian.exportToObsidian).not.toHaveBeenCalled();+ });+ });+// ===========================================================================// CAPTURE & INBOX// ===========================================================================diff --git a/server/routes/brainIdeaLoom.js b/server/routes/brainIdeaLoom.jsindex 8dc78ff316..2a922730eb 100644--- a/server/routes/brainIdeaLoom.js+++ b/server/routes/brainIdeaLoom.js@@ -4,8 +4,14 @@ import { Router } from 'express';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';import { partialWithoutDefaults } from '../lib/zodCompat.js';-import { ideaLoomListInputSchema, ideaLoomSettingsInputSchema } from '../lib/brainValidation.js';+import {+ ideaLoomImportInputSchema,+ ideaLoomListInputSchema,+ ideaLoomSettingsInputSchema,+ ideaLoomSyncInputSchema,+} from '../lib/brainValidation.js';import * as ideaLoomLists from '../services/idealoomLists.js';+import * as ideaLoomObsidian from '../services/idealoomObsidian.js';const router = Router();@@ -18,6 +24,16 @@ router.put('/ideas/idealoom/settings', asyncHandler(async (req, res) => {res.json(await ideaLoomLists.updateSettings(updates));}));+router.post('/ideas/idealoom/import', asyncHandler(async (req, res) => {+ validateRequest(ideaLoomImportInputSchema, req.body);+ res.json(await ideaLoomObsidian.importFromObsidian());+}));++router.post('/ideas/idealoom/sync', asyncHandler(async (req, res) => {+ const { listId } = validateRequest(ideaLoomSyncInputSchema, req.body);+ res.json(await ideaLoomObsidian.exportToObsidian({ listId }));+}));+router.get('/ideas/idealoom/lists', asyncHandler(async (_req, res) => {res.json(await ideaLoomLists.listLists());}));diff --git a/server/services/idealoomLists.js b/server/services/idealoomLists.jsindex 90e72782e6..22be0ab38d 100644--- a/server/services/idealoomLists.js+++ b/server/services/idealoomLists.js@@ -69,6 +69,43 @@ export async function createList(data) {return list;}+/**+ * Store a list read from an IdeaLoom note without minting a new id or+ * replacing the note's timestamps. Import metadata is owned by the exchange+ * service, so normal list edits cannot accidentally overwrite it.+ */+export async function upsertImportedList(id, data) {+ if (!store.isValidId(id)) return null;+ await store.saveTypeIndex();+ return store.queueRecordWrite(id, async () => {+ const current = await store.loadOne(id);+ const now = timestamp();+ const list = {+ ...(current || {}),+ ...data,+ id,+ schemaVersion: IDEALOOM_LIST_SCHEMA_VERSION,+ sync: data.sync ?? current?.sync,+ createdAt: data.createdAt ?? current?.createdAt ?? now,+ updatedAt: data.updatedAt ?? current?.updatedAt ?? now,+ };+ await store.saveOneNow(id, list);+ return list;+ });+}++/** Update importer-owned local metadata without changing list content. */+export async function updateSyncMetadata(id, sync) {+ if (!store.isValidId(id)) return null;+ return store.queueRecordWrite(id, async () => {+ const current = await store.loadOne(id);+ if (!current) return null;+ const list = { ...current, sync: { ...(current.sync || {}), ...sync } };+ await store.saveOneNow(id, list);+ return list;+ });+}+export async function updateList(id, updates) {if (!store.isValidId(id)) return null;return store.queueRecordWrite(id, async () => {diff --git a/server/services/idealoomObsidian.js b/server/services/idealoomObsidian.jsnew file mode 100644index 0000000000..d8eab7956d--- /dev/null+++ b/server/services/idealoomObsidian.js@@ -0,0 +1,377 @@+/**+ * Explicit IdeaLoom <-> Obsidian exchange.+ *+ * IdeaLoom notes are deliberately parsed here instead of through the generic+ * Obsidian YAML helper. The generic reader is intentionally forgiving; this+ * boundary must preserve escaped prompt/title values and reject ambiguous+ * list documents before they enter the local list store.+ */++import { createHash } from 'crypto';+import { existsSync } from 'fs';+import { join } from 'path';+import * as obsidian from './obsidian.js';+import * as ideaLoomLists from './idealoomLists.js';++export const IDEA_LOOM_FOLDER = 'Idea Loom';+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;+const NUMBERED_IDEA_RE = /^(\d+)\.\s+(.+)$/;++const RESULT_KEYS = ['imported', 'exported', 'skipped', 'conflicted', 'malformed', 'unavailable', 'failed'];++const newResult = () => {+ const counts = Object.fromEntries(RESULT_KEYS.map((key) => [key, 0]));+ return {+ ...counts,+ counts,+ details: Object.fromEntries(RESULT_KEYS.map((key) => [key, []])),+ };+};++const addResult = (result, kind, detail) => {+ result[kind] += 1;+ result.counts[kind] += 1;+ result.details[kind].push(detail);+};++const hashContent = (content) => createHash('sha256').update(content, 'utf8').digest('hex');++const isIsoDate = (value) => typeof value === 'string'+ && value.length > 0+ && !Number.isNaN(Date.parse(value));++const decodeScalar = (value) => {+ const trimmed = value.trim();+ if (trimmed.startsWith('"') && trimmed.endsWith('"')) {+ const source = trimmed.slice(1, -1);+ let decoded = '';+ for (let index = 0; index < source.length; index += 1) {+ if (source[index] !== '\\') {+ decoded += source[index];+ continue;+ }+ index += 1;+ const escape = source[index];+ const escapes = { '"': '"', '\\': '\\', '/': '/', b: '\b', f: '\f', n: '\n', r: '\r', t: '\t' };+ if (escape === 'u' && /^[0-9a-f]{4}$/i.test(source.slice(index + 1, index + 5))) {+ decoded += String.fromCharCode(Number.parseInt(source.slice(index + 1, index + 5), 16));+ index += 4;+ } else if (escape in escapes) {+ decoded += escapes[escape];+ } else {+ return null;+ }+ }+ return decoded;+ }+ if (trimmed.startsWith("'") && trimmed.endsWith("'")) {+ return trimmed.slice(1, -1).replaceAll("''", "'");+ }+ return trimmed || null;+};++const parseFrontmatter = (lines) => {+ if (lines[0] !== '---') return { error: 'missing frontmatter' };+ const end = lines.findIndex((line, index) => index > 0 && line === '---');+ if (end < 0) return { error: 'unterminated frontmatter' };++ const values = {};+ for (let index = 1; index < end; index += 1) {+ const line = lines[index];+ if (!line.trim() || line.trim().startsWith('#')) continue;+ const match = /^(\s*)([A-Za-z][A-Za-z0-9_-]*):(?:\s*)(.*)$/.exec(line);+ if (!match) return { error: `invalid frontmatter line ${index + 1}` };+ const [, indent, key, rawValue] = match;+ if (key === 'tags' && !rawValue.trim()) {+ const tags = [];+ let tagIndex = index + 1;+ while (tagIndex < end && /^\s+-\s+/.test(lines[tagIndex])) {+ const tag = decodeScalar(lines[tagIndex].replace(/^\s+-\s+/, ''));+ if (typeof tag !== 'string' || !tag) return { error: `invalid tag at line ${tagIndex + 1}` };+ tags.push(tag.replace(/^#/, ''));+ tagIndex += 1;+ }+ values.tags = tags;+ index = tagIndex - 1;+ continue;+ }+ if (indent) return { error: `unexpected indentation at line ${index + 1}` };+ if (key === 'tags' && rawValue.trim().startsWith('[') && rawValue.trim().endsWith(']')) {+ const inner = rawValue.trim().slice(1, -1).trim();+ values.tags = inner ? inner.split(',').map((entry) => decodeScalar(entry)).filter(Boolean).map((tag) => tag.replace(/^#/, '')) : [];+ continue;+ }+ const value = decodeScalar(rawValue);+ if (value === null) return { error: `empty frontmatter value for ${key}` };+ values[key] = value;+ }+ return { end, values };+};++const parseBody = (lines) => {+ const headingIndex = lines.findIndex((line) => /^#{1,6}\s+\S/.test(line));+ if (headingIndex < 0) return { error: 'missing prompt heading' };++ let prompt = lines[headingIndex].replace(/^#{1,6}\s+/, '').trim();+ let cursor = headingIndex + 1;+ if (prompt.toLowerCase() === 'prompt') {+ while (cursor < lines.length && !lines[cursor].trim()) cursor += 1;+ prompt = lines[cursor]?.trim() || '';+ cursor += 1;+ }+ if (!prompt || prompt.startsWith('#')) return { error: 'missing prompt text' };++ const helpLines = [];+ const ideas = [];+ let sawIdea = false;+ for (; cursor < lines.length; cursor += 1) {+ const line = lines[cursor];+ if (!line.trim()) {+ if (!sawIdea) helpLines.push('');+ continue;+ }+ if (/^#{1,6}\s+(help|ideas)\s*:?$/i.test(line.trim())) continue;+ const match = NUMBERED_IDEA_RE.exec(line.trim());+ if (!match) {+ if (sawIdea) return { error: `invalid numbered idea at line ${cursor + 1}` };+ helpLines.push(line.trim());+ continue;+ }+ sawIdea = true;+ const expected = ideas.length + 1;+ if (Number(match[1]) !== expected || !match[2].trim()) {+ return { error: `idea numbering must be dense starting at 1 (line ${cursor + 1})` };+ }+ ideas.push(match[2].trim());+ }++ return { prompt, help: helpLines.join('\n').trim(), ideas };+};++/** Parse the supported IdeaLoom Markdown shape into a local list document. */+export function parseIdeaLoomMarkdown(content) {+ if (typeof content !== 'string') return { ok: false, error: 'content is not text' };+ const lines = content.replaceAll('\r\n', '\n').replaceAll('\r', '\n').split('\n');+ const frontmatter = parseFrontmatter(lines);+ if (frontmatter.error) return { ok: false, error: frontmatter.error };+ const { values } = frontmatter;+ const id = values.id || values.uuid;+ const createdAt = values.created || values.createdAt;+ const updatedAt = values.modified || values.updatedAt;+ if (!UUID_RE.test(id || '')) return { ok: false, error: 'missing or invalid UUID' };+ if (!['draft', 'completed'].includes(values.status)) return { ok: false, error: 'unsupported status' };+ if (!values.title || !values.category || !isIsoDate(createdAt) || !isIsoDate(updatedAt)) {+ return { ok: false, error: 'missing title, category, created, or modified metadata' };+ }++ const body = parseBody(lines.slice(frontmatter.end + 1));+ if (body.error) return { ok: false, error: body.error };+ return {+ ok: true,+ list: {+ id,+ prompt: body.prompt,+ title: values.title,+ category: values.category,+ status: values.status,+ ...(body.help ? { help: body.help } : {}),+ ideas: body.ideas,+ createdAt,+ updatedAt,+ tags: Array.isArray(values.tags) ? values.tags : [],+ },+ };+}++const yamlString = (value) => JSON.stringify(String(value));++/** Render a local list in the stable Markdown shape consumed by IdeaLoom. */+export function renderIdeaLoomMarkdown(list) {+ const lines = [+ '---',+ `id: ${yamlString(list.id)}`,+ `title: ${yamlString(list.title)}`,+ `category: ${yamlString(list.category)}`,+ `status: ${yamlString(list.status)}`,+ `created: ${yamlString(list.createdAt)}`,+ `modified: ${yamlString(list.updatedAt)}`,+ 'tags:',+ ' - "idea-loom"',+ '---',+ `# ${String(list.prompt).replace(/[\r\n]+/g, ' ').trim()}`,+ ];+ if (list.help?.trim()) lines.push('', list.help.trim());+ if (list.ideas?.length) {+ lines.push('', ...list.ideas.map((idea, index) => `${index + 1}. ${String(idea).replace(/[\r\n]+/g, ' ').trim()}`));+ }+ return `${lines.join('\n')}\n`;+}++const slugify = (value) => String(value || 'list')+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, '-')+ .replace(/^-+|-+$/g, '')+ .slice(0, 80) || 'list';++const datePart = (value) => {+ const parsed = new Date(value);+ return Number.isNaN(parsed.getTime()) ? new Date().toISOString().slice(0, 10) : parsed.toISOString().slice(0, 10);+};++const generatedNotePath = (list, suffix = '') =>+ `${IDEA_LOOM_FOLDER}/${datePart(list.createdAt)}-${slugify(list.title)}${suffix}.md`;++const configuredExchange = async () => {+ const settings = await ideaLoomLists.getSettings();+ if (!settings.enabled) return { result: newResult(), reason: 'integration-disabled' };+ if (!settings.obsidianVaultId) return { result: newResult(), reason: 'vault-not-configured' };+ const vault = await obsidian.getVaultById(settings.obsidianVaultId);+ if (!vault) {+ return { result: newResult(), reason: 'vault-not-found' };+ }+ if (!existsSync(vault.path)) {+ return { result: newResult(), reason: 'path-not-found' };+ }+ return { settings, vault };+};++const withReason = (result, reason) => {+ addResult(result, reason === 'integration-disabled' || reason === 'vault-not-configured' ? 'skipped' : 'unavailable', { reason });+ return result;+};++/** Import valid notes from the configured Idea Loom folder. */+export async function importFromObsidian() {+ const exchange = await configuredExchange();+ if (!exchange.vault) return withReason(exchange.result, exchange.reason);+ const scan = await obsidian.scanVault(exchange.settings.obsidianVaultId, { folder: IDEA_LOOM_FOLDER });+ if (scan.error) return withReason(newResult(), scan.error);+ if (!existsSync(join(exchange.vault.path, IDEA_LOOM_FOLDER))) {+ return withReason(newResult(), 'folder-not-found');+ }+ const result = newResult();+ const unavailable = scan.skippedUnavailable || 0;+ for (let index = 0; index < unavailable; index += 1) addResult(result, 'unavailable', { reason: 'note-unavailable' });++ const loaded = await Promise.allSettled(scan.notes.map((note) =>+ obsidian.getNote(exchange.settings.obsidianVaultId, note.path, { includeBacklinks: false })));+ const parsedNotes = [];+ loaded.forEach((entry, index) => {+ const note = scan.notes[index];+ if (entry.status === 'rejected') {+ addResult(result, 'failed', { path: note.path, reason: entry.reason?.message || 'read failed' });+ } else if (entry.value?.error === 'NOTE_EVICTED') {+ addResult(result, 'unavailable', { path: note.path, reason: 'note-unavailable' });+ } else if (entry.value?.error) {+ addResult(result, 'failed', { path: note.path, reason: entry.value.error });+ } else {+ const parsed = parseIdeaLoomMarkdown(entry.value.content);+ if (!parsed.ok) addResult(result, 'malformed', { path: note.path, reason: parsed.error });+ else parsedNotes.push({ ...parsed.list, notePath: note.path, contentHash: hashContent(entry.value.content) });+ }+ });++ const byId = new Map();+ parsedNotes.forEach((note) => {+ const entries = byId.get(note.id) || [];+ entries.push(note);+ byId.set(note.id, entries);+ });+ const importable = [];+ for (const entries of byId.values()) {+ if (entries.length > 1) {+ entries.forEach((note) => addResult(result, 'skipped', { path: note.notePath, reason: 'duplicate-id', id: note.id }));+ continue;+ }+ importable.push(entries[0]);+ }+ const imports = await Promise.allSettled(importable.map(async (note) => {+ const existing = await ideaLoomLists.getList(note.id);+ if (existing?.sync?.notePath === note.notePath && existing.sync?.lastKnownContentHash === note.contentHash) {+ return { kind: 'skipped', path: note.notePath, reason: 'unchanged', id: note.id };+ }+ await ideaLoomLists.upsertImportedList(note.id, {+ prompt: note.prompt,+ title: note.title,+ category: note.category,+ status: note.status,+ help: note.help || '',+ ideas: note.ideas,+ createdAt: note.createdAt,+ updatedAt: note.updatedAt,+ sync: {+ notePath: note.notePath,+ lastKnownContentHash: note.contentHash,+ lastImportedAt: new Date().toISOString(),+ },+ });+ return { kind: 'imported', path: note.notePath, id: note.id, action: existing ? 'updated' : 'created' };+ }));+ imports.forEach((entry, index) => {+ const note = importable[index];+ if (entry.status === 'rejected') addResult(result, 'failed', { path: note.notePath, id: note.id, reason: entry.reason?.message || 'import failed' });+ else addResult(result, entry.value.kind, entry.value);+ });+ return result;+}++const writeNote = async (vaultId, notePath, content) => {+ const existing = await obsidian.getNote(vaultId, notePath, { includeBacklinks: false });+ if (existing?.error === 'NOTE_EVICTED') return { kind: 'unavailable', reason: 'note-unavailable' };+ if (existing?.error && existing.error !== 'NOTE_NOT_FOUND') return { kind: 'failed', reason: existing.error };+ const parsedExisting = existing?.content ? parseIdeaLoomMarkdown(existing.content) : null;+ if (parsedExisting?.ok && parsedExisting.list.id !== undefined) return { kind: 'existing', id: parsedExisting.list.id };+ if (existing?.content) return { kind: 'existing', id: null };+ const created = await obsidian.createNote(vaultId, notePath, content);+ if (!created?.error) return { kind: 'written' };+ if (created.error === 'NOTE_EVICTED') return { kind: 'unavailable', reason: 'note-unavailable' };+ return { kind: 'failed', reason: created.error };+};++/** Export one local list, preserving an imported note path forever. */+const exportOne = async (vaultId, list) => {+ const content = renderIdeaLoomMarkdown(list);+ const importedPath = list.sync?.notePath;+ let notePath = importedPath || generatedNotePath(list);+ let pathResult = await writeNote(vaultId, notePath, content);+ if (!importedPath && pathResult.kind === 'existing') {+ let suffix = `-${list.id.slice(0, 8)}`;+ notePath = generatedNotePath(list, suffix);+ pathResult = await writeNote(vaultId, notePath, content);+ }+ if (pathResult.kind === 'existing') {+ if (pathResult.id !== list.id) return { kind: 'failed', reason: 'note-path-owned-by-another-list', notePath };+ const updated = await obsidian.updateNote(vaultId, notePath, content);+ if (updated?.error === 'NOTE_EVICTED') return { kind: 'unavailable', reason: 'note-unavailable', notePath };+ if (updated?.error) return { kind: 'failed', reason: updated.error, notePath };+ } else if (pathResult.kind !== 'written') {+ return { ...pathResult, notePath };+ }+ await ideaLoomLists.updateSyncMetadata(list.id, {+ notePath,+ lastKnownContentHash: hashContent(content),+ lastExportedAt: new Date().toISOString(),+ });+ return { kind: 'exported', id: list.id, notePath };+};++/** Explicitly export all lists, or one selected list, to the configured vault. */+export async function exportToObsidian({ listId } = {}) {+ const exchange = await configuredExchange();+ if (!exchange.vault) return withReason(exchange.result, exchange.reason);+ const result = newResult();+ const lists = await ideaLoomLists.listLists();+ const selected = listId ? lists.filter((list) => list.id === listId) : lists;+ if (listId && !selected.length) {+ addResult(result, 'failed', { id: listId, reason: 'list-not-found' });+ return result;+ }+ const outcomes = await Promise.allSettled(selected.map((list) => exportOne(exchange.settings.obsidianVaultId, list)));+ outcomes.forEach((entry, index) => {+ const list = selected[index];+ if (entry.status === 'rejected') addResult(result, 'failed', { id: list.id, reason: entry.reason?.message || 'write failed' });+ else if (entry.value.kind === 'exported') addResult(result, 'exported', entry.value);+ else addResult(result, entry.value.kind, { id: list.id, ...entry.value });+ });+ return result;+}diff --git a/server/services/idealoomObsidian.test.js b/server/services/idealoomObsidian.test.jsnew file mode 100644index 0000000000..38496804f1--- /dev/null+++ b/server/services/idealoomObsidian.test.js@@ -0,0 +1,173 @@+import { describe, expect, it, beforeEach, vi } from 'vitest';+import { mkdirSync, mkdtempSync, rmSync } from 'fs';+import { join } from 'path';+import { tmpdir } from 'os';++vi.mock('./obsidian.js', () => ({+ getVaultById: vi.fn(),+ scanVault: vi.fn(),+ getNote: vi.fn(),+ createNote: vi.fn(),+ updateNote: vi.fn(),+}));++vi.mock('./idealoomLists.js', () => ({+ getSettings: vi.fn(),+ getList: vi.fn(),+ listLists: vi.fn(),+ upsertImportedList: vi.fn(),+ updateSyncMetadata: vi.fn(),+}));++import * as obsidian from './obsidian.js';+import * as lists from './idealoomLists.js';+import {+ importFromObsidian,+ parseIdeaLoomMarkdown,+ renderIdeaLoomMarkdown,+ exportToObsidian,+} from './idealoomObsidian.js';++const VAULT_ID = '0f6c6a6f-8c16-4c7d-9a8b-2e2f6f2cb4d1';+const LIST_ID = 'f1c2d3e4-5678-4abc-9def-0123456789ab';+let vaultRoot;++const list = (overrides = {}) => ({+ id: LIST_ID,+ prompt: 'What should we build next?',+ title: 'Next steps: "small"',+ category: 'product',+ status: 'draft',+ help: 'Keep the ideas practical.',+ ideas: ['First idea', 'Second idea'],+ createdAt: '2026-08-29T10:00:00.000Z',+ updatedAt: '2026-08-29T11:00:00.000Z',+ ...overrides,+});++const note = (overrides = {}) => ({+ path: 'Idea Loom/2026-08-29-next-steps.md',+ ...overrides,+});++beforeEach(() => {+ vi.clearAllMocks();+ if (vaultRoot) rmSync(vaultRoot, { recursive: true, force: true });+ vaultRoot = mkdtempSync(join(tmpdir(), 'idealoom-obsidian-test-'));+ mkdirSync(join(vaultRoot, 'Idea Loom'), { recursive: true });+ lists.getSettings.mockResolvedValue({ enabled: true, obsidianVaultId: VAULT_ID, autoSync: false });+ obsidian.getVaultById.mockResolvedValue({ id: VAULT_ID, name: 'Example Vault', path: vaultRoot });+ obsidian.scanVault.mockResolvedValue({ vault: { path: vaultRoot }, notes: [], skippedUnavailable: 0 });+ lists.listLists.mockResolvedValue([]);+});++describe('IdeaLoom Markdown contract', () => {+ it('round-trips escaped metadata, help text, and ordered ideas', () => {+ const original = list({ title: 'Quotes "and" \\slashes', help: 'A helpful note: preserve it.' });+ const parsed = parseIdeaLoomMarkdown(renderIdeaLoomMarkdown(original));++ expect(parsed).toEqual({+ ok: true,+ list: expect.objectContaining({+ id: original.id,+ title: original.title,+ category: original.category,+ status: original.status,+ prompt: original.prompt,+ help: original.help,+ ideas: original.ideas,+ createdAt: original.createdAt,+ updatedAt: original.updatedAt,+ }),+ });+ });++ it('rejects malformed metadata and non-dense numbered ideas', () => {+ const rendered = renderIdeaLoomMarkdown(list());+ expect(parseIdeaLoomMarkdown(rendered.replace(`id: "${LIST_ID}"`, 'id: "not-a-uuid"')).ok).toBe(false);+ expect(parseIdeaLoomMarkdown(rendered.replace('status: "draft"', 'status: "archived"')).ok).toBe(false);+ expect(parseIdeaLoomMarkdown(rendered.replace('1. First idea\n2. Second idea', '1. First idea\n3. Second idea')).error)+ .toMatch(/dense/);+ expect(parseIdeaLoomMarkdown('---\nid: "' + LIST_ID + '"\n---\n# Prompt').ok).toBe(false);+ });+});++describe('IdeaLoom Obsidian exchange', () => {+ it('does no vault I/O while disabled or unconfigured', async () => {+ lists.getSettings.mockResolvedValueOnce({ enabled: false, obsidianVaultId: null, autoSync: false });+ expect((await importFromObsidian()).counts.skipped).toBe(1);+ expect(obsidian.getVaultById).not.toHaveBeenCalled();+ expect(obsidian.scanVault).not.toHaveBeenCalled();++ lists.getSettings.mockResolvedValueOnce({ enabled: true, obsidianVaultId: null, autoSync: false });+ expect((await exportToObsidian()).counts.skipped).toBe(1);+ expect(obsidian.getVaultById).not.toHaveBeenCalled();+ });++ it('imports valid notes, surfaces malformed and unavailable notes, and is idempotent', async () => {+ const valid = renderIdeaLoomMarkdown(list());+ const validNote = note();+ const malformedNote = note({ path: 'Idea Loom/malformed.md' });+ const unavailableNote = note({ path: 'Idea Loom/cloud.md' });+ obsidian.scanVault.mockResolvedValue({+ vault: { path: vaultRoot },+ notes: [validNote, malformedNote, unavailableNote],+ skippedUnavailable: 0,+ });+ obsidian.getNote.mockImplementation(async (_vaultId, path) => {+ if (path === validNote.path) return { content: valid };+ if (path === malformedNote.path) return { content: 'not IdeaLoom' };+ return { error: 'NOTE_EVICTED' };+ });+ let stored = null;+ lists.getList.mockImplementation(async () => stored);+ lists.upsertImportedList.mockImplementation(async (id, data) => { stored = { id, ...data }; return stored; });++ const first = await importFromObsidian();+ expect(first.counts).toMatchObject({ imported: 1, malformed: 1, unavailable: 1 });+ expect(lists.upsertImportedList).toHaveBeenCalledWith(LIST_ID, expect.objectContaining({+ sync: expect.objectContaining({ notePath: validNote.path, lastKnownContentHash: expect.any(String) }),+ }));++ const second = await importFromObsidian();+ expect(second.counts).toMatchObject({ skipped: 1, malformed: 1, unavailable: 1 });+ expect(lists.upsertImportedList).toHaveBeenCalledOnce();+ });++ it('skips duplicate UUIDs without importing either note', async () => {+ const valid = renderIdeaLoomMarkdown(list());+ const first = note();+ const second = note({ path: 'Idea Loom/duplicate.md' });+ obsidian.scanVault.mockResolvedValue({ vault: { path: vaultRoot }, notes: [first, second], skippedUnavailable: 0 });+ obsidian.getNote.mockResolvedValue({ content: valid });++ const result = await importFromObsidian();+ expect(result.counts).toMatchObject({ skipped: 2, imported: 0 });+ expect(result.details.skipped.every((entry) => entry.reason === 'duplicate-id')).toBe(true);+ expect(lists.upsertImportedList).not.toHaveBeenCalled();+ });++ it('exports a new list and preserves an imported filename', async () => {+ const local = list();+ lists.listLists.mockResolvedValue([local]);+ obsidian.getNote.mockResolvedValue({ error: 'NOTE_NOT_FOUND' });+ obsidian.createNote.mockResolvedValue({ path: 'created' });++ const created = await exportToObsidian();+ expect(created.counts.exported).toBe(1);+ expect(obsidian.createNote).toHaveBeenCalledWith(VAULT_ID, expect.stringMatching(/^Idea Loom\/2026-08-29-next-steps-small\.md$/), expect.stringContaining('1. First idea'));+ expect(lists.updateSyncMetadata).toHaveBeenCalledWith(LIST_ID, expect.objectContaining({ notePath: expect.stringContaining('Idea Loom/') }));++ const importedPath = 'Idea Loom/2026-01-01-original-name.md';+ lists.listLists.mockResolvedValue([local, list({ id: '0a1b2c3d-4e5f-4a6b-8c7d-8e9f0a1b2c3d', sync: { notePath: importedPath } })]);+ obsidian.getNote.mockImplementation(async (_id, path) => path === importedPath+ ? { content: renderIdeaLoomMarkdown(list({ id: '0a1b2c3d-4e5f-4a6b-8c7d-8e9f0a1b2c3d' })) }+ : { error: 'NOTE_NOT_FOUND' });+ obsidian.updateNote.mockResolvedValue({ path: importedPath });+ obsidian.createNote.mockResolvedValue({ path: 'created' });++ const exported = await exportToObsidian({ listId: '0a1b2c3d-4e5f-4a6b-8c7d-8e9f0a1b2c3d' });+ expect(exported.counts.exported).toBe(1);+ expect(obsidian.updateNote).toHaveBeenCalledWith('0f6c6a6f-8c16-4c7d-9a8b-2e2f6f2cb4d1', importedPath, expect.any(String));+ });+});