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 (claude): 6 findings from the local review pass

Adam Eivya6b99fe28486
diff --git a/.changelog/v2.10.0.md b/.changelog/v2.10.0.md
index 09fcbc83ac..6c88278cf5 100644
--- a/.changelog/v2.10.0.md
+++ b/.changelog/v2.10.0.md
@@ -30,7 +30,7 @@ fixes.
## Changed
-- **Merge-verified worktree cleanup — reaps merged branches/worktrees without ever risking in-progress work.** Periodic worktree cleanup was previously disabled because it could obliterate worktrees still in use by other agents or outside the CoS system. The cleanup now reaps a worktree **only** when both gates pass: the working tree is clean (auto-generated lockfile churn ignored) **and** the branch is fully merged into the default branch. Merge detection (`isBranchMergedInto`) covers both normal merges (ancestor check) and squash/rebase merges (synthesized-tree `git cherry` patch-id), so it can't be fooled by a squashed history. The daily `agent-data-cleanup` job now runs this safe reap across both CoS worktrees (`data/cos/worktrees/`) and the `/work` / `/claim` / superpowers trees under `.claude/worktrees/` — unlocking locked-but-merged trees before removal — then falls back to the existing orphan-integration pass for dead agents whose commits never landed. Because the two gates together mean "nothing pending and nothing to lose," the previous data-loss failure mode is structurally impossible. To make detection bulletproof going forward, the automated review-loop and `/do:pr` merge commands now prefer a true merge commit (`gh pr merge --merge`) over `--squash`, keeping each branch tip in the default branch's history.
+- **Merge-verified worktree cleanup — reaps merged branches/worktrees without ever risking in-progress work.** Periodic worktree cleanup was previously disabled because it could obliterate worktrees still in use by other agents or outside the CoS system. The cleanup now reaps a worktree **only** when both gates pass: the working tree is clean (auto-generated lockfile churn ignored) **and** the branch is fully merged into the default branch. Merge detection (`isBranchMergedInto`) covers both normal merges (ancestor check) and squash/rebase merges (synthesized-tree `git cherry` patch-id), so it can't be fooled by a squashed history. The daily `agent-data-cleanup` job now runs this safe reap across both CoS worktrees (`data/cos/worktrees/`) and the `/work` / `/claim` / superpowers trees under `.claude/worktrees/` — skipping locked or in-progress trees — then falls back to the existing orphan-integration pass for dead agents whose commits never landed. Because the two gates together mean "nothing pending and nothing to lose," the previous data-loss failure mode is structurally impossible. To make detection bulletproof going forward, the automated review-loop and `/do:pr` merge commands now prefer a true merge commit (`gh pr merge --merge`) over `--squash`, keeping each branch tip in the default branch's history.
- **Autofixer and Google Calendar sync now run through your configured AI provider.** Both previously hardcoded `claude -p`, ignoring whichever provider/model the rest of PortOS uses. They now resolve a configured CLI provider/model and route through a shared, dependency-light invocation path (`server/lib/cliProviderRun.js`) — the same per-CLI argv conventions (Codex `exec -`, Gemini stdin, Claude Code `-p -`) the main runner uses. New UI controls let you pick the provider/model per feature: a **Settings › Autofixer** tab, and a picker on the **Calendar › Config** tab (for Google MCP-sync accounts). Both default to Claude Code when unset, so existing installs are unchanged. The picker is restricted to enabled **CLI** providers — the autofixer must edit files and run pm2, and the calendar sync must call MCP tools, neither of which an API chat provider can do. *Migration note:* calendar MCP sync no longer honors the legacy `CLAUDE_PATH` env var — point the provider's command at your binary under **AI Providers** instead. The Claude-specific `--allowedTools` MCP flag is now passed only to Claude-family providers.
diff --git a/PLAN.md b/PLAN.md
index 8f01712c5d..29c7765890 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -125,7 +125,7 @@ Surfaced while building the sync-hygiene feature (duplicate detection/merge, non
- [ ] [series-merge-season-rehoming] **Series merge re-homes issues un-grouped.** `recordMerge.mergeSeries` re-points the loser series' issues to the survivor via `issues.reassignIssuesToSeries`, which sets `seasonId: null` (seasons are series-scoped, so the loser's season ids don't exist on the survivor; seasons are unioned by number separately). The moved issues land un-grouped and the user must re-assign them to a survivor season. A smarter merge could map loser seasons → survivor seasons by number and preserve issue→season grouping.
- [ ] [conflict-restore-additive] **"Restore mine" is additive for keyed fields, not a faithful overwrite.** `conflictJournalResolver.resolveConflict` restore-all applies the snapshot via `updateUniverse(id, () => patch)`, which merges `categories` per-key — so a category the user deleted *after* the conflict is resurrected on restore. Acceptable for v1 (resurrect-not-lose), but the UI says "restore your whole version." Consider a true-replace path for restore-all. Surfaced in /code-review (medium).
- [ ] [merge-cascade-no-rollback] **`recordMerge.mergeUniverses`/`mergeSeries` cascade has no rollback.** Union-write survivor → re-point each child → tombstone loser runs as separate awaits; a mid-loop throw (e.g. a child concurrently tombstoned → NOT_FOUND) leaves the survivor merged but the loser un-tombstoned, and a retry trips `ERR_HAS_LIVE_SERIES` on the remaining children. Single-user/low-concurrency so low-probability, but a half-merge has no cleanup. Consider catching per-child and reporting, or finishing the loser tombstone best-effort. Surfaced in /code-review (medium).
-- [ ] [merge-orphan-series-via-api] **`mergeSeries` permits merging two orphan series via the API.** The same-universe guard `(survivor.universeId||null) !== (loser.universeId||null)` is `null !== null` = false for two orphans, so a direct POST `/api/pipeline/series/merge` with two orphan ids proceeds — contradicting `duplicateDetection`, which segregates orphans as un-mergeable in the UI. Reject when both `universeId` are empty (or require a universe). Surfaced in /code-review (low-medium).
+- [x] [merge-orphan-series-via-api] **DONE in v2.10.0.** `recordMerge.js:334-340` now throws `Orphan series (no universe) cannot be merged …` when both `universeId` are null, and `recordMerge.test.js:231` pins it. (Was: `mergeSeries` permitted merging two orphan series via the API because `null !== null` is false.)
- [ ] [conflict-source-attribution] **Conflict-journal `source` is `via:'sync'/peerId:null` on the peer-push path.** `applyIncomingPush` calls `mergeUniversesFromSync`/`mergeSeriesFromSync` without the `{ source }` arg even though `sourceInstanceId` is in scope, so the Conflicts tab can't attribute which peer collided. Thread `{ via:'peer-push', peerId: sourceInstanceId }` from `applyIncomingPush`. Surfaced in /code-review (low, attribution only).
- [ ] [dup-detect-collection-count-undercount] **`duplicateDetection.collectionItemsByUniverse` last-wins instead of summing.** Uses `.set(universeId, length)` while `seriesByUniverse` accumulates with `+`; if two live collections share a `universeId` (partial-merge/hand-edit), `linkedCollectionItemCount` undercounts the survivor-suggestion heuristic. Sum like the series count. Surfaced in /code-review (low, display only).
- [ ] [conflict-journal-push-flush-coalesce] **Coalesce per-push base-hash flushes.** `pushRecordToPeer` (`server/services/sharing/peerSync.js` ~947) stamps a base hash and calls `flushBaseHashes()` per pushed universe/series, so a large push loop rewrites `sync_base_hashes.json` once per record. Copilot (PR #489) suggested debouncing. A `setTimeout`-based debounce was tried and reverted because the real unref'd timer leaked into `peerSync.test.js`'s same-file settle-waits and made the suite flaky. A safe coalescing approach (e.g. a microtask/`queueMicrotask` batch within a single push burst, or a test-injectable scheduler) could land the optimization without the timer-leak flake. Low priority — the flush is serialized + fire-and-forget and the file is tiny.
@@ -155,6 +155,7 @@ Surfaced by the multi-reviewer release gate for v2.10.0. The CRITICAL/correctnes
- [ ] [merge-union-seasons-collision] **`unionSeasons` silently drops a loser season whose `number` collides with a survivor's.** `server/services/recordMerge.js` (~line 151) `continue`s past a colliding loser season, discarding its authored title/episodes/arc metadata even though the merge is documented as "no data loss" (this is a local merge, so the conflict journal never sees it). Either union the loser season's non-empty fields into the survivor, or surface a count in the `cascade` summary so the UI can warn "N loser seasons not merged." (Batch-2 NIT.)
- [ ] [conflict-journal-basehash-evict] **`sync_base_hashes.json` entries are never evicted on record delete.** `server/lib/conflictJournal.js#setSyncBaseHash` keys by `${kind}:${id}`; when a record is tombstoned and force-pruned its base-hash entry leaks (slow unbounded growth on a long-lived federated install — not a correctness bug). Delete the entry as part of the delete cascade / tombstone prune. (Batch-2 NIT.)
- [ ] [test-merge-route-contracts] **Route-level tests for the merge endpoints' contracts.** `universeBuilder.test.js`/`pipeline.test.js` only assert `status === 400` for identical-ids and never pin the body `code` (`MERGE_VALIDATION`); there's no route test for a successful `POST /merge` (`{ merged, cascade }`), the `DELETE /universe-builder/:id` 409 `UNIVERSE_HAS_LIVE_SERIES` + `context.blockingSeries` body the UI depends on, nor the `POST /merge/ai-resolve` error contract (`MERGE_AI_NO_MERGEABLE_FIELDS` 422, no-provider, `LLM_INVALID_JSON` 502). Add them. (Batch-2 IMPROVEMENT.)
+- [ ] [test-codereview-defaults-cache-isolation] **`codeReview.test.js` doesn't reset the module-level `cachedDefaults` between tests.** `getCodeReviewDefaults` memoizes into `cachedDefaults` (invalidated only by a `settings:updated` event the test stubs as a no-op); `afterEach` resets `mockedSettings.current` but never clears the cache, so a future test adding a second `getCodeReviewDefaults()` call with different settings would silently read stale data. Export a test-only `__resetCodeReviewDefaultsCache()` and call it in `afterEach`. Latent (no current failure). (Batch-1/claude NIT.)
- [ ] [test-codereview-local-route] **`POST /api/code-review/local` has no route-level test.** Add a supertest-style test (mocking `runLocalCodeReview`/`getSettings`): empty `diff` → 400 (Zod), unknown `backend` → 400 (`z.enum`), `model` omitted falls back to the settings model, and `{ ok: false }` service result → 502. Also add `validation.test.js` assertions that `featureProviderConfigSchema.parse({ providerId:'', model:'' })` yields `undefined`s and `codeReviewSettingsSchema` rejects unknown keys (`.strict()`). (Batch-3 IMPROVEMENT/NIT.)
## Future Ideas
diff --git a/client/src/pages/Shell.jsx b/client/src/pages/Shell.jsx
index 1762869e24..084ff1626e 100644
--- a/client/src/pages/Shell.jsx
+++ b/client/src/pages/Shell.jsx
@@ -734,7 +734,7 @@ export default function Shell() {
<div className="flex items-center gap-2 ml-auto">
{connected && (
<button
- onClick={() => { stopSession(); setTimeout(startSession, 1000); }}
+ onClick={() => { stopSession(); setTimeout(() => { if (mountedRef.current) startSession(); }, 1000); }}
className="flex items-center gap-1.5 px-2.5 py-2 bg-port-card hover:bg-port-border text-gray-300 hover:text-white rounded-lg text-sm transition-colors border border-port-border min-h-[40px]"
title="Restart session (kill + new)"
>
diff --git a/server/services/agentManagement.js b/server/services/agentManagement.js
index ae89b0174e..b8954fa340 100644
--- a/server/services/agentManagement.js
+++ b/server/services/agentManagement.js
@@ -110,7 +110,14 @@ export async function pauseAgent(agentId, reason = null) {
pausedAgents.delete(agentId);
return result;
}
- await markAgentPaused(agentId, agentInfo, pausedAt, reason);
+ // Persist failure must roll back the in-memory flag too, or the maps drift
+ // (pausedAgents set, runnerAgents never deleted) until the next restart.
+ const persistedRunner = await markAgentPaused(agentId, agentInfo, pausedAt, reason).then(() => true, (err) => {
+ pausedAgents.delete(agentId);
+ emitLog('error', `❌ Failed to persist pause for runner agent ${agentId}: ${err.message}`, { agentId });
+ return false;
+ });
+ if (!persistedRunner) return { success: false, error: 'Failed to persist paused state' };
runnerAgents.delete(agentId);
emitLog('info', `⏸️ Paused runner agent ${agentId}${reason ? `: ${reason}` : ''}`, { agentId, reason });
return { success: true, agentId, pausedAt, mode: 'runner' };
@@ -122,7 +129,15 @@ export async function pauseAgent(agentId, reason = null) {
}
pausedAgents.set(agentId, { pausedAt, reason });
- await markAgentPaused(agentId, agent, pausedAt, reason);
+ // Persist BEFORE killing the process, and roll back the in-memory flag on a
+ // persist failure — otherwise a throw here leaves the agent flagged paused
+ // in-memory while its process keeps running (the kill below never executes).
+ const persisted = await markAgentPaused(agentId, agent, pausedAt, reason).then(() => true, (err) => {
+ pausedAgents.delete(agentId);
+ emitLog('error', `❌ Failed to persist pause for agent ${agentId}: ${err.message}`, { agentId });
+ return false;
+ });
+ if (!persisted) return { success: false, error: 'Failed to persist paused state' };
if (agent.tuiSessionId) {
shellService.writeToSession(agent.tuiSessionId, '\x1b');
diff --git a/server/services/calendarGoogleSync.js b/server/services/calendarGoogleSync.js
index 9b24ed3597..88d1a6c880 100644
--- a/server/services/calendarGoogleSync.js
+++ b/server/services/calendarGoogleSync.js
@@ -148,7 +148,7 @@ After fetching ALL calendars, output ONLY a single JSON object (no markdown fenc
Include the full events arrays as returned by gcal_list_events. Output NOTHING else — just the JSON.`;
- const result = await runClaudeMcp(prompt, io, accountId);
+ const result = await runConfiguredMcp(prompt, io, accountId);
mcpSyncLock.delete(accountId);
@@ -224,7 +224,7 @@ For each calendar, use:
Output NOTHING else — just the JSON array.`;
- const result = await runClaudeMcp(prompt, io, accountId);
+ const result = await runConfiguredMcp(prompt, io, accountId);
if (result.error) {
console.error(`❌ Calendar discovery failed: ${result.error}`);
@@ -247,7 +247,7 @@ Output NOTHING else — just the JSON array.`;
return { calendars: merged, status: 'success' };
}
-async function runClaudeMcp(prompt, io, accountId) {
+async function runConfiguredMcp(prompt, io, accountId) {
// Resolve the user's configured calendar-sync provider/model (falls back to
// claude-code — the historical default — when unset). Restricted to CLI
// providers since the sync relies on MCP tool calling.
diff --git a/server/services/conflictJournalResolver.js b/server/services/conflictJournalResolver.js
index 0511ed53f7..6a25fe12fa 100644
--- a/server/services/conflictJournalResolver.js
+++ b/server/services/conflictJournalResolver.js
@@ -24,6 +24,7 @@
* destructive "revert to exact snapshot."
*/
+import { existsSync } from 'fs';
import { conflictJournalStore, RESTORABLE_FIELDS } from '../lib/conflictJournal.js';
import { updateUniverse, ERR_NOT_FOUND as UNIVERSE_NOT_FOUND } from './universeBuilder.js';
import { updateSeries, ERR_NOT_FOUND as SERIES_NOT_FOUND } from './pipeline/series.js';
@@ -113,7 +114,10 @@ export async function resolveConflict(id, { action, fields = [] } = {}) {
/** Permanently remove a journal entry (the "dismiss / clear" action). */
export async function deleteConflict(id) {
- await getConflict(id); // 404 if missing
+ // Don't gate on getConflict() — it requires a successful parse, so a corrupt
+ // journal entry would 404 here and become permanently undeletable. Check raw
+ // directory existence instead, then hard-delete (deleteOne is idempotent).
+ if (!existsSync(store().recordDir(id))) throw makeErr(`Conflict entry not found: ${id}`, ERR_NOT_FOUND);
await store().deleteOne(id);
return { id, deleted: true };
}
diff --git a/server/services/sharing/importer.js b/server/services/sharing/importer.js
index 9a15d01a48..99e8b2341f 100644
--- a/server/services/sharing/importer.js
+++ b/server/services/sharing/importer.js
@@ -300,9 +300,19 @@ async function copyAssetsLocally(bucketPath, assetRefs) {
return { copied, available, missing };
}
+// Peer-supplied record ids index into `join(bucketPath, …, `${id}.json`)`. A
+// `../`-bearing id from a buggy/malicious federation peer would turn those reads
+// into a path-traversal existence/parse oracle on the host. Reject anything that
+// isn't a bare filename segment before it reaches a join. (Write-side idPattern
+// already blocks persistence; this closes the read side.)
+const isSafeRecordId = (id) =>
+ typeof id === 'string' && id.length > 0 && basename(id) === id
+ && !id.includes('/') && !id.includes('\\') && !id.includes('\0');
+
async function processAnnotationManifest(bucket, manifest) {
const recordId = (manifest.recordIds || [])[0] || manifest.senderInstanceId;
if (!recordId) return { applied: 0, missing: true, reason: 'no-record-id' };
+ if (!isSafeRecordId(recordId)) return { applied: 0, missing: true, reason: 'bad-record-id' };
const recordPath = join(bucket.path, 'records', 'media-annotations', `${recordId}.json`);
const record = await readJSONFile(recordPath, null, { logError: false });
if (!record) return { applied: 0, missing: true, reason: 'record-not-synced' };
@@ -328,6 +338,7 @@ async function mergeMediaJobRecords(bucketPath, recordIds) {
const [persisted, incoming] = await Promise.all([
readJSONFile(persistedPath, { jobs: [] }, { logError: false }),
Promise.all((recordIds || []).map(async (id) => {
+ if (!isSafeRecordId(id)) return null;
const recordPath = join(mediaDir, `${id}.json`);
if (!existsSync(recordPath)) return null;
return readJSONFile(recordPath, null, { logError: false });
@@ -357,6 +368,7 @@ async function readReferencedRecords(bucketPath, manifest) {
const records = { series: [], issues: [], universes: [], media: [] };
const missing = [];
const resolveOne = async (id) => {
+ if (!isSafeRecordId(id)) return { kind: 'missing', id };
if (id.startsWith('ser-')) {
const r = await readJSONFile(join(bucketPath, 'records', 'series', `${id}.json`), null, { logError: false });
return r ? { kind: 'series', record: r } : { kind: 'missing', id };