Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: stop IdeaLoom sync from resurrecting a note you deleted in Obsidian (#5339)

[._.]/ Adam Eivy83b22ceb2be5
diff --git a/client/src/components/brain/IdeaLoomLists.jsx b/client/src/components/brain/IdeaLoomLists.jsx
index 957e9d70b1..b53c6f6dba 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, Download, Plus, Save, Trash2, Upload, X } from 'lucide-react';
+import { ArrowDown, ArrowUp, CheckCircle2, Download, Plus, RotateCcw, Save, Trash2, Upload, X } from 'lucide-react';
import * as api from '../../services/api';
import toast from '../ui/Toast';
import InlineConfirmRow from '../ui/InlineConfirmRow';
@@ -8,6 +8,12 @@ import useUrlParams from '../../hooks/useUrlParams';
const emptyList = () => ({ title: '', prompt: '', category: '', help: '', status: 'draft', ideas: [] });
+// Every outcome the server can report. Anything that is not a clean
+// imported/exported/skipped result needs the user's attention, so the summary
+// names all of them rather than collapsing them into a single failure count.
+const PROBLEM_KEYS = ['conflicted', 'missing', 'malformed', 'unavailable', 'failed'];
+const RESULT_KEYS = ['imported', 'exported', 'skipped', ...PROBLEM_KEYS];
+
// The list API is strict: it accepts exactly these keys and rejects record
// metadata (id, schemaVersion, timestamps, importer-owned sync state). Project
// the draft rather than spreading it, or every edit round-trips as a 400.
@@ -51,6 +57,7 @@ export default function IdeaLoomLists() {
const [ideaText, setIdeaText] = useState('');
const [exchangeBusy, setExchangeBusy] = useState(false);
const [exchangeResult, setExchangeResult] = useState(null);
+ const [vaults, setVaults] = useState([]);
const { isConfirming, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();
const select = useCallback((id) => updateParams({ list: id }), [updateParams]);
@@ -64,6 +71,10 @@ export default function IdeaLoomLists() {
toast.error(error.message || 'Failed to load IdeaLoom lists');
return [[], null];
});
+ // The vault list only names existing vaults to choose between; a failure
+ // here leaves the picker empty rather than blocking local list editing.
+ const vaultData = await api.getNotesVaults().catch(() => ({ vaults: [] }));
+ setVaults(vaultData?.vaults || []);
setLists(Array.isArray(nextLists?.lists) ? nextLists.lists : (Array.isArray(nextLists) ? nextLists : []));
setSettings(nextSettings?.settings || nextSettings);
setLoading(false);
@@ -128,6 +139,15 @@ export default function IdeaLoomLists() {
setIdeaText('');
};
+ const patchSettings = async (updates) => {
+ const result = await api.updateIdeaLoomSettings(updates, { silent: true }).catch((error) => {
+ toast.error(error.message || 'Failed to update IdeaLoom settings');
+ return null;
+ });
+ if (!result) return;
+ setSettings(result.settings || result);
+ };
+
const runExchange = async (action, successMessage) => {
setExchangeBusy(true);
const result = await action().catch((error) => {
@@ -138,7 +158,7 @@ export default function IdeaLoomLists() {
if (!result) return;
const counts = result.counts || result;
setExchangeResult(counts);
- const problems = ['conflicted', 'malformed', 'unavailable', 'failed'].reduce((total, key) => total + (counts[key] || 0), 0);
+ const problems = PROBLEM_KEYS.reduce((total, key) => total + (counts[key] || 0), 0);
if (problems) toast.error(`${successMessage} with ${problems} issue${problems === 1 ? '' : 's'}`);
else toast.success(successMessage);
await load();
@@ -153,12 +173,29 @@ export default function IdeaLoomLists() {
<div><h2 className="font-medium text-white">IdeaLoom lists</h2><p className="text-xs text-gray-500">Separate from native Brain ideas</p></div>
<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>
+ {settings && <div className="mb-3 space-y-2 rounded border border-port-border p-2">
+ <label className="flex items-center gap-2 text-xs text-gray-300" htmlFor="idealoom-enabled">
+ <input id="idealoom-enabled" type="checkbox" checked={Boolean(settings.enabled)} onChange={(event) => patchSettings({ enabled: event.target.checked })} />
+ Sync with an Obsidian vault
+ </label>
+ {settings.enabled && <label className="block text-xs text-gray-300" htmlFor="idealoom-vault">Vault
+ <select id="idealoom-vault" value={settings.obsidianVaultId || ''} onChange={(event) => patchSettings({ obsidianVaultId: event.target.value || null })} className="mt-1 block min-h-[44px] w-full rounded border border-port-border bg-port-bg px-3 text-sm text-white">
+ <option value="">Choose a vault…</option>
+ {vaults.map((vault) => <option key={vault.id} value={vault.id}>{vault.name}</option>)}
+ </select>
+ </label>}
+ {settings.enabled && settings.obsidianVaultId && <label className="flex items-start gap-2 text-xs text-gray-300" htmlFor="idealoom-autosync">
+ <input id="idealoom-autosync" type="checkbox" checked={Boolean(settings.autoSync)} onChange={(event) => patchSettings({ autoSync: event.target.checked })} />
+ <span>Export automatically after an edit<span className="block text-gray-500">Never deletes or recreates a note. A note you deleted in Obsidian is reported, not restored.</span></span>
+ </label>}
+ </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"><Download 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"><Upload size={14} />Export to Obsidian</button>
+ {Boolean(exchangeResult?.missing) && <button type="button" disabled={exchangeBusy} onClick={() => runExchange(() => api.syncIdeaLoomToObsidian(null, { silent: true, recreateMissing: true }), 'Deleted notes recreated')} className="flex min-h-[44px] items-center gap-2 rounded border border-port-warning px-3 text-xs text-port-warning hover:bg-port-warning/10 disabled:opacity-50"><RotateCcw size={14} />Recreate {exchangeResult.missing} deleted note{exchangeResult.missing === 1 ? '' : 's'}</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.conflicted || 0} conflicted · {exchangeResult.malformed || 0} malformed · {exchangeResult.unavailable || 0} unavailable · {exchangeResult.failed || 0} failed</p>}
+ {exchangeResult && <p role="status" className="mb-3 text-xs text-gray-400">Last exchange: {RESULT_KEYS.map((key) => `${exchangeResult[key] || 0} ${key}`).join(' · ')}</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.jsx
index 2c3d819f16..835a95e504 100644
--- a/client/src/components/brain/IdeaLoomLists.test.jsx
+++ b/client/src/components/brain/IdeaLoomLists.test.jsx
@@ -6,6 +6,7 @@ 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(),
+ updateIdeaLoomSettings: vi.fn(), getNotesVaults: vi.fn(),
}));
vi.mock('../ui/Toast', () => ({ default: { error: vi.fn(), success: vi.fn() } }));
@@ -42,9 +43,50 @@ beforeEach(() => {
vi.clearAllMocks();
api.getIdeaLoomLists.mockResolvedValue([]);
api.getIdeaLoomSettings.mockResolvedValue({ enabled: false, obsidianVaultId: null, autoSync: false });
+ api.getNotesVaults.mockResolvedValue({ vaults: [{ id: 'vault-1', name: 'Example Vault' }] });
});
describe('IdeaLoomLists', () => {
+ it('opts into vault sync and automatic export one explicit step at a time', async () => {
+ api.updateIdeaLoomSettings
+ .mockResolvedValueOnce({ enabled: true, obsidianVaultId: null, autoSync: false })
+ .mockResolvedValueOnce({ enabled: true, obsidianVaultId: 'vault-1', autoSync: false })
+ .mockResolvedValueOnce({ enabled: true, obsidianVaultId: 'vault-1', autoSync: true });
+ renderPanel();
+
+ // The auto-sync toggle stays out of reach until sync is on AND a vault is
+ // chosen, so it can never be enabled against an unconfigured integration.
+ fireEvent.click(await screen.findByLabelText('Sync with an Obsidian vault'));
+ await waitFor(() => expect(screen.queryByLabelText('Vault')).toBeTruthy());
+ expect(screen.queryByLabelText(/Export automatically/)).toBeNull();
+
+ fireEvent.change(screen.getByLabelText('Vault'), { target: { value: 'vault-1' } });
+ const autoSync = await screen.findByLabelText(/Export automatically/);
+ fireEvent.click(autoSync);
+
+ await waitFor(() => expect(api.updateIdeaLoomSettings).toHaveBeenLastCalledWith({ autoSync: true }, expect.anything()));
+ });
+
+ it('offers explicit recovery only after an exchange reports a deleted note', async () => {
+ api.getIdeaLoomSettings.mockResolvedValue({ enabled: true, obsidianVaultId: 'vault-1', autoSync: false });
+ api.syncIdeaLoomToObsidian
+ .mockResolvedValueOnce({ counts: { exported: 0, missing: 1 } })
+ .mockResolvedValueOnce({ counts: { exported: 1, missing: 0 } });
+ renderPanel();
+
+ expect(screen.queryByText(/Recreate/)).toBeNull();
+ fireEvent.click(await screen.findByText('Export to Obsidian'));
+
+ const recover = await screen.findByText('Recreate 1 deleted note');
+ fireEvent.click(recover);
+
+ await waitFor(() => expect(api.syncIdeaLoomToObsidian)
+ .toHaveBeenLastCalledWith(null, expect.objectContaining({ recreateMissing: true })));
+ // The first, automatic-shaped export must NOT have asked for a recreate.
+ expect(api.syncIdeaLoomToObsidian.mock.calls[0][1]).not.toHaveProperty('recreateMissing');
+ await waitFor(() => expect(screen.queryByText(/Recreate/)).toBeNull());
+ });
+
it('keeps local list editing available while vault sync is disabled', async () => {
api.createIdeaLoomList.mockResolvedValue({ id: 'list-1', title: 'Launch ideas', prompt: 'Why?', category: 'product', status: 'draft', ideas: ['One'] });
renderPanel();
diff --git a/client/src/services/apiBrain.js b/client/src/services/apiBrain.js
index 6eb8301e17..5086311df1 100644
--- a/client/src/services/apiBrain.js
+++ b/client/src/services/apiBrain.js
@@ -132,9 +132,17 @@ export const deleteIdeaLoomList = (id, options = {}) => request(`/brain/ideas/id
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
-});
+// `recreateMissing` is the explicit recovery request for a vault note the user
+// deleted. Automatic sync never sets it, so recreating a note is always a
+// deliberate click rather than a side effect of saving a list.
+export const syncIdeaLoomToObsidian = (listId, options = {}) => {
+ const { recreateMissing, ...requestOptions } = options;
+ return request('/brain/ideas/idealoom/sync', {
+ method: 'POST',
+ body: JSON.stringify({ ...(listId ? { listId } : {}), ...(recreateMissing ? { recreateMissing: true } : {}) }),
+ ...requestOptions
+ });
+};
// Brain - Admin
export const getBrainAdmin = (filters) => {
diff --git a/docs/API.md b/docs/API.md
index 34e5bf096b..a38cc40b95 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -348,7 +348,7 @@ Context tools remain read-only. Semantic reads and writes are independent, defau
| 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 |
+| POST | `/brain/ideas/idealoom/sync` | Explicitly export all lists, or one list (`listId`), to the configured Obsidian vault. `recreateMissing: true` is the only way to rewrite a note deleted in the vault — automatic sync never sets it |
| 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.md
index 3f4b411366..f3da14e7f6 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. 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`.
+- 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. Exchange is base-hash reconciled: a note and a list that both changed since the stored hash report `conflicted` and neither is written, and a note deleted in the vault reports `missing` rather than being recreated (an iCloud note that is merely un-downloaded is `unavailable`, a separate outcome). Opt-in automatic export (`autoSync`, off by default, debounced by `server/services/idealoomAutoSync.js`) can only update an existing note — it never deletes, recreates, or resolves a conflict. Backed up in full with the rest of `data/brain/`; the vault notes themselves are the user's Obsidian data and are outside PortOS's snapshot. Adapters: `server/services/idealoomLists.js` (records), `server/services/idealoomObsidian.js` (exchange).
- 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.md
index 04ca507a96..f5d35eaf90 100644
--- a/docs/features/brain-system.md
+++ b/docs/features/brain-system.md
@@ -223,13 +223,57 @@ 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, conflicted, malformed, unavailable, and failed work. When a
-note and its local list both changed since the last exchange, import and export
-fail closed with a conflict result rather than overwriting either side. List
-records and vault identifiers remain under `data/brain/idealoom-lists/` and
-never enter Brain federation or the memory bridge. Automatic-sync behavior and
-user-directed conflict resolution are intentionally handled by the follow-up
-sync slice.
+exported, skipped, conflicted, missing, malformed, unavailable, and failed
+work. Each stays a distinct outcome so a deleted note never reads as a failed
+one. List records and vault identifiers remain under
+`data/brain/idealoom-lists/` and never enter Brain federation or the memory
+bridge.
+
+### Conflicts
+
+Every exchanged list stores the hash of the note as it was last read or
+written. That hash is the base for the next comparison:
+
+| Vault note vs. base | Local list vs. base | Outcome |
+|---|---|---|
+| unchanged | unchanged | `skipped` (`unchanged`) — nothing is written |
+| changed | unchanged | import updates the list; export reports `skipped` (`external-change`) |
+| unchanged | changed | export writes the note |
+| changed | changed | `conflicted` (`both-sides-changed`) — **neither side is overwritten** |
+
+A conflict is resolved by hand: edit whichever side you want to keep so the
+other becomes the only changed one, then run the exchange again.
+
+### Deletions
+
+Deleting a vault note is treated as a decision, never as drift to repair. A
+list whose note is gone is reported as `missing` (`note-deleted-externally`)
+by both import and export, and **nothing is written** — the local list is kept
+so nothing is lost. Recreating the note takes an explicit "Recreate deleted
+notes" action, which is the only path that sets `recreateMissing`. In the other
+direction, deleting a local list leaves its vault note alone: removing the note
+is done in Obsidian.
+
+An iCloud note that has not been downloaded to this Mac is `unavailable`, not
+`missing` — the file still exists, so it is never a recovery candidate.
+
+### Automatic sync
+
+Automatic export is off by default and needs two separate opt-ins: vault sync
+enabled with a vault chosen, then **Export automatically after an edit**. Both
+are re-read when the write actually fires, so turning either off cancels work
+already queued. Automatic writes are debounced, so reordering a list one click
+at a time is a single note write.
+
+Automatic sync is deliberately the least powerful path in the feature. It can
+only ever update an existing note whose content differs from the list: it never
+deletes a note, never recreates a deleted one, and never resolves a conflict.
+Anything it cannot do safely is reported and waits for an explicit action.
+
+There is no import/export feedback loop: only a local list edit schedules an
+automatic export, and an export whose rendered Markdown already matches the
+note on disk is skipped instead of rewritten, so a freshly imported list does
+not export itself back.
## Implementation Files
@@ -239,7 +283,8 @@ sync slice.
| `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/idealoomObsidian.js` | Validated IdeaLoom Markdown import/export with base-hash conflict and deletion handling |
+| `server/services/idealoomAutoSync.js` | Opt-in debounced automatic export (never deletes or recreates a note) |
| `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.json
index 602dd5b409..305392cb07 100644
--- a/server/lib/apiRouteCatalog.generated.json
+++ b/server/lib/apiRouteCatalog.generated.json
@@ -2443,7 +2443,7 @@
"sources": [
{
"source": "server/routes/brainIdeaLoom.js",
- "line": 27
+ "line": 28
}
]
},
@@ -2454,7 +2454,7 @@
"sources": [
{
"source": "server/routes/brainIdeaLoom.js",
- "line": 37
+ "line": 41
}
]
},
@@ -2465,7 +2465,7 @@
"sources": [
{
"source": "server/routes/brainIdeaLoom.js",
- "line": 41
+ "line": 49
}
]
},
@@ -2476,7 +2476,7 @@
"sources": [
{
"source": "server/routes/brainIdeaLoom.js",
- "line": 59
+ "line": 73
}
]
},
@@ -2487,7 +2487,7 @@
"sources": [
{
"source": "server/routes/brainIdeaLoom.js",
- "line": 46
+ "line": 56
}
]
},
@@ -2498,7 +2498,7 @@
"sources": [
{
"source": "server/routes/brainIdeaLoom.js",
- "line": 52
+ "line": 62
}
]
},
@@ -2509,7 +2509,7 @@
"sources": [
{
"source": "server/routes/brainIdeaLoom.js",
- "line": 18
+ "line": 19
}
]
},
@@ -2520,7 +2520,7 @@
"sources": [
{
"source": "server/routes/brainIdeaLoom.js",
- "line": 22
+ "line": 23
}
]
},
@@ -2531,7 +2531,7 @@
"sources": [
{
"source": "server/routes/brainIdeaLoom.js",
- "line": 32
+ "line": 36
}
]
},
diff --git a/server/lib/brainValidation.js b/server/lib/brainValidation.js
index a4da407879..75184bc8d0 100644
--- a/server/lib/brainValidation.js
+++ b/server/lib/brainValidation.js
@@ -300,8 +300,12 @@ export const ideaLoomSettingsInputSchema = z.object({
export const ideaLoomImportInputSchema = z.preprocess((value) => value ?? {}, z.object({}).strict());
+// `recreateMissing` is the explicit recovery switch for a vault note the user
+// deleted. It is only ever reachable from a user-initiated sync request —
+// automatic sync omits it, so it can never resurrect a deleted note on its own.
export const ideaLoomSyncInputSchema = z.preprocess((value) => value ?? {}, z.object({
- listId: z.string().uuid().optional()
+ listId: z.string().uuid().optional(),
+ recreateMissing: z.boolean().optional().default(false)
}).strict());
// Create/Update Admin input schema
diff --git a/server/routes/brain.test.js b/server/routes/brain.test.js
index 0c3aad9409..720aa98d70 100644
--- a/server/routes/brain.test.js
+++ b/server/routes/brain.test.js
@@ -88,6 +88,8 @@ vi.mock('../services/idealoomLists.js', () => ({
deleteList: vi.fn()
}));
+vi.mock('../services/idealoomAutoSync.js', () => ({ scheduleAutoSync: vi.fn() }));
+
vi.mock('../services/idealoomObsidian.js', () => ({
importFromObsidian: vi.fn(),
exportToObsidian: vi.fn(),
@@ -151,6 +153,7 @@ vi.mock('../services/brainJournal.js', () => ({
import * as brainService from '../services/brain.js';
import * as ideaLoomLists from '../services/idealoomLists.js';
import * as ideaLoomObsidian from '../services/idealoomObsidian.js';
+import { scheduleAutoSync } from '../services/idealoomAutoSync.js';
import { getBrainGraphSearchIndex, getBrainGraphOverview, getBrainGraphNeighborhood } from '../services/brainGraph.js';
import { syncAllBrainData, getEmbeddingCoverage } from '../services/brainMemoryBridge.js';
import { getChangesSince } from '../services/brainSyncLog.js';
@@ -254,7 +257,41 @@ describe('Brain Routes', () => {
.send({ listId: LIST_ID });
expect(exported.status).toBe(200);
expect(exported.body.counts.exported).toBe(1);
- expect(ideaLoomObsidian.exportToObsidian).toHaveBeenCalledWith({ listId: LIST_ID });
+ // recreateMissing defaults to false: an export that does not ASK to
+ // recover a deleted note must never be handed a truthy switch.
+ expect(ideaLoomObsidian.exportToObsidian).toHaveBeenCalledWith({ listId: LIST_ID, recreateMissing: false });
+
+ const recovered = await request(app)
+ .post('/api/brain/ideas/idealoom/sync')
+ .send({ listId: LIST_ID, recreateMissing: true });
+ expect(recovered.status).toBe(200);
+ expect(ideaLoomObsidian.exportToObsidian).toHaveBeenLastCalledWith({ listId: LIST_ID, recreateMissing: true });
+ });
+
+ it('schedules automatic sync from local edits only, never from an exchange', async () => {
+ const input = {
+ prompt: 'Find practical improvements', title: 'Practical improvements',
+ category: 'product', ideas: ['Improve empty states']
+ };
+ ideaLoomLists.createList.mockResolvedValue({ id: LIST_ID, ...input });
+ ideaLoomLists.updateList.mockResolvedValue({ id: LIST_ID, ...input, title: 'Renamed' });
+ ideaLoomLists.deleteList.mockResolvedValue(true);
+ ideaLoomObsidian.importFromObsidian.mockResolvedValue({ counts: { imported: 1 } });
+ ideaLoomObsidian.exportToObsidian.mockResolvedValue({ counts: { exported: 1 } });
+
+ await request(app).post('/api/brain/ideas/idealoom/lists').send(input);
+ await request(app).put(`/api/brain/ideas/idealoom/lists/${LIST_ID}`).send({ title: 'Renamed' });
+ expect(scheduleAutoSync).toHaveBeenCalledTimes(2);
+ expect(scheduleAutoSync).toHaveBeenCalledWith(LIST_ID);
+
+ scheduleAutoSync.mockClear();
+ // Deleting a list must not schedule a write — the vault note is the
+ // user's to remove. Import/export must not either, or the two halves of
+ // the exchange would keep re-triggering each other.
+ await request(app).delete(`/api/brain/ideas/idealoom/lists/${LIST_ID}`);
+ await request(app).post('/api/brain/ideas/idealoom/import').send({});
+ await request(app).post('/api/brain/ideas/idealoom/sync').send({});
+ expect(scheduleAutoSync).not.toHaveBeenCalled();
});
it('rejects unknown exchange request fields', async () => {
diff --git a/server/routes/brainIdeaLoom.js b/server/routes/brainIdeaLoom.js
index 2a922730eb..827b3ade40 100644
--- a/server/routes/brainIdeaLoom.js
+++ b/server/routes/brainIdeaLoom.js
@@ -12,6 +12,7 @@ import {
} from '../lib/brainValidation.js';
import * as ideaLoomLists from '../services/idealoomLists.js';
import * as ideaLoomObsidian from '../services/idealoomObsidian.js';
+import { scheduleAutoSync } from '../services/idealoomAutoSync.js';
const router = Router();
@@ -29,18 +30,27 @@ router.post('/ideas/idealoom/import', asyncHandler(async (req, res) => {
res.json(await ideaLoomObsidian.importFromObsidian());
}));
+// The explicit export. This is the ONLY caller that can pass recreateMissing,
+// so recovering a note the user deleted in the vault always takes a deliberate
+// request — automatic sync reports the deletion and writes nothing.
router.post('/ideas/idealoom/sync', asyncHandler(async (req, res) => {
- const { listId } = validateRequest(ideaLoomSyncInputSchema, req.body);
- res.json(await ideaLoomObsidian.exportToObsidian({ listId }));
+ const { listId, recreateMissing } = validateRequest(ideaLoomSyncInputSchema, req.body);
+ res.json(await ideaLoomObsidian.exportToObsidian({ listId, recreateMissing }));
}));
router.get('/ideas/idealoom/lists', asyncHandler(async (_req, res) => {
res.json(await ideaLoomLists.listLists());
}));
+// Only these two user-initiated write routes schedule an automatic export.
+// The import and sync routes deliberately do not: keeping the trigger on the
+// user's edit path is what stops an import from provoking an export, and that
+// export from provoking the next import.
router.post('/ideas/idealoom/lists', asyncHandler(async (req, res) => {
const data = validateRequest(ideaLoomListInputSchema, req.body);
- res.status(201).json(await ideaLoomLists.createList(data));
+ const list = await ideaLoomLists.createList(data);
+ scheduleAutoSync(list.id);
+ res.status(201).json(list);
}));
router.get('/ideas/idealoom/lists/:id', asyncHandler(async (req, res) => {
@@ -53,9 +63,13 @@ router.put('/ideas/idealoom/lists/:id', asyncHandler(async (req, res) => {
const updates = validateRequest(partialWithoutDefaults(ideaLoomListInputSchema), req.body);
const list = await ideaLoomLists.updateList(req.params.id, updates);
if (!list) throw new ServerError('IdeaLoom list not found', { status: 404, code: 'NOT_FOUND' });
+ scheduleAutoSync(list.id);
res.json(list);
}));
+// Deleting a list deliberately leaves its vault note alone and schedules
+// nothing: an implicit remote delete is the one automatic action this
+// integration must never take. Removing the note is the user's job in Obsidian.
router.delete('/ideas/idealoom/lists/:id', asyncHandler(async (req, res) => {
if (!await ideaLoomLists.deleteList(req.params.id)) {
throw new ServerError('IdeaLoom list not found', { status: 404, code: 'NOT_FOUND' });
diff --git a/server/services/idealoomAutoSync.js b/server/services/idealoomAutoSync.js
new file mode 100644
index 0000000000..cbe5f395ec
--- /dev/null
+++ b/server/services/idealoomAutoSync.js
@@ -0,0 +1,80 @@
+/**
+ * Opt-in, debounced automatic IdeaLoom export.
+ *
+ * Automatic writes are the one part of the exchange the user never watches, so
+ * this layer is deliberately the most conservative one:
+ *
+ * - **Opt-in twice.** It runs only when the integration is enabled AND
+ * `autoSync` is on AND a vault is configured. Every gate is re-read at fire
+ * time, so turning the toggle off cancels work already queued.
+ * - **Never destructive.** It calls `exportToObsidian` with the defaults, so it
+ * cannot delete a note and cannot recreate one the user deleted — a list
+ * whose note is gone comes back as `missing` and waits for an explicit
+ * recovery request.
+ * - **No feedback loop.** Only a user-initiated local list write schedules a
+ * run (the import and sync routes never do), and an export whose rendered
+ * Markdown already matches the note on disk is skipped rather than rewritten.
+ *
+ * The debounce coalesces a burst of edits — reordering ideas one click at a
+ * time is one vault write, not eight.
+ */
+
+import * as ideaLoomLists from './idealoomLists.js';
+import * as ideaLoomObsidian from './idealoomObsidian.js';
+
+export const AUTO_SYNC_DEBOUNCE_MS = 5000;
+
+const pending = new Set();
+let timer = null;
+// Runs are chained rather than fired concurrently: two overlapping exports of
+// the same list would read the same base hash and race on the note.
+let queue = Promise.resolve();
+
+const runPending = async () => {
+ const listIds = [...pending];
+ pending.clear();
+ if (!listIds.length) return;
+
+ const settings = await ideaLoomLists.getSettings();
+ if (!settings.enabled || !settings.autoSync || !settings.obsidianVaultId) return;
+
+ for (const listId of listIds) {
+ const result = await ideaLoomObsidian.exportToObsidian({ listId });
+ const problems = ['conflicted', 'missing', 'malformed', 'unavailable', 'failed']
+ .reduce((total, key) => total + (result[key] || 0), 0);
+ if (problems) console.warn(`⚠️ IdeaLoom auto-sync left ${problems} unresolved outcome(s) for list ${listId}`);
+ }
+};
+
+/**
+ * Queue a debounced automatic export of one list.
+ *
+ * Safe to call on every save: repeat calls inside the debounce window collapse
+ * into one run, and the whole run is a no-op while the toggles are off.
+ */
+export function scheduleAutoSync(listId, { delayMs = AUTO_SYNC_DEBOUNCE_MS } = {}) {
+ if (!listId) return;
+ pending.add(listId);
+ if (timer) clearTimeout(timer);
+ timer = setTimeout(() => {
+ timer = null;
+ // This fires outside the Express request lifecycle, so an unhandled throw
+ // here would take down the process instead of reaching error middleware.
+ queue = queue
+ .then(runPending)
+ .catch((error) => console.error(`❌ IdeaLoom auto-sync failed: ${error.message}`));
+ }, delayMs);
+ timer.unref?.();
+}
+
+/** Await any queued automatic export — used by tests and shutdown paths. */
+export async function flushAutoSync() {
+ if (timer) {
+ clearTimeout(timer);
+ timer = null;
+ queue = queue
+ .then(runPending)
+ .catch((error) => console.error(`❌ IdeaLoom auto-sync failed: ${error.message}`));
+ }
+ await queue;
+}
diff --git a/server/services/idealoomAutoSync.test.js b/server/services/idealoomAutoSync.test.js
new file mode 100644
index 0000000000..5afbd21dd5
--- /dev/null
+++ b/server/services/idealoomAutoSync.test.js
@@ -0,0 +1,104 @@
+import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest';
+
+vi.mock('./idealoomLists.js', () => ({ getSettings: vi.fn() }));
+vi.mock('./idealoomObsidian.js', () => ({ exportToObsidian: vi.fn() }));
+
+import * as lists from './idealoomLists.js';
+import * as exchange from './idealoomObsidian.js';
+import { AUTO_SYNC_DEBOUNCE_MS, flushAutoSync, scheduleAutoSync } from './idealoomAutoSync.js';
+
+const LIST_ID = 'f1c2d3e4-5678-4abc-9def-0123456789ab';
+const OTHER_ID = '0a1b2c3d-4e5f-4a6b-8c7d-8e9f0a1b2c3d';
+const clean = () => ({ imported: 0, exported: 1, skipped: 0, conflicted: 0, missing: 0, malformed: 0, unavailable: 0, failed: 0 });
+
+// Real time is never awaited here: the debounce is driven with fake timers so
+// the contract is tested without a production sleep in the suite.
+const settle = async () => {
+ await vi.advanceTimersByTimeAsync(AUTO_SYNC_DEBOUNCE_MS);
+ await flushAutoSync();
+};
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ vi.clearAllMocks();
+ lists.getSettings.mockResolvedValue({ enabled: true, autoSync: true, obsidianVaultId: 'vault-1' });
+ exchange.exportToObsidian.mockResolvedValue(clean());
+});
+
+afterEach(async () => {
+ await flushAutoSync();
+ vi.useRealTimers();
+});
+
+describe('IdeaLoom automatic sync', () => {
+ it('debounces a burst of edits into one export per list', async () => {
+ scheduleAutoSync(LIST_ID);
+ scheduleAutoSync(LIST_ID);
+ scheduleAutoSync(OTHER_ID);
+ expect(exchange.exportToObsidian).not.toHaveBeenCalled();
+
+ await settle();
+
+ expect(exchange.exportToObsidian).toHaveBeenCalledTimes(2);
+ expect(exchange.exportToObsidian).toHaveBeenCalledWith({ listId: LIST_ID });
+ expect(exchange.exportToObsidian).toHaveBeenCalledWith({ listId: OTHER_ID });
+ });
+
+ it('never asks the exchange to recreate a deleted note', async () => {
+ scheduleAutoSync(LIST_ID);
+ await settle();
+
+ // recreateMissing is absent, so the export defaults to fail-closed and a
+ // note the user deleted comes back as `missing` rather than reappearing.
+ expect(exchange.exportToObsidian).toHaveBeenCalledWith({ listId: LIST_ID });
+ expect(exchange.exportToObsidian.mock.calls[0][0]).not.toHaveProperty('recreateMissing');
+ });
+
+ it.each([
+ ['auto-sync off', { enabled: true, autoSync: false, obsidianVaultId: 'vault-1' }],
+ ['integration disabled', { enabled: false, autoSync: true, obsidianVaultId: 'vault-1' }],
+ ['no vault configured', { enabled: true, autoSync: true, obsidianVaultId: null }],
+ ])('writes nothing when %s', async (_label, settings) => {
+ lists.getSettings.mockResolvedValue(settings);
+
+ scheduleAutoSync(LIST_ID);
+ await settle();
+
+ expect(exchange.exportToObsidian).not.toHaveBeenCalled();
+ });
+
+ it('re-reads the toggles at fire time, so turning auto-sync off cancels queued work', async () => {
+ scheduleAutoSync(LIST_ID);
+ lists.getSettings.mockResolvedValue({ enabled: true, autoSync: false, obsidianVaultId: 'vault-1' });
+
+ await settle();
+
+ expect(exchange.exportToObsidian).not.toHaveBeenCalled();
+ });
+
+ it('keeps running after a failed export instead of crashing the process', async () => {
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+ exchange.exportToObsidian.mockRejectedValueOnce(new Error('vault offline'));
+
+ scheduleAutoSync(LIST_ID);
+ await settle();
+ expect(consoleError).toHaveBeenCalledWith(expect.stringContaining('vault offline'));
+
+ exchange.exportToObsidian.mockResolvedValue(clean());
+ scheduleAutoSync(OTHER_ID);
+ await settle();
+ expect(exchange.exportToObsidian).toHaveBeenLastCalledWith({ listId: OTHER_ID });
+ consoleError.mockRestore();
+ });
+
+ it('warns rather than silently swallowing an unresolved outcome', async () => {
+ const consoleWarn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ exchange.exportToObsidian.mockResolvedValue({ ...clean(), exported: 0, conflicted: 1 });
+
+ scheduleAutoSync(LIST_ID);
+ await settle();
+
+ expect(consoleWarn).toHaveBeenCalledWith(expect.stringContaining(LIST_ID));
+ consoleWarn.mockRestore();
+ });
+});
diff --git a/server/services/idealoomObsidian.js b/server/services/idealoomObsidian.js
index 907d9345e1..8ece19333c 100644
--- a/server/services/idealoomObsidian.js
+++ b/server/services/idealoomObsidian.js
@@ -18,7 +18,7 @@ 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 RESULT_KEYS = ['imported', 'exported', 'skipped', 'conflicted', 'missing', 'malformed', 'unavailable', 'failed'];
const newResult = () => {
const counts = Object.fromEntries(RESULT_KEYS.map((key) => [key, 0]));
@@ -378,10 +378,31 @@ export async function importFromObsidian() {
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);
});
+ await reportDeletedNotes(exchange.vault.path, result);
return result;
}
-const writeNote = async (vaultId, notePath, content) => {
+/**
+ * Surface previously-exchanged lists whose vault note has been deleted.
+ *
+ * The deletion is REPORTED, never acted on: the local record is kept so the
+ * user can decide between deleting the list and recovering the note through an
+ * explicit sync. `existsSync` is the right probe rather than the scan result —
+ * an iCloud-evicted note is still a file on disk, and reporting an
+ * un-downloaded note as deleted would invite exactly the destructive recovery
+ * this outcome exists to gate.
+ */
+const reportDeletedNotes = async (vaultPath, result) => {
+ const lists = await ideaLoomLists.listLists();
+ lists.forEach((list) => {
+ const notePath = list.sync?.notePath;
+ if (!notePath || !list.sync?.lastKnownContentHash) return;
+ if (existsSync(join(vaultPath, notePath))) return;
+ addResult(result, 'missing', { id: list.id, path: notePath, reason: 'note-deleted-externally' });
+ });
+}
+
+const writeNote = async (vaultId, notePath, content, { allowCreate = true } = {}) => {
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 };
@@ -390,18 +411,31 @@ const writeNote = async (vaultId, notePath, content) => {
return { kind: 'existing', id: parsedExisting.list.id, content: existing.content };
}
if (existing?.content) return { kind: 'existing', id: null };
+ // The note is absent. Writing it is a CREATE, which the caller must opt into:
+ // for a list that has already been exchanged, absence means the user deleted
+ // the note, and recreating it would resurrect data they removed on purpose.
+ if (!allowCreate) return { kind: 'missing', reason: 'note-deleted-externally' };
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) => {
+/**
+ * Export one local list, preserving an imported note path forever.
+ *
+ * `recreateMissing` is the explicit, user-directed recovery switch. Without it
+ * a list whose note has been deleted in the vault reports `missing` and writes
+ * nothing — automatic sync must never resurrect a note the user removed.
+ */
+const exportOne = async (vaultId, list, { recreateMissing = false } = {}) => {
const content = renderIdeaLoomMarkdown(list);
const importedPath = list.sync?.notePath;
+ const previouslyExchanged = Boolean(importedPath && list.sync?.lastKnownContentHash);
+ const allowCreate = !previouslyExchanged || recreateMissing;
let notePath = importedPath || generatedNotePath(list);
- let pathResult = await writeNote(vaultId, notePath, content);
+ let pathResult = await writeNote(vaultId, notePath, content, { allowCreate });
+ if (pathResult.kind === 'missing') return { ...pathResult, id: list.id, notePath };
if (!importedPath && pathResult.kind === 'existing' && pathResult.id !== list.id) {
let suffix = `-${list.id.slice(0, 8)}`;
notePath = generatedNotePath(list, suffix);
@@ -413,6 +447,12 @@ const exportOne = async (vaultId, list) => {
const localChanged = hasLocalChanges(list);
if (remoteChanged && localChanged) return { kind: 'conflicted', reason: 'both-sides-changed', notePath };
if (remoteChanged) return { kind: 'skipped', reason: 'external-change', notePath };
+ // The note already reads exactly as this list renders. Writing it anyway is
+ // what turns a just-imported list into an export, and that export into the
+ // next import's "changed" note — so a no-op write is skipped, not repeated.
+ if (hashContent(pathResult.content) === hashContent(content)) {
+ return { kind: 'skipped', reason: 'unchanged', notePath, id: list.id };
+ }
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 };
@@ -427,8 +467,14 @@ const exportOne = async (vaultId, list) => {
return { kind: 'exported', id: list.id, notePath };
};
-/** Explicitly export all lists, or one selected list, to the configured vault. */
-export async function exportToObsidian({ listId } = {}) {
+/**
+ * Explicitly export all lists, or one selected list, to the configured vault.
+ *
+ * Automatic sync calls this with the defaults, so it can never delete or
+ * recreate a vault note; `recreateMissing` is only ever set by an explicit
+ * user-directed recovery request.
+ */
+export async function exportToObsidian({ listId, recreateMissing = false } = {}) {
const exchange = await configuredExchange();
if (!exchange.vault) return withReason(exchange.result, exchange.reason);
const result = newResult();
@@ -441,7 +487,7 @@ export async function exportToObsidian({ listId } = {}) {
// Path allocation checks the vault before writing. Keep exports sequential so
// two lists with the same generated date/title cannot choose the same path.
for (const list of selected) {
- const [entry] = await Promise.allSettled([exportOne(exchange.settings.obsidianVaultId, list)]);
+ const [entry] = await Promise.allSettled([exportOne(exchange.settings.obsidianVaultId, list, { recreateMissing })]);
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 });
diff --git a/server/services/idealoomObsidian.test.js b/server/services/idealoomObsidian.test.js
index 1cd578895c..a771a13470 100644
--- a/server/services/idealoomObsidian.test.js
+++ b/server/services/idealoomObsidian.test.js
@@ -217,6 +217,10 @@ describe('IdeaLoom Obsidian exchange', () => {
const importedList = list({ id: '0a1b2c3d-4e5f-4a6b-8c7d-8e9f0a1b2c3d' });
lists.listLists.mockResolvedValue([local, {
...importedList,
+ // Edited locally since the last exchange, so this is a real export rather
+ // than the no-op an unchanged list would be skipped for.
+ ideas: ['First idea', 'Second idea', 'Third idea'],
+ updatedAt: '2026-08-29T13:00:00.000Z',
sync: {
notePath: importedPath,
lastKnownContentHash: createHash('sha256').update(renderIdeaLoomMarkdown(importedList), 'utf8').digest('hex'),
@@ -254,4 +258,67 @@ describe('IdeaLoom Obsidian exchange', () => {
expect(result.counts).toMatchObject({ conflicted: 1, exported: 0 });
expect(obsidian.updateNote).not.toHaveBeenCalled();
});
+
+ it('reports an externally deleted note as missing instead of recreating it', async () => {
+ const notePath = 'Idea Loom/2026-01-01-original-name.md';
+ const synced = list({
+ sync: {
+ notePath,
+ lastKnownContentHash: createHash('sha256').update(renderIdeaLoomMarkdown(list()), 'utf8').digest('hex'),
+ lastImportedAt: '2026-08-29T11:00:00.000Z',
+ },
+ });
+ lists.listLists.mockResolvedValue([synced]);
+ obsidian.getNote.mockResolvedValue({ error: 'NOTE_NOT_FOUND' });
+
+ const automatic = await exportToObsidian();
+
+ expect(automatic.counts).toMatchObject({ missing: 1, exported: 0 });
+ expect(automatic.details.missing[0]).toMatchObject({ id: LIST_ID, notePath, reason: 'note-deleted-externally' });
+ expect(obsidian.createNote).not.toHaveBeenCalled();
+ expect(obsidian.updateNote).not.toHaveBeenCalled();
+
+ obsidian.createNote.mockResolvedValue({ path: notePath });
+ const recovered = await exportToObsidian({ recreateMissing: true });
+
+ expect(recovered.counts).toMatchObject({ missing: 0, exported: 1 });
+ expect(obsidian.createNote).toHaveBeenCalledWith(VAULT_ID, notePath, expect.stringContaining('1. First idea'));
+ });
+
+ it('surfaces a deleted note on import without dropping the local list', async () => {
+ const notePath = 'Idea Loom/2026-01-01-original-name.md';
+ lists.listLists.mockResolvedValue([list({
+ sync: {
+ notePath,
+ lastKnownContentHash: 'stale-hash',
+ lastImportedAt: '2026-08-29T11:00:00.000Z',
+ },
+ })]);
+
+ const result = await importFromObsidian();
+
+ expect(result.counts).toMatchObject({ missing: 1, imported: 0 });
+ expect(result.details.missing[0]).toMatchObject({ id: LIST_ID, path: notePath });
+ });
+
+ it('does not rewrite a note that already matches the list (no import/export loop)', async () => {
+ const notePath = 'Idea Loom/2026-01-01-original-name.md';
+ const content = renderIdeaLoomMarkdown(list());
+ lists.listLists.mockResolvedValue([list({
+ sync: {
+ notePath,
+ // The hash the importer stored, so nothing looks externally changed.
+ lastKnownContentHash: createHash('sha256').update(content, 'utf8').digest('hex'),
+ lastImportedAt: '2026-08-29T12:00:00.000Z',
+ },
+ })]);
+ obsidian.getNote.mockResolvedValue({ content });
+
+ const result = await exportToObsidian();
+
+ expect(result.counts).toMatchObject({ exported: 0, skipped: 1, conflicted: 0 });
+ expect(result.details.skipped[0]).toMatchObject({ reason: 'unchanged' });
+ expect(obsidian.updateNote).not.toHaveBeenCalled();
+ expect(obsidian.createNote).not.toHaveBeenCalled();
+ });
});