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
Apply manuscript fix batches atomically
[._.]/ Adam Eivy50a849f37a4d
diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.jsindex 42e55e36f0..c0721459a5 100644--- a/server/services/pipeline/issues.js+++ b/server/services/pipeline/issues.js@@ -909,6 +909,68 @@ export function updateStage(issueId, stageId, patch = {}) {return updateStageWithLatest(issueId, stageId, () => patch);}+function mergeStagePatch(currentStage, stageId, patch, { snapshotPrior = false } = {}) {+ const isVisual = VISUAL_STAGE_IDS.includes(stageId);+ const isAudio = AUDIO_STAGE_IDS.includes(stageId);+ const nextRunHistory = snapshotRunHistory(currentStage, patch, stageId, { force: snapshotPrior });+ const merged = {+ ...currentStage,+ ...patch,+ runHistory: nextRunHistory,+ updatedAt: new Date().toISOString(),+ };+ if (isVisual) return sanitizeVisualStage(merged, stageId);+ if (isAudio) return sanitizeAudioStage(merged);+ return sanitizeTextStage(merged);+}++export function updateStagesWithLatest(seriesId, updates = [], { snapshotPrior = false } = {}) {+ if (!isStr(seriesId) || !seriesId) {+ return Promise.reject(makeErr('seriesId is required', ERR_VALIDATION));+ }+ if (!Array.isArray(updates) || updates.length === 0) {+ return Promise.resolve([]);+ }+ for (const { stageId } of updates) {+ if (!STAGE_IDS.includes(stageId)) {+ return Promise.reject(makeErr(`Unknown stage: ${stageId}`, ERR_VALIDATION));+ }+ }++ return queueSeriesIssuesWrite(seriesId, async () => {+ const state = await readState();+ const results = [];+ let changed = false;+ for (const update of updates) {+ const idx = state.issues.findIndex((i) => i.id === update.issueId);+ if (idx < 0) throw makeErr(`Issue not found: ${update.issueId}`, ERR_NOT_FOUND);+ const cur = state.issues[idx];+ if (cur.deleted || cur.seriesId !== seriesId) throw makeErr(`Issue not found: ${update.issueId}`, ERR_NOT_FOUND);+ const currentStage = cur.stages[update.stageId];+ const patch = update.computeFn(currentStage);+ if (isPlainObject(patch) && Object.keys(patch).length === 0) {+ results.push({ issue: cur, stage: currentStage });+ continue;+ }+ const nextStage = mergeStagePatch(currentStage, update.stageId, patch, { snapshotPrior });+ const mergedIssue = sanitizeIssue({+ ...cur,+ stages: { ...cur.stages, [update.stageId]: nextStage },+ updatedAt: new Date().toISOString(),+ });+ if (!mergedIssue) throw makeErr('Invalid issue payload', ERR_VALIDATION);+ state.issues[idx] = mergedIssue;+ results.push({ issue: mergedIssue, stage: mergedIssue.stages[update.stageId] });+ changed = true;+ }+ if (changed) {+ await saveIssuesNow(state.issues.filter((i) => i.seriesId === seriesId));+ emitRecordUpdated('series', seriesId);+ }+ return results;+ });+}+/*** Restore a prior `runHistory` snapshot as the active stage state. Looks up the* snapshot by `runId` against the freshest persisted record (so a concurrent@@ -994,8 +1056,6 @@ export function updateStageWithLatest(issueId, stageId, computeFn, { snapshotPriconst cur = await store().loadOne(issueId);if (!cur) throw makeErr(`Issue not found: ${issueId}`, ERR_NOT_FOUND);if (cur.deleted) throw makeErr(`Issue not found: ${issueId}`, ERR_NOT_FOUND);- const isVisual = VISUAL_STAGE_IDS.includes(stageId);- const isAudio = AUDIO_STAGE_IDS.includes(stageId);const currentStage = cur.stages[stageId];const patch = computeFn(currentStage);// Empty-patch fast path: a computeFn that returns `{}` is a "decided not@@ -1008,17 +1068,7 @@ export function updateStageWithLatest(issueId, stageId, computeFn, { snapshotPri// Snapshot the prior `{ runId, input, output }` into runHistory when this// patch carries a fresh lastRunId (i.e. a generate just replaced prior// content). Computed BEFORE the spread so it reads pre-merge state.- const nextRunHistory = snapshotRunHistory(currentStage, patch, stageId, { force: snapshotPrior });- const merged = {- ...currentStage,- ...patch,- runHistory: nextRunHistory,- updatedAt: new Date().toISOString(),- };- let next;- if (isVisual) next = sanitizeVisualStage(merged, stageId);- else if (isAudio) next = sanitizeAudioStage(merged);- else next = sanitizeTextStage(merged);+ const next = mergeStagePatch(currentStage, stageId, patch, { snapshotPrior });const mergedIssue = sanitizeIssue({...cur,stages: { ...cur.stages, [stageId]: next },diff --git a/server/services/pipeline/issues.test.js b/server/services/pipeline/issues.test.jsindex 405a3c8fc2..beb25ba0ae 100644--- a/server/services/pipeline/issues.test.js+++ b/server/services/pipeline/issues.test.js@@ -1167,6 +1167,41 @@ describe('pipeline issues service', () => {});describe('concurrent write serialization', () => {+ it('updateStagesWithLatest validates the whole batch before writing any issue', async () => {+ const first = await svc.createIssue({+ seriesId: 'ser-1',+ title: 'First',+ stages: { prose: { output: 'First draft.', status: 'ready' } },+ });+ const second = await svc.createIssue({+ seriesId: 'ser-1',+ title: 'Second',+ stages: { prose: { output: 'Second draft.', status: 'ready' } },+ });++ await expect(+ svc.updateStagesWithLatest('ser-1', [+ {+ issueId: first.id,+ stageId: 'prose',+ computeFn: () => ({ output: 'First changed.', status: 'edited', lastRunId: 'bulk-1' }),+ },+ {+ issueId: second.id,+ stageId: 'prose',+ computeFn: () => {+ throw Object.assign(new Error('stale second section'), { code: 'TEST_STALE' });+ },+ },+ ], { snapshotPrior: true }),+ ).rejects.toMatchObject({ code: 'TEST_STALE' });++ const afterFirst = await svc.getIssue(first.id);+ const afterSecond = await svc.getIssue(second.id);+ expect(afterFirst.stages.prose.output).toBe('First draft.');+ expect(afterSecond.stages.prose.output).toBe('Second draft.');+ });+it('two concurrent writes do not clobber each other — both fields survive in final state', async () => {// This is the key regression test for the queueIssueWrite tail.// If the write queue is bypassed or broken, both calls read the samediff --git a/server/services/pipeline/manuscriptFix.js b/server/services/pipeline/manuscriptFix.jsindex 016274d8d0..99001dd1fa 100644--- a/server/services/pipeline/manuscriptFix.js+++ b/server/services/pipeline/manuscriptFix.js@@ -15,7 +15,7 @@import { randomUUID } from 'crypto';import { runStagedLLM } from '../../lib/stageRunner.js';import { getSeries, MANUSCRIPT_TYPES } from './series.js';-import { getIssue, updateStageWithLatest } from './issues.js';+import { getIssue, updateStageWithLatest, updateStagesWithLatest } from './issues.js';import { collectManuscriptSections, stageVersionsOf } from './arcPlanner.js';import { getComment, updateComment } from './manuscriptReview.js';@@ -239,15 +239,22 @@ async function planEditsBySection(edits, comment) {return planned;}-async function applyPlannedEdits(planned) {+async function applyPlannedEdits(seriesId, planned) {const sections = [];- for (const group of planned) {- const { issue, stage } = await updateStageWithLatest(group.issueId, group.stageId, (cur) => {+ const updates = planned.map((group) => ({+ issueId: group.issueId,+ stageId: group.stageId,+ computeFn: (cur) => {if (stageTextOf(cur) !== group.originalText) {throw makeErr('Manuscript changed while applying the fix — regenerate the fix', ERR_VALIDATION);}return { output: group.output, status: 'edited', lastRunId: `fix-${randomUUID()}` };- }, { snapshotPrior: true });+ },+ }));+ const updated = await updateStagesWithLatest(seriesId, updates, { snapshotPrior: true });+ for (let i = 0; i < updated.length; i += 1) {+ const group = planned[i];+ const { issue, stage } = updated[i];sections.push(sectionFrom(issue, group.stageId, stage));}return sections;@@ -349,7 +356,7 @@ export async function acceptManuscriptFix(seriesId, { commentId, find, replace,}const planned = await planEditsBySection(acceptedEdits, comment);- const sections = await applyPlannedEdits(planned);+ const sections = await applyPlannedEdits(seriesId, planned);const updated = await updateComment(seriesId, commentId, { status: 'accepted' });return { comment: updated, section: sections[0] || null, sections };}