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: retry STALE_JOURNAL merges a few times before failing save

[._.]/ Adam Eivy91fc64eddf17
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 0d3566719f..dda9575b5d 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,7 +2,7 @@
## Changed
-- **Daily Log no longer parks autosave when voice dictation lands mid-edit.** A spoken segment is merged into the textarea (append-at-end, caret restored) instead of leaving the user to Save or refresh, and full-content saves send the last-seen `updatedAt` as `ifMatchUpdatedAt`. When a concurrent append advances that clock, the server returns 409 `STALE_JOURNAL` with the current entry; the client folds in any missing voice segments and retries once so an in-flight PUT cannot silently drop dictation.
+- **Daily Log no longer parks autosave when voice dictation lands mid-edit.** A spoken segment is merged into the textarea (append-at-end, caret restored) instead of leaving the user to Save or refresh, and full-content saves send the last-seen `updatedAt` as `ifMatchUpdatedAt`. When a concurrent append advances that clock, the server returns 409 `STALE_JOURNAL` with the current entry in `context.entry`; the client folds in any missing voice segments and retries a few times so an in-flight PUT cannot silently drop dictation.
- **Series Autopilot can learn which models actually work at each step.** AI run history now distinguishes technical completion from a later editorial keep/revert decision and aggregates evidence by orchestration step, creative-versus-judge role, provider, model, and reasoning effort. The new opt-in selector requires multiple quality-reviewed samples plus a positive reliability threshold, ignores disabled providers and removed models, and remains a soft default beneath explicit run choices and exact prompt-stage pins. The Options panel reports how much attributed and quality-reviewed evidence exists, while local APIs expose the full metrics and allow an operator to correct or backfill a historical outcome, including its effort when the older run predates effort telemetry. Concurrent metadata updates for one run are serialized so provider telemetry cannot overwrite its Autopilot step/role attribution, and internal structure-verification calls retain the judge role instead of inheriting their repairer's creative role. Foundation judges record contract-valid responses separately from true editorial approval, and foundation repairs automatically record accepted versus rolled-back outcomes, so a model that finishes a long run but makes the story worse is not learned as a success.
diff --git a/client/src/components/brain/tabs/DailyLogTab.jsx b/client/src/components/brain/tabs/DailyLogTab.jsx
index 256086bb80..53c8fd2a3a 100644
--- a/client/src/components/brain/tabs/DailyLogTab.jsx
+++ b/client/src/components/brain/tabs/DailyLogTab.jsx
@@ -68,9 +68,10 @@ export const appendJournalSegment = (content, text) => {
// Re-apply any voice segments the server holds that the local body is missing
// — the recovery path after a STALE_JOURNAL 409 (an append landed while a PUT
-// was in flight). Non-voice concurrent edits are left to the server entry's
-// content only when local is empty; otherwise local typing wins and voice is
-// folded back in.
+// was in flight). Only `source === 'voice'` segments are folded in: concurrent
+// typed/edit segments are already reflected in server content, and replaying
+// them would duplicate free-form edits. When local is empty we fall back to
+// the server body wholesale so a blank client still adopts remote state.
export const mergeMissingVoiceSegments = (localContent, serverEntry) => {
let next = localContent || '';
const segs = Array.isArray(serverEntry?.segments) ? serverEntry.segments : [];
@@ -83,6 +84,12 @@ export const mergeMissingVoiceSegments = (localContent, serverEntry) => {
return next;
};
+// Max PUT attempts per save (1 initial + retries). Each STALE_JOURNAL folds in
+// voice segments the concurrent write added and advances the ifMatch clock.
+// Cap is small: voice bursts are short, and the next autosave tick retries
+// whatever is still dirty if we exhaust the budget mid-burst.
+const STALE_JOURNAL_MAX_ATTEMPTS = 3;
+
export default function DailyLogTab() {
const [date, setDate] = useState(localToday());
// Backend today — resolved via GET /daily-log/today on mount so the
@@ -259,7 +266,15 @@ export default function DailyLogTab() {
setContent((prevContent) => {
const next = appendJournalSegment(prevContent, appendedText);
const el = editorRef.current;
- if (el && document.activeElement === el && next !== prevContent) {
+ // Only restore caret when the control is focused and reports a real
+ // selection (detached/non-textarea nodes leave selectionStart undefined).
+ if (
+ el
+ && document.activeElement === el
+ && next !== prevContent
+ && typeof el.selectionStart === 'number'
+ && typeof el.selectionEnd === 'number'
+ ) {
const start = el.selectionStart;
const end = el.selectionEnd;
queueMicrotask(() => {
@@ -356,11 +371,15 @@ export default function DailyLogTab() {
// against an already-unhealthy server.
firstDirtyAtRef.current = null;
setSaving(true);
- let res = await putDailyLog(targetDate, body, ifMatch);
- // One bounded retry: merge any voice segments the concurrent write added,
- // advance the ifMatch clock, and re-PUT. A second conflict (another append
- // mid-retry) falls through as failure — the next autosave tick retries.
- if (res?.stale) {
+ // Bounded stale-retry loop: each 409 folds in voice segments the concurrent
+ // write added, advances the ifMatch clock, and re-PUTs. Exhausting the
+ // budget falls through as failure — content stays dirty so the next
+ // autosave tick (or explicit Save) retries with a fresh clock.
+ let res = null;
+ for (let attempt = 0; attempt < STALE_JOURNAL_MAX_ATTEMPTS; attempt += 1) {
+ res = await putDailyLog(targetDate, body, ifMatch);
+ if (!res?.stale) break;
+ if (attempt === STALE_JOURNAL_MAX_ATTEMPTS - 1) break;
const serverEntry = res.entry;
body = mergeMissingVoiceSegments(body, serverEntry);
ifMatch = serverEntry.updatedAt || null;
@@ -373,7 +392,6 @@ export default function DailyLogTab() {
? body
: mergeMissingVoiceSegments(prev, serverEntry)));
}
- res = await putDailyLog(targetDate, body, ifMatch);
}
savingRef.current = false;
if (!mountedRef.current) return;
diff --git a/client/src/components/brain/tabs/DailyLogTab.test.jsx b/client/src/components/brain/tabs/DailyLogTab.test.jsx
index 64e67158fa..d041f749ef 100644
--- a/client/src/components/brain/tabs/DailyLogTab.test.jsx
+++ b/client/src/components/brain/tabs/DailyLogTab.test.jsx
@@ -428,6 +428,75 @@ describe('DailyLogTab autosave', () => {
expect(editor().value).toBe('typed while speaking\n\nspoken mid-flight');
});
+ it('retries multiple STALE_JOURNAL 409s until a PUT lands', async () => {
+ const stale1 = {
+ date: TODAY,
+ content: 'existing\n\nspoken-a',
+ segments: [
+ { text: 'existing', at: `${TODAY}T12:00:00Z`, source: 'edit' },
+ { text: 'spoken-a', at: `${TODAY}T12:02:00Z`, source: 'voice' },
+ ],
+ segmentCount: 2,
+ updatedAt: `${TODAY}T12:02:00Z`,
+ obsidianPath: null,
+ };
+ const stale2 = {
+ date: TODAY,
+ content: 'existing\n\nspoken-a\n\nspoken-b',
+ segments: [
+ ...stale1.segments,
+ { text: 'spoken-b', at: `${TODAY}T12:03:00Z`, source: 'voice' },
+ ],
+ segmentCount: 3,
+ updatedAt: `${TODAY}T12:03:00Z`,
+ obsidianPath: null,
+ };
+ let calls = 0;
+ api.updateDailyLog.mockImplementation(async (date, content, _opts) => {
+ calls += 1;
+ if (calls === 1) {
+ const err = new Error('Daily log was modified since you last loaded it');
+ err.code = 'STALE_JOURNAL';
+ err.status = 409;
+ err.context = { entry: stale1 };
+ throw err;
+ }
+ if (calls === 2) {
+ const err = new Error('Daily log was modified since you last loaded it');
+ err.code = 'STALE_JOURNAL';
+ err.status = 409;
+ err.context = { entry: stale2 };
+ throw err;
+ }
+ return {
+ date,
+ entry: { ...entryFor(date, content), updatedAt: `${date}T12:04:00Z` },
+ };
+ });
+ await renderTab();
+ fireEvent.change(editor(), { target: { value: 'typed while speaking' } });
+ await act(async () => { await vi.advanceTimersByTimeAsync(1600); });
+
+ expect(api.updateDailyLog).toHaveBeenCalledTimes(3);
+ expect(api.updateDailyLog.mock.calls[0]).toEqual([
+ TODAY,
+ 'typed while speaking',
+ { silent: true, ifMatchUpdatedAt: `${TODAY}T12:00:00Z` },
+ ]);
+ expect(api.updateDailyLog.mock.calls[1]).toEqual([
+ TODAY,
+ 'typed while speaking\n\nspoken-a',
+ { silent: true, ifMatchUpdatedAt: `${TODAY}T12:02:00Z` },
+ ]);
+ expect(api.updateDailyLog.mock.calls[2]).toEqual([
+ TODAY,
+ 'typed while speaking\n\nspoken-a\n\nspoken-b',
+ { silent: true, ifMatchUpdatedAt: `${TODAY}T12:03:00Z` },
+ ]);
+ expect(editor().value).toBe('typed while speaking\n\nspoken-a\n\nspoken-b');
+ expect(screen.queryByText(/Save failed/i)).not.toBeInTheDocument();
+ });
+
it('shows save status in the toolbar', async () => {
await renderTab();
expect(screen.getByText(/· Saved/)).toBeInTheDocument();
diff --git a/client/src/services/apiBrain.js b/client/src/services/apiBrain.js
index 0b57d4ad43..6b1f52af9a 100644
--- a/client/src/services/apiBrain.js
+++ b/client/src/services/apiBrain.js
@@ -302,10 +302,12 @@ export const appendDailyLog = (date, text, source = 'text', options = {}) => req
export const updateDailyLog = (date, content, options = {}) => {
// `ifMatchUpdatedAt` is an optimistic concurrency token (the entry's
// updatedAt the client last observed). It rides in the JSON body; the rest
- // of `options` (silent, headers, …) are request() fetch options.
+ // of `options` (silent, headers, …) are request() fetch options. Only a
+ // non-empty string is forwarded — anything else is treated as "no token"
+ // so the server force-writes (same as omitting the field).
const { ifMatchUpdatedAt, ...requestOptions } = options;
const body = { content };
- if (ifMatchUpdatedAt !== undefined && ifMatchUpdatedAt !== null) {
+ if (typeof ifMatchUpdatedAt === 'string' && ifMatchUpdatedAt.length > 0) {
body.ifMatchUpdatedAt = ifMatchUpdatedAt;
}
return request(
diff --git a/server/services/brainJournal.js b/server/services/brainJournal.js
index e472880128..9686db6abb 100644
--- a/server/services/brainJournal.js
+++ b/server/services/brainJournal.js
@@ -274,7 +274,11 @@ export async function setJournalContent(date, content, { ifMatchUpdatedAt } = {}
const existing = await getEntry(date);
// Precondition: a full rewrite based on a known updatedAt must not clobber
// a concurrent append (voice dictation is the common case — the client
- // autosave and the append share the same day key).
+ // autosave and the append share the same day key). When the on-disk entry
+ // has no `updatedAt` (pre-stamp legacy / hand-edited store), there is no
+ // clock to compare — accept the write rather than rejecting forever.
+ // brainStorage.upsertWithId always stamps updatedAt on new writes, so this
+ // path is an edge case, not the steady state.
if (
typeof ifMatchUpdatedAt === 'string'
&& ifMatchUpdatedAt.length > 0
diff --git a/server/services/brainJournal.test.js b/server/services/brainJournal.test.js
index f74b31433b..475c6a5ed4 100644
--- a/server/services/brainJournal.test.js
+++ b/server/services/brainJournal.test.js
@@ -81,7 +81,7 @@ vi.mock('./brainStorage.js', () => ({
}));
import * as journal from './brainJournal.js';
-import { brainEvents, getAll } from './brainStorage.js';
+import { brainEvents, getAll, getById } from './brainStorage.js';
import * as obsidian from './obsidian.js';
// Pull the payload of the last emit of `name`, or undefined if it never fired.
@@ -258,6 +258,22 @@ describe('brainJournal', () => {
const forced = await journal.setJournalContent('2026-04-17', 'overwrite all');
expect(forced.content).toBe('overwrite all');
});
+
+ it('accepts a rewrite when the on-disk entry has no updatedAt to compare', async () => {
+ // Legacy / hand-edited stores may lack a clock. Rejecting forever would
+ // trap the day; accept the write when there is nothing to precondition on.
+ getById.mockResolvedValueOnce({
+ id: '2026-04-17',
+ date: '2026-04-17',
+ content: 'legacy body',
+ segments: [{ text: 'legacy body', at: '2026-04-17T10:00:00.000Z', source: 'edit' }],
+ // deliberately no updatedAt
+ });
+ const next = await journal.setJournalContent('2026-04-17', 'recovered', {
+ ifMatchUpdatedAt: '2026-04-17T12:00:00.000Z',
+ });
+ expect(next.content).toBe('recovered');
+ });
});
describe('deleteJournal', () => {