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([issue-3706]): keep the ingest note pointer and bound the daily-log resync

[._.]/ Adam Eivy4a1da8c2f832
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index f8cc10fb9e..5732360cee 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -8,6 +8,10 @@
- **[issue-3706] Saving a note that iCloud has offloaded no longer risks freezing the UI.** [issue-3704] stopped offloaded files from stalling PortOS when they were *read*, but saving over one was still unguarded — and measuring it showed that overwriting an offloaded note stalls exactly like reading it, even though the save replaces every byte of the file. That matters more than a manual save: your Brain daily-log mirror and YouTube transcript ingest write notes on their own schedule, so a stuck iCloud could have frozen every page with nobody at the keyboard. PortOS now checks before saving, asks iCloud for the note and waits briefly, and if it still hasn't arrived reports "temporarily unavailable" for that one note — leaving its existing contents untouched — instead of hanging. Background mirrors skip that note quietly and pick it up on their next pass.
+- **[issue-3706] Re-ingesting a YouTube video no longer loses track of its existing vault note.** If the note had been offloaded by iCloud, the mirror was skipped — and the skip was recorded as "this video has no note", which stranded the existing note where deleting the ingest could never clean it up, and made the next re-ingest create a second note at a fresh date. A skipped mirror now keeps the existing note's location and simply retries next time.
+
+- **[issue-3706] "Re-sync all entries now" stops early when the vault is unavailable instead of grinding for hours.** With a stuck iCloud, every entry waited up to 20 seconds before being skipped, so a full re-sync of a long daily-log history could run for hours with no way to cancel it. It now stops after a run of consecutive failures and reports that it stopped, so you get an answer in seconds and can fix the vault first.
+
- Internal: [issue-3706] the awaited `brctl download` used before an overwrite moved out of `mortalLoomStore` into the shared `icloudFile.materializeAndWait`, now that Obsidian's `updateNote` needs the identical bounded materialize — the second caller is what earned the extraction. It also no longer throws when `spawn` fails synchronously (EMFILE under load), which would otherwise surface from a save as a raw spawn error instead of the handled refusal. The module docblock gained a measured syscall table — `stat`/`open`/`rename` never materialize a dataless file, while `read`, `write` (including after `O_TRUNC` — truncating does **not** skip the download), `link`, and `clonefile` all do — so the next reader doesn't re-derive it from first principles and reach the intuitive, wrong conclusion.
- Internal: [issue-3705] the MortalLoom store's boot/settings-change eviction pin no longer carries its own copy of the `brctl download` spawn/detach/exit-handler plumbing — it now delegates to the shared `icloudFile.requestMaterialization` helper the read paths already use. The helper gained an explicit dedupe policy (`retryAfterExit`): the read paths stay tracked in its capped in-flight map so a later read can retry, while the pin opts out and keeps its own single-sticky-path dedupe (re-pin only when the configured path changes) plus an `onFailure` hook that clears the sticky path so a failed or killed pin can retry. The once-per-process "brctl not found on PATH" warning also folded into the shared flag, so it fires at most once across the pin, read, and write paths rather than once per caller. ~40 lines of duplicated spawn plumbing removed. Two small, deliberate behavior changes come with the consolidation: the pin now inherits the shared 120s download deadline (a wedged boot pin is SIGKILL'd and left to the next `settings:updated` to retry, instead of lingering unref'd forever), and it now only spawns `brctl` for genuine iCloud (`/Library/Mobile Documents/`) paths rather than any macOS path — the pin exists solely for the iCloud store, so a non-iCloud configured path is no longer handed a doomed `brctl download`.
diff --git a/server/services/brainJournal.js b/server/services/brainJournal.js
index 2d76552780..1593544d62 100644
--- a/server/services/brainJournal.js
+++ b/server/services/brainJournal.js
@@ -469,6 +469,10 @@ async function removeFromObsidian(entry) {
* vault. Used when the user first points the daily log at a vault or changes
* which vault it targets.
*/
+// Consecutive failed upserts that mean "the vault is gone", not "this entry is odd".
+// Sized so an ordinary transient blip cannot trip it but a systemic outage does.
+const MAX_CONSECUTIVE_RESYNC_SKIPS = 25;
+
export async function resyncAllToObsidian() {
const settings = await getSettings();
if (!settings.obsidianVaultId) return { synced: 0, skipped: 0 };
@@ -476,13 +480,33 @@ export async function resyncAllToObsidian() {
const { records } = await listJournals({ limit: 10000, includeContent: true });
let synced = 0;
let skipped = 0;
+ let consecutiveSkips = 0;
+ let stoppedEarly = false;
for (const entry of records) {
// force:true so this bulk resync still writes even when the user has
// turned off the per-write autoSync — they explicitly clicked "Re-sync
// all entries now", which is the manual-sync escape hatch.
const path = await syncToObsidian(entry, { force: true }).catch(() => null);
- if (path) synced += 1;
- else skipped += 1;
+ if (path) {
+ synced += 1;
+ consecutiveSkips = 0;
+ continue;
+ }
+ skipped += 1;
+ consecutiveSkips += 1;
+ // Circuit breaker. This is a FOREGROUND request over up to 10,000 entries,
+ // and an evicted note now costs up to MATERIALIZE_TIMEOUT_MS (20s) before it
+ // is refused (#3706) — so a wedged iCloud or an unplugged vault would turn
+ // "Re-sync all entries now" into a multi-hour request the user cannot cancel.
+ // A run of failures means the VAULT is unavailable, not that one entry is
+ // odd: inside this loop a null is always a failed upsert (the vault is
+ // configured, and force:true bypasses the autoSync check), so there is no
+ // legitimate run of skips to confuse it with. Stop and report instead.
+ if (consecutiveSkips >= MAX_CONSECUTIVE_RESYNC_SKIPS) {
+ stoppedEarly = true;
+ console.warn(`⚠️ Daily-log resync stopped after ${consecutiveSkips} consecutive failures — vault unavailable?`);
+ break;
+ }
}
- return { synced, skipped };
+ return { synced, skipped, stoppedEarly };
}
diff --git a/server/services/brainJournal.test.js b/server/services/brainJournal.test.js
index b09f378abd..2b797dc918 100644
--- a/server/services/brainJournal.test.js
+++ b/server/services/brainJournal.test.js
@@ -334,4 +334,53 @@ describe('brainJournal', () => {
expect(callOrder).toEqual(['start-1', 'end-1', 'start-2', 'end-2']);
});
});
+
+ /**
+ * #3706 fallout: an evicted note now costs up to MATERIALIZE_TIMEOUT_MS (20s)
+ * before upsertNote refuses it, and this bulk resync is a FOREGROUND request
+ * over up to 10,000 entries — so an unavailable vault must not turn "Re-sync
+ * all entries now" into a multi-hour request nobody can cancel.
+ */
+ describe('resyncAllToObsidian — circuit breaker', () => {
+ // Valid consecutive calendar dates (a bare day counter would mint 2026-03-32).
+ const isoDay = (i) => new Date(Date.UTC(2026, 0, 1 + i)).toISOString().slice(0, 10);
+
+ beforeEach(async () => {
+ // autoSync:false while seeding — appendJournal fires its OWN fire-and-forget
+ // mirror per entry, which would double the call count. resyncAllToObsidian
+ // passes force:true, so it still runs.
+ await journal.updateSettings({ obsidianVaultId: 'v1', autoSync: false, obsidianFolder: 'Daily Log' });
+ });
+
+ it('stops after a run of consecutive failures instead of grinding through every entry', async () => {
+ for (let i = 0; i < 40; i += 1) await journal.appendJournal(isoDay(i), `day ${i}`);
+ obsidian.upsertNote.mockClear();
+ obsidian.upsertNote.mockResolvedValue(null); // vault unavailable for every entry
+
+ const stats = await journal.resyncAllToObsidian();
+
+ expect(stats.stoppedEarly).toBe(true);
+ // Bailed at the threshold rather than attempting all 40.
+ expect(obsidian.upsertNote).toHaveBeenCalledTimes(25);
+ expect(stats.synced).toBe(0);
+ });
+
+ it('does not trip on scattered failures among successes', async () => {
+ for (let i = 0; i < 30; i += 1) await journal.appendJournal(isoDay(i), `day ${i}`);
+ // Every third entry fails — never 25 in a row, so the run must complete.
+ obsidian.upsertNote.mockClear();
+ let n = 0;
+ obsidian.upsertNote.mockImplementation(async () => {
+ n += 1;
+ return n % 3 === 0 ? null : 'Daily Log/note.md';
+ });
+
+ const stats = await journal.resyncAllToObsidian();
+
+ expect(stats.stoppedEarly).toBe(false);
+ expect(obsidian.upsertNote).toHaveBeenCalledTimes(30);
+ expect(stats.synced + stats.skipped).toBe(30);
+ });
+ });
+
});
diff --git a/server/services/obsidian.js b/server/services/obsidian.js
index 6772faa617..5296c78485 100644
--- a/server/services/obsidian.js
+++ b/server/services/obsidian.js
@@ -324,11 +324,19 @@ export async function createNote(vaultId, notePath, content = '') {
return { error: 'NOTE_EXISTS', message: 'A note with this name already exists' };
}
- // No eviction guard here, deliberately (#3706): the `existsSync` above means
- // this only ever writes a file that does NOT exist, and a file that does not
- // exist cannot be dataless — there is nothing offloaded to materialize. The
- // overwrite case is `updateNote`, which is guarded. Don't add a screen here
+ // No dataless screen here, deliberately (#3706): the `existsSync` above means
+ // this only ever writes a file that does NOT exist, and a path with no file at
+ // it cannot be a dataless vnode — there is nothing offloaded to materialize.
+ // The overwrite case is `updateNote`, which is guarded. Don't add a screen here
// "for symmetry"; it would cost a stat per created note and can never fire.
+ //
+ // This covers the modern APFS representation only. The LEGACY representation —
+ // an evicted file replaced by a sibling `.<name>.md.icloud` placeholder, which
+ // `mortalLoomStore` still checks for (`icloudPlaceholderPath`) — is NOT handled:
+ // `existsSync(fullPath)` is false for a placeholder-shadowed note, so this
+ // creates a fresh file beside the placeholder rather than refusing. Tracked
+ // separately; it predates #3706 and needs its own decision about whether vaults
+ // ever see placeholders on current macOS.
await writeFile(fullPath, content, 'utf-8');
console.log(`📓 Created note: ${notePath} in vault ${vault.name}`);
return await getNote(vaultId, notePath, { includeBacklinks: false });
diff --git a/server/services/youtubeIngest.js b/server/services/youtubeIngest.js
index b832b320b3..33b083226d 100644
--- a/server/services/youtubeIngest.js
+++ b/server/services/youtubeIngest.js
@@ -159,6 +159,31 @@ async function loadIndex() {
// everything.
const NEW_INGEST = { transcript: null, obsidian: null, video: null, audio: null, taskId: null, agentPrompt: null, incomplete: null };
+/**
+ * Decide what the ingest index should record for the Obsidian mirror.
+ *
+ * `putIngest` MERGES (`{...existing, ...patch}`), so writing an explicit
+ * `obsidian: null` erases `prior.obsidian.path` — stranding the existing note
+ * where `deleteIngest` can never unlink it, and letting the next re-ingest mint a
+ * second note at a fresh dated path. That is exactly the orphan the note-path
+ * reuse in `runIngest` exists to prevent.
+ *
+ * So a mirror that was ATTEMPTED and FAILED keeps the old pointer. This became
+ * reachable when `updateNote` gained a TRANSIENT failure (NOTE_EVICTED, #3706):
+ * a note iCloud has offloaded is refused, and `upsertNote` reports that as the
+ * same `null` a hard failure gives — so without this, one evicted note would
+ * silently orphan itself on the next ingest.
+ *
+ * Nulling out is still correct when no mirror was attempted at all (no vault
+ * configured / autoSync off): there is no attempt whose failure we'd be papering
+ * over, and an explicit null is the honest record.
+ */
+export function resolveObsidianPointer({ written, vaultId, notePath, prior }) {
+ if (written) return { path: written, vaultId };
+ if (notePath && prior?.obsidian) return prior.obsidian;
+ return null;
+}
+
async function putIngest(videoId, patch) {
return indexMutex(async () => {
const index = await loadIndex();
@@ -658,7 +683,7 @@ export async function startYoutubeIngest({
? await obsidian.upsertNote(vaultId, notePath, markdown)
.catch((err) => { console.error(`📓 Obsidian sync failed for ${meta.videoId}: ${err.message}`); return null; })
: null;
- if (written) landed.obsidian = { path: written, vaultId };
+ landed.obsidian = resolveObsidianPointer({ written, vaultId, notePath, prior });
}
} else {
// Not fatal — the user still gets the link record, the activity event,
diff --git a/server/services/youtubeIngest.test.js b/server/services/youtubeIngest.test.js
index 03edece931..23dd13263c 100644
--- a/server/services/youtubeIngest.test.js
+++ b/server/services/youtubeIngest.test.js
@@ -19,6 +19,7 @@ import {
buildIngestNote,
buildAgentTaskContext,
cancelYoutubeIngest,
+ resolveObsidianPointer,
__testing,
} from './youtubeIngest.js';
@@ -258,3 +259,40 @@ describe('buildIngestNote frontmatter safety', () => {
expect(note).toContain('title: "Storytelling: the eight principles"');
});
});
+
+/**
+ * The index records ONE note location per video, and putIngest MERGES — so an
+ * explicit `obsidian: null` erases the prior pointer and strands the note where
+ * deleteIngest can never unlink it. #3706 made that reachable on a healthy vault
+ * by giving updateNote a transient failure (an iCloud-evicted note is refused,
+ * which upsertNote reports as the same null a hard failure gives).
+ */
+describe('resolveObsidianPointer', () => {
+ const prior = { obsidian: { path: 'Consumed/YouTube/2026-01-15 talk.md', vaultId: 'v1' } };
+
+ it('records the new location when the mirror succeeded', () => {
+ expect(resolveObsidianPointer({
+ written: 'Consumed/YouTube/2026-03-01 talk.md', vaultId: 'v1', notePath: 'x.md', prior,
+ })).toEqual({ path: 'Consumed/YouTube/2026-03-01 talk.md', vaultId: 'v1' });
+ });
+
+ it('KEEPS the prior pointer when an attempted mirror failed', () => {
+ // The evicted-note case: without this the existing note is orphaned and the
+ // next re-ingest mints a second note at a fresh dated path.
+ expect(resolveObsidianPointer({
+ written: null, vaultId: 'v1', notePath: 'Consumed/YouTube/2026-01-15 talk.md', prior,
+ })).toEqual(prior.obsidian);
+ });
+
+ it('nulls out when NO mirror was attempted (no vault configured)', () => {
+ // notePath null means we never tried — an explicit null is the honest record,
+ // not a failure being papered over.
+ expect(resolveObsidianPointer({ written: null, vaultId: null, notePath: null, prior })).toBeNull();
+ });
+
+ it('nulls out when an attempt failed and there is no prior pointer to keep', () => {
+ expect(resolveObsidianPointer({
+ written: null, vaultId: 'v1', notePath: 'x.md', prior: null,
+ })).toBeNull();
+ });
+});