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

address review (gemini): serialize issue stage/field saves on the series write tail (fixes renumber-vs-stage-save clobber from the per-record split)

Adam Eivy490e34695f53
diff --git a/PLAN.md b/PLAN.md
index 4d3ee29108..7639e53017 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -130,6 +130,8 @@ Surfaced during code review of the federated-media-collection-sync feature and c
- [ ] [aitoolkit-ollama-ready-hook-injection] **Vendored AI toolkit imports out to a PortOS service.** `server/lib/aiToolkit/runner.js:8` does `import { ensureProviderReady as ensureOllamaProviderReady } from '../../services/ollamaManager.js'` (added by the "Run Ollama as a startup service" work), used at ~line 313 in the API chat-completions path. This violates the documented self-containment rule ("Keep the directory self-contained — no imports out to other PortOS modules — so future upstream syncs don't fight local edits"). Fix: inject `ensureProviderReady` through the runner `config`/`hooks` (the factory already accepts `hooks = {}`) and wire it where PortOS constructs the toolkit, mirroring the `executeCliRun`/`stopRun` override pattern in `server/index.js`; the hook early-returns success for non-Ollama providers, so no behavior change. Surfaced during v2.8.0 release review (claude). Deferred: cross-file DI refactor of the toolkit boundary with no test coverage — maintainability/sync-hygiene only, no runtime impact today.
- [ ] [pipeline-issue-bulk-write-queue-serialization] **Series-wide issue writes bypass the per-id write queue, racing per-issue stage saves.** `saveIssuesNow` (`server/services/pipeline/issues.js:460`) writes each issue via `saveOneNow` (raw, no queue). The renumber paths (e.g. `updateIssue` ~line 768) hold `queueSeriesIssuesWrite(seriesId)` — a *series-level* mutex — while stage saves (~line 879) hold `queueRecordWrite(issueId)` — a *per-id* mutex. Different keys ⇒ they don't serialize: a renumber's bulk write of issue X can interleave with a concurrent stage blur-save of issue X (last write wins, losing one). This is the documented "async PATCH races on shared records" class (see CLAUDE.md `issueWriteTail`). The naive fix (wrap each `saveIssuesNow` write in `queueRecordWrite(id)`) is insufficient AND deadlock-prone: (a) the renumber reads ALL issues into `state` up front, so even a per-id-queued write carries a stale snapshot that clobbers a stage-save landing mid-operation; (b) `queueRecordWrite` is not re-entrant (`collectionStore.js:116`), so any caller already inside `queueRecordWrite(id)` for an affected id deadlocks. Correct fix needs a design choice — either make stage saves also acquire the series queue (one mutex per series), or have renumber re-read+re-apply each issue inside its own per-id queue — plus a regression test simulating the concurrent renumber-vs-stage-save. Surfaced during v2.8.0 release review (codex, P1). Deferred: core pipeline storage, needs design + test, deadlock risk on a rushed fix.
- [ ] [ollama-linux-systemd-enable-not-start] **Linux "Run at Startup" only starts Ollama for the current boot.** The systemd controller in `getServiceController` (`server/services/ollamaManager.js:80-82`) uses `systemctl start`/`stop` and `getServiceStatus` (line 109-120) treats `is-active` as `runAtStartup`, so the UI claims the service will run at login even though it won't survive a reboot (macOS `brew services start` IS persistent, so the contract is platform-inconsistent). Fix: Linux start → `systemctl enable --now ollama`, stop → `systemctl disable --now ollama`, and split status into `is-enabled` (→ `runAtStartup`) vs `is-active` (→ `running`) as two queries. Surfaced during v2.8.0 release review (codex, P2). Deferred: Linux-only path, untestable on the macOS dev machine, zero existing test coverage, privileged systemctl semantics — land it where it can be exercised on a real systemd host.
+- [ ] [migration-037-history-streaming] **History JSON→JSONL migration loads the whole file into memory.** `scripts/migrations/037-history-json-to-jsonl.js` reads all of `history.json` (and any existing `.jsonl`) and stringifies the union — fine for typical history sizes, but a very large action-history file could spike heap at upgrade time. Convert to a streaming/append-only line-by-line rewrite if large histories become a problem. Surfaced during v2.8.0 release review (gemini, IMPROVEMENT). Deferred: one-shot migration, speculative for realistic sizes.
+- [ ] [localllm-env-atomic-write] **`.env` backend marker write is non-atomic.** `writeBackend` in `server/services/localLlm.js` (~line 94) uses `writeFileSync` to rewrite `.env`; a crash mid-write could corrupt it. `atomicWrite` (temp+rename, passes strings through unchanged) would make it crash-safe — but `writeBackend` is currently sync and the write is tiny/rare. Surfaced during v2.8.0 release review (gemini, IMPROVEMENT). Deferred: requires a sync→async ripple for a microsecond-wide crash window.
## Future Ideas
diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.js
index 8cd38a2957..39b23fc078 100644
--- a/server/services/pipeline/issues.js
+++ b/server/services/pipeline/issues.js
@@ -753,15 +753,21 @@ function mergeIssuePatch(cur, patch = {}) {
export function updateIssue(id, patch = {}, { skipRenumber = false } = {}) {
const needsRenumber = !skipRenumber && ('seasonId' in patch || 'arcPosition' in patch);
if (!needsRenumber) {
- return store().queueRecordWrite(id, async () => {
- const cur = await store().loadOne(id);
- if (!cur) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);
- if (cur.deleted) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);
- const merged = mergeIssuePatch(cur, patch);
- await saveIssueNow(merged);
- emitRecordUpdated('series', merged.seriesId);
- return merged;
- });
+ // Route through the SERIES tail (see updateStageWithLatest) so a plain
+ // field update can't race a concurrent series-wide renumber rewriting this
+ // issue. seriesId is immutable, so read it outside the lock to pick the
+ // queue, then re-read the issue inside.
+ return getIssue(id, { includeDeleted: true }).then((existing) =>
+ queueSeriesIssuesWrite(existing.seriesId, async () => {
+ const cur = await store().loadOne(id);
+ if (!cur) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);
+ if (cur.deleted) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);
+ const merged = mergeIssuePatch(cur, patch);
+ await saveIssueNow(merged);
+ emitRecordUpdated('series', merged.seriesId);
+ return merged;
+ }),
+ );
}
return getIssue(id, { includeDeleted: true }).then((existing) =>
@@ -876,7 +882,15 @@ export function updateStageWithLatest(issueId, stageId, computeFn) {
// rather than waiting in line for an error it already knows about.
return Promise.reject(makeErr(`Unknown stage: ${stageId}`, ERR_VALIDATION));
}
- return store().queueRecordWrite(issueId, async () => {
+ // Serialize on the SERIES tail (not the per-id queue) so a stage save can't
+ // interleave with a series-wide renumber/bulk write that rewrites this same
+ // issue — both share one mutex per series. The per-record split (migrations
+ // 035/036) otherwise left renumbers on the series queue and stage saves on
+ // the per-id queue (two independent mutexes over the same shared resource);
+ // see CLAUDE.md "single tail per shared file". seriesId is immutable, so read
+ // it outside the lock to pick the queue, then re-read the issue INSIDE the
+ // lock for the freshest stage.
+ const work = async () => {
const 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);
@@ -913,7 +927,10 @@ export function updateStageWithLatest(issueId, stageId, computeFn) {
await saveIssueNow(mergedIssue);
emitRecordUpdated('series', mergedIssue.seriesId);
return { issue: mergedIssue, stage: mergedIssue.stages[stageId] };
- });
+ };
+ return getIssue(issueId, { includeDeleted: true }).then((existing) =>
+ queueSeriesIssuesWrite(existing.seriesId, work),
+ );
}
/**
diff --git a/server/services/pipeline/issues.test.js b/server/services/pipeline/issues.test.js
index e64fb5fd74..db0e4dfb37 100644
--- a/server/services/pipeline/issues.test.js
+++ b/server/services/pipeline/issues.test.js
@@ -2,12 +2,23 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
import { mockNoPeerSync, mockNoPeers } from '../../lib/mockPathsDataRoot.js';
const fileStore = new Map();
+// One-shot write delay hook for the concurrency regression test: when set, the
+// first atomicWrite whose (path, data) matches is held for `ms` before landing,
+// letting a test force a specific read→write interleaving deterministically.
+let pendingWriteDelay = null;
vi.mock('../../lib/fileUtils.js', () => ({
tryReadFile: vi.fn().mockResolvedValue(null),
PATHS: { data: '/mock/data' },
ensureDir: vi.fn().mockResolvedValue(undefined),
- atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, data); }),
+ atomicWrite: vi.fn(async (path, data) => {
+ if (pendingWriteDelay && pendingWriteDelay.match(path, data)) {
+ const { ms } = pendingWriteDelay;
+ pendingWriteDelay = null; // one-shot
+ await new Promise((resolve) => setTimeout(resolve, ms));
+ }
+ fileStore.set(path, data);
+ }),
readJSONFile: vi.fn(async (path, fallback) => (fileStore.has(path) ? fileStore.get(path) : fallback)),
}));
@@ -28,6 +39,7 @@ describe('pipeline issues service', () => {
beforeEach(() => {
fileStore.clear();
uuidCounter = 0;
+ pendingWriteDelay = null;
});
it('createIssue assigns iss- id and auto-numbers within a series', async () => {
@@ -1117,5 +1129,43 @@ describe('pipeline issues service', () => {
expect(final.stages.idea.output).toBe('beat sheet content');
expect(final.status).toBe('needs-review');
});
+
+ it('a series-wide renumber cannot clobber a concurrent stage save on an affected issue', async () => {
+ // Regression for the per-record-split race (migrations 035/036): renumbers
+ // serialize on the per-series tail while stage/single-issue saves used the
+ // per-id tail — two independent mutexes over the same issue. A renumber that
+ // rewrites an issue's number from a stale in-memory snapshot could clobber a
+ // concurrent stage edit on it. Both now share the series tail.
+ const series = await seriesSvc.createSeries({ name: 'Renumber race' });
+ const v1 = await seasonsSvc.createSeason(series.id, { title: 'Volume 1', number: 1 });
+ const v2 = await seasonsSvc.createSeason(series.id, { title: 'Volume 2', number: 2 });
+ await svc.createIssue({ seriesId: series.id, seasonId: v1.id, arcPosition: 1, title: 'V1 E1' });
+ const target = await svc.createIssue({ seriesId: series.id, seasonId: v2.id, arcPosition: 1, title: 'V2 E1' });
+ expect(target.number).toBe(2); // numbered after the single V1 issue
+
+ // Force the clobbering interleave deterministically: hold the STAGE write
+ // of `target` (the one carrying the edit) until after the renumber's write
+ // of `target` lands. Without a shared mutex the stage save read the issue
+ // at #2, so its delayed write lands a stale {#2, output} over the renumber's
+ // {#3, no output} — losing the renumber. Sharing the series tail forces the
+ // stage save to run AFTER the renumber and re-read the freshest (#3) record,
+ // so both the number and the edit survive.
+ pendingWriteDelay = {
+ ms: 50,
+ match: (path, data) => path.includes(target.id) && data?.stages?.idea?.output === 'STAGE-EDIT',
+ };
+
+ // (a) stage edit on the V2 issue, (b) a new V1 issue that renumbers the V2
+ // issue from #2 to #3 (rewriting target's record).
+ await Promise.all([
+ svc.updateStage(target.id, 'idea', { status: 'ready', output: 'STAGE-EDIT' }),
+ svc.createIssue({ seriesId: series.id, seasonId: v1.id, arcPosition: 2, title: 'V1 E2' }),
+ ]);
+
+ const after = await svc.getIssue(target.id);
+ expect(after.stages.idea.output).toBe('STAGE-EDIT'); // stage edit survived the renumber
+ expect(after.stages.idea.status).toBe('ready');
+ expect(after.number).toBe(3); // renumber also applied
+ });
});
});