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 release review (claude,codex,gemini): CRITICAL + correctness fixes
Adam Eivy34639e35c9cb
diff --git a/PLAN.md b/PLAN.mdindex 8fe63ca2a2..8f01712c5d 100644--- a/PLAN.md+++ b/PLAN.md@@ -11,7 +11,7 @@ _Batch-cleared 2026-05-25: 23 Next Up items shipped together via parallel sub-ag- [ ] [peer-sync-per-category-version-gate] **Generalize the cross-install schema version gate from whole-payload to per-category.** Surfaced by code review during the batch-clear of `[peer-sync-video-collection-metadata-sync]` (2026-05-25). `compareSchemaVersions` (`server/lib/schemaVersions.js`) walks the UNION of category keys, and the three gate sites (`dataSync.js` `applyRemote`, `peerSync.js` push, `importer.js` import) reject the ENTIRE payload on any `ahead.length > 0`. So introducing a brand-new category key — or bumping one category — makes every not-yet-upgraded peer reject ALL categories (universe, pipeline, …), severing sync across a federation that upgrades on independent schedules. `videoHistory` sidestepped this by deliberately staying OUT of `PORTOS_SCHEMA_VERSIONS` (see the comment there), but `mediaCollections: 1` has the same latent property. Fix: scope the ahead-check to the category (for `applyRemote`/import) or the record's kind→category (for push) actually being transferred, so a newer sender's unknown/bumped category gates only THAT category's transfer, not unrelated ones. Keep the union-walk for diagnostics/UI. Needs new cross-key test coverage (today's tests only exercise same-category gaps).- [ ] [voice-weather-settings-location] **Wire a real `settings.location { lat, lon }` field so `weather_now` can use a configured location.** Surfaced during the batch-clear review of `[voice-cos-tool-expansion]` (2026-05-25). The `weather_now` voice tool already reads `settings?.location?.{lat,lon}` (forward-compatible, guarded) but no Settings UI or Zod slice ever sets it, so with no `lat`/`lon` args it always falls back to the default location. Add a `location` settings field (Settings UI + a Zod slice in `server/lib/validation.js`), then the existing tool path lights up. Small.- [ ] [mediacard-use-mediaimage-for-syncing-assets] **`MediaCard.jsx` grid thumbnails still use a raw `<img src={previewUrl}>`.** Same peer-sync placeholder/live-swap gap that `[peer-sync-medialightbox-use-mediaimage-for-syncing-assets]` fixed for the lightbox — `client/src/components/media/MediaCard.jsx` (~line 42) doesn't get the "Syncing" placeholder or the `peerSync:asset-arrived` atomic swap. Swap the raw `<img>` for `MediaImage`. Surfaced by that item's cross-check during the batch-clear (2026-05-25); was outside its stated scope.-- [ ] [chrome-canary-followups] **Hardening for the custom-Chrome-binary feature (xhigh code-review 2026-05-25).** **High-severity:** (a) On macOS headed mode (the default), `browser/server.js:208` uses `macAppBundle` only and silently ignores `chromePath` — a UI user who fills in `chromePath` for Canary/Chromium/Brave but leaves `macAppBundle` empty gets stock Chrome and the log misreports the binary; couple the two fields in the UI (or auto-derive `macAppBundle` from `chromePath` when the latter is inside a `.app`). (b) Neither `spawn(chromePath, …)` (line 216) nor `spawn('/usr/bin/open', …)` (line 208) has an `.on('error', …)` listener — a typo in `chromePath` emits 'error' with no listener → `uncaughtException` → portos-browser PM2 child crashes and restart-loops. (c) `scripts/setup-browser.js#applyCanaryToConfig` writes `chromePath` + `macAppBundle` but doesn't flip `headless: false`; combined with the seed default of `headless: true` (`data.reference/browser-config.json`), a fresh install accepting Canary runs Canary invisibly. (d) `browser/server.js#loadConfig` does bare `JSON.parse(raw)` with no try/catch — combined with setup-browser's non-atomic `writeFileSync` and the `cachedConfig` race, a partial-file write crashes the supervisor on next start (PM2 restart-loop forever). **Medium-severity:** (e) `setup-browser.js#loadConfig` silently catches all JSON parse errors and returns `{}`, then `applyCanaryToConfig` saves `{chromePath, macAppBundle}` only — wiping every other user-customized key. (f) Top-level `await runCanarySetup()` has no try/catch — any EACCES on data/browser-config.json aborts `npm run setup` / `update.sh` at what was previously a no-op step. (g) Idempotency guard only checks `chromePath`: users who decline get re-prompted on every update, and users who set only `macAppBundle` keep getting re-prompted. (h) `PORTOS_USE_CANARY` only matches literal `'0'`/`'false'` (opt-out) or `'1'`/`'true'` (opt-in) — `'no'`/`'off'`/`'yes'`/`'on'`/`'True'` fall through both branches. (i) `spawnSync(install.cmd, …, { stdio: 'inherit' })` for brew/winget can hang on a sudo password prompt under non-TTY + `PORTOS_USE_CANARY=1` (update.sh stalls). (j) `cachedConfig` in `browserService.js` is stale relative to setup-browser's direct write — GET /api/browser/config returns pre-update values until process restart. (k) `saveConfig` uses bare `writeFileSync` — switch to the canonical `atomicWrite` pattern (`server/lib/fileUtils.js`). **Low-severity:** (l) `spawnSync` failure-status check `result.status !== 0` treats `status: null` (spawn-failure / signal kill) identically to a non-zero exit and never logs `result.error` — masks ENOENT/EPERM/SIGKILL. (m) `optionalPath` Zod schema accepts any string up to 1024 chars; no `.app`/`.exe` sanity check — user pastes the bundle into `chromePath` → spawn() EISDIR. (n) `launchBrowser`'s reuse-existing-Chrome early-return (line 167) fires BEFORE `headlessMode = config.headless === true` (line 170), leaving the module-level default `false` after a PM2 restart that reuses Chrome — /health reports wrong mode (pre-existing, but in a function touched by this change). (o) `detectCanary` on macOS only checks `/Applications/...`; misses per-user `~/Applications/Google Chrome Canary.app` installs (corporate Macs, `HOMEBREW_CASK_OPTS=--appdir=$HOME/Applications`).+- [ ] [chrome-canary-followups] **Hardening for the custom-Chrome-binary feature (xhigh code-review 2026-05-25).** _DONE in the v2.10.0 release review: (b) both `spawn()` calls now have `.on('error', …)` listeners; (d) `browser/server.js#loadConfig` now try/catches the `JSON.parse`; (e) `setup-browser.js#loadConfig` now warns + returns `null` and `applyCanaryToConfig` skips the save when the existing config is unreadable; (f) top-level `runCanarySetup()` is now `.catch()`-wrapped. (c) is tracked separately in `[setup-browser-canary-headless]`. Remaining: (a), (g)–(o)._ **High-severity:** (a) On macOS headed mode (the default), `browser/server.js:208` uses `macAppBundle` only and silently ignores `chromePath` — a UI user who fills in `chromePath` for Canary/Chromium/Brave but leaves `macAppBundle` empty gets stock Chrome and the log misreports the binary; couple the two fields in the UI (or auto-derive `macAppBundle` from `chromePath` when the latter is inside a `.app`). (b) Neither `spawn(chromePath, …)` (line 216) nor `spawn('/usr/bin/open', …)` (line 208) has an `.on('error', …)` listener — a typo in `chromePath` emits 'error' with no listener → `uncaughtException` → portos-browser PM2 child crashes and restart-loops. (c) `scripts/setup-browser.js#applyCanaryToConfig` writes `chromePath` + `macAppBundle` but doesn't flip `headless: false`; combined with the seed default of `headless: true` (`data.reference/browser-config.json`), a fresh install accepting Canary runs Canary invisibly. (d) `browser/server.js#loadConfig` does bare `JSON.parse(raw)` with no try/catch — combined with setup-browser's non-atomic `writeFileSync` and the `cachedConfig` race, a partial-file write crashes the supervisor on next start (PM2 restart-loop forever). **Medium-severity:** (e) `setup-browser.js#loadConfig` silently catches all JSON parse errors and returns `{}`, then `applyCanaryToConfig` saves `{chromePath, macAppBundle}` only — wiping every other user-customized key. (f) Top-level `await runCanarySetup()` has no try/catch — any EACCES on data/browser-config.json aborts `npm run setup` / `update.sh` at what was previously a no-op step. (g) Idempotency guard only checks `chromePath`: users who decline get re-prompted on every update, and users who set only `macAppBundle` keep getting re-prompted. (h) `PORTOS_USE_CANARY` only matches literal `'0'`/`'false'` (opt-out) or `'1'`/`'true'` (opt-in) — `'no'`/`'off'`/`'yes'`/`'on'`/`'True'` fall through both branches. (i) `spawnSync(install.cmd, …, { stdio: 'inherit' })` for brew/winget can hang on a sudo password prompt under non-TTY + `PORTOS_USE_CANARY=1` (update.sh stalls). (j) `cachedConfig` in `browserService.js` is stale relative to setup-browser's direct write — GET /api/browser/config returns pre-update values until process restart. (k) `saveConfig` uses bare `writeFileSync` — switch to the canonical `atomicWrite` pattern (`server/lib/fileUtils.js`). **Low-severity:** (l) `spawnSync` failure-status check `result.status !== 0` treats `status: null` (spawn-failure / signal kill) identically to a non-zero exit and never logs `result.error` — masks ENOENT/EPERM/SIGKILL. (m) `optionalPath` Zod schema accepts any string up to 1024 chars; no `.app`/`.exe` sanity check — user pastes the bundle into `chromePath` → spawn() EISDIR. (n) `launchBrowser`'s reuse-existing-Chrome early-return (line 167) fires BEFORE `headlessMode = config.headless === true` (line 170), leaving the module-level default `false` after a PM2 restart that reuses Chrome — /health reports wrong mode (pre-existing, but in a function touched by this change). (o) `detectCanary` on macOS only checks `/Applications/...`; misses per-user `~/Applications/Google Chrome Canary.app` installs (corporate Macs, `HOMEBREW_CASK_OPTS=--appdir=$HOME/Applications`).- [ ] [voice-tool-edge-hardening] **Edge-case hardening for the new voice tools (all low-severity, from the xhigh code-review 2026-05-25).** (c) `timer_set` is a bare in-memory `setTimeout` with no persistence (lost silently on restart) and no dedup across tool-loop iterations (LLM re-issue → double notification). Also minor: `dataSync.js` per-`(category,forPeerId)` `checksumCache` keys are never evicted (unbounded for cycling peer ids; negligible for a home federation). _(Fixed in the v2.9.0 release review: (a) the `calendar_today` DST-offset bug — `anchorLocalMidnightUtc` now samples the offset at the target midnight; (b) `calendar_next` now matches calendarSync's `endTime >= now` range so in-progress and all-day-today events surface; and `resolveExcludeSet` is now deferred to the `getChecksum` cache-miss path.)_- [ ] [shared-pill-chip-component] **Extract a shared `<Pill>` (or `<Chip>`) component for inline label badges.** The pattern `<span className="text-xs … rounded px-2 py-0.5">{label}</span>` is hand-rolled across the client: `client/src/pages/WritersRoomGuide.jsx` (multiple call sites — the local `Pill` helper added 2026-05-25 for length-target cards is a candidate seed), `client/src/pages/Instances.jsx:695,874`, and `client/src/components/goals/GoalDetailPanel.jsx:857,868`. Promote to `client/src/components/ui/Pill.jsx` with `tone="accent|muted|note|context"` variants and migrate the call sites. Surfaced by the simplify-agent reuse review during the Writers Room Guide length-targets change. Skip until another touch into one of those files justifies the sweep.@@ -135,11 +135,8 @@ Surfaced while building the sync-hygiene feature (duplicate detection/merge, nonSurfaced by a gemini review during PR #489 (sync-hygiene) that scoped beyond that PR's diff — these are in the already-merged Chrome-variant browser feature + the commands service, NOT in #489. Verified against the actual code where noted; out of scope for #489, land them in a separate hardening PR.-- [ ] [browser-spawn-error-handler] **Chrome `spawn()` calls have no `'error'` listener → crash the browser supervisor.** `browser/server.js` lines ~208 (`spawn('/usr/bin/open', …)`) and ~216 (`spawn(chromePath, …)`) attach no `.on('error', …)`, so a missing/non-executable Chrome binary raises `uncaughtException` and takes the process down. Add `.on('error', (err) => { console.error('❌ Failed to spawn Chrome:', err.message); chromeProcess = null; })` to both. Verified (gemini CRITICAL).-- [ ] [browser-loadconfig-json-guard] **`loadConfig` bare `JSON.parse` crashes on a corrupt config.** `browser/server.js:54` does `raw ? JSON.parse(raw) : {}` with no try/catch — a partially-written/corrupt `data/browser-config.json` throws and crashes boot. Wrap in try/catch returning `{}` with an emoji-prefixed warning. Verified (gemini CRITICAL).- [ ] [commands-centralized-parser] **`commands.js` re-implements command parsing with a naive `split(/\s+/)` instead of the centralized quote-aware parser.** `server/services/commands.js:28` splits on whitespace (breaks quoted args) and only imports `ALLOWED_COMMANDS`/`DANGEROUS_SHELL_CHARS` from `commandSecurity.js` — not its `parseCommandArgs`/`validateCommand`. Route through `validateCommand` so allow-listing, dangerous-char checks, and quote-aware arg parsing are one verified step. Verified (gemini IMPROVEMENT).-- [ ] [setup-browser-config-loss] **`scripts/setup-browser.js` `loadConfig` swallows JSON parse errors silently, then `applyCanaryToConfig` → `saveConfig` can overwrite a corrupt config with a near-empty one (key loss).** Add an emoji-prefixed warning on parse failure and avoid calling `saveConfig` when the existing file was unreadable. Verified (gemini IMPROVEMENT).-- [ ] [setup-browser-canary-headless] **Fresh Canary opt-in may run headless-invisible — verify intent.** gemini flagged that `applyCanaryToConfig` (`scripts/setup-browser.js:81`) sets `chromePath`/`macAppBundle` but not `headless: false`, so a fresh install that opts into Canary could run it invisibly. UNVERIFIED — confirm whether `false` is already the effective default before changing. (gemini IMPROVEMENT.)+- [ ] [setup-browser-canary-headless] **Decide the intended headed/headless default for the managed browser — seed says `true`, code comment says headed.** VERIFIED during the v2.10.0 release review: `data.reference/browser-config.json` ships `"headless": true`, but `browser/server.js`'s header comment says "Default headed" and `headlessMode = config.headless === true`. So a fresh install runs headless, which contradicts the comment AND means opting into Canary at setup runs it invisibly (defeating the "visible differentiated browser" purpose). This is a behavioral decision (intent-ambiguous), so it was deliberately NOT changed in the release: either flip the seed to `"headless": false` AND set `config.headless = false` in `scripts/setup-browser.js#applyCanaryToConfig`, or fix the code comment to say headless-by-default. (gemini IMPROVEMENT; release-review confirmed the seed value.)### Worktree cleanup — deferred follow-ups (2026-05-25)@@ -148,6 +145,18 @@ Surfaced while adding merge-verified worktree reaping (`isBranchMergedInto` + `r- [ ] [worktree-remove-helper] **Extract the repeated "worktree remove --force → on-fail rm + prune" dance into one helper.** The pattern (`git worktree remove <path> --force`, catch → `rm -rf` + `git worktree prune`) is now inlined in 4 spots in `server/services/worktreeManager.js`: `removeWorktree`, `reapMergedWorktrees`, `cleanupExternalRepoWorktrees`, and `removePersistentWorktree`. Extract `forceRemoveWorktreeDir(repo, worktreePath, label)` and route all four through it. Deferred from the `/simplify` pass on the reaper change because two of the four call sites are outside that feature's diff and the logging context differs slightly per site.- [ ] [plan-task-prefer-merge] **Switch the `/claim` (`plan-task`) Phase-6 merge order to prefer `--merge` over `--squash`.** The live `plan-task` prompt in `server/services/taskSchedule.js` (~line 562) still tries `gh pr merge --auto || --squash || --merge || --rebase`, so `/claim` squash-merges by default — inconsistent with the new `--merge`-first default now used by the review-loop / `/do:pr` agent prompts (`agentPromptBuilder.js`) and the `pr-reviewer-review` stage prompt. Deferred because: (a) `plan-task` is a **version-migrated** prompt, so the change needs a `PROMPT_VERSIONS['plan-task']` bump (7→8) **and** the v7 default preserved in `PREVIOUS_DEFAULT_PROMPTS['plan-task']` (~190-line byte-exact copy — error-prone); (b) `/claim` self-cleans its worktree/branch in Phase 7 regardless of merge method, so it doesn't contribute to worktree accumulation; and (c) `reapMergedWorktrees` detects squash merges anyway, so cleanup is already correct. Low benefit, non-trivial migration cost — do it as a focused follow-up when touching `plan-task` prompt versioning next.+### v2.10.0 release-review follow-ups (2026-05-25)++Surfaced by the multi-reviewer release gate for v2.10.0. The CRITICAL/correctness findings were fixed in-release (paused-agent cleanup protection, browser spawn/loadConfig guards, CLI pause-ordering double-finalize, runner immediate-fallback exit-0 race, conflict-journal `ERR_TARGET_GONE`→409, pause-route Zod). The items below were deferred as test-coverage gaps or non-blocking improvements.++- [ ] [test-paused-agent-cleanup-protection] **Add a test that `agentDataCleanup` excludes paused agents from worktree/data reaping.** The fix (`server/services/autonomousJobs.js` reads `data/cos/state.json` and unions `status === 'paused'` ids into the protect set) is currently unverified by tests — `agentDataCleanup` is a private (non-exported) handler and has no test today. Export it (or the `SCRIPT_HANDLERS` map), build fs (`readdir`/`stat`/`rm`) + `reapMergedWorktrees`/`cleanupOrphanedWorktrees` mocks, seed a state.json with a paused agent, and assert its worktree + data dir are NOT reaped. (Batch-1 CRITICAL review follow-up.)+- [ ] [test-pause-agent-branches] **Cover the non-happy-path `pauseAgent` branches.** `agentManagement.test.js` only tests the direct-mode happy path. Add: runner-branch success + `pauseAgentViaRunner` failure → `pausedAgents` rolled back and agent stays in `runnerAgents`; TUI branch (ESC + delayed `killSession`); and the close-handler skip-finalization contract (a `pausedAgents`-flagged agent hitting the CLI/TUI/runner close handler does NOT finalize the task / clean the worktree). (Batch-1 IMPROVEMENT.)+- [ ] [cosrunner-orphan-paused-emit] **`cos-runner/index.js` emits `agent:paused` but nothing listens.** `cosRunnerClient.js` never subscribes to `agent:paused` (pause state is applied synchronously via the HTTP `/pause` path), so the emit is dead code implying a server listener that doesn't exist. Either drop the emit or wire `socket.on('agent:paused', …)` and handle it idempotently. (Batch-1 NIT.)+- [ ] [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-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- **Identity Context Injection** — per-task-type digital twin preamble toggle.diff --git a/browser/server.js b/browser/server.jsindex c727990ae2..f5ec0f9650 100644--- a/browser/server.js+++ b/browser/server.js@@ -51,7 +51,17 @@ function getMacAppBundle(config) {async function loadConfig() {const raw = await readFile(CONFIG_FILE, 'utf-8').catch(() => null);- return raw ? JSON.parse(raw) : {};+ if (!raw) return {};+ // Guard against a partially-written / corrupt config (now user-editable via+ // the Browser settings UI). An unguarded JSON.parse here throws on boot —+ // loadConfig is awaited from launchBrowser()→main() with no catch, so a bad+ // file would crash the PM2 child into a restart-loop. Fall back to defaults.+ try {+ return JSON.parse(raw);+ } catch (err) {+ console.error(`⚠️ Corrupt browser-config.json, using defaults: ${err.message}`);+ return {};+ }}async function checkCdp() {@@ -212,6 +222,13 @@ async function launchBrowser() {// download keep-alive WS close event + reconnect loop instead.chromeProcess = null;});+ // A bad macAppBundle (user-editable via the Browser settings UI) emits+ // 'error'; with no listener that becomes an uncaughtException → PM2+ // restart-loop. Log and null out so the CDP-wait loop reports unreachable.+ chromeProcess.on('error', (err) => {+ console.error(`❌ Failed to spawn Chrome via open: ${err.message}`);+ chromeProcess = null;+ });} else {chromeProcess = spawn(chromePath, args, { stdio: 'ignore', windowsHide: true });chromeProcess.on('exit', (code) => {@@ -222,6 +239,17 @@ async function launchBrowser() {downloadWs = null;}});+ // A bad chromePath (user-editable via the Browser settings UI) emits+ // 'error'; with no listener that becomes an uncaughtException → PM2+ // restart-loop. Log and null out so the CDP-wait loop reports unreachable.+ chromeProcess.on('error', (err) => {+ console.error(`❌ Failed to spawn Chrome (${chromePath}): ${err.message}`);+ chromeProcess = null;+ if (downloadWs) {+ try { downloadWs.close(); } catch {}+ downloadWs = null;+ }+ });}// Wait for CDP to become availablediff --git a/scripts/setup-browser.js b/scripts/setup-browser.jsindex 496c250939..17112f01bc 100644--- a/scripts/setup-browser.js+++ b/scripts/setup-browser.js@@ -36,9 +36,17 @@ if (!existsSync(profileDir)) {console.log('📁 Created browser profile directory');}+// Returns {} when the file is absent, the parsed object when readable, or null+// when it exists but is corrupt — so callers can avoid overwriting (and wiping+// the user's other keys: cdpPort, userDataDir, etc.) on a transient corruption.function loadConfig() {if (!existsSync(configFile)) return {};- try { return JSON.parse(readFileSync(configFile, 'utf-8')); } catch { return {}; }+ try {+ return JSON.parse(readFileSync(configFile, 'utf-8'));+ } catch (err) {+ console.warn(`⚠️ browser-config.json is unreadable (${err.message}); leaving it untouched.`);+ return null;+ }}function saveConfig(config) {@@ -80,6 +88,10 @@ function canaryInstallCommand() {function applyCanaryToConfig(found) {const config = loadConfig();+ if (config === null) {+ console.warn(' Skipping Canary config write — fix the corrupt browser-config.json first.');+ return;+ }config.chromePath = found.bin;if (found.app) config.macAppBundle = found.app;saveConfig(config);@@ -108,7 +120,7 @@ async function runCanarySetup() {}const config = loadConfig();- if (typeof config.chromePath === 'string' && config.chromePath.trim()) {+ if (typeof config?.chromePath === 'string' && config.chromePath.trim()) {// Already configured — don't re-prompt on subsequent setup/update runs.return;}@@ -160,6 +172,8 @@ async function runCanarySetup() {else console.log('⚠️ Canary installed but the binary was not found at the expected path. You can set chromePath manually in Settings → Browser.');}-await runCanarySetup();+// A throw here (EACCES writing the config, install subprocess failure, etc.)+// must not abort the larger `npm run setup` / update.sh step it's chained into.+await runCanarySetup().catch((err) => console.warn(`⚠️ Browser Canary setup skipped: ${err.message}`));console.log('✅ Browser setup complete');diff --git a/server/routes/conflictJournal.js b/server/routes/conflictJournal.jsindex c06f81e80a..34668b8798 100644--- a/server/routes/conflictJournal.js+++ b/server/routes/conflictJournal.js@@ -14,6 +14,9 @@ const router = Router();const SERVICE_ERROR_STATUS = {[resolver.ERR_NOT_FOUND]: 404,[resolver.ERR_VALIDATION]: 400,+ // Target record was deleted since the conflict was archived — the entry is+ // still actionable via discard, so surface 409 rather than a generic 500.+ [resolver.ERR_TARGET_GONE]: 409,};const mapServiceError = (err) => {const status = SERVICE_ERROR_STATUS[err?.code];diff --git a/server/routes/conflictJournal.test.js b/server/routes/conflictJournal.test.jsindex 606e900761..526d1d8da5 100644--- a/server/routes/conflictJournal.test.js+++ b/server/routes/conflictJournal.test.js@@ -6,6 +6,7 @@ import { errorMiddleware } from '../lib/errorHandler.js';const resolverMock = {ERR_NOT_FOUND: 'CONFLICT_JOURNAL_NOT_FOUND',ERR_VALIDATION: 'CONFLICT_JOURNAL_VALIDATION',+ ERR_TARGET_GONE: 'CONFLICT_TARGET_GONE',listConflicts: vi.fn(),getConflict: vi.fn(),resolveConflict: vi.fn(),@@ -55,6 +56,15 @@ describe('conflict-journal routes', () => {expect(res.status).toBe(404);});+ it('maps ERR_TARGET_GONE to 409 (record deleted since the conflict was archived)', async () => {+ resolverMock.resolveConflict.mockRejectedValue(+ Object.assign(new Error('The universe this conflict targets no longer exists — discard the entry.'), { code: resolverMock.ERR_TARGET_GONE }),+ );+ const res = await request(makeApp()).post('/api/conflict-journal/e1/resolve').send({ action: 'restore-all' });+ expect(res.status).toBe(409);+ expect(res.body.code).toBe('CONFLICT_TARGET_GONE');+ });+it('DELETE /:id removes an entry', async () => {resolverMock.deleteConflict.mockResolvedValue({ id: 'e1', deleted: true });const res = await request(makeApp()).delete('/api/conflict-journal/e1');diff --git a/server/routes/cosAgentRoutes.js b/server/routes/cosAgentRoutes.jsindex e1c26da738..59758cba43 100644--- a/server/routes/cosAgentRoutes.js+++ b/server/routes/cosAgentRoutes.js@@ -3,11 +3,17 @@*/import { Router } from 'express';+import { z } from 'zod';import * as cos from '../services/cos.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { validateRequest } from '../lib/validation.js';const router = Router();+// `reason` is persisted into task metadata + interpolated into logs; guard the+// shape so a non-string body can't store `[object Object]`.+const pauseBodySchema = z.object({ reason: z.string().max(500).optional() });+// GET /api/cos/health - Get health statusrouter.get('/health', asyncHandler(async (req, res) => {const health = await cos.getHealthStatus();@@ -70,7 +76,8 @@ router.post('/agents/:id/terminate', asyncHandler(async (req, res) => {// POST /api/cos/agents/:id/pause - Stop process, preserve task/worktree for later resumerouter.post('/agents/:id/pause', asyncHandler(async (req, res) => {- const result = await cos.pauseAgent(req.params.id, req.body?.reason || null);+ const { reason } = validateRequest(pauseBodySchema, req.body ?? {});+ const result = await cos.pauseAgent(req.params.id, reason || null);if (result?.error) {throw new ServerError(result.error, { status: 404, code: 'NOT_FOUND' });}diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex 7cde7b5e64..86393ba58f 100644--- a/server/services/agentCliSpawning.js+++ b/server/services/agentCliSpawning.js@@ -542,21 +542,9 @@ export async function spawnDirectly({const finalSuccess = terminatedByUser ? false : success;const finalError = terminatedByUser ? 'Agent terminated by user' : null;- // Release lane + complete execution tracking BEFORE the writeFile +- // error-analysis + state-write chain — neither call blocks on I/O, but- // lanes serialize related work. Fall back to outer scope when- // activeAgents was cleared by killAgent before close fired.- releaseAgentLane({- agentId,- success: finalSuccess,- duration,- exitCode: code,- executionId: agentData?.executionId || executionId,- laneName: agentData?.laneName || laneName,- errorExecutionMessage: finalError || undefined,- });-- // Flush remaining stream parser data+ // Flush remaining stream parser data (persists the tail of the transcript+ // before any early-return, so a paused agent's output.txt is complete for+ // the resume modal).if (streamParser) {const remaining = streamParser.flush();for (const line of remaining) {@@ -578,6 +566,10 @@ export async function spawnDirectly({await writeFile(outputFile, outputBuffer).catch(() => {});+ // Paused agents are finalized in `markAgentPaused` (which already released+ // the lane + execution). Return BEFORE `releaseAgentLane` below — re-running+ // it on the same executionId logs a spurious "Invalid state transition".+ // Mirrors the TUI path's pause-check-before-releaseAgentLane ordering.if (pausedAgents.has(agentId)) {pausedAgents.delete(agentId);if (agentData?.pid) unregisterSpawnedAgent(agentData.pid);@@ -585,6 +577,20 @@ export async function spawnDirectly({return;}+ // Release lane + complete execution tracking BEFORE the error-analysis ++ // state-write chain — neither call blocks on I/O, but lanes serialize+ // related work. Fall back to outer scope when activeAgents was cleared by+ // killAgent before close fired.+ releaseAgentLane({+ agentId,+ success: finalSuccess,+ duration,+ exitCode: code,+ executionId: agentData?.executionId || executionId,+ laneName: agentData?.laneName || laneName,+ errorExecutionMessage: finalError || undefined,+ });+// Use raw stream buffer for error analysis (contains full JSON with error details)const analysisBuffer = rawStreamBuffer || outputBuffer;const errorAnalysis = finalSuccess ? null : (immediateFallbackAnalysis || analyzeAgentFailure(analysisBuffer, task, model));diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex 398b3bfe62..e21a7aad10 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -34,7 +34,7 @@ import { extractCodexAssistantTail } from '../lib/codexAssistantExtract.js';import { buildTuiSpawnConfig, spawnTuiAgent } from './agentTuiSpawning.js';import { selectModelForTask } from './agentModelSelection.js';import { processAgentCompletion } from './agentCompletion.js';-import { activeAgents, runnerAgents, spawningTasks, useRunner, isTruthyMeta, isFalsyMeta } from './agentState.js';+import { activeAgents, runnerAgents, pausedAgents, spawningTasks, useRunner, isTruthyMeta, isFalsyMeta } from './agentState.js';import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, normalizeReviewers } from '../lib/validation.js';import { resolveReviewLoopOptions } from './codeReview.js';import { v4 as uuidv4 } from '../lib/uuid.js';@@ -1043,6 +1043,14 @@ export async function handlePipelineProgression(task, agentId, success) {* Handle agent completion (from runner events).*/export async function handleAgentCompletion(agentId, exitCode, success, duration) {+ // Paused agents are finalized by markAgentPaused, not here — skip so a stray+ // completion event can't clean the worktree / complete the task out from+ // under a later resume. Mirrors the CLI/TUI close-handler pause guards.+ if (pausedAgents.has(agentId)) {+ pausedAgents.delete(agentId);+ runnerAgents.delete(agentId);+ return;+ }const agent = runnerAgents.get(agentId);if (!agent) {// Agent not in memory map (server restarted). Check cos state for context.@@ -1056,6 +1064,12 @@ export async function handleAgentCompletion(agentId, exitCode, success, durationconsole.log(`✅ Agent ${agentId} already completed (handled by orphan cleanup)`);return;}+ // Post-restart the in-memory pausedAgents map is empty, but the persisted+ // status still says paused — don't finalize a paused agent on a stray event.+ if (cosAgent.status === 'paused') {+ console.log(`⏸️ Ignoring completion for paused agent ${agentId} (awaiting resume)`);+ return;+ }console.log(`🔄 Completing untracked agent ${agentId} from cos state (post-restart)`);await completeAgent(agentId, {success,diff --git a/server/services/autonomousJobs.js b/server/services/autonomousJobs.jsindex 3b73050e93..a6f7925ca5 100644--- a/server/services/autonomousJobs.js+++ b/server/services/autonomousJobs.js@@ -91,6 +91,20 @@ async function agentDataCleanup() {// `initSpawner()` + scheduled orphan cleanup) just to read the maps.const activeIds = new Set(getActiveAgentIds())+ // Also protect PAUSED agents. Pausing intentionally preserves the agent's+ // worktree + data dir as resume context, but a paused agent is removed from+ // the in-memory active/runner maps (so `getActiveAgentIds()` omits it) and —+ // critically — those maps are empty after a server restart while the agent's+ // `status: 'paused'` survives in state.json. Read the persisted status so a+ // paused agent's worktree/transcript is never reaped or rm'd out from under a+ // later resume. (readJSONFile keeps this off the subAgentSpawner import path.)+ const cosState = await readJSONFile(join(PATHS.cos, 'state.json'), null)+ if (cosState?.agents && typeof cosState.agents === 'object') {+ for (const [id, agent] of Object.entries(cosState.agents)) {+ if (agent?.status === 'paused') activeIds.add(id)+ }+ }+const agentsDir = join(PATHS.cos, 'agents')let cleaned = 0if (existsSync(agentsDir)) {diff --git a/server/services/conflictJournalResolver.js b/server/services/conflictJournalResolver.jsindex 8350525f78..0511ed53f7 100644--- a/server/services/conflictJournalResolver.js+++ b/server/services/conflictJournalResolver.js@@ -25,11 +25,14 @@*/import { conflictJournalStore, RESTORABLE_FIELDS } from '../lib/conflictJournal.js';-import { updateUniverse } from './universeBuilder.js';-import { updateSeries } from './pipeline/series.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';export const ERR_NOT_FOUND = 'CONFLICT_JOURNAL_NOT_FOUND';export const ERR_VALIDATION = 'CONFLICT_JOURNAL_VALIDATION';+// The conflict entry exists but the record it targets was tombstoned between+// archive time and resolution — distinct from ERR_NOT_FOUND (the entry itself).+export const ERR_TARGET_GONE = 'CONFLICT_TARGET_GONE';const makeErr = (message, code) => Object.assign(new Error(message), { code });// RESTORABLE_FIELDS (the user-authored content fields a restore/merge may write@@ -58,12 +61,21 @@ export async function getConflict(id) {// Apply a content patch through the right service's normal update path.async function applyToRecord(kind, recordId, patch) {+ // The target record may have been tombstoned between conflict-archive time and+ // resolution. Translate the services' not-found codes into ERR_TARGET_GONE so+ // the route maps it to a clean 409 ("discard the entry") instead of a 500.+ const translateGone = (err) => {+ if (err?.code === UNIVERSE_NOT_FOUND || err?.code === SERIES_NOT_FOUND) {+ throw makeErr(`The ${kind} this conflict targets no longer exists — discard the entry.`, ERR_TARGET_GONE);+ }+ throw err;+ };if (kind === 'universe') {// Mutator form bypasses the literal-patch reference-sheet preservation// guard — the restored snapshot is the trusted writer here.- await updateUniverse(recordId, () => patch);+ await updateUniverse(recordId, () => patch).catch(translateGone);} else if (kind === 'series') {- await updateSeries(recordId, patch);+ await updateSeries(recordId, patch).catch(translateGone);} else {throw makeErr(`Unsupported conflict kind: ${kind}`, ERR_VALIDATION);}diff --git a/server/services/conflictJournalResolver.test.js b/server/services/conflictJournalResolver.test.jsindex 3dc30a435e..5b3b799c74 100644--- a/server/services/conflictJournalResolver.test.js+++ b/server/services/conflictJournalResolver.test.js@@ -89,6 +89,15 @@ describe('conflictJournalResolver', () => {.rejects.toMatchObject({ code: resolver.ERR_VALIDATION });});+ it('translates a deleted target record into ERR_TARGET_GONE (not the raw NOT_FOUND)', async () => {+ // Entry points at a universe id that no longer exists (tombstoned between+ // archive and resolution). updateUniverse throws NOT_FOUND; the resolver+ // must surface ERR_TARGET_GONE so the route maps it to 409, not 500.+ const entryId = await seedEntry('does-not-exist', { id: 'does-not-exist', name: 'Ghost', starterPrompt: 'local' });+ await expect(resolver.resolveConflict(entryId, { action: 'restore-all' }))+ .rejects.toMatchObject({ code: resolver.ERR_TARGET_GONE });+ });+it('listConflicts filters by status; deleteConflict removes the entry', async () => {const u = await universeSvc.createUniverse({ name: 'X' });const e1 = await seedEntry(u.id, { id: u.id, name: 'X' });diff --git a/server/services/runner.js b/server/services/runner.jsindex 7de64644d7..24ad194d75 100644--- a/server/services/runner.js+++ b/server/services/runner.js@@ -246,7 +246,11 @@ export async function executeCliRun(runId, provider, prompt, workspacePath, onDametadata.endTime = new Date().toISOString();metadata.duration = Date.now() - startTime;metadata.exitCode = code;- metadata.success = code === 0;+ // A mid-stream fallback signal (e.g. usage-limit hit) SIGTERM-kills the+ // child; if it happens to exit 0 in that race, don't record the run as+ // successful — the fallback path (onRunFailed) must fire. Mirrors the TUI+ // finish({ success: false }) handling of the same signal.+ metadata.success = code === 0 && !immediateFallbackAnalysis;metadata.outputSize = Buffer.byteLength(output);// Analyze errors if the run failed (delegate to toolkit's error detection)diff --git a/server/services/runner.test.js b/server/services/runner.test.jsindex 49d57d4612..60b97d953b 100644--- a/server/services/runner.test.js+++ b/server/services/runner.test.js@@ -134,6 +134,32 @@ describe('executeCliRun — Codex sentinel suppression', () => {}),});});++ it('records failure (not success) when the fallback-killed child exits 0 in the race', async () => {+ const child = makeChild();+ spawn.mockReturnValue(child);+ setAIToolkit(fakeToolkit({ analyzeError }), { dataDir: '/tmp/test-runner' });++ const provider = {+ id: 'claude-code', name: 'Claude Code', command: 'claude', args: [],+ defaultModel: 'claude-opus-4-7', timeout: 60000,+ };++ const completed = new Promise((resolve) => {+ executeCliRun('run-fallback-exit0', provider, 'test prompt', '/workspace', undefined, resolve, 60000);+ });++ await Promise.resolve();+ child.stderr.emit('data', Buffer.from('Now using extra usage\n'));+ expect(child.kill).toHaveBeenCalledWith('SIGTERM');++ // SIGTERM races and the child happens to exit 0 — must NOT be recorded as+ // success, or the usage-limit fallback (onRunFailed) silently never fires.+ child.emit('close', 0);+ const metadata = await completed;+ expect(metadata.success).toBe(false);+ expect(metadata.errorAnalysis).toMatchObject({ requiresFallback: true });+ });});describe('buildCliArgs — claude-code defaultModel honoring', () => {