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
address review (codex): recheck series tombstones inside per-id queue before GC delete (deleteOneNow)
Adam Eivybb60524fa097
diff --git a/PLAN.md b/PLAN.mdindex 9a72a67ce2..4d3ee29108 100644--- a/PLAN.md+++ b/PLAN.md@@ -128,6 +128,8 @@ Surfaced during code review of the federated-media-collection-sync feature and c- [ ] [media-sync-drawer-test-act-warning] **Test polish: `SyncDetailDrawer.test.jsx` act() warning.** The universe-kind "shows per-peer breakdown" test renders without awaiting the async record-name fetch, emitting a React `act()` warning (test still passes). Wrap the render/assertions in `waitFor`/`act`. Test-quality only.- [ ] [peer-sync-tombstone-cooldown-bypass] **Schema-block cooldown suppresses tombstone (delete) pushes for up to 5 min.** `pushRecordToPeer` (`server/services/sharing/peerSync.js` ~line 714) short-circuits on `sub.blockedBySchema && !options.bypassSchemaCooldown` BEFORE building the push payload, so a delete (tombstone) edit to a schema-blocked subscription is held off — even though the receiver-side gate (~line 1197) explicitly exempts tombstones (`record.deleted !== true`) so soft-deletes always converge. Delete still converges on the next `peer:online` (which passes `bypassSchemaCooldown: true`) or after the cooldown elapses, so this is eventual-consistency-correct but slow in the rare schema-mismatch + edit-triggered-delete window. Fix: resolve whether the pending push is a tombstone (load the record, or thread a `deleted` hint) before the cooldown gate and bypass the cooldown for tombstones, mirroring the receiver exemption. Surfaced during v2.8.0 release review (claude). Deferred: touches delicate push-gate ordering, no test coverage, low impact.- [ ] [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.## Future Ideasdiff --git a/server/lib/collectionStore.js b/server/lib/collectionStore.jsindex 7a314f07f7..12a0b34987 100644--- a/server/lib/collectionStore.js+++ b/server/lib/collectionStore.js@@ -282,6 +282,23 @@ export function createCollectionStore({});}+ /**+ * Hard-delete a record WITHOUT the per-id queue. Removes the entire+ * `{dir}/{id}/` subtree AND drops the id from `knownIds` (the readdir-ENOENT+ * fallback source). The delete-side counterpart to `saveOneNow`: call it+ * INSIDE a `queueRecordWrite(id, …)` block when an external recheck must span+ * the load→delete boundary atomically (e.g. tombstone GC re-checking that the+ * record is still deleted before removing it). Idempotent — missing dir is a+ * no-op. Outside a queue, prefer `deleteOne`.+ */+ async function deleteOneNow(id) {+ if (!isValidId(id)) {+ throw new Error(`collectionStore[${type}]: invalid record id "${id}" — must match ${idPattern}`);+ }+ await rm(recordDir(id), { recursive: true, force: true });+ knownIds.delete(id);+ }+/*** Hard-delete a record. Removes the entire `{dir}/{id}/` subtree so any* sidecar files (per-record images, derived assets) go with it. Serialized@@ -292,10 +309,7 @@ export function createCollectionStore({if (!isValidId(id)) {throw new Error(`collectionStore[${type}]: invalid record id "${id}" — must match ${idPattern}`);}- return queueRecordWrite(id, async () => {- await rm(recordDir(id), { recursive: true, force: true });- knownIds.delete(id);- });+ return queueRecordWrite(id, () => deleteOneNow(id));}/**@@ -361,6 +375,7 @@ export function createCollectionStore({loadAll,saveOneNow,saveOne,+ deleteOneNow,deleteOne,// Concurrency primitivesqueueRecordWrite,diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.jsindex 99b2d2204b..4ae9dbf3d6 100644--- a/server/services/pipeline/series.js+++ b/server/services/pipeline/series.js@@ -511,13 +511,35 @@ export async function mergeSeriesFromSync(remoteSeries) {*/export async function pruneTombstonedSeries(beforeMs) {if (!Number.isFinite(beforeMs)) return { pruned: 0 };- const series = await store().loadAll();- const prunable = series.filter((s) => {- if (!s?.deleted) return false;- const t = Date.parse(s.deletedAt || '');- if (!Number.isFinite(t)) return false;- return t < beforeMs;- });- await Promise.all(prunable.map((s) => store().deleteOne(s.id)));- return { pruned: prunable.length };+ const s = store();+ const series = await s.loadAll();+ const candidates = [];+ for (const rec of series) {+ if (!rec?.deleted) continue;+ const t = Date.parse(rec.deletedAt || '');+ if (!Number.isFinite(t)) continue;+ if (t < beforeMs) candidates.push(rec.id);+ }+ // Re-check the tombstone status INSIDE each per-id queue. A concurrent+ // mergeSeriesFromSync could have un-deleted the record (newer remote+ // `updatedAt`, `deleted: false`) between our out-of-queue snapshot and the+ // queued delete; without the re-check we'd rm -rf a freshly un-deleted+ // record. Mirrors pruneTombstonedUniverses. Uses deleteOneNow (not deleteOne —+ // that re-enters queueRecordWrite for the same id and would deadlock).+ const results = await Promise.allSettled(candidates.map((id) =>+ s.queueRecordWrite(id, async () => {+ const fresh = await s.loadOne(id);+ if (!fresh?.deleted) return false; // un-deleted between snapshot and queue+ const t = Date.parse(fresh.deletedAt || '');+ if (!Number.isFinite(t) || t >= beforeMs) return false;+ await s.deleteOneNow(id);+ return true;+ })+ ));+ let pruned = 0;+ for (const r of results) {+ if (r.status === 'fulfilled' && r.value === true) pruned += 1;+ else if (r.status === 'rejected') console.log(`⚠️ pruneTombstonedSeries: delete failed: ${r.reason?.message || r.reason}`);+ }+ return { pruned };}